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>package kim.guler.berkin.simpledownload
import android.os.Handler
import android.os.Looper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.isActive
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import okio.buffer
import okio.sink
import java.io.File
/**
* Created by <NAME> on 11.01.2020.
*/
object SimpleDownloader {
private const val BUFFER_SIZE = 8 * 1024L
private val mainHandler by lazy { Handler(Looper.getMainLooper()) }
suspend fun String.download(
targetFilePath: String,
completionListener: (success: Boolean, exception: Exception?) -> Unit,
progressCallback: ((progress: Int) -> Unit)? = null
) {
downloadURL(this, targetFilePath, completionListener, progressCallback)
}
suspend fun downloadURL(
url: String,
targetFilePath: String,
completionListener: (success: Boolean, exception: Exception?) -> Unit,
progressCallback: ((progress: Int) -> Unit)? = null
) {
val request = Request.Builder().url(url).build()
val client = with(OkHttpClient.Builder()) {
addNetworkInterceptor { chain ->
val originalResponse = chain.proceed(chain.request())
val responseBody = originalResponse.body
originalResponse.newBuilder().body(
ProgressResponseBody(
responseBody!!,
progressCallback,
completionListener
)
).build()
}
}.build()
withContext(Dispatchers.IO) {
try {
val execute = client.newCall(request).execute()
if (!isActive) {
return@withContext
}
File(targetFilePath).parentFile?.mkdirs()
val body = execute.body ?: return@withContext
val bufferedSource = body.source()
val bufferedSink = File(targetFilePath).sink().buffer()
useResources(bufferedSource, bufferedSink) {
var read: Long
do {
read = bufferedSource.read(bufferedSink.buffer, BUFFER_SIZE)
bufferedSink.emit()
} while (read > 0 && isActive)
}
} catch (ex: Exception) {
mainHandler.post {
completionListener.invoke(false, ex)
}
}
}
}
}<file_sep>package kim.guler.berkin.simpledownload
import kotlin.Exception
/**
* Created by <NAME> on 11.01.2020.
*/
inline fun useResources(vararg resources: AutoCloseable, block: () -> Unit) {
try {
block.invoke()
} catch (ex: Exception) {
resources.forEach { it.close() }
throw ex
}
resources.forEach { it.close() }
}<file_sep>package kim.guler.berkin.simpledownload
import android.os.Handler
import android.os.Looper
import okhttp3.ResponseBody
import okio.Buffer
import okio.ForwardingSource
import okio.Source
import okio.buffer
/**
* Created by <NAME> on 11.01.2020.
*/
class ProgressResponseBody(
private val responseBody: ResponseBody,
private val progressCallback: ((progress: Int) -> Unit)?,
private val completionListener: (success: Boolean, exception: Exception?) -> Unit
) : ResponseBody() {
private val mainHandler by lazy { Handler(Looper.getMainLooper()) }
private val bufferedSource by lazy {
source(responseBody.source()).buffer()
}
override fun contentLength() = responseBody.contentLength()
override fun contentType() = responseBody.contentType()
override fun source() = bufferedSource
private fun source(source: Source): Source {
return object : ForwardingSource(source) {
var totalBytesRead = 0L
override fun read(sink: Buffer, byteCount: Long): Long {
val read = super.read(sink, byteCount)
if (read == -1L) {
mainHandler.post {
completionListener.invoke(true, null)
}
} else {
totalBytesRead += read
mainHandler.post {
progressCallback?.invoke((totalBytesRead.toFloat() / contentLength().toFloat() * 100f).toInt())
}
}
return read
}
}
}
}<file_sep>rootProject.name='Simple Download'
include ':library'
|
848e30e8b7657195d4e46c9c670c136b37d26678
|
[
"Kotlin",
"Gradle"
] | 4
|
Kotlin
|
bigahega/simpledownloader
|
855eb37e8d164bd30b79738e78c4d5ce6847c9a3
|
21b91a9020a24b7e9d9dcffea8e9eeddeff5dcd6
|
refs/heads/master
|
<file_sep>var express = require("express")
var router = express.Router();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '<PASSWORD>!',
database : 't411db'
});
var torrent_model = {
"id": 0,
"name": null,
"category": null,
"rewritename": null,
"seeders": null,
"leechers": null,
"comments": null,
"added": null,
"size": null,
"times_completed": null,
"owner": null,
"categoryname": null,
"username": null
}
var findAllTorrents = function(options, callback){
/* options = {
query : "string",
cid : number | [number],
limit : number, (default : 50)
offset : number, (default : 0)
sort : "string", (default : id)
order : "asc" | "desc" (default : desc)
}
*/
var cols_ordered = ["id","rewritename","seeders","leechers","added","size","times_completed"]
if(options.cid){
if(typeof options.cid=="string"){
if(options.cid.match(/\[(\s*\d*\s*)(,\s*\d*\s*)*\]/)){
options.cid = JSON.parse(options.cid)
}
}
else if(typeof options.cid=="number"){
options.cid = [options.cid]
}
else{
options.cid = undefined
}
}
if(options.query && options.query.length>2){
var tmpStr = options.query.toLowerCase()
options.query = tmpStr.replace(" ","-")
}
var col_ordered = "id"
if(options.sort){
cols_ordered.forEach(function(elt){
if(options.sort.match(elt)){
col_ordered = elt
}
})
}
var direction = "DESC"
if(options.order){
if(options.order.toLowerCase().match("asc")){
direction = "ASC"
}
}
var query = 'SELECT * FROM Torrents'+
(options.query?" WHERE rewritename LIKE "+connection.escape('%'+options.query+'%'):"")+
(options.cid?((options.query?" AND":" WHERE")+" category IN ("+connection.escape(options.cid)+")"):"")+
' ORDER BY '+col_ordered+' '+direction+' LIMIT '+connection.escape(options.limit?parseInt(options.limit) : 50)+' OFFSET '+connection.escape(options.offset|| 0)
connection.query(query, function(err, rows, fields) {
if (err) throw err;
!!callback && callback(rows)
});
}
var findTorrentById = function(id, callback){
var query = 'SELECT * FROM Torrents WHERE id=?'
var num_id = parseInt(id)
if(id!=NaN){
connection.query(query, [num_id], function(err, rows, fields){
if(err) throw err;
!!callback && callback(rows)
})
}
else{
!!callback && callback(null)
}
}
var createTorrent = function(torrent){
var repTorrent = {}
for(var key in torrent_model){
repTorrent[key] = torrent[key]? torrent[key] : null
}
return repTorrent
}
var insertTorrent = function(torrent, callback){
var query = 'INSERT INTO Torrents SET ?'
connection.query(query, createTorrent(torrent), function(err, rows, fields) {
if (err){
throw err;
!!callback && callback(false)
}
else{
!!callback && callback(true)
}
});
}
exports.insertTorrent = insertTorrent
var updateTorrent = function(torrent, callback){
}
var deleteTorrent = function(id){
}
var deleteCategory = function(CID, callback){
if(CID){
var query = 'DELETE FROM Torrents WHERE category=?'
connection.query(query, [CID], function(err, rows, fields) {
if (err){
throw err;
!!callback && callback(false)
}
else{
!!callback && callback(true)
}
});
}
else{
!!callback && callback(false)
}
}
exports.deleteCategory = deleteCategory
var deleteAllTorrents = function(callback){
var query = 'TRUNCATE TABLE Torrents'
connection.query(query, function(err, rows, fields) {
if (err){
throw err;
!!callback && callback(false)
}
else{
!!callback && callback(true)
}
});
}
exports.deleteAllTorrents = deleteAllTorrents
var getLastInsertedId = function(callback){
var query = 'SELECT MAX(id) FROM Torrents'
connection.query(query, function(err, rows, fields){
if (err){
throw err;
!!callback && callback(-1)
}
else{
!!callback && callback(rows[0]["MAX(id)"])
}
})
}
exports.getLastInsertedId = getLastInsertedId
var getNbTorrents = function(callback){
var query = 'SELECT COUNT(*) FROM Torrents'
connection.query(query, function(err, rows, fields){
if (err){
throw err;
!!callback && callback(-1)
}
else{
!!callback && callback(rows[0]["COUNT(*)"])
}
})
}
exports.getNbTorrents = getNbTorrents
var getNbTorrentsByCid = function(CID, callback){
if(CID){
var query = 'SELECT COUNT(*) FROM Torrents WHERE category=?'
connection.query(query, [CID], function(err, rows, fields){
if (err){
throw err;
!!callback && callback(-1)
}
else{
!!callback && callback(rows[0]["COUNT(*)"])
}
})
}
else{
!!callback && callback(-1)
}
}
exports.getNbTorrentsByCid = getNbTorrentsByCid
router.route('/torrents')
.get(function (req, res){
findAllTorrents(req.query, function(data){
if(!!data)
res.json(data)
else
res.status(500).send()
})
})
.post(function (req, res){
insertTorrent(req.body, function(ok){
if(ok)
res.status(201).send()
else
res.status(500).send()
})
})
router.route('/torrents/:id')
.get(function (req, res){
findTorrentById(req.params.id, function(data){
if(!data){
res.status(404).send()
}
else{
res.json(data)
}
})
})
.put(function (req, res){
res.status(501).send("Not implemented")
})
.delete(function (req, res){
res.status(501).send("Not implemented")
})
exports.router = router<file_sep>var request = require("request")
var t411url = "https://api.t411.me"
var userToken = null
var getUserToken = function(username, password, callback){
var postData = {
"username" : username,
"password" : <PASSWORD>
}
request.post({url: (t411url+'/auth'), form: postData}, function(err,httpResponse,body){
var jsonBody = JSON.parse(body)
if(jsonBody.hasOwnProperty("token")){
callback(jsonBody["token"])
}
else{
callback(null)
}
})
}
exports.connectUser = function(username, password, callback){
getUserToken(username, password, function(token){
if(token){
console.log("Authenticated !")
userToken = token
!!callback && callback()
}
else{
console.log("Bad username / password !")
!!callback && callback()
}
})
}
var isConnected = function(){
return userToken? true:false
}
exports.isConnected = isConnected
exports.getTorrentsCount = function(cid, callback){
if(!cid){
!!callback && callback(0)
}
else{
var url = t411url+
'/torrents/search/'+
"&cid="+cid+
"&limit=1"
request.get({url: url, headers: {'Authorization':userToken}}, function(err,httpResponse,body){
if(err){
!!callback && callback(0)
}
else{
var bodyLines = body.split('\n')
var reqResult = JSON.parse((bodyLines.length>0)?bodyLines[3]:bodyLines[0])
var nbTorrents = reqResult.total?parseInt(reqResult.total):0;
!!callback && callback(nbTorrents)
}
})
}
}
exports.getTorrents = function(searchParams, callback){
if(!isConnected()){
!!callback && callback(null)
}
else{
var url = t411url+
'/torrents/search/'+
(!!searchParams && searchParams.query?searchParams.query:'')+
(!!searchParams && searchParams.cid?"&cid="+searchParams.cid:'')+
(!!searchParams && searchParams.limit?"&limit="+searchParams.limit:"&limit=100")+
(!!searchParams && searchParams.offset?"&offset="+searchParams.offset:'')
request.get({url: url, headers: {'Authorization':userToken}}, function(err,httpResponse,body){
if(err){
!!callback && callback(null)
}
else{
var processedTorrents = []
var bodyLines = body.split('\n')
var strResult = (bodyLines.length>0)?bodyLines[3]:bodyLines[0]
if(!(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(strResult.replace(/"(\\.|[^"\\])*"/g,'')))){
var reqResult = JSON.parse(strResult)
var torrents = reqResult.torrents?reqResult.torrents:[]
torrents.forEach(function(elt){
if(isNaN(elt)){
processedTorrents.push(elt)
}
})
!!callback && callback(processedTorrents)
}
else{
console.log("non valid rep")
!!callback && callback(processedTorrents)
}
}
})
}
}
exports.getAllCID = function(callback){
var cids = [];
if(userToken){
request.get({url: (t411url+'/categories/tree'), headers: {'Authorization':userToken}}, function(err,httpResponse,body){
var jsonBody = JSON.parse(body)
for(var pid in jsonBody){
if(jsonBody[pid].hasOwnProperty("cats")){
for(var cid in jsonBody[pid].cats){
cids.push(cid)
}
}
}
callback && callback(cids)
})
}
else{
console.log("No user connected !")
!!callback && callback(null)
}
}<file_sep>var express = require("express")
var bodyParser = require("body-parser")
var cookieParser = require("cookie-parser")
var app = express()
var t411 = require("./t411-handler.js")
var Users = require("./ressources/users.js")
var Torrents = require("./ressources/torrents.js")
//Express initialization
app.set('trust proxy', 1) // trust first proxy
app.use(express.static('public'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }))// parse application/x-www-form-urlencoded
app.use(bodyParser.json())// parse application/json
exports.app = app
var authentication = require('./authentication.js')
//Middleware - Loggin each request with timestamp + path
app.use(function (req, res, next) {
var d = new Date();
var strDate = d.toLocaleString();
strDate = strDate.substr(0,strDate.indexOf('GMT'))
console.log(strDate+"- "+req.method+" : "+req.url);
next();
});
var options = {
root: __dirname + '/app/',
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
}
app.get("/", function (req, res){
if(req.user){
res.sendFile("index.html", options, function (err) {
if (err) {
console.log(err);
res.status(err.status).end();
}
})
}
else{
res.redirect('/login')
}
})
app.get('/login', function(req, res){
res.sendFile("login.html", options, function (err) {
if (err) {
console.log(err);
res.status(err.status).end();
}
})
})
app.use('/api', function (req, res, next){
if(req.user){
next()
}
else{
res.status(401).send({msg : "You have to sign in."})
}
},Torrents.router, Users.router)
//Start server
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Nox Node Server - START ! - HOST : http://%s:%s', host, port)
})<file_sep>CREATE TABLE users (
id int PRIMARY KEY NOT NULL AUTO_INCREMENT,
username VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
firstname VARCHAR(255),
lastname VARCHAR(255),
t411_username VARCHAR(255),
t411_password VARCHAR(255),
rights int NOT NULL DEFAULT 0
)
CREATE TABLE torrents (
id int PRIMARY KEY NOT NULL,
name VARCHAR(255),
category VARCHAR(255),
rewritename VARCHAR(255),
seeders int,
leechers int,
comments int,
added DATETIME,
size BIGINT,
times_completed int,
owner VARCHAR(255),
categoryname VARCHAR(255),
username VARCHAR(255)
)<file_sep>var server = require('./index.js')
var app = server.app
var passport = require("passport")
var LocalStrategy = require('passport-local').Strategy;
var flash = require('connect-flash')
var session = require('express-session')
var RedisStore = require('connect-redis')(session)
var redis = require("redis")
var redis_client = redis.createClient()
var Users = require("./ressources/users.js")
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true,
store: new RedisStore({
client: redis_client
})
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(flash())
passport.use(new LocalStrategy(
function(username, password, done) {
Users.findUser(username, function (err, user) {
if (err) { return done(err) }
if (!user) {
return done(null, false, { message: 'Incorrect username.' })
}
if (!Users.validPassword(password, user.password)) {
return done(null, false, { message: 'Incorrect password.' })
}
return done(null, user)
})
}
))
passport.serializeUser(function(user, done) {
done(null, user.username)
})
passport.deserializeUser(function(username, done) {
Users.findUser(username, function(err, user) {
done(err, user)
})
})
//Route for login in - CREDENTIALS : {"username":username, "password":<PASSWORD>}
app.post('/login', passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login',
failureFlash: true }))
app.get('/logout', function(req, res){
req.logout()
res.redirect('/')
})<file_sep>var express = require("express")
var router = express.Router();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '<PASSWORD>!',
database : 't411db'
});
var user_model = {
"username":null,
"password":<PASSWORD>,
"t411_username":null,
"t411_password":<PASSWORD>,
"firstname":null,
"lastname":null
}
exports.validPassword = function(givenPwd, userPwd){
if(givenPwd.match(userPwd)){
return true
}
return false
}
var createUser = function(user){
var repUser = {}
for(var key in user_model){
repUser[key] = user[key]? user[key] : null
}
return repUser
}
var findUser = function(username, callback){
var query = 'SELECT * FROM Users WHERE username=?'
connection.query(query, [username], function(err, rows, fields){
if(err){
!!callback && callback(err)
}
else{
!!callback && callback(null, rows[0])
}
})
}
exports.findUser = findUser
var insertUser = function(user, callback){
var query = 'INSERT INTO Users SET ?'
connection.query(query, createUser(user), function(err, rows, fields){
if (err){
!!callback && callback(err)
}
else{
!!callback && callback()
}
})
}
exports.insertUser = insertUser
var updateUser = function(user, callback){
}
router.route('/users/:username')
.get(function (req, res){
if(req.params.username){
findUser(req.params.username, function(err, user){
if(err){
res.status(500).send(err)
}
else{
if(user){
res.json(user)
}
else{
res.status(404).send()
}
}
})
}
else{
res.status(400).send({msg:"Missing parameters."})
}
})
exports.router = router
|
cc6b2ee2243f9c6569095a2db08d22ed6b50ce31
|
[
"JavaScript",
"SQL"
] | 6
|
JavaScript
|
Noxionx/NoxNodeServ
|
3c73c7a2dfb8348caaa3277fc75309019be3137e
|
7cd033b4076d15d5b3ceeebde92a5912417cea82
|
refs/heads/master
|
<repo_name>pawanpathak03101987/BhattaVyapar<file_sep>/app/src/main/java/com/pawan/bhattavyapar/adapter/HomeFragment_Adapter.kt
package com.pawan.bhattavyapar.adapter
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.fragment.app.FragmentActivity
import com.pawan.bhattavyapar.R
import com.pawan.bhattavyapar.ui.fragments.CustomerProfileFragment
import com.pawan.bhattavyapar.ui.fragments.RecivingBalanceFragment
import kotlinx.android.synthetic.main.home_adapter.view.*
import java.util.ArrayList
class HomeFragment_Adapter {
companion object{
public fun createList(activity: FragmentActivity,lyMain:LinearLayout)
{
val inflater: LayoutInflater =
activity?.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
lyMain.removeAllViews()
for (i in 0 until 5) {
val view: ViewGroup =
inflater.inflate(R.layout.home_adapter, lyMain, false) as ViewGroup
lyMain.addView(view)
view.lyConMain.setOnClickListener {
val bundle = Bundle()
bundle.putString("fragmentName", "Customer Profile")
val moviesFragment = CustomerProfileFragment()
moviesFragment.arguments = bundle
activity.supportFragmentManager.beginTransaction()
.replace(R.id.activity_main_content_id, moviesFragment).commit()
}
}
}}
}<file_sep>/app/src/main/java/com/pawan/bhattavyapar/utils/DatePickerClass.java
package com.pawan.bhattavyapar.utils;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class DatePickerClass extends DialogFragment implements DatePickerDialog.OnDateSetListener {
TextView tv;
int day = 0, month = 0, year = 0;
public DatePickerClass() {
}
@SuppressLint("ValidFragment")
public DatePickerClass(TextView tv) {
this.tv = tv;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
String sDate = tv.getText().toString();
day = calendar.get(Calendar.DAY_OF_MONTH);
month = calendar.get(Calendar.MONTH);
year = calendar.get(Calendar.YEAR);
calendar.add(Calendar.DATE, 1);
// }
DatePickerDialog datepickerdialog = new DatePickerDialog(getActivity(), this, year, month, day);
// datepickerdialog.getDatePicker().setMinDate(new Date().getTime());
datepickerdialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
return datepickerdialog;
}
@Override
public void onDateSet(android.widget.DatePicker view, int selectedyear, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
Calendar calander2 = Calendar.getInstance();
year = selectedyear;
month = monthOfYear;
day = dayOfMonth;
calander2.setTimeInMillis(0);
calander2.set(year, month, day, 0, 0, 0);
calander2.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
Date SelectedDate = calander2.getTime();
String StringDateformat = new SimpleDateFormat("dd-MM-yyyy").format(SelectedDate);
tv.setText(StringDateformat);
}
}<file_sep>/app/src/main/java/com/pawan/bhattavyapar/MyApplication.kt
package com.pawan.bhattavyapar
import android.app.Application
import androidx.multidex.MultiDexApplication
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.firestore.ktx.firestoreSettings
import com.google.firebase.ktx.Firebase
class MyApplication : MultiDexApplication() {
override fun onCreate() {
super.onCreate()
db = Firebase.firestore
val settings = firestoreSettings {
isPersistenceEnabled = true
}
db.firestoreSettings = settings
}
companion object{
lateinit var db:FirebaseFirestore
fun getFireStoreObj():FirebaseFirestore{
return db
}
}
}<file_sep>/app/src/main/java/com/pawan/bhattavyapar/ui/mainpage/MainActivity.kt
package com.pawan.bhattavyapar.ui.mainpage
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.core.content.ContextCompat
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.pawan.bhattavyapar.MyApplication
import com.pawan.bhattavyapar.R
import com.pawan.bhattavyapar.adapter.ClickListener
import com.pawan.bhattavyapar.adapter.NavigationRVAdapter
import com.pawan.bhattavyapar.adapter.RecyclerTouchListener
import com.pawan.bhattavyapar.data.model.NavigationItemModel
import com.pawan.bhattavyapar.ui.fragments.AddNewCustomerFragment
import com.pawan.bhattavyapar.ui.fragments.HomeFragment
import com.pawan.bhattavyapar.ui.fragments.RecivingBalanceFragment
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
lateinit var drawerLayout: DrawerLayout
private lateinit var adapter: NavigationRVAdapter
private var items = arrayListOf(
NavigationItemModel(android.R.drawable.btn_star_big_on, "Business Profile"),
NavigationItemModel(android.R.drawable.btn_star_big_on, "Add Customer"),
NavigationItemModel(android.R.drawable.btn_star_big_on, "Receive Balance"),
NavigationItemModel(android.R.drawable.btn_star_big_on, "Rate"),
)
fun SaveData()
{
val user = hashMapOf(
"Country" to "Rasia",
"CountryCode" to "Ch",
"CountryID" to "20",
"CreatedOn" to "2020-09-01T00:00:00",
"IsActive" to true,
"UploadedBy" to 2,
"CreatedBy" to 2
)
// Add a new document with a generated ID
MyApplication.getFireStoreObj().collection("MstCountry").document("335HHVa1xTyyrNZaer2D")
.set(user)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
drawerLayout = findViewById(R.id.drawer_layout)
// Set the toolbar
setSupportActionBar(toolbar)
SaveData()
navigation_rv.addOnItemTouchListener(RecyclerTouchListener(this, object : ClickListener {
override fun onClick(view: View, position: Int) {
when (position) {
0 -> {
// # Home Fragment
val bundle = Bundle()
bundle.putString("fragmentName", "Home Fragment")
val homeFragment = HomeFragment()
homeFragment.arguments = bundle
supportFragmentManager.beginTransaction()
.replace(R.id.activity_main_content_id, homeFragment).commit()
}
1 -> {
// # Music Fragment
val bundle = Bundle()
bundle.putString("fragmentName", "Add Customer")
val musicFragment = AddNewCustomerFragment()
musicFragment.arguments = bundle
supportFragmentManager.beginTransaction()
.replace(R.id.activity_main_content_id, musicFragment).commit()
}
2 -> {
// # Movies Fragment
val bundle = Bundle()
bundle.putString("fragmentName", "Receive Balance")
val moviesFragment = RecivingBalanceFragment()
moviesFragment.arguments = bundle
supportFragmentManager.beginTransaction()
.replace(R.id.activity_main_content_id, moviesFragment).commit()
}
}
// Don't highlight the 'Profile' and 'Like us on Facebook' item row
if (position != 6 && position != 4) {
updateAdapter(position)
}
Handler().postDelayed({
drawerLayout.closeDrawer(GravityCompat.START)
}, 200)
}
}))
// Setup Recyclerview's Layout
updateAdapter(0)
// Set 'Home' as the default fragment when the app starts
val bundle = Bundle()
bundle.putString("fragmentName", "Home Fragment")
val homeFragment = HomeFragment()
homeFragment.arguments = bundle
supportFragmentManager.beginTransaction()
.replace(R.id.activity_main_content_id, homeFragment).commit()
val toggle: ActionBarDrawerToggle = object : ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
override fun onDrawerClosed(drawerView: View) {
// Triggered once the drawer closes
super.onDrawerClosed(drawerView)
try {
val inputMethodManager =
getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(currentFocus?.windowToken, 0)
} catch (e: Exception) {
e.stackTrace
}
}
override fun onDrawerOpened(drawerView: View) {
// Triggered once the drawer opens
super.onDrawerOpened(drawerView)
try {
val inputMethodManager =
getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
} catch (e: Exception) {
e.stackTrace
}
}
}
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
// Set Header Image
navigation_header_img.setImageResource(R.mipmap.facebook)
// Set background of Drawer
navigation_layout.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary))
navigation_rv.layoutManager = LinearLayoutManager(this)
navigation_rv.setHasFixedSize(true)
}
private fun updateAdapter(highlightItemPos: Int) {
adapter = NavigationRVAdapter(items, highlightItemPos)
navigation_rv.adapter = adapter
adapter.notifyDataSetChanged()
}
override fun onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START)
} else {
// Checking for fragment count on back stack
if (supportFragmentManager.backStackEntryCount > 0) {
// Go to the previous fragment
supportFragmentManager.popBackStack()
} else {
// Exit the app
super.onBackPressed()
}
}
}
}<file_sep>/app/src/main/java/com/pawan/bhattavyapar/data/model/SignUpUser.kt
package com.pawan.bhattavyapar.data.model
/**
* Data class that captures user information for logged in users retrieved from SignUpRepository
*/
data class SignUpUser(
val userId: String,
val displayName: String
)<file_sep>/app/src/main/java/com/pawan/bhattavyapar/data/model/NavigationItemModel.kt
package com.pawan.bhattavyapar.data.model
data class NavigationItemModel(var icon: Int, var title: String)<file_sep>/app/src/main/java/com/pawan/bhattavyapar/ui/signup/SignUpActivity.kt
package com.pawan.bhattavyapar.ui.signup
import android.app.Activity
import android.content.Intent
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import android.os.Bundle
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.Button
import android.widget.EditText
import android.widget.ProgressBar
import android.widget.Toast
import com.pawan.bhattavyapar.MyApplication
import com.pawan.bhattavyapar.R
import com.pawan.bhattavyapar.ui.login.LoginActivity
import com.pawan.bhattavyapar.ui.signup.SignUpUserView
import com.pawan.bhattavyapar.ui.signup.SignUpViewModel
import com.pawan.bhattavyapar.ui.login.LoginViewModelFactory
import com.pawan.bhattavyapar.ui.mainpage.MainActivity
import com.pawan.bhattavyapar.utils.Others
import kotlinx.android.synthetic.main.activity_sign_up.*
import java.util.*
class SignUpActivity : AppCompatActivity() {
private lateinit var signUpViewModel: SignUpViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sign_up)
val username = findViewById<EditText>(R.id.username)
val password = findViewById<EditText>(R.id.password)
val login = findViewById<Button>(R.id.btnLogin)
val btnLogin = findViewById(R.id.btnLogin) as Button
val btnSignup = findViewById(R.id.btnSignup) as Button
btnLogin.setOnClickListener(View.OnClickListener {
val intent = Intent(this@SignUpActivity, LoginActivity::class.java)
startActivity(intent)
})
button3.setOnClickListener(View.OnClickListener {
checkforNewUser()
})
//val loading = findViewById<ProgressBar>(R.id.loading)
/*signUpViewModel = ViewModelProviders.of(this, SignUpViewModelFactory())
.get(SignUpViewModel::class.java)
signUpViewModel.signUpFormState.observe(this@SignUpActivity, Observer {
val signUpFormState = it ?: return@Observer
// disable login button unless both username / password is valid
login.isEnabled = signUpFormState.isDataValid
if (signUpFormState.usernameError != null) {
username.error = getString(signUpFormState.usernameError)
}
if (signUpFormState.passwordError != null) {
password.error = getString(signUpFormState.passwordError)
}
})
signUpViewModel.signUpResult.observe(this@SignUpActivity, Observer {
val signUpResult = it ?: return@Observer
//loading.visibility = View.GONE
if (signUpResult.error != null) {
showLoginFailed(signUpResult.error)
}
if (signUpResult.success != null) {
updateUiWithUser(signUpResult.success)
}
setResult(Activity.RESULT_OK)
//Complete and destroy login activity once successful
finish()
})*/
/*username.afterTextChanged {
signUpViewModel.signUpDataChanged(
username.text.toString(),
password.text.toString()
)
}
*/
/*password.apply {
afterTextChanged {
signUpViewModel.signUpDataChanged(
username.text.toString(),
password.text.toString()
)
}
setOnEditorActionListener { _, actionId, _ ->
when (actionId) {
EditorInfo.IME_ACTION_DONE ->
signUpViewModel.signUp(
username.text.toString(),
password.text.toString()
)
}
false
}
login.setOnClickListener {
//loading.visibility = View.VISIBLE
signUpViewModel.signUp(username.text.toString(), password.text.toString())
}
}*/
}
private fun checkforNewUser() {
MyApplication.getFireStoreObj().collection("MstUsers").whereEqualTo("PrimaryMobileNo", editMobileNumber.text.toString()).get().addOnSuccessListener { result ->
if (editMobileNumber.text.toString().length==0)
{
Toast.makeText(this,"Enter mobile number",Toast.LENGTH_LONG).show()
}else if (editPassword.text.toString().length==0)
{
Toast.makeText(this,"Enter password",Toast.LENGTH_LONG).show()
}else if (editConfirmPassword.text.toString().length==0)
{
Toast.makeText(this,"Enter confirm password",Toast.LENGTH_LONG).show()
}else if(!editPassword.text.toString().equals(editConfirmPassword.text.toString()))
{
Toast.makeText(this,"Password is not matched",Toast.LENGTH_LONG).show()
} else if (result.size()>0)
{
Toast.makeText(this,"This mobile is already exits",Toast.LENGTH_LONG).show()
}
else{
val docUid=UUID.randomUUID().toString()
val user = hashMapOf(
"CountryID" to 3,
"CreatedOn" to Others.getCurrentDate(),
"FirstName" to "",
"FullName" to "",
"IsActive" to true,
"IsDeleted" to false,
"LastName" to "",
"Password" to <PASSWORD>(),
"PrimaryMobileNo" to editMobileNumber.text.toString(),
"UserRoleID" to 1,
"UserUID" to docUid
)
Log.e("User", "user is new")
// Add a new document with a generated ID
MyApplication.getFireStoreObj().collection("MstUsers").document(docUid)
.set(user) .addOnSuccessListener {
val intent = Intent(this@SignUpActivity, LoginActivity::class.java)
startActivity(intent)
}
.addOnFailureListener { e -> Log.w("Sign up", "Error writing document", e) }
}
}
.addOnFailureListener { exception ->
Log.e("User", "Error getting documents.", exception)
// Log.e("User", "${document.id} => ${document.data}")
}
}
private fun updateUiWithUser(model: SignUpUserView) {
val welcome = getString(R.string.welcome)
val displayName = model.displayName
// TODO : initiate successful logged in experience
Toast.makeText(
applicationContext,
"$welcome $displayName",
Toast.LENGTH_LONG
).show()
}
private fun showLoginFailed(@StringRes errorString: Int) {
Toast.makeText(applicationContext, errorString, Toast.LENGTH_SHORT).show()
}
}
/**
* Extension function to simplify setting an afterTextChanged action to EditText components.
*/
fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
this.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(editable: Editable?) {
afterTextChanged.invoke(editable.toString())
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
})
}<file_sep>/app/src/main/java/com/pawan/bhattavyapar/utils/Others.kt
package com.pawan.bhattavyapar.utils
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
class Others {
companion object{
fun getCurrentDate(): String? {
val df: DateFormat = SimpleDateFormat("yyyy-MM-dd")
val dateobj = Date()
return df.format(dateobj)
}
}
}<file_sep>/app/src/main/java/com/pawan/bhattavyapar/adapter/CustomerProfile_Adapter.kt
package com.pawan.bhattavyapar.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.fragment.app.FragmentActivity
import com.pawan.bhattavyapar.R
class CustomerProfile_Adapter {
companion object{
public fun createList(activity: FragmentActivity, lyMain: LinearLayout)
{
val inflater: LayoutInflater =
activity?.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
lyMain.removeAllViews()
for (i in 0 until 5) {
val view: ViewGroup =
inflater.inflate(R.layout.customer_profile_adapter, lyMain, false) as ViewGroup
lyMain.addView(view)
}
}}
}
|
eb9768cb014c80fcd6255a605473e8282dde6923
|
[
"Java",
"Kotlin"
] | 9
|
Kotlin
|
pawanpathak03101987/BhattaVyapar
|
48d903b1d3d48a8bee55d18afd9f8a2099c8c822
|
8505dedd86e2af827f547d174d579b2612b9777b
|
refs/heads/master
|
<repo_name>Igor3Volf/SOEN387<file_sep>/SOEN387/src/technical_service/UserRDG.java
package technical_service;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import ts.UserTS;
import model.User;
import Utility.DatabaseConn;
public class UserRDG {
private int userId;
private String userName;
private String password;
private int currentDeck;
private String gameStatus;
private int gameId;
private int handId;
public void setUserId(int userId) {
this.userId = userId;
}
public String getGameStatus() {
return gameStatus;
}
public int getGameId() {
return gameId;
}
public int getHandId() {
return handId;
}
public void setGameStatus(String gameStatus) {
this.gameStatus = gameStatus;
}
public void setGameId(int gameId) {
this.gameId = gameId;
}
public void setHandId(int handId) {
this.handId = handId;
}
public int getUserId() {
return userId;
}
public String getUserName() {
return userName;
}
public int getCurrentDeck() {
return currentDeck;
}
public void setUserName(String u) {
this.userName = u;
}
public void setCurrentDeck(int d) {
this.currentDeck = d;
}
public UserRDG(int userId, String userName, String password,
int currentDeck, String gameStatus, int gameId, int handId) {
super();
this.userId = userId;
this.userName = userName;
this.password = <PASSWORD>;
this.currentDeck = currentDeck;
this.gameStatus = gameStatus;
this.gameId = gameId;
this.handId = handId;
}
public UserRDG(int id, String n, int d) {
this.userId = id;
this.userName = n;
this.currentDeck = d;
}
public UserRDG(int id, String n, String pass) {
this.userId = id;
this.userName = n;
this.password = <PASSWORD>;
}
public UserRDG(String n) {
this.userName = n;
}
public UserRDG(){
this.userId = 0;
this.userName = "";
this.password = "";
this.currentDeck = 0;
this.gameStatus = "";
this.gameId = 0;
this.handId = 0;
}
public static void truncate(Connection conn){
String trunSQL = "TRUNCATE Users;";
try {
PreparedStatement prepStat = conn.prepareStatement(trunSQL);
prepStat.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized static List<UserRDG> findAll() {
Connection conn = (new DatabaseConn()).dbConn.get();
List<UserRDG> l = new ArrayList<UserRDG>();
String allUsersSQL = "SELECT userId, userName, currentDeck, gameStatus, gameId, handId FROM Users";
PreparedStatement prepStat = null;
try {
prepStat = conn.prepareStatement(allUsersSQL);
ResultSet rs = prepStat.executeQuery();
while (rs.next()) {
UserRDG ur= new UserRDG();
ur.setUserId(Integer.parseInt(rs.getString("userId")));
ur.setUserName(rs.getString("userName"));
ur.setGameStatus(rs.getString("gameStatus"));
if(!(rs.getString("currentDeck")==null))
ur.setCurrentDeck(Integer.parseInt(rs.getString("currentDeck")));
if(!(rs.getString("gameId")==null))
ur.setGameId(Integer.parseInt(rs.getString("gameId")));
if(!(rs.getString("handId")==null))
ur.setHandId(Integer.parseInt(rs.getString("handId")));
l.add(ur);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (prepStat != null) {
try {
prepStat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return l;
}
public synchronized static UserRDG find(String username) {
Connection conn = (new DatabaseConn()).dbConn.get();
UserRDG ur = new UserRDG();
String allUsersSQL = "SELECT userId, userName, currentDeck, gameStatus, gameId, handId FROM Users WHERE userName = ?";
PreparedStatement prepStat = null;
try {
prepStat = conn.prepareStatement(allUsersSQL);
prepStat.setString(1, username);
ResultSet rs = prepStat.executeQuery();
if(rs.next()) {
ur.setUserId(Integer.parseInt(rs.getString("userId")));
ur.setUserName(rs.getString("userName"));
ur.setGameStatus(rs.getString("gameStatus"));
if(!(rs.getString("currentDeck")==null))
ur.setCurrentDeck(Integer.parseInt(rs.getString("currentDeck")));
if(!(rs.getString("gameId")==null))
ur.setGameId(Integer.parseInt(rs.getString("gameId")));
if(!(rs.getString("handId")==null))
ur.setHandId(Integer.parseInt(rs.getString("handId")));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (prepStat != null) {
try {
prepStat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return ur;
}
public synchronized static UserRDG find(int userId) {
Connection conn = (new DatabaseConn()).dbConn.get();
UserRDG ur = null;
String allUsersSQL = "SELECT userId, userName, currentDeck, gameStatus, gameId, handId FROM Users WHERE userId = ?";
PreparedStatement prepStat = null;
try {
prepStat = conn.prepareStatement(allUsersSQL);
prepStat.setInt(1, userId);
ResultSet rs = prepStat.executeQuery();
if(rs.next()) {
ur = new UserRDG();
ur.setUserId(Integer.parseInt(rs.getString("userId")));
ur.setUserName(rs.getString("userName"));
ur.setGameStatus(rs.getString("gameStatus"));
if(!(rs.getString("currentDeck")==null))
ur.setCurrentDeck(Integer.parseInt(rs.getString("currentDeck")));
if(!(rs.getString("gameId")==null))
ur.setGameId(Integer.parseInt(rs.getString("gameId")));
if(!(rs.getString("handId")==null))
ur.setHandId(Integer.parseInt(rs.getString("handId")));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (prepStat != null) {
try {
prepStat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return ur;
}
public synchronized static UserRDG find(String u, String pass) {
Connection conn = (new DatabaseConn()).dbConn.get();
UserRDG ur = null;
String sqlStatement = "SELECT userId, userName, currentDeck, gameStatus, gameId, handId FROM Users WHERE userName = ? AND password = MD5(?)";
PreparedStatement prepStat = null;
try {
prepStat = conn.prepareStatement(sqlStatement);
prepStat.setString(1, u);
prepStat.setString(2, pass);
ResultSet rs = prepStat.executeQuery();
if(rs.next()) {
ur = new UserRDG();
ur.setUserId(Integer.parseInt(rs.getString("userId")));
ur.setUserName(rs.getString("userName"));
ur.setGameStatus(rs.getString("gameStatus"));
if(!(rs.getString("currentDeck")==null))
ur.setCurrentDeck(Integer.parseInt(rs.getString("currentDeck")));
if(!(rs.getString("gameId")==null))
ur.setGameId(Integer.parseInt(rs.getString("gameId")));
if(!(rs.getString("handId")==null))
ur.setHandId(Integer.parseInt(rs.getString("handId")));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (prepStat != null) {
try {
prepStat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return ur;
}
public synchronized static int insert(UserTS u) {
int result = -1;
Connection conn = (new DatabaseConn()).dbConn.get();
String sqlStatement = "INSERT INTO Users (userId,userName,password) VALUES(?,?,MD5(?))";
PreparedStatement prepStat = null;
try {
prepStat = conn.prepareStatement(sqlStatement);
prepStat.setInt(1, u.getUserId());
prepStat.setString(2, u.getUserName());
prepStat.setString(3, u.getPassword());
result = prepStat.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public synchronized static int delete(int uid) {
int result = -1;
Connection conn = (new DatabaseConn()).dbConn.get();
String sqlStatement = "DELETE FROM Users WHERE userId=?";
PreparedStatement prepStat = null;
try {
prepStat = conn.prepareStatement(sqlStatement);
prepStat.setInt(1, uid);
result = prepStat.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public synchronized static int update(int uid, String fieldName, String newValue) {
int result = -1;
Connection conn = (new DatabaseConn()).dbConn.get();
String sqlStatement = "UPDATE Users SET "+fieldName+"=? WHERE userId=?";
PreparedStatement prepStat = null;
try {
prepStat = conn.prepareStatement(sqlStatement);
prepStat.setString(1, newValue);
prepStat.setInt(2, uid);
result = prepStat.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public synchronized static int update(int uid, String fieldName, int newValue) {
int result = -1;
Connection conn = (new DatabaseConn()).dbConn.get();
String sqlStatement = "UPDATE Users SET "+fieldName+"=? WHERE userId=?";
PreparedStatement prepStat = null;
try {
prepStat = conn.prepareStatement(sqlStatement);
prepStat.setInt(1, newValue);
prepStat.setInt(2, uid);
result = prepStat.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public synchronized static int getMaxId() {
int result = 0;
Connection conn = (new DatabaseConn()).dbConn.get();
String sqlStatement = "SELECT MAX(userId) as 'max' FROM Users;";
PreparedStatement prepStat = null;
ResultSet rs;
try {
prepStat = conn.prepareStatement(sqlStatement);
rs = prepStat.executeQuery();
while (rs.next()) {
result=rs.getInt("max");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
<file_sep>/README.md
# SOEN387
A project where the main focus was to split tasks in different paterns.
There are 3 main layer of the web service.
-Application : where user's request is processing and the respond is being send back.
-Domain: the request is being processed here and so is the responce. The instantiation of nessary objects is happining here.
-Technical Services: This is the lowest layer and it is used to load or save the information to or from databases.
Each layer is using different paterns such as:
Front Controlers, Dispatcher and Template View for Application layer.
Commands, Unit of Work, Factory, Input and Output Mappers, Proxy for Domain layer.
Table Date Gateaway and Finder for Technical Services.
This project was using library SoenEA which is Proffessor's Stuard Thiel library that we had to use in order to achieve success of this project.
<file_sep>/SOEN387/src/pc/ChallengePlayer.java
package pc;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Map;
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 Utility.DatabaseConn;
import ts.ChallengeTS;
import ts.UserTS;
/**
* Servlet implementation class Register
*/
@WebServlet("/ChallengePlayer")
public class ChallengePlayer extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ChallengePlayer() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
// this doPost was based on the goGet from the file that Thiel Stuart
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ")
.append(request.getContextPath());
(new DatabaseConn()).init();
try {
String challengee = request.getParameter("player");
if (request.getSession(true).getAttribute("userid") == null) {
request.setAttribute("message", "You must be logged in");
request.getRequestDispatcher("WEB-INF/jsp/fail.jsp").forward(
request, response);
} else if (challengee == null || challengee.isEmpty()) {
request.setAttribute("message", "You must enter a challengee.");
request.getRequestDispatcher("WEB-INF/jsp/fail.jsp").forward(
request, response);
} else if (Integer.parseInt(challengee)==(int)(request.getSession(true).getAttribute(
"userid"))) {
request.setAttribute("message",
"You cannot challenge your self.");
request.getRequestDispatcher("WEB-INF/jsp/fail.jsp").forward(
request, response);
} else {
int challenger = (int) request.getSession(true).getAttribute(
"userid");
int deckId = UserTS.hasDeck(challenger);
if (deckId <= 0) {
request.setAttribute("message", "You must have a deck.");
request.getRequestDispatcher("WEB-INF/jsp/fail.jsp")
.forward(request, response);
} else {
if (!UserTS.exist(challengee)) {
request.setAttribute("message",
"This Challangee does not exist.");
request.getRequestDispatcher("WEB-INF/jsp/fail.jsp")
.forward(request, response);
} else {
ChallengeTS.challenge(challenger, challengee);
request.setAttribute("message",
"The challenge have been created.");
request.getRequestDispatcher("WEB-INF/jsp/success.jsp")
.forward(request, response);
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
(new DatabaseConn()).tearDown();
}
}
}
<file_sep>/SOEN387/src/pc/AcceptChallenge.java
package pc;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Map;
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 net.minidev.json.JSONObject;
import net.minidev.json.parser.JSONParser;
import org.apache.commons.io.IOUtils;
import Utility.DatabaseConn;
import technical_service.UserRDG;
import ts.ChallengeTS;
import ts.GameTS;
import ts.UserTS;
/**
* Servlet implementation class Register
*/
@WebServlet("/AcceptChallenge")
public class AcceptChallenge extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AcceptChallenge() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
// this doPost was based on the goGet from the file that Thiel Stuart
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ")
.append(request.getContextPath());
(new DatabaseConn()).init();
try {
String challengeId = request.getParameter("challenge");
if (request.getSession(true).getAttribute("userid") == null) {
request.setAttribute("message", "You must be logged in.");
request.getRequestDispatcher("WEB-INF/jsp/fail.jsp").forward(
request, response);
} else {
int challanger= (int)request.getSession(true).getAttribute("userid");
System.out.println("Challanger " +challanger+" "+"Challanger "+challengeId);
if (challengeId == null || challengeId.isEmpty() || challengeId == "") {
request.setAttribute("message",
"You need to select a challenge.");
request.getRequestDispatcher("WEB-INF/jsp/fail.jsp")
.forward(request, response);
} else {
if(ChallengeTS.yourOwnChallenge(challengeId, challanger)){
request.setAttribute("message",
"You cannot accept your own challenge.");
request.getRequestDispatcher("WEB-INF/jsp/fail.jsp")
.forward(request, response);
}
else if (!ChallengeTS.yourChallenge(challengeId, challanger)) {
request.setAttribute("message",
"You cannot accept someone else challenge.");
request.getRequestDispatcher("WEB-INF/jsp/fail.jsp")
.forward(request, response);
} else {
ChallengeTS.acceptChallenge(challengeId);
GameTS.initGame(challengeId);
request.setAttribute("message",
"That user has been successfully accepted challenge.");
request.getRequestDispatcher("WEB-INF/jsp/success.jsp")
.forward(request, response);
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
(new DatabaseConn()).tearDown();
}
}
}
<file_sep>/SOEN387/src/pc/Register.java
package pc;
import java.io.IOException;
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 Utility.DatabaseConn;
import ts.UserTS;
/**
* Servlet implementation class Register
*/
@WebServlet("/Register")
public class Register extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Register() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
// this doPost was based on the goGet from the file that Thiel Stuart
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException {
// TODO Auto-generated method stub
try {
response.getWriter().append("Served at: ")
.append(request.getContextPath());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
(new DatabaseConn()).init();
try {
String user = request.getParameter("user");
String pass = request.getParameter("pass");
if (user == null || user.isEmpty() || pass == null
|| pass.isEmpty()) {
request.setAttribute("message",
"Please enter both a username and a password.");
request.getRequestDispatcher("WEB-INF/jsp/fail.jsp").forward(
request, response);
} else {
if (UserTS.contains(user)) {
request.setAttribute("message",
"That user has already registered.");
request.getRequestDispatcher("WEB-INF/jsp/fail.jsp")
.forward(request, response);
} else {
UserTS newU = UserTS.register(user, pass);
System.out.println("Session Id " + newU.getUserId());
request.getSession(true).setAttribute("userid", newU.getUserId());
request.setAttribute("message",
"That user has been successfully registered.");
request.getRequestDispatcher("WEB-INF/jsp/success.jsp")
.forward(request, response);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
(new DatabaseConn()).tearDown();
}
}
}
<file_sep>/SOEN387/src/technical_service/ChallengeRDG.java
package technical_service;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import Utility.DatabaseConn;
import technical_service.CardRDG;
import ts.CardTS;
import ts.ChallengeTS;
public class ChallengeRDG {
private int chalId;
private int challenger;
private int challengee;
private int status;
public ChallengeRDG(int chalId, int challenger, int challengee, int status) {
super();
this.chalId = chalId;
this.challenger = challenger;
this.challengee = challengee;
this.status = status;
}
public int getChalId() {
return chalId;
}
public int getChallenger() {
return challenger;
}
public int getChallengee() {
return challengee;
}
public int getStatus() {
return status;
}
public void setChallenger(int challenger) {
this.challenger = challenger;
}
public void setChallengee(int challengee) {
this.challengee = challengee;
}
public void setStatus(int status) {
this.status = status;
}
public synchronized static int getMaxId() {
int result = 0;
Connection conn = (new DatabaseConn()).dbConn.get();
String sqlStatement = "SELECT MAX(chalId) as 'max' FROM Challenges;";
PreparedStatement prepStat = null;
ResultSet rs;
try {
prepStat = conn.prepareStatement(sqlStatement);
rs = prepStat.executeQuery();
while (rs.next()) {
result = rs.getInt("max");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public synchronized static List<ChallengeRDG> findAll() {
Connection conn = (new DatabaseConn()).dbConn.get();
List<ChallengeRDG>list=new ArrayList<ChallengeRDG>();
ChallengeRDG ur = null;
String scriptSQL = "SELECT chalId, challenger, challengee, statusId FROM Challenges ";
PreparedStatement prepStat = null;
try {
prepStat = conn.prepareStatement(scriptSQL);
ResultSet rs = prepStat.executeQuery();
while (rs.next()) {
int chalId = Integer.parseInt(rs.getString("chalId"));
int challenger = Integer.parseInt(rs.getString("challenger"));
int challengee = Integer.parseInt(rs.getString("challengee"));
int statusId = Integer.parseInt(rs.getString("statusId"));
System.out.println("chalId" + chalId);
System.out.println("challenger : " + challenger);
System.out.println("challengee : " + challengee);
System.out.println("statusId : " + statusId);
ur = new ChallengeRDG(chalId, challenger, challengee, statusId);
list.add(ur);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (prepStat != null) {
try {
prepStat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return list;
}
public synchronized static ChallengeRDG find(int cId) {
Connection conn = (new DatabaseConn()).dbConn.get();
ChallengeRDG ur = null;
String scriptSQL = "SELECT chalId, challenger, challengee, statusId FROM Challenges WHERE chalId = ?";
PreparedStatement prepStat = null;
try {
prepStat = conn.prepareStatement(scriptSQL);
prepStat.setInt(1, cId);
ResultSet rs = prepStat.executeQuery();
while (rs.next()) {
int chalId = Integer.parseInt(rs.getString("chalId"));
int challenger = Integer.parseInt(rs.getString("challenger"));
int challengee = Integer.parseInt(rs.getString("challengee"));
int statusId = Integer.parseInt(rs.getString("statusId"));
System.out.println("Find chalId" + chalId);
System.out.println("Find challenger : " + challenger);
System.out.println("Find challengee : " + challengee);
System.out.println("Find statusId : " + statusId);
ur = new ChallengeRDG(chalId, challenger, challengee, statusId);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (prepStat != null) {
try {
prepStat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return ur;
}
public synchronized static int insert(ChallengeTS c) {
int result = -1;
Connection conn = (new DatabaseConn()).dbConn.get();
String sqlStatement = "INSERT INTO Challenges (chalId,challenger,challengee, statusId) VALUES(?,?,?,?)";
PreparedStatement prepStat = null;
try {
System.out.println("Insert chalId" + c.getChalId());
System.out.println("Insert challenger : " + c.getChallenger());
System.out.println("Insert challengee : " + c.getChallengee());
System.out.println("Insert statusId : " + c.getStatus());
prepStat = conn.prepareStatement(sqlStatement);
prepStat.setInt(1, c.getChalId());
prepStat.setInt(2, c.getChallenger());
prepStat.setInt(3, c.getChallengee());
prepStat.setString(4, String.valueOf(c.getStatus()));
result = prepStat.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static int update(String cId, int status) {
int result = -1;
Connection conn = (new DatabaseConn()).dbConn.get();
String sqlStatement = "UPDATE Challenges SET statusId=? WHERE chalId=?";
PreparedStatement prepStat = null;
try {
prepStat = conn.prepareStatement(sqlStatement);
prepStat.setString(1, String.valueOf(status));
prepStat.setInt(2, Integer.parseInt(cId));
result = prepStat.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
<file_sep>/SOEN387/src/ts/BoardTS.java
package ts;
import model.Play;
import technical_service.GameRDG;
import technical_service.HandRDG;
import technical_service.UserRDG;
public class BoardTS {
public int getGameid() {
return gameid;
}
public int[] getDecks() {
return decks;
}
public int[] getPlayers() {
return players;
}
public Play[] getPlays() {
return plays;
}
public void setGameid(int gameid) {
this.gameid = gameid;
}
public void setDecks(int[] decks) {
this.decks = decks;
}
public void setPlayers(int[] players) {
this.players = players;
}
public void setPlays(Play[] plays) {
this.plays = plays;
}
public BoardTS(int gameid, int[] decks, int[] players, Play[] plays) {
super();
this.gameid = gameid;
this.decks = decks;
this.players = players;
this.plays = plays;
}
public BoardTS() {
this.gameid = 0;
this.decks = new int[2];
this.players = new int[2];
this.plays = new Play[2];
}
private int gameid;
private int[] decks;
private int[] players;
private Play[] plays;
public synchronized static BoardTS listBoard(String gId) {
int intGid= Integer.parseInt(gId);
BoardTS b = new BoardTS();
b.setGameid(intGid);
GameRDG grdg = GameRDG.find(intGid);
int[] plrs = {grdg.getPlayer1(),grdg.getPlayer2()};
UserRDG p1 =UserRDG.find(grdg.getPlayer1());
UserRDG p2 =UserRDG.find(grdg.getPlayer2());
int[] dks = {p1.getCurrentDeck(),p2.getCurrentDeck()};
HandRDG h1 = HandRDG.find(p1.getHandId());
HandRDG h2 = HandRDG.find(p2.getHandId());
Play play1= new Play(h1.getHandSize(),h1.getDeckSize(),p1.getGameStatus());
Play play2= new Play(h2.getHandSize(),h2.getDeckSize(),p2.getGameStatus());
Play[] playL= {play1, play2};
b.setDecks(dks);
b.setPlayers(plrs);
b.setPlays(playL);
System.out.println("Game Id "+ b.getGameid());
System.out.println("Player Id "+ b.getPlayers()[0]);
System.out.println("Player Id "+ b.getPlayers()[1]);
System.out.println("Deck Id "+ b.getDecks()[0]);
System.out.println("Deck Id "+ b.getDecks()[1]);
System.out.println("Status P1 "+ b.getPlays()[0].getStatus());
System.out.println("Status P1 "+ b.getPlays()[0].getHandsize());
System.out.println("Status P1 "+ b.getPlays()[0].getDecksize());
System.out.println("Status P2 "+ b.getPlays()[1].getStatus());
System.out.println("Status P2 "+ b.getPlays()[1].getHandsize());
System.out.println("Status P2 "+ b.getPlays()[1].getDecksize());
return b;
}
}
<file_sep>/SOEN387/src/technical_service/GameRDG.java
package technical_service;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import ts.CardTS;
import ts.GameTS;
import Utility.DatabaseConn;
public class GameRDG {
public int getGameId() {
return gameId;
}
public int getPlayer1() {
return player1;
}
public int getPlayer2() {
return player2;
}
public void setGameId(int gameId) {
this.gameId = gameId;
}
public void setPlayer1(int player1) {
this.player1 = player1;
}
public void setPlayer2(int player2) {
this.player2 = player2;
}
public GameRDG(int gameId, int player1, int player2) {
super();
this.gameId = gameId;
this.player1 = player1;
this.player2 = player2;
}
public GameRDG(int player1, int player2) {
super();
this.player1 = player1;
this.player2 = player2;
}
public int getPlayer1Hand() {
return player1Hand;
}
public int getPlayer2Hand() {
return player2Hand;
}
public int getPlayer1Bench() {
return player1Bench;
}
public int getPlayer2Bench() {
return player2Bench;
}
public void setPlayer1Hand(int player1Hand) {
this.player1Hand = player1Hand;
}
public void setPlayer2Hand(int player2Hand) {
this.player2Hand = player2Hand;
}
public void setPlayer1Bench(int player1Bench) {
this.player1Bench = player1Bench;
}
public void setPlayer2Bench(int player2Bench) {
this.player2Bench = player2Bench;
}
public GameRDG(int gameId, int player1, int player2, int player1Hand,
int player2Hand, int player1Bench, int player2Bench) {
super();
this.gameId = gameId;
this.player1 = player1;
this.player2 = player2;
this.player1Hand = player1Hand;
this.player2Hand = player2Hand;
this.player1Bench = player1Bench;
this.player2Bench = player2Bench;
}
public GameRDG(){
this.gameId = 0;
this.player1 = 0;
this.player2 = 0;
this.player1Hand = 0;
this.player2Hand = 0;
this.player1Bench = 0;
this.player2Bench = 0;
}
public GameRDG(int gId) {
this.gameId = gId;
}
private int gameId;
private int player1;
private int player2;
private int player1Hand;
private int player2Hand;
private int player1Bench;
private int player2Bench;
public synchronized static int getMaxId() {
int result = 0;
Connection conn = (new DatabaseConn()).dbConn.get();
String sqlStatement = "SELECT MAX(gameId) as 'max' FROM Games;";
PreparedStatement prepStat = null;
ResultSet rs;
try {
prepStat = conn.prepareStatement(sqlStatement);
rs = prepStat.executeQuery();
while (rs.next()) {
result = rs.getInt("max");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static List<GameRDG> findAll() {
Connection conn = (new DatabaseConn()).dbConn.get();
List<GameRDG> l = new ArrayList<GameRDG>();
String allUsersSQL = "SELECT gameId, player1, player2, player1Hand, player2Hand, player1Bench, player2Bench FROM Games";
PreparedStatement prepStat = null;
try {
prepStat = conn.prepareStatement(allUsersSQL);
ResultSet rs = prepStat.executeQuery();
while (rs.next()) {
GameRDG grdg= new GameRDG();
grdg.setGameId(Integer.parseInt(rs.getString("gameId")));
grdg.setPlayer1(Integer.parseInt(rs.getString("player1")));
grdg.setPlayer2(Integer.parseInt(rs.getString("player2")));
grdg.setPlayer1Hand(Integer.parseInt(rs.getString("player1Hand")));
grdg.setPlayer2Hand(Integer.parseInt(rs.getString("player2Hand")));
grdg.setPlayer1Bench(Integer.parseInt(rs.getString("player1Bench")));
grdg.setPlayer2Bench(Integer.parseInt(rs.getString("player2Bench")));
l.add(grdg);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (prepStat != null) {
try {
prepStat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return l;
}
public synchronized static GameRDG find(int gId) {
Connection conn = (new DatabaseConn()).dbConn.get();
GameRDG grdg = null;
String scriptSQL = "SELECT gameId, player1, player2, player1Hand, player2Hand, player1Bench, player2Bench FROM Games WHERE gameId = ?";
PreparedStatement prepStat = null;
try {
prepStat = conn.prepareStatement(scriptSQL);
prepStat.setInt(1, gId);
ResultSet rs = prepStat.executeQuery();
if (rs.next())
{
grdg= new GameRDG(gId);
grdg.setGameId(Integer.parseInt(rs.getString("gameId")));
grdg.setPlayer1(Integer.parseInt(rs.getString("player1")));
grdg.setPlayer2(Integer.parseInt(rs.getString("player2")));
grdg.setPlayer1Hand(Integer.parseInt(rs.getString("player1Hand")));
grdg.setPlayer2Hand(Integer.parseInt(rs.getString("player2Hand")));
grdg.setPlayer1Bench(Integer.parseInt(rs.getString("player1Bench")));
grdg.setPlayer2Bench(Integer.parseInt(rs.getString("player2Bench")));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (prepStat != null) {
try {
prepStat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return grdg;
}
public synchronized static int insert(GameTS g) {
int result = -1;
Connection conn = (new DatabaseConn()).dbConn.get();
String sqlStatement = "INSERT INTO Games (gameId, player1, player2, player1Hand, player2Hand, player1Bench, player2Bench) VALUES(?,?,?,?,?,?,?)";
PreparedStatement prepStat = null;
try {
prepStat = conn.prepareStatement(sqlStatement);
prepStat.setInt(1, g.getGameId());
prepStat.setInt(2, g.getPlayer1());
prepStat.setInt(3, g.getPlayer2());
prepStat.setInt(4, g.getPlayer1Hand());
prepStat.setInt(5, g.getPlayer2Hand());
prepStat.setInt(6, g.getPlayer1Bench());
prepStat.setInt(7, g.getPlayer2Bench());
result = prepStat.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
<file_sep>/SOEN387/src/ts/GameTS.java
package ts;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import technical_service.CardRDG;
import technical_service.ChallengeRDG;
import technical_service.DeckRDG;
import technical_service.GameRDG;
import technical_service.HandRDG;
import technical_service.UserRDG;
public class GameTS {
private synchronized static int getUniqueId(){
int uid = GameRDG.getMaxId()+1;
return uid ;
}
public int getGameId() {
return gameId;
}
public int getPlayer1() {
return player1;
}
public int getPlayer2() {
return player2;
}
public void setGameId(int gameId) {
this.gameId = getUniqueId();
}
public void setPlayer1(int player1) {
this.player1 = player1;
}
public void setPlayer2(int player2) {
this.player2 = player2;
}
public GameTS(int gameId, int player1, int player2) {
super();
this.gameId = gameId;
this.player1 = player1;
this.player2 = player2;
}
public GameTS(int player1, int player2) {
super();
this.player1 = player1;
this.player2 = player2;
}
public int getPlayer1Hand() {
return player1Hand;
}
public int getPlayer2Hand() {
return player2Hand;
}
public int getPlayer1Bench() {
return player1Bench;
}
public int getPlayer2Bench() {
return player2Bench;
}
public void setPlayer1Hand(int player1Hand) {
this.player1Hand = player1Hand;
}
public void setPlayer2Hand(int player2Hand) {
this.player2Hand = player2Hand;
}
public void setPlayer1Bench(int player1Bench) {
this.player1Bench = player1Bench;
}
public void setPlayer2Bench(int player2Bench) {
this.player2Bench = player2Bench;
}
public GameTS(int player1, int player2, int player1Hand,
int player2Hand) {
super();
this.gameId = getUniqueId();
this.player1 = player1;
this.player2 = player2;
this.player1Hand = player1Hand;
this.player2Hand = player2Hand;
this.player1Bench = 0;
this.player2Bench = 0;
}
public GameTS(int player1, int player2, int player1Hand,
int player2Hand, int player1Bench, int player2Bench) {
super();
this.gameId = getUniqueId();
this.player1 = player1;
this.player2 = player2;
this.player1Hand = player1Hand;
this.player2Hand = player2Hand;
this.player1Bench = player1Bench;
this.player2Bench = player2Bench;
}
public GameTS(int gameId, int player1, int player2, int player1Hand,
int player2Hand, int player1Bench, int player2Bench) {
super();
this.gameId = gameId;
this.player1 = player1;
this.player2 = player2;
this.player1Hand = player1Hand;
this.player2Hand = player2Hand;
this.player1Bench = player1Bench;
this.player2Bench = player2Bench;
}
private int gameId;
private int player1;
private int player2;
private int player1Hand;
private int player2Hand;
private int player1Bench;
private int player2Bench;
public synchronized static void initGame(String challengeId) {
ChallengeRDG c =ChallengeRDG.find(Integer.parseInt(challengeId));
int player1 = c.getChallenger();
int player2 = c.getChallengee();
int hI1= HandTS.newHand();
int hI2=HandTS.newHand();
GameTS g=new GameTS(player1,player2,hI1,hI2);
GameRDG.insert(g);
UserTS.statusPlay(player1);
UserTS.statusPlay(player2);
UserTS.assignToGame(player1, g.getGameId());
UserTS.assignToGame(player2, g.getGameId());
UserTS.assignHand(player1,hI1);
UserTS.assignHand(player2,hI2);
}
public static Map<Integer,Integer[]> listGames()
{
Map<Integer,Integer[]> map = new HashMap<Integer,Integer[]>();
List<GameRDG> rdgl= GameRDG.findAll();
for(GameRDG val:rdgl)
{
Integer[] temp = new Integer[2];
int key=val.getGameId();
temp[0]=val.getPlayer1();
temp[1]=val.getPlayer2();
map.put(key,temp);
}
return map;
}
public static int drawCard(int uId, String gId) {
int nextCardId = DeckTS.nextCardInTheDeck(gId);
if(nextCardId>0){
UserRDG u = UserRDG.find(uId);
CardTS.putInHand(nextCardId, u.getHandId());
HandTS.addCard(u.getHandId());
return nextCardId;
}
else{
return nextCardId;
}
}
}
<file_sep>/SOEN387/src/ts/UserTS.java
package ts;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import model.User;
import technical_service.UserRDG;
public class UserTS {
/* 0 - userId
* 1 - userName
* 2 - password
* 3 - currentDeck
* 4 - gameStatus
* 5 - gameId
* 6 - handId *
* */
private final static String[]FIELD_NAME={"userId","userName","password","currentDeck","gameStatus","gameId","handId"};
private int userId = 0;
private String userName;
private String password;
private int currentDeck;
public int getUserId() {
return userId;
}
public String getUserName() {
return userName;
}
public String getPassword() {
return password;
}
public int getCurrentDeck() {
return currentDeck;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setCurrentDeck(int currentDeck) {
this.currentDeck = currentDeck;
}
public UserTS(String userName,String password){
this.userId=getUniqueId();
this.password=<PASSWORD>;
this.userName=userName;
}
public static void assignDeck(int uId, int deckId){
if(UserRDG.update(uId, FIELD_NAME[3], deckId)>0){
System.out.println("Current updated ");
}else{
System.out.println("Something went wrong. ");
}
}
public static int verify(String user,String pass)
{
UserRDG u = UserRDG.find(user, pass);
if(u!=null){
return u.getUserId();
}else{
return -1;
}
}
public static boolean exist(String challengee)
{
int ichall=Integer.parseInt(challengee);
List<UserRDG> list = UserRDG.findAll();
for(UserRDG val : list){
if(val.getUserId()==ichall){
return true;
}
}
return false;
}
public static boolean contains(String userName)
{
List<UserRDG> list = UserRDG.findAll();
for(UserRDG val : list){
if(val.getUserName().equals(userName)){
return true;
}
}
return false;
}
public synchronized static UserTS register(String u, String pass){
UserTS umod = new UserTS(u, pass);
UserRDG.insert(umod);
return umod;
}
public synchronized static Map<Integer, String> getMap(){
List<UserRDG> u=UserRDG.findAll();
Map<Integer, String> m = new HashMap<Integer, String>();
for(UserRDG val:u){
m.put(val.getUserId(),val.getUserName() );
}
return m;
}
private synchronized static int getUniqueId(){
int uid = UserRDG.getMaxId()+1;
return uid ;
}
public static int hasDeck(int chalanger) {
return UserRDG.find(chalanger).getCurrentDeck();
}
public static void assignToGame(int player, int gameId) {
UserRDG.update(player, FIELD_NAME[5], gameId);
}
public static void assignHand(int player, int handId) {
UserRDG.update(player, FIELD_NAME[6], handId);
}
public static boolean checkGame(int uId, String gId)
{
int temp = Integer.parseInt(gId);
if(temp == UserRDG.find(uId).getGameId())
return true;
else
return false;
}
public static void statusPlay(int user) {
UserRDG.update(user, FIELD_NAME[4], "Playing");
}
public static boolean retire(int uid, String gameId) {
UserRDG u = UserRDG.find(uid);
if(u.getGameStatus().equals("Retire")){
return false;
}
else{
UserRDG.update(uid, FIELD_NAME[4], "Retire");
return true;
}
}
}
|
304d0883c1d918cc172f66f86934761fd2e78599
|
[
"Markdown",
"Java"
] | 10
|
Java
|
Igor3Volf/SOEN387
|
7ab34340a8d09537a2fdc2ff6b8c2d329d66ae71
|
574d5157e77f16a3975233c0b520a258a9549187
|
refs/heads/master
|
<file_sep>using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Linq;
using AngleSharp.Html.Dom;
using AngleSharp.Html.Parser;
public static class Api
{
public static List<Article> ScrapeTls()
{
var html = GetTLSHtml();
return GetItems(html);
}
private static string GetTLSHtml()
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("user-agent", "amazon is trash");
var url = $"https://www.thelakewoodscoop.com";
var html = client.GetStringAsync(url).Result;
return html;
}
}
private static List<Article> GetItems(string html)
{
var parser = new HtmlParser();
IHtmlDocument document = parser.ParseDocument(html);
var itemDivs = document.QuerySelectorAll(".post");
List<Article> items = new List<Article>();
foreach (var div in itemDivs)
{
Article news = new Article();
var href = div.QuerySelectorAll("h2 a").First();
news.Title = href.TextContent.Trim();
news.Url = href.Attributes["href"].Value;
var image = div.QuerySelector("img");
news.ImageUrl = image.Attributes["src"].Value;
var date = div.QuerySelector("small");
if (date!=null && date.TextContent.Trim() != "")
{
news.Date = DateTime.Parse(date.TextContent.Trim());
}
items.Add(news);
}
return items;
}
}
|
ddc8a2afad724c674278be67faf7a410f095b6a3
|
[
"C#"
] | 1
|
C#
|
SueWeiss/TLSScraper
|
c8cbf38ba368cbfbd6bac22581ff1f51b26ed46e
|
d6638d155365b945a9fcc30a7472eeb460b38bd1
|
refs/heads/master
|
<repo_name>eshta/fixtures-bundle<file_sep>/Tests/Executor/ExecutorTest.php
<?php
namespace Eshta\FixturesBundle\Tests\Executor;
use Eshta\FixturesBundle\Executor\ORMExecutor;
use Eshta\FixturesBundle\Repository\DBALFixtureRepository;
use Eshta\FixturesBundle\Tests\BaseTest;
use Eshta\FixturesBundle\Tests\TestFixture\Fixture1;
/**
* Class ExecutorTest
* @package Eshta\FixturesBundle\Tests\Executor
* @author <NAME> <<EMAIL>>
*/
class ExecutorTest extends BaseTest
{
/**
* @test
*/
public function execute()
{
$objectManager = $this->getMockSqliteEntityManager();
$repository = new DBALFixtureRepository($objectManager->getConnection());
$executor = new ORMExecutor($objectManager, $repository);
$fixtures = [
new Fixture1()
];
$executor->execute($fixtures);
$this->assertTrue($repository->exists($fixtures[0]));
}
/**
* @test
*/
public function executeSkipPreviouslyLoadedFixture()
{
$objectManager = $this->getMockSqliteEntityManager();
$repository = new DBALFixtureRepository($objectManager->getConnection());
$executor = new ORMExecutor($objectManager, $repository);
$fixture = $this->getMockBuilder(Fixture1::class)
->setMethods(['load'])
->getMock();
$fixture
->expects($this->once())
->method('load')
;
$fixtures = [
$fixture
];
$executor->execute($fixtures);
$this->assertTrue($repository->exists(current($fixtures)));
$executor->execute($fixtures);
}
}
<file_sep>/Tests/TestFixture/OrderedFixture.php
<?php
namespace Eshta\FixturesBundle\Tests\TestFixture;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
/**
* Class OrderedFixture
* @package Eshta\FixturesBundle\Tests\TestFixture
* @author <NAME> <<EMAIL>>
*/
class OrderedFixture implements FixtureInterface, OrderedFixtureInterface
{
/**
* @param ObjectManager $manager
*/
public function load(ObjectManager $manager)
{
}
/**
* @return int
*/
public function getOrder()
{
return 1;
}
}
<file_sep>/Repository/DBALFixtureRepository.php
<?php
namespace Eshta\FixturesBundle\Repository;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Exception\TableNotFoundException;
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Types\Type;
/**
* Class DBALFixtureRepository
* @package Eshta\Repository
* @author <NAME> <<EMAIL>>
*/
class DBALFixtureRepository implements FixtureRepositoryInterface
{
/**
* @var Connection
*/
private $connection;
/**
* @var string
*/
private $tableName = 'fixtures_log';
/**
* DBALFixtureRepository constructor.
* @param Connection $connection
*/
public function __construct(Connection $connection)
{
$this->connection = $connection;
$this->initialize();
}
/**
* Checks if the fixtures table exists
*
* @return boolean
*/
public function initialized()
{
try {
$this->connection->fetchAll(
"
SELECT * FROM {$this->tableName};
LIMIT 1;
"
);
return true;
} catch (TableNotFoundException $e) {
return false;
}
}
/**
* @todo revisit
* Create table if it does not exist
*
* @return void
*/
private function initialize()
{
$schemaManager = $this->connection->getSchemaManager();
if (!$this->initialized()) {
$columns = array(
'id' => new Column('id', Type::getType('integer'), array(
'length' => 10,
'notnull' => true,
)),
'name' => new Column('name', Type::getType('string'), array(
'length' => 500
)),
'load_order' => new Column('load_order', Type::getType('integer'), array(
'length' => 3,
'notnull' => false,
)),
'date_loaded' => new Column('date_loaded', Type::getType('datetime'))
);
$columns['id']->setAutoincrement(true);
$table = new Table($this->tableName, $columns);
$table->setPrimaryKey(array('id'));
$schemaManager->createTable($table);
}
}
/**
* @param FixtureInterface $fixture
* @return bool
* @throws \Doctrine\DBAL\DBALException
*/
public function exists(FixtureInterface $fixture)
{
$key = get_class($fixture);
$sql = "
SELECT count(id) AS found
FROM {$this->tableName}
WHERE name=?
";
$statement = $this->connection->prepare($sql);
$statement->bindValue(1, (string)$key);
$statement->execute();
$row = $statement->fetchAll();
return isset($row[0]['found']) ? $row[0]['found'] > 0 : false;
}
/**
* @param FixtureInterface $fixture
* @return void
* @throws \Doctrine\DBAL\DBALException
*/
public function add(FixtureInterface $fixture)
{
if ($this->exists($fixture)) {
return;
}
$order = null;
if ($fixture instanceof OrderedFixtureInterface) {
$order = $fixture->getOrder();
}
$fixtureReflection = new \ReflectionClass($fixture);
$className = $fixtureReflection->getName();
$sql = "INSERT INTO {$this->tableName} (`name`, `load_order`, `date_loaded`)" .
"VALUES (?, ?, ?)";
$this->connection->executeQuery(
$sql,
[$className, $order, \date('Y-m-d H:i:s')]
);
}
}
<file_sep>/Repository/FixtureRepositoryInterface.php
<?php
namespace Eshta\FixturesBundle\Repository;
use Doctrine\Common\DataFixtures\FixtureInterface;
/**
* Interface FixtureRepositoryInterface
* @package Eshta\Repository
* @author <NAME> <<EMAIL>>
*/
interface FixtureRepositoryInterface
{
/**
* @param FixtureInterface $fixture
* @return bool
*/
public function exists(FixtureInterface $fixture);
/**
* @param FixtureInterface $fixtureInterface
* @return mixed
*/
public function add(FixtureInterface $fixtureInterface);
/**
* Checks if the fixtures table exists
*
* @return boolean
*/
public function initialized();
}
<file_sep>/Executor/ORMExecutor.php
<?php
namespace Eshta\FixturesBundle\Executor;
use Doctrine\Common\DataFixtures\Executor\AbstractExecutor;
use Doctrine\Common\Persistence\ObjectManager;
use Eshta\FixturesBundle\Repository\FixtureRepositoryInterface;
use Doctrine\Common\DataFixtures\Executor\ORMExecutor as DoctrineORMExecutor;
/**
* Class ORMExecutor
* @package Eshta\FixturesBundle\Executor
* @author <NAME> <<EMAIL>>
*/
class ORMExecutor
{
/**
* @var FixtureRepositoryInterface
*/
protected $fixtureRepository;
/**
* @var ObjectManager
*/
protected $objectManager;
/**
* @var DoctrineORMExecutor
*/
protected $ormExecutor;
/**
* ORMExecutorDecorator constructor.
* @param ObjectManager $objectManager
* @param FixtureRepositoryInterface $fixtureRepository
*/
public function __construct(ObjectManager $objectManager, FixtureRepositoryInterface $fixtureRepository)
{
$this->fixtureRepository = $fixtureRepository;
$this->objectManager = $objectManager;
$this->ormExecutor = new DoctrineORMExecutor($objectManager);
}
/**
* @param array $fixtures
* @return void
*/
public function execute(array $fixtures)
{
foreach ($fixtures as $fixture) {
if ($this->fixtureRepository->exists($fixture)) {
continue;
}
$this->ormExecutor->load($this->objectManager, $fixture);
$this->fixtureRepository->add($fixture);
}
}
/**
* @param callable $logger
*/
public function setLogger($logger)
{
return $this->ormExecutor->setLogger($logger);
}
}
<file_sep>/Command/LoadDataFixturesDoctrineCommand.php
<?php
namespace Eshta\FixturesBundle\Command;
use Eshta\FixturesBundle\DirectoryResolver\BundleResolver;
use Eshta\FixturesBundle\Executor\ORMExecutor;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Doctrine\Bundle\DoctrineBundle\Command\DoctrineCommand;
use Eshta\FixturesBundle\Loader\FixtureLoader;
use Eshta\FixturesBundle\Repository\DBALFixtureRepository;
use InvalidArgumentException;
/**
* Load persistent data fixtures from bundles.
* @package Eshta\FixturesBundle\Command
* @author <NAME> <<EMAIL>>
*/
class LoadDataFixturesDoctrineCommand extends DoctrineCommand
{
/**
* @var FixtureLoader
*/
protected $loader;
/**
* @return void
*/
protected function configure()
{
$this
->setName('eshta:fixtures:load')
->setDescription('Load data fixtures to your database.')
->addArgument('file', InputArgument::OPTIONAL, 'Used to load single file')
->addOption(
'fixtures',
null,
InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY,
'The directory or file to load data fixtures from.'
)
->addOption(
'em',
null,
InputOption::VALUE_REQUIRED,
'The entity manager to use for this command.'
)
->addOption(
'force',
null,
InputOption::VALUE_NONE,
'Used in conjunction with file to force load a fixture'
)
->setHelp(
<<<EOT
<fg=blue;options=bold>Eshta Fixtures Bundle</fg=blue;options=bold>
The <info>eshta:fixtures:load</info> command loads outstanding data fixtures from your bundles:
<info>./app/console eshta:fixtures:load</info>
You can also optionally specify the path to fixtures with the <info>--fixtures</info> option:
<info>./app/console eshta:fixtures:load --fixtures=/path/to/fixtures1 --fixtures=/path/to/fixtures2</info>
EOT
);
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
/* @var $doctrine \Doctrine\Common\Persistence\ManagerRegistry */
$doctrine = $this->getContainer()->get('doctrine');
$entityManager = $doctrine->getManager($input->getOption('em'));
$repository = new DBALFixtureRepository($entityManager->getConnection());
$this->loader = new FixtureLoader($repository);
$file = $input->getArgument('file');
$forceLoad = $input->getOption('force');
if ($file) {
$this->loader->loadFile($file, $forceLoad);
} else {
$this->loadFromFixturesOption($input->getOption('fixtures'));
}
$fixtures = $this->loader->getFixtures();
if (!$fixtures) {
if ($file) {
throw new InvalidArgumentException(
'Fixture file is already loaded use --force to force load the fixture'
);
} else {
$output->writeln("\n<info>The database is up to date, no outstanding fixtures to load</info>\n", 'info');
return;
}
}
$executor = new ORMExecutor($entityManager, $repository);
$executor->setLogger(function ($message) use ($output) {
$output->writeln(sprintf(' <comment>></comment> <info>%s</info>', $message));
});
$executor->execute($fixtures);
}
/**
* Process directory, and if its not defined, get bundles directory paths
*
* @param $directory
* @return void
*/
protected function loadFromFixturesOption($directory)
{
if ($directory) {
$paths = is_array($directory) ? $directory : [$directory];
} else {
$paths = (new BundleResolver($this->getApplication()->getKernel()))->getPaths();
}
foreach ($paths as $path) {
if (is_dir($path)) {
$this->loader->loadFromDirectory($path);
}
}
}
}
<file_sep>/Tests/Loader/LoaderTest.php
<?php
namespace Eshta\FixturesBundle\Tests\Loader;
use Eshta\FixturesBundle\Loader\FixtureLoader;
use Eshta\FixturesBundle\Repository\DBALFixtureRepository;
use Eshta\FixturesBundle\Tests\BaseTest;
use Eshta\FixturesBundle\Tests\TestFixture\Fixture1;
/**
* Class LoaderTest
* @package Eshta\FixturesBundle\Tests\Loader
* @author <NAME> <<EMAIL>>
*/
class LoaderTest extends BaseTest
{
/**
* @var FixtureLoader
*/
private $loader;
const FIXTURES_DIR = __DIR__ . '/../TestFixture/';
const FIXTURE_FILE = self::FIXTURES_DIR . '/Fixture1.php';
public function setUp()
{
$connection = $this->getMockSqliteEntityManager()->getConnection();
$dbalRepository = new DBALFixtureRepository($connection);
$this->loader = new FixtureLoader($dbalRepository);
}
/**
* @return \PHPUnit_Framework_MockObject_MockObject
*/
private function getRepositoryMock()
{
return $this->getMockBuilder(DBALFixtureRepository::class)
->disableOriginalConstructor()
->setMethods(['exists'])
->getMock();
}
/**
* @return FixtureLoader
*/
private function getLoaderWithFixtureAlreadyLoaded()
{
$dbalRepository = $this->getRepositoryMock();
$dbalRepository->method('exists')->willReturn(true);
return new FixtureLoader($dbalRepository);
}
/**
* @test
*/
public function loadFile()
{
$this->loader->loadFile(self::FIXTURE_FILE);
$this->assertInstanceOf(Fixture1::class, current($this->loader->getFixtures()));
}
/**
* @test
*/
public function loadFileDoesNotLoadALoadedFixture()
{
$loader = $this->getLoaderWithFixtureAlreadyLoaded();
$loader->loadFile(self::FIXTURE_FILE, false);
$this->assertCount(0, $loader->getFixtures());
}
/**
* @test
*/
public function loadFileForceLoad()
{
$loader = $this->getLoaderWithFixtureAlreadyLoaded();
$loader->loadFile(self::FIXTURE_FILE, true);
$this->assertCount(1, $loader->getFixtures());
}
/**
* @test
* @expectedException \InvalidArgumentException
*/
public function loadNonExistingFile()
{
$this->loader->loadFile('Fixture1.php');
}
/**
* @test
* @expectedException \InvalidArgumentException
*/
public function loadFromNonExistingDirectory()
{
$this->loader->loadFromDirectory('/tmp/'.mt_rand(1, 514).time());
}
/**
* @test
*/
public function loadFromDirectory()
{
$this->loader->loadFromDirectory(self::FIXTURES_DIR);
$this->assertCount(2, $this->loader->getFixtures());
}
/**
* @test
*/
public function loadFromDirectorySkipLoadedFixtures()
{
$loader = $this->getLoaderWithFixtureAlreadyLoaded();
$loader->loadFromDirectory(self::FIXTURES_DIR);
$this->assertCount(0, $loader->getFixtures());
}
}
<file_sep>/EshtaFixturesBundle.php
<?php
namespace Eshta\FixturesBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/**
* Class EshtaFixturesBundle
* @package Eshta\FixturesBundle
* @author <NAME> <<EMAIL>>
*/
class EshtaFixturesBundle extends Bundle
{
}<file_sep>/Loader/FixtureLoader.php
<?php
namespace Eshta\FixturesBundle\Loader;
use Doctrine\Common\DataFixtures\Loader;
use Eshta\FixturesBundle\Repository\FixtureRepositoryInterface;
/**
* Class FixtureLoader
* @package Eshta\FixturesBundle\Loader
* @author <NAME> <<EMAIL>>
*/
class FixtureLoader
{
/**
* The file extension of fixture files.
*
* @var string
*/
protected $fileExtension = '.php';
/**
* @var FixtureRepositoryInterface
*/
protected $repository;
/**
* @var Loader
*/
protected $loader;
/**
* FixtureLoader constructor.
* @param FixtureRepositoryInterface $repository
*/
public function __construct(FixtureRepositoryInterface $repository) {
$this->loader = new Loader();
$this->repository = $repository;
}
/**
* Find fixtures classes in a given directory and load them.
*
* Include the file, instantiate each fixture and add it to
* fixtures array
*
* @param string $directory Directory to find fixture classes in.
* @return array $fixtures Array of loaded fixture object instances
*/
public function loadFromDirectory($directory)
{
if (!is_dir($directory)) {
throw new \InvalidArgumentException(sprintf('"%s" is not a valid directory', $directory));
}
$fixtures = [];
$includedFiles = $this->getIncludedFiles($directory);
$declared = get_declared_classes();
foreach ($declared as $className) {
$reflectionClass = new \ReflectionClass($className);
$sourceFile = $reflectionClass->getFileName();
if (in_array($sourceFile, $includedFiles) && ! $this->loader->isTransient($className)) {
$fixture = new $className;
if ($this->repository->exists($fixture)) {
continue;
}
$fixtures[] = $fixture;
$this->loader->addFixture($fixture);
}
}
return $fixtures;
}
/**
* @param string $fileName
* @param bool $force
* @return array
*/
public function loadFile($fileName, $force = false)
{
if (!file_exists($fileName)) {
throw new \InvalidArgumentException(sprintf('File %s does not exist', $fileName));
}
$fixtures = [];
$file = new \SplFileInfo($fileName);
$sourceFile = realpath($file->getPathName());
require_once $sourceFile;
$declared = get_declared_classes();
foreach ($declared as $className) {
$reflectionClass = new \ReflectionClass($className);
$classSourceFile = $reflectionClass->getFileName();
if ($classSourceFile == $sourceFile && ! $this->loader->isTransient($className)) {
$fixture = new $className;
if ($this->repository->exists($fixture) && $force == false) {
continue;
}
$fixtures[] = $fixture;
$this->loader->addFixture($fixture);
}
}
return $fixtures;
}
/**
* @return array
*/
public function getFixtures()
{
return $this->loader->getFixtures();
}
/**
* @param string $directory
* @return array
*/
protected function getIncludedFiles($directory)
{
$includedFiles = [];
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($directory),
\RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($iterator as $file) {
if ($file->getBasename($this->fileExtension) == $file->getBasename()) {
continue; // skip directory curser
}
$sourceFile = realpath($file->getPathName());
require_once $sourceFile;
$includedFiles[] = $sourceFile;
}
return $includedFiles;
}
}
<file_sep>/README.md
EshtaFixturesBundle
===================
[](https://travis-ci.org/eshta/fixtures-bundle)
Based on doctrine fixtures, similar to doctrine data fixtures bundle, but it persists fixtures instead, so it detects if a certain fixture is loaded it will not load it like doctrine migrations, best used as a place for seeded data.
Setup
-----
### Installation
```bash
composer require eshta/fixtures-bundle
```
```php
// app/AppKernel.php
// ...
class AppKernel extends Kernel
{
public function registerBundles()
{
// ...
$bundles[] = new Eshta\FixturesBundle\EshtaFixturesBundle();
return $bundles
}
// ...
}
```
### Configuration
Exclude the fixtures log table from DBAL schema
```yml
doctrine:
dbal:
schema_filter: ~^(?!fixtures_log)~
```
Usage
-----
#### Help:
```bash
app/console eshta:fixtures:load -h
```
#### Load:
```bash
app/console eshta:fixtures:load
```
It will load any outstanding fixtures only, it also supports ordering as with the normal fixtures bundle
#### Load file:
```bash
app/console eshta:fixtures:load [--force] <file>
```
Documentation
-------------
checkout [doctrine fixtures bundle](http://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html) except for setup, the documentation is the same.
<file_sep>/DirectoryResolver/BundleResolver.php
<?php
namespace Eshta\FixturesBundle\DirectoryResolver;
use Symfony\Component\HttpKernel\KernelInterface;
/**
* Class BundleResolver
* @package Eshta\DirectoryResolver
* @author <NAME> <<EMAIL>>
*/
class BundleResolver
{
/**
* @var string
*/
private $subDirectory = '/DataFixtures/ORM/';
/**
* @var KernelInterface
*/
private $kernel;
/**
* BundleResolver constructor.
* @param KernelInterface $kernel
* @param null|string $subDirectory
*/
public function __construct(KernelInterface $kernel, $subDirectory = null)
{
$this->kernel = $kernel;
if ($subDirectory) {
$this->subDirectory = $subDirectory;
}
}
/**
* @return array
*/
public function getPaths()
{
$paths = [];
foreach ($this->kernel->getBundles() as $bundle) {
$paths[] = $bundle->getPath() . $this->subDirectory;
}
return $paths;
}
}
<file_sep>/Tests/TestFixture/Fixture1.php
<?php
namespace Eshta\FixturesBundle\Tests\TestFixture;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
/**
* Class Fixture1
* @package Eshta\Tests\TestFixture
* @author <NAME> <<EMAIL>>
*/
class Fixture1 implements FixtureInterface
{
/**
* @param ObjectManager $manager
*/
public function load(ObjectManager $manager)
{
}
}
<file_sep>/Tests/Repository/DBALRepositoryTest.php
<?php
namespace Eshta\FixturesBundle\Tests\Repository;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\ORM\EntityManager;
use Eshta\FixturesBundle\Repository\DBALFixtureRepository;
use Eshta\FixturesBundle\Tests\BaseTest;
use Eshta\FixturesBundle\Tests\TestFixture\Fixture1;
use Eshta\FixturesBundle\Tests\TestFixture\OrderedFixture;
/**
* Class DBALRepositoryTest
* @package Eshta\FixturesBundle\Tests
* @author <NAME> <<EMAIL>>
*/
class DBALRepositoryTest extends BaseTest
{
/**
* @var EntityManager
*/
private $entityManager;
public function setUp()
{
$this->entityManager = $this->getMockSqliteEntityManager();
}
/**
* @test
*/
public function initialization()
{
$repository = new DBALFixtureRepository($this->entityManager->getConnection());
$this->assertTrue($repository->initialized());
}
/**
* @test
*/
public function add()
{
$repository = new DBALFixtureRepository($this->entityManager->getConnection());
$fixture = new Fixture1();
$repository->add($fixture); // load
$repository->add($fixture); // do nothing, since its already loaded
return $fixture;
}
/**
* @test
*/
public function addOrderedFixture()
{
$repository = new DBALFixtureRepository($this->entityManager->getConnection());
$fixture = new OrderedFixture();
$repository->add($fixture); // load
$this->assertTrue($repository->exists($fixture));
}
/**
* @test
*/
public function exists()
{
$fixture = new Fixture1();
$repository = new DBALFixtureRepository($this->entityManager->getConnection());
$this->assertFalse($repository->exists($fixture));
$repository->add($fixture);
$this->assertTrue($repository->exists($fixture));
}
}
<file_sep>/Tests/BaseTest.php
<?php
namespace Eshta\FixturesBundle\Tests;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\Setup;
use PHPUnit_Framework_TestCase;
/**
* Class BaseTest
* @package Eshta\FixturesBundle\Tests
* @author <NAME> <<EMAIL>>
*/
abstract class BaseTest extends PHPUnit_Framework_TestCase
{
/**
* EntityManager mock object together with
* annotation mapping driver and pdo_sqlite
* database in memory
*
* @return EntityManager
*/
protected function getMockSqliteEntityManager()
{
$dbParams = ['driver' => 'pdo_sqlite', 'memory' => true];
$config = Setup::createAnnotationMetadataConfiguration([], true);
return EntityManager::create($dbParams, $config);
}
}
|
a2df0bdf52917564ce16dc68aa5695abc37bff62
|
[
"Markdown",
"PHP"
] | 14
|
PHP
|
eshta/fixtures-bundle
|
80f9e5263d52c44ae29eced0319f359024b30b73
|
3881b7db71f001604f8e5b0a1a30f662b979a460
|
refs/heads/master
|
<file_sep>function popup() {
var name = $("#orderName").val();
if (name == "") {
alert("주문자 이름을 입력하세요.");
$("#orderName").focus();
return;
}
var count = $("#orderCount").val();
if (count == "--수량을 선택하세요--") {
alert("수량을 선택하세요.");
$("#orderCount").focus();
return;
}
var address = $("#orderAddress").val();
if (address == "") {
alert("주소를 입력하세요.");
$("#orderAddress").focus();
return;
}
var phonenumber = $("#phoneNum").val();
if (phonenumber == "") {
alert("전화번호를 입력하세요.");
$("#phoneNum").focus();
return;
}
function isCellPhone(p) {
var regExp = /^(01[016789]{1}|02|0[3-9]{1}[0-9]{1})[-][0-9]{3,4}[-][0-9]{4}$/;
return regExp.test(p);
}
if (!isCellPhone(phonenumber)) {
alert("휴대폰번호 입력형식이 틀립니다. 010-0000-0000으로 입력해주세요.");
$("#phoneNum").focus();
return;
}
alert("주문완료!");
}
|
3fdeb722506ffb7d3c3ca5ccbaca7dbc42f4fa5e
|
[
"JavaScript"
] | 1
|
JavaScript
|
junggghee/scodan7_junghee
|
4169ab658eb68f5ec0d1d3a255210a4f0d44bb68
|
b6aab295bcd9493ac2d9dd176d6b99811431f3c1
|
refs/heads/master
|
<repo_name>programmerGM/faculdade_hash_arquivos<file_sep>/include/pessoa.h
/*
* Criação: 09/12/2016
* Alteração 09/18/2016
* Author: <NAME>
* Author: <NAME>
*
* Descrição: Trabalho de Hash/Arquivos
*/
#ifndef PESSOA_H
#define PESSOA_H
#include <iostream>
using namespace std;
class pessoa {
public:
pessoa();
pessoa(int codigo, std::string nome, int idade);
virtual ~pessoa();
int get_codigo();
int get_idade();
void set_idade(int idade);
void set_codigo(int codigo);
std::string get_nome();
void set_nome(std::string nome);
void imprimir(int op);
private:
int codigo;
int idade;
std::string nome;
};
#endif /* PESSOA_H */
<file_sep>/include/hash.h
/*
* Criação: 09/12/2016
* Alteração 09/18/2016
* Author: <NAME>
* Author: <NAME>
*
* Descrição: Trabalho de Hash/Arquivos
*/
#ifndef HASH_H
#define HASH_H
#include <iostream>
#include <list>
#include <fstream>
#include <sstream>
#include "pessoa.h"
#define TAM 5
using namespace std;
class hash {
public:
hash();
hash(const hash& orig);
virtual ~hash();
void insere(pessoa p);
void remover(int cod);
void consulta(int cod);
void consultanome(string nome);
void imprimirhash();
void carregar_dados();
void salvar_dados();
void delete_db();
private:
list<pessoa> plist[TAM];
int calcular_hash(int codigo);
list<pessoa>::iterator it;
};
#endif /* HASH_H */
<file_sep>/README.md
## Trabalho universitário - Estruturas de dados II
<h6>4ª fase - 2016/2</h6>
Trabalho da matéria Estruturas de dados II para estudo de arquivos e Hash na linguagem C++.
* <h5>Tecnologias utilizadas e estudadas</h5>
- C++; <br />
- Hash; <br />
- Arquivos. <br />
<file_sep>/main.cpp
/*
* Criação: 09/12/2016
* Alteração 09/18/2016
* Author: <NAME>
* Author: <NAME>
*
* Descrição: Trabalho de Hash/Arquivos
*/
#include <locale>
#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include "hash.h"
#include "pessoa.h"
using namespace std;
void iniciar();
int menu();
void reiniciar(hash *tab_hash);
void insert_pessoa(hash *tab_hash);
void remover_pessoa(hash *tab_hash);
void consultar_codigo(hash *tab_hash);
void consultar_nome(hash *tab_hash);
void testar(hash *tab_hash);
/*
*
*/
int main(int argc, char** argv) {
setlocale(LC_ALL, "Portuguese");
iniciar();
return 0;
}
int menu()
{
int opcao;
cout << "###########################################" << endl;
cout << "# Menu #" << endl;
cout << "#=========================================#" << endl;
cout << "# [1] Reiniciar #" << endl;
cout << "# [2] Inserir #" << endl;
cout << "# [3] Remover #" << endl;
cout << "# [4] Consultar Especifico - pelo codigo #" << endl;
cout << "# [5] Consultar Especifico - pelo nome #" << endl;
cout << "# [6] - Listar #" << endl;
cout << "# [7] Testar #" << endl;
cout << "# [0] - Sair #" << endl;
cout << "###########################################" << endl << endl;
cin >> opcao;
return opcao;
}
// Função onde é executado todo o programa até o usuário sair.
void iniciar()
{
a:
int opcao = -1;
hash *tab_hash = new hash();
tab_hash->carregar_dados();
while (opcao != 0)
{
system("cls");
opcao = menu();
cout << endl;
switch(opcao)
{
case 0:
cout << "########### Programa encerrado ##########" << endl;
break;
case 1:
reiniciar(tab_hash);
goto a;
break;
case 2:
insert_pessoa(tab_hash);
break;
case 3:
remover_pessoa(tab_hash);
break;
case 4:
consultar_codigo(tab_hash);
break;
case 5:
consultar_nome(tab_hash);
break;
case 6:
tab_hash->imprimirhash();
break;
case 7:
testar(tab_hash);
break;
default:
cout << "#### Opcao invalida, tente novamente ####" << endl;
break;
}
if (opcao != 0)
{
getchar();
scanf("c\n");
}
} // FIM DO WHILE
tab_hash->salvar_dados();
} // FIM DO INICIAR
void reiniciar(hash *tab_hash)
{
tab_hash->delete_db();
delete tab_hash;
cout << "######### Cadastros reiniciado ##########" << endl;
}
void insert_pessoa(hash *tab_hash)
{
system("CLS");
int codigo, idade;
string nome;
cout << "######### [Inserir nova pessoa] #########" << endl;
cout << "###### Informe oo codigo da pessoa ######" << endl << "### [X> ";
cin >> codigo;
if(codigo == -1){
system("CLS");
cout << "Pressione qualquer tecla para continuar . . .";
return;
}
cout << "######## Informe o nome da pessoa #######" << endl << "##### [X> ";
cin >> nome;
cout << "####### Informe a idade da pessoa #######" << endl << "##2## [X> ";
cin >> idade;
if(codigo != 0 && idade > 0 && idade <= 130){
pessoa pes(codigo, nome, idade);
tab_hash->insere(pes);
cout << "Pessoa inserida com sucesso." << endl;
}else{
cout << "## Dados incorretos, codigo -1 para sair ##" << endl;
system("PAUSE");
insert_pessoa(tab_hash);
}
}
void remover_pessoa(hash *tab_hash)
{
int codigo;
cout << "########### [Remover pessoa] ############" << endl;
cout << "#### Informe o codigo a ser removido ####" << endl;
cout << "# [x> ";
cin >> codigo;
system("CLS");
tab_hash->remover(codigo);
}
void consultar_codigo(hash *tab_hash)
{
int codigo;
cout << "Informe o codigo que deseja consultar: ";
cin >> codigo;
system("CLS");
tab_hash->consulta(codigo);
}
void consultar_nome(hash* tab_hash)
{
string nome;
cout << "## Informe o nome que desenha consultar ##" << endl << "[X> ";
cin >> nome;
system("CLS");
tab_hash->consultanome(nome);
}
void testar(hash *tab_hash)
{
int codigo;
string nome;
int idade;
for (int i = 0; i < 3000 ; i++)
{
codigo = i;
string nome = "pessoa";
stringstream b;
b << i;
nome.append(b.str());
idade = rand () % 80 + 18;
pessoa pes(codigo, nome, idade);
tab_hash->insere(pes);
}
cout << "Testado." << endl;
}
<file_sep>/src/pessoa.cpp
/*
* Criação: 09/12/2016
* Alteração 09/18/2016
* Author: <NAME>
* Author: <NAME>
*
* Descrição: Trabalho de Hash/Arquivos
*/
#include "pessoa.h"
pessoa::pessoa()
{
}
pessoa::pessoa(int codigo, std::string nome, int idade)
{
this->codigo = codigo;
this->nome = nome;
this->idade = idade;
}
pessoa::~pessoa()
{
}
int pessoa::get_codigo()
{
return this->codigo;
}
void pessoa::set_codigo(int codigo)
{
this->codigo = codigo;
}
void pessoa::set_nome(std::string nome)
{
this->nome = nome;
}
std::string pessoa::get_nome()
{
return this->nome;
}
int pessoa::get_idade()
{
return this->idade;
}
void pessoa::set_idade(int idade)
{
this->idade = idade;
}
void pessoa::imprimir(int op)
{
switch(op)
{
case 1: // sem codigo
cout << "[> Nome: " << this->nome << endl << "[> Idade: " << idade << endl;
break;
case 2: // sem nome
cout << "[> Codigo: " << this->codigo << endl << "[> Idade: " << idade << endl;
break;
default: //completo
cout << "[> Codigo: " << this->codigo << endl << "[> Nome: " << this->nome << endl << "[> Idade: " << idade << endl;
}
}
<file_sep>/src/hash.cpp
/*
* Criação: 09/12/2016
* Alteração 09/18/2016
* Author: <NAME>
* Author: <NAME>
*
* Descrição: Trabalho de Hash/Arquivos
*/
#include "hash.h"
hash::hash() {}
hash::hash(const hash& orig) {
}
hash::~hash()
{
for (int i = 0; i < TAM ; i++)
{
for (it = plist[i].begin(); it != plist[i].end(); it++)
{
plist[i].erase(it);
it = plist[i].begin();
}
}
}
void hash::insere(pessoa p)
{
for (it = plist[calcular_hash(p.get_codigo())].begin(); it != plist[calcular_hash(p.get_codigo())].end(); it++)
{
if (it->get_codigo() == p.get_codigo())
{
cout << "##### Este código já está registrado #####" << endl;
return;
}
}
plist[calcular_hash(p.get_codigo())].push_back(p);
}
void hash::remover(int cod)
{
for (it = plist[calcular_hash(cod)].begin(); it != plist[calcular_hash(cod)].end(); it++)
{
if (it->get_codigo() == cod)
{
plist[calcular_hash(cod)].erase(it);
cout << "####### Pessoa removida com sucesso ######" << endl;
return;
}
}
cout << "######### Pessoa não encontrada ##########" << endl;
}
void hash::consulta(int cod)
{
for (it = plist[calcular_hash(cod)].begin(); it != plist[calcular_hash(cod)].end(); it++)
{
if (it->get_codigo() == cod)
{
cout << "###### Pessoa encontrada com sucesso #####" << endl;
it->imprimir(1);
cout << endl << "Pressione qualquer tecla para prosseguir ...";
return;
}
}
cout << "########## Pessoa nao encontrada #########" << endl;
}
void hash::consultanome(string nome)
{
for (int i = 0; i < TAM ; i++)
{
for (it = plist[i].begin(); it != plist[i].end(); it++)
{
if (it->get_nome() == nome)
{
cout << "###### Pessoa encontrada com sucesso #####" << endl;
it->imprimir(2);
cout << endl << "Pressione qualquer tecla para prosseguir ...";
return ;
}
}
}
cout << "########## Pessoa nao encontrada #########" << endl;
}
void hash::imprimirhash()
{
int counter = 0;
cout << "\e[H\e[2J"; // limpa tela
for (int i = 0; i < TAM ; i++)
{
it = plist[i].begin();
if (it == plist[i].end())
{
cout << ">> Hash [" << (i) << "] está vazio." << endl;
cout << "=========================" << endl;
}
else
{
cout << endl << ">> Hash [" << (i) << "]:" << endl << endl;
for (it = plist[i].begin(); it != plist[i].end(); it++)
{
if(counter == 10) // "paginação"
{
getchar();
scanf("c\n");
counter = 0;
cout << "\e[H\e[2J"; // limpa tela
}
cout << "[" << it->get_codigo() << "> " << endl;
it->imprimir(1);
counter += 1;
}
cout << endl << "=========================" << endl;
}
}
}
int hash::calcular_hash(int codigo)
{
return codigo % 5;
}
void hash::carregar_dados()
{
for (int i = 0; i < TAM ; i++)
{
ostringstream s;
s << i;
string i_as_string(s.str());
string str = "controle_arq_" + i_as_string + ".txt";
ifstream arq(str.c_str(), ios::in);
if (arq.fail())
{
cout << "##### Erro interno, comunique o admin ####" << endl;
}
else
{
int codigo;
int idade;
string nome;
while(!arq.eof())
{
arq >> codigo >> nome >> idade;
pessoa pes(codigo, nome, idade);
this->insere(pes);
}
}
arq.close();
}
}
void hash::salvar_dados()
{
for (int i = 0; i < TAM ; i++)
{
ostringstream s;
s << i;
string i_as_string(s.str());
string str = "controle_arq_" + i_as_string + ".txt";
if(!plist[i].empty())
{
ofstream arq(str.c_str(), ios::trunc);
it = plist[i].begin();
if (it != plist[i].end())
{
for (it = plist[i].begin(); it != plist[i].end(); it++)
{
arq << it->get_codigo() << "\t";
arq << it->get_nome() << "\t";
arq << it->get_idade() << endl;
}
}
arq.close();
}
}
}
void hash::delete_db()
{
for(int i = 0; i < TAM; i++)
{
std::ostringstream s;
s << i;
string i_as_string(s.str());
string str = "controle_arq_" + i_as_string + ".txt";
if(!plist[i].empty())
{
remove(str.c_str());
}
}
}
|
6a3005fc58d66cefa69b1652419ae6c59a3370c9
|
[
"Markdown",
"C++"
] | 6
|
C++
|
programmerGM/faculdade_hash_arquivos
|
7b2c6ef739d1beeb7d4b012a2e5a82a7f1212897
|
42fb76bb46f32a6b4b0cd864611a6188807a7320
|
refs/heads/master
|
<repo_name>dennismoha/Teamwork<file_sep>/controllers/gifs.js
/* eslint-disable no-undef */
const db = require('../dbConfig/db');
const multer = require('multer');
//creating a new gif
const storage = multer.diskStorage({
destination: function(req, file,cb) {
cb(null,'uploads/')
},
filename: function(req,file,cb) {
console.log(file)
cb(null, file.originalname)
}
})
const imgg = (req,res,next) => {
const upload = multer({storage}).single('image')
upload(req,res, (err)=> {
if(err) {
throw err
}
console.log('file uploaded to the server')
console.log(req.file)
//sending files to cloudinary
const cloudinary = require('cloudinary').v2
cloudinary.config({
cloud_name: 'moha254',
api_key: '934657442839282',
api_secret: '<KEY>'
})
const path = req.file.path
console.log(path);
const uniquefilename = new Date().toISOString()
cloudinary.uploader.upload(
path,
{public_id: `blog/${uniquefilename}`, tags: `blog`},
(err,image)=> {
if(err){
res.send(err)
console.log('error uploading to cloudinary')
}
db.query('insert into gifs (url) values($1)',[image.url])
console.log('gif image successfully')
}
)
})
next()
}
const deleteGif = (req,res,next) => {
const id = parseInt(req.params.id)
db.query('DELETE from gifs where id=$1',[id],(err,results)=> {
if(err) {
throw err
}
res.status(200).json({message:'gif successfully deleted'})
})
}
module.exports = {imgg,deleteGif}
<file_sep>/test/test.js
/* eslint-disable no-undef */
const articles = require('../routes/articles')
const chai = require('chai');
const chaiHttp = require('chai-http');
const {expect} = chai;
chai.use(chaiHttp);
describe('articles test route',()=> {
it('displays the whole articles',(done)=> {
chai
.request(articles)
.get('/')
.end((req,res) => {
expect(res).to.have.status(200);
expect(res.body.status).to.equals('succcess');
expect(res.body.message).to.equals('articles showed successfully')
done();
})
})
})<file_sep>/routes/articles.js
const express = require('express');
const router = express.Router();
const getArticles = require('../controllers/articles');
const auth = require('../middleware/auth')
router.post('/newarticle/',auth,getArticles.createArticles); //creates a new article
router.get('/',auth,getArticles.getarticles); //displays all the articles
router.get('/:id',auth,getArticles.articleIdById); //displays a specific article
router.put('/articleupdate/:id',auth,getArticles.articleUpdate); //updates a specific article
router.delete('/:id',auth,getArticles.deleteArticle); //deletes a specific article
router.get('/userArticle/:id',auth,getArticles.userArticles);
module.exports = router;
<file_sep>/controllers/gif_comments.js
const db = require('../dbConfig/db');
//adding a new gif comment
const addGifComments =(req,res) => {
const {comment} = req.body
db.query('insert into gif_comment (comment) values($1)',[comment],(err,results)=> {
if(err) {
throw err
}
res.status(201).send('successfully added a new gif comment')
})
}
//show all comments for a specific gif
// const gifCommentsdisplay = (req,res) => {
// const {gif_comment_id} = parseInt(req.params.id);
// db.query('select * from gif_comment where gif_comment_id = $1',[gif_comment_id],(err,results)=> {
// if(err) {
// throw err;
// }
// res.send(results.rows[0])
// console.log(results)
// })
// }
const gifCommentsdisplay =(req,res) => {
db.query('select comment from gif_comment',(err,results)=> {
if(err) {
throw err
}
res.send(results.rows[0])
console.log(results.rows)
})
}
module.exports = {addGifComments,gifCommentsdisplay}<file_sep>/app.js
/* eslint-disable no-undef */
// eslint-disable-next-line no-undef
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const db = require('./dbConfig/db');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json())
//const db = require('./dbConfig/db');
const Articles = require('./routes/articles')
const Comments = require('./routes/comments');
const gifroute = require('./routes/gif');
const users = require('./routes/users')
const gifComments = require('./routes/gif_comments');
app.use('/v1/users/auth',users);
app.use('/v1/users/articles',Articles);
app.use('/v1/users/comments',Comments);
app.use('/v1/users/gif',gifroute)
app.use('/v1/users/gif/gifComments',gifComments)
// eslint-disable-next-line no-undef
module.exports = app;<file_sep>/controllers/articles.js
const db = require('../dbConfig/db');
//displaying all the articles
const getarticles = function (req,res,next){
db.query('select * from articles ',function(err,results){
if(err) {
res.status(400).send(err)
console.log("there's an error in the get article route")
}
//res.status(200).json(results.rows);
res.send('articles showed successfully')
console.log('get articles working well');
});
}
//getting an article with a single id
const articleIdById = function(request,response,next){
const den = parseInt(request.params.id)
console.log(den)
db.query('select * from articles where id = $1',[den],(err,results)=>{
if(err) {
throw err;
}
response.status(200).json(results.rows)
console.log(results)
console.log('select Id article worked well');
})
}
//article post route
const createArticles = (req,res,next)=> {
const {content} = req.body;
db.query('insert into articles (content) values($1)',[content],(err,results)=>{
if(err) {
throw err
}
//res.status(201).send(`User added with ID: ${results.rows}`)
res.status(201).send(results.rows)
console.log('added new article');
})
}
//displaying all articles from a certain user
const userArticles = function(req,res,next){
const Id = parseInt(req.params.id);
db.query('select * from articles where article_id =$1',[Id],(err,results)=>{
if(err) {
throw err
}
res.status(201).json(results.rows);
})
}
//const deleteArticles;
const deleteArticle = (req,res,next)=> {
const id = parseInt(req.params.id);
db.query("DELETE FROM articles WHERE id = $1 ",[id],(err,results)=> {
if(err) {
throw err;
}
res.status(200).send('article successfully deleted')
})
}
//const updateArticles;
const articleUpdate = (req,res)=> {
const Id = parseInt(req.params.id);
const {article, content} = req.body;
console.log(req.body)
db.query('UPDATE articles SET article_id = $1,content = $2 where id= $3',[article,content,Id],function(err,results) {
if(err) {
throw err;
console.log(err)
}
res.status(200).send(`User modified with ID: ${Id}`);
})
}
module.exports = {getarticles,
articleIdById,
createArticles,
deleteArticle,
articleUpdate,
userArticles}
<file_sep>/dbConfig/db.js
const express = require('express');
const pg = require('pg');
const config = {
user: 'postgres',
database: 'teamwork',
password: '<PASSWORD>',
port : 5432
}
const pool = new pg.Pool(config);
module.exports = pool;<file_sep>/controllers/users.js
/* eslint-disable no-undef */
const db = require('../dbConfig/db');
const bcrypt = require('bcrypt')
const jwt = require ('jsonwebtoken');
const Signup = function (req,res){
bcrypt.hash(req.body.password, 10) .then(
(hash) => {
const email = req.body.email
const password = hash
db.query('insert into employees (email,password) values($1,$2)',[email,password])
.then(
() => {
res.status(201).json({
message: "new user added successfully"
})
}
).catch(
(error) => {
res.status(400).json({message:'that email address exist'})
throw error
}
)
}
)
}
const login = (req,res)=> {
const {email} = req.body;
//const {password} = bcrypt.hash(req.body.password)
db.query('select * from employees where email = $1',[email])
.then(
(user) => {
if(!user) {
return res.status(401).json({
error: new Error ("user not found")
});
}
const k = (user.rows[0].password)
bcrypt.compare(req.body.password,k).then(
(valid) => {
if(!valid) {
return res.status(401).json({
error : new Error("incorrect password")
});
}
const token = jwt.sign({userId:user._id},'RANDOM_TOKEN_SECRET',{expiresIn:'24h'})
res.status(200).json({
userId: user._id,
token: token
})
}
).catch(
(error) => {
res.status(400).send(error)
// throw error
}
)
})
.catch((error)=> {
console.log('error last catch')
throw error
})
}
module.exports = {Signup,login}
<file_sep>/README.md
# Teamwork
Teamwork system project by DEVCTRAINING with andela
Part of the Andela Dev C training project
<file_sep>/routes/comments.js
const express = require('express');
const router = express.Router();
const getComments = require('../controllers/comments');
const auth = require('../middleware/auth')
router.post('/',auth,getComments.createComment);
router.get('/',auth,getComments.commentsDisplay);
router.get('/comment/:id',auth,getComments.comentIdDisplay);
router.put('/:id',auth,getComments.updateComment);
router.get('/spec/:id',auth,getComments.personComment)//get a specific person's comments
module.exports = router;<file_sep>/controllers/comments.js
const db = require('../dbConfig/db');
//creating a new comment
const createComment = (req,res)=> {
const {text} = req.body;
console.log(text)
db.query('insert into comments (text) values($1)',[text],(err,results)=> {
if(err) {
throw err;
}
res.status(200).send(`comment added with ID: ${results.text}`)
})
}
const commentsDisplay= function (req,res){
db.query('select * from comments ',function(err,results){
if(err) {
throw err
}
res.status(200).json(results.rows)
});
}
//getting a specific comment by it's id
const comentIdDisplay = (req, res) => {
const Id = parseInt(req.params.id);
db.query('select * from comments where comment_id = $1',[Id],(err,results)=> {
if(err) {
throw err;
}
res.status(200).json(results.rows)
})
}
//updating a comment
const updateComment = (req,res)=> {
const comment_Id = parseInt(req.params.id);
const {text} = req.body;
db.query('UPDATE comments SET text = $1 where comment_id = $2',[text,comment_Id],(err,results)=> {
if(err) {
throw err
}
console.log(results)
// res.status(200).send(results)
res.status(200).json({message:'comment updated successfully!!'})
})
}
//getting a comments from a specific person
const personComment = (req, res) => {
const {owner_id} =parseInt(req.params.id)
db.query('select * from comments where owner_id =$1',[owner_id],(err,results)=> {
if(err) {
throw err
}
res.status(201).send(results.fields)
console.log(results)
})
}
module.exports = {createComment,commentsDisplay,comentIdDisplay,updateComment,personComment};
|
0037f6c735650c1f4745b0c217f783355994aa99
|
[
"JavaScript",
"Markdown"
] | 11
|
JavaScript
|
dennismoha/Teamwork
|
809fd60d8656b52d5855cacd7d275b0abe976fb6
|
aa9caa3d2d99a40eb0689c59af172c021be6c1b5
|
refs/heads/master
|
<file_sep>import java.util.ArrayList;
public class Lab_9 {
private static double finalfitness;
public static ScalesSolution RMHC(ArrayList<Double> weights, int n, int iter)
{
ScalesSolution oldsol = new ScalesSolution(n);
double oldfit, newfit = 0;
for (int i = 0; i <= iter; i++)
{
oldfit = oldsol.ScalesFitness(weights);
//System.out.println(oldsol.GetSol() + " .oldfit.. " + oldfit);
ScalesSolution newsol = new ScalesSolution(oldsol.GetSol());
newsol.SmallChange();
newfit = newsol.ScalesFitness(weights);
//System.out.println(newsol.GetSol() + " .newfit.. " + newfit);
if (newfit < oldfit)
{
oldsol = newsol;
finalfitness = newfit;
//System.out.println(" result newfit... " + newfit);
}
else
{
finalfitness = oldfit;
}
}
return (oldsol);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// ScalesSolution s = new ScalesSolution("00000");
// s.println();
// s.SmallChange();
// s.println();
//
// ScalesSolution s1 = new ScalesSolution(10);
// s1.println();
// ScalesSolution s2 = new ScalesSolution(s1.GetSol());
// s2.println();
ArrayList<Double> test = new ArrayList<Double>();
test.add((double) 1);
test.add((double) 2);
test.add((double) 3);
test.add((double) 4);
test.add((double) 10);
test.add((double) 198);
test.add((double) 223);
test.add((double) 34);
test.add((double) 4790);
test.add((double) 1033);
test.add((double) 10);
test.add((double) 20);
test.add((double) 30);
test.add((double) 40);
test.add((double) 100);
test.add((double) 1098);
test.add((double) 2023);
test.add((double) 304);
test.add((double) 40790);
test.add((double) 10033);
//System.out.println("Best Solution ... = " + RMHC(test, 20, 400).GetSol());
ArrayList<Double> h = CS2004.ReadNumberFile("1000 Primes.txt");
//System.out.println(h);
// for (int i = 0; i < 5; i++)
// {
// System.out.println(h.get(i));
// }
System.out.println("Best Solution ... = " + RMHC(h, 200, 100).GetSol());
System.out.println("Best fitness " + finalfitness);
}
}
<file_sep>
public class SA {
private static double c_rate = 0.5;
//0.35
public static double SA_H_Search(int iter, int n, double[][] distances)
{
double temp = 100000;
//double temp = 4500;
double min_temp = 0.00;
//double Lambda = Math.pow((0.001/temp),(1/(double)iter));
double currentFitness = 0;
TSP.CreateRandomTSP(n);
for (int i = 0; i < iter; i++)
{
while (temp > min_temp)
{
currentFitness = TSP.TSPFitnessFunc(n, TSP.tList, distances);
TSP.SwapSmallChangeTSP(n);
double newFitness = TSP.TSPFitnessFunc(n, TSP.tList, distances);
if (newFitness > currentFitness)
{
if (TSP.Probability(currentFitness, newFitness, temp))
{
TSP.UndoSwap();
}else
{
continue;
}
}else
{
currentFitness = newFitness;
}
temp *= c_rate;
}
}
return (currentFitness);
}
}
<file_sep>
public class Summation {
int res = 0;
public int LinearSum(int n)
{
for (int i = 0; i <= n; i++)
{
res = res + i;
}
return res;
}
public String Check(int x)
{
if (res == (x*(x+1))/2)
{
return "correct";
}
return null;
}
}
<file_sep>import java.util.ArrayList;
public class Lab6 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> random2 = ThreeSort.RandomArray(5);
ArrayList<Integer> random3 = ThreeSort.RandomArray(6);
ArrayList<Integer> random4 = ThreeSort.RandomArray(7);
// for (int i = 0; i < 10; i++){
// ArrayList<Integer> random = ThreeSort.RandomArray(35000);
// final long startTime = System.currentTimeMillis();
// ThreeSort.SortA(random);
// //ThreeSort.SortB(random);
// //ThreeSort.SortC(random);
// final long endTime = System.currentTimeMillis();
// System.out.print("Total Execution Time = " + (endTime - startTime));
// System.out.println();
// }
System.out.println("Sort Algorithm A");
ThreeSort.ShowArray(random2);
ThreeSort.ShowArray(ThreeSort.SortA(random2));
System.out.println();
System.out.println("------------------");
System.out.println("Sort Algorithm B");
ThreeSort.ShowArray(random3);
ThreeSort.ShowArray(ThreeSort.SortB(random3));
System.out.println();
System.out.println("------------------");
System.out.println("Sort Algorithm C");
ThreeSort.ShowArray(random4);
ThreeSort.ShowArray(ThreeSort.SortC(random4));
}
}
<file_sep>/**
* filename: ILoveCS2004.java
* Author: Dr <NAME> (or your name!)
* Date: Sept. 21, 2017 (or Todayís date!)
*/
public class ILoveCS2004
{
public static void main(String[] args)
{
System.out.println("I love CS2004!");
RootApproximator rm=new RootApproximator(25);
System.out.println(rm.getRoot());
}
}
<file_sep>import java.util.ArrayList;
public class Lab8 {
static ScalesSolution s = new ScalesSolution(5);
static int amount = 8;
static ScalesSolution s2 = new ScalesSolution(amount);
public static void main(String args[])
{
/* for(int i=0;i<10;++i)
{
int x = CS2004.UI(0, 1);
System.out.println(x);
}
ScalesSolution s = new ScalesSolution("10101");
s.println();
s = new ScalesSolution("10101x");
s.println();
s = new ScalesSolution(10);
s.println();*/
/*ArrayList<Double> weights = new ArrayList<>();
double n = 1, x = 2, p = 3, l = 4, f = 10;
weights.add(n);
weights.add(x);
weights.add(p);
weights.add(l);
weights.add(f);
System.out.println(weights);
s.println();
System.out.println(s.ScalesFitness(weights));
//--------------------
//Scales solution for specific amount of numbers from prime text file
ArrayList<Double> h = CS2004.ReadNumberFile("1000 Primes.txt");
ArrayList<Double> newReadNum = new ArrayList<>();
ArrayList<Double> newReadNum10 = new ArrayList<>();
ArrayList<Double> newReadNum100 = new ArrayList<>();
ArrayList<Double> newReadNum250 = new ArrayList<>();
ArrayList<Double> newReadNum500 = new ArrayList<>();
ArrayList<Double> newReadNum1000 = new ArrayList<>();
//making smaller arraylist
for (int i = 0; i < amount; i++)
{
newReadNum.add(h.get(i));
}
System.out.println(newReadNum);
s2.println();
System.out.println(s2.ScalesFitness(newReadNum));
*/
ArrayList<Double> h = CS2004.ReadNumberFile("1000 Primes.txt");
//10 weights
double average = 0;
double xs;
for (int i = 0; i < 100; i++)
{
ScalesSolution s10 = new ScalesSolution(10);
xs = s10.ScalesFitness(h);
//System.out.println(xs);
average = average + xs;
}
double newAverage = average / 100;
System.out.println(newAverage);
//100 weights
for (int i = 0; i < 100; i++)
{
ScalesSolution s100 = new ScalesSolution(100);
xs = s100.ScalesFitness(h);
//System.out.println(xs);
average = average + xs;
}
newAverage = average / 100;
System.out.println(newAverage);
//250 weights
for (int i = 0; i < 100; i++)
{
ScalesSolution s250 = new ScalesSolution(250);
xs = s250.ScalesFitness(h);
//System.out.println(xs);
average = average + xs;
}
newAverage = average / 100;
System.out.println(newAverage);
//500 weights
for (int i = 0; i < 100; i++)
{
ScalesSolution s500 = new ScalesSolution(500);
xs = s500.ScalesFitness(h);
//System.out.println(xs);
average = average + xs;
}
newAverage = average / 100;
System.out.println(newAverage);
//1000 weights
for (int i = 0; i < 100; i++)
{
ScalesSolution s1000 = new ScalesSolution(1000);
xs = s1000.ScalesFitness(h);
//System.out.println(xs);
average = average + xs;
}
newAverage = average / 100;
System.out.println(newAverage);
}
}<file_sep>import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
//import java.util.LinkedList;
import java.util.Stack;
import java.util.concurrent.ArrayBlockingQueue;
public class Lab5 {
public static void PrintCollection(Collection<Data> c)
{
for (Iterator<Data> iter = c.iterator(); iter.hasNext();)
{
Data x = (Data)iter.next();
x.Print();
}
System.out.println();
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
// TODO Auto-generated method stub
Data x = new Data("Fred",21);
Data y = new Data("Jo",43);
Data z = new Data("Zoe",37);
Data b = new Data("Harry",78);
ArrayList<Data> ArrayA = new ArrayList<Data>();
ArrayList<Data> ArrayB = new ArrayList<Data>();
ArrayA.add(x);
ArrayA.add(y);
ArrayA.add(b);
ArrayA.add(z);
PrintCollection(ArrayA);
ArrayB = ArrayA;
PrintCollection(ArrayB);
ArrayA.remove(1);
System.out.println("First Test");
System.out.println("Array B = ");
PrintCollection(ArrayB);
System.out.println("Array A = ");
PrintCollection(ArrayA);
//The code above just directs us to the data in one table. Doesn't clone it.
//Changing one array WILL change the other.
Data x2 = new Data("Janet",21);
Data y2 = new Data("Mario",43);
Data z2 = new Data("Nikky",37);
Data b2 = new Data("Ahmed",78);
ArrayList<Data> ArrayC = new ArrayList<Data>();
ArrayList<Data> ArrayD = new ArrayList<Data>();
ArrayC.add(x2);
ArrayC.add(y2);
ArrayC.add(b2);
ArrayC.add(z2);
System.out.println("-------------");
PrintCollection(ArrayC);
ArrayD = (ArrayList<Data>)ArrayC.clone();
ArrayC.remove(1);
PrintCollection(ArrayD);
System.out.println("Second Test");
System.out.println("Array C = ");
PrintCollection(ArrayC);
System.out.println("Array D = ");
PrintCollection(ArrayD);
System.out.println();
//The code above clones the array list in to the other array list. Changes in one
//list WILL NOT be shown in the other list.
//STACK
Stack<Data> stack = new Stack<Data>();
stack.push(x);
stack.push(y);
stack.push(z);
while (stack.isEmpty() == false)//while the stack is NOT empty
{
stack.pop().Print();//print all data being removed (pop = removes the top item)
}
System.out.println(stack.size());//when the stack is empty print the size of the empty stack
//QUEUES
ArrayBlockingQueue<Data> q = new ArrayBlockingQueue<Data>(10);
q.add(x);
q.add(y);
q.add(z);
System.out.println("Queues");
PrintCollection(q);
while(q.isEmpty() == false)//while the queue is NOT empty
{
q.poll().Print();//.poll() retrieves and removes the head of the queue
}
System.out.println(q.size());//when the queue is empty print the size of the empty stack
for(int i=0;i<20;++i)
{
q.offer(new Data("Test:"+String.valueOf(i),i));
}
PrintCollection(q);
//when changing the for loop to 20 and keeping the .add(), there is an error because the maximum size
//of the queue can only be 10, when 20 is entered is can't add anymore
//items to the queue
//.offer() will add values to the queue only if it can without violating any rules
}
}
<file_sep>import java.util.ArrayList;
public class Code_Runner_Test_Code {
public static double ArrayMax(ArrayList<Double> array){
if (array.isEmpty()==true)
{
return Double.MIN_VALUE;
}
else
{
double CurrentMax = array.get(0);
for (int i = 1; i < array.size(); i++)
{
if (array.get(i)>CurrentMax)
{
CurrentMax = array.get(i);
}
}
return(CurrentMax);
}
}
public static int LinearSummation(int n)
{
if (n < 1)
{
return 0;
}
else
{
int res = 0;
for (int i = 0; i <= n; i++)
{
res = res + i;
}
return res;
}
}
public static boolean IsEven(int a)
{
if ((a % 2) == 0)
{
return true;
}
else
{
return false;
}
}
public static String RevString(String input)
{
String result = "";
for (int i = (input.length() - 1); i > -1; i--)
{
result = result + input.charAt(i);
}
return result;
}
public static int Factorial(int x)
{
int res = 1;
if (x < 0)
{
x = -1;
return x;
}
else
{
for (int i = 1; i <= x; i++)
{
res = res * i;
}
return res;
}
}
public static int CharCounter(String a, char b)
{
int count = 0;
char g;
a = a.toLowerCase();
for (int i = 0; i < a.length(); i++)
{
g = a.charAt(i);
if (g == b)
{
count = count + 1;
};
}
return count;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//System.out.println(CharCounter(\"AAAAAaaaaa\", 'a'));
// ArrayList<Integer> input = new ArrayList<Integer>();
// input.add(5);
// input.add(2);
// input.add(3);
// input.add(4);
//
//
// ArrayList<Integer> x = createExpected(input);
//
// for (int i = 0; i < x.size(); i++)
// {
// System.out.print(x.get(i));
// }
//
// String text = \"/xyz.jpg\";
// System.out.println(text);
// text = text.replace(\"/\", \"\");
// System.out.println(text);
String test = "[[{movie_id}]]";
String newResult = test.substring(1, test.length()-1);
System.out.println(newResult);
}
public static ArrayList<Integer> createExpected(ArrayList<Integer> sizes)
{
ArrayList<Integer> output = new ArrayList<Integer>();
for (int i = 0; i < sizes.size(); i++)
{
for (int j = 0; j < sizes.get(i); j++)
{
output.add(sizes.get(i));
}
}
return output;
}
}
<file_sep>
public class CannonSolution
{
private double angle;
private double velocity;
// public double targetRange = 75000; //2% change
public double targetRange = 95000; //1% change
// public double targetRange = 65000; //3% change
public CannonSolution(double a,double v)
{
angle = a;
velocity = v;
}
public CannonSolution()
{
angle = RandomDouble(25, 55);
velocity = RandomDouble(1500, 1650);
}
public double CannonFitness()
{
double fitness = Cannon.GetMaxRange(angle, velocity);
return fitness;
}
public double CannonFitness2()
{
double range = Cannon.GetMaxRange(angle, velocity);
double fitness = Math.abs(range - targetRange);
return fitness;
}
public double RandomDouble(double lower, double upper)
{
double random = CS2004.UR(lower, upper);
return random;
}
public void SmallChange()
{
int p = CS2004.UI(0, 1);
if (p == 0)
{
float difference = 55 - 25;
float smallNum = (difference * 1) / 100.0f;
double addition = CS2004.UR(-smallNum, smallNum);
angle = angle + addition;
}
else if (p == 1)
{
float difference = 1650 - 1500;
float smallNum = (difference * 1) / 100.0f;
double addition = CS2004.UR(-smallNum, smallNum);
velocity = velocity + addition;
}
if (angle < 25)
{
angle = 25;
}else if (55 < angle)
{
angle = 55;
}else if (velocity < 1500)
{
velocity = 1500;
}else if (1650 < velocity)
{
velocity = 1650;
}
}
public double GetAngle()
{
return(angle);
}
public double GetVelocity()
{
return(velocity);
}
}
<file_sep>
public class Labsheet_4 {
//THIS IS TO PRINT OUT EACH VALUE OF THE ARRAY
private static void PrintArray(double[] X)
{
int n = X.length;
for (int i = 0; i < n; i++)
{
System.out.println(X[i]);
}
}
//THIS IS THE PREFIX AVERAGE 1 ALGORTIHM
public static double[] PrefixAverage1(double X[]){
int n = X.length;
double A[] = new double[n];
for (int i = 0; i < n; i++)
{
double s = X[0];
for (int j = 1; j < n; j++)
{
if (j <= i)
{
s = s + X[j];
}
}
A[i] = s / (i+1);
}
return A;
}
//THIS IS THE PREFIX AVERAGE 2 ALGORTIHM
public static double[] PrefixAverage2(double X[])
{
int n = X.length;
double A[] = new double [n];
double s = 0;
for (int i = 0; i < n; i++)
{
s = s + X[i];
A[i] = s / (i + 1);
}
return A;
}
public static void main(String args[])
{
double X[] = {7, 3, -1, 2, 9 ,0, 0.8, 52, 2.2, 900};
double Y[] = {1,2,3,4,5,6,7,8,10};
double A[] = PrefixAverage1(X);
double B[] = PrefixAverage2(Y);
System.out.println("Prefix Average Test 1");
System.out.println("Array Input");
PrintArray(X);
System.out.println("Average Output");
PrintArray(A);
System.out.println("Prefix Average Test 2");
System.out.println("Array Input");
PrintArray(Y);
System.out.println("Average Output");
PrintArray(B);
}
}
<file_sep>import java.util.ArrayList;
import java.util.Arrays;
public class Lab_15 {
public static int iter = 100000, runs = 25;
public static String data_48 = "TSP_Data/TSP_48.txt", opt_data_48 = "TSP_Data/TSP_48_OPT.txt",
data_51 = "TSP_Data/TSP_51.txt", opt_data_51 = "TSP_Data/TSP_51_OPT.txt",
data_52 = "TSP_Data/TSP_52.txt", opt_data_52 = "TSP_Data/TSP_52_OPT.txt",
data_70 = "TSP_Data/TSP_70.txt", opt_data_70 = "TSP_Data/TSP_70_OPT.txt",
data_76 = "TSP_Data/TSP_76.txt", opt_data_76 = "TSP_Data/TSP_76_OPT.txt",
data_100 = "TSP_Data/TSP_100.txt", opt_data_100 = "TSP_Data/TSP_100_OPT.txt",
data_105 = "TSP_Data/TSP_105.txt", opt_data_105 = "TSP_Data/TSP_105_OPT.txt",
data_136 = "TSP_Data/TSP_136.txt", data_150 = "TSP_Data/TSP_150.txt",
data_198 = "TSP_Data/TSP_198.txt", data_226 = "TSP_Data/TSP_226.txt",
data_264 = "TSP_Data/TSP_264.txt", data_318 = "TSP_Data/TSP_318.txt",
data_400 = "TSP_Data/TSP_400.txt", data_442 = "TSP_Data/TSP_442.txt",
opt_data_442 = "TSP_Data/TSP_442_OPT.txt", data_493 = "TSP_Data/TSP_493.txt",
data_574 = "TSP_Data/TSP_574.txt", none = "";
public static double AverageRMHCFitness(int n, double[][] distances)
{
double fitness = 0.0;
for (int i = 0; i < runs; i++)
{
fitness += RMHC.RMHC_H_Search(iter, n, distances);
}
fitness /= runs;
return (fitness);
}
public static double AverageRRHCFitness(int n, double[][] distances)
{
double fitness = 0.0;
for (int i = 0; i < runs; i++)
{
fitness += RRHC.RRHC_H_Search(n, distances);
}
fitness /= runs;
return (fitness);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
double [][] distances = TSP.ReadArrayFile(data_48, " ");
ArrayList<Integer> optimum_tour = TSP.GetOptimumTour(opt_data_48);
int n = distances.length;
double [][] y = MST.PrimsMST(distances);
double mst_fit = TSP.GetMSTFitness(y, n);
double opt_fit = TSP.TSPFitnessFunc(n, optimum_tour, distances);
//put in for loop to run 25 times(store as variable, then work out the average and spit that out
double rmhc_fitness = RMHC.RMHC_H_Search(iter, n, distances);
//double rmhc_fitness = AverageRMHCFitness(n, distances);
//methods in the main lab
//all shared variables can stay in TSP
//at least 1/3 needs to be comments
//What does each method do, inputs and outputs, state sophisticated loops etc... JUST EXPLAIN !!!
double rrhc_fitness = RRHC.RRHC_H_Search(n, distances);
//double rrhc_fitness = AverageRRHCFitness(n, distances);
double shc_fitness = SHC.SHC_H_Search(iter, n, distances);
double sa_fitness = SA.SA_H_Search(iter, n, distances);
//48 cities = 70% for RMHC, 80% for SHC, 82% for RRHC, 90% for SA.
//Optimum divided by my best fitness
//for MST each % should be round 10% less than optimum
//MST fitness divided by my best fitness
//MST fitness should ALWAS be less than the optimum
//RRHC uses RMHC --> CHECK LECTURE NOTES !!!!
//Temperature for the SHC and SA will be difficult, test on the 48 and tweak temperature until
//you get a better result than the heuristic search methods
System.out.println("RMHC fitness = " + rmhc_fitness);//my fitness
System.out.println("SHC fitness = " + shc_fitness);//my fitness
System.out.println("RRHC fitness = " + rrhc_fitness);//my fitness
System.out.println("SA fitness = " + sa_fitness);//my fitness
System.out.println("Optimum Fitness = " + opt_fit); //actual best fitness
System.out.println("MST Fitness = " + mst_fit); //estimation of the best fitness
}
}
<file_sep>import java.util.ArrayList;
public class Lab_14 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> genericArrangement = new ArrayList<Integer>();
int clusterID1 = 1, clusterID2 = 2, clusterID3 = 3;
for (int j = 0; j < 25; j++)
{
genericArrangement.add(clusterID1);
}
for (int j = 0; j < 50; j++)
{
genericArrangement.add(clusterID2);
}
for (int j = 0; j < 25; j++)
{
genericArrangement.add(clusterID3);
}
double[][] clusterLabArray = KMeans.ReadArrayFile("ClusterLab.txt", ",");
for (int i = 0; i < 10; i++)
{
KMeans kObject = new KMeans(clusterLabArray, 3, 100);
ArrayList<Integer> newArrangement = kObject.RunIter(3, 10, genericArrangement, false);
double kappaResult = KMeans.GroupingWK(genericArrangement, newArrangement);
System.out.println(kappaResult);
}
System.out.println("-------Second txt file------");
ArrayList<Integer> genericArrangement2 = new ArrayList<Integer>();
for (int j = 0; j < 25; j++)
{
genericArrangement2.add(1);
}
for (int j = 0; j < 50; j++)
{
genericArrangement2.add(2);
}
for (int j = 0; j < 25; j++)
{
genericArrangement2.add(3);
}
for (int j = 0; j < 50; j++)
{
genericArrangement2.add(4);
}
double[][] clusterLabArray2 = KMeans.ReadArrayFile("IrisData.txt", ",");
for (int i = 0; i < 100; i++)
{
KMeans kObject2 = new KMeans(clusterLabArray2, 5, 150);
ArrayList<Integer> newArrangement2 = kObject2.RunIter(4, 10, genericArrangement2, false);
double kappaResult2 = KMeans.GroupingWK(genericArrangement2, newArrangement2);
System.out.println(kappaResult2);
}
}
}
<file_sep>public class RRHC {
private static double bestFitness;
private static int iter = 5000, randomRestarts = 20;
public static double RRHC_H_Search(int n, double[][] distances)
{
for (int i = 0; i < randomRestarts - 1; i++)
{
double currentFitness = RMHC.RMHC_H_Search(iter, n, distances);
if (i == 0) bestFitness = currentFitness;
if (currentFitness < bestFitness) bestFitness = currentFitness;
}
return (bestFitness);
}
}
<file_sep>
public class ArrayMaxExcercise {
public double ArrayMax(double arr[]){
double CurrentMax = arr[0];
for (int i = 1; i < arr.length; i++)
{
if (arr[i]>CurrentMax)
{
CurrentMax=arr[i];
}
}
return(CurrentMax);
}
}
|
248f07a8cef4dcfc69f2c0fc2292a7d4b3841368
|
[
"Java"
] | 14
|
Java
|
pelumi2000/Level2-Java
|
01ed71498fde230622ac6699c0c09e1a16694023
|
9a3b61cc6f16d122b2804efe76d9064241a0b011
|
refs/heads/master
|
<file_sep>#!/usr/bin/python3
import sys
sys.path.insert(0, './pyAudioAnalysis') # nopep8
import random
import numpy as np
import pyAudioAnalysis
from pyAudioAnalysis import audioTrainTest as aT
import plotly.subplots
import os, argparse, sys
def set_seed(seed=1337):
random.seed(seed)
np.random.seed(seed)
def train_fold(fold_no):
data_folders = [dataset_path+"/train"+str(fold_no)+"/"+args.classcode+str(i) for i in range(class_count)]
aT.extract_features_and_train(
data_folders, 1.0, 1.0, aT.shortTermWindow, aT.shortTermStep, args.algorithm, model_name, False
)
def test_fold(fold_no):
test_folders = [dataset_path+"/test"+str(fold_no)+"/"+args.classcode+str(i) for i in range(class_count)]
aT.evaluate_model_for_folders(
test_folders, model_name, args.algorithm, args.classcode+"1"
)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# required
parser.add_argument('-d', '--datapath', help='Path of the dataset wrt current working directory.', required=True)
parser.add_argument('-m', '--modelname', help='Name of the model, used for output names.', required=True)
parser.add_argument('-c', '--classcode', help='Code of the class identifier (fi, fu).', required=True)
parser.add_argument('-a', '--algorithm', help='Classifier: svm, svm_rbf, randomforest...', default='randomforest')
args = parser.parse_args()
dataset_path = args.datapath
if args.classcode == 'fi':
class_name = 'Filling type'
class_count = 4
elif args.classcode == 'fu':
class_name = 'Filling level [%]'
class_count = 3
else:
raise NotImplementedError
set_seed()
# TODO: reduce repetitions, reuse features?
for i in range(3):
model_name = args.modelname+str(i)
train_fold(i)
test_fold(i)
print("il finito")
<file_sep>#!/usr/bin/python3
import pyAudioAnalysis
from pyAudioAnalysis import audioTrainTest as aT
import os, argparse, sys
import pandas as pd
import re
def predict_object(object_no, model_name, algorithm, dirpath, column_names):
"""Predicts the class for all wav objects in the directory,
with matching object_no. Uses the trained model with name model_name.
Args:
model_name (str): pyAudioAnalysis model name.
algorithm (str): pyAudioAnalysis algorithm.
object_no (int): object of the experiment.
dirpath (str): path of the wav files.
column_names (list): table column names.
Returns:
pd.DataFrame: table of results.
"""
if not os.path.isdir(dirpath):
print("Can't find path "+dirpath)
# create empty array (column) for each name
results_dict = {name:[] for name in column_names}
class_name = column_names[2]
file_pattern="o"+str(object_no)+r"_([\w\d_]+)_audio.wav"
files = [f for f in os.listdir(dirpath) if re.match(file_pattern, f)]
for fname in files:
seq_no = re.match(file_pattern, fname).group(1)
c, p, probs_names = \
aT.file_classification(os.path.join(dirpath,fname), model_name, algorithm)
results_dict['Object'].append(object_no)
results_dict['Sequence'].append(seq_no)
results_dict[class_name].append(c)
# class probabilities
for k in range(len(p)):
results_dict[class_name+' prob'+str(k)].append(p[k])
print("classified obj"+str(object_no)+" "+seq_no+" : "+str(c))
return pd.DataFrame(results_dict).sort_values(['Object', 'Sequence'])
<file_sep># CORSMAL Challenge pyAudioAnalysis
Analyzing filling type & level task of the [CORSMAL challenge](http://corsmal.eecs.qmul.ac.uk/containers_manip.html) with only the audio modality using [pyAudioAnalysis](https://github.com/tyiannak/pyAudioAnalysis) library.
This code is a part of the team "Because It's Tactile".
The rest of our team's code resides in [v-iashin/CORSMAL](https://github.com/v-iashin/CORSMAL) repository, please check it. Our team won the CORSMAL challenge in [2020 Intelligent Sensing Summer School](http://cis.eecs.qmul.ac.uk/school2020.html)!
## Installation
_Tested on Ubuntu 18.04_
1. Clone this repository `git clone --recursive https://github.com/gokhansolak/CORSMAL-pyAudioAnalysis.git` (mind the `--recursive` flag).
2. Follow the [installation guide in pyAudioAnalysis to install dependencies](https://github.com/tyiannak/pyAudioAnalysis#installation). Also make sure `ffmpeg` is installed. Alternatively, you may use `conda` environment (`conda env create -f environment.yml`) which will install a virtual environment with all requirements for `pyAudioAnalysis` and `ffmpeg`.
## Restructure dataset
We provide the scripts for both validation and final (public and private) set ups. To replicate the results you need just need to run only the lines with `final`. If you would like to experiment with different models you will also need to prepare the folder for validation.
For final analysis on the test set, we use `./gather_final_dataset.sh`. `./gather_final_dataset.sh` puts the _wav_ files into a structured folder, separating classes, as expected by [pyAudioAnalysis](https://github.com/tyiannak/pyAudioAnalysis) library.
**Warning:** Dataset paths of different batches (filling type or level, validation or final) must be separate, otherwise the library will confuse the classes. Note that we append `/final/fi` to `<target data path>`
```bash
chmod +x ./gather_final_dataset.sh
# for filling type (fi)
./gather_final_dataset.sh <source data path> <target data path>/final/fi "fi"
# for filling level (fu)
./gather_final_dataset.sh <source data path> <target data path>/final/fu "fu"
# Note that killing the script in the middle may change the current directory.
```
If you would like to experiment with different models, use `./gather_validation_dataset.sh` instead of `./gather_final_dataset.sh`, because the target folder structure changes. Run the following to restructure both validation subsets:
```bash
chmod +x ./gather_validation_dataset.sh
# for filling type (fi)
./gather_validation_dataset.sh <source data path> <target data path>/validation/fi "fi"
# for filling level (fu)
./gather_validation_dataset.sh <source data path> <target data path>/validation/fu "fu"
# Note that killing the script in the middle may change the current directory.
```
The expected source dir structure.
```
<source data path>:
├── [1-9]
│ └── audio
│ └── sSS_fiI_fuU_bB_lL_audio.wav # SS - subject id, I - fill level, etc
└── [10-15]
└── audio
└── XXXX_audio.wav # OO - object id and XXXX - event id
```
The training folders created by `gather_final/validation_dataset` will look like this (`fi*` or `fu*` are the classes, `train[0-2]` are split ids):
```
<target data path>
├── final
│ ├── fi
│ │ ├── test
│ │ └── train
│ │ └── fi[0-3]
│ └── fu
│ ├── test
│ └── train
│ └── fu[0-2]
and if you extracted validation
<target data path>
└── validation
├── fi
│ ├── test[0-2]
│ │ └── fi[0-3]
│ └── train[0-2]
│ └── fi[0-3]
└── fu
├── test[0-2]
│ └── fu[0-2]
└── train[0-2]
└── fu[0-2]
```
## Make Final Predictions on Test Set
To make the predictions using our pre-trained random forest models, copy the content of `./models` into `./`, and run these lines to apply them to make predictions on objects _10, 11, 12_ (public test set), as follows
```bash
# Run `conda activate pyAudioAnalysis` if you are using conda and replace `python3` with `python`
# for filling level (fu)
python3 ./src/apply_existing_model.py -d <target data path>/final/fu/test -m "flevel-randomforest-final" -c "fu"
# for filling type (fi)
python3 ./src/apply_existing_model.py -d <target data path>/final/fi/test -m "ftype-randomforest-final" -c "fi"
```
Use `--predict_on_private` to obtain predictions on the private test set objects (_13, 14, 15_).
It will create `.csv` files in the `./` directory. They should match the ones in `./results`.
We output the probabilities, so that we can ensemble the results with another model later.
Our final CORSMAL predictions are compiled using the `main.py` file in [v-iashin/CORSMAL](https://github.com/v-iashin/CORSMAL) repository.
We blend the outputs of multiple models developed by our team. The other models and the final blending script are in [v-iashin/CORSMAL](https://github.com/v-iashin/CORSMAL).
We tried multiple combinations with different strategies (see *src/combine_filling_results.py* file).
The *averaging* strategy improved both *filling type* and *filling level* task performances.
In validation set, for *filling level*, *vggish* model achieves a 75.5% accuracy, when ensemble with *pyAudioAnalysis/randomforest* and *r(2+1)d* models, it increases to 78.4%. You can find the outputs of these models in the _results/validation_ folder.
## How to Train Another Model
Start by looking for the best hyper-parameters on validation set. The training and 3-fold validation sequence can be run using `./src/train_filling_validation.py`:
```bash
# Run `conda activate pyAudioAnalysis` if you are using conda and replace `python3` with `python`
# for filling type (fi)
python3 ./src/train_filling_validation.py -d <target data path>/validation/fi -m "ftype-my-model" -c "fi"
# for filling level (fu)
python3 ./src/train_filling_validation.py -d <target data path>/validation/fu -m "flevel-my-model" -c "fu"
```
where `<target data path>` is the same path you used to form validation sets. `<model name> (-m)` an arbitrary string which will be appended to results. By default it will train a random forest classifier (run `python3 ./train_filling_validation.py --help` to see more).
When run, it will extract audio features, tune model parameters automatically and finally output some useful statistics about the model performance.
It is happening with minimal code, thanks to pyAudioAnalysis library!
The results on the CORSMAL validation data can be found in the _results/validation/performance_ folder.
Randomforest classifier gets ~94% on the filling type task and ~70% accuracy on the filling level task. Feel free to tune it more.
Then, train your model on the full training dataset (train final) run using `./src/train_filling_final.py`:
```bash
# Run `conda activate pyAudioAnalysis` if you are using conda and replace `python3` with `python`
# for filling type (fi)
python3 ./src/train_filling_final.py -d <target data path>/final/fi -m "ftype-my-model-final" -c "fi"
# for filling level (fu)
python3 ./src/train_filling_final.py -d <target data path>/final/fu -m "flevel-my-model-final" -c "fu"
```
<file_sep>#!/bin/bash
# Moves CORSMAL audio files into class folders; splits train and test folders.
# NOTE: it will overwrite the files in the target folder, if any.
function move_case(){
i=$1
case_path=$2
echo "object $i"
cd "${source_path}/$i/audio"
# iterate classes
for j in {0,1,2,3}; do
echo " class $j"
file_prefix="[0-z_]+${class_code}${j}[0-z_]+_audio\.wav"
mkdir -p "${case_path}/${class_code}${j}"
for f in *.wav; do
# echo $f
if [[ "$f" =~ ^${file_prefix} ]]; then
# compressing audio because the library wants mono audio
ffmpeg -y -v 0 -i "${BASH_REMATCH[0]}" -ac 1 "${case_path}/${class_code}${j}/o${i}_${BASH_REMATCH[0]}"
fi
done
done
}
function create_fold(){
fold_no=$1
for i in {1,2,3,4,5,6,7,8,9}; do
# modulus for object types (cup,glass,box)
mod_i=$(($i % 3))
if [[ "$mod_i" -eq ${fold_no} ]]; then
# test set
echo "test"
move_case "$i" "${target_path}/test${fold_no}"
else
# train set
echo "train"
move_case "$i" "${target_path}/train${fold_no}"
fi
done
}
echo "$PWD"
if [ "$#" -ne "3" ]; then
echo "Usage: gather_dataset <source data path> <target data path> <class code>"
exit 0
fi
initial_path="$PWD"
source_path="$PWD/$1"
target_path="$PWD/$2"
class_code="$3"
# create 3-folds
for fold in {0,1,2}; do
echo "=== fold $fold"
create_fold ${fold}
done
# back to the beginning
echo " back to ${initial_path}"
cd "${initial_path}"
<file_sep>#!/usr/bin/python3
import sys
sys.path.insert(0, './pyAudioAnalysis') # nopep8
# takes an already trained pyAudioAnalysis model and predicts the
# audio file classes in the given folder
import pyAudioAnalysis
from pyAudioAnalysis import audioTrainTest as aT
import plotly.subplots
import os, argparse, sys
import pandas as pd
import filling_analysis_common as filling
if __name__ == '__main__':
parser=argparse.ArgumentParser()
# required
parser.add_argument('-d', '--datapath', help='Path of the test set wrt current working directory.', required=True)
parser.add_argument('-m', '--modelname', help='Name of the model, used for output names.', required=True)
parser.add_argument('-c', '--classcode', help='Code of the class identifier (fi, fu)', required=True)
parser.add_argument('-a', '--algorithm', help='Classifier: svm, svm_rbf, randomforest...', default='randomforest')
parser.add_argument('-s', '--predict_on_private', help='If True also makes preds for private subset',
action='store_true', default=False)
# optional
parser.add_argument('-v', '--validation', help='3-fold validation.', action='store_true')
args = parser.parse_args()
dataset_path = args.datapath
model_name = args.modelname
if args.classcode == 'fi':
class_name = 'Filling type'
class_count = 4
elif args.classcode == 'fu':
class_name = 'Filling level [%]'
class_count = 3
else:
raise NotImplementedError
column_names=["Object", "Sequence", class_name] + [class_name+" prob"+str(i) for i in range(class_count)]
df = pd.DataFrame(columns=column_names)
if args.validation:
test_objects = [[3,6,9],[1,4,7],[2,5,8]]
for fold_no in [0,1,2]:
print("fold "+str(fold_no))
for obj in test_objects[fold_no]:
df_obj = filling.predict_object(obj, model_name+str(fold_no), args.algorithm, dataset_path+str(fold_no), column_names)
df = pd.concat([df, df_obj])
df.to_csv(model_name+'_result.csv', index=False)
else:
for obj in [10,11,12]:
df_obj = filling.predict_object(obj, model_name, args.algorithm, dataset_path, column_names)
df = pd.concat([df, df_obj])
df.to_csv(model_name+'_result_public_test.csv', index=False)
if args.predict_on_private:
# init the dataset again
df = pd.DataFrame(columns=column_names)
for obj in [13,14,15]:
df_obj = filling.predict_object(obj, model_name, args.algorithm, dataset_path, column_names)
df = pd.concat([df, df_obj])
df.to_csv(model_name+'_result_private_test.csv', index=False)
print("il finito")
<file_sep>#!/bin/bash
# go to the path and take the files in the class folders out
path=$1
# iterate folders
for d in ${path}/*; do
echo $d
# iterate files
for f in $d/*;do
cp $f ${path}
done
done
<file_sep>import pandas as pd
import argparse, os
if __name__ == '__main__':
parser=argparse.ArgumentParser()
parser.add_argument('-f', '--files', nargs='+', help='List of space separated file paths.', required=True)
parser.add_argument('-o', '--output', help='Name of the output file, w/o extension.', default='combined')
args = parser.parse_args()
df_list = []
for f in args.files:
df_list.append(pd.read_csv(f))
df_comb = pd.concat(df_list)
df_comb.to_csv(args.output+'.csv', index=False)
<file_sep>#!/usr/bin/python3
import sys
sys.path.insert(0, './pyAudioAnalysis') # nopep8
import random
import numpy as np
import pyAudioAnalysis
from pyAudioAnalysis import audioTrainTest as aT
import plotly.subplots
import os, argparse, sys
import pandas as pd
import filling_analysis_common as filling
def train(train_path):
data_folders = [os.path.join(train_path,args.classcode+str(i)) for i in range(class_count)]
aT.extract_features_and_train(
data_folders, 1.0, 1.0, aT.shortTermWindow, aT.shortTermStep, args.algorithm, model_name, False
)
def set_seed(seed=1337):
random.seed(seed)
np.random.seed(seed)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# required
parser.add_argument('-d', '--datapath', help='Path of the dataset w.r.t. current working directory.', required=True)
parser.add_argument('-m', '--modelname', help='Name of the model, used for output names.', required=True)
parser.add_argument('-c', '--classcode', help='Code of the class identifier (fi, fu).', required=True)
parser.add_argument('-a', '--algorithm', help='Classifier: svm, svm_rbf, randomforest...', default='randomforest')
args = parser.parse_args()
dataset_path = args.datapath
model_name = args.modelname
if args.classcode == 'fi':
class_name = 'Filling type'
class_count = 4
elif args.classcode == 'fu':
class_name = 'Filling level [%]'
class_count = 3
else:
raise NotImplementedError
#train
set_seed()
train_path = os.path.join(dataset_path, "train")
train(train_path)
# create table for results
column_names=["Object", "Sequence", class_name] + [class_name+" prob"+str(i) for i in range(class_count)]
df = pd.DataFrame(columns=column_names)
# test path is more specific
test_path = os.path.join(dataset_path, "test")
for obj in [10,11,12]:
df_obj = filling.predict_object(obj, model_name, args.algorithm, test_path, column_names)
df = pd.concat([df, df_obj])
df.to_csv(model_name+'.csv', index=False)
print("il finito")
<file_sep>#!/usr/bin/python3
# takes the csv probabilities (given as csv files) of two models
# and combines them to make the final prediction
import os, argparse, sys
import pandas as pd
import re
import pdb
def choose_index(i):
# print(rowlist)
res = rowlist[i].filter(regex='prob').squeeze()
# choose the maximum valued class
max_str=res.idxmax()
return max_str[-1]
def combine_max(rowlist):
res = rowlist[0]
for r in rowlist[1:]:
res = res.filter(regex='prob').add(r.filter(regex='prob'), fill_value=0)
# choose the maximum valued class
max_str=(res.max()).idxmax()
return max_str[-1]
def combine_average(rowlist):
# print(rowlist)
res = rowlist[0]
for r in rowlist[1:]:
res = res.filter(regex='prob').add(r.filter(regex='prob'), fill_value=0)
# choose the maximum valued class
max_str=(res.sum()/2).idxmax()
return max_str[-1]
def combine_weighted_average(rowlist):
# weight with the max prediction value
for i in range(len(rowlist)):
rowlist[i] = rowlist[i].filter(regex='prob')
rowlist[i] = rowlist[i].max() * rowlist[i]
res = rowlist[0]
for r in rowlist[1:]:
res = res.add(r, fill_value=0)
# choose the maximum valued class
max_str=(res.sum()/2).idxmax()
return max_str[-1]
if __name__ == '__main__':
parser=argparse.ArgumentParser()
parser.add_argument('-f', '--files', nargs='+', help='List of space separated file paths.', required=True)
parser.add_argument('-s', '--strategy', help='Strategy name: average, max, weighted, first, second.', default='average')
parser.add_argument('-o', '--output', help='Name of the output file, w/o extension.', default='combined')
parser.add_argument('-c', '--classname', help='Name of the class.', default='Filling type')
parser.add_argument('-v', '--validation', help='Calculates the accuracy.', action='store_true')
args = parser.parse_args()
print('strategy: '+str(args.strategy))
df_truth = pd.read_csv('ground_truth.csv')
df_list = []
# read csv files as pandas df
for f in args.files:
print('reading '+f)
df = pd.read_csv(f, index_col=False)
# clear column names
df = df[df.columns.drop(list(df.filter(regex='Unnamed')))]
df = df.rename(columns=lambda x: re.sub(r'^.+prob[_ ]?(\d)',args.classname+r' prob\1', x))
df = df.sort_values(['Object', 'Sequence'])
# put into list
df_list.append(df)
# pdb.set_trace()
# apply the specified strategy
df_combined = pd.DataFrame(columns=['Object', 'Sequence', args.classname])
true_pred = 0.0
for index, row in df_list[0].iterrows():
rowlist = []
for df in df_list[:]:
r = df.loc[(df['Object'] == row['Object']) & (df['Sequence'] == row['Sequence'])]
rowlist.append(r)
# calculate the combined label and append
if args.strategy == 'average':
label = combine_average(rowlist)
elif args.strategy == 'max':
label = combine_max(rowlist)
elif args.strategy == 'weighted':
label = combine_weighted_average(rowlist)
elif args.strategy == 'first':
label = choose_index(0)
elif args.strategy == 'second':
label = choose_index(1)
new_row = {'Object':row['Object'], 'Sequence':row['Sequence'], args.classname:int(label)}
df_combined = df_combined.append(new_row, ignore_index=True)
if args.validation:
true_val = df_truth.loc[(df_truth['Object'] == row['Object']) & (df_truth['Sequence'] == row['Sequence'])][args.classname].iloc[0]
if int(label) == true_val:
true_pred += 1.0
df_combined.to_csv(args.output+'.csv')
if args.validation:
print(true_pred/len(df_truth['Object']))
|
6270f7efd4efef249b68f13abdfd6420bb0df7d1
|
[
"Markdown",
"Python",
"Shell"
] | 9
|
Python
|
gokhansolak/CORSMAL-pyAudioAnalysis
|
73dcb935246bf01d847da9fabb67648473a37bb1
|
6d986a3c10021ed9cc3d0a4fa9b0123037350e8e
|
refs/heads/master
|
<repo_name>radtek/workWithPrinter<file_sep>/src/router.js
const router = require('express').Router();
const Printer = require('@thiagoelg/node-printer');
const childProcess = require('child_process');
const { PrinterApp } = require('./common/config');
const LableSample = process.cwd()+'/src/common/testSample.nlbl';
router.route('/')
.get((req, res) => {
res.json(Printer.getPrinters().map((el) => el.name));
})
.post(async (req, res) => {
childProcess.exec(`${PrinterApp} ${LableSample} "${req.body.string}" "${req.body.printer}"`);
res.status(204).end();
});
module.exports = router;
<file_sep>/app.js
const express = require('express');
const router = require('./src/router');
const app = express();
app.use(express.json());
app.use(express.static(__dirname + '/client/public'));
app.get("/", function(req, res) {
res.sendFile('public/index.html', {root: __dirname });
});
app.use('/printer', router);
module.exports = app;
<file_sep>/server.js
const app = require('./app');
const { PORT } = require('./src/common/config');
app.listen(PORT, () => {
console.log(`Server is running in http://localhost:${PORT}\\`);
});
<file_sep>/NiceLableSDK/ConsoleApp1/Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using NiceLabel.SDK;
namespace ConsoleApp1 {
class Program {
static void Main(string[] args) {
try {
string sdkFilesPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "..\\..\\..\\SDKFiles");
if (Directory.Exists(sdkFilesPath)) {
PrintEngineFactory.SDKFilesPath = sdkFilesPath;
}
PrintEngineFactory.PrintEngine.Initialize();
}
catch (SDKException exception) {
}
ILabel label = PrintEngineFactory.PrintEngine.OpenLabel(args[0]);
label.PrintSettings.PrinterName = args[2];
label.Variables["value"].SetValue(args[1]);
label.Print(1);
}
}
}
<file_sep>/client/public/js.js
const chosePrinter = document.querySelector('select');
fetch('http://localhost:8000/printer')
.then((res) => {
res.json().then((printers) => {
for(let i = 0; i < printers.length; i++) {
let el = document.createElement("option");
el.innerHTML = printers[i];
chosePrinter.append(el);
}
})
});
document.querySelector('button').addEventListener('click', () => {
// console.log(document.querySelector('textarea').value);
fetch('http://localhost:8000/printer', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
printer: chosePrinter.value,
string: document.querySelector('textarea').value.trim()
})
}).then((res) => {
console.log(res);
})
});
function changeButtonState() {
if(chosePrinter.value !== "Выберите принтер" && document.querySelector('textarea').value !== "") {
document.querySelector('button').removeAttribute('disabled');
} else {
document.querySelector('button').setAttribute('disabled', 'disabled');
}
}
chosePrinter.addEventListener('change', changeButtonState);
document.querySelector('textarea').addEventListener('blur', changeButtonState);
<file_sep>/src/common/config.js
module.exports = {
PORT: 8000,
PrinterApp: process.cwd() + "\\NiceLableSDK\\ConsoleApp1\\bin\\Debug\\ConsoleApp1.exe"
}
|
dddd8d6dbd254b0bb556f0ae216ee23041f9d4a5
|
[
"JavaScript",
"C#"
] | 6
|
JavaScript
|
radtek/workWithPrinter
|
a369c2ea29d87e3057e7fc41f2296bba7f6f295a
|
acbb9c830edcb80a5bf84958e6291c22d8869444
|
refs/heads/master
|
<repo_name>pgstuff/usa_ein<file_sep>/src/usa_ein.c
#include "postgres.h"
#include "fmgr.h"
#include "libpq/pqformat.h"
#include "utils/builtins.h"
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
typedef uint32 usa_ein_t;
#define USAEINGetDatum(x) Int32GetDatum(x)
#define DatumGetUSAEIN(x) DatumGetInt32(x)
#define PG_GETARG_USAEIN(n) DatumGetUSAEIN(PG_GETARG_DATUM(n))
#define PG_RETURN_USAEIN(x) return USAEINGetDatum(x)
//#define DIGITTOINT(n) (((n) >= '0' && (n) <= '9') ? (int32) ((n) - '0') : 0)
Datum usa_ein_in(PG_FUNCTION_ARGS);
Datum usa_ein_out(PG_FUNCTION_ARGS);
Datum usa_ein_to_text(PG_FUNCTION_ARGS);
Datum usa_ein_from_text(PG_FUNCTION_ARGS);
Datum usa_ein_send(PG_FUNCTION_ARGS);
Datum usa_ein_recv(PG_FUNCTION_ARGS);
Datum usa_ein_lt(PG_FUNCTION_ARGS);
Datum usa_ein_le(PG_FUNCTION_ARGS);
Datum usa_ein_eq(PG_FUNCTION_ARGS);
Datum usa_ein_ne(PG_FUNCTION_ARGS);
Datum usa_ein_ge(PG_FUNCTION_ARGS);
Datum usa_ein_gt(PG_FUNCTION_ARGS);
Datum usa_ein_cmp(PG_FUNCTION_ARGS);
static usa_ein_t cstring_to_usa_ein(char *usa_ein_string);
static char *usa_ein_to_cstring(usa_ein_t usa_ein);
static bool usa_ein_is_valid(int32 prefix, int32 serial);
/* generic input/output functions */
PG_FUNCTION_INFO_V1(usa_ein_in);
Datum
usa_ein_in(PG_FUNCTION_ARGS)
{
usa_ein_t result;
char *usa_ein_str = PG_GETARG_CSTRING(0);
result = cstring_to_usa_ein(usa_ein_str);
PG_RETURN_USAEIN(result);
}
PG_FUNCTION_INFO_V1(usa_ein_out);
Datum
usa_ein_out(PG_FUNCTION_ARGS)
{
usa_ein_t packed_usa_ein;
char *usa_ein_string;
packed_usa_ein = PG_GETARG_USAEIN(0);
usa_ein_string = usa_ein_to_cstring(packed_usa_ein);
PG_RETURN_CSTRING(usa_ein_string);
}
/* type to/from text conversion routines */
PG_FUNCTION_INFO_V1(usa_ein_to_text);
Datum
usa_ein_to_text(PG_FUNCTION_ARGS)
{
char *usa_ein_string;
text *usa_ein_text;
usa_ein_t packed_usa_ein = PG_GETARG_USAEIN(0);
usa_ein_string = usa_ein_to_cstring(packed_usa_ein);
usa_ein_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(usa_ein_string)));
PG_RETURN_TEXT_P(usa_ein_text);
}
PG_FUNCTION_INFO_V1(usa_ein_from_text);
Datum
usa_ein_from_text(PG_FUNCTION_ARGS)
{
text *usa_ein_text = PG_GETARG_TEXT_P(0);
char *usa_ein_str = DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(usa_ein_text)));
usa_ein_t usa_ein = cstring_to_usa_ein(usa_ein_str);
PG_RETURN_USAEIN(usa_ein);
}
/* Functions to convert to/from bytea */
PG_FUNCTION_INFO_V1(usa_ein_send);
Datum
usa_ein_send(PG_FUNCTION_ARGS)
{
StringInfoData buffer;
usa_ein_t usa_ein = PG_GETARG_USAEIN(0);
pq_begintypsend(&buffer);
pq_sendint(&buffer, (int32)usa_ein, 4);
PG_RETURN_BYTEA_P(pq_endtypsend(&buffer));
}
PG_FUNCTION_INFO_V1(usa_ein_recv);
Datum usa_ein_recv(PG_FUNCTION_ARGS)
{
usa_ein_t usa_ein;
StringInfo buffer = (StringInfo) PG_GETARG_POINTER(0);
usa_ein = pq_getmsgint(buffer, 4);
PG_RETURN_USAEIN(usa_ein);
}
/* functions to support btree opclass */
PG_FUNCTION_INFO_V1(usa_ein_lt);
Datum
usa_ein_lt(PG_FUNCTION_ARGS)
{
usa_ein_t a = PG_GETARG_USAEIN(0);
usa_ein_t b = PG_GETARG_USAEIN(1);
PG_RETURN_BOOL(a < b);
}
PG_FUNCTION_INFO_V1(usa_ein_le);
Datum
usa_ein_le(PG_FUNCTION_ARGS)
{
usa_ein_t a = PG_GETARG_USAEIN(0);
usa_ein_t b = PG_GETARG_USAEIN(1);
PG_RETURN_BOOL (a <= b);
}
PG_FUNCTION_INFO_V1(usa_ein_eq);
Datum
usa_ein_eq(PG_FUNCTION_ARGS)
{
usa_ein_t a = PG_GETARG_USAEIN(0);
usa_ein_t b = PG_GETARG_USAEIN(1);
PG_RETURN_BOOL(a == b);
}
PG_FUNCTION_INFO_V1(usa_ein_ne);
Datum
usa_ein_ne(PG_FUNCTION_ARGS)
{
usa_ein_t a = PG_GETARG_USAEIN(0);
usa_ein_t b = PG_GETARG_USAEIN(1);
PG_RETURN_BOOL(a != b);
}
PG_FUNCTION_INFO_V1(usa_ein_ge);
Datum
usa_ein_ge(PG_FUNCTION_ARGS)
{
usa_ein_t a = PG_GETARG_USAEIN(0);
usa_ein_t b = PG_GETARG_USAEIN(1);
PG_RETURN_BOOL(a >= b);
}
PG_FUNCTION_INFO_V1(usa_ein_gt);
Datum
usa_ein_gt(PG_FUNCTION_ARGS)
{
usa_ein_t a = PG_GETARG_USAEIN(0);
usa_ein_t b = PG_GETARG_USAEIN(1);
PG_RETURN_BOOL(a > b);
}
PG_FUNCTION_INFO_V1(usa_ein_cmp);
Datum
usa_ein_cmp(PG_FUNCTION_ARGS)
{
usa_ein_t a = PG_GETARG_USAEIN(0);
usa_ein_t b = PG_GETARG_USAEIN(1);
PG_RETURN_INT32(a - b);
}
static int32
usa_ein_cmp_internal(usa_ein_t a, usa_ein_t b)
{
return a - b;
/*if (a < b)
return -1;
else if (a > b)
return 1;
return 0;*/
}
/*****************************************************************************
* Aggregate functions
*****************************************************************************/
PG_FUNCTION_INFO_V1(usa_ein_smaller);
Datum
usa_ein_smaller(PG_FUNCTION_ARGS)
{
usa_ein_t left = PG_GETARG_USAEIN(0);
usa_ein_t right = PG_GETARG_USAEIN(1);
usa_ein_t result;
result = usa_ein_cmp_internal(left, right) < 0 ? left : right;
PG_RETURN_TEXT_P(result);
}
PG_FUNCTION_INFO_V1(usa_ein_larger);
Datum
usa_ein_larger(PG_FUNCTION_ARGS)
{
usa_ein_t left = PG_GETARG_USAEIN(0);
usa_ein_t right = PG_GETARG_USAEIN(1);
usa_ein_t result;
result = usa_ein_cmp_internal(left, right) > 0 ? left : right;
PG_RETURN_TEXT_P(result);
}
/*
* Convert a cstring to an USA EIN, validating the input.
* Input in forms AA-BBBBBBB or AABBBBBBB is accepted.
*/
static usa_ein_t
cstring_to_usa_ein(char *usa_ein_str)
{
char *c;
usa_ein_t result;
char dashes[] = {2};
int dashes_no = 0;
int ndigits = 0;
int32 prefix,
serial;
prefix = serial = result = 0;
for (c = usa_ein_str; *c != 0; c++)
{
if (*c >= '0' && *c <= '9')
{
if (ndigits < 2) prefix = prefix * 10 + *c - '0';
else if (ndigits < 9) serial = serial * 10 + *c - '0';
result = result * 10 + *c - '0';
ndigits++;
}
else if (*c == '-')
{
int pos = c - usa_ein_str;
if (dashes_no < 1 && pos == dashes[dashes_no])
dashes_no++;
else
ereport(ERROR,
(errmsg("Invalid format of input data \"%s\".", usa_ein_str),
errhint("Valid formats are: AA-BBBBBBB or AABBBBBBB")));
}
else
ereport(ERROR,
(errmsg("Unexpected character '%c' in input data \"%s\".", *c, usa_ein_str),
errhint("Valid USA EIN consists of digits and optional dashes")));
}
if (ndigits != 9)
ereport(ERROR,
(errmsg("Invalid number of digits (%d) in input data \"%s\".", ndigits, usa_ein_str),
errhint("Valid USA EIN consists of 9 digits.")));
if (!usa_ein_is_valid(prefix, serial))
ereport(ERROR,
(errmsg("USA EIN number \"%s\" is invalid.", usa_ein_str)));
PG_RETURN_USAEIN(result);
}
/*static usa_ein_t
cstring_to_usa_ein(char *usa_ein_str)
{
char *c;
usa_ein_t result;
char dashes[] = {2};
int dashes_no = 0;
int ndigits = 0;
int32 prefix,
serial;
prefix = serial = 0;
for (c = usa_ein_str; *c != 0; c++)
{
if (isdigit(*c))
{
if (ndigits < 2) prefix = prefix * 10 + DIGITTOINT(*c);
else if (ndigits < 9) serial = serial * 10 + DIGITTOINT(*c);
ndigits++;
}
else if (*c == '-')
{
int pos = c - usa_ein_str;
if (dashes_no < 1 && pos == dashes[dashes_no])
dashes_no++;
else
ereport(ERROR,
(errmsg("invalid format of input data %s", usa_ein_str),
errhint("Valid formats are: AA-BBBBBBB or AABBBBBBB")));
}
else
ereport(ERROR,
(errmsg("unexpected character '%c' in input data %s", *c, usa_ein_str),
errhint("Valid USA EIN consists of digits and optional dashes")));
}
if (ndigits != 9)
ereport(ERROR,
(errmsg("invalid number of digits (%d) in input data %s", ndigits, usa_ein_str),
errhint("Valid USA EIN consists of 9 digits")));
if (!usa_ein_is_valid(prefix, serial))
ereport(ERROR,
(errmsg("USA EIN number %s is invalid", usa_ein_str)));
result = serial + (prefix << 24);
PG_RETURN_USAEIN(result);
}*/
/* Convert the internal representation to the AA-BBBBBBB output string */
static char *
usa_ein_to_cstring(usa_ein_t usa_ein)
{
int32 remainder = usa_ein;
int32 digit_value;
char *usa_ein_str = palloc(11);
if (usa_ein < 0)
/* Error out */;
if (usa_ein > 999999999 || usa_ein < 0)
ereport(ERROR,
(errmsg("Invalid data."),
errhint("The EIN data is out of range.")));
digit_value = remainder * .00000001;
usa_ein_str[0] = '0' + digit_value;
remainder = remainder - digit_value * 100000000;
digit_value = remainder * .0000001;
usa_ein_str[1] = '0' + digit_value;
remainder = remainder - digit_value * 10000000;
digit_value = remainder * .000001;
usa_ein_str[2] = '-';
usa_ein_str[3] = '0' + digit_value;
remainder = remainder - digit_value * 1000000;
digit_value = remainder * .00001;
usa_ein_str[4] = '0' + digit_value;
remainder = remainder - digit_value * 100000;
digit_value = remainder * .0001;
usa_ein_str[5] = '0' + digit_value;
remainder = remainder - digit_value * 10000;
digit_value = remainder * .001;
usa_ein_str[6] = '0' + digit_value;
remainder = remainder - digit_value * 1000;
digit_value = remainder * .01;
usa_ein_str[7] = '0' + digit_value;
remainder = remainder - digit_value * 100;
digit_value = remainder * .1;
usa_ein_str[8] = '0' + digit_value;
remainder = remainder - digit_value * 10;
usa_ein_str[9] = '0' + remainder;
usa_ein_str[10] = '\0';
return usa_ein_str;
}
/*static char *
usa_ein_to_cstring(usa_ein_t usa_ein)
{
int32 prefix,
serial;
int32 ndigits;
char *usa_ein_str = palloc(11);
if (usa_ein < 0)
* Error out *;
serial = usa_ein & ((1 << 24) - 1);
prefix = (usa_ein >> 24) & 127;
if (!usa_ein_is_valid(prefix, serial))
ereport(ERROR,
(errmsg("USA EIN number %s is invalid", usa_ein_str)));
if ((ndigits = snprintf(usa_ein_str, 11, "%02d-%07d", prefix, serial)) != 10)
ereport(ERROR,
(errmsg("invalid size (%d) of in input data %s", ndigits-1, usa_ein_str),
errhint("Valid USA EIN consists of 9 digits")));
if (usa_ein_str[2] != '-')
ereport(ERROR,
(errmsg("invalid format of input data %s", usa_ein_str),
errhint("Valid formats are: AA-BBBBBBB or AABBBBBBB")));
return usa_ein_str;
}*/
/*
* Check whether the components of the USA EIN are valid.
*/
static bool
usa_ein_is_valid(int32 prefix, int32 serial)
{
if (prefix == 0)
return false;
if (prefix == 7 || prefix == 8 || prefix == 9)
return false;
return true;
}
<file_sep>/sql/usa_ein.sql
/*
* Author: The maintainer's name
* Created at: Wed Oct 14 23:12:59 -0400 2015
*
*/
SET client_min_messages = warning;
-- SQL definitions for USAEIN type
CREATE TYPE usa_ein;
-- basic i/o functions
CREATE OR REPLACE FUNCTION usa_ein_in(cstring) RETURNS usa_ein AS '$libdir/usa_ein'
LANGUAGE C IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION usa_ein_out(usa_ein) RETURNS cstring AS '$libdir/usa_ein'
LANGUAGE C IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION usa_ein_send(usa_ein) RETURNS bytea AS '$libdir/usa_ein'
LANGUAGE C IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION usa_ein_recv(internal) RETURNS usa_ein AS '$libdir/usa_ein'
LANGUAGE C IMMUTABLE STRICT;
CREATE TYPE usa_ein (
input = usa_ein_in,
output = usa_ein_out,
send = usa_ein_send,
receive = usa_ein_recv,
internallength = 4,
passedbyvalue
);
-- functions to support btree opclass
CREATE OR REPLACE FUNCTION usa_ein_lt(usa_ein, usa_ein) RETURNS bool AS '$libdir/usa_ein'
LANGUAGE C IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION usa_ein_le(usa_ein, usa_ein) RETURNS bool AS '$libdir/usa_ein'
LANGUAGE C IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION usa_ein_eq(usa_ein, usa_ein) RETURNS bool AS '$libdir/usa_ein'
LANGUAGE C IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION usa_ein_ne(usa_ein, usa_ein) RETURNS bool AS '$libdir/usa_ein'
LANGUAGE C IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION usa_ein_ge(usa_ein, usa_ein) RETURNS bool AS '$libdir/usa_ein'
LANGUAGE C IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION usa_ein_gt(usa_ein, usa_ein) RETURNS bool AS '$libdir/usa_ein'
LANGUAGE C IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION usa_ein_cmp(usa_ein, usa_ein) RETURNS int4 AS '$libdir/usa_ein'
LANGUAGE C IMMUTABLE STRICT;
-- to/from text conversion
CREATE OR REPLACE FUNCTION usa_ein_to_text(usa_ein) RETURNS text AS '$libdir/usa_ein'
LANGUAGE C IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION usa_ein_from_text(text) RETURNS usa_ein AS '$libdir/usa_ein'
LANGUAGE C IMMUTABLE STRICT;
-- operators
CREATE OPERATOR < (
leftarg = usa_ein, rightarg = usa_ein, procedure = usa_ein_lt,
commutator = >, negator = >=,
restrict = scalarltsel, join = scalarltjoinsel
);
CREATE OPERATOR <= (
leftarg = usa_ein, rightarg = usa_ein, procedure = usa_ein_le,
commutator = >=, negator = >,
restrict = scalarltsel, join = scalarltjoinsel
);
CREATE OPERATOR = (
leftarg = usa_ein, rightarg = usa_ein, procedure = usa_ein_eq,
commutator = =, negator = <>,
restrict = eqsel, join = eqjoinsel,
merges
);
CREATE OPERATOR <> (
leftarg = usa_ein, rightarg = usa_ein, procedure = usa_ein_ne,
commutator = <>, negator = =,
restrict = neqsel, join = neqjoinsel
);
CREATE OPERATOR > (
leftarg = usa_ein, rightarg = usa_ein, procedure = usa_ein_gt,
commutator = <, negator = <=,
restrict = scalargtsel, join = scalargtjoinsel
);
CREATE OPERATOR >= (
leftarg = usa_ein, rightarg = usa_ein, procedure = usa_ein_ge,
commutator = <=, negator = <,
restrict = scalargtsel, join = scalargtjoinsel
);
-- aggregates
CREATE OR REPLACE FUNCTION usa_ein_smaller(usa_ein, usa_ein)
RETURNS usa_ein
AS '$libdir/usa_ein'
LANGUAGE C IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION usa_ein_larger(usa_ein, usa_ein)
RETURNS usa_ein
AS '$libdir/usa_ein'
LANGUAGE C IMMUTABLE STRICT;
CREATE AGGREGATE min(usa_ein) (
SFUNC = usa_ein_smaller,
STYPE = usa_ein,
SORTOP = <
);
CREATE AGGREGATE max(usa_ein) (
SFUNC = usa_ein_larger,
STYPE = usa_ein,
SORTOP = >
);
-- btree operator class
CREATE OPERATOR CLASS usa_ein_ops DEFAULT FOR TYPE usa_ein USING btree AS
OPERATOR 1 <,
OPERATOR 2 <=,
OPERATOR 3 =,
OPERATOR 4 >=,
OPERATOR 5 >,
FUNCTION 1 usa_ein_cmp(usa_ein, usa_ein);
-- cast from/to text
CREATE CAST (usa_ein AS text) WITH FUNCTION usa_ein_to_text(usa_ein) AS ASSIGNMENT;
CREATE CAST (text AS usa_ein) WITH FUNCTION usa_ein_from_text(text) AS ASSIGNMENT;
/* Does this survive a pg_dump?
CREATE CAST (int AS usa_ein) WITHOUT FUNCTION AS ASSIGNMENT;
CREATE CAST (usa_ein AS int) WITHOUT FUNCTION;
*/
|
296e9980a7665f3f4802205985b3210b704e0abe
|
[
"C",
"SQL"
] | 2
|
C
|
pgstuff/usa_ein
|
290630c6c0e66a388adf537e14358f6c6bfda4fc
|
7214722d528960317e66dec4d7dc4dff1236e095
|
refs/heads/master
|
<file_sep>package com.hitherejoe.module_androidtest_only.injection.component;
import com.hitherejoe.module_androidtest_only.injection.module.DataManagerTestModule;
import com.hitherejoe.mvvm_hackernews.injection.component.DataManagerComponent;
import com.hitherejoe.mvvm_hackernews.injection.scope.PerDataManager;
import dagger.Component;
@PerDataManager
@Component(dependencies = TestComponent.class, modules = DataManagerTestModule.class)
public interface DataManagerTestComponent extends DataManagerComponent {
}<file_sep>package com.hitherejoe.mvvm_hackernews.data.remote;
import com.google.gson.GsonBuilder;
import retrofit.RestAdapter;
import retrofit.converter.GsonConverter;
public class RetrofitHelper {
public HackerNewsService newHackerNewsService() {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(HackerNewsService.ENDPOINT)
.setLogLevel(RestAdapter.LogLevel.FULL)
.setConverter(new GsonConverter(new GsonBuilder().create()))
.build();
return restAdapter.create(HackerNewsService.class);
}
}
<file_sep>package com.hitherejoe.module_androidtest_only.injection.component;
import com.hitherejoe.module_androidtest_only.injection.module.ApplicationTestModule;
import com.hitherejoe.mvvm_hackernews.injection.component.ApplicationComponent;
import javax.inject.Singleton;
import dagger.Component;
@Singleton
@Component(modules = ApplicationTestModule.class)
public interface TestComponent extends ApplicationComponent {
}
<file_sep>include ':app', ':module_androidtest_only'
|
e8efbb422bcaead8ca1fca2d6cd2857a2a145451
|
[
"Java",
"Gradle"
] | 4
|
Java
|
maheshwarLigade/MVVM_Hacker_News
|
d2d8687e9db634a7df00a3878c9ab6e0dea82c1a
|
c9a1eb61b54c80285c3e18480e77a54f9716ad7d
|
refs/heads/master
|
<file_sep><?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
$postData = file_get_contents('php://input');
$data = json_decode($postData, true);
$data = json_decode($data['data']);
// Подключаем класс для работы с excel
require_once('PHPExcel.php');
// Подключаем класс для вывода данных в формате excel
require_once('PHPExcel/Writer/Excel5.php');
// Создаем объект класса PHPExcel
//$xls = new PHPExcel();
$xls = PHPExcel_IOFactory::load('template.xls');
// Устанавливаем индекс активного листа
$xls->setActiveSheetIndex(0);
// Получаем активный лист
$sheet = $xls->getActiveSheet();
// Подписываем лист
//$sheet->setTitle('Таблица умножения');
// Вставляем текст в ячейку A1
//$sheet->setCellValue("A1", 'Таблица умножения');
//$sheet->getStyle('A1')->getFill()->setFillType(
// PHPExcel_Style_Fill::FILL_SOLID);
//$sheet->getStyle('A1')->getFill()->getStartColor()->setRGB('EEEEEE');
// Объединяем ячейки
//$sheet->mergeCells('A1:H1');
// Выравнивание текста
//$sheet->getStyle('A1')->getAlignment()->setHorizontal(
// PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//for ($i = 2; $i < 10; $i++) {
// for ($j = 2; $j < 10; $j++) {
// Выводим таблицу умножения
// $sheet->setCellValueByColumnAndRow(
// $i - 2,
// $j,
// $i . "x" .$j . "=" . ($i*$j));
// Применяем выравнивание
// $sheet->getStyleByColumnAndRow($i - 2, $j)->getAlignment()->
// setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
// }
//}
//
$i=12;
foreach ($data as $item) {
$sheet->setCellValue("E".$i, ($i-11));
$sheet->setCellValue("D".$i, $item->name_group);
$sheet->setCellValue("H".$i, $item->minus_word);
$sheet->setCellValue("J".$i, $item->header1);
$sheet->setCellValue("K".$i, $item->header2);
$sheet->setCellValue("L".$i, $item->info_text);
$sheet->setCellValue("P".$i, $item->url);
$sheet->setCellValue("Q".$i, $item->os);
$sheet->setCellValue("X".$i, $item->quick_link_value);
$sheet->setCellValue("Y".$i, $item->quick_link_url);
$sheet->setCellValue("Z".$i, $item->quick_link_text);
$sheet->setCellValue("AE".$i, $item->quick_link_note);
$i++;
// echo $item->minus_word."<br/>\n";
}
$filename = time().'.xls';
// Выводим содержимое файла
$objWriter = new PHPExcel_Writer_Excel5($xls);
$objWriter->save('files/'.$filename);
echo json_encode(['filename' => $filename]);
?>
|
db6011e3a5296a2e61012069b157618b80499fd9
|
[
"PHP"
] | 1
|
PHP
|
fukalov1/reklama
|
ea073f6cdad8c7165a3a5f12a8ca2b9938de32ab
|
de25881059893899551644be1192c8098dd69626
|
refs/heads/master
|
<repo_name>Nita112233/test1<file_sep>/formdemografi/admin.py
from django.contrib import admin
from .models import Post
from .models import Patient, Condition, Evidence, Identifier, Address, HumanName
from .models import ContactPoint, Location, Attachment
# from .models import ServiceType, Reference, CodeableConcept, Coding
# from .models import Practitioner, HealthcareService, Encounter, DiagnosticReport
# from .models import Quantity, Period, PractitionerRole
class IdentifierInline(admin.TabularInline):
model = Identifier
extra = 1
class HumanNameInline(admin.TabularInline):
model = HumanName
extra = 1
class ContactPointInline(admin.TabularInline):
model = ContactPoint
extra = 1
class AddressInline(admin.TabularInline):
model = Address
extra = 1
class AttachmentInline(admin.TabularInline):
model = Attachment
extra = 1
class EvidenceInline(admin.TabularInline):
model = Evidence
extra = 1
class PatientAdmin(admin.ModelAdmin):
inlines = [
IdentifierInline, HumanNameInline, ContactPointInline, AddressInline,
AttachmentInline,
]
class ConditionAdmin(admin.ModelAdmin):
inlines = [
IdentifierInline, EvidenceInline,
]
admin.site.register(Post)
admin.site.register(Patient, PatientAdmin)
admin.site.register(Condition, ConditionAdmin)
# admin.site.register(Post, ServiceType, Reference, CodeableConcept, Coding, Practitioner,
# HealthcareService, Condition, Evidence, Encounter, DiagnosticReport, Identifier,
# Address, Quantity, HumanName, ContactPoint, Location, Attachment, Period,
# PractitionerRole) #register the model
# http://stackoverflow.com/questions/30472741/inlinemodeladmin-not-showing-up-on-admin-page
|
ddc720d086c35ab50d1a2c4927994c922e88508a
|
[
"Python"
] | 1
|
Python
|
Nita112233/test1
|
bb60264af4f2b58c860061bf0f88b4c679dca42f
|
5693f0c9c2d42dbf45dd15a8999e67467ac04565
|
refs/heads/master
|
<repo_name>abhishekmishra/pypicoturtle<file_sep>/src/picoturtle.py
import urllib.request
import urllib.parse
import json
import webbrowser
import builtins
import sys
import datetime
from pathlib import Path
import os.path
import platform
import os
import stat
import subprocess
PICOTURTLE_WEBCANVAS_RELEASES_URL = 'https://github.com/abhishekmishra/picoturtle-web-canvas/releases/download/'
PICOTURTLE_WEBCANVAS_VERSION_TAG = 'v0.0.10'
# def turtle_request(url):
# #TODO: Added debug/verbose param to enable request times.
# #start = datetime.datetime.now().timestamp()
# res = urllib.request.urlopen(url)
# t = json.loads(res.read().decode('utf-8'))
# #end = datetime.datetime.now().timestamp()
# #delta = end - start
# #print(url + ' Took ' + str(delta))
# return t
builtins.t = None
def get_picoturtle_exec_name():
if platform.system() == 'Linux':
return 'picoturtle-web-canvas-linux'
elif platform.system() == 'Windows':
return 'picoturtle-web-canvas-win.exe'
elif platform.system() == 'Darwin':
return 'picoturtle-web-canvas-macos'
else:
print(platform.system())
def get_default_picoturtle_exec_path():
return os.path.join(str(Path.home()), get_picoturtle_exec_name())
def download_picoturtle_web_canvas(location=None, force=False):
toolbar_width = 40
last_bar = 0
def download_progress(blocknum, bs, size):
pct = (blocknum * bs)/size
bar = int(pct * toolbar_width)
#print(str(blocknum * bs) + ' of ' + str(size))
nonlocal last_bar
for i in range(last_bar, bar):
sys.stdout.write("-")
sys.stdout.flush()
last_bar = bar
url = PICOTURTLE_WEBCANVAS_RELEASES_URL \
+ PICOTURTLE_WEBCANVAS_VERSION_TAG \
+ '/' + get_picoturtle_exec_name()
if location == None:
location = get_default_picoturtle_exec_path()
if os.path.exists(location) and not force:
print('File already exists at location -> ' + location)
else:
print('Downloading ' + url + ' at -> ' + location)
# setup toolbar
sys.stdout.write("[%s]" % (" " * toolbar_width))
sys.stdout.flush()
# return to start of line, after '['
sys.stdout.write("\b" * (toolbar_width+1))
urllib.request.urlretrieve(url, location, download_progress)
print('Done.')
st = os.stat(location)
os.chmod(location, st.st_mode | stat.S_IEXEC)
def run_picoturtle_web_canvas():
exec_path = get_default_picoturtle_exec_path()
subprocess.check_call([exec_path])
class Turtle:
"""
proxy to turtle remote api
"""
def __init__(self,
name=None,
host="127.0.0.1",
port="3000",
bulk=True,
bulk_limit=100,
open_browser=True):
self.turtle_url = "http://" + host + ":" + port
self.bulk = bulk
self.bulk_limit = bulk_limit
self.name = name
self.open_browser = open_browser
self.commands = []
if self.name == None:
self.turtle_init()
def turtle_request(self, cmd, args=None, is_obj=False):
if self.bulk == True and (cmd != 'create'):
cargs = []
if args != None:
if is_obj:
arg_obj = {}
for i in range(len(args)):
arg_obj[args[i]['k']] = args[i]['v']
cargs.append(arg_obj)
else:
for i in range(len(args)):
cargs.append(args[i]['v'])
command = {'cmd': cmd, 'args': cargs}
self.commands.append(command)
if (len(self.commands) >= self.bulk_limit) or (cmd == 'stop') or (cmd == 'state'):
# print(self.commands)
# drain the commands
req = urllib.request.Request(self.turtle_url + '/turtle/' +
self.name + '/commands')
req.add_header('Content-Type',
'application/json; charset=utf-8')
jsondata = json.dumps(self.commands)
jsondataasbytes = jsondata.encode('utf-8') # needs to be bytes
req.add_header('Content-Length', len(jsondataasbytes))
res = urllib.request.urlopen(req, jsondataasbytes)
# print('Draining ' + str(len(self.commands)) + ' commands for ' +
# self.name)
self.commands = []
t = json.loads(res.read().decode('utf-8'))
return t
else:
#print('start -> ' + request_url)
request_url = '/turtle/'
if self.name != None:
request_url += self.name
request_url += '/'
request_url += cmd
if args != None:
request_url += '?'
for i in range(len(args)):
if (i > 0):
request_url += '&'
request_url += args[i]['k']
request_url += '='
request_url += str(args[i]['v'])
res = urllib.request.urlopen(self.turtle_url + request_url)
t = json.loads(res.read().decode('utf-8'))
print('done -> ' + request_url)
return t
def turtle_init(self):
self.commands = []
t = self.turtle_request(
'create', args=[{
'k': 'x',
'v': 250
}, {
'k': 'y',
'v': 250
}])
self.name = t['name']
if self.open_browser:
webbrowser.open(self.turtle_url +
'/index.html?details=0&list=0&name=' + self.name)
return t
def penup(self):
t = self.turtle_request('penup')
return t
def pendown(self):
t = self.turtle_request('pendown')
return t
def penwidth(self, w):
t = self.turtle_request('penwidth', args=[{'k': 'w', 'v': w}])
return t
def stop(self):
t = self.turtle_request('stop')
return t
def state(self):
t = self.turtle_request('state')
return t
def home(self):
t = self.turtle_request('home')
return t
def clear(self):
t = self.turtle_request('clear')
return t
def forward(self, d):
t = self.turtle_request('forward', args=[{'k': 'd', 'v': d}])
return t
def back(self, d):
t = self.turtle_request('back', args=[{'k': 'd', 'v': d}])
return t
def goto(self, x, y):
t = self.turtle_request(
'goto', args=[{'k': 'x', 'v': x}, {'k': 'y', 'v': y}])
return t
def setx(self, x):
t = self.turtle_request('setx', args=[{'k': 'x', 'v': x}])
return t
def sety(self, y):
t = self.turtle_request('sety', args=[{'k': 'y', 'v': y}])
return t
def left(self, a):
t = self.turtle_request('left', args=[{'k': 'a', 'v': a}])
return t
def right(self, a):
t = self.turtle_request('right', args=[{'k': 'a', 'v': a}])
return t
def heading(self, a):
t = self.turtle_request('heading', args=[{'k': 'a', 'v': a}])
return t
def font(self, f):
t = self.turtle_request('font', args=[{'k': 'f', 'v': f}])
return t
def filltext(self, text):
t = self.turtle_request('filltext', args=[{'k': 'text', 'v': text}])
return t
def stroketext(self, text):
t = self.turtle_request('stroketext', args=[{'k': 'text', 'v': text}])
return t
def pencolour(self, r, g, b):
t = self.turtle_request('pencolour', [{
'k': 'r',
'v': r
}, {
'k': 'g',
'v': g
}, {
'k': 'b',
'v': b
}], True)
return t
def export_img(self, filename):
t = self.turtle_request(
'export_img', args=[{'k': 'filename', 'v': filename}])
return t
def canvas_size(self, width, height):
t = self.turtle_request('canvas_size', args=[
{'k': 'width', 'v': width},
{'k': 'height', 'v': height}])
return t
def create_turtle():
name = None
port = None
if len(sys.argv) > 1:
name = sys.argv[1]
if len(sys.argv) > 2:
port = sys.argv[2]
if port is not None:
t = Turtle(name, port=port)
builtins.t = t
else:
t = Turtle(name)
builtins.t = t
def penup():
return builtins.t.penup()
def pendown():
return builtins.t.pendown()
def penwidth(w):
return builtins.t.penwidth(w)
def stop():
return builtins.t.stop()
def state():
return builtins.t.state()
def home():
return builtins.t.home()
def clear():
return builtins.t.clear()
def forward(d):
return builtins.t.forward(d)
def back(d):
return builtins.t.back(d)
def goto(x, y):
return builtins.t.goto(x, y)
def setx(x):
return builtins.t.setx(x)
def sety(y):
return builtins.t.sety(y)
def left(a):
return builtins.t.left(a)
def right(a):
return builtins.t.right(a)
def heading(a):
return builtins.t.heading(a)
def font(f):
return builtins.t.font(f)
def filltext(text):
return builtins.t.filltext(text)
def stroketext(text):
return builtins.t.stroketext(text)
def pencolour(r, g, b):
builtins.t.pencolour(r, g, b)
def export_img(filename):
return builtins.t.export_img(filename)
def canvas_size(width, height):
return builtins.t.canvas_size(width, height)
if __name__ == "__main__":
# t = Turtle()
# t.penup()
# t.pendown()
# t.pencolour(0, 0, 255)
# for i in range(4):
# t.forward(50)
# t.right(90)
# t.stop()
download_picoturtle_web_canvas()
run_picoturtle_web_canvas()
<file_sep>/build.py
from pybuilder.core import use_plugin, init, Author
use_plugin("python.core")
use_plugin("python.unittest")
use_plugin("python.install_dependencies")
use_plugin("python.flake8")
#use_plugin("python.coverage")
use_plugin("python.distutils")
authors = [Author('<NAME>', '<EMAIL>')]
name = "pypicoturtle"
default_task = "publish"
version = "0.0.1"
license = "MIT"
summary = "PicoTurtle python client"
url = "https://github.com/abhishekmishra/pypicoturtle"
@init
def set_properties(project):
project.set_property("dir_source_main_python", "src")
project.set_property("dir_source_unittest_python", "test")
project.set_property("dir_source_main_scripts", "bin")
<file_sep>/README.md
# pypicoturtle
PicoTurtle client for python
|
e2274851d2956555eed66706fab4374da1ff7dee
|
[
"Markdown",
"Python"
] | 3
|
Python
|
abhishekmishra/pypicoturtle
|
b9d0640b1a6dde6876eee6664ec2c09ac8dfebf9
|
dcf2b1cd0bf9e1837ff13965397198f0774582d9
|
refs/heads/main
|
<file_sep>/*let a = +prompt("1")
let b = +prompt("2")
function pow(a, b) {
let result = a;
for (let i = 1; i < b; i++) {
result *= a
}
return result;
}
alert(pow(a,b))*/
/*function value(a){
let num = 1000;
a = num
while (num > 50) {
console.log(num)
num = num / 2;
}
return num;
}
console.log(value())*/
var x = 136;
console.log(Math.round(x / 10) * 10);<file_sep>/*
// 6
let month = prompt("Enter your number month");
let seasons = ['Winter', 'Spring', 'Summer', 'Autumn'];
if (month >= 1 && month <= 12){
alert ("Your season is " + seasons[Math.floor(month % 12 / 3)])
} else {alert("This month doesn`t exist")};
*/
/*
// 7
let a = Number(prompt("First number"));
let b = Number(prompt("Secont Number"));
if (a <= 1 && b > 5){
alert(a + b)
} else {
alert(a - b)
}
*/
/*
// 8
let amount = prompt("Enter product quantity");
let price = prompt("Enter price of product");
let sum = amount * price;
if (sum >= 500 && sum <= 499){
alert("To pay " + (sum * 0.98) + "$")
} else if (sum >= 800){
alert("To pay " + (sum * 0.97) + "$")
} else {
alert("You doesn`t have any discount")
}
*/
//9
let x = Number(prompt("Enter X"));
let y = Number(prompt("Enter Y"));
let r = Number(prompt("Enter R"));
let k = r * r;
let sum = (x*x + y*y);
if(k>=sum){
alert("The point belongs to the circle")
} else {
alert("Dot does not belong to the circle")
}
|
965e9d2f06a6d0f87fa4a00af7210af2cdef086d
|
[
"JavaScript"
] | 2
|
JavaScript
|
EnvyEternal/UserCardHomeWork
|
ef20f0468e0e658a1fa4006c62a3c7fff30c7e23
|
5a081c4b802808ea0c5e4454eaa317404dbc2f71
|
refs/heads/master
|
<file_sep>#
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'
use_frameworks!
target 'netronixgroup_test' do
pod 'Alamofire', '~> 4.6'
pod 'SwiftyJSON'
target 'netronixgroup_testTests' do
inherit! :search_paths
end
end
<file_sep>//
// Event.swift
// netronixgroup_test
//
// Created by <NAME> on 22/02/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import SwiftyJSON
struct Event {
var _id : String?
var measurements : Array<Array<Measurement>> = []
var name : String?
var unit : String?
mutating func mapping(json: SwiftyJSON.JSON) {
_id = json["_id"].string
measurements = []
for measurmentItem in json["measurements"].arrayValue {
var measurement = Measurement.init()
measurement.mapping(json: measurmentItem)
measurements.append([measurement])
}
name = json["name"].string
unit = json["unit"].string
}
struct Measurement {
var measurementValue: Array<String> = []
mutating func mapping(json: SwiftyJSON.JSON) {
measurementValue = []
for measurementValueItem in json.arrayValue {
measurementValue.append(String.init(describing: measurementValueItem.object))
}
}
}
}
<file_sep>//
// netronixgroup_testTests.swift
// netronixgroup_testTests
//
// Created by <NAME> on 22/02/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import XCTest
@testable import netronixgroup_test
@testable import SwiftyJSON
class netronixgroup_testTests: XCTestCase {
var event: Event!
override func setUp() {
super.setUp()
event = Event()
}
override func tearDown() {
super.tearDown()
event = nil
}
// MARK: Tests func
func testEventDataGoodStructure() {
// With perfect JSON model response
let json: JSON = ["name":"Temperature","unit":"℃","measurements":[[1519460317,5.043124756498185]],"_id":"5a911fdd21f2b200014a4683"]
checkEventModel(json: json)
}
func testEventDataNoMeasurements() {
// JSON model response missing Measurements array
let json: JSON = ["name":"Pressure","unit":"hPa","measurements":[],"_id":"5a911fdc21f2b200014a4601"]
checkEventModel(json: json)
}
func testEventDataWithoutUnit() {
// Test with JSON model response missing Unit value
let json: JSON = ["name":"Serial","measurements":[[1519460312,"0B100100"],[1519460313,"0B100100"],[1519460314,"0B100100"],[1519460315,"0B100100"],[1519460316,"0B100100"]],"_id":"5a911fdc21f2b200014a4602"]
checkEventModel(json: json)
}
func checkEventModel(json: JSON) {
event.mapping(json: json)
XCTAssertNotNil(event._id)
XCTAssert(event.measurements.count > 0)
XCTAssertNotNil(event.name)
XCTAssertNotNil(event.unit)
}
}
<file_sep>//
// APIManager.swift
// netronixgroup_test
//
// Created by <NAME> on 22/02/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import Alamofire
class APIManager: NSObject {
static let shared = APIManager()
// Basic request for reading stream
func requestStream(parameters: Parameters,
encoding: ParameterEncoding,
headers: HTTPHeaders,
method: HTTPMethod,
path: String,
successHandler: @escaping (Any) -> Void,
errorHandler: @escaping (Error) -> Void) {
let request = Alamofire.request(path, method: method, parameters: parameters, encoding: encoding, headers: headers)
request.stream { (streamResponse) in
successHandler(streamResponse)
}
request.responseData { response in
switch response.result {
case .success:
print("stream end successful")
case .failure(let error):
print(error)
errorHandler(error)
}
}
}
}
<file_sep>//
// EventCollectionViewCell.swift
// netronixgroup_test
//
// Created by <NAME> on 22/02/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class EventCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var labelName: UILabel!
@IBOutlet weak var labelMeasurements: UILabel!
@IBOutlet weak var labelUnit: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func configureCell(item: Event) {
self.labelName.text = item.name
var measurementsString = ""
for itemMeasurement in item.measurements {
for measurement in itemMeasurement {
measurementsString.append(measurement.measurementValue.joined(separator: ","))
}
measurementsString.append("\n")
}
self.labelMeasurements.text = measurementsString
self.labelUnit.text = item.unit
}
}
<file_sep>//
// APIManager+Methods.swift
// netronixgroup_test
//
// Created by <NAME> on 22/02/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Alamofire
import SwiftyJSON
private let kURLAPI = "https://jsdemo.envdev.io/"
private let kSsePath = "sse"
extension APIManager {
func sseRequest(parameters: [String : Any],
successHandler: @escaping (SwiftyJSON.JSON) -> Void,
errorHandler: @escaping (Error) -> Void) {
requestStream(parameters: parameters,
encoding: URLEncoding.default,
headers: [:],
method: .get,
path: kURLAPI + kSsePath,
successHandler: { (response) in
let utf8Text = String(data: response as! Data, encoding: .utf8)
let clearJsonString = utf8Text?.replacingOccurrences(of: "data: ", with: "")
let jsonData = (clearJsonString?.data(using: String.Encoding.utf8))!
do {
let json = try JSON(data: jsonData)
print(json)
successHandler(json)
return
}
catch {
errorHandler(NSError(domain:String(describing: self), code:0, userInfo:["Error parsing json" : "Error parsing json"]))
}
}, errorHandler: { (error) in
errorHandler(error)
})
}
}
<file_sep>Aptitude test for job applicants (iOS Developer) by [TestTask](https://github.com/netronixgroup/ios-dev/blob/master/TestTask.md)
## Setup & Run
To run this application you should do next steps:
1. Download ZIP of just clone repository by url
```
git clone https://github.com/romacv/netronixgroup_test.git
```
2. Open project file in XCode
```
netronixgroup_test.xcworkspace
```
3. Select netronixgroup_test target and any of simulator or real iOS Device
<img src="https://raw.githubusercontent.com/romacv/netronixgroup_test/master/Screen%20Shot%202018-02-24%20at%2015.52.18.png" width="320">
## Unit tests
Project contain unit test for validate JSON response.
For example it have 3 methods:
```
func testEventDataGoodStructure() - With perfect JSON model response
func testEventDataNoMeasurements() - JSON model response missing Measurements array
func testEventDataWithoutUnit() - // JSON model response missing Unit value
```
You can try to launch each or together from netronixgroup_testTests.swift file.
<img src="https://raw.githubusercontent.com/romacv/netronixgroup_test/master/Screen%20Shot%202018-02-24%20at%2015.59.07.png" width="320">
<file_sep>//
// ViewController.swift
// netronixgroup_test
//
// Created by <NAME> on 22/02/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
let cellId = "cell"
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var labelTop: UILabel!
var arrayEvents: Array<Event> = []
// MARK: Main
override func viewDidLoad() {
super.viewDidLoad()
setup()
loadData()
}
// MARK: Actions
func setup() {
collectionView.register(UINib.init(nibName: "EventCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: cellId)
collectionView.decelerationRate = UIScrollViewDecelerationRateFast
collectionView.reloadData()
}
func loadData() {
APIManager.shared.sseRequest(parameters: [:],
successHandler: { (response) in
let responseArray = response.arrayValue
for responseItem in responseArray {
var event = Event.init()
event.mapping(json: responseItem)
self.arrayEvents.append(event)
}
DispatchQueue.main.async {
self.labelTop.text = "Events count: \(self.arrayEvents.count.description)"
self.collectionView.reloadData()
}
},
errorHandler: { (error) in
print(error)
})
}
// MARK: Collection View
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrayEvents.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! EventCollectionViewCell
let item = arrayEvents[indexPath.row]
cell.configureCell(item: item)
return cell
}
}
|
6957d10e9bf6c5b4ac992ef92527eec2a5c0bb19
|
[
"Swift",
"Ruby",
"Markdown"
] | 8
|
Ruby
|
romacv/netronixgroup_test
|
4ca21600a1c6a5ef46b43dc39bc774e86155d4f6
|
6f6ba0352fad7b97b2b70a022efee720ab07402f
|
refs/heads/master
|
<file_sep>using Assets.Scripts;
using Pathfinding;
using UnityEngine;
using UnityEngine.AI;
public class Unit : MonoBehaviour
{
public AIPath AiPath { get; set; }
public Animator Animator { get; set; }
public Constants.UnitState UnitState;
void Start()
{
AiPath = GetComponent<AIPath>();
AiPath.constrainInsideGraph = true;
Animator = GetComponent<Animator>();
}
void Update()
{
if (Input.GetMouseButtonDown(Constants.RightMouseButton))
{
Move(this);
}
if (AiPath.remainingDistance < 2f && UnitState != Constants.UnitState.Idle)
{
UnitAnimator.Idle(Animator);
UnitState = Constants.UnitState.Idle;
Debug.Log("Stop");
}
if (AiPath.remainingDistance >= 2f && UnitState != Constants.UnitState.Moving)
{
UnitAnimator.Move(Animator);
UnitState = Constants.UnitState.Moving;
Debug.Log("Moving");
}
}
private static void Move(Unit unit)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Physics.Raycast(ray, out RaycastHit hit, 100);
unit.AiPath.destination = hit.point;
UnitAnimator.Move(unit.Animator);
unit.UnitState = Constants.UnitState.Moving;
Debug.Log("Move");
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace Assets.Scripts
{
public static class UnitAnimator
{
public static void Idle(Animator uniAnimator)
{
ClearAll(uniAnimator);
uniAnimator.SetBool("idle", true);
}
public static void Move(Animator uniAnimator)
{
ClearAll(uniAnimator);
uniAnimator.SetBool("walk", true);
}
private static void ClearAll(Animator unitAnimator)
{
unitAnimator.SetBool("idle", false);
unitAnimator.SetBool("walk", false);
unitAnimator.SetBool("attack_01", false);
unitAnimator.SetBool("die", false);
}
}
}
<file_sep>namespace Assets.Scripts
{
public static class Constants
{
public static readonly int LeftMouseButton = 0;
public static readonly int RightMouseButton = 1;
public enum UnitState
{
Idle,
Moving,
Attacking,
Dieing,
}
}
}
|
87854bcc4957113aee9a63989a99e8cf31f93c32
|
[
"C#"
] | 3
|
C#
|
richhildebrand/TD-RTS
|
47d52b6587bc7941f8f95f274881614fa19eb307
|
575cfab9ff1600ca7cdd0fa9b1047ce0533e9174
|
refs/heads/master
|
<file_sep>FROM node:latest
MAINTAINER Sneaker15 <<EMAIL>>
#Install libpcap-dev
RUN \
sed -i 's/# \(.*multiverse$\)/\1/g' /etc/apt/sources.list && \
apt-get update && \
apt-get -y upgrade && \
apt-get install -y \
libpcap-dev \
etherwake && \
apt-get clean && rm -rf /var/lib/apt/lists/*
VOLUME /usr/src/app
VOLUME /usr/src/app/config
WORKDIR /usr/src/app
# Install app dependencies
#-> part of the initialize script
# RUN npm install
CMD npm run start
<file_sep>#! /usr/bin/env bash
# pull dasher repository from github
docker run --rm -it -w /app -v $(pwd):/app travix/base-alpine-git git clone https://github.com/maddox/dasher.git
cp dasher/config/config.example.json config/config.example.json
# rebuild the image from Dockerfile
docker-compose build
# Install app dependencies
docker-compose run --rm -e restart=none dasher npm install
# start container
docker-compose up -d
<file_sep># docker-dasher
Dockerized (via docker-compose) version of [dasher](https://github.com/maddox/dasher). Credits go to <NAME> for his very helpful project!
# Prerequisites
Have docker and docker-compose installed
# Setup buttons
configure via `config/config.json`
see `config/config.example.json` for an example
# Linux
## Installation
`./initialize.sh`
## Find MAC address of Amazon button
`run ./findbutton.sh | grep Amazon`
## Uninstall
`./uninstall.sh`
# Windows
## Installation
`initialize.bat`
## Find MAC address of Amazon button (filtering tbd)
`findbutton.bat`
## Uninstall
`unistall.bat`
<file_sep>#! /usr/bin/env bash
docker-compose exec dasher node node_modules/node-dash-button/bin/findbutton
|
7efdd65b1457aa5d2d793aed352b38352a632dea
|
[
"Markdown",
"Dockerfile",
"Shell"
] | 4
|
Dockerfile
|
datenzar/docker-dasher
|
ab20851735eabaeb867c61d288621d415bd912d7
|
53db4e22c6e9e820511a1efa177d233e81ba5213
|
refs/heads/master
|
<file_sep>let auto = function() {
let me = {};
publicAPI();
//static method
function getRequiredLicenseCategory() {
return 'B';
}
function publicAPI() {
//default values for AUTO
me.maxSpeed = 100;
me.speed = 0;
me.speedUnit = 'km/h';
me.getSpeed = function () {
return me.speed;
};
me.setSpeed = function (_speed) {
me.speed = _speed;
};
me.turnEngineOn = function () {
me.isEngineOn = true;
};
me.turnEngineOff = function () {
me.isEngineOn = false;
};
me.isEngineOn = false;
me.pressKlaxon = function () {
console.log('Beeeep');
};
}
return me;
};
let cabriolet = function () {
let me = auto();
publicAPI();
function publicAPI() {
//extend AUTO class with some extra properties
me.roofCollapsed = false;
me.collapseRoof = function () {
me.roofCollapsed = true;
}
me.raiseRoof = function () {
me.roofCollapsed = false;
}
me.setSpeed = function (_speed) {
me.speed = _speed;
}
//overriding default values in auto class
me.speedUnit = 'mph';
me.maxSpeed = 150;
me.pressKlaxon = function () {
console.log('Fancy Beeeeeeep');
}
}
return me;
}
//create instances
let a = auto();
let c = cabriolet();
console.log(a);
console.log('auto Klaxon: ');
a.pressKlaxon();
console.log(c);
console.log('cabriolet Klaxon: ');
c.pressKlaxon();
|
c5275b79d729f00b414af28bc4e062b4d3232a97
|
[
"JavaScript"
] | 1
|
JavaScript
|
norb00/Functional_Pattern_in_OOP_homeTask
|
b1a28c339b10f88df786bb9f0a9ffb27ead7b2ef
|
f6ed527c59581193715e6ed16ad4d2e1fa86aaf1
|
refs/heads/master
|
<repo_name>gwicks/gmusicapi-curl<file_sep>/cplayer.cpp
#include <iostream>
#include <dirent.h>
#include <vector>
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string>
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <curl/curl.h>
#include <curses.h>
#include <menu.h>
#include <taglib/tag.h>
#include <taglib/fileref.h>
#include "GoogleMusicAPI.cpp"
void drawFrame(int,int,int,int);
void songSelect(int,int,Song,std::vector<Song>);
int mainMenu(int lastpos,int lastpg,bool doInit,std::vector<Song> lsongs)
{
std::vector<Song> testItems;
struct winsize w;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
int maxrows = w.ws_row;
int maxcols = w.ws_col;
maxrows = maxrows - 3;
maxcols = maxcols - 3;
if (doInit)
{
initscr();
start_color();
cbreak();
noecho();
intrflush(stdscr, false);
init_pair(1, COLOR_WHITE, COLOR_BLACK);
init_pair(2, COLOR_RED, COLOR_WHITE);
keypad(stdscr, true);
}
testItems = lsongs;
drawFrame(0,0,LINES-1,COLS-1);
move(1,1);
printw("NCPlayer");
int i = 0, ppos = 2;
if (testItems.size() <= maxrows)
{
for (i = 0; i < testItems.size(); i++)
{
mvprintw(ppos + i,1,testItems.at(i).title.c_str());
}
}
else
{
for (i = 0;i < maxrows; i++)
{
mvprintw(ppos + i,1,testItems.at(lastpg+i).title.c_str());
}
}
mvchgat(1,1,COLS-2,A_BOLD,1,NULL);
mvchgat(lastpos + 2,1,COLS-2,A_NORMAL,2,NULL);
bool done = false;
int pos = lastpos;
int startval = lastpg;
Song currsong = testItems.at(pos);
while (!done)
{
int ch = getch();
switch (ch)
{
case 24:
done = true;
break;
case '\n':
done = true;
songSelect(pos,startval,currsong,testItems);
break;
case KEY_UP:
if (pos > 0)
{
mvchgat(pos+2,1,COLS-2,A_NORMAL,1,NULL);
pos = pos - 1;
currsong = testItems.at(startval + pos);
mvchgat(pos+2,1,COLS-2,A_NORMAL,2,NULL);
}
break;
case KEY_DOWN:
if (pos < testItems.size() - 1 && pos <= maxrows - 2)
{
mvchgat(pos+2,1,COLS-2,A_NORMAL,1,NULL);
pos = pos + 1;
currsong = testItems.at(startval + pos);
mvchgat(pos+2,1,COLS-2,A_NORMAL,2,NULL);
}
break;
case KEY_NPAGE:
if (startval + pos < testItems.size())
{
startval = startval + 1;
char blank = ' ';
std::string clearStr = std::string(maxcols,blank);
for (i = 0;i < maxrows; i++)
{
mvprintw(ppos + i,1,clearStr.c_str());
mvprintw(ppos + i,1,testItems.at(startval+i).title.c_str());
currsong = testItems.at(startval + pos);
mvchgat(pos+2,1,COLS-2,A_NORMAL,2,NULL);
}
refresh();
}
break;
case KEY_PPAGE:
if (startval > 0)
{
startval = startval - 1;
char blank = ' ';
std::string clearStr = std::string(maxcols,blank);
for (i = 0;i < maxrows; i++)
{
mvprintw(ppos + i,1,clearStr.c_str());
mvprintw(ppos + i,1,testItems.at(startval+i).title.c_str());
currsong = testItems.at(startval + pos);
mvchgat(pos+2,1,COLS-2,A_NORMAL,2,NULL);
}
}
break;
}
refresh();
}
endwin();
return 0;
}
std::vector<Song> listMPG(char* dirname)
{
std::vector<Song> retVector;
DIR *dir;
struct dirent *ent;
if ((dir = opendir (dirname)) != NULL)
{
while ((ent = readdir (dir)) != NULL)
{
std::string tempstr = ent->d_name;
std::string temppath = dirname + tempstr;
if (tempstr.size() >= 4 && tempstr.substr(tempstr.size() - 4,4) == ".mp3")
{
TagLib::FileRef tempref (temppath.c_str());
TagLib::Tag *temptag = tempref.tag();
std::string temptitle = temptag->title().toCString();
std::string tempartist = temptag->artist().toCString();
std::string tempalbum = temptag->album().toCString();
std::string tempyear = boost::lexical_cast<std::string>(temptag->year());
Song tsong = Song(temptitle,tempartist,tempalbum,tempyear,"");
tsong.pathuri = temppath;
tsong.isStream = false;
retVector.push_back(tsong);
}
}
closedir (dir);
} else {
//printf("Cannot open");
}
return retVector;
}
std::string user = "";
std::string password = "";
std::string authToken = "";
std::string xtToken = "";
int main()
{
std::string doLogin = "y";
std::vector<Song> songs;
if (doLogin == "y")
{
std::cout << "Google Email: ";
std::cin >> user;
std::cout << "Google Password: ";
std::cin >> password;
authToken = getAuthToken(user,password);
xtToken = getXTCookie(authToken);
songs = getAllSongs(authToken,xtToken);
}
mainMenu(0,0,true,songs);
return 0;
}
void songSelect(int lpos,int pgpos,Song s,std::vector<Song> lastSongs)
{
erase();
drawFrame(0,0,LINES-1,COLS-1);
attron(A_BOLD);
mvprintw(1,1,"Title: %s",s.title.c_str());
mvprintw(2,1,"Artist: %s",s.artist.c_str());
mvprintw(3,1,"Album: %s",s.album.c_str());
mvprintw(4,1,"Year: %s",s.year.c_str());
attroff(A_BOLD);
mvprintw(5,1,"<Play>");
mvprintw(5,9,"<Back>");
bool isDone = false;
int mpos = 0;
mvchgat(5,1,6,A_NORMAL,2,NULL);
while (!isDone)
{
int ch = getch();
switch(ch)
{
case '\n':
if (mpos == 0)
{
std::string cmd = "";
if (s.isStream)
{
attron(A_BOLD);
mvprintw(6,1,"(Now Playing: Press Ctrl-C to Stop; Left and Right Arrows to Seek; Space to Pause)");
attroff(A_BOLD);
refresh();
playSong(getStreamURL(authToken,s.id));
mvprintw(6,1," ");
refresh();
}
else
{
cmd = "mpg123 -q -C '" + s.pathuri + "' > /dev/null/ 2&>1";
mvprintw(6,1,"Playing...");
refresh();
system(cmd.c_str());
mvprintw(6,1," ");
refresh();
}
}
else
{
isDone = true;
}
break;
case KEY_LEFT:
if (mpos == 0)
{
mpos = 1;
mvchgat(5,1,6,A_NORMAL,1,NULL);
mvchgat(5,9,6,A_NORMAL,2,NULL);
}
else
{
mpos = 0;
mvchgat(5,1,6,A_NORMAL,2,NULL);
mvchgat(5,9,6,A_NORMAL,1,NULL);
}
break;
case KEY_RIGHT:
if (mpos == 0)
{
mpos = 1;
mvchgat(5,1,6,A_NORMAL,1,NULL);
mvchgat(5,9,6,A_NORMAL,2,NULL);
}
else
{
mpos = 0;
mvchgat(5,1,6,A_NORMAL,2,NULL);
mvchgat(5,9,6,A_NORMAL,1,NULL);
}
break;
}
refresh();
}
erase();
mainMenu(lpos,pgpos,false,lastSongs);
}
void drawFrame(int startrow, int startcol, int endrow, int endcol) {
int saverow, savecol;
getyx(stdscr,saverow,savecol);
mvaddch(startrow,startcol,ACS_ULCORNER);
for (int i = startcol + 1; i < endcol; i++)
addch(ACS_HLINE);
addch(ACS_URCORNER);
for (int i = startrow +1; i < endrow; i++) {
mvaddch(i,startcol,ACS_VLINE);
mvaddch(i,endcol,ACS_VLINE);
}
mvaddch(endrow,startcol,ACS_LLCORNER);
for (int i = startcol + 1; i < endcol; i++)
addch(ACS_HLINE);
addch(ACS_LRCORNER);
move(saverow,savecol);
refresh();
}
<file_sep>/Makefile
CC = g++
CFLAGS = -c --std=c++11
LDFLAGS = -lcurses -lcurl -ljsoncpp -ltag
SOURCES=cplayer.cpp
EXECUTABLE = cplayer
all: cplayer
cplayer: cplayer.o
$(CC) cplayer.o -o cplayer $(LDFLAGS)
cplayer.o: cplayer.cpp
$(CC) $(CFLAGS) cplayer.cpp $(LDFLAGS)
<file_sep>/song.cpp
#include "song.hpp"
Song::Song (std::string t,std::string art,std::string alb,std::string yr,std::string i)
{
title = t;
artist = art;
album = alb;
year = yr;
id = i;
pathuri = "";
isStream = false;
}
std::string Song::getID()
{
return id;
}
<file_sep>/README.md
gmusicapi-curl
==============
A C++ implementation of the Google Music API using libcurl.
Prequisites (Base)
==============
Boost Libraries
Curl Development Libraries
TagLib Libraries
JsonCPP
Prequisites (CPlayer)
==============
Ncurses Development Libraries
mpg123
Installation/Usage
===================
To use this port, simply drop in the GoogleMusicAPI.cpp, song.cpp, and song.hpp files into your project.
cplayer.cpp is an example application that uses the API and is a good example of how to use it.
Issues
===================
Appears to have heavy issues compiling on FreeBSD for unknown reasons (possibly having to do with the port of JsonCPP).
<file_sep>/song.hpp
#include <iostream>
#include <string>
class Song
{
public:
std::string title,artist,album,year,id,pathuri;
bool isStream;
Song(std::string,std::string,std::string,std::string,std::string);
std::string getID();
bool operator< (const Song &other) const {
return title < other.title;
}
};
<file_sep>/GoogleMusicAPI.cpp
#include <stdio.h>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <curl/curl.h>
#include <jsoncpp/json/json.h>
#include "song.cpp"
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
std::string getAuthToken(std::string uname,std::string pass)
{
CURL *curl;
CURLcode res;
static std::string readBuffer;
struct curl_httppost *formpost = NULL;
struct curl_httppost *lastptr = NULL;
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if (curl)
{
curl_easy_setopt(curl, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
readBuffer.clear();
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl,CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(curl,CURLOPT_POST, 1);
std::string postData = "Email=" + uname + "&Passwd=" + pass + "&service=sj";
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postData.c_str());
curl_easy_setopt(curl, CURLOPT_COOKIEJAR, "cookies.dat");
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
curl_formfree(formpost);
}
std::vector<std::string> authArr;
boost::split(authArr,readBuffer,boost::is_any_of("\n"));
std::string authKey = authArr[2];
boost::replace_first(authKey,"Auth=","");
return authKey;
}
std::string getXTCookie(std::string authToken)
{
CURL *curlx;
CURLcode resx;
static std::string readBufferx;
struct curl_httppost *formpostx = NULL;
struct curl_httppost *lastptrx = NULL;
std::string headerText = "Authorization: GoogleLogin auth=" + authToken;
const char *header = headerText.c_str();
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers,header);
struct curl_slist *cookies;
curl_global_init(CURL_GLOBAL_ALL);
curlx = curl_easy_init();
if (curlx)
{
curl_easy_setopt(curlx, CURLOPT_URL, "https://play.google.com/music/listen?u=0");
curl_easy_setopt(curlx, CURLOPT_HTTPHEADER, headers);
readBufferx.clear();
curl_easy_setopt(curlx,CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curlx,CURLOPT_WRITEDATA, &readBufferx);
curl_easy_setopt(curlx,CURLOPT_HTTPGET, 1);
curl_easy_setopt(curlx, CURLOPT_COOKIEJAR, "cookies.dat");
resx = curl_easy_perform(curlx);
curl_formfree(formpostx);
}
CURLcode r = curl_easy_getinfo(curlx, CURLINFO_COOKIELIST,&cookies);
struct curl_slist *nc;
int i;
nc = cookies, i = 1;
std::string rawXT;
while (nc)
{
std::string currentData = nc->data;
if (boost::find_first(currentData,"xt"))
{
rawXT = currentData;
}
nc = nc->next;
i++;
}
std::vector<std::string> parsedCookie;
boost::split(parsedCookie,rawXT,boost::is_any_of("\t"));
std::string xtToken = parsedCookie[6];
curl_easy_cleanup(curlx);
return xtToken;
}
std::vector<Song> getAllSongs(std::string authToken,std::string xtToken)
{
CURL *curlt;
CURLcode rest;
static std::string readBuffert;
struct curl_httppost *formpostt = NULL;
struct curl_httppost *lastptrt = NULL;
std::string headerTextt = "Authorization: GoogleLogin auth=" + authToken;
const char *headert = headerTextt.c_str();
struct curl_slist *headerst = NULL;
headerst = curl_slist_append(headerst,headert);
curl_global_init(CURL_GLOBAL_ALL);
curlt = curl_easy_init();
if (curlt)
{
std::string argURL = "https://play.google.com/music/services/streamingloadalltracks?u=0&xt=" + xtToken + "==&format=jsarray";
curl_easy_setopt(curlt, CURLOPT_URL, argURL.c_str());
curl_easy_setopt(curlt, CURLOPT_HTTPHEADER, headerst);
readBuffert.clear();
curl_easy_setopt(curlt,CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curlt,CURLOPT_WRITEDATA, &readBuffert);
curl_easy_setopt(curlt,CURLOPT_HTTPGET, 1);
curl_easy_setopt(curlt, CURLOPT_COOKIEJAR, "cookies.dat");
rest = curl_easy_perform(curlt);
/* always cleanup */
curl_easy_cleanup(curlt);
curl_formfree(formpostt);
}
std::string songData = readBuffert;
std::size_t found = songData.find("<script type='text/javascript'>\nwindow.parent['slat_process']([");
songData = songData.substr(found+63);
std::size_t foundEnd = songData.find(");\nwindow.parent['slat_progress']");
songData = songData.substr(0,foundEnd);
while (boost::find_first(songData,",,"))
{
boost::replace_all(songData,",,",",");
}
int index = songData.rfind("]\n,");
songData = songData.substr(0,index);
songData = "{\"playlist\":" + songData + "]}";
Json::Value root;
Json::Reader reader;
bool parsedSuccess = reader.parse(songData,root,false);
if (not parsedSuccess)
{
std::cout << reader.getFormatedErrorMessages() << std::endl;
}
const Json::Value playlist = root["playlist"];
std::vector<Song> songArray;
for (unsigned int index=0; index < playlist.size() - 1;++index)
{
Json::Value currv = playlist[index];
int s = 0;
Song tempS ("","","","","");
tempS.title = currv[s+1].asString();
tempS.artist = currv[s+3].asString();
tempS.album = currv[s+4].asString();
if (currv[s+12].asInt() > 1000)
{
tempS.year = std::to_string(currv[s+12].asInt());
}
else
{
tempS.year = "????";
}
tempS.id = currv[s].asString();
tempS.isStream = true;
songArray.push_back(tempS);
}
std::sort(songArray.begin(), songArray.end());
return songArray;
}
std::string getStreamURL(std::string authToken,std::string id)
{
CURL *curlu;
CURLcode resu;
static std::string readBufferu;
struct curl_httppost *formpostu = NULL;
struct curl_httppost *lastptru = NULL;
std::string headerTextu = "Authorization: GoogleLogin auth=" + authToken;
const char *headeru = headerTextu.c_str();
struct curl_slist *headersu = NULL;
headersu = curl_slist_append(headersu,headeru);
curl_global_init(CURL_GLOBAL_ALL);
curlu = curl_easy_init();
if (curlu)
{
std::string argURLu = "https://play.google.com/music/play?u=0&songid=" + id + "&pt=e";
curl_easy_setopt(curlu, CURLOPT_URL, argURLu.c_str());
curl_easy_setopt(curlu, CURLOPT_HTTPHEADER, headersu);
readBufferu.clear();
curl_easy_setopt(curlu,CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curlu,CURLOPT_WRITEDATA, &readBufferu);
curl_easy_setopt(curlu,CURLOPT_HTTPGET, 1);
curl_easy_setopt(curlu, CURLOPT_COOKIEFILE, "cookies.dat");
resu = curl_easy_perform(curlu);
/* always cleanup */
curl_easy_cleanup(curlu);
curl_formfree(formpostu);
}
//std::cout << readBufferu << std::endl;
Json::Value root;
Json::Reader reader;
bool parsedSuccess = reader.parse(readBufferu,root,false);
const Json::Value url = root["url"];
std::string finalURL = url.asString();
boost::replace_first(finalURL, "https", "http");
return finalURL;
}
void playSong(std::string surl)
{
std::string cmd = "mpg123 -q -C '" + surl + "' > /dev/null 2>&1";
system(cmd.c_str());
}
|
c6b6e7f18613855249a1508fc0cdfa9319094324
|
[
"Markdown",
"Makefile",
"C++"
] | 6
|
C++
|
gwicks/gmusicapi-curl
|
070da1b516230a3b151e81f1a626c4623b1fd40c
|
51dfcaff78e27b4ad414ab565e6b00701659d6f2
|
refs/heads/master
|
<repo_name>shilliscmu/GRU_By_Hand<file_sep>/gru.py
import torch
import torch.nn as nn
import numpy as np
import itertools
class Sigmoid:
"""docstring for Sigmoid"""
def __init__(self):
pass
def forward(self, x):
self.res = 1/(1+np.exp(-x))
return self.res
def backward(self):
return self.res * (1-self.res)
def __call__(self, x):
return self.forward(x)
class Tanh:
def __init__(self):
pass
def forward(self, x):
self.res = np.tanh(x)
return self.res
def backward(self):
return 1 - (self.res**2)
def __call__(self, x):
return self.forward(x)
class GRU_Cell:
"""docstring for GRU_Cell"""
def __init__(self, in_dim, hidden_dim):
self.d = in_dim
self.h = hidden_dim
h = self.h
d = self.d
self.Wzh = np.random.randn(h,h)
self.Wrh = np.random.randn(h,h)
self.Wh = np.random.randn(h,h)
self.Wzx = np.random.randn(h,d)
self.Wrx = np.random.randn(h,d)
self.Wx = np.random.randn(h,d)
self.dWzh = np.zeros((h,h))
self.dWrh = np.zeros((h,h))
self.dWh = np.zeros((h,h))
self.dWzx = np.zeros((h,d))
self.dWrx = np.zeros((h,d))
self.dWx = np.zeros((h,d))
self.z_act = Sigmoid()
self.r_act = Sigmoid()
self.h_act = Tanh()
def forward(self, x, h):
# input:
# - x: shape(input dim), observation at current time-step
# - h: shape(hidden dim), hidden-state at previous time-step n
#
# output:
# - h_t: hidden state at current time-step
# reset gate
# r = self.r_act(np.matmul(self.Wrh, h) + np.matmul(self.Wrx, x))
# # input gate
# z = self.z_act(np.matmul(self.Wzh, h) + np.matmul(self.Wzx, x))
# # update gate
# g = self.h_act(np.matmul(self.Wh , (r * h)) + np.matmul(self.Wx, x))
# # output gate
# return (1 - z) * h + z * g
self.x = x
self.htminus1 = h
self.rt = self.r_act(self.Wrh @ self.htminus1 + self.Wrx @ self.x)
self.zt = self.z_act(self.Wzh @ self.htminus1 + self.Wzx @ self.x)
self.htilde = self.h_act(self.Wh @ (self.rt * self.htminus1) + self.Wx @ self.x)
self.h = (1 - self.zt) * self.htminus1 + self.zt * self.htilde
return self.h
def backward(self, delta):
# input:
# - delta: shape(hidden dim), summation of derivative wrt loss from next layer at
# same time-step and derivative wrt loss from same layer at
# next time-step
#
# output:
# - dx: Derivative of loss wrt the input x
# - dh: Derivative of loss wrt the input hidden h
# dLoss_dX
dHt_dHtilde = delta * self.zt
dHtilde_dX = self.h_act.backward()
dHt_dZt = delta * (self.htilde - self.htminus1)
dZt_dX = np.reshape(self.z_act.backward(), (1, self.h.size))
dHtilde_dRt = np.reshape(self.h_act.backward(), (1, self.h.size))
dRt_dX = np.reshape(self.r_act.backward(), (1, self.h.size))
dLoss_dX = ((dHt_dHtilde * dHtilde_dX) @ self.Wx) + ((dHt_dZt * dZt_dX) @ self.Wzx) + ((dHt_dHtilde * dHtilde_dRt) @ self.Wh) * self.htminus1 * dRt_dX @ self.Wrx
# dLoss_dHtminus
dHt_dHtminus1 = (1 - self.zt) * delta
# dLoss_dHtminus1 = dHt_dHtminus1 + dHt_dHtilde * dHtilde_dHtminus1 @ self.Wh + dHt_dZt * dZt_dHtminus1 @ self.Wzh + ((dHt_dHtilde * dHtilde_dRt) @ self.Wh) * dRt_dHtminus1 @ self.Wrh
dLoss_dHtminus1 = ((dHt_dZt * dZt_dX) @ self.Wzh) + (((dHt_dHtilde * dHtilde_dRt) @ self.Wh) * self.htminus1 * dRt_dX @ self.Wrh) + dHt_dHtminus1 + (((dHt_dHtilde * dHtilde_dRt) @ self.Wh) * self.rt)
# weights
dZt_dWzh = self.z_act.backward()
dRt_dWrh = self.r_act.backward()
dHtilde_dWh = self.h_act.backward()
dRt_dWrx = self.r_act.backward()
dZt_dWzx = self.z_act.backward()
dHtilde_dWx = self.h_act.backward()
# self.dWzh = (dHt_dZt * dZt_dWzh) @ self.htminus1
self.dWzh = np.reshape((dHt_dZt * dZt_dWzh), (self.h.size, 1)) @ np.reshape(self.htminus1, (1, self.h.size))
# self.dWrh = ((dHt_dHtilde * dHtilde_dRt) @ self.Wh) * self.htminus1 * dRt_dWrh @ self.htminus1
self.dWrh = (np.reshape(((dHt_dHtilde * dHtilde_dRt) @ self.Wh) * self.htminus1 * dRt_dWrh, (self.h.size, 1)) @ np.reshape(self.htminus1, (1, self.h.size)))
# self.dWh = dHt_dHtilde @ self.htminus1
self.dWh = np.reshape(dHt_dHtilde * dHtilde_dWh, (self.h.size, 1)) @ np.reshape(self.rt * self.htminus1, (1, self.h.size))
# self.dWzx = ((dHt_dZt * dZt_dWzx) @ self.x)
self.dWzx = np.reshape(dHt_dZt * dZt_dWzx, (self.h.size, 1)) @ np.reshape(self.x, (1, self.x.size))
# self.dWrx = ((dHt_dHtilde * dHtilde_dRt) @ self.Wh) * self.htminus1 * dRt_dWrx @ self.x
self.dWrx = np.reshape(((dHt_dHtilde * dHtilde_dRt) @ self.Wh) * self.htminus1 * dRt_dWrx, (self.h.size, 1)) @ np.reshape(self.x, (1, self.x.size))
# self.dWx = (dHt_dHtilde * dHtilde_dWx) @ self.x
self.dWx = np.reshape((dHt_dHtilde * dHtilde_dWx), (self.h.size, 1)) @ np.reshape(self.x, (1, self.x.size))
return dLoss_dX, dLoss_dHtminus1
def test():
gru = GRU_Cell(3, 4)
x = np.array([2, 4, 6])
h = np.array([3, 5, 7, 9])
gru.forward(x, h)
delta = np.array([[0.52057634, -1.14434139, 1, 1]])
gru.backward(delta)
if __name__ == '__main__':
test()
<file_sep>/README.md
# GRU_By_Hand
Numpy implementation of a GRU Cell
|
6bbf1c9cd0c48723dc9d4df1ce80021944d4da34
|
[
"Markdown",
"Python"
] | 2
|
Python
|
shilliscmu/GRU_By_Hand
|
161325d9883e741d740d1a7925b6e326de112120
|
b9623b1f253925f8f79c7cfd7affd820b755ee4a
|
refs/heads/master
|
<file_sep># Inspired by
https://cloud.google.com/asset-inventory/docs/monitoring-asset-changes<file_sep>using System;
namespace GCPFunctionsX.Utilities
{
public class TimeMachine
{
/// <summary>
/// Gets the time right now formatted as a long date string
/// </summary>
/// <returns></returns>
public string Now()
{
return DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt");
}
}
}<file_sep>#!/bin/sh
terraform destroy --auto-approve
rm -rf .terraform
rm terraform.tfplan*
rm terraform.tfstate*<file_sep>const fs = require('fs')
const request = require('request')
const JiraService = require('./lib/jira-service')
const JIRATemplates = require('./lib/jira-templates')
const util = require('util')
function configureLogger() {
const log4js = require('log4js')
log4js.configure({
appenders: { gappend: { type: 'file', filename: 'execution.log' } },
categories: { default: { appenders: ['gappend'], level: 'error' } },
})
const logger = log4js.getLogger()
logger.category = 'gcp-demos/jira-workflow'
logger.level = 'debug'
return logger
}
function main() {
let logger = configureLogger()
logger.debug('Beginning Execution')
let jiraService = new JiraService(process.env.AUTH_SECRET)
// jiraService.getJiras(function (error, response, body) {
// if (error) throw new Error(error)
// logger.debug(JSON.stringify(body))
// })
// let res = jiraService.getJira('GOOG-1')
// res.then(function(response) {
// logger.debug(response)
// console.log(util.inspect(response.data))
// })
let data = JIRATemplates.default
jiraService.createJira(data)
}
if (require.main === module) {
main()
}
<file_sep># GCP Functions: PubSub
## Deployments
### PubSub Publisher
gcloud functions deploy pubsub-message-publisher --entry-point GCPFunctionsX.MessagePublisher --runtime dotnet3 --trigger-http --allow-unauthenticated
### PUBSUB: Hello Pub/Sub debugger
gcloud functions deploy hello-cloudevent-pubsub-function2 --runtime dotnet3 --entry-point HelloCloudEventPubSubFunction.Function --trigger-topic cloud-functions-topic --allow-unauthenticated
### PUBSUB: Responder
gcloud functions deploy pubsub-responder --runtime dotnet3 --entry-point GCPFunctionsX.PubSubResponder --trigger-topic cloud-functions-topic --allow-unauthenticated
### Firewall Destroyer
gcloud functions deploy firewall-destroyer --runtime dotnet3 --entry-point GCPFunctionsX.FirewallDestroyer --trigger-topic cloud-functions-topic --quiet
## Testing
### PUBSUB VERIFY
TOPIC_NAME="cloud-functions-topic"
for i in {1..5};
do
gcloud pubsub topics publish ${TOPIC_NAME} --message="Hello World ${i}"
done
for i in {1..5};
do
gcloud functions logs read hello-cloudevent-pubsub-function
done
### PUBSUB INSTANCE FIND AND DELETE FUNCTION. Create 25 instances, because they contain the word instance in it, they should be deleted.
```bash
#!/usr/bin/env bash
PROJECT_ID=$(gcloud config get-value project)
PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format="get(projectNumber)")
for i in {1..25};
do
gcloud beta compute --project=$PROJECT_ID instances create instance-${i} --zone=us-central1-a --machine-type=e2-medium --subnet=default --network-tier=PREMIUM --maintenance-policy=MIGRATE --service-account=${PROJECT_NUMBER}-compute<EMAIL> --scopes=https://www.googleapis.com/auth/devstorage.read_only,https://www.googleapis.com/auth/logging.write,https://www.googleapis.com/auth/monitoring.write,https://www.googleapis.com/auth/servicecontrol,https://www.googleapis.com/auth/service.management.readonly,https://www.googleapis.com/auth/trace.append --image=debian-10-buster-v20210512 --image-project=debian-cloud --boot-disk-size=10GB --boot-disk-type=pd-balanced --boot-disk-device-name=instance-1 --no-shielded-secure-boot --shielded-vtpm --shielded-integrity-monitoring --reservation-affinity=any &
sleep 0.5
done
```
<file_sep>#!/usr/bin/env bash
PROJECT_ID=$(gcloud config get-value project)
while true
do
./sub-pull.sh
printf "\n"
sleep 5
done<file_sep># GIT Secrets
## Overview
* Prevent Service Account JSON Key File accidental commit/upload
## Getting Started
Installation
```bash
./install.osx.git-secrets.sh
```
### Adding Git Secrets
```bash
git secrets --add 'private_key"'
```
### Removing Git Secrets
```bash
vi ../.git/config # remove lines under [secrets]
```
### Bypassing Git Secrets on Commit
Bypassing the warning on a `git commit`
```bash
git commit -m "Message" --no-verify
```
## Reference
For Mac OSX:
* [Reference](https://github.com/awslabs/git-secrets#installing-git-secrets)
* [Reference](https://cloud.google.com/blog/products/gcp/help-keep-your-google-cloud-service-account-keys-safe)
<file_sep>#!/bin/bash
PROJECT_ID=$(gcloud config get-value project)
function init() {
[ ! -d "policy-library" ] && git clone https://github.com/GoogleCloudPlatform/policy-library
}
init
terraform plan -var-file=terraform.tfvars -out my.tfplan
terraform show -json ./my.tfplan > ./tfplan.json
gcloud beta terraform vet tfplan.json --policy-library policy-library
VIOLATIONS=$(gcloud beta terraform vet tfplan.json --policy-library=policy-library --format=json)
retVal=$?
if [ $retVal -eq 2 ]; then
# Optional: parse the VIOLATIONS variable as json and check the severity level
echo "$VIOLATIONS"
echo "Violations found; not proceeding with terraform apply"
exit 1
fi
if [ $retVal -ne 0]; then
echo "Error during gcloud beta terraform vet; not proceeding with terraform apply"
exit 1
fi
echo "No policy violations detected; proceeding with terraform apply"
terraform apply --auto-approve
<file_sep># GCS - Kitchen and Inspec
## Prerequisites
* Terraform v0.11.x (latest is v0.11.14)
* Ruby
* Inspec
* Kitchen-Terraform
## Getting Started
```bash
# you would need to install ruby first
gem install inspec -v 2.3.28 --no-document
gem install kitchen-terraform -v 4.8.1 --no-document
# inspec and kitchen need to be accessible via your PATH
```
## Running
```bash
kitchen list # overall status
kitchen create
kitchen converge
kitchen verify
# this will FAIL and is hard-coded to have buckets exist in us-central1
```
## References
* [Inspec GCP Resources](https://github.com/inspec/inspec-gcp/tree/master/docs/resources)
<file_sep>using Google.Apis.Auth.OAuth2;
using System.Threading.Tasks;
namespace GCPFunctionsX.Utilities
{
public interface ITokenService
{
Task<string> GetBearerToken(string audience);
}
public class TokenService : ITokenService
{
public async Task<string> GetBearerToken(string audience)
{
// get bearer token
var oidcToken = await GoogleCredential
.GetApplicationDefault()
.GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience(audience));
var token = await oidcToken.GetAccessTokenAsync();
return token;
}
}
}
<file_sep>#!/usr/bin/env bash
brew install git-secrets
git secrets --install
git secrets --add 'private_key"'
git secrets --add 'private_key_id"'
<file_sep>{
"description": "Can perform builds",
"etag": "AA==",
"includedPermissions": [
"artifactregistry.aptartifacts.create",
"artifactregistry.dockerimages.get",
"artifactregistry.dockerimages.list",
"artifactregistry.files.get",
"artifactregistry.files.list",
"artifactregistry.locations.get",
"artifactregistry.locations.list",
"artifactregistry.packages.get",
"artifactregistry.packages.list",
"artifactregistry.repositories.downloadArtifacts",
"artifactregistry.repositories.get",
"artifactregistry.repositories.list",
"artifactregistry.repositories.listEffectiveTags",
"artifactregistry.repositories.listTagBindings",
"artifactregistry.repositories.uploadArtifacts",
"artifactregistry.tags.create",
"artifactregistry.tags.get",
"artifactregistry.tags.list",
"artifactregistry.tags.update",
"artifactregistry.versions.get",
"artifactregistry.versions.list",
"artifactregistry.yumartifacts.create",
"cloudbuild.builds.create",
"cloudbuild.builds.get",
"cloudbuild.builds.list",
"cloudbuild.builds.update",
"cloudbuild.workerpools.use",
"containeranalysis.occurrences.create",
"containeranalysis.occurrences.delete",
"containeranalysis.occurrences.get",
"containeranalysis.occurrences.list",
"containeranalysis.occurrences.update",
"logging.logEntries.create",
"logging.logEntries.list",
"logging.privateLogEntries.list",
"logging.views.access",
"pubsub.topics.create",
"pubsub.topics.publish",
"remotebuildexecution.blobs.get",
"resourcemanager.projects.get",
"resourcemanager.projects.list",
"source.repos.get",
"source.repos.list",
"storage.buckets.create",
"storage.buckets.get",
"storage.buckets.list",
"storage.objects.create",
"storage.objects.delete",
"storage.objects.get",
"storage.objects.list",
"storage.objects.update"
],
"name": "roles/cloudbuild.builds.builder",
"stage": "GA",
"title": "Cloud Build Service Account"
}
<file_sep># Docker Samples
```bash
cd ls/
./build.sh
docker run ls:latest
cd source-env/
./build.sh
docker run source-env:latest
cd inject-env/
./build.sh
docker run --env EXTERNAL_APP=MYAPP inject-env:latest
```
<file_sep># IAM Role Fetch
Awesome script by https://github.com/jdyke/gcp_iam_update_bot
## Getting Started
```bash
./run.sh
```<file_sep>#!/bin/sh
docker build --tag source-env .
<file_sep>using System;
namespace GCPFunctionsX.Utilities
{
public class LogWriter
{
public void Log(string msg)
{
Console.WriteLine(msg);
}
}
}<file_sep>#!/bin/sh
dotnet new mvc -o HelloWorldAspNetCore
cd HelloWorldAspNetCore
dotnet run --urls=http://localhost:8080
dotnet publish -c Release
cd bin/Release/netcoreapp3.0/publish/
<file_sep>#!/bin/bash
PROJECT_ID=$(gcloud config get-value project)
terraform plan -var-file=terraform.tfvars -out my.tfplan
echo "Running terraform-validator..."
RES=$(terraform-validator validate my.tfplan --project $PROJECT_ID --policy-path=../policy-library/ 2> /dev/null)
if [ "$RES" = "No violations found." ]; then
echo "Running terraform apply"
terraform apply my.tfplan
else
RED='\033[0;31m'
NC='\033[0m'
printf "${RED}Error: ${RES[@]}${NC}"
fi
<file_sep>#!/bin/bash
set -x
PROJECT_ID=$(gcloud config get-value project)
function init() {
gcloud services enable cloudasset.googleapis.com --project $PROJECT_ID
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member "user:$(gcloud config get-value account)" \
--role "roles/cloudasset.owner"
gcloud pubsub topics create cai-rt-feed --project $PROJECT_ID
gcloud beta services identity create \
--service=cloudasset.googleapis.com \
--project=$PROJECT_ID
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member=serviceAccount:service-$(gcloud projects describe $PROJECT_ID --format="get(projectNumber)")@gcp-sa-cloudasset.iam.gserviceaccount.com \
--role=roles/cloudasset.serviceAgent
# create feed
FEED_ID="test-feed"
gcloud asset feeds create $FEED_ID \
--project=$PROJECT_ID \
--content-type=resource \
--asset-types="storage.googleapis.com/Bucket" \
--pubsub-topic="projects/$PROJECT_ID/topics/cai-rt-feed"
gcloud asset feeds describe $FEED_ID --project=$PROJECT_ID
gcloud pubsub subscriptions create cai-rt-subscription \
--topic cai-rt-feed \
--project $PROJECT_ID
}
init
<file_sep>#!/bin/sh
sudo bash -c 'cat << EOF > /usr/local/bin/gs
git status
EOF'
sudo chmod +x /usr/local/bin/gs
sudo bash -c 'cat << EOF > /usr/local/bin/gb
git branch
EOF'
sudo chmod +x /usr/local/bin/gb
sudo bash -c 'cat << EOF > /usr/local/bin/gpm
git push -u origin master
EOF'
sudo chmod +x /usr/local/bin/gpm
sudo bash -c 'cat << EOF > /usr/local/bin/gc
git commit -m "\$1"
EOF'
sudo chmod +x /usr/local/bin/gc
<file_sep>FROM mcr.microsoft.com/dotnet/core/aspnet:3.0
ADD ./ /app
ENV ASPNETCORE_URLS=http://*:${PORT}
WORKDIR /app
ENTRYPOINT [ "dotnet", "HelloWorldAspNetCore.dll"]
<file_sep># Terraform - Config Validator Demo
A simple set of demos, showcasing a few use cases around using `gcloud terraform vet`:
1. All GCS buckets deployed SHALL NOT be in the US
2. Change the property, ".parameters.locations" in policy-library/constraints/storage_location.yaml to 'US' to allow bucket deploy
```bash
cat > policy-library/constraints/storage_location.yaml <<EOF
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
apiVersion: constraints.gatekeeper.sh/v1alpha1
kind: GCPStorageLocationConstraintV1
metadata:
name: allow_some_storage_location
annotations:
description: Checks Cloud Storage bucket locations against allowed or disallowed
locations.
bundles.validator.forsetisecurity.org/healthcare-baseline-v1: security
spec:
severity: high
match:
target: # {"$ref":"#/definitions/io.k8s.cli.setters.target"}
- "organizations/**"
parameters:
mode: "allowlist"
locations:
- asia-southeast1
exemptions: []
EOF
```
## Getting Started
1. Set your your application-default credentials to an account that has access to provision via terraform
```gcloud auth application-default login```
2. **Run Terraform Vet**
```./apply.sh```
3. Verify
```gsutil ls -p $PROJECT_ID```
4. Destroy
```./destroy.sh```
## Package
Zip
```zip -r tfdemo.zip .```
## Updating a Constraint
1. Constraints are located in the ../../policy-library - WHERE do we get this?
```cat ../../policy-library/policies/constraints/storage_location.yaml``` - BUCKETS are only allowed in ASIA-SOUTHEAST1?
2. Now... what if we update the bucket location to the US...
## References
## Resources
* https://cloud.google.com/docs/terraform/policy-validation/validate-policies
### Legacy
* [Forseti Security Slides](https://docs.google.com/presentation/d/18HUHWppc4GFbK5fhe7kQfeOg_bk0XUzqTFG6v55XfVk/edit#slide=id.p)
* [Installing Terraform Validator](https://github.com/GoogleCloudPlatform/terraform-validator)
* git clone and run `go install .` then copy the binary 'sudo cp terraform-validator /usr/local/bin/')
```bash
RES=$(terraform-validator validate my.tfplan --project $PROJECT_ID --policy-path=../../policy-library/ 2> /dev/null)
echo $RES
if [ "$RES" = "No violations found." ]; then
terraform apply my.tfplan
else
RED='\033[0;31m'
NC='\033[0m'
printf "${RED}Error: ${RES[@]}${NC}"
fi
```<file_sep>#!/bin/sh
## Mac OSX
# Get Terraform v0.12.14
curl -O https://releases.hashicorp.com/terraform/0.12.14/terraform_0.12.14_darwin_amd64.zip
unzip terraform_0.12.14_darwin_amd64.zip
chmod +x terraform
./terraform --version # should equal 0.12.14
rm terraform_0.12.14_darwin_amd64.zip
# Get Terraform Validator (https://github.com/forseti-security/policy-library/blob/master/docs/user_guide.md#how-to-use-terraform-validator)
gsutil cp gs://terraform-validator/releases/2019-11-07/terraform-validator-darwin-amd64 .
chmod 755 terraform-validator-darwin-amd64
<file_sep>#!/usr/bin/env bash
mkdir -p roles
rm -f roles/*
for i in $(gcloud iam roles list --filter='etag:AA==' --format json | jq -r '.[].name'); do
echo -n "Describing ${i} ..."
gcloud iam roles describe "${i}" --format json > "${i}"
echo "done."
done
<file_sep>FROM debian:stable-slim
LABEL MAINTAINER="<NAME> <<EMAIL>>"
CMD echo "$EXTERNAL_APP"
<file_sep>const request = require('request')
const axios = require('axios')
class JiraService {
constructor(authorization) {
this._authorization = authorization
}
/**
* @param {string} jiraId - The JIRA Project combined with the JIRA Number (CLOUD-12345)
*/
async getJiras(cb) {
let options = {
method: 'GET',
url: 'https://gwongclouddev.atlassian.net/rest/api/2/search',
headers: {
'cache-control': 'no-cache',
authorization: this._authorization,
},
}
request(options, cb)
}
/**
* @param {string} jiraId - The JIRA Project combined with the JIRA Number (CLOUD-12345)
*/
async getJira(jiraId) {
let url = `https://gwongclouddev.atlassian.net/rest/api/2/issue/${jiraId}`
let result = await axios.get(url, {
headers: {
'Content-Type': 'application/json',
Authorization: this._authorization,
},
})
return result
}
/**
* @param cb {function(error, response)} - callback fn
*/
getJiraByJql(jql, cb) {
var options = {
method: 'GET',
url: `https://gwongclouddev.atlassian.net/rest/api/2/search?jql=${jql}`,
headers: {
Authorization: this._authorization,
},
}
request(options, cb)
}
/**
* @param {} data - The JIRA ticket data to create
*/
async createJira(data) {
let url = 'https://gwongclouddev.atlassian.net/rest/api/2/issue'
let options = {
headers: {
Authorization: this._authorization,
'content-type': 'application/json',
},
}
return await axios.post(url, data, options)
}
/**
* @param {} jiraId - The JIRA Project combined with the JIRA Number (CLOUD-12345)
* @param {} cb - The call back function
*/
async approveJira(jiraId, cb) {
let url = `https://gwongclouddev.atlassian.net/rest/api/2/issue/${jiraId}/comment`
let options = {
headers: {
Authorization: this._authorization,
'content-type': 'application/json',
},
}
let data = {
body: 'Approved',
}
return await axios.post(url, data, options)
}
/**
* @param {} jiraId - The JIRA Project combined with the JIRA Number (CLOUD-12345)
* @param {} cb - The call back function
*/
async reassignJira(jiraId, assignee, cb) {
let url = `https://gwongcloudev.atlassian.net/rest/api/2/issue/${jiraId}`
let options = {
headers: {
Authorization: this._authorization,
'content-type': 'application/json',
},
}
let data = {
fields: {
assignee: {
name: assignee,
},
},
}
return await axios.put(url, data, options)
}
/**
* @param {} jiraId
* @param {} cb
*/
async assignJiraToGarrett(jiraId, cb) {
return await this.reassignJira(jiraId, 'garrettwong', cb)
}
/**
* @param {} jiraId
* @param {} cb
*/
async assignJiraToGarrettsAutomation(jiraId, cb) {
return await this.reassignJira(jiraId, 'garrettwong', cb)
}
}
module.exports = JiraService
<file_sep>FROM debian:stable-slim
LABEL MAINTAINER="<NAME> <<EMAIL>>"
# setup workdir
RUN mkdir -p /root/garrettwong
WORKDIR /root/garrettwong
COPY . .
CMD ls<file_sep>#!/bin/sh
PROJECT_ID="sandbox-0700"
gsutil mb -p $PROJECT_ID gs://garrettwong-terraform-testing
gcloud iam service-accounts create tf-project-account --project $PROJECT_ID
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member=serviceAccount:tf-project-account@$PROJECT_ID.iam.gserviceaccount.com \
--role=roles/editor
<file_sep># JIRA API
## Getting Started
1. Ensure that you have configured your own JIRA Cloud tenant. [Atlassian Admin](https://admin.atlassian.com/)
2. Create a JIRA Project
3. [Generate a JIRA API Key](https://id.atlassian.com/manage-profile/security/api-tokens)
4. Create the file below, which is already .gitignored.
5. Ensure that it is exported as an ENV variable.
```bash
# Create file using JIRA API KEY from https://id.atlassian.com/manage-profile/security/api-tokens
cat > ../JIRA.SECRET <<EOF
[YOUR_JIRA_API_KEY]
EOF
export AUTH_SECRET="$(cat ../JIRA.SECRET)"
npm i
# RUN CORE APP
node app.js
# RUN TEST
node tests/createJira.test.js
```
<file_sep>const JiraService = require('../lib/jira-service.js');
const JIRATemplates = require('../lib/jira-templates.js');
(async () => {
try {
let jiraService = new JiraService(process.env.AUTH_SECRET)
let a = await jiraService.createJira(JIRATemplates.default)
console.log(a)
console.log('testing')
await jiraService.approveJira(a.data.key);
console.log('comment that says: approved')
} catch (e) {
// Deal with the fact the chain failed
console.log('fail', e)
}
})();<file_sep>FROM debian:stable-slim
LABEL MAINTAINER="<NAME> <<EMAIL>>"
RUN rm /bin/sh && ln -s /bin/bash /bin/sh
# setup workdir
RUN mkdir -p /root/garrettwong
WORKDIR /root/garrettwong
COPY . .
ENV ENVIRONMENT "TEST"
ENV APP "APP"
CMD echo "$APP:$ENVIRONMENT"
<file_sep>using Google.Apis.Auth.OAuth2;
using Google.Apis.Compute.v1;
using Google.Apis.Services;
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;
namespace GCPFunctionsX.Utilities
{
public class ComputeEngineService
{
public void DeleteInstance(string projectId, string instance, string zone)
{
ComputeService computeService = new ComputeService(new BaseClientService.Initializer
{
HttpClientInitializer = GetCredential(),
ApplicationName = "Google-ComputeSample/0.1",
});
InstancesResource.DeleteRequest request = computeService.Instances.Delete(projectId, zone, instance);
// To execute asynchronously in an async method, replace `request.Execute()` as shown:
var response = request.Execute();
// Data.Operation response = await request.ExecuteAsync();
// TODO: Change code below to process the `response` object:
Console.WriteLine(JsonConvert.SerializeObject(response));
}
public static GoogleCredential GetCredential()
{
GoogleCredential credential = Task.Run(() => GoogleCredential.GetApplicationDefaultAsync()).Result;
if (credential.IsCreateScopedRequired)
{
credential = credential.CreateScoped("https://www.googleapis.com/auth/cloud-platform");
}
return credential;
}
}
}<file_sep>#!/bin/bash
set -x
PROJECT_ID=$(gcloud config get-value project)
function teardown() {
FEED_ID="test-feed"
gcloud pubsub subscriptions delete cai-rt-subscription \
--project $PROJECT_ID
gcloud asset feeds delete $FEED_ID \
--project=$PROJECT_ID
gcloud projects remove-iam-policy-binding $PROJECT_ID \
--member=serviceAccount:service-$(gcloud projects describe $PROJECT_ID --format="get(projectNumber)")@gcp-<EMAIL> \
--role=roles/cloudasset.serviceAgent
gcloud pubsub topics delete cai-rt-feed --project $PROJECT_ID
gcloud projects remove-iam-policy-binding $PROJECT_ID \
--member "user:$(gcloud config get-value account)" \
--role "roles/cloudasset.owner"
gcloud services disable cloudasset.googleapis.com --project $PROJECT_ID
}
teardown
<file_sep>#!/usr/bin/env bash
function install_terraform12() {
VERSION="0.12.30"
wget https://releases.hashicorp.com/terraform/${VERSION}/terraform_${VERSION}_darwin_amd64.zip
unzip terraform_${VERSION}_darwin_amd64.zip
sudo mv terraform /usr/local/bin/terraform12
terraform --version
# remove .zip file
rm -rf terraform_$VERSION_darwin_amd64.zip
}
install_terraform12<file_sep># GCP Demos
## Demos
| Demo | Description |
|------------------------------------|-------------------------------------------------------------|
| [Docker](docker/) | Get started with Docker |
| [GIT DevOps Scripts](git-devops-scripts/) | DevOps scripts for Git |
| [IAM Role Fetch](iam-role-fetch/) | Fetch all IAM roles |
| [Kitchen and Inspec](kitchen-and-inspec/) | Get started with terraform v0.11.x testing with kitchen and inspec |
| [Terraform vet](terraform-vet/) | Terraform vet (May 10, 2022) |
| [Terraform Validator Demo (v0.11.x)](terraform11-validator-demo/) | Get started with terraform v0.11.x with terraform-validator |
| [Terraform Validator Demo (v0.12.x)](terraform12-validator-demo/) | Get started with terraform v0.12.x with terraform-validator |
<file_sep>#!/bin/bash
PROJECT_ID=$(gcloud config get-value project)
function init() {
[ ! -d "policy-library" ] && git clone https://github.com/GoogleCloudPlatform/policy-library
}
init
terraform plan -var-file=terraform.tfvars -out my.tfplan
terraform destroy --auto-approve
<file_sep>#!/usr/bin/env bash
for i in {1..5}
do
gsutil mb gs://ilovecookies-${i} &
# gsutil cp run.sh gs://ilovecookies-${i} &
sleep 0.1
done
sleep 5
for i in {1..5}
do
gsutil rm -rf gs://ilovecookies-${i} &
done<file_sep># Terraform Validator Demo
Demo, showcasing how to leverage terraform-validator in a simple bash pipeline. This demo targets usage with terraform v0.11.x and the associated terraform-validator version.
## Scenarios
1. All GCS buckets deployed SHALL NOT be in the US
2. (TBD)
## Prerequisites
1. Terraform v0.11.x
2. terraform-validator
## Getting Started
Install terraform-validator for terraform v0.11.x:
```bash
gsutil cp gs://terraform-validator/releases/2019-03-28/terraform-validator-darwin-amd64 .
chmod +x terraaform-validator-darwin-amd64
```
```bash
# 1. Set your your application-default credentials to an account that has access to provision via terraform
gcloud auth application-default login
PROJECT_ID="sandbox-0700"
# 2. Initialize Terraform resources and modules
terraform init
# 3. Run Terraform Plan with an -out param
terraform plan -var-file="terraform.tfvars" -out my.tfplan
# 4. **Run Terraform Validator**
./terraform-validator-darwin-amd64 validate my.tfplan --project $PROJECT_ID --policy-path=../policy-library
# 5. Update the terraform.tfvars file
Location = "US" has been blacklisted and will be reported as a violation.
In order to bypass this, deploy the resource in an alternative region, for example, "asia-southeast1".
To pass terraform-validator, comment out line, location="US",
and uncomment the line location="asia-southeast1"
# 6. Run Terraform Apply
terraform apply my.tfplan
# 6. Verify
gsutil ls -p $PROJECT_ID
```
## Demo Scripts
```bash
# 1. Update terraform.tfvars
# 2. Set your gcloud config project id (This is only for running the run_to_* scripts)
PROJECT_ID="[YOUR_PROJECT_ID]"
gcloud config set project $PROJECT_ID
./tf_validate.sh
./tf_apply.sh
```
## Demo: Updating Constraints
1. Constraints are located in the ../../policy-library - WHERE do we get this?
`cat ../../policy-library/policies/constraints/storage_location.yaml` - BUCKETS are only allowed in ASIA-SOUTHEAST1?
2. Now... what if we update the bucket location to the US...
## Resources
- [Forseti Security Slides](https://docs.google.com/presentation/d/18HUHWppc4GFbK5fhe7kQfeOg_bk0XUzqTFG6v55XfVk/edit#slide=id.p)
- [Installing Terraform Validator](https://github.com/GoogleCloudPlatform/terraform-validator)
- git clone and run `go install .` then copy the binary 'sudo cp terraform-validator /usr/local/bin/')
<file_sep># Terraform v0.12.x Validator
Demo to get started with Terraform v0.12.x.
1. All GCS buckets deployed SHALL NOT be in the US
2. Restrict the application of particular IAAM roles
## Prerequisites
1. Terraform v0.12.x
2. This demo has been tuned for *Mac OSX*. If using Linux or Windows, please download the respective `terraform` AND `terraform-validator` binaries.
## Getting Started
```bash
# 0. Download terraform and terraform-validator
./init.sh
# 1. Set your your application-default credentials to an account that has access to provision via terraform
gcloud auth application-default login
PROJECT_ID="sandbox-0700"
# 2. Initialize Terraform resources and modules
./terraform init
./terraform fmt
# 3. Run Terraform Plan with an -out param
./terraform plan -var-file="terraform.tfvars" -out my.tfplan
# 4. Convert binary plan file to json
./terraform show -json ./my.tfplan > ./my.tfplan.json
# 5. **Run Terraform Validator**
./terraform-validator-darwin-amd64 validate my.tfplan.json --policy-path ../policy-library
# 6. Run Terraform Apply
./terraform apply my.tfplan
# 6. Verify
gsutil ls -p $PROJECT_ID
```
## Demo
```bash
# 0. Download terraform and terraform-validator
./init.sh
# 1. Update terraform.tfvars
# 2. Set your gcloud config project id (This is only for running the run_to_* scripts)
PROJECT_ID="[YOUR_PROJECT_ID]"
gcloud config set project $PROJECT_ID
./run_to_validate.sh
./run_to_apply.sh
# 3. Update the Policy Library Constraints (../policy-library/policies/constraints/)
```
## Resources
- [Forseti Security Slides](https://docs.google.com/presentation/d/18HUHWppc4GFbK5fhe7kQfeOg_bk0XUzqTFG6v55XfVk/edit#slide=id.p)
- [Installing Terraform Validator](https://github.com/GoogleCloudPlatform/terraform-validator)
- To run as `terraform-validator`, you'll have to move this to your /usr/local/bin/ directory via running `sudo cp terraform-validator /usr/local/bin/`.
<file_sep>const JIRATemplates = {
default: {
fields: {
project: {
key: "GOOG"
},
issuetype: {
self: 'https://gwongclouddev.atlassian.net/rest/api/2/issuetype/10001',
id: '10001',
description: 'Functionality or a feature expressed as a user goal.',
iconUrl: 'https://gwongclouddev.atlassian.net/rest/api/2/universal_avatar/view/type/issuetype/avatar/10315?size=medium',
name: 'Story',
subtask: false,
avatarId: 10315,
hierarchyLevel: 0
},
summary: 'Default Summary',
customfield_10006: {
self: 'https://gwongclouddev.atlassian.net/rest/api/2/customFieldOption/10020',
value: 'Stop, Drop and Fix!',
id: '10020'
}
},
}
};
module.exports = JIRATemplates;<file_sep>#!/bin/sh
git config credential.helper store
<file_sep># GCP Functions: Security Automation
GCPFunctionsX contains a set of Cloud Functions.
As of now there are 3 primary categories of Cloud Functions:
1. Http triggered (with Serverless VPC access)
2. GCS triggered (used for SOAR automation)
3. Pub/Sub triggered (used for SOAR automation)
## Function Test URLs
For ease and simplicity, here is the list of all the cloud function urls.
### Pub/Sub
- PubSubResponder - handles soar related events such as instances that do not follow naming convention by deleting them automatically. This depends on a Logging Sink
### GCS
* StorageDebugger - simple example of responding to a gcs object write event
## Looking for other functions?
* i.e. The Cloud Asset Inventory and Cloud Scheduler auto-export to BigQuery function
### Zip
```bash
zip -r ../code.zip . -x '*bin/*' -x '*obj/*'
# or to dir directly
zip -r ~/Git/[YOURPATH]/code.zip . -x '*bin/*' -x '*obj/*'
```
## References
* https://cloud.google.com/functions/docs/testing/test-http#functions-testing-http-example-csharp
* https://codelabs.developers.google.com/codelabs/cloud-functions-csharp#5
<file_sep>using CloudNative.CloudEvents;
using GCPFunctionsX.Utilities;
using Google.Cloud.Functions.Framework;
using Google.Events.Protobuf.Cloud.PubSub.V1;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace GCPFunctionsX
{
public class PubSubResponder : ICloudEventFunction<MessagePublishedData>
{
public async Task HandleAsync(CloudEvent cloudEvent, MessagePublishedData data, CancellationToken cancellationToken)
{
Console.WriteLine("Message published data:");
Console.WriteLine($" Message: {data.Message}");
Console.WriteLine($" Message.TextData: {data.Message.TextData}");
Console.WriteLine("Cloud event information:");
Console.WriteLine($" ID: {cloudEvent.Id}");
Console.WriteLine($" Source: {cloudEvent.Source}");
Console.WriteLine($" Type: {cloudEvent.Type}");
Console.WriteLine($" Subject: {cloudEvent.Subject}");
Console.WriteLine($" DataSchema: {cloudEvent.DataSchema}");
Console.WriteLine($" DataContentType: {cloudEvent.DataContentType}");
Console.WriteLine($" Time: {cloudEvent.Time?.ToUniversalTime():yyyy-MM-dd'T'HH:mm:ss.fff'Z'}");
Console.WriteLine($" SpecVersion: {cloudEvent.SpecVersion}");
// TODO: we should handle the type of input via the service name + method name properties
// parse
var jObj = JObject.Parse(data.Message.TextData);
var methodName = jObj.SelectToken("$.protoPayload.methodName").Value<string>();
var instanceSelfLink = jObj.SelectToken("$.protoPayload.resourceName").Value<string>();
switch(methodName)
{
// EVENT: Insert a Compute Instance
case "v1.compute.instances.insert":
case "beta.compute.instances.insert":
// create instance from compute engine > instances > create
var instanceName = Path.GetFileName(instanceSelfLink);
var res = Regex.Match(instanceSelfLink, "projects/(.+)/zones/(.+)/instances/(.+)");
var input = res.Groups[0];
var projectId = res.Groups[1];
var zone = res.Groups[2];
var instance = res.Groups[3];
if (instance.ToString().Contains("instance"))
{
var cs = new ComputeEngineService();
cs.DeleteInstance(projectId.ToString(), instance.ToString(), zone.ToString());
}
break;
// EVENT: List Service Account Keys
case "google.iam.admin.v1.ListServiceAccountKeys":
var email = jObj.SelectToken("$.protoPayload.authenticationInfo.principalEmail").Value<string>();
break;
// EVENT: SET IAM POLICY
case "google.iam.admin.v1.SetIAMPolicy":
var e = jObj.SelectToken("$.protoPayload.authenticationInfo.principalEmail").Value<string>();
var deltas = jObj.SelectToken("$.protoPayload.response").Value<string>();
break;
default:
break;
}
}
}
}
<file_sep>#!/usr/bin/env bash
PROJECT_ID=$(gcloud config get-value project)
X=$(gcloud pubsub subscriptions pull cai-rt-subscription \
--project $PROJECT_ID \
--auto-ack \
--format=json)
if [[ "$X" == "[]" ]]; then
echo "Pub/Sub subscription is empty."
exit 0
fi
RES=$(gcloud pubsub subscriptions pull cai-rt-subscription \
--project $PROJECT_ID \
--auto-ack \
--format=json \
| jq -r .[0].message.data | base64 -d)
function log_to_gcs() {
LOCAL_FILE_PATH=$1
gsutil mb gs://gwc-cai-rt-feed-results
gsutil cp $LOCAL_FILE_PATH gs://gwc-cai-rt-feed-results
rm $LOCAL_FILE_PATH
}
echo "$RES"
TEMP_FILE_NAME=$(date +%s)
echo "$RES" > ${TEMP_FILE_NAME}.json
log_to_gcs "${TEMP_FILE_NAME}.json"
printf "\n"
|
8fae21f88519b170bfeb72fc76f2835258446f46
|
[
"Ruby",
"Markdown",
"JavaScript",
"C#",
"Dockerfile",
"Shell"
] | 44
|
Markdown
|
garrettwong/gcp-demos
|
be9c2f1562e1e6f5cd4eb923d67f4f7a36fcff3a
|
901acd26ca64f6eef19f5ae012ff17e0d93fe8eb
|
refs/heads/main
|
<file_sep># Don't print a new line at the start of the prompt
add_newline = false
[line_break]
disabled = true
[character]
error_symbol = "[✘ ❯](bold red)"
success_symbol = "[✔ ❯](bold green)"
vicmd_symbol = "[v ❯](bold blue)"
[package]
disabled = true
[directory]
read_only = " 🔒"
truncation_length = 5
style = "bold dimmed cyan"
[git_commit]
commit_hash_length = 8
style = "bold white"
[git_state]
progress_divider = " of "
[git_status]
conflicted = " 🏳 "
ahead = "× "
behind = " "
diverged = " "
untracked = " "
stashed = " 📦 "
modified = "📝 "
staged = "🗃️ "
renamed = "👅 "
deleted = "🗑️ "
format = "$all_status$ahead_behind"
<file_sep>#!/bin/bash
# script to free up some ram run it with cron
#free -h > /home/yassen/Desktop/befor
sync; echo 1 > /proc/sys/vm/drop_caches
sync; echo 2 > /proc/sys/vm/drop_caches
#free -h > /home/yassen/Desktop/after
#echo " " >> /home/yassen/Desktop/after
#date >> /home/yassen/Desktop/after
<file_sep>#!/bin/bash
############################ this script is for debian based ###################################
#download main packages that i can't live without it
sudo apt install python3 python3-pip vim neovim dmenu rofi firefox htop youtube-dl git ffmpeg pcmanfm mpv fish sxiv nomacs ncdu ranger fonts-font-awesome fonts-powerline trash-cli tldr zathura shellcheck hardinfo ical xmind
#download the colorscript repo - installation is in https://gitlab.com/dwt1/shell-color-scripts.git
sudo git clone https://gitlab.com/yassen.tarek23/shell-color-scripts.git
#download starship prombet
curl https://raw.githubusercontent.com/anhsirk0/fetch-master-6000/master/fm6000.pl --output fm6000
#chmod +x the fm6000 file and place it into .config
curl -fsSL https://starship.rs/install.sh | bash
# place it into .config
sudo add-apt-repository ppa:papirus/papirus
sudo apt-get update
sudo apt-get install papirus-icon-theme
#download icon theme
# install some arabic fonts use this links
# https://arbfonts.com/noto-sans-arabic-bold-font-download.html
# https://arbfonts.com/noto-naskh-arabic-ui-font-download.html
#download imagemagice and move the policy.xml to /etc/imagemagic.. to edit the original policy it enables imagemagic to make pdf file from multible images
# the dir gnome-terminal is to change the terminal theme put it in ~
<file_sep>#!/bin/bash
~/.config/./fm6000 -c bright_cyan
<file_sep>#!/bin/bash
fortune | figlet | lolcat
<file_sep>#!/bin/bash
### this file is bieng executed by systemd /etc/systemd/system/startup.service ###
############# wake up the device from suspend useing keyboard and mouse ##########
sudo -u yassen echo enabled > /sys/bus/usb/devices/usb1/power/wakeup
sudo -u yassen echo enabled > /sys/bus/usb/devices/usb2/power/wakeup
sudo -u yassen echo enabled > /sys/bus/usb/devices/usb3/power/wakeup
sudo -u yassen echo enabled > /sys/bus/usb/devices/usb4/power/wakeup
sudo -u yassen echo enabled > /sys/bus/usb/devices/usb5/power/wakeup
sudo -u yassen echo enabled > /sys/bus/usb/devices/usb6/power/wakeup
sudo -u yassen echo enabled > /sys/bus/usb/devices/usb7/power/wakeup
sudo -u yassen echo enabled > /sys/bus/usb/devices/usb8/power/wakeup
<file_sep>#!/bin/bash
# this script rename files by numbers 001 002 003 etc...
# to add more zeors change the "%04d" to whatever zeros wanter
#rename 's/\d+/sprintf("%04d", $&)/e' *.jpg
<file_sep>#!/bin/bash
cmatrix
|
fbec08750f52a4c2cd617b8989b3793f32334088
|
[
"TOML",
"Shell"
] | 8
|
TOML
|
yassentarek/dotfiles
|
5f49c7ac2e9ec00245a684d401865a0055f0cdc7
|
29730cd0804eecf44e11b8c74e82bd4d573db3a4
|
refs/heads/master
|
<repo_name>MaysysInc/docker-registry-browser<file_sep>/app/assets/javascripts/repositories.js
$(document).on("turbolinks:load", function() {
$("#delete_confirm").on("keyup", function(e) {
var field = $(this);
var button = $("#delete-button");
if(field.val() == field.data("expected")) {
button.removeClass("disabled");
}
else {
button.addClass("disabled");
}
e.preventDefault();
});
});
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
<file_sep>/README.md
# Docker Registry Browser
[](https://travis-ci.org/klausmeyer/docker-registry-browser)
Web Interface for the [Docker Registry HTTP API V2](https://docs.docker.com/registry/spec/api/) written in Ruby on Rails.
## Screenshots
Repositories overview
[](https://github.com/klausmeyer/docker-registry-browser/raw/master/docs/screenshot1.png)
Tag overview
[](https://github.com/klausmeyer/docker-registry-browser/raw/master/docs/screenshot2.png)
Tag details - part 1
[](https://github.com/klausmeyer/docker-registry-browser/raw/master/docs/screenshot3.png)
Tag details - part 2
[](https://github.com/klausmeyer/docker-registry-browser/raw/master/docs/screenshot4.png)
Delete tag
[](https://github.com/klausmeyer/docker-registry-browser/raw/master/docs/screenshot5.png)
## Usage
### Docker
Execute:
```
docker run --name registry-browser -it -p 8080:8080 -e DOCKER_REGISTRY_URL=http://your-registry:5000 klausmeyer/docker-registry-browser
```
### Manual setup
1. Install ruby e.g. using [RVM](http://rvm.io) (see `.ruby-version` file for required version).
2. Execute `gem install bundler && bundle install --without development test` inside your local clone of this repository
3. Run the application using `DOCKER_REGISTRY_URL=http://your-registry:5000 bundle exec bundle exec puma -C config/puma.rb`
## Configuration
The configuration is done by environment variables.
| Option | Required | Type | Example | Description |
| -------------------- | -------- | ------ | ------------------------- | --------------------------------------------------------- |
| DOCKER_REGISTRY_URL | yes | String | http://your-registry:5000 | URL to the Docker Registry which should be browsed |
| NO_SSL_VERIFICATION | no | Bool | true | Enable to skip SSL verification (default `false`) |
| BASIC_AUTH_USER | no | String | joe | Username for basic-auth against registry |
| BASIC_AUTH_PASSWORD | no | String | <PASSWORD> | Password for basic-auth against registry |
| ENABLE_DELETE_IMAGES | no | Bool | true | Allow deletion of tags (default `false`) |
| PUBLIC_REGISTRY_URL | no | String | your-registry:5000 | The public URL to the Docker Registry to do docker pull |
You can also set BASIC_AUTH_USER and BASIC_AUTH_PASSWORD as [Docker Swarm secrets](https://docs.docker.com/engine/swarm/secrets/).
**Note:**
If you're using a reverse-proxy setup with SSL termination in front of this application in combination with `ENABLE_DELETE_IMAGES=true` you must make sure that the application knows about this fact (by sending `X-Forwarded-Proto: https` in the HTTP headers). Otherwise the application would throw errors like `"HTTP Origin header [...] didn't match request.base_url [...]"` when you're trying to delete image-tags.
<file_sep>/spec/features/show_image_spec.rb
require "rails_helper"
feature "Image details" do
scenario "Show details of image", :vcr do
visit "/"
within :css, ".panel:nth-child(2)" do
click_link "Image: hello-world"
end
expect(page).to have_content "Namespace: test / Image: hello-world"
expect(page).to have_content "Tag: latest"
expect(page).to have_content "Tag: v1"
expect(page).to have_content "Tag: v2"
expect(page).to have_content "Tag: v3"
end
end
|
4be5d9c3b1f498ef716fcac710d28e6a01dfd4a8
|
[
"JavaScript",
"Ruby",
"Markdown"
] | 3
|
JavaScript
|
MaysysInc/docker-registry-browser
|
dc49de46d4d705ef5445c90d1a95763033aaa165
|
f60321bc82a495cf523a8c9eb55f3283eaa6adf8
|
refs/heads/master
|
<repo_name>innetra/easy_contacts<file_sep>/app/models/person.rb
class Person < Contact
validates_presence_of :name
validates_presence_of :last_name
validates_uniqueness_of :name, :scope => :last_name
belongs_to :company
accepts_nested_attributes_for :company,
:reject_if => proc { |attributes| attributes['name'].blank? }
def full_name
"#{self.name} #{self.last_name}"
end
def title_description
unless self.company_id.blank?
unless self.title.blank?
I18n.translate "people.show.title_description",
:default => '{{title}} at {{company}}',
:title => self.title, :company => self.company.name
else
self.company.name
end
else
self.title
end
end
end
<file_sep>/app/models/phone.rb
class Phone < ActiveRecord::Base
validates_presence_of :number
belongs_to :owner, :polymorphic => true
belongs_to :type, :class_name => 'PhoneType'
end
<file_sep>/app/models/website.rb
class Website < ActiveRecord::Base
validates_presence_of :address
belongs_to :owner, :polymorphic => true
belongs_to :type, :class_name => 'WebsiteType'
end
<file_sep>/app/models/address.rb
class Address < ActiveRecord::Base
belongs_to :owner, :polymorphic => true
belongs_to :type, :class_name => 'AddressType'
belongs_to :city
belongs_to :country
belongs_to :province
def city_name
city.name if city
end
def city_name=(name)
self.city = City.find_or_create_by_name(name.to_s.titleize) unless name.blank?
end
def province_name
province.name if province
end
def province_name=(name)
self.province = Province.find_or_create_by_name(name.to_s.titleize) unless name.blank?
end
def country_name
country.name if country
end
def country_name=(name)
self.country = Country.find_or_create_by_name(name.to_s.titleize) unless name.blank?
end
end
<file_sep>/generators/easy_contacts/easy_contacts_generator.rb
class EasyContactsGenerator < Rails::Generator::Base
default_options :skip_migrations => false, :detailed_addresses => false
def manifest
record do |m|
# Stylesheets
m.directory('public/stylesheets/sass')
m.file 'stylesheets/sass/easy_contacts.sass',
'public/stylesheets/sass/easy_contacts.sass'
# Locales
m.directory('config/locales')
m.template 'locales/es-MX.easy_contacts.yml',
'config/locales/es-MX.easy_contacts.yml'
# Detailed addresses (street number, apartment number, and area)
if options[:detailed_addresses]
m.directory('app/views/addresses')
m.file 'views/addresses/_address.html.haml',
'app/views/addresses/_address.html.haml'
m.file 'views/addresses/_form.html.haml',
'app/views/addresses/_form.html.haml'
m.migration_template 'migrations/detailed_addresses.rb', 'db/migrate',
:migration_file_name => 'create_detailed_addresses'
end
# Migrations
unless options[:skip_migrations]
m.migration_template 'migrations/easy_contacts.rb', 'db/migrate',
:migration_file_name => 'create_easy_contacts'
end
end
end
protected
def banner
"Usage: #{$0} easy_contacts [--skip-migration] [--detailed-addresses]"
end
def add_options!(opt)
opt.separator ''
opt.separator 'Options:'
opt.on('--skip-migrations',
'Don\'t generate migrations file') { |v| options[:skip_migrations] = v }
opt.on('--detailed-addresses',
'Generate detailed addresses view\'s') { |v| options[:detailed_addresses] = v }
end
end
<file_sep>/init.rb
config.to_prepare do
ApplicationController.helper(AddressesHelper)
ApplicationController.helper(EmailsHelper)
ApplicationController.helper(InstantMessengersHelper)
ApplicationController.helper(PhonesHelper)
ApplicationController.helper(WebsitesHelper)
end
<file_sep>/app/models/address_type.rb
class AddressType < ActiveRecord::Base
validates_presence_of :description
end
<file_sep>/app/controllers/instant_messengers_controller.rb
class InstantMessengersController < ApplicationController
def destroy
@instant_messenger = InstantMessenger.find(params[:id])
@instant_messenger.destroy
end
end
<file_sep>/app/models/company.rb
class Company < Contact
validates_presence_of :name
validates_uniqueness_of :name, :case_sensitive => false
has_many :people
default_scope :order => 'name DESC'
end
<file_sep>/app/controllers/emails_controller.rb
class EmailsController < ApplicationController
def destroy
@email = Email.find(params[:id])
@email.destroy
end
end
<file_sep>/app/controllers/addresses_controller.rb
class AddressesController < ApplicationController
def destroy
@address = Address.find(params[:id])
@address.destroy
end
end
<file_sep>/app/controllers/phones_controller.rb
class PhonesController < ApplicationController
def destroy
@phone = Phone.find(params[:id])
@phone.destroy
respond_to do |format|
format.js
end
end
end
<file_sep>/app/controllers/companies_controller.rb
class CompaniesController < ApplicationController
def index
@companies = Company.all(:conditions => ["name LIKE ?", "%#{params[:search]}%"], :limit => 10, :order => "name")
end
def new
@company = Company.new
@company.setup_child_elements
end
def create
@company = Company.new(params[:company])
respond_to do |format|
if @company.save
flash[:notice] = t("companies.create.flash.notice", :default => 'Company created.')
format.html { redirect_to(@company) }
format.xml { render :xml => @company, :status => :created, :location => @company }
else
@company.setup_child_elements
flash[:error] = t("companies.create.flash.error", :default => 'Company not created.')
format.html { render :action => "new" }
format.xml { render :xml => @company.errors, :status => :unprocessable_entity }
end
end
end
def show
@company = Company.find_by_id(params[:id])
end
def edit
@company = Company.find_by_id(params[:id])
@company.setup_child_elements
end
def update
@company = Company.find_by_id(params[:id])
respond_to do |format|
if @company.update_attributes(params[:company])
flash[:notice] = t('companies.update.flash.notice', :default => 'Company updated.')
format.html { redirect_to(@company) }
format.xml { head :ok }
else
@company.setup_child_elements
flash[:error] = t('companies.update.flash.error', :default => 'Company not updated.')
format.html { render :action => "edit" }
format.xml { render :xml => @company.errors, :status => :unprocessable_entity }
end
end
end
end
<file_sep>/generators/easy_contacts/templates/migrations/detailed_addresses.rb
class CreateDetailedAddresses < ActiveRecord::Migration
def self.up
add_column :addresses, :number, :string
add_column :addresses, :apartment, :string
add_column :addresses, :area, :string
end
def self.down
remove_column :addresses, :number
remove_column :addresses, :apartment
remove_column :addresses, :area
end
end
<file_sep>/README.rdoc
= Easy Contacts
Rails fullstack contacts management plugin (with Rails Engines).
== Requirements
* Rails 2.3.2 (support for {Rails Engines}[http://railscasts.com/episodes/149-rails-engines] needed).
* {Auto Complete}[http://github.com/rails/auto_complete/tree/master] Plugin
* {Haml}[http://haml.hamptoncatlin.com/]
* {EasyGenerators}[http://github.com/innetra/easy_generators/tree/master]
== Install
First install the plugin in your application:
script/plugin install git://github.com/innetra/easy_contacts.git
This plugin requires some i18n translation files, migrations, and stylesheets. Generate them with:
script/generate easy_contacts
The easy_authentication generator provides the following options (you'll need them if the generator is run more than once):
--skip-migrations
Finally generate the phone, email, instant messenger, website, and address types for your application (you'll need to run the migrations first):
rake easy_contacts:init
Restart your application and you're done!
Enjoy!
== Quick Demo
If you want to see a complete implementation of EasyContacts you can start in a
snap with the following Rails application template:
rails -m http://gist.github.com/105723.txt your_new_application
== License
Copyright (c) 2008 Innetra Consultancy Services, S.C.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<file_sep>/config/routes.rb
ActionController::Routing::Routes.draw do |map|
map.resources :addresses, :only => :destroy
map.resources :cities, :only => :index
map.resources :companies, :has_many => :people
map.resources :contacts, :only => :index
map.resources :countries, :only => :index
map.resources :emails, :only => :destroy
map.resources :instant_messengers, :only => :destroy
map.resources :people
map.resources :phones, :only => :destroy
map.resources :provinces, :only => :index
map.resources :websites, :only => :destroy
end
<file_sep>/app/helpers/phones_helper.rb
module PhonesHelper
# Insert existing nested phone numbers
def insert_phones(form)
# Existing owner's phones
content_tag :ul, :id => 'phones' do
form.fields_for :phones do |nested_attributes|
render :partial => 'phones/form', :object => nested_attributes
end
end
end
# Insert new nested phone number
def insert_new_phone_link(form)
# New phone link
content_tag :p do
form.fields_for :phones, form.object.phones.new do |nested_attributes|
link_to_function t('phones.helper.new', :default => 'Add new Phone') do |page|
page.insert_html :bottom, :phones, :partial => 'phones/form',
:object => nested_attributes
end
end
end
end
# Insert phone type select tag (collection_select)
def insert_phone_type_options(form)
form.collection_select :type_id, PhoneType.all, :id, :description, {}
end
# Insert delete phone link
def insert_delete_phone_link(form)
# If it's a new record it will remove only the html,
# otherwise it will request record deletion using Ajax
if form.object.new_record?
link_to_function t('phones.helper.delete', :default => 'Delete'),
"$(this).parents('li.phone').remove()", :class => :red
else
link_to_remote t('phones.helper.delete', :default => 'Delete'),
:url => form.object, :confirm => t('phones.helper.delete_confirmation',
:default => 'Are you shure?'), :method => :delete,
:html => { :class => :red }
end
end
end
<file_sep>/app/controllers/websites_controller.rb
class WebsitesController < ApplicationController
def destroy
@website = Website.find(params[:id])
@website.destroy
respond_to do |format|
format.js
end
end
end
<file_sep>/app/models/contact.rb
class Contact < ActiveRecord::Base
belongs_to :owner, :polymorphic => true
has_many :addresses, :as => :owner
has_many :emails, :as => :owner
has_many :instant_messengers, :as => :owner
has_many :phones, :as => :owner
has_many :websites, :as => :owner
accepts_nested_attributes_for :addresses,
:reject_if => proc { |attributes| attributes['address'].blank? }
accepts_nested_attributes_for :emails,
:reject_if => proc { |attributes| attributes['address'].blank? }
accepts_nested_attributes_for :instant_messengers,
:reject_if => proc { |attributes| attributes['nick'].blank? }
accepts_nested_attributes_for :phones,
:reject_if => proc { |attributes| attributes['number'].blank? }
accepts_nested_attributes_for :websites,
:reject_if => proc { |attributes| attributes['address'].blank? }
# Setup child elements for contact's
def setup_child_elements
if phones.empty?
phones.build
phones.build :type_id => 4 # fax
end
if emails.empty?
emails.build
emails.build
end
instant_messengers.build if instant_messengers.empty?
websites.build if websites.empty?
addresses.build if addresses.empty?
end
end
<file_sep>/app/models/instant_messenger.rb
class InstantMessenger < ActiveRecord::Base
validates_presence_of :nick
belongs_to :owner, :polymorphic => true
belongs_to :protocol, :class_name => 'InstantMessengerProtocol'
belongs_to :type, :class_name => 'InstantMessengerType'
end
<file_sep>/app/controllers/contacts_controller.rb
class ContactsController < ApplicationController
def index
if params.has_key?(:search)
@contacts = Contact.all(:conditions => ["name LIKE ? OR last_name LIKE ?", "%#{params[:search]}%", "%#{params[:search]}%"],
:limit => 10, :order => "name, last_name")
else
@contacts = Contact.all(:order => "name, last_name")
end
respond_to do |format|
format.html # index.html.erb
format.js { render :template => nil }
format.xml { render :xml => @contacts }
end
end
end
<file_sep>/app/helpers/addresses_helper.rb
module AddressesHelper
# Insert existing nested address numbers
def insert_addresses(form)
# Existing owner's addresses
content_tag :ul, :id => 'addresses' do
form.fields_for :addresses do |nested_attributes|
render :partial => 'addresses/form', :object => nested_attributes
end
end
end
# Insert new nested address number
def insert_new_address_link(form)
# New address link
content_tag :p do
form.fields_for :addresses, form.object.addresses.new do |nested_attributes|
link_to_function t('addresses.helper.new', :default => 'add another address') do |page|
page.insert_html :bottom, :addresses, :partial => 'addresses/form',
:object => nested_attributes
end
end
end
end
# Insert address type select tag (collection_select)
def insert_address_type_options(form)
form.collection_select :type_id, AddressType.all, :id, :description, {}
end
# Insert delete address link
def insert_delete_address_link(form)
# If it's a new record it will remove only the html,
# otherwise it will request record deletion using Ajax
if form.object.new_record?
link_to_function t('addresses.helper.delete', :default => 'Delete'),
"$(this).parents('li.address').remove()", :class => :red
else
link_to_remote t('addresses.helper.delete', :default => 'Delete'),
:url => form.object,
:confirm => t('addresses.helper.delete_confirmation',
:default => 'Are you shure?'),
:method => :delete, :html => { :class => :red }
end
end
end
<file_sep>/app/helpers/instant_messengers_helper.rb
module InstantMessengersHelper
# Insert existing nested instant messengers
def insert_instant_messengers(form)
# Existing owner's instant messengers
content_tag :ul, :id => 'instant_messengers' do
form.fields_for :instant_messengers do |nested_attributes|
render :partial => 'instant_messengers/form',
:object => nested_attributes
end
end
end
# Insert new nested instant messenger number
def insert_new_instant_messenger_link(form)
# New instant messenger link
content_tag :p do
form.fields_for :instant_messengers, form.object.instant_messengers.new do |nested_attributes|
link_to_function t('instant_messengers.helper.new',
:default => 'Add new Instant Messenger') do |page|
page.insert_html :bottom, :instant_messengers,
:partial => 'instant_messengers/form', :object => nested_attributes
end
end
end
end
# Insert instant messenger type select tag (collection_select)
def insert_instant_messenger_type_options(form)
form.collection_select :type_id, InstantMessengerType.all,
:id, :description, {}
end
def insert_instant_messenger_protocol_options(form)
form.collection_select :protocol_id, InstantMessengerProtocol.all,
:id, :name, {}
end
# Insert delete instant messenger link
def insert_delete_instant_messenger_link(form)
# If it's a new record it will remove only the html,
# otherwise it will request record deletion using Ajax
if form.object.new_record?
link_to_function t('instant_messengers.helper.delete',
:default => 'Delete'),
"$(this).parents('li.instant_messenger').remove()", :class => :red
else
link_to_remote t('instant_messengers.helper.delete',
:default => 'Delete'), :url => form.object,
:confirm => t('instant_messengers.helper.delete_confirmation',
:default => 'Are you shure?'),
:method => :delete, :html => { :class => :red }
end
end
end
<file_sep>/lib/tasks/easy_contacts.rake
namespace :easy_contacts do
desc "Initial database setup for easy_contacts"
task :init => :environment do
# Create Phone, Email, Instant Messenger, Web Address and Addresses types
PhoneType.create!(:description => "Work")
PhoneType.create!(:description => "Movil")
PhoneType.create!(:description => "Home")
PhoneType.create!(:description => "Fax")
PhoneType.create!(:description => "Pager")
PhoneType.create!(:description => "Skype")
PhoneType.create!(:description => "Other")
EmailType.create!(:description => "Work")
EmailType.create!(:description => "Home")
EmailType.create!(:description => "Otro")
InstantMessengerProtocol.create!(:name => "AIM")
InstantMessengerProtocol.create!(:name => "Google Talk")
InstantMessengerProtocol.create!(:name => "ICQ")
InstantMessengerProtocol.create!(:name => "Jabber")
InstantMessengerProtocol.create!(:name => "MSN")
InstantMessengerProtocol.create!(:name => "Skype")
InstantMessengerProtocol.create!(:name => "Yahoo")
InstantMessengerProtocol.create!(:name => "Other")
InstantMessengerType.create!(:description => "Work")
InstantMessengerType.create!(:description => "Home")
InstantMessengerType.create!(:description => "Other")
WebsiteType.create!(:description => "Work")
WebsiteType.create!(:description => "Home")
WebsiteType.create!(:description => "Other")
AddressType.create!(:description => "Work")
AddressType.create!(:description => "Home")
AddressType.create!(:description => "Other")
# Country
Country.create!(:name => "México")
end
end
<file_sep>/app/helpers/emails_helper.rb
module EmailsHelper
# Insert existing nested email
def insert_emails(form)
# Existing owner's emails
content_tag :ul, :id => 'emails' do
form.fields_for :emails do |nested_attributes|
render :partial => 'emails/form', :object => nested_attributes
end
end
end
# Insert new nested email
def insert_new_email_link(form)
# New email link
content_tag :p do
form.fields_for :emails, form.object.emails.new do |nested_attributes|
link_to_function t('emails.helper.new', :default => 'Email') do |page|
page.insert_html :bottom, :emails, :partial => 'emails/form',
:object => nested_attributes
end
end
end
end
# Insert email type select tag (collection_select)
def insert_email_type_options(form)
form.collection_select :type_id, EmailType.all, :id, :description, {}
end
# Insert delete email link
def insert_delete_email_link(form)
# If it's a new record it will remove only the html,
# otherwise it will request record deletion using Ajax
if form.object.new_record?
link_to_function t('emails.helper.delete', :default => 'Delete'),
"$(this).parents('li.email').remove()", :class => :red
else
link_to_remote t('emails.helper.delete', :default => 'Delete'), :url => form.object,
:confirm => t('emails.helper.delete_email',
:default => 'Are you shure?'),
:method => :delete, :html => { :class => :red }
end
end
end
<file_sep>/generators/easy_contacts/templates/migrations/easy_contacts.rb
class CreateEasyContacts < ActiveRecord::Migration
def self.up
create_table :addresses do |t|
t.integer :owner_id
t.string :owner_type
t.integer :type_id, :default => 1
t.string :address
t.integer :city_id
t.integer :province_id
t.integer :country_id
t.string :zip
t.timestamps
end
create_table :contacts do |t|
t.string :type
t.integer :owner_id
t.string :owner_type
t.integer :company_id # Only for Person
t.string :name # Only for Company
t.string :last_name
t.string :title
t.timestamps
end
create_table :emails do |t|
t.integer :owner_id
t.string :owner_type
t.integer :type_id, :default => 1
t.string :address
t.timestamps
end
create_table :instant_messengers do |t|
t.integer :owner_id
t.string :owner_type
t.integer :protocol_id, :default => 1
t.integer :type_id, :default => 1
t.string :nick
t.timestamps
end
create_table :phones do |t|
t.integer :owner_id
t.string :owner_type
t.integer :type_id, :default => 1
t.string :number
t.timestamps
end
create_table :websites do |t|
t.integer :owner_id
t.string :owner_type
t.integer :type_id, :default => 1
t.string :address
t.timestamps
end
create_table :address_types do |t|
t.string :description
end
create_table :cities do |t|
t.string :name
end
create_table :countries do |t|
t.string :name
end
create_table :email_types do |t|
t.string :description
end
create_table :instant_messenger_protocols do |t|
t.string :name
end
create_table :instant_messenger_types do |t|
t.string :description
end
create_table :phone_types do |t|
t.string :description
end
create_table :provinces do |t|
t.string :name
end
create_table :website_types do |t|
t.string :description
end
end
def self.down
drop_table :addresses
drop_table :contacts
drop_table :emails
drop_table :instant_messengers
drop_table :phones
drop_table :websites
drop_table :address_types
drop_table :cities
drop_table :countries
drop_table :email_types
drop_table :instant_messenger_protocols
drop_table :instant_messenger_types
drop_table :phone_types
drop_table :provinces
drop_table :website_types
end
end
<file_sep>/app/models/email.rb
class Email < ActiveRecord::Base
validates_presence_of :address
validates_format_of :address,
:with => /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
belongs_to :owner, :polymorphic => true
belongs_to :type, :class_name => 'EmailType'
def before_save
self.address.downcase!
end
end
<file_sep>/app/controllers/people_controller.rb
require 'ostruct'
class PeopleController < ApplicationController
def index
@people = Person.all :conditions => ["name LIKE ? OR last_name LIKE ?",
"%#{params[:search]}%", "%#{params[:search]}%"], :limit => 10,
:order => "name, last_name"
end
def new
@person = Person.new
@person.setup_child_elements
end
def create
@person = Person.new(params[:person])
respond_to do |format|
if @person.save
flash[:notice] = t('people.create.flash.notice', :default => 'Company created.')
format.html { redirect_to(@person) }
format.xml { render :xml => @person, :status => :created, :location => @person }
else
@person.setup_child_elements
flash[:error] = t('people.create.flash.error', :default => 'Company not created')
format.html { render :action => "new" }
format.xml { render :xml => @person.errors, :status => :unprocessable_entity }
end
end
end
def show
@person = Person.find_by_id(params[:id])
end
def edit
@person = Person.find_by_id(params[:id])
@person.setup_child_elements
end
def update
@person = Person.find_by_id(params[:id])
respond_to do |format|
if @person.update_attributes(params[:person])
flash[:notice] = t('people.update.flash.notice', :default => 'Company updated.')
format.html { redirect_to(@person) }
format.xml { head :ok }
else
@person.setup_child_elements
flash[:error] = t('people.update.flash.error', :default => 'Company not updated.')
format.html { render :action => "edit" }
format.xml { render :xml => @person.errors, :status => :unprocessable_entity }
end
end
end
end
<file_sep>/app/controllers/countries_controller.rb
class CountriesController < ApplicationController
def index
@countries = Country.all(:conditions => ["name LIKE ?", "%#{params[:search]}%"], :limit => 10, :order => "name")
render :template => nil
end
end
|
a909988ac7faf7d2242dca1a41b612dced063950
|
[
"RDoc",
"Ruby"
] | 29
|
Ruby
|
innetra/easy_contacts
|
a21226d15dbe2537cce83b688890c693d90f6fed
|
82211e88485854a31313d4e8e651ab0da6e774fb
|
refs/heads/master
|
<repo_name>protolif/edtf-ruby<file_sep>/lib/edtf/version.rb
module EDTF
VERSION = '3.0.4'.freeze
end
<file_sep>/Gemfile
source 'https://rubygems.org'
gemspec
group :debug do
gem 'ruby-debug', :require => false, :platform => :jruby
gem 'byebug', :require => false, :platform => :mri
gem 'rubinius-compiler', '~>2.0', :require => false, :platform => :rbx
gem 'rubinius-debugger', '~>2.0', :require => false, :platform => :rbx
end
group :development do
gem 'rake'
gem 'racc', :platform => :ruby
gem 'cucumber'
gem 'rspec', '~>3.0'
gem 'simplecov', :require => false
gem 'rubinius-coverage', :platform => :rbx
gem 'coveralls', '~>0.8', :require => false
end
group :extra do
gem 'ZenTest'
end
# active_support requires this
gem 'i18n'
platform :rbx do
gem 'rubysl-singleton', '~>2.0'
gem 'rubysl-open3', '~>2.0'
gem 'rubysl-enumerator', '~>2.0'
gem 'rubysl-base64', '~>2.0'
gem 'rubysl-bigdecimal', '~>2.0'
gem 'rubysl-drb', '~>2.0'
gem 'json'
end
|
59a42aae69cd360b1359c5dee5781508fbc3f4a8
|
[
"Ruby"
] | 2
|
Ruby
|
protolif/edtf-ruby
|
7f6d3082f9e2c4826ed656ea370be36b42c9a1ee
|
36206216787b0693678cb3cbc58eca8a921b4a45
|
refs/heads/master
|
<file_sep>"""navigation_project_intro.py
Code from the Udacity IPython notebook introduction to the Navigation project.
"""
from unityagents import UnityEnvironment
import numpy as np
env = UnityEnvironment(file_name="Banana.exe")
# get the default brain
brain_name = env.brain_names[0]
brain = env.brains[brain_name]
# reset the environment
env_info = env.reset(train_mode=True)[brain_name]
# number of agents in the environment
print('Number of agents:', len(env_info.agents))
# number of actions
action_size = brain.vector_action_space_size
print('Number of actions:', action_size)
# examine the state space
state = env_info.vector_observations[0]
print('States look like:', state)
state_size = len(state)
print('States have length:', state_size)
# take random actions in the environment
env_info = env.reset(train_mode=False)[brain_name]
state = env_info.vector_observations[0]
score = 0
while True:
action = np.random.randint(action_size)
env_info = env.step(action)[brain_name]
next_state = env_info.vector_observations[0]
reward = env_info.rewards[0]
done = env_info.local_done[0]
score += reward
state = next_state
if done:
break
print("Score: {}".format(score))
env.close()<file_sep># Project Report
This document is my report for the banana-collecting Navigation project.
# Learning Algorithm
The learning algorithm is an adaptation of the Deep Q-Learning (DQN) algorithm, specifically based on the [Udacity code for solving the OpenAI Lunar Lander problem](https://github.com/udacity/deep-reinforcement-learning/tree/master/dqn/solution). DQN uses the idea of training a deep neural network to approximate the action values _q_. To provide improved stability while training, DQN contains the following innovations:
* Experience Replay: Tuples of (state, action, reward, next_state) are stored in a replay buffer so that the agent can learn from past experiences.
* Fixed Q-targets: Target Q-network weights are updated less often than the primary Q-network, which allows the network to avoid chasing a moving target during training.
For this implementation, the neural network architecture chosen contains the following PyTorch layers, coded in **qnetwork.py**:
* A BatchNorm1d layer to receive the input state
* A Linear layer of size 128
* A Linear layer of size 64
* A Linear layer of size 4 to generate the output action values
The BatchNorm1d layer is used for batch normalization in order to improve learning performance. ReLU activation functions are used between the Linear hidden layers.
Additional hyperparameters in **dqn_agent.py** and **train_banana_agent.py** are described below:
* BUFFER_SIZE: replay buffer size, i.e. max number of (S,A,R,S) tuples that can be stored
* BATCH_SIZE: minibatch size used for training
* GAMMA: discount factor for future rewards
* TAU: interpolation parameter used for soft update of target parameters
* LR: learning rate
* UPDATE_EVERY: parameter controlling how often to update the network
* EPS_START, EPS_END, EPS_DECAY: parameters for the epsilon-greedy policy, controlling how often to choose a random action
# Reward Plots
The agent solved the environment in 840 episodes. A plot of the training rewards is shown below.

For further validation, the trained agent was run through the environment for an additional 100 episodes, achieving an average score of 13.29. A plot of the validation rewards is shown below.

# Ideas for Future Work
This implementation uses a straightforward vanilla implementation of the DQN algorithm. A few improvements would likely improve performance:
* Prioritized Experience Replay: Resampling tuples that generate a larger TD error could allow the algorithm to learn more from particularly important experiences.
* Frame stacking: Stacking multiple frames together into a sequence for input (as reported by DeepMind for its Atari implementations) would likely improve agent performance by allowing it to utilize a short-term memory of bananas that are not in its current field of view, but which it has seen in the past few timesteps.
<file_sep>from unityagents import UnityEnvironment
import numpy as np
import torch
from collections import deque
from dqn_agent import Agent
import matplotlib.pyplot as plt
n_episodes = 100
env = UnityEnvironment(file_name="Banana.exe")
# get the default brain
brain_name = env.brain_names[0]
brain = env.brains[brain_name]
# create an Agent
agent = Agent(state_size=37, action_size=4, seed=0)
# load the weights from file
agent.qnetwork_local.load_state_dict(torch.load('checkpoint.pth'))
scores = []
scores_window = deque(maxlen=100)
for i_episode in range(0, n_episodes):
brain_info = env.reset(train_mode=False)[brain_name]
state = brain_info.vector_observations[0]
score = 0
while True:
action = agent.act(state, eps=0.0, training_mode=False)
env_info = env.step(action)[brain_name]
state = env_info.vector_observations[0]
reward = env_info.rewards[0]
done = env_info.local_done[0]
score += reward
if done:
break
scores_window.append(score) # save most recent score
scores.append(score) # save most recent score
print('\rEpisode {}\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)), end="")
env.close()
# plot the scores
fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot(np.arange(len(scores)), scores)
plt.ylabel('Score')
plt.xlabel('Episode #')
plt.show()<file_sep># udacity-drlnd-navigation
# Introduction
This is my submission for the Navigation project of the Udacity Deep Reinforcement Learning Nanodegree. The purpose of the project is to train an agent to collect yellow bananas while avoiding blue bananas in a Unity environment, using an adaptation of the Deep Q-learning (DQN) algorithm.
# Project Details
The environment for this project is a Unity ML-Agents environment provided by Udacity. In this environment, an agent navigates a square world filled with yellow bananas and blue bananas. The agent is provided a reward of +1 for collecting a yellow banana, and a reward of -1 for collecting a blue banana. Therefore, the agent's goal is to collect as many yellow bananas as possible while avoiding blue bananas.
The state space (of the agent's observations) is a vector of 37 numbers that contains information on the agent's velocity, as well as ray-based perception of objects in the agent's forward field-of-view.
The agent's action space is discrete, with 4 possible actions at each step:
* 0: move forward
* 1: move backward
* 2: turn left
* 3: turn right
The environment is considered solved when the agent obtains an average score of at least +13 over 100 consecutive episodes.
# Getting Started
The dependencies for this submission are the same as for the [Udacity Deep Reinforcement Learning nanodegree](https://github.com/udacity/deep-reinforcement-learning#dependencies):
* Python 3.6
* pytorch
* unityagents
* [Udacity banana project environment](https://s3-us-west-1.amazonaws.com/udacity-drlnd/P1/Banana/Banana_Windows_x86_64.zip)
This project was completed and tested on a local Windows environment (64-bit) running Python 3.6.10 in a conda environment.
# Instructions
To train the agent, run **train_banana_agent.py**. This will save the model parameters in **checkpoint.pth** once the agent has fulfilled the criteria for considering the environment solved.
To run the trained agent, run **run_banana_agent.py**. This will load the saved model parameters from checkpoint.pth, and run the trained model in the banana-collecting environment. The *n_episodes* parameter is the number of episodes that will be run. By default, this parameter is set to 100 to facilitate validation of the trained agent.
<file_sep>"""train_banana_agent.py
Train the banana-collecting agent.
"""
from unityagents import UnityEnvironment
import numpy as np
import torch
from collections import deque
from dqn_agent import Agent
import matplotlib.pyplot as plt
def dqn(agent, n_episodes=1500, eps_start=1.0, eps_end=0.01, eps_decay=0.995, score_threshold=13.0):
"""Deep Q-Learning.
Params
======
n_episodes (int): maximum number of training episodes
eps_start (float): starting value of epsilon, for epsilon-greedy action selection
eps_end (float): minimum value of epsilon
eps_decay (float): multiplicative factor (per episode) for decreasing epsilon
"""
scores = [] # list containing scores from each episode
scores_window = deque(maxlen=100) # last 100 scores
eps = eps_start # initialize epsilon
for i_episode in range(0, n_episodes):
brain_info = env.reset(train_mode=True)[brain_name]
state = brain_info.vector_observations[0]
score = 0
while True:
action = agent.act(state, eps, training_mode=True)
env_info = env.step(action)[brain_name]
next_state = env_info.vector_observations[0]
reward = env_info.rewards[0]
done = env_info.local_done[0]
agent.step(state, action, reward, next_state, done)
score += reward
state = next_state
if done:
break
scores_window.append(score) # save most recent score
scores.append(score) # save most recent score
eps = max(eps_end, eps_decay*eps) # decrease epsilon
print('\rEpisode {}\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)), end="")
if i_episode % 100 == 0:
print('\rEpisode {}\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)))
if np.mean(scores_window)>=score_threshold:
print('\nEnvironment solved in {:d} episodes!\tAverage Score: {:.2f}'.format(i_episode-100, np.mean(scores_window)))
torch.save(agent.qnetwork_local.state_dict(), 'checkpoint.pth')
break
return scores
env = UnityEnvironment(file_name="Banana.exe")
# get the default brain
brain_name = env.brain_names[0]
brain = env.brains[brain_name]
# reset the environment
env_info = env.reset(train_mode=True)[brain_name]
# create an Agent
banana_action_size = brain.vector_action_space_size
state = env_info.vector_observations[0]
banana_state_size = len(state)
agent = Agent(state_size=banana_state_size, action_size=banana_action_size, seed=0)
# run DQN
scores = dqn(agent)
env.close()
# plot the scores
fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot(np.arange(len(scores)), scores)
plt.ylabel('Score')
plt.xlabel('Episode #')
plt.show()
|
4dfcd9722719a510bb26fa234d8d97136c26e5f0
|
[
"Markdown",
"Python"
] | 5
|
Python
|
dsotingco/udacity-drlnd-navigation
|
29fe5dc5b4985e8391efd9e9f3ace2b08d40721d
|
cc7820414ce9bee61be32f4c9047a4ba57e6a364
|
refs/heads/master
|
<file_sep>require "open-uri"
require "nokogiri"
namespace :scrape do
desc "Race results for a given date"
task :race_results => :environment do
url = "http://racing.hkjc.com/racing/Info/Meeting/Results/English"
parse_data = Nokogiri::HTML(open(url))
i = 0
while (i <= 11) do
j = 1
next_page = parse_data.css('#raceDateSelect > option')[i].attr('value')
while (j <= 16) do
url = "http://racing.hkjc.com/racing/Info/Meeting/Results/English/#{next_page}/#{j}"
puts url
data = Nokogiri::HTML(open(url))
OneLine(data, j)
j += 1
end
i += 1
end
end
end
def OneLine(parsed_data, j)
distance = parsed_data.css('table > tbody > tr > td > span.number14')
# distance = distance
# distance = "1234m"
date = parsed_data.css('#raceDateSelect option[@selected="selected"]')
racenumber = j
rank = parsed_data.css('div.clearDivFloat.rowDiv15 > table.tableBorder.trBgBlue.tdAlignC.number12.draggable > tbody > tr > td:nth-child(1)')
number = parsed_data.css('div.clearDivFloat.rowDiv15 > table.tableBorder.trBgBlue.tdAlignC.number12.draggable > tbody > tr > td:nth-child(2)')
horse = parsed_data.css('table.tableBorder.trBgBlue.tdAlignC.number12.draggable > tbody > tr > td:nth-child(3).tdAlignL.font13.fontStyle > a:nth-child(1)')
jockey = parsed_data.css('table.tableBorder.trBgBlue.tdAlignC.number12.draggable > tbody > tr > td:nth-child(4).tdAlignL.font13.fontStyle > a:nth-child(1)')
trainer = parsed_data.css('table.tableBorder.trBgBlue.tdAlignC.number12.draggable > tbody > tr > td:nth-child(5).tdAlignL.font13.fontStyle > a:nth-child(1)')
actualweight = parsed_data.css('div.clearDivFloat.rowDiv15 > table.tableBorder.trBgBlue.tdAlignC.number12.draggable > tbody > tr > td:nth-child(6)')
horseweight = parsed_data.css('div.clearDivFloat.rowDiv15 > table.tableBorder.trBgBlue.tdAlignC.number12.draggable > tbody > tr > td:nth-child(7)')
draw = parsed_data.css('div.clearDivFloat.rowDiv15 > table.tableBorder.trBgBlue.tdAlignC.number12.draggable > tbody > tr > td:nth-child(8)')
lbw = parsed_data.css('div.clearDivFloat.rowDiv15 > table.tableBorder.trBgBlue.tdAlignC.number12.draggable > tbody > tr > td:nth-child(9)')
finishtime = parsed_data.css('div.clearDivFloat.rowDiv15 > table.tableBorder.trBgBlue.tdAlignC.number12.draggable > tbody > tr > td:nth-child(11)')
odd = parsed_data.css('div.clearDivFloat.rowDiv15 > table.tableBorder.trBgBlue.tdAlignC.number12.draggable > tbody > tr > td:nth-child(12)')
rank.each_with_index do |item, index|
new_result = Race.new
new_result.distance = distance.text unless distance.nil?
new_result.date = date[0].text unless date[0].nil?
new_result.racenumber = racenumber unless racenumber.nil?
new_result.rank = rank[index].text unless rank[index].nil?
new_result.number = number[index].text unless number[index].nil?
new_result.horse = horse[index].text unless horse[index].nil?
new_result.jockey = jockey[index].text unless jockey[index].nil?
new_result.trainer = trainer[index].text unless trainer[index].nil?
new_result.actualweight = actualweight[index].text unless actualweight[index].nil?
new_result.horseweight = horseweight[index].text unless horseweight[index].nil?
new_result.draw = draw[index].text unless draw[index].nil?
new_result.lbw = lbw[index].text unless lbw[index].nil?
new_result.finishtime = finishtime[index].text unless finishtime[index].nil?
new_result.odd = odd[index].text unless odd[index].nil?
if new_result.save
puts "#{new_result.date} saved in db"
else
puts "#{new_result.date} not saved in db"
end
end
end<file_sep>source 'https://rubygems.org'
ruby '2.2.1'
gem 'rails', '4.2.1'
gem "mongoid", "~> 4.0.2"
gem 'jbuilder', '~> 2.0'
gem "newrelic_rpm", ">= 3.9.8"
gem 'unicorn'
gem 'bcrypt', '~> 3.1.7'
gem 'active_hash'
gem 'rack-cors', :require => 'rack/cors'
gem 'mandrill-api'
gem 'rails_12factor'
group :development do
gem "spring"
gem "spring-commands-rspec"
gem "web-console"
gem "better_errors"
gem "binding_of_caller"
end
group :development, :test do
gem "awesome_print"
gem "bundler-audit", require: false
gem "byebug"
gem "dotenv-rails"
gem "factory_girl_rails"
gem "pry-rails"
gem "rspec-rails", "~> 3.0"
end
<file_sep>Rails.application.routes.draw do
resources :tao_bao_items, only: [:index]
end
<file_sep>require 'rails_helper'
RSpec.describe TaoBaoItemsController, type: :controller do
end
<file_sep>class Race
include Mongoid::Document
field :distance, type: String
field :date, type: String
field :racenumber, type: Integer
field :rank, type: String
field :number, type: String
field :horse, type: String
field :jockey, type: String
field :trainer, type: String
field :actualweight, type: Integer
field :horseweight, type: Integer
field :draw, type: String
field :lbw, type: String
field :finishtime, type: String
field :odd, type: Float
end
|
54267988d2a47bd65c0e39337f3328b84f19113c
|
[
"Ruby"
] | 5
|
Ruby
|
sion10/Jockey_Scrape
|
b0201f48b8464815093c0079554b53cb77b9b0f8
|
b0188740b849d1475f1faf6ba1fc957b313cd5c6
|
refs/heads/master
|
<file_sep>import React from 'react';
import { HashRouter as Router, Route } from 'react-router-dom';
import withTracker from '../../withTracker';
import Navigation from '../Navigation';
import SignUpPage from '../SignUp';
import SignInPage from '../SignIn';
import PasswordForgetPage from '../PasswordForget';
import AccountPage from '../Account';
import NotesPage from '../Notes';
import { withAuthentication } from '../Session';
import * as ROUTES from '../../constants/routes';
const App = () => (
<Router>
<div className="app">
<Navigation />
<hr />
<Route exact path={ROUTES.DEFAULT} component={withTracker(NotesPage)} />
<Route exact path={ROUTES.NOTES} component={withTracker(NotesPage)} />
<Route exact path={ROUTES.SIGN_UP} component={withTracker(SignUpPage)} />
<Route exact path={ROUTES.SIGN_IN} component={withTracker(SignInPage)} />
<Route exact path={ROUTES.PASSWORD_FORGET} component={withTracker(PasswordForgetPage)} />
<Route exact path={ROUTES.ACCOUNT} component={withTracker(AccountPage)} />
<hr />
</div>
</Router>
);
export default withAuthentication(App);
<file_sep>import React from 'react';
import Nav from 'react-bootstrap/lib/Nav';
import Navbar from 'react-bootstrap/lib/Navbar';
import Alert from 'react-bootstrap/lib/Alert';
import ReactGA from 'react-ga';
import { AuthUserContext } from '../Session';
import SignOutButton from '../SignOut';
import * as ROUTES from '../../constants/routes';
const Navigation = () => (
<Navbar bg="light" expand="lg">
<Navbar.Brand href="/">Notepad</Navbar.Brand>
<Navbar.Collapse id="basic-navbar-nav">
<AuthUserContext.Consumer>
{authUser => (authUser ? <NavigationAuth authUser={authUser} /> : <NavigationNonAuth />)}
</AuthUserContext.Consumer>
</Navbar.Collapse>
<Alert key="info" variant="info">
{'Under construction - '}
<ReactGA.OutboundLink
eventLabel="https://github.com/ayildirim/notepad"
to="https://github.com/ayildirim/notepad"
target="_blank"
>
{"See what's cooking"}
</ReactGA.OutboundLink>
</Alert>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
</Navbar>
);
const NavigationAuth = ({ authUser }) => (
<Nav className="mr-auto">
<Nav.Link href={`/#${ROUTES.NOTES}`}>Notes</Nav.Link>
<Nav.Link href={`/#${ROUTES.ACCOUNT}`}>Account</Nav.Link>
<SignOutButton />
</Nav>
);
const NavigationNonAuth = () => (
<Nav className="mr-auto">
<Nav.Link href={`/#${ROUTES.SIGN_IN}`}>Sign in</Nav.Link>
</Nav>
);
export default Navigation;
<file_sep>import React, { Component } from 'react';
import axios from 'axios';
import { API_URL } from './Config';
export default function withBackend(WrappedComponent) {
const Backend = class extends Component {
getDataFromDb = async () => {
const res = await axios.post(`${API_URL}/api/getData`, {
jwt: JSON.parse(localStorage.getItem('authUser')).jwt,
});
return res.data;
};
putDataToDB = async (message) => {
const res = await axios.post(`${API_URL}/api/putData`, {
message,
jwt: JSON.parse(localStorage.getItem('authUser')).jwt,
});
return res;
};
deleteFromDB = async (idTodelete) => {
const res = await axios.delete(`${API_URL}/api/deleteData`, {
data: {
_id: idTodelete,
jwt: JSON.parse(localStorage.getItem('authUser')).jwt,
},
});
return res;
};
updateDB = async (idToUpdate, updateToApply) => {
const res = await axios.post(`${API_URL}/api/updateData`, {
id: idToUpdate,
update: { message: updateToApply },
jwt: JSON.parse(localStorage.getItem('authUser')).jwt,
});
return res;
};
render() {
return <WrappedComponent {...this.props} backend={this} />;
}
};
return Backend;
}
<file_sep>Backend : [](https://david-dm.org/ayildirim/notepad?path=packages%2Fbackend) [](https://david-dm.org/ayildirim/notepad?path=packages%2Fbackend&type=dev)
Frontend : [](https://circleci.com/gh/ayildirim/notepad)
[](https://david-dm.org/ayildirim/notepad?path=packages%2Ffrontend) [](https://david-dm.org/ayildirim/notepad?path=packages%2Ffrontend&type=dev)
### Deployment
- Set MONGOLAB_URI environment variable with your Mongo DB credentials and path
- Run Deploy step described in the CircleCI configuration file on your server
- Initialize the API server using PM2: "pm2 start npm -- start --watch"
### Development environment
- Visual Studio Code is the configured tool for the project
- Configuration of vscode settings & extensions are in the /.vscode/settings.json
### JS Dev Utilities and Code Hygiene
- Yarn for dependency management
- Eslint for code syntax
- Prettier for code formatting
- Flow for data type safety
- Husky precommit hooks for running tests locally prior to commits made locally
|
18027c441add1bcbfd4dfa80aba9acefc4060b28
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
maxabrahamsson/notepad
|
cd6263b8eede5b11061b76b910a16ac05af2e47b
|
3f662541663db9e5a00a14206919aaea32baec0e
|
refs/heads/master
|
<repo_name>zhouhaoxiang/webpackAndReactStudy<file_sep>/todoListwithredux/containers/inputwithconnect.js
import {connect} from 'react-redux';
import {addTodo,saveInfo,changeColor} from './../actions/action'
import defaultFunc from './../actions/action'
import Input from './../components/input';
import {bindActionCreators} from 'redux';
function mapDispatchToProps(dispatch) {
return{
// addTodo:()=>{
// dispatch(addTodo());
// },
addTodo:bindActionCreators(addTodo,dispatch),
inputChange:(e)=>{
dispatch(saveInfo(e.target.value));
},
async:()=>{
dispatch(defaultFunc.fetchInfo())
},
changeColor:()=>{
dispatch(changeColor())
}
}
}
function mapStateToProps(state) {
return{
input: state.a.input,
time: state.b.time,
color: state.b.color,
}
}
const Inputwith=connect(
mapStateToProps,mapDispatchToProps
)(Input);
export default Inputwith;<file_sep>/README.md
# wepackAndReactStudy
react16 redux react-router4 webpack
<file_sep>/todoListwithredux/components/input.js
import React from 'react';
class Input extends React.Component{
constructor(props){
super(props);
}
render(){
return(
<div>
<input value={this.props.input} onChange={this.props.inputChange}/>
<button onClick={this.props.addTodo}>AddTodo</button>
<button onClick={this.props.async}>async</button>
<span onClick={this.props.changeColor} style={{background: this.props.color}}>{this.props.time}</span>
</div>
)
}
}
export default Input
<file_sep>/react-router/index.js
import React from 'react'
import ReactDom from 'react-dom'
// 首先我们需要导入一些组件...
import {BrowserRouter ,HashRouter, Switch ,Route, Link } from 'react-router-dom'
function Header() {
return(
<div>Header</div>
)
}
function Main() {
return(
<div>Main</div>
)
}
const App=()=>(
<div>
<Header/>
<Main/>
</div>
)
// ReactDom.render(
// <HashRouter>
// <div>
// <li><Link to='/main'>main</Link></li>
// <Route exact path='/' component={App}/>
// <Route path='/main' component={Main}/>
// <li><Link to='/'>back</Link></li>
// </div>
// </HashRouter>
// , document.getElementById('root')
// )
const Home = () => (
<div>
<h2>Home</h2>
</div>
)
const About = () => (
<div>
<h2>About</h2>
</div>
)
const Topic = ({ match }) => (
<div>
<h3>{match.params.topicId}</h3>
</div>
)
const Topics = ({ match }) => {
console.log(match);
return(
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${match.url}/rendering`}>
Rendering with React
</Link>
</li>
<li>
<Link to={`${match.url}/components`}>
Components
</Link>
</li>
<li>
<Link to={`${match.url}/props-v-state`}>
Props v. State
</Link>
</li>
</ul>
<Route path={`${match.url}/:topicId`} component={Topic}/>
<Route exact path={match.url} render={() => (
<h3>Please select a topic.</h3>
)}/>
</div>
)}
const BasicExample = () => (
<BrowserRouter>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/topics123">Topics</Link></li>
</ul>
<hr/>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
<Route path="/topics123" component={Topics}/>
</div>
</BrowserRouter>
)
ReactDom.render(
<BasicExample/>,
document.getElementById('demo')
)<file_sep>/todoListwithredux/index.js
import React from 'react'
import App from './components/App';
import ReactDom from 'react-dom';
import {createStore,applyMiddleware} from 'redux';
import Reducers from './reducers/addTodo'
import {Provider} from 'react-redux';
import {createLogger} from 'redux-logger';
import thunk from 'redux-thunk'
const logger = createLogger();
let initalState={a:{input:'',content:[]},b:{time: 0,color:'red'}};
let store=createStore(Reducers,initalState,applyMiddleware(thunk));
store.subscribe(function () {
console.log(store.getState());
console.log('change');
})
ReactDom.render(
<Provider store={store}>
<App/>
</Provider>,
document.getElementById('root')
)<file_sep>/todoListwithredux/containers/Listwithconnect.js
import {connect} from 'react-redux';
import List from './../components/List';
import {deleteTask} from "../actions/action";
function mapStateToProps(state) {
return{
content:state.a.content
}
}
function mapDispatchToProps(dispatch) {
return{
delete:(e)=>{
console.log(e.target.id)
dispatch(deleteTask(e.target.id));
}
}
}
const Listwith=connect(
mapStateToProps,
mapDispatchToProps
)(List)
export default Listwith;<file_sep>/todoListwithredux/components/App.js
import React from 'react';
import Listwith from './../containers/Listwithconnect';
import Inputwith from './../containers/inputwithconnect';
class App extends React.Component{
render(){
return(
<div>
<Inputwith/>
<Listwith/>
</div>
)
}
}
export default App;<file_sep>/todoListwithredux/components/List.js
import React from 'react';
import './List.css';
class List extends React.Component{
render(){
return(
<ul>
<li className="top">下面是todoList</li>
{
this.props.content.map((item,index)=>{
return <li key={item.id}>{item.value}<button id={item.id} onClick={this.props.delete}>删除</button></li>
})
}
</ul>
)
}
}
export default List
|
57e18d2648fa2cffff60dd6d7ddbe3ec8ada104a
|
[
"JavaScript",
"Markdown"
] | 8
|
JavaScript
|
zhouhaoxiang/webpackAndReactStudy
|
076645a8e7db643f86566cf7d7e09dc312d17c32
|
2ea06141c6507bceb988402eb9e01a0a30d62a1d
|
refs/heads/master
|
<repo_name>htelahun/telahun_h_3014_hw3<file_sep>/admin/phpscripts/sessions.php
<?php
//protecting the admin_index page, only shows info on page if logged in
session_start();
function confirm_logged_in(){
if (!isset($_SESSION['user_id'])) {
redirect_to("admin_login.php");
}
}
function logged_out(){
session_destroy();
redirect_to("admin_index.php");
}
//link to function in admin_index.php, sends you to the index page if you kill the browser then sign in again
function first_log(){
if (!isset($_SESSION['FirstVisit'])) {
$_SESSION['FirstVisit'] = 1;
redirect_to("admin_edit.php");
}
}
?>
<file_sep>/admin/admin_edit.php
<?php
//init_set('display_errors', 1);//mac
//error_reporting(E_All); //mac
require_once('phpscripts/config.php');
//confirm_logged_in();
//grab the id from the session
$id = $_SESSION['user_id'];
//echo $id;
//get single function on read.php file
$tbl = "tbl_user";
$col = "user_id";
$popform = getSingle($tbl, $col, $id);
//make info into array, echo in the HTML code
$found_user = mysqli_fetch_array($popform, MYSQLI_ASSOC);
//echo $found_user;
if(isset($_POST['submit'])){
$fname = trim($_POST ['fname']);
$username = trim($_POST['username']);
$password = trim($_POST['<PASSWORD>']);
$email = trim($_POST['email']);
$result = editUser($id, $fname, $username, $password, $email);
$message = $result;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../css/login.css">
<title>Edit user</title>
</head>
<body>
<header>
<ul>
<li >
<a class="loginimg" href="admin_index.php"> <img src="../images/back.png" alt="">
</a>
</li>
</ul>
<h1 class="header">EDIT USER</h1>
</header>
<?php if(!empty($message)){echo $message;} ?>
<form class="mid" action="admin_edit.php" method="post">
<label style="color:white;font-weight:bold;" class="mid">FIRST NAME</label>
<input style="color:white;" class="center-input" type="text" name="fname" value=" <?php echo $found_user['user_fname']; ?>"><br><br>
<label style="color:white;font-weight:bold;" class="mid">USERNAME </label>
<input class="center-input" type="text" name="username" value=" <?php echo $found_user['user_name']; ?>"><br><br>
<label style="color:white;font-weight:bold;" class="mid ">PASSWORD </label>
<input class="center-input" type="text" name="password" value=" <?php echo $found_user['user_pass']; ?>"><br><br>
<label style="color:white;font-weight:bold;" class="mid">E-MAIL</label>
<input class="center-input" type="text" name="email" value="<?php echo $found_user['user_email']; ?>"><br><br>
<input style="margin-top:5%;margin-bottom:5%;" class="center-btn2" type="submit" name="submit" value="Edit Account">
</form>
</script>
</body>
</html>
<file_sep>/admin/phpscripts/login.php
<?php
function logIn($username, $password, $ip)
{
require_once('connect.php');
$username = mysqli_real_escape_string($link, $username);
$password = mysqli_real_escape_string($link, $password);
$loginstring = "Select * from tbl_user where user_name = '{$username}' and user_pass = '{$password}'";
$loginUser = "Select * from tbl_user where user_name = '{$username}'";
$user_set = mysqli_query($link, $loginstring);
$user_only = mysqli_query($link, $loginUser);
if(mysqli_num_rows($user_set))
{
$founduser = mysqli_fetch_array($user_set, MYSQLI_ASSOC);
$id = $founduser['user_id'];
$_SESSION['user_id'] = $id;
$_SESSION['user_name'] = $founduser['user_name'];
$_SESSION['user_date'] = $founduser['user_date'];
$_SESSION['user_attempts'] = $founduser['user_attempts'];
$firstLog = $founduser['user_edit'];
if($firstLog == NULL){
$first = "UPDATE tbl_user set user_edit = CURRENT_TIMESTAMP where user_id = {$id}";
$firstupdate = mysqli_query($link, $first);
redirect_to('admin/admin_edit.php');
}else{
redirect_to('admin/admin_index.php');
}
if(mysqli_query($link, $loginstring))
{
$noattempts = $founduser['user_attempts'];
if($noattempts <= 3)
{
$update = "UPDATE tbl_user set user_ip='{$ip}' where user_id = {$id} ";
$updatequery = mysqli_query($link, $update);
$lastlog = "select user_date from tbl_user where user_id = {$id}";
$lastlogQuery = mysqli_query($link, $lastlog);
$time = "UPDATE tbl_user set user_date = CURRENT_TIMESTAMP where user_id = {$id}";
$timeupdate = mysqli_query($link, $time);
$attempsvalue = "UPDATE tbl_user set user_attempts='0' where user_name = '{$username}' ";
$attempsvalueupdate = mysqli_query($link, $attempsvalue);
}
else{
redirect_to("admin/admin_lockout.php");
}
}
{
redirect_to("admin/admin_index.php");
}
}
elseif(mysqli_num_rows($user_only)){
$founduser = mysqli_fetch_array($user_only, MYSQLI_ASSOC);
$_SESSION['user_name'] = $founduser['user_fname'];
$_SESSION['user_attempts'] = $founduser['user_attempts'];
$_SESSION['user_edit'] = $founduser['user_edit'];
$_SESSION['user_attempts'] += 1;
$attempts = $_SESSION['user_attempts'];
$fail = "UPDATE tbl_user set user_attempts='{$attempts}' where user_name = '{$username}' ";
$failupdate = mysqli_query($link, $fail);
$msg ="Wrong info";
return $msg;
}
else{
$msg ="Wrong ";
return $msg;
}
mysqli_close($link);
}
?>
<file_sep>/admin/admin_index.php
<?php
require_once('phpscripts/config.php');
confirm_logged_in();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CMS Homepage</title>
<link rel="stylesheet" href="../css/login.css">
</head>
<body>
<header>
<ul>
<li >
<a class="logout" href="../index.php">LOGOUT</a>
</li>
</ul>
</header>
<section class="login-box">
<div class="center-2">
<?php
echo "<h1> Hello {$_SESSION['user_name']}!</h1>";
echo "<p> Your last log in was on : {$_SESSION['user_date']}</p>";
?>
</div>
<a class="link1 click" href="admin_add.php">CREATE USER</a>
<a class=" click" href="admin_edit.php">EDIT USER</a>
<a class="click" href="admin_delete.php">DELETE USER</a>
</section>
</body>
</html>
<file_sep>/admin/admin_lockout.php
<?php
require_once('phpscripts/config.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CMS Homepage</title>
<link rel="stylesheet" href="../css/login.css">
</head>
<body>
<section class="login-box">
<div class="center-2">
<h1 style="text-align:center;margin-top:20%;">Incorrect login information. <br><br>Try again later.</h1>
</div>
</section>
</body>
</html>
<file_sep>/admin/admin_add.php
<?php
//init_set('display_errors', 1);//mac
//error_reporting(E_All); //mac
require_once('phpscripts/config.php');
confirm_logged_in();
if(isset($_POST['submit'])){
$fname = trim($_POST ['fname']);
$username = trim($_POST['username']);
// $password = trim($_POST['password']);
$email = trim($_POST['email']);
$userlvl = $_POST['userlvl'];
if(empty($userlvl)){
$message = "Please select user level";
}else {
$result = createUser($fname, $username,$email, $userlvl);
$message = $result;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="../css/login.css">
<title>Create User</title>
</head>
<body>
<header>
<ul>
<li >
<a class="loginimg" href="admin_index.php"> <img src="../images/back.png" alt="">
</a>
</li>
</ul>
<h1 class="header">CREATE USER</h1>
</header>
<?php if(!empty($message)){echo $message;} ?>
<form action="admin_add.php" method="post" enctype="multipart/form-data"><!--default to text only in form. wont work for img or video. multipart expects something other than text there. Allows for upload of files. takes care of going to the server for us-->
<label style="color:white;font-weight:bold;" class="mid">FIRST NAME</label>
<input style="color:white;" class="center-input" type="text" name="fname"value="" <?php if(!empty($fname)){echo $fname;} ?>><br><br>
<label style="color:white;font-weight:bold;" class="mid">USERNAME </label>
<input class="center-input" type="text" name="username" value="" <?php if(!empty($username)){echo $username;} ?>><br><br>
<label style="color:white;font-weight:bold;" class="mid">E-MAIL</label>
<input class="center-input" type="text" name="email" value="" <?php if(!empty($email)){echo $email;} ?>><br><br>
<label style="color:white;font-weight:bold;" class="mid">USER LEVEL </label>
<select class="mid center-input" name="userlvl">
<option value="">Please select user level</option>
<option value="2">Web Admin</option>
<option value="1">Web master</option>
</select><br><br>
<input style="margin-top:5%;" class="center-btn2" type="submit" name="submit" value="Create User">
</form>
</body>
</html>
<file_sep>/admin/admin_delete.php
<?php
//init_set('display_errors', 1);//mac
//error_reporting(E_All); //mac
require_once('phpscripts/config.php');
//confirm_logged_in();
$tbl = "tbl_user";
$user = getAll($tbl);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../css/login.css">
<title>Delete User</title>
</head>
<body>
<header>
<ul>
<li >
<a class="loginimg" href="admin_index.php"> <img src="../images/back.png" alt="">
</a>
</li>
</ul>
<h1 class="header">DELETE USER</h1>
</header>
<section>
<div >
<ul class="position">
<li class="movies">
<?php
while($row = mysqli_fetch_array($user)){
//
echo "<p style=\"margin-left:20%;\" >{$row['user_fname']}</p> <a style=\"margin-top:-45px;margin-left:200px;width:90px;padding: 10px;border: solid 1px white;background-color: #464646;color: white;float: left;text-decoration:none;\" href=\"phpscripts/caller.php?caller_id=delete&id={$row['user_id']}\">Delete User</a><br>";
}
?>
</li>
</ul>
</div>
</section>
</body>
</html>
<file_sep>/index.php
<?php
//init_set('display_errors', 1);//mac
//error_reporting(E_All); //mac
require_once('admin/phpscripts/config.php');
//what ip address youre signing in at
//test it localhost/MMED_3014_18/admin/admin_login.php
//php.net there are $_SERVER options
$ip = $_SERVER['REMOTE_ADDR'];
//echo $ip;
if (isset($_POST['submit'])) {
//trim gets rid of whitespace
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if ($username !=="" && $password !=="") {
// echo "you can type";
$result = logIn($username, $password, $ip);
$message = $result;
}else{
$message ="Please fill in the required fields";
//echo $message;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Admin Login</title>
<link rel="stylesheet" href="css/login.css">
</head>
<body>
<!-- <div class="forgot-box">
<p>Username : Hana <br><br> Password: 123</p>
</div> -->
<div class="login-box">
<h1 class="center-t">ADMIN LOGIN</h1>
<p class="center1">
<?php
if(!empty($message)){
echo $message;
}
?>
</p>
<form action="index.php" method="post">
<input class="center" type="text" name="username" placeholder="USERNAME">
<img alt="">
<br><br>
<input class="center" type="text" name="password" placeholder="<PASSWORD>">
<br><br>
<a class="forgot" href="#">Forgot Password?</a>
<input class="center-btn" type="submit" name="submit" value="LOGIN">
</form>
</div>
<script src="js/main.js">
</script>
</body>
</html>
<file_sep>/js/main.js
(function() {
var forgot = document.querySelector(".forgot");
var loginBox = document.querySelector(".login-box");
function popup() {
// loginBox.style.visibility = "hidden";
console.log("done");
}
forgot.addEventListener('click',popup,false);
})();
<file_sep>/admin/phpscripts/read.php
<?php
// get all of something
function getAll($tbl){
include('connect.php');
$queryAll = "SELECT * FROM {$tbl}";
$runAll = mysqli_query($link, $queryAll);
if($runAll){
return $runAll;
}else{
$error ="there was an error accessing this info. Please contact your admin.";
return $error;
}
mysqli_close($link);
}
function getSingle($tbl,$col,$id){
include('connect.php');
$querySingle = "SELECT * FROM {$tbl} WHERE {$col} = {$id}";
$runSingle = mysqli_query($link, $querySingle);
if($runSingle){
return $runSingle;
}else{
$error ="there was an error accessing this info. Please contact your admin.";
return $error;
}
mysqli_close($link);
}
function filterType($tbl,$tbl2, $tbl3, $col, $col2, $col3, $filter){
//convert your SQL query from phpmyadmin to variables, variablesin final query need to be in curly brackets
//$tbl = "tbl_movies";
//$tbl2 ="tbl_genre";
//$tbl3 = "tbl_mov_genre";
//$col="movies_id";
//$col2 = "genre_id";
//$col3 = "genre_name";
//$filter
//move all of the above variables to the index page or whereever the condition is set
include('connect.php');
$queryFilter="SELECT * FROM {$tbl} , {$tbl2}, {$tbl3} WHERE {$tbl}.{$col} = {$tbl3}.{$col} AND {$tbl2}.{$col2} = {$tbl3}.{$col2} AND {$tbl2}.{$col3}= '{$filter} '";
//echo $queryFilter; //to test if the queries working copy and paste in the SQL section phpmyadmin
$runFilter = mysqli_query($link, $queryFilter);
if($runFilter){
return $runFilter;
}else{
$error = "There was an error accesing this info";
return error;
}
mysqli_close($link);
}
?>
|
653ce93ae9a8d102357482c792752c33c45f6ca6
|
[
"JavaScript",
"PHP"
] | 10
|
PHP
|
htelahun/telahun_h_3014_hw3
|
1e1bb6bb400c3d5214d8429a53aa180589f6d46d
|
a5bf868dac80a69a73bf7f1bacb979c779362585
|
refs/heads/master
|
<repo_name>gyangsob/algorithmstudy<file_sep>/mercy/mercy.c
#include <stdio.h>
int main(void)
{
unsigned int input_num; // Input contains just one positive integer N
scanf("%d", &input_num);
// for optimization...
while(input_num > 0) {
printf("Hello Algospot!\n");
input_num--;
}
return 0;
}
<file_sep>/draw/draw.c
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int * p1_x;
int * p2_x;
int * p3_x;
int * p1_y;
int * p2_y;
int * p3_y;
int * p4_x;
int * p4_y;
int i, t;
scanf("%d", &t);
// 입력받은 TC개수만큼 int 변수 dynamic allocation
p1_x = (int *)malloc((sizeof(int))*t);
p2_x = (int *)malloc((sizeof(int))*t);
p3_x = (int *)malloc((sizeof(int))*t);
p1_y = (int *)malloc((sizeof(int))*t);
p2_y = (int *)malloc((sizeof(int))*t);
p3_y = (int *)malloc((sizeof(int))*t);
p4_x = (int *)malloc((sizeof(int))*t);
p4_y = (int *)malloc((sizeof(int))*t);
for(i=0; i < t; i++){
// 3개의 꼭지점 정보 입력
scanf("%d %d",&p1_x[i], &p1_y[i]);
scanf("%d %d",&p2_x[i], &p2_y[i]);
scanf("%d %d",&p3_x[i], &p3_y[i]);
// 남은 한 점의 좌표는 세점을 xor 연산한 결과
p4_x[i] = p1_x[i] ^ p2_x[i] ^ p3_x[i];
p4_y[i] = p1_y[i] ^ p2_y[i] ^ p3_y[i];
}
for(i=0; i<t; i++){
printf("%d %d\n", p4_x[i], p4_y[i]);
}
// 할당한 변수 해제
free(p1_x);
free(p2_x);
free(p3_x);
free(p1_y);
free(p2_y);
free(p3_y);
free(p4_x);
free(p4_y);
}
<file_sep>/miss_spell/miss_spell.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRING_MAX 1000+1
#define TC_MAX 10
#define TC_MIN 1
char * miss_spell(int, char *);
int main(void)
{
int i;
int miss_spell_num;
int tc_num;
char input_string[STRING_MAX];
char **out_str;
scanf("%d", &tc_num);
out_str = (char **)malloc(sizeof(char *)*tc_num);
for(i=0; i<tc_num; i++){
out_str[i] = (char *)malloc(sizeof(char)*STRING_MAX);
}
for(i=0; i<tc_num; i++) {
scanf("%d %s", &miss_spell_num, input_string);
out_str[i] = miss_spell(miss_spell_num, input_string);
}
for(i=0; i<tc_num; i++) {
printf("%d %s\n", i+1, out_str[i]);
}
for(i=0; i<tc_num; i++) {
free(out_str[i]);
}
free(out_str);
return 0;
}
char *miss_spell(int miss_spell_num, char *input_string)
{
char *return_string;
return_string = (char *)malloc(sizeof(char)*STRING_MAX);
// return_string에 input_string의 시작주소부터 제거할 문자가 있는 위치-1까지 붙여넣는다
strncat(return_string, input_string, miss_spell_num-1);
// return_string에 제거할 문자 다음 위치부터 문자열의 끝까지 붙여넣는다
// 전체 문자열의 길이에서 제거할 문자의 위치를 뺀 뒤 1을 더하면 남은 문자열 개수를 구할 수 있다
// strncat은 dest 문자열의 결과를 리턴한다.
// strncat은 dest 문자열의 \0을 찾아 그 위치부터 src의 문자열을 복사한다.
strncat(return_string, input_string+miss_spell_num, strlen(input_string)-miss_spell_num+1);
return return_string;
}
<file_sep>/encrypt/encrypt.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRING_MAX 100+1
char * enc_str(char *);
int main(void)
{
int tc_num, i;
char input_string[STRING_MAX]={0,};
char **out_str;
scanf("%d", &tc_num);
out_str=(char**)malloc(sizeof(char*)*tc_num);
for(i=0; i<tc_num; i++) {
out_str[i]=(char*)malloc(sizeof(char)*STRING_MAX);
memset(out_str[i], 0, sizeof(char)*STRING_MAX);
scanf("%s", input_string);
out_str[i] = enc_str(input_string);
}
for(i=0; i<tc_num; i++)
printf("%s\n", out_str[i]);
// free memory
for(i=0; i<tc_num; i++) {
free(out_str[i]);
}
free(out_str);
}
char *enc_str(char *input_string)
{
int i;
char *output_string;
output_string = (char*)malloc(sizeof(char)*STRING_MAX);
// first, add charater where located even index
for(i=0; i<strlen(input_string); i++){
if(i%2==0) // even number
strncat(output_string, input_string+i, 1);
}
// and add charater where located odd index
// this way is valid because feature of strncat function : strncat return resulting destination pointer.
for(i=0; i<strlen(input_string); i++){
if(i%2==1) // odd number
strncat(output_string, input_string+i, 1);
}
return output_string;
}
<file_sep>/xhaeneung/xhaeneung.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRING_MAX 30+1
#define TC_MAX 10
#define TC_MIN 1
typedef struct _score{
char *operand_str1;
char *operand_str2;
char *answer_str;
char operator;
int operand_int1;
int operand_int2;
int result;
} score_t;
char *my_gets(char*, int);
int convert_string_to_int(char *);
char *convert_int_to_string(int);
int check_string(char *, char *);
char find_operator(char *);
extern char *strtok_r(char *, const char *, char **);
int main(void)
{
int tc_num, i;
char *token;
char *saveptr;
char *out_str;
char input_string[STRING_MAX]={0,};
score_t **score_data;
scanf("%d", &tc_num);
getchar(); // for flushing stdin buffer
// pointer initialize
out_str = (char *)malloc(sizeof(char)*STRING_MAX);
score_data = (score_t **)malloc(sizeof(score_t *)*tc_num);
for(i=0; i<tc_num; i++){
score_data[i] = (score_t *)malloc(sizeof(score_t));
score_data[i]->operand_str1 = (char *)malloc(sizeof(char)*STRING_MAX);
score_data[i]->operand_str2 = (char *)malloc(sizeof(char)*STRING_MAX);
score_data[i]->answer_str = (char *)malloc(sizeof(char)*STRING_MAX);
}
for(i=0; i<tc_num; i++){
// fgets함수를 이용해 stdin으로부터 입력을 받으면 \n문자까지 입력되기 때문에 \n을 \0으로 교체하는 api 사용
strcpy(out_str, my_gets(input_string, STRING_MAX));
// +,-,* 연산기호 찾기
score_data[i]->operator = find_operator(out_str);
// 연산 기호를 기준으로 문자열 parsing
token = strtok_r(out_str, "+-*= ", &saveptr);
strcpy(score_data[i]->operand_str1, token);
token = strtok_r(saveptr, "+-*= ", &saveptr);
strcpy(score_data[i]->operand_str2, token);
token = strtok_r(saveptr, "+-*= ", &saveptr);
strcpy(score_data[i]->answer_str, token);
// string을 integer로 변환
score_data[i]->operand_int1 = convert_string_to_int(score_data[i]->operand_str1);
score_data[i]->operand_int2 = convert_string_to_int(score_data[i]->operand_str2);
// 연산기호에 따라서 계산하기
switch(score_data[i]->operator){
case '+':
score_data[i]->result = score_data[i]->operand_int1 + score_data[i]->operand_int2;
break;
case '*':
score_data[i]->result = score_data[i]->operand_int1 * score_data[i]->operand_int2;
break;
case '-':
score_data[i]->result = score_data[i]->operand_int1 - score_data[i]->operand_int2;
break;
}
}
for(i=0; i<tc_num; i++){
// 채점 조건에 따라 10보다 크거나 0보다 작은 수는 오답처리
if(score_data[i]->result > 10 || score_data[i]->result < 0){
printf("No\n");
}
// 그 외 숫자에 대해서
else{
// 입력한 문자열과 계산 결과가 서로 anagram인지 확인하여
// anagram일 경우 Yes 출력
if(check_string(score_data[i]->answer_str, convert_int_to_string(score_data[i]->result))){
printf("Yes\n");
}
// anagram아 아닐 경우No 출력
else {
printf("No\n");
}
}
}
// 할당한 자원 해제
for(i=0; i<tc_num; i++){
free(score_data[i]->operand_str1);
free(score_data[i]->operand_str2);
free(score_data[i]->answer_str);
free(score_data[i]);
}
free(out_str);
free(score_data);
}
char *my_gets(char *str, int size)
{
int len, i;
fgets(str, size, stdin);
len = strlen(str);
// 문자열의 끝까지
for(i=0; i<len; i++){
// 개행문자를 널문자로 변경
if(str[i] == '\n')
str[i] = '\0';
}
return str;
}
char find_operator(char *str)
{
int len, i;
char ret_val;
len = strlen(str);
// 입력형식이 정해져있기 때문에 연산기호는 하나만 찾으면 된다
for(i=0; i<len; i++){
if(str[i] == '+' || str[i] == '-' || str[i] == '*'){
ret_val = str[i];
break;
}
}
return ret_val;
}
int convert_string_to_int(char *str)
{
if(!strcmp(str, "zero")) return 0;
else if(!strcmp(str, "one")) return 1;
else if(!strcmp(str, "two")) return 2;
else if(!strcmp(str, "three")) return 3;
else if(!strcmp(str, "four")) return 4;
else if(!strcmp(str, "five")) return 5;
else if(!strcmp(str, "six")) return 6;
else if(!strcmp(str, "seven")) return 7;
else if(!strcmp(str, "eight")) return 8;
else if(!strcmp(str, "nine")) return 9;
else if(!strcmp(str, "ten")) return 10;
else return -1;
}
char *convert_int_to_string(int num)
{
if(num == 0) return "zero";
else if(num == 1) return "one";
else if(num == 2) return "two";
else if(num == 3) return "three";
else if(num == 4) return "four";
else if(num == 5) return "five";
else if(num == 6) return "six";
else if(num == 7) return "seven";
else if(num == 8) return "eight";
else if(num == 9) return "nine";
else if(num == 10) return "ten";
else return NULL;
}
// 두 문자열이 서로 anagram 관계인지 확인하는 함수
int check_string(char *str1, char *str2)
{
int i, x;
int count1[128]={0,};
int count2[128]={0,};
// 문자열의 끝까지
for(i=0; str1[i]; i++){
x = str1[i] | 32; // char에 ascii코드 값을or 연산하여 배열의 index로 사용
count1[x]++;
}
for(i=0; str2[i]; i++){
x = str2[i] | 32;
count2[x]++;
}
// 두 int 배열의 값이 같지 않으면 anagram 관계가 아니다
for(i='a'; i<='z'; i++){
if(count1[i] != count2[i]) break;
}
// 중간에 빠져나왔으면 anagram 관계가 아니기 때문에
// anagram 관계일 때에 i값은 z보다 크다.
if(i > 'z') return 1;
else return 0;
}
<file_sep>/uri/uri.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRING_MAX (80+1)
#define TC_MAX 10
#define TC_MIN 1
char * adjust_string(char *, int);
int main(void)
{
int tc_num=0;
int i, j=0;
char input_string[STRING_MAX], token[STRING_MAX];
char **result;
char *temp;
scanf("%d", &tc_num);
getchar();
result = (char **)malloc(sizeof(char *)*tc_num);
for(i=0; i<tc_num; i++){
result[i] = (char *)malloc(sizeof(char)*STRING_MAX);
}
for(i=0; i<tc_num; i++) {
j=0;
scanf("%s", input_string);
getchar();
temp = input_string;
// end of string
while(temp[j] != '\0'){
// check encoded token if char of 'n' index == % and char of 'n+1' index == 2
if(temp[j] == '%' && temp[j+1] && temp[j+1] == '2'){
switch (temp[j+2]){
case '0':
// swap %20 to ' '
temp[j] = ' ';
temp = adjust_string(temp, j);
break;
case '1':
// swap %21 to '!'
temp[j] = '!';
temp = adjust_string(temp, j);
break;
case '4':
// swap %24 to '$'
temp[j] = '$';
temp = adjust_string(temp, j);
break;
case '5':
// swap %25 to '%'
temp[j] = '%';
temp = adjust_string(temp, j);
break;
case '8':
// swap %28 to '('
temp[j] = '(';
temp = adjust_string(temp, j);
break;
case '9':
// swap %29 to ')'
temp[j] = ')';
temp = adjust_string(temp, j);
break;
case 'a':
// swap %2a to '*'
temp[j] = '*';
temp = adjust_string(temp, j);
break;
}
}
j++;
}
strncpy(result[i], temp, strlen(temp));
memset(input_string, '\0', STRING_MAX);
}
for(i=0; i<tc_num; i++){
printf("%s\n", result[i]);
}
}
// function name : adjust_string
// input : char *str, int index
// output : char *
// purpose : for strip string, after changing encoded character to decoded character
// index marks a position of '%' character before changing decoded character.
char * adjust_string(char *str, int index)
{
char *ret_string;
ret_string = (char *)malloc(sizeof(char)*(strlen(str)));
// The decoded character remain using strncat from string[0] to string[index+1]
strncat(ret_string, str, index+1);
// and remove 2 more characters
strncat(ret_string, str+index+3, strlen(str)-index-3);
return ret_string;
}
<file_sep>/anagram/anagram.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRING_MAX (100+1)
int check_anagram(char *, char *);
int check_string_order(char *, char *);
int main(void)
{
int tc_num = 0;
int i;
char token1[STRING_MAX], token2[STRING_MAX];
char **result;
scanf("%d", &tc_num);
getchar();
result = (char **)malloc(sizeof(char *)*tc_num);
for(i=0; i<tc_num; i++)
result[i] = (char *)malloc(sizeof(char)*4);
for(i=0; i<tc_num; i++){
scanf("%s", token1);
scanf("%s", token2);
// check_anagram returns 1 if two strings are consist of same characters.
// check anagram fisrt
if(check_anagram(token1, token2)){
// check_string_order returns 1 if two strings have difference order and same length
if(check_string_order(token1, token2))
strncpy(result[i], "No.", strlen("No."));
else
strncpy(result[i], "Yes", strlen("Yes"));
}
else
strncpy(result[i], "No.", strlen("No."));
}
for(i=0; i<tc_num; i++){
printf("%s\n", result[i]);
free(result[i]);
}
free(result);
}
int check_anagram(char *str1, char *str2)
{
int i;
// integer array for marking alphanumeric : Upper case(26) + Lower case(26) + Numeric(10)
int count[62] = {0,};
// increase array index
for(i=0; str1[i]; i++){
// Upper case
if(str1[i] >= 'A' && str1[i] <= 'Z')
count[str1[i]-65]++;
// Lower case
else if(str1[i] >= 'a' && str1[i] <= 'z')
count[str1[i]-97+26]++;
// Numeric
else if(str1[i] >= '0' && str1[i] <= '9')
count[str1[i]-48+52]++;
}
// decrease array index
for(i=0; str2[i]; i++){
// Upper case
if(str2[i] >= 'A' && str2[i] <= 'Z')
count[str2[i]-65]--;
// Lower case
else if(str2[i] >= 'a' && str2[i] <= 'z')
count[str2[i]-97+26]--;
// Numeric
else if(str2[i] >= '0' && str2[i] <= '9')
count[str2[i]-48+52]--;
}
// if count[index] is not zero, two strings are not anagram
for(i=0; i<62; i++){
if(count[i]) break;
}
if(i == 62) return 1;
else return 0;
}
int check_string_order(char *str1, char *str2)
{
if(strlen(str1) == strlen(str2) && strcmp(str1, str2) == 0)
return 1;
else
return 0;
}
<file_sep>/endian/endian.c
#include <stdio.h>
// defint macro
// bit shift operation to change big endian to little endian
// [X000] --> [000X] : 0xff000000 마스킹 후 3바이트 right shift
// [0X00] --> [00X0] : 0x00ff0000 마스킹 후 1바이트 right shift
// [00X0] --> [0X00] : 0x0000ff00 마스킹 후 1바이트 left shift
// [000X] --> [X000] : 0x000000ff 마스킹 후 3바이트 left shift
#define SWAP32(l) \
( ((((l) & 0xff000000) >> 24) | \
(((l) & 0x00ff0000) >> 8) | \
(((l) & 0x0000ff00) << 8) | \
(((l) & 0x000000ff) << 24)))
int main(void)
{
unsigned int l;
unsigned int num;
scanf("%d", &num);
while(num>0) {
scanf("%u", &l);
printf("%u\n", SWAP32(l));
num--;
}
}
|
b511dcae94a22e28c20a12bddf43ef93c3f50ff4
|
[
"C"
] | 8
|
C
|
gyangsob/algorithmstudy
|
42a0f808a05440a03f3c4cf5daa3e1ed4a55f004
|
bbb9e4b95032ac988fe836ae48d3bf9e16378aeb
|
refs/heads/master
|
<repo_name>arun-gokul/arun<file_sep>/functions/event/Event.java
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONObject;
import com.catalyst.Context;
import com.catalyst.event.EVENT_STATUS;
import com.catalyst.event.EventRequest;
import com.catalyst.event.CatalystEventHandler;
import com.zc.common.ZCProject;
import com.zc.component.cache.ZCCache;
public class Event implements CatalystEventHandler{
private static final Logger LOGGER = Logger.getLogger(Event.class.getName());
@Override
public EVENT_STATUS handleEvent(EventRequest paramEventRequest, Context paramContext) throws Exception {
try
{
ZCProject.initProject();
Object eventData = paramEventRequest.getData();
LOGGER.log(Level.SEVERE,"Data is "+eventData.toString());
ZCCache.getInstance().putCacheValue("Event", "Working", 1l);
LOGGER.log(Level.SEVERE,"Project Details "+paramEventRequest.getProjectDetails().toString());
}
catch (Exception e) {
LOGGER.log(Level.SEVERE,"Exception in Event Function",e);
}
return EVENT_STATUS.SUCCESS;
}
}
<file_sep>/functions/basicio/BasicIO.java
import com.catalyst.Context;
import com.catalyst.basic.BasicIO;
import com.catalyst.basic.ZCFunction;
import java.util.logging.Logger;
import java.util.logging.Level;
import com.zc.common.ZCProject;
import com.zc.component.cache.ZCCache;
public class BasicIO implements ZCFunction {
private static final Logger LOGGER = Logger.getLogger(BasicIO.class.getName());
@Override
public void runner(Context context, BasicIO basicIO) throws Exception {
try {
ZCProject.initProject();
String name = (String) basicIO.getParameter("name");
LOGGER.log(Level.INFO, "Hello "+name);
ZCCache.getInstance().putCacheValue("BasicIO", "Working", 1l);
basicIO.setStatus(200);
}
catch(Exception e) {
LOGGER.log(Level.SEVERE,"Exception in BasicIO",e);
basicIO.setStatus(500);
}
basicIO.write("Hello From BasicIO.java");
}
}
|
1c3ca5c1dfc4dbdeb96fe49f50a0241aa994fede
|
[
"Java"
] | 2
|
Java
|
arun-gokul/arun
|
2b95dd1c0476bd1f16c6fc151380e7993fcb5b75
|
9b529e0bc32274684052c1d5463f32d9a40b892b
|
refs/heads/master
|
<repo_name>barakgonen/barakLihiPCodeGen<file_sep>/Input_Files/HW1/sample14.c
#include <stdio.h>
void main() {
float a;
int b;
double e;
int x;
float f;
f=0;
x=1;
b=1;
a = 5;
e = 7;
// e = a--; //e=5. a=4 store to a and than decrement
printf("%.2f\n",e); //print 5.00
printf("%d\n",b++); //print: 1. b=2.
printf("%.2f\n",--a); //print 3.00 = a
printf("%.2f\n",-e); //print -5.00
a=1;
if (a--) //true. a=0
printf("%d\n",x++); //print 1. x=2
else
printf("%d\n",++x); // print 3
if (--a) //true. a=-1
printf("%d\n",++x); // print 4
a=1;
b=1;
if(a==b)
printf("%.2f\n",a); //print 1.00
if(a==1)
printf("%.2f\n",a+a); //print 2.00
if(0==a) //false
printf("%.2f\n",a);
if(a!=b) //false
printf("%.2f\n",a);
if(a>=b)
printf("%.2f\n",a*4); //print 4.00
while (a<=2)
printf("%.2f\n",++a); //print 2.00 , 3.00
a=1;
printf("%.2f\n",a); // print 1.00
return;
}<file_sep>/Input_Files/HW2/sample06.c
#include <stdio.h>
struct B{
int c;
struct B** d;
float* e;
};
void main() {
float a[1];
struct B b;
// struct B* f;
// b.c = 6;
// f = b.c;
// (*f).d = 6;
// (*((*f).d)).e = 5;
//
// a[0] = 2.5;
// printf("%f\n", (*((*((*f).d)).e))[0] * 2.0 );
return;
}
<file_sep>/Input_Files/HW1/sample30.c
#include <stdio.h>
void main(){
int i;
int j;
int k;
i=0;
for(i=0;i<5;i++){
j = i+1;
while(j<5){
k = j+1;
do{
printf("%d\n",i);
printf("%d\n",j);
printf("%d\n",k);
k++;
}while(k < 5);
j++;
}
}
return;
}
<file_sep>/Input_Files/HW2/sample10.c
#include <stdio.h>
void main() {
int a[2];
int b[2][2];
int i;
int j;
i = 0;
while (i < 2) {
j = 0;
while (j < 2) {
b[i][j] = (i+1)*50+(j+1)*20;
j = j + 1;
}
i = i + 1;
}
printf("%d\n", b[0][0] + b[1][1]);
return;
}
<file_sep>/Input_Files/HW2/sample07.c
#include <stdio.h>
void main() {
int i;
int j;
int b;
i = 5;
while (i > 0) {
j = 1;
while (j < i) {
printf("%d\n", j++);
}
i = i-1;
}
if (0){
printf("%d\n", 15);
}
if (1) {
printf("%d\n", 42);
} else {
printf("%d\n", 16);
}
switch (55) {
case 1:
{
printf("%d\n", 0);
break;
}
case 55:
{
break;
}
case -8:
{
printf("%d\n", 1);
printf("%d\n", 2);
break;
}
}
i = (5*6)+0;
i *= -1;
printf("%d\n", i);
b = 1;
b = !b;
b = b || (i < 0);
printf("%d\n", b);
return;
}<file_sep>/Input_Files/HW1/sample19.c
#include <stdio.h>
void main() {
int a;
int b = 2;
int c = 3;
int d = 5;
a = 1;
while ((a || 0) && (2 < 5)){
printf("%d\n",1);
break;
printf("%d\n",2);
}
printf("%d\n",3);
for (a = 2; a < d; ++a){
break;
for (c = 3; c < d; c++){
printf("%d\n", 2);
}
break;
}
b=3;
do{
printf("%d\n",a+b);
b-=1;
}while(b);
return;
}<file_sep>/Input_Files/HW1/sample31.c
#include <stdio.h>
void main(){
int i;
int j;
for(i=0;i<2;i++){
for(j=2;j>0;j--){
printf("%d\n",i);
printf("%d\n",j);
}
}
i=0;
while(i<2){
j=2;
while(j>0){
printf("%d\n",i);
printf("%d\n",j);
j--;
}
i++;
}
i=0;
do{
j=2;
do{
printf("%d\n",i);
printf("%d\n",j);
j--;
}while(j>0);
i++;
}while(i<2);
return;
}
<file_sep>/Input_Files/HW2/sample05MOD.c
#include <stdio.h>
void main() {
int a[1];
int* b;
int** c;
int*** d;
b = a;
c = &b;
d = &c;
a[0] = 8;
printf("%d\n",(**d)[0]);
return;
}
<file_sep>/Input_Files/HW1/sample28.c
#include <stdio.h>
void main(){
int i1;
int i2;
int i3;
float f1;
float f2;
double d1;
double d2;
i1 = 10;
i2 = 20;
f1 = 15.0;
f2 = 12.0;
d1 = 13.0;
d2 = 33.0;
d1 = ((d1 == d2)?d1:(d1+1.0)) + ((d1 <= d2)? (2.5*4.0) :-3.2);
printf("%f\n", d1);
printf("%f\n", d2);
printf("%f\n", f1);
printf("%f\n", f2);
i3 = (i1++) + (--i2);
printf("%d\n", i1);
printf("%d\n", i2);
printf("%d\n", i3);
i1 = 1;
i2 = 0;
i3 = (i1 && 0) || (!i2) || i3;
printf("%d\n", i1);
printf("%d\n", i2);
printf("%d\n", i3);
f1 *= (8.2+3.8);
f2 /= (24.0/2.0);
f2 += f1;
f2 -= f1;
printf("%f\n", f1);
printf("%f\n", f2);
return;
}
<file_sep>/Input_Files/HW2/sample06MOD.c
#include <stdio.h>
struct B{
int c;
struct B** d;
float* e;
};
void main() {
float a[1];
struct B b;
struct B* f;
b.c = 6;
f = &b;
(*f).d = &b;
(*((*f).d)).e = a;
a[0] = 2.5;
printf("%f\n", ((*((*f).d)).e)[0] * 2.0 );
return;
}
<file_sep>/Input_Files/HW2/sample09.c
#include <stdio.h>
struct D{
int e[20];
struct D* p;
};
struct B{
struct D* c;
struct D d;
};
struct A{
int i;
struct B b;
};
void main() {
struct A a;
a.b.d.p = 7;
a.i = 0;
while (a.i < 20) {
a.b.d.e[a.i] = a.i;
a.i = a.i + 1;
}
printf("%d\n", (*(a.b.d.p)).e[a.i-1]);
return;
}
<file_sep>/Input_Files/HW2/sample08.c
#include <stdio.h>
struct B{
int c;
int d;
};
struct A{
struct B b;
};
void main() {
struct A a;
struct A e[2][2][2][2][2][2][2][2];
e[0][1][0][1][0][1][1][0].b.c = 1;
e[0][1][0][1][0][1][1][0].b.d = 1;
printf("%d\n",e[0][1][0][1][0][1][1][0].b.c + e[0][1][0][1][0][1][1][0].b.d);
return;
}<file_sep>/Input_Files/HW2/sample05.c
#include <stdio.h>
void main() {
int a[1];
int* b;
int** c;
int*** d;
b = 5;
c = 6;
d = 7;
a[0] = 8;
printf("%d\n",(***d)[0]);
return;
}<file_sep>/Input_Files/HW2/sample14.c
#include <stdio.h>
struct BaseObject
{
int AAA;
int BBB;
int CCC;
};
void main()
{
int *pc; // 5
int *c; // 6
int* k = 10; // 7
int a = 1; // 8
int b = 2; // 9
int c = 3; // 10
int d = 4; // 11
double* e = 13; // 12
float s = 2.2; // 13
int** second = 7; // 14
int *** third = 14; // 15
int**** forth = 15; // 16
double* cd[30];
struct BaseObject* bla;
int i;
c = 22;
printf("%d\n", c); // value of c which is 22
pc = 7;
printf("%d\n", pc); // value of pc which is 7
printf("%d\n", *pc); // address of pc which is 5
printf("%d\n", e); // value of e which is 13
printf("%d\n", *e); // address of e which is 2.2
printf("%d\n", forth); // the address which forth is pointing at, which is 15
printf("%d\n", *forth); // the value in the address of third which should be 14
printf("%d\n", **forth); // the value in the address of second which should be 7
printf("%d\n", ***forth); // the value int the address of k which should be 10
for (i = 0; i < 30; i++){
cd[i] = i;
}
for (i = 0; i < 30; i++){
printf("%f\n", *cd[i]);
}
//
// c = *k;
// k = (*c) + 2;
// printf("%d\n", k); // value of k which is 12
// printf("%d\n", c); // address of c, which is the address of k which is 7
// printf("%d\n", *c); // address of c which is 6 BUG!
//
// printf("%d\n", 999998);
// k = (*c)++;
// printf("%d\n", k);
// printf("%d\n", *c);
// printf("%d\n", 999999);
//
// k = 5 * (*(c)++);
// printf("%d\n", k);
// printf("%d\n", c);
// printf("%d\n", c);
// ++(*c);
// printf("%d\n", c);
//
// printf("%d\n", c);
// (*c)++;
// printf("%d\n", c);
//
// a=(*c)+2;
// a = 5 * (**d);
//
// printf("%d\n", c);
// *c++;
// printf("%d\n", c);
//
// printf("%d\n", c);
// ++*c;
// printf("%d\n", c);
return;
} <file_sep>/Input_Files/HW1/sample32.c
#include <stdio.h>
void main() {
int a;
int b;
a = 1;
while (a < 5){
b = 1;
while (b < 10){
if (a == 3){
printf("%d\n",b);
break;
}
b = b * 2;
}
a = a + 1;
}
printf("%d\n",a);
return;
}
<file_sep>/cmake-build-debug/CMakeFiles/compiler.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/compiler.dir/compiler_files/CodeGenerator.c.obj"
"CMakeFiles/compiler.dir/compiler_files/ctree.c.obj"
"CMakeFiles/compiler.dir/compiler_files/dsm_extension.c.obj"
"CMakeFiles/compiler.dir/compiler_files/gram.c.obj"
"CMakeFiles/compiler.dir/compiler_files/heap.c.obj"
"CMakeFiles/compiler.dir/compiler_files/lexer.c.obj"
"CMakeFiles/compiler.dir/compiler_files/nmetab.c.obj"
"CMakeFiles/compiler.dir/compiler_files/prnttree.c.obj"
"CMakeFiles/compiler.dir/compiler_files/symtab.c.obj"
"CMakeFiles/compiler.dir/compiler_files/token.c.obj"
"CMakeFiles/compiler.dir/compiler_files/tree.c.obj"
"CMakeFiles/compiler.dir/compiler_files/treestk.c.obj"
"compiler.exe"
"compiler.exe.manifest"
"compiler.pdb"
"libcompiler.dll.a"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/compiler.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/Input_Files/HW2/sample02.c
#include <stdio.h>
void main() {
int a;
int *b;
a = 10;
b = 5;
if(0){
a = a + 6;
} else{
(*b) = 10*a;
}
printf("%d\n",a);
return;
}
<file_sep>/Input_Files/HW1/sample16.c
#include <stdio.h>
void main()
{
int b = 1;
float a;
a = 5;
do
{
printf("%.2f\n", --a); //print 3,2,1,0
if (a && b)
{
printf("%d\n", 555); //print 555,555,555
}
} while (a || 0);
return;
}<file_sep>/Input_Files/HW1/sample17.c
#include <stdio.h>
void main()
{
float a;
int b;
b = 1;
a = 5;
for (a = 0; a < 5; a++)
{
printf("%d\n", b);
printf("%f\n", a);
b -= b; //b=0. print 111
}
for (a = 1; a < 3; a++)
{
if (!b)
printf("%d\n", 111);
b -= b; //b=0. print 111
}
return;
}<file_sep>/Input_Files/HW2/sample11.c
#include <stdio.h>
void main() {
int a;
a = 1;
while ((a || 0) && (2 < 5)){
printf("%d\n",1);
break;
printf("%d\n",2);
}
printf("%d\n",3);
return;
}
<file_sep>/Input_Files/HW2/sample03.c
#include <stdio.h>
struct BaseOne
{
double qqqq;
double eeee;
};
struct BaseTwo
{
int rrrr;
int tttt;
int yyyy;
struct BaseOne uuuuu;
};
struct BaseThree
{
int iiii;
int oooo;
int pppp;
struct BaseTwo ssss;
};
struct BaseFour
{
int dddd;
int ffff;
int kkkk;
struct BaseThree G;
};
void main() {
int i; // 5
int b[10]; // start: 6 --> end 16
double c[10]; // start: 17 --> end 28
float d[15]; // start: 29 --> end 41
struct BaseFour e[31]; // start: 42 --> end 414
struct BaseFour f[1][2][2][2];
struct BaseFour bS;
int a[4][6];
int fourD[5][4][13][4];
int four[1][1][1][1][1][1][1][1][1][1][2][2][2][2][2][2][2][2][2][2];
int j = 8;
int aV = 6;
double dV = 4.4;
float cV = 5.5;
int indexA;
int indexB;
int indexC;
int indexD;
b[7] = 99;
printf("%d\n", b[7]);
i = 7;
b[i] = 98;
printf("%d\n", b[i]);
b[i + j] = 98;
printf("%d\n", b[i + j]);
b[4] = 12345;
printf("%d\n", b[4]);
b[7] = 15;
b[8] = 7;
printf("%d\n", b[7]);
printf("%d\n", b[8]);
printf("%d\n", b[b[8]]);
i = 53;
printf("%d\n", aV);
printf("%f\n", dV);
printf("%f\n", cV);
printf("%d\n", i);
bS.dddd = 123 + i;
bS.ffff = 456 - i;
bS.kkkk = 789 * i;
bS.G.iiii = i + 2 * i + 3 * i;
bS.G.oooo = (i + 1) * 2;
bS.G.pppp = i * i;
bS.G.ssss.rrrr = 123 - (5 * i);
bS.G.ssss.tttt = 456 + (7 / 7);
bS.G.ssss.yyyy = 789 - (i * -5);
bS.G.ssss.uuuuu.eeee = 5.5;
bS.G.ssss.uuuuu.qqqq = 2 * 3.05;
printf("%d\n", bS.dddd);
printf("%d\n", bS.ffff);
printf("%d\n", bS.kkkk);
printf("%d\n", bS.G.iiii);
printf("%d\n", bS.G.oooo);
printf("%d\n", bS.G.pppp);
printf("%d\n", bS.G.ssss.rrrr);
printf("%d\n", bS.G.ssss.tttt);
printf("%d\n", bS.G.ssss.yyyy);
printf("%f\n", bS.G.ssss.uuuuu.eeee);
printf("%f\n", bS.G.ssss.uuuuu.qqqq);
printf("%d\n", aV);
aV++;
printf("%d\n", aV);
++aV;
printf("%d\n", aV);
aV = aV + 1;
printf("%d\n", aV);
aV = 1 + aV;
printf("%d\n", aV);
aV += 1;
printf("%d\n", aV);
for (i = 0; i < 10; i++){
b[i] = i*2;
}
for (i = 0; i < 10; i++){
printf("%d\n", b[i]);
}
for (i = 0; i < 10; i++){
c[i] = i + 2.02;
}
for (i = 0; i < 10; i++){
printf("%f\n", c[i]);
}
for (i = 0; i < 15; i++){
d[i] = i + 2.12;
}
for (i = 0; i < 15; i++){
printf("%f\n", d[i]);
}
b[2] = 4;
b[3] = 8;
printf("%d\n", b[2]);
printf("%d\n", b[3]);
b[3] = 2 + 15;
printf("%d\n", b[3]);
b[6] = 8;
b[7] = 11;
printf("%d\n", b[6]);
printf("%d\n", b[7]);
printf("%d\n", b[2]);
b[4] = b[6] + b[7];
printf("%d\n", b[4]);
printf("%d\n", b[6]);
printf("%d\n", b[7]);
b[5] = 6;
printf("%d\n", b[5]);
++b[5];
printf("%d\n", b[5]);
b[5]++;
printf("%d\n", b[5]);
b[4] = 2;
printf("%d\n", b[4]);
printf("%d\n", b[2]);
b[b[4]]++;
printf("%d\n", b[2]);
printf("%d\n", b[5]);
b[1] = 2;
b[2] = 3;
b[3] = 4;
b[4] = 5;
b[5] = 6;
b[6] = 7;
b[7] = 88;
printf("%d\n", b[b[b[b[1]]]]);
printf("%d\n", b[4]);
printf("%d\n", b[b[b[b[b[b[b[1]]]]]]]);
printf("%d\n", b[7]);
b[b[b[b[b[b[b[1]]]]]]]++;
printf("%d\n", b[b[b[b[b[b[b[1]]]]]]]);
++b[b[b[b[b[b[b[1]]]]]]];
printf("%d\n", b[b[b[b[b[b[b[1]]]]]]]);
b[b[b[b[b[b[b[1]]]]]]]--;
printf("%d\n", b[b[b[b[b[b[b[1]]]]]]]);
--b[b[b[b[b[b[b[1]]]]]]];
printf("%d\n", b[b[b[b[b[b[b[1]]]]]]]);
b[b[b[b[b[b[b[1]]]]]]]++;
printf("%d\n", b[7]);
b[4] = 3;
printf("%d\n", b[4]);
printf("%d\n", b[3]);
b[7] = b[b[4]];
printf("%d\n", b[7]);
for (i = 0; i < 31; i++){
e[i].dddd = 123 + i;
e[i].ffff = 456 - i;
e[i].kkkk = 789 * i;
e[i].G.iiii = i + 2 * i + 3 * i;
e[i].G.oooo = (i + 1) * 2;
e[i].G.pppp = i * i;
e[i].G.ssss.rrrr = 123 - (5 * i);
e[i].G.ssss.tttt = 456 + (7 / 7);
e[i].G.ssss.yyyy = 789 - (i * -5);
e[i].G.ssss.uuuuu.eeee = i * 5.5;
e[i].G.ssss.uuuuu.qqqq = i * 2 * 3.05;
}
for (i = 0; i < 31; i++){
printf("%d\n", e[i].dddd);
printf("%d\n", e[i].ffff);
printf("%d\n", e[i].kkkk);
printf("%d\n", e[i].G.iiii);
printf("%d\n", e[i].G.oooo);
printf("%d\n", e[i].G.pppp);
printf("%d\n", e[i].G.ssss.rrrr);
printf("%d\n", e[i].G.ssss.tttt);
printf("%d\n", e[i].G.ssss.yyyy);
printf("%f\n", e[i].G.ssss.uuuuu.qqqq);
printf("%f\n", e[i].G.ssss.uuuuu.eeee);
}
fourD[2][2][0][8] = 20;
printf("%d\n", fourD[2][2][0][8]);
fourD[1][3][4][5] = 999;
printf("%d\n", fourD[1][3][4][5]);
indexA = 7;
indexB = 3;
indexC = 5;
indexD = 4;
fourD[4][5][6][7] = indexA + indexB + indexC + indexD;
printf("%d\n", fourD[4][5][6][7]);
indexA = 3;
indexB = 2;
indexC = 8;
indexD = 2;
fourD[indexA][indexB][indexC][indexD] = 2;
printf("%d\n", fourD[3][2][8][2]);
printf("%d\n", fourD[indexA][indexB][indexC][indexD]);
fourD[indexA][indexB][indexC][indexD] = indexA + indexB + indexC + indexD;
a[3][2] = 12;
printf("%d\n", a[3][2]);
for (i = 0; i < 10; i++) {
b[i] = 1 * 2 * 3 * 4 + i;
}
for (i = 0; i < 10; i++) {
printf("%d\n", b[i]);
}
b[7] = 2;
for (i = 0; i < 10; i++){
printf("%d\n", b[i]);
}
a[2][1] = 9090;
printf("%d\n", a[2][1]);
printf("%d\n", a[3][2]);
for (indexA = 0; indexA < 5; indexA++){
for(indexB = 0; indexB < 4; indexB++){
for(indexC = 0; indexC < 13; indexC++){
for(indexD = 0; indexD < 4; indexD++){
fourD[indexA][indexB][indexC][indexD] = (indexA + indexB + indexC + indexD);
}
}
}
}
for (indexA = 0; indexA < 5; indexA++){
for(indexB = 0; indexB < 4; indexB++){
for(indexC = 0; indexC < 13; indexC++){
for(indexD = 0; indexD < 4; indexD++){
printf("%d\n", fourD[indexA][indexB][indexC][indexD]);
}
}
}
}
for (i =0; i < 4; i++){
for (j = 0; j < 6; j++){
a[i][j]=i + j;
}
}
for (i =0; i < 4; i++){
for (j = 0; j < 6; j++){
printf("%d\n", a[i][j]);
}
}
a[5][2] = 3;
printf("%d\n",a[5][2]);
f[1][2][3][4].dddd = 123 + indexA;
f[1][2][3][4].ffff = 2131 - indexB;
// f[1][2][3][4].kkkk = 2.2 * 4 - indexC;
f[1][2][3][4].G.oooo = (indexA + 1) * 2;
f[1][2][3][4].G.iiii = 232131 + 1;
f[1][2][3][4].G.pppp = indexD * indexC;
f[1][2][3][4].G.ssss.rrrr = 123 - (5 * i);
f[1][2][3][4].G.ssss.tttt = 456 + (7 / 7);
f[1][2][3][4].G.ssss.yyyy = 789 - (indexC * -5);
f[1][2][3][4].G.ssss.uuuuu.eeee = indexA * 5.5;
f[1][2][3][4].G.ssss.uuuuu.qqqq = indexC * 2 * 3.05;
printf("%d\n", f[1][2][3][4].dddd);
printf("%d\n", f[1][2][3][4].ffff);
// printf("%d\n", f[1][2][3][4].kkkk);
printf("%d\n", f[1][2][3][4].G.oooo);
printf("%d\n", f[1][2][3][4].G.iiii);
printf("%d\n", f[1][2][3][4].G.pppp);
printf("%d\n", f[1][2][3][4].G.ssss.rrrr);
printf("%d\n", f[1][2][3][4].G.ssss.tttt);
printf("%d\n", f[1][2][3][4].G.ssss.yyyy);
printf("%f\n", f[1][2][3][4].G.ssss.uuuuu.qqqq);
printf("%f\n", f[1][2][3][4].G.ssss.uuuuu.eeee);
for (indexA = 0; indexA < 1; indexA++){
for(indexB = 0; indexB < 2; indexB++){
for(indexC = 0; indexC < 2; indexC++){
for(indexD = 0; indexD < 2; indexD++){
f[indexA][indexB][indexC][indexD].dddd = 123 + indexA;
f[indexA][indexB][indexC][indexD].ffff = 456 - indexB;
f[indexA][indexB][indexC][indexD].kkkk = 789 * indexB;
f[indexA][indexB][indexC][indexD].G.iiii = indexB + 2 * indexD + 3 * indexC;
f[indexA][indexB][indexC][indexD].G.oooo = (indexA + 1) * 2;
// f[indexA][indexB][indexC][indexD].G.pppp = indexD * indexC;
// f[indexA][indexB][indexC][indexD].G.ssss.rrrr = 123 - (5 * indexA);
// f[indexA][indexB][indexC][indexD].G.ssss.tttt = 456 + (7 / 7);
// f[indexA][indexB][indexC][indexD].G.ssss.yyyy = 789 + (indexC * -5);
// f[indexA][indexB][indexC][indexD].G.ssss.uuuuu.eeee = indexA * 5.5;
f[indexA][indexB][indexC][indexD].G.ssss.uuuuu.qqqq = indexC * 2 * 3.05;
}
}
}
}
for (indexA = 0; indexA < 1; indexA++){
for(indexB = 0; indexB < 2; indexB++){
for(indexC = 0; indexC < 2; indexC++){
for(indexD = 0; indexD < 2; indexD++){
printf("%d\n", f[indexA][indexB][indexC][indexD].ffff);
printf("%d\n", f[indexA][indexB][indexC][indexD].dddd);
printf("%d\n", f[indexA][indexB][indexC][indexD].kkkk);
printf("%d\n", f[indexA][indexB][indexC][indexD].G.iiii);
printf("%d\n", f[indexA][indexB][indexC][indexD].G.oooo);
// printf("%d\n", f[indexA][indexB][indexC][indexD].G.pppp);
// printf("%d\n", f[indexA][indexB][indexC][indexD].G.ssss.rrrr);
// printf("%d\n", f[indexA][indexB][indexC][indexD].G.ssss.tttt);
// printf("%d\n", f[indexA][indexB][indexC][indexD].G.ssss.yyyy);
printf("%f\n", f[indexA][indexB][indexC][indexD].G.ssss.uuuuu.qqqq);
// printf("%f\n", f[indexA][indexB][indexC][indexD].G.ssss.uuuuu.eeee);
}
}
}
}
return;
}<file_sep>/Input_Files/HW2/sample15.c
#include <stdio.h>
// struct st1
// { //total_size = 1+1+20+10+12 = 44
// int a; // →inc 0, size = 1
// double * *b; //→inc 1, size = 1
// float * c[20]; // →inc 2, size = 20 * 1 = 20
// int * **c[10]; // →inc 22, size = 10 * 1 = 10
// double * d[2][3][2]; // →inc 32, size = 2 * 3 * 2 * 1 = 12
// };
void main()
{
// struct st1 ****a; // →address = 5, size = 1
// int * *b; // →address = 6, size = 1
// double * c[30]; // →address = 7, size = 30 * 1 = 30
// float * *d[2][2][2]; // →address = 37, size = 2 * 2 * 2 * 1 = 8
// struct st1 arrS1[5]; // →address = 45, size = 5 * 44 = 220
// struct st1 arrS2[2][3]; // →address = 265, size = 2 * 3 * 44 = 264
// double arrD1[5]; // →address = 529, size = 5 * 1 = 5
// double arrD2[5][2]; // →address = 534, size = 5 * 2 * 1 = 10
// int arrI1[2]; // →address = 544, size = 2 * 1 = 2
// double * pD; // →address = 546, size = 1
// struct st1 * pS; // →address = 547, size = 1
// pD = 529; (arrD1);
// pD[2] = 18.2 + (pD[1]++) * pD[0];
// pS = 45; (arrS1);
// pS[1].a ++;
return;
}<file_sep>/Input_Files/HW1/sample26.c
#include <stdio.h>
void main() {
double i;
double j;
double k;
i = 10.0;
j = 5.0;
k = 3.0;
while (i >= 0) {
k = k + 2.0;
if (k > i) {
while (j <= 10.0) {
j = j + 1.0;
printf("%f\n", j);
}
}
else {
k = k - 1.0;
};
i = i - 1.0;
printf("%f\n", i);
}
return;
}<file_sep>/Input_Files/HW2/sample13.c
#include <stdio.h>
#include <stdlib.h>
struct BaseObject
{
int AAA;
int BBB;
int CCC;
};
struct bakBAK
{
int aa;
struct BaseObject base;
int bb;
int cc;
};
struct blaTYpe
{
int a;
int b;
int c;
struct bakBAK aa;
};
void main()
{
struct blaTYpe a;
a.a = 1;
a.b = 2;
a.c = 3;
a.aa.aa = 4;
a.aa.bb = 5;
a.aa.cc = 6;
a.aa.base.AAA = 7;
a.aa.base.BBB = 8;
a.aa.base.CCC = 9;
printf("%d\n", a.a);
printf("%d\n", a.b);
printf("%d\n", a.aa.aa);
printf("%d\n", a.aa.bb);
printf("%d\n", a.aa.cc);
printf("%d\n", a.aa.base.AAA);
printf("%d\n", a.aa.base.BBB);
printf("%d\n", a.aa.base.CCC);
return;
}<file_sep>/Input_Files/HW1/sample11.c
#include <stdio.h>
void main() {
float a;
int b;
double e;
int x;
float f;
f=0;
x=1;
b=1;
a = 5;
// e = a--; //e=5. a=4
e = 8.6;
printf("%.2f\n",e); //print 5.00
printf("%d\n",b++); //print: 1. b=2.
printf("%.2f\n",--a); //print 3.00 = a
printf("%.2f\n",-e); //print -5.00
a=1;
if (a--) //true. a=0
printf("%d\n",x++); //print 1. x=2
else
printf("%d\n",++x); // print 3
if (--a) //true. a=-1
printf("%d\n",++x); // print 4
x--;
printf("%d\n",x);// print 3
x = (x==5)?(11):(22); //x=22
printf("%d\n",x);
++x;
for(a=1;a>=1;x--){
for(a=1;a>0;--x) {
if (a-- > 0)
printf("%d\n", x); //print 23
if (x)
printf("%d\n",x); //print 23
}
}
printf("%d\n",x); //print 21
a=35;
b=550;
a+=b;
printf("%.2f\n",a); //print 585.00
a-=b;
printf("%.2f\n",a); //print 550.00
a-=2;
printf("%.2f\n",a); //print 548.00
a+=3;
printf("%.2f\n",a); //print 551.00
a=10.23;
b=20;
a-=0.23;
a*=b;
printf("%.2f\n",a); //print 200.00
a/=b;
printf("%.2f\n",a); //print 10.00
a=4;
f=5;
printf("%.2f\n",a+f); //print 9.00
a = f-3;
printf("%.2f\n",a); //print 2.00
a = 3- f;
printf("%.2f\n",a); //print -2.00
a = f+f;
printf("%.2f\n",a); //print 10.00
a = 1+f;
printf("%.2f\n",a); //print 6.00
a = a*a;
printf("%.2f\n",a); //print 36.00
a = a/a;
printf("%.2f\n",a); //print 1.00
a = 6/a;
printf("%.2f\n",a); //print 6.00
// a = a/12;
// printf("%.2f\n",a); //print 0.50
a = 2*a;
printf("%.2f\n",a); //print 1.00
a = a*4;
printf("%.2f\n",a); //print 4.00
b = 1;
do{
printf("%.2f\n",--a); //print 3,2,1,0
if(a&&b){
printf("%d\n",555); //print 555,555,555
}
}while(a||0);
for(a=1;a<3;a++) {
if (!b)
printf("%d\n", 111);
b -= b; //b=0. print 111
}
a=1;
b=1;
if(a==b)
printf("%.2f\n",a); //print 1.00
if(a==1)
printf("%.2f\n",a+a); //print 2.00
if(0==a) //false
printf("%.2f\n",a);
if(a!=b) //false
printf("%.2f\n",a);
if(a>=b)
printf("%.2f\n",a*4); //print 4.00
while (a<=2)
printf("%.2f\n",++a); //print 2.00 , 3.00
a=1;
printf("%.2f\n",+a); // print 1.00
return;
}
<file_sep>/Input_Files/HW2/sample04.c
#include <stdio.h>
void main() {
int a;
int b;
a = 18;
b = 958;
switch(a){
case 18:
{
printf("%d\n",0);
break;
}
case 2:
{
printf("%d\n",1);
break;
}
case 30:
{
printf("%d\n",2);
printf("%d\n",3);
break;
}
}
switch(b){
case 958:
{
printf("%d\n",4);
break;
}
}
return;
}
|
6d2c314becbb8c8da0eb32757985864d040f1aad
|
[
"C",
"CMake"
] | 26
|
C
|
barakgonen/barakLihiPCodeGen
|
b79888fe7ffc17a57f3e62de09f3ecff31411e5a
|
40bf9f823d9af3d48bf128eaff2502abd7932e2e
|
refs/heads/master
|
<repo_name>Apocaliptic95/SQL<file_sep>/README.md
# SQL
Platforma - projekt bazy dla projektu cake z repozytorium PHP
Piwo i Schronisko - Projekty baz na zajęcia z baz danych
<file_sep>/Postgres-schronisko.sql
DROP TABLE IF EXISTS Adopcja;
DROP TABLE IF EXISTS Przyjecie;
DROP TABLE IF EXISTS Specjalista;
DROP TABLE IF EXISTS Specjalizacja;
DROP TABLE IF EXISTS Klient;
DROP TABLE IF EXISTS Pracownik;
DROP TABLE IF EXISTS Diagnoza;
DROP TABLE IF EXISTS Badanie;
DROP TABLE IF EXISTS Choroba;
DROP TABLE IF EXISTS Zwierze;
DROP TABLE IF EXISTS Weterynarz;
DROP TABLE IF EXISTS Typ;
DROP TABLE IF EXISTS Rasa;
DROP TABLE IF EXISTS Adres;
DROP TABLE IF EXISTS Poziom_zagrozenia;
DROP TABLE IF EXISTS Stanowisko;
CREATE TABLE Adres (
id_Adres INT NOT NULL SERIAL PRIMARY KEY,
Ulica VARCHAR(20) NOT NULL CHECK(LENGTH(Ulica)>2),
Miejscowosc VARCHAR(25) NOT NULL CHECK(LENGHT(Miejscowosc)>2),
Nr_mieszkania VARCHAR(10) NOT NULL,
Kod_poczt VARCHAR(6) NOT NULL,
);
CREATE TABLE Poziom_zagrozenia (
id_zagrozenia INT NOT NULL SERIAL PRIMARY KEY,
opis TEXT NOT NULL
);
CREATE TABLE Choroba (
id_Choroba INT NOT NULL SERIAL PRIMARY KEY,
Nazwa VARCHAR(20) NOT NULL,
Poziom_zagrozenia INT NOT NULL REFERENCES Poziom_zagrozenia (id_zagrozenia),
);
CREATE TABLE Rasa (
id_Rasa INT NOT NULL SERIAL PRIMARY KEY,
Nazwa VARCHAR(20) NOT NULL,
);
CREATE TABLE Specjalizacja (
id_Specjalizacja INT NOT NULL SERIAL PRIMARY KEY,
Nazwa VARCHAR(50) NOT NULL,
);
CREATE TABLE Typ (
id_Typ INT NOT NULL SERIAL PRIMARY KEY,
Nazwa VARCHAR(20) NOT NULL,
);
CREATE TABLE Stanowisko (
id_Stanowisko INT NOT NULL SERIAL PRIMARY KEY,
Nazwa VARCHAR(20) NOT NULL,
Pensja MONEY NOT NULL,
);
CREATE TABLE Weterynarz (
id_Weterynarz INT NOT NULL SERIAL PRIMARY KEY,
Adres INT NOT NULL REFERENCES Adres (id_Adres),
Adres_korespondencji INT REFERENCES Adres (id_Adres),
Imie VARCHAR(20) NOT NULL,
Nazwisko VARCHAR(25) NOT NULL,
Telefon VARCHAR(15) NOT NULL,
);
CREATE TABLE Specjalista (
id_Weterynarz INT NOT NULL REFERENCES Weterynarz (id_Weterynarz) ON DELETE CASCADE,
id_Specjalizacja INT NOT NULL REFERENCES Specjalizacja (id_Specjalizacja) ON DELETE CASCADE,
PRIMARY KEY(id_Weterynarz, id_Specjalizacja)
);
CREATE TABLE Zwierze (
id_Zwierze INT NOT NULL SERIAL PRIMARY KEY,
id_Rasa INT NOT NULL REFERENCES Rasa (id_Rasa),
id_Typ INT NOT NULL REFERENCES Typ (id_Typ),
Imie VARCHAR(20) NOT NULL,
Wiek INT NOT NULL,
Opis TEXT NOT NULL,
);
CREATE TABLE Badanie (
id_Badanie INT NOT NULL SERIAL PRIMARY KEY,
id_Zwierze INT NOT NULL REFERENCES Zwierze (id_Zwierze),
id_Weterynarz INT NOT NULL REFERENCES Weterynarz (id_Weterynarz),
Data_badania DATE NOT NULL DEFAULT NOW(),
Zalecenia TEXT NOT NULL,
Oplata_badania MONEY NOT NULL,
);
CREATE TABLE Diagnoza (
id_Badanie INT NOT NULL REFERENCES Badanie (id_Badanie) ON DELETE CASCADE,
id_Choroba INT NOT NULL REFERENCES Choroba (id_Choroba),
PRIMARY KEY(id_Badanie, id_Choroba)
);
CREATE TABLE Klient (
id_Klient INT NOT NULL SERIAL PRIMARY KEY,
Adres_korespondencji INT REFERENCES Adres (id_Adres),
Adres_staly INT NOT NULL REFERENCES Adres (id_Adres),
Imie VARCHAR(20) NOT NULL,
Nazwisko VARCHAR(25) NOT NULL,
Pesel VARCHAR(11) NOT NULL,
Telefon VARCHAR(15) NOT NULL,
Pozwolenie BIT NOT NULL,
);
CREATE TABLE Pracownik (
id_Pracownik INT NOT NULL SERIAL PRIMARY KEY,
Stanowisko INT NOT NULL REFERENCES Stanowisko (id_Stanowisko),
Adres_korespondencji INT REFERENCES Adres (id_Adres),
Adres_staly INT NOT NULL REFERENCES Adres (id_Adres),
Imie VARCHAR(20) NOT NULL,
Nazwisko VARCHAR(25) NOT NULL,
Pesel VARCHAR(11) UNIQUE NOT NULL,
Telefon VARCHAR(15) NOT NULL,
Premia MONEY NOT NULL,
);
CREATE TABLE Adopcja (
id_Zwierze INT NOT NULL PRIMARY KEY REFERENCES Zwierze (id_Zwierze),
id_Pracownik INT NOT NULL REFERENCES Pracownik (id_Pracownik),
id_Klient INT NOT NULL REFERENCES Klient (id_Klient),
Data_adopcji DATE NOT NULL DEFAULT NOW(),
Oplata MONEY NOT NULL,
);
CREATE TABLE Przyjecie (
id_Zwierze INT NOT NULL PRIMARY KEY REFERENCES Zwierze (id_Zwierze),
id_Klient INT NOT NULL REFERENCES Klient (id_Klient),
id_Pracownik INT NOT NULL REFERENCES Pracownik (id_Pracownik),
Data_przyjecia DATE NOT NULL DEFAULT NOW(),
Opis TEXT NOT NULL,
Oplata MONEY NOT NULL,
);
INSERT INTO Adres (Ulica,Miejscowosc,Nr_mieszkania,Kod_poczt) VALUES
('Mazowiecka','Gdańsk','50','06-500'),
('Abrahama','Gdańsk','13','80-210'),
('Traugutta','Warszawa','250','10-520'),
('Leśna','Łódź','20','22-599'),
('Cicha','Kraków','80','09-789');
INSERT INTO Choroba (Nazwa,Poziom_zagrozenia) VALUES
('Wścieklizna',5),
('Złamanie',2),
('Nieznana',5),
('Zatrucie',3),
('Nosówka',5);
INSERT INTO Rasa (Nazwa) VALUES
('Labrador'),
('Perski'),
('Dalmatyńczyk'),
('Amstaff'),
('Mieszana');
INSERT INTO Specjalizacja (Nazwa) VALUES
('Choroby psów i kotów'),
('Radiologia Weterynaryjna'),
('Chir<NAME>'),
('Choroby Ryb'),
('Choroby Z<NAME>');
INSERT INTO Typ (Nazwa) VALUES
('Kot'),
('Pies'),
('Ryba'),
('Chomik'),
('Kanarek');
INSERT INTO Stanowisko (Nazwa,Pensja) VALUES
('Obsługa klienta',1200),
('Pomocnik',800),
('Nadzorca',1500),
('Stróż',1300),
('Wolontariusz',0);
INSERT INTO Weterynarz (Adres,Adres_korespondencji,Imie,Nazwisko,Telefon) VALUES
(1,NULL,'Jan','Kowalski','102013012'),
(2,NULL,'Andrzej','Nowak','999222333'),
(3,NULL,'Marek','Witkowski','112244556'),
(4,NULL,'Wojciech','Grabowski','858923034'),
(5,NULL,'Maria','Ślesicka','098653534');
INSERT INTO Specjalista VALUES (1,1),(2,2),(3,3),(4,4),(5,5);
INSERT INTO Zwierze (id_Rasa,id_Typ,Imie,Wiek,Opis) VALUES
(1,2,'Reks',2,'Przyjazny pies.'),
(3,2,'Antek',1,'Lubiący zabawę szczeniak.'),
(2,1,'Mruczek',1,'Wyjątkowo leniwy kot.'),
(4,2,'Drago',5,'Silny i niezależny pies.'),
(5,2,'Diana',2,'Przyjazna i lubiąca dzieci.');
SET DATEFORMAT dmy;
INSERT INTO Poziom_zagrozenia (opis) VALUES
('Brak'),
('Niski'),
('Średni'),
('Wysoki'),
('Śmiertelny');
INSERT INTO Badanie (id_Zwierze,id_Weterynarz,Data_badania,Zalecenia,Oplata_badania) VALUES
(1,1,'09/09/2012','Izolacja i szczepionka',50),
(2,2,'04/05/2013','Gips',100),
(3,3,'12/12/2014','Antybiotyk',120),
(4,4,'15/10/2015','Dieta',20),
(5,5,'19/01/2012','Izolacja i antybiotyk',140);
INSERT INTO Diagnoza (id_Badanie,id_Choroba) VALUES
(1,1),
(2,2),
(3,3),
(4,4),
(5,5);
INSERT INTO Klient (Adres_korespondencji,Adres_staly,Imie,Nazwisko,Pesel,Telefon,Pozwolenie) VALUES
(NULL,1,'Jan','Kowalski','94636271723','102013012',1),
(NULL,2,'Andrzej','Nowak','09786754321','999222333',1),
(NULL,3,'Marek','Witkowski','09435261783','112244556',1),
(NULL,4,'Wojciech','Grabowski','77648362345','858923034',1),
(NULL,5,'Maria','Ślesicka','74521345732','098653534',1);
INSERT INTO Pracownik (Stanowisko,Adres_korespondencji,Adres_staly,Imie,Nazwisko,Pesel,Telefon,Premia) VALUES
(1,NULL,5,'Agata','Potocka','73948574627','090988763',0),
(2,NULL,4,'Mariusz','Doliński','54858696749','857465443',100),
(3,NULL,3,'Jan','Spędowski','89576342512','244233456',200),
(4,NULL,2,'Michał','Spelak','09877678965','122312334',0),
(5,NULL,1,'Aleksandra','Górska','96756544323','675464674',0);
INSERT INTO Adopcja (id_Zwierze,id_Pracownik,id_Klient,Data_adopcji,Oplata) VALUES
(1,1,5,'09/12/2010',100),
(2,2,4,'21/10/2001',10),
(3,3,3,'23/04/2009',150),
(4,4,2,'26/01/2013',50),
(5,5,1,'01/02/2003',40);
INSERT INTO Przyjecie (id_Zwierze,id_Pracownik,id_Klient,Data_przyjecia,Opis,Oplata) VALUES
(1,1,5,'09/12/2010','<NAME>',100),
(2,2,4,'21/10/2001','<NAME>',10),
(3,3,3,'23/04/2009','<NAME>',150),
(4,4,2,'26/01/2013','Potulny',50),
(5,5,1,'01/02/2003','<NAME>',40);<file_sep>/Postgres-piwo.sql
CREATE TABLE IF NOT EXISTS butelkowanie (
idbutelkowanie SERIAL,
pojemnosc INT NOT NULL,
rodzaj_butelki VARCHAR(250) NOT NULL,
kolor_butelki VARCHAR(250) NOT NULL,
rodzaj_etykiety VARCHAR(250) NOT NULL
);
CREATE TABLE IF NOT EXISTS Chmiel (
idpochodzenie SERIAL,
kraj VARCHAR(200) NOT NULL,
rodzaj VARCHAR(200) NOT NULL
);
CREATE TABLE IF NOT EXISTS dane_producenta (
id_kraj SERIAL,
numer_telefonu INTEGER NOT NULL,
ulica VARCHAR(50) NOT NULL,
kod_pocztowy INTEGER NOT NULL,
numer_budynku INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS Hurtownia (
idhurtownia SERIAL
);
CREATE TABLE IF NOT EXISTS przedstawiciel (
idprzedstawiciel SERIAL,
imie VARCHAR(200) NOT NULL,
nazwisko VARCHAR(200) NOT NULL,
kontakt INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS importer (
idimporter SERIAL,
Nazwa VARCHAR(200) NOT NULL,
kraj VARCHAR(200) NOT NULL
);
CREATE TABLE IF NOT EXISTS opinie (
idopinie SERIAL,
smak VARCHAR(250) NOT NULL,
barwa VARCHAR(250) NOT NULL,
moc INTEGER NOT NULL,
stosunek_ceny_do_jakosci INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS komentarz (
idkomentarz SERIAL,
tresc VARCHAR(250) NOT NULL,
idopinie INTEGER NULL FOREIGN KEY REFERENCES opinie(idopinie) ON DELETE NO ACTION
);
CREATE TABLE IF NOT EXISTS producent (
idproducent SERIAL,
nazwa VARCHAR(200) NOT NULL,
opis VARCHAR(200) NOT NULL
);
CREATE TABLE IF NOT EXISTS adres_hurtowni (
idadres_hurtowni SERIAL,
idhurtownia INTEGER NOT NULL FOREIGN KEY REFERENCES Hurtownia(idhurtownia) ON UPDATE CASCADE,
ulica VARCHAR(255) NOT NULL,
numer INTEGER NOT NULL,
kod_pocztowy INTEGER NOT NULL,
kraj VARCHAR(255) NOT NULL,
);
CREATE TABLE IF NOT EXISTS importer_has_hurtownie (
id_importer_hurtowni SERIAL,
idimporter INTEGER NOT NULL,
idhurtownia INTEGER NOT NULL,
FOREIGN KEY(idimporter) REFERENCES importer(idimporter) ON update CASCADE,
FOREIGN KEY(idhurtownia) REFERENCES Hurtownia(idhurtownia) ON update CASCADE
);
CREATE TABLE IF NOT EXISTS kontakt (
idkontakt SERIAL,
idhurtownia INTEGER NOT NULL,
numer_tel_kom INTEGER NOT NULL,
numer_tel_stacj INTEGER NOT NULL,
fax INTEGER NOT NULL,
mail VARCHAR(250) NOT NULL,
FOREIGN KEY(idhurtownia) REFERENCES Hurtownia(idhurtownia)ON UPDATE CASCADE
);
CREATE TABLE IF NOT EXISTS Piwo (
idPiwo SERIAL,
idpochodzenie INTEGER NOT NULL,
idopinie INTEGER NOT NULL,
FOREIGN KEY(idpochodzenie) REFERENCES Chmiel(idpochodzenie) ON DELETE CASCADE,
FOREIGN KEY(idopinie) REFERENCES opinie(idopinie) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS Piwo_has_butelkowanie (
idbutelka_piwa SERIAL,
idpochodzenie INTEGER NOT NULL,
idPiwo INTEGER NOT NULL,
idbutelkowanie INTEGER NOT NULL,
FOREIGN KEY (idpochodzenie) REFERENCES Chmiel(idpochodzenie) ON update CASCADE,
FOREIGN KEY (idPiwo) REFERENCES Piwo(idpiwo) ON update CASCADE,
FOREIGN KEY (idbutelkowanie) REFERENCES butelkowanie(idbutelkowanie) ON update CASCADE
);
CREATE TABLE IF NOT EXISTS producent_has_Hurtownia (
idprod_hurt SERIAL,
idhurtownia INTEGER NOT NULL,
FOREIGN KEY(idhurtownia) REFERENCES Hurtownia(idhurtownia) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS producent_has_importer (
idprod_imp SERIAL,
idimporter INTEGER NOT NULL,
FOREIGN KEY(idimporter) REFERENCES importer(idimporter) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS producent_has_Piwo (
idproducent_piwa SERIAL,
idpochodzenie INTEGER NOT NULL,
idPiwo INTEGER NOT NULL,
FOREIGN KEY(idpochodzenie) REFERENCES Chmiel(idpochodzenie) ON update CASCADE,
FOREIGN KEY(idPiwo) REFERENCES Piwo(idPiwo) ON update CASCADE
);
CREATE TABLE IF NOT EXISTS hurtownie_has_przedstawiciel (
idprzedstawicielhurtowni SERIAL,
idprzedstawiciel INTEGER NOT NULL,
idhurtownia INTEGER NOT NULL,
FOREIGN KEY(idhurtownia) REFERENCES Hurtownia(idhurtownia) ON update CASCADE,
FOREIGN KEY(idprzedstawiciel) REFERENCES przedstawiciel(idprzedstawiciel) ON update CASCADE
);
CREATE TABLE IF NOT EXISTS rodzaj_piwa (
idrodzaj_piwa SERIAL,
idpochodzenie INTEGER NOT NULL,
idPiwo INTEGER NOT NULL,
ciemne VARCHAR(23) NULL,
jasne VARCHAR(23) NULL,
smakowe VARCHAR(30) NULL,
FOREIGN KEY(idpochodzenie) REFERENCES Chmiel(idpochodzenie) ON update CASCADE,
FOREIGN KEY(idPiwo) REFERENCES Piwo(idpiwo) ON update CASCADE
);
---
INSERT INTO butelkowanie(idbutelkowanie,pojemnosc,rodzaj_butelki, kolor_butelki, rodzaj_etykiety)
VALUES
(1,300,2,'niebieska','mala'),
(2,500,2,'czerwona','duza'),
(3,700,2,'zielona','duza'),
(4,500,2,'czarny','mala'),
(5,800,3,'biala','mala');
INSERT INTO Chmiel(idpochodzenie,kraj,rodzaj)
VALUES
(1,'niemcy','ciemny'),
(2,'polska','ciemny'),
(4,'rosja','ciemny'),
(3,'niemcy','jasny'),
(5,'chiny','jasny');
INSERT INTO dane_producenta (id_kraj,numer_telefonu,ulica, kod_pocztowy,numer_budynku)
VALUES
(1,23232345,'DSFSDF',87,2),
(2,23534323,'DSFSDF',87,2),
(3,23454323,'DSFSDF',45,2),
(4,23232344,'DSFSDF',32,2),
(5,23232366,'DSFSDF',87,2);
INSERT INTO Hurtownia(idhurtownia)
VALUES (1), (2), (3), (4), (5), (6), (7);
INSERT INTO przedstawiciel(idprzedstawiciel,imie, nazwisko, kontakt)
VALUES
(1,'piotr','grucz',53242343),
(2,'kamil','nowak',22223123),
(3,'greg','baja',22311112),
(4,'donald','ziemniak',9993832),
(5,'chynj','abaas',332323);
INSERT INTO importer(idimporter,nazwa,kraj)
VALUES
(1,'grujek','polska'),
(2,'nefph','anglia'),
(3,'zenix','holandia'),
(4,'dex','irlandia'),
(5,'armani','niemcy'),
(6,'gifox','szwjcaria');
INSERT INTO opinie(idopinie,smak,barwa,stosunek_ceny_do_jakosci,moc)
VALUES
(1,2,1,5,2),
(2,2,3,3,3),
(3,2,1,1,40),
(4,1,2,2,5),
(5,2,2,1,5);
INSERT INTO komentarz(tresc,idopinie)
VALUES
('<NAME> !', 1),
('SlABE',2),
('<NAME>', 1),
('FATALNE', 3),
('IDEALNE', 1);
INSERT INTO Producent(idproducent,nazwa,opis)
VALUES
(1,'grzyszkowiak','pomorze'),
(3,'tyskie','karpacz'),
(2,'vox','statry'),
(4,'warka','poznan'),
(5,'browar','malopolska');
INSERT INTO adres_hurtowni (idadres_hurtowni,idhurtownia,ulica,numer,kod_pocztowy,kraj)
VALUES
(1,1,'konopielki',2,32323,'polska'),
(2,3,'konopel',2,323423,'polska'),
(3,4,'zielona',2,3323,'polska'),
(4,1,'konf',2,3323,'niemcy'),
(5,1,'poborzna',1,32323,'anglia');
INSERT INTO kontakt(idkontakt,idhurtownia,numer_tel_kom,numer_tel_stacj,fax,mail)
VALUES
(1,2,23223,49645,77123,'<EMAIL>'),
(2,1,23723,454545,28933,'<EMAIL>'),
(3,5,2823,4945,231123,'<EMAIL>'),
(4,2,29823,45745,231623,'<EMAIL>'),
(5,3,23293,49945,234123,'<EMAIL>'),
(6,1,21263,48545,253123,'<EMAIL>');
INSERT INTO Piwo(idpiwo,idpochodzenie,idopinie)
VALUES
(1,1,2),
(2,2,3),
(3,3,1),
(4,2,1),
(5,1,1);
INSERT INTO rodzaj_piwa(idrodzaj_piwa, idpochodzenie, idPiwo, ciemne, jasne, smakowe)
VALUES
(1,2, 3,'tak', NULL, NULL),
(2,3, 2, NULL,'tak', NULL),
(3,2, 4,'tak', NULL, NULL),
(4,2, 4,'tak', NULL, NULL),
(5,2, 5, NULL, NULL,'tak');<file_sep>/Platforma-MySQL.sql
CREATE TABLE `jezyk` (
`id_jezyk` int(11) NOT NULL,
`nazwa_jezyk` varchar(30) COLLATE utf8_polish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
INSERT INTO `jezyk` (`id_jezyk`, `nazwa_jezyk`) VALUES
(1, 'Angielski'),
(2, 'Polski'),
(3, 'Niemiecki');
CREATE TABLE `kategoria` (
`id_kategoria` int(11) NOT NULL,
`nazwa_kategoria` varchar(30) COLLATE utf8_polish_ci NOT NULL,
`opis_kategoria` text COLLATE utf8_polish_ci NOT NULL,
`dir_kategoria` text COLLATE utf8_polish_ci,
`img_kategoria` varchar(100) COLLATE utf8_polish_ci NOT NULL DEFAULT 'default.png'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
INSERT INTO `kategoria` (`id_kategoria`, `nazwa_kategoria`, `opis_kategoria`, `dir_kategoria`, `img_kategoria`) VALUES
(7, 'Podstawy', 'Podstawowe słówka.', '1eca15f2-ec39-4067-8977-30759a5ac923', 'icon-blue-m-easy-circle.png'),
(8, 'Człowiek', 'Słówka związane z ludźmi.', 'afae073a-d21b-40b7-a18d-c919db6da7a1', 'people.png'),
(9, 'Zwierzęta', 'Wszystko o zwierzętach.', 'f5c38024-44d3-42e9-a4fb-8aace725808e', 'Turtle.png'),
(10, 'Szkoła', 'Życie szkolne.', '1cccbc58-a516-4f69-9064-00891a06ad05', 'Categories-applications-education-school-icon.png');
CREATE TABLE `konto` (
`id_konto` int(11) NOT NULL,
`rola_id` int(11) DEFAULT '1',
`imie_konto` varchar(20) COLLATE utf8_polish_ci NOT NULL,
`nazwisko_konto` varchar(30) COLLATE utf8_polish_ci NOT NULL,
`email_konto` varchar(50) COLLATE utf8_polish_ci NOT NULL,
`login_konto` varchar(30) COLLATE utf8_polish_ci NOT NULL,
`haslo_konto` varchar(100) COLLATE utf8_polish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
INSERT INTO `konto` (`id_konto`, `rola_id`, `imie_konto`, `nazwisko_konto`, `email_konto`, `login_konto`, `haslo_konto`) VALUES
(1, 1, 'Jan', 'Kowalski', '<EMAIL>', 'Użytkownik', 'uzytkownik'),
(2, 3, 'Bartek', 'Kowalski', '<EMAIL>', 'SuperRedaktor', 'superredaktor'),
(3, 4, 'Kacper', 'Kowalski', '<EMAIL>', 'Administrator', 'administrator'),
(4, 2, 'Andrzej', 'Kowalski', '<EMAIL>', 'Redaktor', 'redaktor');
CREATE TABLE `podkategoria` (
`id_podkategoria` int(11) NOT NULL,
`kategoria_id` int(11) NOT NULL,
`nazwa_podkategoria` varchar(30) COLLATE utf8_polish_ci NOT NULL,
`opis_podkategoria` text CHARACTER SET utf32 COLLATE utf32_polish_ci NOT NULL,
`img_podkategoria` varchar(100) COLLATE utf8_polish_ci DEFAULT 'default.png',
`dir_podkategoria` text COLLATE utf8_polish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
INSERT INTO `podkategoria` (`id_podkategoria`, `kategoria_id`, `nazwa_podkategoria`, `opis_podkategoria`, `img_podkategoria`, `dir_podkategoria`) VALUES
(8, 7, 'Dni Tygodnia', 'Słówka z dni tygodnia.', 'calendar.png', 'ea3de8a7-2c3f-4b92-bf0c-5cb5c663e654'),
(9, 7, 'Kolory', 'Nazwy kolorów.', 'color_icon.png', '876592b2-3672-4fcd-baff-cfbcee75322d'),
(10, 7, 'Liczby', 'Słówka z liczb.', 'number_phone_numbers_stroke-512.png', '5b6fe57b-8823-4cb5-b354-8a9c0af0a452'),
(11, 8, 'Charakter', 'Cechy charakteru.', 'bf5_0.png', '880e5f02-a065-4b03-8b40-a56994890954'),
(12, 8, 'Części ciała', 'Słówka z części ciała.', 'body-512.png', 'c23c0885-f12c-434a-bd7d-22edaf646b2f'),
(13, 8, 'Ubrania', 'Słówka z ubrań.', 'Clothes_Rack_furniture_icon_ID_633.png', '70b7aef8-cc44-4dae-9ea6-ec8c6d882517'),
(14, 8, '<NAME>', 'Rodzina.', 'grandmother2_freealluses.png', 'bdf86745-e2d1-42e3-93b2-3041c750f67a'),
(15, 9, 'Domowe', 'Zwierzęta w domu.', 'd311eb7f9e927ea7ba604387f6278558.jpg', '77f53af7-bc52-46f3-b5a1-ced1304e7785'),
(16, 9, 'Ptaki', 'Wszystko co lata.', 'bird-icon.png', '3e16c732-e9b3-4f04-99a7-41a6cd53ea2c'),
(17, 9, 'Ryby', 'Wodny świat.', 'dolphin_256.png', '5a82d08d-9ada-4ffe-87c9-7b146e2d0c9f'),
(18, 9, 'Dzikie', 'Dzikie zwierzęta.', 'lion-icon.png', 'af2a1993-0dcd-4424-8396-8fc5c00048e6'),
(19, 10, 'Biologia', 'Słówka z biologii.', 'biology_icon.jpg', '3f7b6f3f-042a-4e2f-8a3d-f3262a17f8af'),
(20, 10, 'Informatyka', 'Słówka z informatyki.', 'Computer.png', 'd5d261a9-1997-42e1-9afa-bfe11a4317fc'),
(21, 10, 'Chemia', 'Słówka z chemii.', '1280px-Alizarin_chemical_structure.png', '3f175142-85c0-4f48-94d8-f6ea3991aa76'),
(22, 10, 'Matematyka', 'Słówka z matematyki.', 'basic3-105_calculator-512.png', '6e15cb0d-dcbc-4fd7-83f9-81d4d8beb49f');
CREATE TABLE `rola` (
`id_rola` int(11) NOT NULL,
`nazwa_rola` varchar(30) COLLATE utf8_polish_ci NOT NULL,
`opis_rola` text COLLATE utf8_polish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
INSERT INTO `rola` (`id_rola`, `nazwa_rola`, `opis_rola`) VALUES
(1, 'Użytkownik', 'Zwykły użytkownik.'),
(2, 'Redaktor', 'Redaktor'),
(3, 'SuperRedaktor', 'SuperRedaktor'),
(4, 'Administrator', 'Administrator serwisu.');
CREATE TABLE `slowo` (
`id_slowo` int(11) NOT NULL,
`jezyk_id` int(11) DEFAULT '0',
`nazwa_slowo` varchar(30) COLLATE utf8_polish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
INSERT INTO `slowo` (`id_slowo`, `jezyk_id`, `nazwa_slowo`) VALUES
(1, 2, 'czarny'),
(2, 1, 'black'),
(3, 2, 'szary'),
(4, 1, 'grey'),
(5, 2, 'biały'),
(6, 1, 'white'),
(7, 2, 'żółty'),
(8, 1, 'yellow'),
(9, 2, 'pomarańczowy'),
(10, 1, 'orange'),
(11, 2, 'zielony'),
(12, 1, 'green'),
(13, 2, 'brązowy'),
(14, 1, 'brown'),
(15, 2, 'różowy'),
(16, 1, 'pink'),
(17, 2, 'czerwony'),
(18, 1, 'red'),
(19, 2, 'złoty'),
(20, 1, 'golden'),
(21, 2, 'fioletowy'),
(22, 1, 'purple'),
(23, 2, 'niebieski'),
(24, 1, 'blue'),
(25, 2, 'jasnoniebieski'),
(26, 1, 'light blue'),
(27, 2, 'srebrny'),
(28, 1, 'silver'),
(29, 2, 'poniedziałek'),
(30, 1, 'Monday'),
(31, 2, 'wtorek'),
(32, 1, 'Tuesday'),
(33, 2, 'środa'),
(34, 1, 'Wednesday'),
(35, 2, 'czwartek'),
(36, 1, 'Thursday'),
(37, 2, 'piątek'),
(38, 1, 'Friday'),
(39, 2, 'sobota'),
(40, 1, 'Saturday'),
(41, 2, 'niedziela'),
(42, 1, 'Sunday'),
(43, 2, 'jeden'),
(44, 1, 'one'),
(45, 2, 'dwa'),
(46, 1, 'two'),
(47, 2, 'trzy'),
(48, 1, 'three'),
(49, 2, 'cztery'),
(50, 1, 'four'),
(51, 2, 'pięć'),
(52, 1, 'five'),
(53, 2, 'sześć'),
(54, 1, 'six'),
(55, 2, 'siedem'),
(56, 1, 'seven'),
(57, 2, 'osiem'),
(58, 1, 'eight'),
(59, 2, 'dziewięć'),
(60, 1, 'nine'),
(61, 2, 'dziesięć'),
(62, 1, 'ten'),
(63, 2, 'jedenaście'),
(64, 1, 'eleven'),
(65, 2, 'dwanaście'),
(66, 1, 'twelve'),
(67, 2, 'trzynaście'),
(68, 1, 'thirteen'),
(69, 2, 'czternaście'),
(70, 1, 'fourteen'),
(71, 2, 'piętnaście'),
(72, 1, 'fifteen'),
(73, 2, 'szesnaście'),
(74, 1, 'sixteen'),
(75, 2, 'siedemnaście'),
(76, 1, 'seventeen'),
(77, 2, 'osiemnaście'),
(78, 1, 'eighteen'),
(79, 2, 'dziewiętnaście'),
(80, 1, 'nineteen'),
(81, 2, 'dwadzieścia'),
(82, 1, 'twenty'),
(83, 2, 'agresywny'),
(84, 1, 'aggressive'),
(85, 2, 'ambitny'),
(86, 1, 'ambitious'),
(87, 2, 'arogancki'),
(88, 1, 'arrogant'),
(89, 2, 'chełpliwy'),
(90, 1, 'boastful'),
(91, 2, 'dominujący'),
(92, 1, 'bossy'),
(93, 2, 'dzielny'),
(94, 1, 'brave'),
(95, 2, 'bystry'),
(96, 1, 'bright'),
(97, 2, 'tolerancyjny'),
(98, 1, 'tolerant'),
(99, 2, 'opanowany'),
(100, 1, 'calm'),
(101, 2, 'szczery'),
(102, 1, 'candid'),
(103, 2, 'beztroski'),
(104, 1, 'carefree'),
(105, 2, 'niedbały'),
(106, 1, 'careless'),
(107, 2, 'cecha'),
(108, 1, 'characteristic'),
(109, 2, 'czarujacy'),
(110, 1, 'charming'),
(111, 2, 'bezczelny'),
(112, 1, 'insolent'),
(113, 2, 'nierozsądny'),
(114, 1, 'unwise'),
(115, 2, 'ciekawy'),
(116, 1, 'curious'),
(117, 2, 'cierpliwy'),
(118, 1, 'patient'),
(119, 2, 'czarujący'),
(120, 2, 'despotyczny'),
(121, 1, 'overbearing'),
(122, 2, '<NAME>chowany'),
(123, 1, 'well-behaved'),
(124, 2, 'dumny'),
(125, 1, 'proud'),
(126, 2, 'dyskretny'),
(127, 1, 'discreet'),
(128, 2, 'egoistyczny'),
(129, 1, 'selfish'),
(130, 2, 'gadatliwy'),
(131, 1, 'talkative'),
(132, 2, 'chamski'),
(133, 1, 'rude'),
(134, 2, 'prostoduszny'),
(135, 1, 'naive'),
(136, 2, 'przebiegły'),
(137, 1, 'cunning'),
(138, 2, 'przezorny'),
(139, 1, 'prudent'),
(140, 2, 'przyjacielski'),
(141, 1, 'friendly'),
(142, 2, 'przyjemny'),
(143, 1, 'pleasant'),
(144, 2, 'rozsądny'),
(145, 1, 'reasonable'),
(146, 2, 'skromny'),
(147, 1, 'modest'),
(148, 2, 'spokojny'),
(149, 1, 'quiet'),
(150, 2, 'otwarty'),
(151, 1, 'open');
CREATE TABLE `tlumaczenie` (
`id_tlumaczenie` int(11) NOT NULL,
`slowo_id_one` int(11) NOT NULL,
`slowo_id_two` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
INSERT INTO `tlumaczenie` (`id_tlumaczenie`, `slowo_id_one`, `slowo_id_two`) VALUES
(1, 2, 1),
(2, 4, 3),
(3, 6, 5),
(4, 8, 7),
(5, 10, 9),
(6, 12, 11),
(7, 14, 13),
(8, 16, 15),
(9, 18, 17),
(10, 20, 19),
(11, 22, 21),
(12, 24, 23),
(13, 26, 25),
(14, 28, 27),
(15, 30, 29),
(16, 32, 31),
(17, 34, 33),
(18, 36, 35),
(19, 38, 37),
(20, 40, 39),
(21, 42, 41),
(22, 44, 43),
(23, 46, 45),
(24, 48, 47),
(25, 50, 49),
(26, 52, 51),
(27, 54, 53),
(28, 56, 55),
(29, 58, 57),
(30, 60, 59),
(31, 62, 61),
(32, 64, 63),
(33, 66, 65),
(34, 68, 67),
(35, 70, 69),
(36, 72, 71),
(37, 74, 73),
(38, 76, 75),
(39, 78, 77),
(40, 80, 79),
(41, 82, 81),
(42, 84, 83),
(43, 86, 85),
(44, 88, 87),
(45, 90, 89),
(46, 92, 91),
(47, 94, 93),
(48, 96, 95),
(49, 98, 97),
(50, 100, 99),
(51, 102, 101),
(52, 104, 103),
(53, 106, 105),
(54, 108, 107),
(55, 110, 109),
(56, 112, 111),
(57, 114, 113),
(58, 116, 115),
(59, 118, 117),
(60, 110, 119),
(61, 121, 120),
(62, 123, 122),
(63, 125, 124),
(64, 127, 126),
(65, 129, 128),
(66, 131, 130),
(67, 133, 132),
(68, 135, 134),
(69, 137, 136),
(70, 139, 138),
(71, 141, 140),
(72, 143, 142),
(73, 145, 144),
(74, 147, 146),
(75, 149, 148),
(76, 151, 150);
CREATE TABLE `uprawnienia` (
`id_uprawnienia` int(11) NOT NULL,
`konto_id` int(11) NOT NULL,
`podkategoria_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
INSERT INTO `uprawnienia` (`id_uprawnienia`, `konto_id`, `podkategoria_id`) VALUES
(1, 4, 10),
(2, 2, 12);
CREATE TABLE `wynik` (
`id_wynik` int(11) NOT NULL,
`konto_id` int(11) NOT NULL,
`zestaw_id` int(11) NOT NULL,
`data_wynik` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`wynik_wynik` int(11) NOT NULL,
`komentarz_wynik` varchar(100) COLLATE utf8_polish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
INSERT INTO `wynik` (`id_wynik`, `konto_id`, `zestaw_id`, `data_wynik`, `wynik_wynik`, `komentarz_wynik`) VALUES
(1, 1, 6, '2016-04-24 12:25:01', 0, 'Polski - Angielski'),
(2, 1, 6, '2016-04-24 12:32:43', 45, 'Angielski - Polski'),
(3, 1, 2, '2016-04-24 12:32:43', 65, 'Angielski - Polski'),
(4, 1, 2, '2016-04-24 12:32:43', 85, 'Polski - Polski'),
(5, 1, 3, '2016-04-24 12:32:43', 95, 'Angielski - Polski'),
(6, 1, 4, '2016-04-24 12:32:43', 25, 'Polski - Polski'),
(7, 1, 5, '2016-04-24 12:32:43', 62, 'Angielski - Polski'),
(8, 1, 6, '2016-04-24 12:32:43', 64, 'Polski - Polski');
CREATE TABLE `zestaw` (
`id_zestaw` int(11) NOT NULL,
`konto_id` int(11) DEFAULT '0',
`jezyk_id_one` int(11) DEFAULT '0',
`jezyk_id_two` int(11) DEFAULT '0',
`podkategoria_id` int(11) NOT NULL,
`nazwa_zestaw` varchar(30) COLLATE utf8_polish_ci NOT NULL,
`ilosc_slowek_zestaw` int(11) NOT NULL DEFAULT '0',
`data_edycji_zestaw` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`prywatny_zestaw` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
INSERT INTO `zestaw` (`id_zestaw`, `konto_id`, `jezyk_id_one`, `jezyk_id_two`, `podkategoria_id`, `nazwa_zestaw`, `ilosc_slowek_zestaw`, `data_edycji_zestaw`, `prywatny_zestaw`) VALUES
(1, 3, 1, 2, 9, 'Kolory', 14, '2016-04-24 12:01:37', 0),
(2, 3, 1, 2, 8, '<NAME>', 7, '2016-04-24 12:02:46', 0),
(3, 3, 1, 2, 10, 'Liczebniki', 20, '2016-04-24 12:04:00', 0),
(4, 3, 1, 2, 11, '<NAME>', 14, '2016-04-24 12:06:09', 0),
(5, 3, 1, 2, 11, '<NAME>', 11, '2016-04-24 12:07:04', 0),
(6, 3, 1, 2, 11, 'Osobowość', 10, '2016-04-24 12:08:03', 0);
CREATE TABLE `zestawienie` (
`id_zestawienie` int(11) NOT NULL,
`tlumaczenie_id` int(11) NOT NULL,
`zestaw_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
INSERT INTO `zestawienie` (`id_zestawienie`, `tlumaczenie_id`, `zestaw_id`) VALUES
(1, 1, 1),
(2, 2, 1),
(3, 3, 1),
(4, 4, 1),
(5, 5, 1),
(6, 6, 1),
(7, 7, 1),
(8, 8, 1),
(9, 9, 1),
(10, 10, 1),
(11, 11, 1),
(12, 12, 1),
(13, 13, 1),
(14, 14, 1),
(15, 15, 2),
(16, 16, 2),
(17, 17, 2),
(18, 18, 2),
(19, 19, 2),
(20, 20, 2),
(21, 21, 2),
(22, 22, 3),
(23, 23, 3),
(24, 24, 3),
(25, 25, 3),
(26, 26, 3),
(27, 27, 3),
(28, 28, 3),
(29, 29, 3),
(30, 30, 3),
(31, 31, 3),
(32, 32, 3),
(33, 33, 3),
(34, 34, 3),
(35, 35, 3),
(36, 36, 3),
(37, 37, 3),
(38, 38, 3),
(39, 39, 3),
(40, 40, 3),
(41, 41, 3),
(42, 42, 4),
(43, 43, 4),
(44, 44, 4),
(45, 45, 4),
(46, 46, 4),
(47, 47, 4),
(48, 48, 4),
(49, 49, 4),
(50, 50, 4),
(51, 51, 4),
(52, 52, 4),
(53, 53, 4),
(54, 54, 4),
(55, 55, 4),
(56, 56, 5),
(57, 57, 5),
(58, 58, 5),
(59, 59, 5),
(60, 60, 5),
(61, 61, 5),
(62, 62, 5),
(63, 63, 5),
(64, 64, 5),
(65, 65, 5),
(66, 66, 5),
(67, 67, 6),
(68, 68, 6),
(69, 69, 6),
(70, 70, 6),
(71, 71, 6),
(72, 72, 6),
(73, 73, 6),
(74, 74, 6),
(75, 75, 6),
(76, 76, 6);
DELIMITER $$
CREATE TRIGGER `slowo_count` AFTER INSERT ON `zestawienie` FOR EACH ROW UPDATE zestaw SET ilosc_slowek_zestaw = ilosc_slowek_zestaw + 1, data_edycji_zestaw=CURRENT_TIMESTAMP WHERE id_zestaw = NEW.zestaw_id
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER `slowo_delete` AFTER DELETE ON `zestawienie` FOR EACH ROW UPDATE zestaw SET ilosc_slowek_zestaw = ilosc_slowek_zestaw - 1, data_edycji_zestaw = CURRENT_TIMESTAMP WHERE id_zestaw = OLD.zestaw_id
$$
DELIMITER ;
ALTER TABLE `jezyk`
ADD PRIMARY KEY (`id_jezyk`);
ALTER TABLE `kategoria`
ADD PRIMARY KEY (`id_kategoria`);
ALTER TABLE `konto`
ADD PRIMARY KEY (`id_konto`),
ADD UNIQUE KEY `login_konto` (`login_konto`),
ADD KEY `rola_id` (`rola_id`);
ALTER TABLE `podkategoria`
ADD PRIMARY KEY (`id_podkategoria`),
ADD KEY `kategoria_id` (`kategoria_id`);
ALTER TABLE `rola`
ADD PRIMARY KEY (`id_rola`);
ALTER TABLE `slowo`
ADD PRIMARY KEY (`id_slowo`),
ADD KEY `jezyk_id` (`jezyk_id`);
ALTER TABLE `tlumaczenie`
ADD PRIMARY KEY (`id_tlumaczenie`),
ADD KEY `slowo_id_one` (`slowo_id_one`),
ADD KEY `slowo_id_two` (`slowo_id_two`);
ALTER TABLE `uprawnienia`
ADD PRIMARY KEY (`id_uprawnienia`),
ADD KEY `konto_id` (`konto_id`),
ADD KEY `podkategoria_id` (`podkategoria_id`);
ALTER TABLE `wynik`
ADD PRIMARY KEY (`id_wynik`),
ADD KEY `konto_id` (`konto_id`),
ADD KEY `zestaw_id` (`zestaw_id`);
ALTER TABLE `zestaw`
ADD PRIMARY KEY (`id_zestaw`),
ADD KEY `konto_id` (`konto_id`),
ADD KEY `jezyk_id_one` (`jezyk_id_one`),
ADD KEY `jezyk_id_two` (`jezyk_id_two`),
ADD KEY `podkategoria_id` (`podkategoria_id`);
ALTER TABLE `zestawienie`
ADD PRIMARY KEY (`id_zestawienie`),
ADD KEY `slowo_id` (`tlumaczenie_id`),
ADD KEY `zestaw_id` (`zestaw_id`);
ALTER TABLE `jezyk`
MODIFY `id_jezyk` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
ALTER TABLE `kategoria`
MODIFY `id_kategoria` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
ALTER TABLE `konto`
MODIFY `id_konto` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
ALTER TABLE `podkategoria`
MODIFY `id_podkategoria` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23;
ALTER TABLE `rola`
MODIFY `id_rola` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
ALTER TABLE `slowo`
MODIFY `id_slowo` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=152;
ALTER TABLE `tlumaczenie`
MODIFY `id_tlumaczenie` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=77;
ALTER TABLE `uprawnienia`
MODIFY `id_uprawnienia` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
ALTER TABLE `wynik`
MODIFY `id_wynik` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
ALTER TABLE `zestaw`
MODIFY `id_zestaw` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
ALTER TABLE `zestawienie`
MODIFY `id_zestawienie` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=77;
ALTER TABLE `konto`
ADD CONSTRAINT `konto_ibfk_1` FOREIGN KEY (`rola_id`) REFERENCES `rola` (`id_rola`) ON DELETE SET NULL;
ALTER TABLE `podkategoria`
ADD CONSTRAINT `podkategoria_ibfk_1` FOREIGN KEY (`kategoria_id`) REFERENCES `kategoria` (`id_kategoria`) ON DELETE CASCADE;
ALTER TABLE `slowo`
ADD CONSTRAINT `slowo_ibfk_1` FOREIGN KEY (`jezyk_id`) REFERENCES `jezyk` (`id_jezyk`) ON DELETE SET NULL;
ALTER TABLE `tlumaczenie`
ADD CONSTRAINT `tlumaczenie_ibfk_1` FOREIGN KEY (`slowo_id_one`) REFERENCES `slowo` (`id_slowo`) ON DELETE CASCADE,
ADD CONSTRAINT `tlumaczenie_ibfk_2` FOREIGN KEY (`slowo_id_two`) REFERENCES `slowo` (`id_slowo`) ON DELETE CASCADE;
ALTER TABLE `uprawnienia`
ADD CONSTRAINT `uprawnienia_ibfk_1` FOREIGN KEY (`konto_id`) REFERENCES `konto` (`id_konto`) ON DELETE CASCADE,
ADD CONSTRAINT `uprawnienia_ibfk_2` FOREIGN KEY (`podkategoria_id`) REFERENCES `podkategoria` (`id_podkategoria`) ON DELETE CASCADE;
ALTER TABLE `wynik`
ADD CONSTRAINT `wynik_ibfk_1` FOREIGN KEY (`konto_id`) REFERENCES `konto` (`id_konto`) ON DELETE CASCADE,
ADD CONSTRAINT `wynik_ibfk_2` FOREIGN KEY (`zestaw_id`) REFERENCES `zestaw` (`id_zestaw`) ON DELETE CASCADE;
ALTER TABLE `zestaw`
ADD CONSTRAINT `zestaw_ibfk_1` FOREIGN KEY (`konto_id`) REFERENCES `konto` (`id_konto`) ON DELETE SET NULL,
ADD CONSTRAINT `zestaw_ibfk_2` FOREIGN KEY (`jezyk_id_one`) REFERENCES `jezyk` (`id_jezyk`) ON DELETE SET NULL,
ADD CONSTRAINT `zestaw_ibfk_3` FOREIGN KEY (`jezyk_id_two`) REFERENCES `jezyk` (`id_jezyk`) ON DELETE SET NULL,
ADD CONSTRAINT `zestaw_ibfk_4` FOREIGN KEY (`podkategoria_id`) REFERENCES `podkategoria` (`id_podkategoria`) ON DELETE CASCADE;
ALTER TABLE `zestawienie`
ADD CONSTRAINT `tlumaczenie_ibfk_3` FOREIGN KEY (`tlumaczenie_id`) REFERENCES `tlumaczenie` (`id_tlumaczenie`) ON DELETE CASCADE,
ADD CONSTRAINT `zestawienie_ibfk_2` FOREIGN KEY (`zestaw_id`) REFERENCES `zestaw` (`id_zestaw`) ON DELETE CASCADE;
|
0d2e4b5bbb7b8cb7ee055da4a9edcdfeb8524b49
|
[
"Markdown",
"SQL"
] | 4
|
Markdown
|
Apocaliptic95/SQL
|
67ea7eed4698ebc0b6830e95d9b382d86c6b8989
|
ef1b8af6eab90832e23ed6b74e81dc7e64f00785
|
refs/heads/master
|
<file_sep># PARANDO CONTAINERS
docker-compose down
# REMOVENDO IMAGENS
docker rmi -f ijm/projeto-db
#docker rmi -f npw/projeto-share
docker rmi -f ijm/projeto-core
docker rmi -f ijm/projeto-web
# REMOVENDO VOLUME
#docker volume remove ./bd:/var/lib/postgresql
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.rdu.ifpb.web.cdi;
import ifpb.dac.projeto.shared.service.ProfService;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.Produces;
/**
*
* @author jose2
*/
@ApplicationScoped
public class ProfServiceProducer {
// java:global/rhecruta-core/UserServiceImpl!br.edu.ifpb.dac.rhecruta.shared.interfaces.UserService, java:global/rhecruta-core/UserServiceImpl
private static final String RESOURCE = "java:global/core/ProfServiceImpl!ifpb.dac.projeto.shared.service.ProfService";
@Dependent
@Produces
@Default
private ProfService getProfService() {
return new ServiceLocator().lookup(RESOURCE, ProfService.class);
}
}
<file_sep>**Instituto Federal de Educação, Ciência e Tecnologia da Paraíba**
**<NAME>**
**Curso Superior de Tecnologia em Análise e Desenvolvimento de Sistemas**
**Desenvolvimento de Aplicações Corporativas**
**Professor**: <NAME>
**Alunos**: <NAME>, <NAME>, <NAME>
<h3 align="center">
Projeto: Final da disciplina
</h3>
Para ver detalhes sobre especificaçÕes do projeto juntamente com uma breve
Em produção
#### ROTEIRO PARA IMPLANTAR E UTILIZAR A APLICAÇÃO COM DOCKER (*)
1. Certifique-se que o seu serviço **Docker** esteja iniciado e que não haja outros serviços rodando nas seguintes portas: 5434, 8082, 4951, 3701, 8083, 4952
2. Para iniciar os containers da ***Aplicação***, a partir da pasta bin deste projeto execute `sh ./run.sh` (\*\*). A partir deste passo, a aplicação já deve estar disponível para uso, logo após os containers terem inicializado.
3. Se desejar parar todos os containers e remover os volumes de persistência de dados, pode ser executado `sh ./stop.sh`(\*\*).
\*\* Os scripts `run.sh` e `stop.sh` são válidos para sistemas unix-like.
** No sistema windows **
execute `stop.bat` (\*\*). para iniciar e `stop.bat` (\*\*). Parar
Os passos acima devem ser suficientes para iniciar os containers/módulos, bem como aqueles responsáveis pela persistência.
4. Depois de inicializados os containers, o serviço web estará disponívesl em [http://localhost:8083/web/](http://localhost:8083/web/).
Foi inserido um usuário `admin` para início de uso do sistema, com as seguinte credenciais:
- email: <EMAIL>
- senha: <PASSWORD>
<hr>
#### O que os scripts fazem:
1. `run.sh`:
- compila o módulos, construindo os arquivos `.war` a serem implantados no Docker.
- inicia os containers através do Docker/docker-compose.
- ao terminar a inicialação do último container, o script é encadeado com a execução de um comando que faz acompanhamento dos logs de inicialização da imagem do `Payara` que abriga o módulo/container `rhecruta-core`. A visualização deste log tem finalidade puramente observatória e pode ser cancelada a qualquer tempo sem prejuízo para execução dos containers no Docker.
2. `stop.sh`:
- encerra todos os containers iniciados através do docker-compose;
- remove as imagens do projeto que foram criadas pelo script de inicalização;
- (pode) remove o volume de persistência do container baseado em `Postgresql`. Sinta-se livre, por exemplo, para comentar/descomentar esta última linha no arquivo com intuito de preservar ou apagar o conteúdo do volume antes de encerrar a execução dos containers.
3. Para sistemas **Windows** run.bat e stop.bat que são correspondèntes aos scriots citados a cima.
<hr>
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ifpb.dac.projeto.shared.service;
import ifpb.dac.projeto.shared.entity.Professor;
import java.io.Serializable;
/**
*
* @author jose2
*/
public interface ProfService extends Serializable {
public void save(Professor professor);
public Professor search(int key);
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ifpb.dac.projeto.core.repsitory;
import java.util.List;
/**
*
* @author jose2
* @param <T>
*/
public interface RepositorioJPA<T> {
public void create(T entity);
public T find(int key ,Class<T> type);
public List<T> findAll(Class<T> type);
public T update(T entity);
public void remove(T entity);
}
<file_sep>cd .. && mvn clean install
docker-compose up -d --build
docker logs -f $(docker ps -q -f name=" projeto-core")
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ifpb.dac.projeto.core.repsitory;
import java.util.Collections;
import java.util.List;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
@Stateless
@Local(RepositorioJPA.class)
public class RepositorioJPAImpl<T> implements RepositorioJPA<T> {
@PersistenceContext(unitName = "iprojeto_PU")
private EntityManager manager;
@Override
public void create(T entity) {
manager.persist(entity);
}
@Override
public T find(int key, Class<T> type) {
return manager.find(type, key);
}
@Override
public List<T> findAll(Class<T> type) {
Query query;
query = manager.createQuery("Select e from " + type.getName() + " as e", type);
List resultado = query.getResultList();
if (!resultado.isEmpty()) {
return resultado;
}
return Collections.EMPTY_LIST;
}
@Override
public T update(T entity) {
return manager.merge(entity);
}
@Override
public void remove(T entity) {
manager.remove(entity);
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ifpb.dac.projeto.core.service;
import ifpb.dac.projeto.core.repsitory.ProfessorRepositorio;
import ifpb.dac.projeto.shared.entity.Professor;
import ifpb.dac.projeto.shared.service.ProfService;
import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
/**
*
* @author jose2
*/
@Stateless
@Remote(ProfService.class)
public class ProfServiceImpl implements ProfService{
@EJB
private ProfessorRepositorio repositorio;
@Override
public void save(Professor professor) {
repositorio.create(professor);
}
@Override
public Professor search(int key) {
return repositorio.find(key, Professor.class);
}
}
<file_sep>FROM postgres
MAINTAINER natarajan <<EMAIL>>
ENV POSTGRES_USER postgres
ENV POSTGRES_PASSWORD <PASSWORD>
ENV POSTGRES_DB projeto
|
e1ae54c8f8f3ab728fd8fff0f85f131b2f22f1e6
|
[
"Markdown",
"Java",
"Dockerfile",
"Shell"
] | 9
|
Shell
|
joseferreir/DAC-projeto
|
5415356c1b95db5ea6908bb0a872a4ed682d1204
|
028d78f0d40e01dd4808d4bb4fd6b065cb957a61
|
refs/heads/master
|
<repo_name>kir-dev13/gulp_setup_0.1<file_sep>/#src/js/script.js
"use strict";
@@include("_checkWebpSupport.js");
|
7754bd150621f7594e467f86c548438f6dd97ee5
|
[
"JavaScript"
] | 1
|
JavaScript
|
kir-dev13/gulp_setup_0.1
|
ae32fc2fd3e9830fda2d9e2968d5171711f26e0e
|
0a29fb9f4bff1e935979d6abde22c891d53c8c21
|
refs/heads/main
|
<file_sep>Notes:
- Exported bot token environment variable
TODO:
- Check this works with Heroku deployment via gitHub
- Add a heroku hosted database
- Experiment with the app falling asleep
- Better error handling so that one error doesnt take the bot down
- Continue with type script version if wanted<file_sep>const { Composer } = require('micro-bot')
const bot = new Composer()
bot.start((ctx) => ctx.reply("Hello! Let's talk!"))
bot.help((ctx) => ctx.reply('Hmm i am not programmed to be helpful, yet!'))
bot.hears('hello', (ctx) => ctx.reply('Ok, I heard you say hello'))
bot.command('sing', (ctx) => ctx.reply('La la la! I got your command.'))
module.exports = bot<file_sep>import e from 'express';
import { Telegraf } from 'telegraf'
import getBotTokenOrQuit from './util/getBotToken';
import { pickRandom } from './util/random';
const fetch = require('node-fetch');
const botToken = getBotTokenOrQuit();
const bot = new Telegraf(botToken)
bot.start((ctx) => ctx.reply("Hello! Let's talk!"))
bot.help((ctx) => ctx.reply('Hmm i am not programmed to be helpful, yet!'))
bot.hears('hello', (ctx) => ctx.reply('Ok, I heard you say hello'))
bot.command('sing', (ctx) => ctx.reply('La la la! I got your command.'))
bot.command('time', (ctx) => {
const date = new Date();
ctx.reply(`The time is ${date.toUTCString()}`)
})
bot.command('fortune', async (ctx) => {
const response = await fetch('http://yerkee.com/api/fortune')
const body = await response.json()
ctx.reply(`Your fortune is ${body.fortune}`)
})
bot.command('dog', async (ctx) => {
const text = ctx.message.text
const requestedBreed = getBreed(text) // length of dog plus 2 (for / and space)
if (requestedBreed) {
const response = await fetch(`https://dog.ceo/api/breed/${requestedBreed}/images`)
if (!response.ok) {
ctx.reply("Sorry that isn't a real breed, so here's a random dog for you")
ctx.replyWithPhoto(await getRandomDog())
}
else {
const body = await response.json()
const photoUrls = body.message
ctx.replyWithPhoto(pickRandom(photoUrls))
}
} else {
ctx.reply("You didn't give me a breed, but here's a random dog")
ctx.replyWithPhoto(await getRandomDog())
}
})
bot.launch()
// Enable graceful stop
process.once('SIGINT', () => bot.stop('SIGINT'))
process.once('SIGTERM', () => bot.stop('SIGTERM'))
async function getRandomDog() {
const response = await fetch('https://dog.ceo/api/breeds/image/random')
const body = await response.json()
const photoUrl = body.message
return photoUrl
}
function getBreed(text: string) {
const withoutDog = text.substring(5)
return removeSpaces(withoutDog.toLowerCase())
}
function removeSpaces(string: string) {
return string.replace(/\s+/g, '');
}
|
9da4b1b7518d466b6ed18ad1b320d29d58508392
|
[
"Markdown",
"TypeScript",
"JavaScript"
] | 3
|
Markdown
|
esmehm/first-telegram-bot
|
55a992b76777a7095c649425e6e57bf836ae2c6b
|
7ad967b0e3c442459dc7bc1dd8e15a6519ecec0a
|
refs/heads/main
|
<file_sep>//recebe o retorno através do webhook
$data = json_decode(file_get_contents("php://input"));
print_r($data);
$idasaas = $data->payment->id;
$installment = $data->payment->installment;
$valpago = $data->payment->value;
$vencbol = $data->payment->originalDueDate;
$confirmed = $data->event;
$forma_pagamento = $data->payment->billingType;
if($confirmed == "PAYMENT_RECEIVED" and $forma_pagamento =="BOLETO" and !empty($idasaas))
{
m_php_baixa($idasaas, $forma_pagamento); //cria métodos para dar baixa direto no sistema.
}
elseif($confirmed == "PAYMENT_CONFIRMED" and $forma_pagamento =="CREDIT_CARD" and !empty($idasaas))
{
m_php_baixa($idasaas, $forma_pagamento); //cria métodos para dar baixa direto no sistema.
}
<file_sep><?php
class asaas{
//Variaveis protegidas_________________________
private $host = '127.0.0.1';
private $user = 'usuario';
private $pass = '<PASSWORD>';
private $banco = 'asaas';
private $codcliente;
private $cliente;
private $urlTeste;
private $urlProducao;
private $apiKey;
private $url;
private $apikey;
private $ambiente;
private $conexao;
//_____________________________________________
//Getters______________________________________
private function GetCodCliente($codcliente){
return $this->codcliente;
}
private function GetCliente(){
return $this->cliente;
}
private function GetUrlTeste(){
return $this->urlTeste;
}
private function GetUrlProducao(){
return $this->urlProducao;
}
private function GetApiKey(){
return $this->apiKey;
}
private function GetHost(){
return $this->host;
}
private function GetUser(){
return $this->user;
}
private function GetPass(){
return $this->pass;
}
private function GetBanco(){
return $this->banco;
}
private function GetUrl(){
return $this->url;
}
private function GetAmbiente(){
return $this->ambiente;
}
//_____________________________________________
//Setters______________________________________
private function SetCodCliente($codcliente){
$this->codcliente = $codcliente;
}
private function SetCliente($cliente){
$this->cliente = $cliente;
}
private function SetUrlTeste($urlTeste){
$this->urlTeste = $urlTeste;
}
private function SetUrlProducao($urlProducao){
$this->urlProducao = $urlProducao;
}
private function SetApiKey($apiKey){
$this->apiKey = $apiKey;
}
private function SetUrl($url){
$this->url = $url;
}
private function SetAmbiente($ambiente){
$this->ambiente = $ambiente;
if($ambiente=='T'){
$this->SetUrl($this->GetUrlTeste());
}elseif($ambiente=='P'){
$this->SetUrl($this->GetUrlProducao());
}
}
//Faz a conexão com o banco de dados e define as variaveis padrão do ASAAS
private function SetConexao($cliente,$dados){
//Verifica se vai usar a conexão padrão ou se o usuário informou uma conexão
if(empty($dados)){
$host = $this->GetHost();
$user = $this->GetUser();
$pass = $this->GetPass();
$banco = $this->GetBanco();
}
else{
$host = $dados[0];
$user = $dados[1];
$pass = $dados[2];
$banco = $dados[3];
}
//Cria a conexão
$con=mysqli_connect($host,$user,$pass,$banco);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Busca os dados padrão do ASAAS
$resultado = mysqli_query($con,"SELECT CodCliente, Cliente, UrlTeste, UrlProducao, ApiKey FROM tblconfig WHERE CodCliente = '$cliente'");
$row=mysqli_fetch_array($resultado,MYSQLI_ASSOC);
//Define as variaveis padrão
$this->SetCodCliente($row['CodCliente']);
$this->SetCliente($row['Cliente']);
$this->SetUrlTeste($row['UrlTeste']);
$this->SetUrlProducao($row['UrlProducao']);
$this->SetApiKey($row['ApiKey']);
//Retorna o ApiKey do ASAAS
return $this->GetApiKey();
}
//_____________________________________________
//Funções______________________________________
//Ao Construir a class define a conesão e o ambiente (T=Teste, P=Producao)
function __construct($cliente,$ambiente,$dados=''){
$this->SetConexao($cliente,$dados);
$this->SetAmbiente($ambiente);
}
//METODOS DE REQUISIÇÃO DO ASAAS
//DELETE
private function DeleteAsaas($url){
//Pega o ApiKey
$apiKey = $this->GetApiKey();
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "DELETE",
CURLOPT_POSTFIELDS => "",
CURLOPT_HTTPHEADER => array(
"access_token: $apiKey"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
//Retorna os dados ou os erros
if ($err) {
return json_decode($err,true);
} else {
return json_decode($response,true);
}
}
//GET
private function GetAsaas($url){
//Pega o ApiKey
$apiKey = $this->GetApiKey();
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"access_token: $apiKey",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
//Retorna os dados ou os erros
if ($err) {
return json_decode($err,true);
} else {
return json_decode($response,true);
}
}
//POST
private function PostAsaas($url, $dados){
//Pega o ApiKey
$apiKey = $this->GetApiKey();
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => http_build_query($dados),
CURLOPT_HTTPHEADER => array(
"access_token: $apiKey",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
//Retorna os dados ou os erros
if ($err) {
return json_decode($err,true);
} else {
return json_decode($response,true);
}
}
//CLIENTES________________________________________________________________________
//Cadastra um cliente
function ClienteNovo($NomeAsas,$EmailAsas,$CpfASas,$CepASas,$TelefoneASAAS,$EnderecoASas,$NumeroCasaAsas,$ComplementoAsas,$CodigoRefAsas)
{
$url = $this->GetUrl().'/api/v3/customers';
$dados = array('name'=>$NomeAsas,
'email'=>$EmailAsas,
'cpfCnpj'=>$CpfASas,
'postalCode'=>$CepASas,
'mobilePhone'=>$TelefoneASAAS,
'address'=>$EnderecoASas,
'addressNumber'=>$NumeroCasaAsas,
'complement'=>$ComplementoAsas,
'externalReference'=>$CodigoRefAsas,
'notificationDisabled'=>true);
return $this->PostAsaas($url, $dados);
}
//Consulta um cliente
function Cliente($customer){
$url = $this->GetUrl().'/api/v3/customers/'.$customer;
return $this->GetAsaas($url);
}
//Busca uma lista de clientes por filtro
function ClientesListar($dados)
{
/*A Variavel dados receber um array com os seguintes indices name, email, cpfcnpj, externalReference, offset, limit
Obs: offset é o numero da pagina no asaas
O Array pode conter 1 ou mais desses parametros, não é obrigatório preencher todos
*/
$valores = '';
if(!empty($dados['name'])){
$valores .= 'name='.$dados['name'].'&';
}
if(!empty($dados['email'])){
$valores .= 'email='.$dados['email'].'&';
}
if(!empty($dados['cpfCnpj'])){
$valores .= 'cpfCnpj='.$dados['cpfCnpj'].'&';
}
if(!empty($dados['externalReference'])){
$valores .= 'externalReference='.$dados['externalReference'].'&';
}
if(!empty($dados['offset'])){
$valores .= 'offset='.$dados['offset'].'&';
}
if(!empty($dados['limit'])){
$valores .= 'limit='.$dados['limit'].'&';
}else{
$valores .= 'limit=100&';
}
$valores = substr($valores,0,-1);
if(!empty($valores)){
$url = $this->GetUrl().'/api/v3/customers?'.$valores;
return $this->GetAsaas($url);
}
}
//Atualiza os dados do cliente
function ClienteAtualizar($customer,$dados){
/*A Variavel dados receber um array com os seguintes indices name, cpfCnpj, email, phone, mobilePhone, address, addressNumber, complement,
postalCode, externalReference, notificationDisabled, additionalEmails, municipalInscription, stateInscription
O Array pode conter 1 ou mais desses parametros, não é obrigatório preencher todos
*/
$url = $this->GetUrl().'/api/v3/customers/'.$customer;
$apiKey = $this->GetApiKey();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($dados));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"access_token: $apiKey"
));
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response);
}
//Deleta um cliente
function ClienteDeletar($customer){
$url = $this->GetUrl().'/api/v3/customers/'.$customer;
return $this->DeleteAsaas($url);
}
//______________________________________________
//COBRANÇA______________________________________
///////////////////////___________CARTÃO DE CRÉDITO
//Atualiza os dados do cliente
function CartaoCriar($dados){
/*A Variavel dados receber um array com os seguintes indices name, cpfCnpj, email, phone, mobilePhone, address, addressNumber, complement,
postalCode, externalReference, notificationDisabled, additionalEmails, municipalInscription, stateInscription
O Array pode conter 1 ou mais desses parametros, não é obrigatório preencher todos
*/
$url = $this->GetUrl().'/api/v3/payments';
$apiKey = $this->GetApiKey();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($dados));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"access_token: $apiKey"
));
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response);
}
//Cria uma cobrança do tipo boleto no ASAAS
function BoletoCriar($Customer,$Vencimento,$Valor,$Ref,$Parcelas='',$nomeevento){
$url = $this->GetUrl().'/api/v3/payments';
$apiKey = $this->GetApiKey();
$dados = array(
"customer" => $Customer,
"billingType"=> "BOLETO",
"dueDate"=> $Vencimento,
"value"=> $Valor,
"description"=> $nomeevento,
"externalReference"=> "$Ref"
);
if(!empty($Parcelas) && $Parcelas > 1){
unset($dados['value']);
$dados['installmentCount'] = $Parcelas;
$dados['installmentValue'] = $Valor;
}
/*
///TIRAR O COMENTÁRIO CASO USE DESCONTO
if(!empty($valdesc) && $valdesc > 1)
{
$dados['discount']['value']=$valdesc;
$dados['discount']['type']="FIXED";
$dados['discount']['dueDateLimitDays']=$datadesc;
}
*/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($dados));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"access_token: $apiKey"
));
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response);
}
//Pega os dados de um boleto no ASAAS
function Boleto($payment){
$url = $this->GetUrl().'/api/v3/payments/'.$payment;
return $this->GetAsaas($url);
}
//Busca uma lista de boletos do ASAAS com filtro
function BoletoListar($dados, $limite_registro){
/*A Variavel dados receber um array com os seguintes indices customer, billingType, status, subscription, installment,
externalReference, offset, limit
Obs: offset é o numero da pagina no asaas
O Array pode conter 1 ou mais desses parametros, não é obrigatório preencher todos
*/
$valores = '';
if(!empty($dados['customer'])){
$valores .= 'customer='.$dados['customer'].'&';
}
if(!empty($dados['billingType'])){
$valores .= 'billingType='.$dados['billingType'].'&';
}
if(!empty($dados['status'])){
$valores .= 'status='.$dados['status'].'&';
}
if(!empty($dados['subscription'])){
$valores .= 'subscription='.$dados['subscription'].'&';
}
if(!empty($dados['installment'])){
$valores .= 'installment='.$dados['installment'].'&';
}
if(!empty($dados['externalReference'])){
$valores .= 'externalReference='.$dados['externalReference'].'&';
}
if(!empty($dados['paymentDate'])){
$valores .= 'paymentDate='.$dados['paymentDate'].'&';
}
if(!empty($dados['offset'])){
$valores .= 'offset='.$dados['offset'].'&';
}
/*
if(!empty($dados['limit'])){
$valores .= 'limit='.$dados['limit'].'&';
}else{
$valores .= 'limit=3&';
}*/
if(!empty($limite_registro))
{
$valores .= 'limit='.$limite_registro.'&';
}
else
{
$valores .= 'limit=3&';
}
$valores = substr($valores,0,-1);
if(!empty($valores)){
$url = $this->GetUrl().'/api/v3/payments?'.$valores.'';
return $this->GetAsaas($url);
}
}
//Listar um parcelamento de boletos - Retorna um array já com o indice da parcela
function BoletoParcelas($installment){
/*O Asaas normalmente traz as parcelas em ordem decrescente porem ele pode mudar essa lógica e
ele nao traz o numero da parcela em um parametro apenas na descrição o que pode ser alterado
a qualquer momento pelo Asaas.
Para retornarmos um array em ordem vamos usar a seguinte logica
1 - Retornar as parcelas do Asaas
2 - Reescrever um array colocando como indice a data de vencimento sem traço
3 - Usar a função do php ksort para ordernar um array pela chave - assim vai ficar em ordem as parcelas
4 - Reescrever novamente o array que agora esta em ordem e colocar como indice o numero da parcela
4.1 - Enquanto estiver reescrevendo o array vamos adicionar os parametros Numero da Parcela e Total de Parcelas
*/
//1º Passo
$url = $this->GetUrl().'/api/v3/payments?installment='.$installment.'&limit=50';
$parcelas = $this->GetAsaas($url); //Pega as parcelas
//2º Passo
$arrParcelas = array();
foreach($parcelas['data'] as $valores){
$data = str_replace('-','',$valores['originalDueDate']);
$arrParcelas[$data] = $valores;
}
//3º Passo
ksort($arrParcelas);
//4º Passo
$vParcelas = array();
$i=1;
$qtd = count($arrParcelas); //Conta a quantidade de parcelas
foreach($arrParcelas as $ordem)
{
$vParcelas[$i] = $ordem; //Inclui o array com as informações da parcela
//4.1º Passo - Inclui as informações de Numero de Parcela e Quantidade de parcelas
$vParcelas[$i]['NumeroParcela'] = $i; //Informa o numero da parcelas
$vParcelas[$i]['TotalParcelas'] = $qtd; //Informa o total de parcelas
$i++; //Passa para a proxima parcela
}
return $vParcelas;
}
//Atualiza os dados do boleto no ASAAS
function BoletoAtualizar($id,$valores){
/*A Variavel dados receber um array com os seguintes indices dueDate, value, description, externalReference
O Array pode conter 1 ou mais desses parametros, não é obrigatório preencher todos
*/
if(!empty($valores['dueDate'])){
$dados['dueDate'] = $valores['dueDate'];
}
if(!empty($valores['value'])){
$dados['value'] = $valores['value'];
}
if(!empty($valores['description'])){
$dados['description'] = $valores['description'];
}
if(!empty($valores['externalReference'])){
$dados['externalReference'] = $valores['externalReference'];
}
//Verifica se o id é uma string para alterar um boleto ou um array para alterar em lote
if(!is_array($id)){
$url = $this->GetUrl().'/api/v3/payments/'.$id;
return $this->PostAsaas($url,$dados);
}
else{
$boletos = array();
foreach($id as $fr){
$url = $this->GetUrl().'/api/v3/payments/'.$fr;
$boletos[] = $this->PostAsaas($url,$dados);
}
return $boletos;
}
}
//Deleta um boleto do ASAAS
function BoletoDeletar($id){
//Verifica se o id é uma string para deletar um boleto ou um array para deletar em lote
if(!is_array($id)){
$url = $this->GetUrl().'/api/v3/payments/'.$id;
return $this->DeleteAsaas($url);
}
else{
$boletos = array();
foreach($id as $fr){
$url = $this->GetUrl().'/api/v3/payments/'.$fr;
$boletos[] = $this->DeleteAsaas($url);
}
return $boletos;
}
}
//______________________________________________
}
?>
<file_sep># asaas
API ASAAS
|
b0c05e7d300070ad1b1cc541ff35455fbe9aa377
|
[
"Markdown",
"PHP"
] | 3
|
PHP
|
lucasmatsumoto/asaas
|
98b6efed0f77c40d252c4bfce8d9e846f1e7809d
|
82ce4a4cfc1ee3997c11c210111a64da00ea779d
|
refs/heads/master
|
<repo_name>lidongcn/js-practice<file_sep>/String/保存.js
/**
* 保存规则 Rules
*/
$scope.saveRules = function () {
// 验证表单, 成功后保存
validator.validate('tradeForm', function () {
Confirm({
title : '确认保存',
content : '请确认是否保存当前设置',
clickedClose: true,
ok : function () {
Rules.save($scope.param, function (result) {
// 如果保存成功, 重新查询
if (result.success) {
alertMsg.success('保存成功!');
//$scope.getRules($stateParams);
$scope.getByActionCode(function (queryParams) {
$scope.getRules(queryParams);
$scope.getRelations();
});
} else {
alertMsg.error('保存失败!原因:' + result.msg);
}
});
}
});
});
};<file_sep>/String/开关.js
消费送积分
/**
* 设置开关
*/
$scope.settingRelation = function () {
//- 声明变量info 保存提示语
var info = {
title : '开启确认',
content: '请确认是否要打开消费积分发放?'
};
if ($scope.tradesIsOpen === 'Y') {
var info = {
title : '关闭确认',
content: '请确认是否要关闭消费积分发放?'
}
}
Confirm({
title: info.title,
content: info.content,
clickedClose: true,
ok: function () {
if ($scope.relationId) {
Rules.openTrade({relationId: $scope.relationId}, function (open) {
if (open.success && open.data) {
var param = {relationId: $scope.relationId},
data = {
status: STATUS_MAP[$scope.tradesIsOpen]
};
Relations.setting(param, data, function (result) {
if (result.success) {
$scope.getRelations();
} else {
alertMsg.error('设置开关失败!');
}
});
} else {
alertMsg.error('规则不能为空!');
}
});
} else {
alertMsg.error('relationId为空!');
}
}
});
};
<file_sep>/README.md
##JavaScript Exercises, Practice, Solution
###The best way we learn anything is by practice and exercise questions. We have started this section for those who are familiar with JavaScript. Hope, these exercises help you to improve your JavaScript coding skills. Currently following sections are available, we are working hard to add more exercises. Happy Coding!<file_sep>/Math/Math_19.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>
The Pythagorean Theorem tells us that the relationship in every right triangle is : c2 = a2 + b2, where c is the
hypotenuse and a, b are two legs of the triangle.
</p>
<script>
function theorem(a, b) {
if ((typeof a !== 'number') || (typeof b !== 'number')) {
return false;
}
return Math.sqrt(a * a + b * b);
}
console.log(theorem(2, 4));
console.log(theorem(3, 4));
</script>
</body>
</html>
|
b6160d5ed9a7e082d2c2e4becda81b994a9b9a58
|
[
"JavaScript",
"HTML",
"Markdown"
] | 4
|
JavaScript
|
lidongcn/js-practice
|
ecd660d4b25a1f7c5a466223b0877f033f91b3d7
|
a0c8cad16383c17b52b7e21e7330c218339c0eae
|
refs/heads/master
|
<file_sep>using MaterialSkin.Common;
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace MaterialSkin.Controls
{
public class CMaterialLabel : Label, IMaterialControl
{
[Browsable(false)]
public int Depth { get; set; }
[Browsable(false)]
public MaterialSkinManager SkinManager => MaterialSkinManager.Instance;
[Browsable(false)]
public MouseState MouseState { get; set; }
/// <summary>
/// 是否使用自定义字体
/// </summary>
[Category("自定义字体")]
[DefaultValue(FontType.MaterialSkin)]
public FontType UseFontType { get; set; }
/// <summary>
/// 自定字体名, 如果启用此属性, UseCustomFont 必须设置为True
/// 通常, 会将自定义字体放在Resources.resx文件中
/// </summary>
[Category("自定义字体")]
public string CustomFontName { get; set; }
/// <summary>
/// 文本显示的正常颜色
/// </summary>
[Category("自定义字体")]
public Color CustomLabelNMLColor { get; set; }
/// <summary>
/// 鼠标覆盖在文本上的颜色
/// </summary>
[Category("自定义字体")]
public Color CustomLabelOVRColor { get; set; }
/// <summary>
/// 鼠标按下去的时候文本的颜色
/// </summary>
[Category("自定义字体")]
public Color CustomLabelDWNColor { get; set; }
// 文字的颜色流程: nml -> mouse enter -> mouse down -> mouse leave -> nml
// 显示的颜色分为三种: nml、ovr、dwn
// 也就是: nml -> ovr -> dwn -> ovr -> nml
// |--->nml
/// <summary>
/// 当鼠标进入的时候
/// </summary>
/// <param name="e"></param>
protected override void OnMouseEnter(EventArgs e)
{
ForeColor = CustomLabelOVRColor ;
}
/// <summary>
/// 当鼠标移开时
/// </summary>
/// <param name="e"></param>
protected override void OnMouseLeave(EventArgs e)
{
ForeColor = CustomLabelNMLColor;
}
/// <summary>
/// 当鼠标抬起的时候
/// </summary>
/// <param name="e"></param>
protected override void OnMouseUp(MouseEventArgs e)
{
ForeColor = CustomLabelOVRColor;
}
/// <summary>
/// 当鼠标按下时
/// </summary>
/// <param name="e"></param>
protected override void OnMouseDown(MouseEventArgs e)
{
ForeColor = CustomLabelDWNColor;
}
/// <summary>
/// 当Font属性改变时
/// </summary>
/// <param name="e"></param>
protected override void OnFontChanged(EventArgs e)
{
if(UseFontType!=FontType.CustomFont)
{
return;
}
if (string.IsNullOrEmpty(CustomFontName))
{
MessageBox.Show("CustomFontName 没有设置!");
return;
}
// 确认字体
Font = new Font(FontManager.GetFont(CustomFontName), Font.Size);
}
protected override void OnCreateControl()
{
base.OnCreateControl();
AutoSize = false;
ForeColor = SkinManager.GetPrimaryTextColor();
UseFontType = FontType.CustomFont;
CustomFontName = "fzjz";
// 确认字体
Font font = SkinManager.ROBOTO_REGULAR_11; // 默认使用皮肤管理中的字体
switch (UseFontType)
{
case FontType.System:
font = new System.Drawing.Font(Font.Name, Font.Size);
break;
case FontType.CustomFont:
font = new Font(FontManager.GetFont(CustomFontName), Font.Size);
break;
case FontType.MaterialSkin:
font = SkinManager.ROBOTO_REGULAR_11;
break;
}
Font = font;
BackColorChanged += (sender, args) => ForeColor = SkinManager.GetPrimaryTextColor();
}
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using TX3Installer.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TX3Installer.Common.Tests
{
[TestClass()]
public class SevenZipHelperTests
{
[TestMethod()]
public void ExtractTest()
{
string sPath = "C:/Users/zhanghui03/source/repos/DirectorEditor/TestResources/testzip.7z";
string tPath = "C:/Users/zhanghui03/source/repos/DirectorEditor/TestResources/xixi";
SevenZipHelper.Extract(sPath, tPath);
}
}
}<file_sep>//#define ENABLE_MAIN_ENTER
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/**
where用法:
<code><![CDATA[
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate);
]]></code>
**/
#if ENABLE_MAIN_ENTER
class Tutorials_5
{
static void Main(string[] args)
{
}
}
#endif
<file_sep>using MVPFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TX3Installer.UILogic;
using TX3Installer.Views;
namespace TX3Installer.Presenters
{
[ViewLogicBinding(typeof(MainInstallerViewLogic))]
public class MainInstallerPresenter:Presenter<IMainInstallerView>
{
public void Show()
{
View.Show();
}
public void Close()
{
View.Close();
}
/// <summary>
/// 设置解压进度条
/// </summary>
/// <param name="value"></param>
public void SetExtractProgress(int value)
{
View.SetExtractProgress(value);
}
}
}
<file_sep>//#define ENABLE_MAIN_ENTER
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/**
* LINQ Method Syntax
*
*/
#if ENABLE_MAIN_ENTER
class Tutorials_4
{
static void Main(string[] args)
{
// string collection
IList<string> stringList = new List<string>() {
"C# Tutorials",
"VB.NET Tutorials",
"Learn C++",
"MVC Tutorials" ,
"Java"
};
// LINQ Query Syntax
var result = stringList.Where(s => s.Contains("Tutorials"));
}
}
#endif
<file_sep>using DirectorEditor.Presenters;
using DirectorEditor.UILogic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TX3Installer.Presenters;
namespace DirectorEditor
{
public static class PresenterStub
{
// 第三方Material Skin控件的P层
private static SkinDemoPresenter _skinDemoPresenter;
public static SkinDemoPresenter SkinDemoPresenter
{
set => _skinDemoPresenter = value;
get
{
if (_skinDemoPresenter == null)
{
_skinDemoPresenter = new SkinDemoPresenter();
}
return _skinDemoPresenter;
}
}
// 安装主界面
private static MainInstallerPresenter _mainInstallerPresenter;
public static MainInstallerPresenter MainInstallerPresenter
{
set => _mainInstallerPresenter = value;
get
{
if(_mainInstallerPresenter == null)
{
_mainInstallerPresenter = new MainInstallerPresenter();
}
return _mainInstallerPresenter;
}
}
}
}
<file_sep>using DirectorEditor;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TX3Installer.Common
{
/// <summary>
/// 7Zip 工具类
/// </summary>
public class SevenZipHelper
{
private static StringBuilder sevenZipOutput;// 7Zip解压log
/// <summary>
/// 解压指定文件到指定目录
/// </summary>
/// <param name="sourcePath"> 指定文件</param>
/// <param name="targetDir"> 指定目录</param>
/// <param name="monitor">是否监视解压的进度</param>
public static void Extract(string sourcePath, string targetDir)
{
// 初始化
sevenZipOutput = new StringBuilder();
Process sevenZip = new Process();
try
{
//读取资源写入
string sevenZPath = Path.Combine(System.Environment.CurrentDirectory, "7z.exe");
if (!File.Exists(sevenZPath))
{
File.WriteAllBytes(sevenZPath, global::TX3Installer.Properties.Resources._7z1);
}
if (!File.Exists(sevenZPath.Replace("exe", "dll")))
{
File.WriteAllBytes(sevenZPath.Replace("exe", "dll"), global::TX3Installer.Properties.Resources._7z);
}
sevenZip.StartInfo.FileName = sevenZPath;
sevenZip.StartInfo.Arguments = "x -y -o\"" + targetDir + "\" \"" + sourcePath + "\"";
sevenZip.StartInfo.UseShellExecute = false;
sevenZip.StartInfo.CreateNoWindow = true;
sevenZip.StartInfo.RedirectStandardOutput = true;
sevenZip.StartInfo.RedirectStandardError = true;
if (!sevenZip.Start())
throw new FileLoadException("7z could not start!");
sevenZip.BeginOutputReadLine();
sevenZip.BeginErrorReadLine();
do
{
Application.DoEvents();
SetProgress((int)(FileOperationHelper.getSizeInCurrentDirectory(targetDir) * 1.0 / InstallerConfig.Config.DataBytesSize * 100));
} while (!sevenZip.WaitForExit(2000));
SetProgress(100);
}
finally
{
if(sevenZip != null)
{
sevenZip.Dispose();
sevenZip = null;
}
}
// 处理输出消息
string output = sevenZipOutput.ToString();
int index = output.IndexOf("Error:");
if (index != -1)
throw new ArgumentException(output.Substring(index + 6).Trim().Replace("\n", "").Replace("\r", ""));
}
/// <summary>
/// 设置进度条
/// </summary>
/// <param name="value"></param>
private static void SetProgress(int value)
{
Trace.WriteLine("progress: " + value);
try
{
ThreadPool.QueueUserWorkItem(val => PresenterStub.MainInstallerPresenter.SetExtractProgress(value), value);
}
catch(Exception ex)
{
}
}
}
}
<file_sep>using IWshRuntimeLibrary;
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace TX3Installer.Common
{
/// <summary>
/// 安装操作
/// </summary>
public class InstallOperation
{
private static int bitness = Marshal.SizeOf(typeof(IntPtr)) * 8;
/// <summary>
/// 创建快捷键
/// </summary>
/// <param name="path"></param>
public static void CreateShortcuts(string path)
{
//path + Path.DirectorySeparatorChar + "DirectorEditor-" + bitness + ".exe";
string exePath = path;
try
{
// 创建桌面的快捷方式
IWshShortcut shortcut = (IWshShortcut)new WshShell().CreateShortcut(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + Path.DirectorySeparatorChar + "DirectorEditor.lnk");
shortcut.Description = "视频编辑器";
shortcut.WorkingDirectory = path;
shortcut.TargetPath = exePath;
shortcut.Save();
// 创建开始菜单的快捷方式
//string shortcutDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu), "Programs", "DirectorEditor");
//Directory.CreateDirectory(shortcutDirectory);
//WshShell shell = new WshShell();
//IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(Path.Combine(shortcutDirectory, "DirectorEditor.lnk"));
//shortcut.Description = "DirectorEditor视频编辑器";
//shortcut.WorkingDirectory = path;
//shortcut.TargetPath = exePath;
//shortcut.Save();
}
catch (Exception e)
{
}
}
}
}<file_sep>namespace TX3Installer.Common
{
/// <summary>
/// 应用程序的配置文件
/// </summary>
public class InstallerConfig
{
/// <summary>
/// 数据总大小
/// </summary>
public readonly ulong DataBytesSize;
/// <summary>
/// 默认安装路径
/// </summary>
public readonly string DefaultInstallPath;
/// <summary>
/// 需要解压文件的MD5
/// </summary>
public readonly string FileMD5;
/// <summary>
/// 安装文件
/// </summary>
public readonly string Install7ZFile;
/// <summary>
/// 程序的版本号
/// </summary>
public readonly string Version;
/// <summary>
/// 可执行文件名
/// </summary>
public readonly string ExeFile;
private static InstallerConfig m_config;
private static ulong m_dataBytesSize = 5499043916;
private static string m_defaultInstallPath = "D:\\Director";
private static string m_install7ZFile = "DirectorEditor.7z";
private static string m_exeFile = "DirectorEditor.exe";
public InstallerConfig(ulong dataBytesSize)
{
DataBytesSize = dataBytesSize;
DefaultInstallPath = m_defaultInstallPath;
Install7ZFile = m_install7ZFile;
ExeFile = m_exeFile;
}
public static InstallerConfig Config
{
get
{
if (m_config == null)
{
m_config = new InstallerConfig(m_dataBytesSize);
}
return m_config;
}
}
}
}<file_sep>//#define ENABLE_MAIN_ENTER
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// Expression用法
/// </summary>
#if ENABLE_MAIN_ENTER
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
}
class Tutorials_6
{
Func<Student, bool> isTeenAger = s => s.Age > 12 && s.Age < 20;
static void Main(string[] args)
{
Expression<Func<Student, bool>> isTeenAgerExpr = s => s.Age > 12 && s.Age < 20;
//compile Expression using Compile method to invoke it as Delegate
Func<Student, bool> isTeenAger = isTeenAgerExpr.Compile();
//Invoke
bool result = isTeenAger(new Student() { StudentID = 1, StudentName = "Steve", Age = 20 });
}
}
#endif
<file_sep>#define ENABLE_MAIN_ENTER
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// Expression tree 用法
/// </summary>
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
}
#if ENABLE_MAIN_ENTER
class Tutorials_7
{
static void Main(string[] args)
{
/*
* Func<Student, bool> isAdult = s => s.age >= 18;
* public bool function(Student s)
* {
* return s.Age > 18;
* }
*/
//Step 1: Create Parameter Expression in C#
ParameterExpression pe = Expression.Parameter(typeof(Student), "s");
//Step 2: Create Property Expression in C#
MemberExpression me = Expression.Property(pe, "Age");
//Step 3: Create Constant Expression in C#
ConstantExpression constant = Expression.Constant(18, typeof(int));
//Step 4: Create Binary Expression in C#
BinaryExpression body = Expression.GreaterThanOrEqual(me, constant);
//Step 5: Create Lambda Expression in C#
var ExpressionTree = Expression.Lambda<Func<Student, bool>>(body, new[] { pe });
Console.WriteLine("Expression Tree: {0}", ExpressionTree);
Console.WriteLine("Expression Tree Body: {0}", ExpressionTree.Body);
Console.WriteLine("Number of Parameters in Expression Tree: {0}",ExpressionTree.Parameters.Count);
Console.WriteLine("Parameters in Expression Tree: {0}", ExpressionTree.Parameters[0]);
// output:
//Expression Tree: s => (s.Age >= 18)
//Expression Tree Body: (s.Age >= 18)
//Number of Parameters in Expression Tree: 1
//Parameters in Expression Tree: s
}
}
#endif
<file_sep>using MVPFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TX3Installer.UIComponents;
using TX3Installer.Views;
namespace TX3Installer.UILogic
{
public class MainInstallerViewLogic : ViewLogic<MainInstallerView, IMainInstallerView>, IMainInstallerView
{
public bool isCompeleted = false;
public void Show()
{
target.Show();
}
public void Close()
{
target.Close();
}
public void Activate()
{
target.Activate();
}
public void SetExtractProgress(int value)
{
target.extractProgress.Value = Math.Max(0, Math.Min(100, value));
if(target.extractProgress.Value == 100 && !isCompeleted)
{
isCompeleted = true;
target.OnCompleteInstall();
}
}
}
}
<file_sep># DirectorEditor
基于winform实现的桌面应用开发框架.
目前计划包含以下主要内容:
1. 网络通信框架
2. 组件库
3. 容器注册服务
## 框架的最终设计理念汇总:
### MVPFramework UI框架设计结构图:
+--------------------------------------------------------------------------+
| MVPFramework |
+--------------------------------------------------------------------------+
+-------------+ +------------------------------+
|= Model Layer| |= Presenter Layer |
| |----------send------------->|+----------------------------+|
| | || || | |
| | || || +--------- ----------+
+-------------+ || || |= Presenter Stub |
|| Presenter List ||-----register------>| |
|| || +----------------------+
|| || |
|| || |
|+----------------------------+| |
+------------------------------+ |
| |
| |
n |
: |
n |
| |
| |
V |
+---------------------------------------------------------------------------------+ |
|= View Layer | |
| +-------------------------+ +----------------------------+| |
| |= View Component Layer | |= View Logic Layer || |
| | | | || V
| | | | || +----------------------+
| | |<--------1:1--------->| || |= View Logic Stub |
| | | | ||-----register------>| |
| | | | || +----------------------+
| | | | ||
| +-------------------------+ +----------------------------+|
|---------------------------------------------------------------------------------+
**优势如下:**
1. 实现V层和P层的完全隔离
2. 完全的数据驱动. 利用Ioc,实现UI的依赖注入
3. 增加对P层的缓存结构, 提升显示界面显示时的效率
**设计的几个约定: **
P层上的每个P都是单例
View Component Layer 和 View Logic Layer 是一一对应关系, 并且可以同时存在多个实例
Presenter Stub是整个结构的访问入口, 不要尝试通过其它手段(比如反射等)去强行直接访问MVP结构中的其它层次,这样做的目的是完全的数据驱动
View Logic layer 与 Presenter layer 有以下几种对应关系:
- Presenter : ViewLogic = 1:1
- Presenter : ViewLogic = N:1
- Presenter : ViewLogic = 1:N
**详细说明:**
Presenter : ViewLogic = 1:1 -> 一个Presenter实例对应一个ViewLogic实例
Presenter : ViewLogic = N:1 -> N种不同类型的实例对应同一ViewLogic类型的不同实例
Presenter : ViewLogic = 1:N -> 一个Presenter实例对应多个类型的ViewLogic实例
稍微难以理解的就是第二种N:1, 解释如下:
P层在代码中是以单例的形式存在, V层在代码中是以多实例的方式存在,
所以P:V = N:1, 在MVPFramework是这样处理的:
一个P层的单例对应一个V层的实例,也就是是说不同类型P层的单例可以对应V层同一类型的多实例
### MVPFramework 界面开发具体流程【以HelperView举例, 详细可参考代码】
1. **建立全局可访问的P层, 也是MVP结构的入口。**
``` csharp
// 帮助界面的P层
private static HelperPresenter _helperPresenter = null;
public static HelperPresenter HelperPresenter { set => _helperPresenter = value;
get
{
if (_helperPresenter == null)
{
_helperPresenter = new HelperPresenter();
}
return _helperPresenter;
}
}
```
如上, 我们可以使用单例来缓存P层, 当然, 如果不缓存P层,可以不这样做。但是,建议这样做。
2. **P层和View Logic绑定。P层主要处理2件事, 一是与ViewLogic绑定, 二是处理数据, 将数据转换成界面显示需要的格式。**
``` csharp
[ViewLogicBinding(typeof(HelperViewLogic))]// 指定Presenter绑定的ViewLogic类型
public class HelperPresenter:Presenter<IHelperView,HelperModel>
{
// ...
}
```
如上, 通过装饰器我们可以确定P层和ViewLogic的绑定关系, IHelperView 定义了P层可以访问ViewLogic中的接口,HelperModel 定义了P层可以缓存M层类型的数据
3. **创建ViewLogic类。这一层级专注于处理界面的显示逻辑。比如组件的显/隐、组件的数据填充等**
``` csharp
// ViewLogic<T1,T2>
// T1 : 指的是绑定的 UI组件
// T2 : 指的是暴露给Presenter的接口
public class HelperViewLogic : ViewLogic<HelperView, IHelperView>, IHelperView
{
public HelperViewLogic() : base()
{
InitViewLogic += () => { this.LayoutView(new HelperModel() { EditorDesc = "帮助文档描述初始数据" }); };
}
```
4. **创建组件。也可以直接引用第三方组件, 因为不需要修改, 这需要在这一层级用第三方的组件拼接好界面即可。**
``` csharp
/// <summary>
/// 帮助界面
/// </summary>
public partial class HelperView:Form
{
public HelperView()
{
InitializeComponent();
}
```
** TX3Installer 的效果图如下 **




## 进度(设计思考流程过程在此记录)
### 2020.9.9.14
桌面应用程序安装Demo完成, 主要包含2个功能:
1. 将压缩的应用程序的7Zip文件加压缩至对应目录
2. 为可执行文件创建桌面快捷方式
遇到的问题:
因为原来的项目工程包含了多个dll, 但是安装程序通常就只是一个EXE, 因此需要将所有引用的资源都内嵌到dll中.
这里涉及到了2种情况:
- 第一种是程序自带的dll, 使用ILMerge在后期生成事件中处理即可
- 第二种是程序引用的第三方资源, 我是采取的嵌入Resources.resx的方式. 不如7Zip.exe和7Zip.dll
### 2020.9.9.10
新建MaterialTextButton类型, 支持自定义字体及大小, 效果如下:

### 2020.9.9.8
开始着手研究Windows下的安装器怎么搞。
Visual Studio 2017 有一个官方的安装器插件, 如下:
https://marketplace.visualstudio.com/items?itemName=VisualStudioClient.MicrosoftVisualStudio2017InstallerProjects
大致创建了一个测试工程, 界面不太友好, 而且不太好改.
从这个样例工程倒是可以学到安装器的大致流程, 仿造这个流程做就好.
于是, 接下来这段时间, 就用MVP Framework 写一个安装器吧, 也验证一下这种设计的优缺点
### 2020.9.8.15.34
超级大版本更新 -> 移除绑定器的概念
### 2020.9.8.10.40
发现一个问题, 以前的结构是先创建viewlogic, 然后再创建presenter实行绑定
现在解耦合之后, 可以先创建presenter, 使用到ViewLogic的时候再进行创建, 这时候, 又会根据绑定器去查找、创建一个实例 。 这样没必要啊
也就是说, 现在没必要用这个绑定器了。 这个只有在强绑定时, 也就是在根据viewLogic去找presenter的时候才会使用
### 2020.9.7.17.30
实现了Presenter -> ViewLogic 的1:N结构, 具体demo见DataPartPresenter
``` csharp
[ViewLogicBinding(typeof(DataPart1ViewLogic))]// 绑定DataPart1ViewLogic
[ViewLogicBinding(typeof(DataPart2ViewLogic))]// 绑定DataPart2ViewLogic
public class DataPartPresenter : PresenterNN
{
// ...
}
```
Presenter 需要2步:
1. 继承PresenterNN
2. 与Presenter绑定的ViewLogic需要用装饰器进行标注
PresenterNN的意思是, 对应N个ViewLogic, N个Model数据描述结构
效果图如下, DataPartPresenter可以处理两个ViewLogic的内容:

### 2020.9.7.9.30
现在注册到PresenterStub的访问顺序结构有问题:
之前是这样的:
``` csharp
PresenterStub.HelperPresenter?.Show();
```
Presenter -> 创建ViewLogic实例 -> 创建组件实例
问题出现在Presenter的实例是在ViewLogic的实例创建之后, 从ViewLogic实例中的绑定的Presenters中选择的第一个
现在的想法是, Presenter可以独立创建. 如果Presenter需要显示某个界面, 则再去处理ViewLogi的创建
这样思考的话, 其实我只是做了ViewLogic -> Presenter的单向绑定, 如果需要做NN关系的话, 那么就需要做一个双向绑定
### 2020.9.7.8
接入MaterialSkin控件开源库

### 2020.9.4 晚上
尝试接入第三方插件库【HZH_Controls】, 完美接入.

### 2020.9.4 早晨
在仔细思考了MVC、MVP等框架的设计理念之后, 对MVPFramework进行了迭代升级:
+--------------------------------------------------------------------------+
| MVPFramework |
+--------------------------------------------------------------------------+
+-------------+ +------------------------------+
|= Model Layer| |= Presenter Layer |
| |----------send------------->|+----------------------------+|
| | || || | |
| | || || +--------- ----------+
+-------------+ || || |= Presenter Stub |
|| Presenter List ||-----register------>| |
|| || +----------------------+
|| || |
|| || |
|+----------------------------+| |
+------------------------------+ |
| |
| |
n |
: |
n |
| |
| |
V |
+---------------------------------------------------------------------------------+ |
|= View Layer | |
| +-------------------------+ +----------------------------+| |
| |= View Component Layer | |= View Logic Layer || |
| | | | || V
| | | | || +----------------------+
| | |<--------1:1--------->| || |= View Logic Stub |
| | | | ||-----register------>| |
| | | | || +----------------------+
| | | | ||
| +-------------------------+ +----------------------------+|
|---------------------------------------------------------------------------------+
其实, 传统的MVC等模式等模式并没有完全实现V层和C层的完全分离, 有的在V层甚至可以直接修改Model层的数据, 基于此, 主要做了以下改进:
1. **将V层进一步划分为View Component Layer 和 View Logic Layer**
这样做的好处主要有:
a. 在View Component Layer上, 不进行任何业务逻辑的处理, UI设计可以完全移交给美术,并且业务逻辑不会受到UI迭代的影响
b. 可以自由嵌入第三方的组件库, 并且支持随时升级。 很多时候,我们都会去选择魔改第三方库以支持自己的业务,这种设计对第三方库无任何侵入式修改,便于维护
2. **完全的数据驱动View层**
a. 为了严格做到各层之间的隔离, 防止因开发者的随意访问各层,而造成后期项目层之间的混乱
b. 作为开发者一方, 我们只关注数据和业务即可, 做到有变动即刷新
3. **P层 和 V层 n:n 的对应关系**
传统的MVC、或则MVP框架, V层和C层、P层都是1:1关系, 主要会出现数据复制的情况:
a. 对于那些不会改动的数据, 每次重新显示界面的时候都会在C层或P层重新处理一遍
b. 如果多个界面用到同一份数据, 传统做法是将数据在每个C层或P层都赋值一份,然后重新处理一遍,效率比较低
c. 如果一个界面有多个数据源, 传统做法是将涉及到的所有Model都会放到C层去处理, 然后传递到V层.问题同上
因此,做了一下改进:
在P层做一次缓存(已做), 缓存的量级达到某一程度时, 触发清理过程(还没做). 清理过程就是根据GC那套思想, 不常用的先清理, 数据占用内存较大的先清理
此外, 完善了View Logic Layer 和 Presenter Layer 绑定时的策略。 目前支持以下三种策略, 预计未来增加一种配置文件策略:
- 装饰器策略
- 标准命名策略
- 组合策略
9.2 的版本提到的DispatchCenter 概念正式替换为 Presenter Stub, 所有的Presenter 都可以在此访问.
DirectorEditor 项目为演示工程
目录结构如下:
Models: 存储各种数据结构
Presenters: 存储Presenter, 也就是业务逻辑处理层
UIComponents: UI组件层, 不包含任何业务逻辑
UILogic: UI业务逻辑层
Views: ViewLogic 需要暴露给Presenter的接口集合
PresenterStub:PresenterStub的全局访问中心
ViewLogicStub: ViewLogicStub的全局访问中心(这个在未来不会对开发者开放直接访问权限)
UI界面编写流程:
1. 在UIComponents目录下创建组件
2. 在Views目录下创建ViewLogic层需要暴露给Presenter层的接口
3. 在UILogic目录下,编写界面的业务逻辑以及实现需要暴露个Presenter层的接口
4. 在Presenters目录下,进行数据处理项目的业务逻辑, 如果有需要,在Models文件夹下定义数据结构
5. 将ViewLogic和PresenteStub分别注册到全局访问中心
6. 在需要的地方进行数据驱动即可
### 2020.9.2
MVPFramework 主体框架初步搭建完成
- M : Model层, 主要定义数据结构.
- P : Presenter层, 主要定义逻辑.
- V : View层, 主要控制视图的显示
相比于传统的winform开发流程(View、逻辑、数据结构全部混在一起), MVPFramework将数据、逻辑、View进行了解耦合,利用C#的反射原理, 在View被初始化的时候,将Presenter与之绑定起来.
Model层是一个可选的层, 因为有一些不需要与服务端、表格、数据库等数据源交互的界面,可以不用Model层。
View和Presenter绑定原理
允许自定义策略去实现绑定结构。 目前主要支持三种策略:
- 装饰器策略
- 标准命名策略
- 组合策略
所谓装饰器策略, 就是在View初始化的时候, 找到CustomAttribute, 如果是PresenterBinding类型, 则将此View和Presenter绑定起来
标准命名策略, 也是在View初始化的时候, 根据固定命名规则在整个Assembly中找到相应的Presenter, 如果找到, 则将它们绑定起来
组合策略, 就是上面的策略组合,找到一个之后, 立马结束。
需要注意的是:
Model ---> Presenter <-----> View
View层需要重新填充内容有以下几种场景:
- View初始化
- Presenter接收到其绑定的数据
调度中心 DispatchCenter
传统的MVC等模式, 其Control层还是依赖于View层, 如果View层被回收了, 那么相应的Control层也没有了。
原则上来说, 没什么问题, 但是Control层还有一个可以做但是不是必须做的内容 - 缓存。
基于这一点思考了下,
之前我们是这样去处理数据刷新的:
从View层获取Control层 ---> 然后调用Control中的接口去处理数据 ---> 如果有改动,则通知View层去刷新
其实在这个流程上, 第一步【从View层获取Control层】可以省略, 前提是需要我们设计一个独立的Control层,实现与View层的完全解耦合。
<file_sep>using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Windows.Forms;
using MaterialSkin.Animations;
using System;
using MaterialSkin.Common;
/// <summary>
/// MaterialTextButton 是 仿造 MaterialRaisedButton, 会加上一些适应项目的改动
/// 1. AutoSize, AutoSize 会改变控件的默认值False, 但是WinForm控件机会记录变动值, 因而在界面上显示为False, 这段是不会出现在脚本中的
/// 也就变相导致了开发者在开发视图界面时, 发现AutoSize设置的是False, 但是实际是True的效果, 因此, 不建议在自定义控件中修改控件的默认参数值
///
///
/// ## 添加自定义字体
/// PrivateFontColllection pfc = new PrivateFontColllection();
/// pfc.AddFontFile("xxx.ttf");
/// </summary>
namespace MaterialSkin.Controls
{
/// <summary>
/// 自定义控件, 非官方控件
/// </summary>
public class MaterialTextButton : Button, IMaterialControl
{
[Browsable(false)]
public int Depth { get; set; }
[Browsable(false)]
public MaterialSkinManager SkinManager => MaterialSkinManager.Instance;
[Browsable(false)]
public MouseState MouseState { get; set; }
public bool Primary { get; set; }
/// <summary>
/// 是否使用自定义字体
/// </summary>
[Category("自定义字体")]
[DefaultValue(FontType.MaterialSkin)]
public FontType UseFontType { get; set; }
/// <summary>
/// 自定字体名, 如果启用此属性, UseCustomFont 必须设置为True
/// 通常, 会将自定义字体放在Resources.resx文件中
/// </summary>
[Category("自定义字体")]
public string CustomFontName { get; set; }
/// <summary>
/// 自定义字体大小,如果启用此属性, UseCustomFont 必须设置为True
/// </summary>
[Category("自定义字体")]
public float CustomFontSize { get; set; }
private readonly AnimationManager _animationManager;
/// <summary>
/// 此字段用来测量文字将要显示的大小, 然后根据这个大小来调整按钮的大小
/// </summary>
private SizeF _textSize;
/// <summary>
/// 显示的图片
/// </summary>
private Image _icon;
public Image Icon
{
get { return _icon; }
set
{
_icon = value;
if (AutoSize)
Size = GetPreferredSize();
Invalidate();
}
}
public MaterialTextButton()
{
Primary = true;
// 管理动画
_animationManager = new AnimationManager(false)
{
Increment = 0.03,
AnimationType = AnimationType.EaseOut
};
_animationManager.OnAnimationProgress += sender => Invalidate();
AutoSizeMode = AutoSizeMode.GrowAndShrink;
//AutoSize = true;
}
public override string Text
{
get { return base.Text; }
set
{
base.Text = value;
Font font = SkinManager.ROBOTO_MEDIUM_10; // 默认使用皮肤管理中的字体
switch(UseFontType)
{
case FontType.System:
font = new System.Drawing.Font(Font.Name, Font.Size);
break;
case FontType.CustomFont:
font = new Font(FontManager.GetFont(CustomFontName), CustomFontSize);
break;
case FontType.MaterialSkin:
font = SkinManager.ROBOTO_MEDIUM_10;
break;
}
_textSize = CreateGraphics().MeasureString(value.ToUpper(), font);
if (AutoSize)
Size = GetPreferredSize();
Invalidate();
}
}
protected override void OnMouseUp(MouseEventArgs mevent)
{
base.OnMouseUp(mevent);
_animationManager.StartNewAnimation(AnimationDirection.In, mevent.Location);
}
protected override void OnPaint(PaintEventArgs pevent)
{
var g = pevent.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = TextRenderingHint.AntiAlias;
g.Clear(Parent.BackColor);
using (var backgroundPath = DrawHelper.CreateRoundRect(ClientRectangle.X,
ClientRectangle.Y,
ClientRectangle.Width - 1,
ClientRectangle.Height - 1,
1f))
{
g.FillPath(Primary ? SkinManager.ColorScheme.PrimaryBrush : SkinManager.GetRaisedButtonBackgroundBrush(), backgroundPath);
}
if (_animationManager.IsAnimating())
{
for (int i = 0; i < _animationManager.GetAnimationCount(); i++)
{
var animationValue = _animationManager.GetProgress(i);
var animationSource = _animationManager.GetSource(i);
var rippleBrush = new SolidBrush(Color.FromArgb((int)(51 - (animationValue * 50)), Color.White));
var rippleSize = (int)(animationValue * Width * 2);
g.FillEllipse(rippleBrush, new Rectangle(animationSource.X - rippleSize / 2, animationSource.Y - rippleSize / 2, rippleSize, rippleSize));
}
}
//Icon
var iconRect = new Rectangle(8, 6, 24, 24);
if (string.IsNullOrEmpty(Text))
// Center Icon
iconRect.X += 2;
if (Icon != null)
g.DrawImage(Icon, iconRect);
//Text
var textRect = ClientRectangle;
if (Icon != null)
{
//
// Resize and move Text container
//
// First 8: left padding
// 24: icon width
// Second 4: space between Icon and Text
// Third 8: right padding
textRect.Width -= 8 + 24 + 4 + 8;
// First 8: left padding
// 24: icon width
// Second 4: space between Icon and Text
textRect.X += 8 + 24 + 4;
}
// 其实这里可以在上面做一个字体缓存, 这里就先做一下简单验证
Font font = SkinManager.ROBOTO_MEDIUM_10; // 默认使用皮肤管理中的字体
switch (UseFontType)
{
case FontType.System:
if(Font.Name == null || Font.Size == 0f)
{
MessageBox.Show("请先设置字体的名字和大小");
return;
}
font = new System.Drawing.Font(Font.Name, Font.Size);
break;
case FontType.CustomFont:
if (CustomFontName == null || CustomFontSize == 0f)
{
MessageBox.Show("请先设置字体的名字和大小");
return;
}
font = new Font(FontManager.GetFont(CustomFontName), CustomFontSize);
break;
case FontType.MaterialSkin:
font = SkinManager.ROBOTO_MEDIUM_10;
break;
}
// 绘制文本
g.DrawString(
Text.ToUpper(),
font,
SkinManager.GetRaisedButtonTextBrush(Primary),
textRect,
new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });
}
private Size GetPreferredSize()
{
return GetPreferredSize(new Size(0, 0));
}
public override Size GetPreferredSize(Size proposedSize)
{
// Provides extra space for proper padding for content
var extra = 16;
if (Icon != null)
// 24 is for icon size
// 4 is for the space between icon & text
extra += 24 + 4;
return new Size((int)Math.Ceiling(_textSize.Width) + extra, 36);
}
}
}
<file_sep>using MVPFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TX3Installer.Views
{
public interface IMainInstallerView: IViewLogic
{
/// <summary>
/// 设置解压数据进度
/// </summary>
/// <param name="value"></param>
void SetExtractProgress(int value);
}
}
<file_sep>// #define ENABLE_MAIN_ENTER
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
#if ENABLE_MAIN_ENTER
namespace Linq.UnitTests
{
class Tutorials_1
{
static void Main(string[] args)
{
string[] names = { "Bill", "Steve", "James", "Mohan" };
// IEnumerable<string>
var myLinqQuery = from name in names
where name.Contains('a')
select name;
foreach (var name in myLinqQuery)
{
Console.WriteLine(name + " ");
}
}
}
}
#endif
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using TX3Installer.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TX3Installer.Common.Tests
{
[TestClass()]
public class FileOperationHelperTests
{
[TestMethod()]
public void getSizeInCurrentDirectoryTest()
{
string tPath = "C:/Users/zhanghui03/source/repos/DirectorEditor/TestResources/xixi";
var size = FileOperationHelper.getSizeInCurrentDirectory(tPath);
}
}
}<file_sep> using MaterialSkin;
using MaterialSkin.Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using TX3Installer.Common;
namespace TX3Installer.UIComponents
{
public partial class MainInstallerView : MaterialForm
{
/// <summary>
/// 当前安装路径
/// </summary>
private string m_curInstallExePath = InstallerConfig.Config.DefaultInstallPath;
public MainInstallerView()
{
InitializeComponent();
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;//设置该属性 为false
this.curInstallPath.Text = m_curInstallExePath;
this.Sizable = false;
}
/// <summary>
/// 隐藏所有控件
/// </summary>
private void hideAllControls()
{
this.materialTextButton1.Visible = false;// 快速安装
this.cMaterialLabel1.Visible = false;// 自定义安装
this.materialCheckBox1.Visible = false;// 显示协议
}
/// <summary>
/// 是否同意相关协议
/// </summary>
private void onCheckStateChanged(object sender, EventArgs e)
{
var isChecked = this.materialCheckBox1.CheckState == CheckState.Checked;
this.materialTextButton1.Enabled = isChecked;
this.cMaterialLabel1.Enabled = isChecked;
}
/// <summary>
/// 立即安装
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void materialTextButton1_Click(object sender, EventArgs e)
{
if (this.extractProgress.Value > 0 && this.extractProgress.Value < 100)
{
MessageBox.Show("正在安装中。。。");
return;
}
this.extractProgress.Visible = true;// 显示进度条
string sPath = Path.Combine(Environment.CurrentDirectory, InstallerConfig.Config.Install7ZFile);
string tPath = m_curInstallExePath;
if (!Directory.Exists(tPath))
{
Directory.CreateDirectory(tPath);
}
if(Directory.GetFiles(tPath).Length > 0) // 如果目标目录存文件, 先删除
{
try
{
FileOperationHelper.RemoveFullFolder(tPath);
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
var thread = new Thread(() => SevenZipHelper.Extract(sPath,tPath))
{
Name = "InstallThread",
IsBackground = true
};
thread.Start();
}
/// <summary>
/// 快速安装
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void materialTextButton3_Click(object sender, EventArgs e)
{
if (this.extractProgress.Value > 0 && this.extractProgress.Value < 100)
{
MessageBox.Show("正在安装中。。。");
return;
}
this.customInstallPanel.Visible = false;// 隐藏界面
this.extractProgress.Visible = true;// 显示进度条
string sPath = Path.Combine(Environment.CurrentDirectory, InstallerConfig.Config.Install7ZFile);
string tPath = m_curInstallExePath;
if(!Directory.Exists(tPath))
{
Directory.CreateDirectory(tPath);
}
var thread = new Thread(() => SevenZipHelper.Extract(sPath, tPath))
{
Name = "InstallThread",
IsBackground = true
};
thread.Start();
}
/// <summary>
/// 完成安装
/// </summary>
public void OnCompleteInstall()
{
string exePath = Path.Combine(m_curInstallExePath, InstallerConfig.Config.ExeFile);
if(File.Exists(exePath))
{
InstallOperation.CreateShortcuts(exePath);
this.materialTextButton5.Visible = true;
}
else
{
MessageBox.Show(string.Format("未能为{0}创建快捷方式",InstallerConfig.Config.ExeFile));
}
}
// 自定义安装设置
private void cMaterialLabel1_Click(object sender, EventArgs e)
{
this.customInstallPanel.Visible = true;
this.materialTextButton1.Visible = false;
}
// 返回
private void materialTextButton4_Click(object sender, EventArgs e)
{
this.customInstallPanel.Visible = false;
this.materialTextButton1.Visible = true;
}
// 浏览
private void materialTextButton2_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog dialog = new FolderBrowserDialog())
{
dialog.SelectedPath = m_curInstallExePath;
dialog.ShowNewFolderButton = true;
if (dialog.ShowDialog() == DialogResult.OK)
this.curInstallPath.Text = dialog.SelectedPath + Path.DirectorySeparatorChar + "DirectorEditor";
}
}
/// <summary>
/// 如果安装路径手动修改了
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void curInstallPath_TextChanged(object sender, EventArgs e)
{
m_curInstallExePath = this.curInstallPath.Text;
}
// 立即体验
private void materialTextButton5_Click(object sender, EventArgs e)
{
string exePath = Path.Combine(m_curInstallExePath, InstallerConfig.Config.ExeFile);
FileOperationHelper.RunExe(exePath);
this.Close();
}
}
}
<file_sep>//#define ENABLE_MAIN_ENTER
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/**
* LINQ Query Syntax
There are two basic ways to write a LINQ query to IEnumerable collection or IQueryable data sources.
1. Query Syntax or Query Expression Syntax
2. Method Syntax or Method Extension Syntax or Fluent
查询语法格式:
<code><![CDATA[
from <range variable> in <IEnumerable<T> or IQueryable<T> Collection>
<Standard Query Operators> <lambda expression>
<select or groupBy operator> <result formation>
]]></code>
**/
#if ENABLE_MAIN_ENTER
class Tutorials_3
{
static void Main(string[] args)
{
}
}
#endif
<file_sep>using DirectorEditor;
using DirectorEditor.UILogic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using TX3Installer.UILogic;
namespace TX3Installer
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run((PresenterStub.MainInstallerPresenter.View as MainInstallerViewLogic).target);
}
}
}
|
a100d9949e5ce63bac9d0446d31a492064edd86a
|
[
"Markdown",
"C#"
] | 20
|
C#
|
bugbug2022/DirectorEditor
|
4533081aa975e92370b8072123fecd81adc53dc4
|
198427b4cbda9485deb57ab8b9e77d141037f502
|
refs/heads/master
|
<repo_name>risscasey/MongoStack<file_sep>/MongoDB-Front-End/README.md
# MongoDB-Front-End
<file_sep>/MongoDB-Front-End/js/script.js
let serverURL;
let serverPort;
let url;
let editing = false;
// Get the JSON File
$.ajax({
url: 'config.json',
type: 'GET',
dataType: 'json',
success:function(keys){
serverURL = keys['SERVER_URL'];
serverPort = keys['SERVER_PORT'];
url = `${keys['SERVER_URL']}:${keys['SERVER_PORT']}`;
getProductsData();
},
error: function(){
console.log('cannot find config.json file, cannot run application');
}
});
// Get all the products
getProductsData = () => {
$.ajax({
url: `${url}/allProducts`,
type: 'GET',
dataType: 'json',
success:function(data){
for (var i = 0; i < data.length; i++) {
$('#productList').append(`
<li
class="list-group-item d-flex justify-content-between align-items-center productItem"
data-id="${data[i]._id}"
>
<span class="productPrice">$${data[i].price} |</span> <b><span class="productName">${data[i].name}</span></b><br>
<div>
<button class="btn btn-info editBtn">Edit</button>
<button class="btn btn-danger removeBtn">Remove</button>
</div>
</li>
`);
}
},
error: function(err){
console.log(err);
console.log('something went wrong with getting all the products');
}
})
}
//Add or Edit a product
$('#addProductButton').click(function(){
event.preventDefault();
let productName = $('#productName').val();
let productPrice = $('#productPrice').val();
if(productName.length === 0){
console.log('please enter a products name');
} else if(productPrice.length === 0){
console.log('please enter a products price');
} else {
if(editing === true){
const id = $('#productID').val();
$.ajax({
url: `${url}/product/${id}`,
type: 'PATCH',
data: {
name: productName,
price: productPrice
},
success:function(result){
$('#productName').val(null);
$('#productPrice').val(null);
$('#productID').val(null);
$('#addProductButton').text('Add New Product').removeClass('btn-warning');
$('#heading').text('Add New Product');
editing = false;
const allProducts = $('.productItem');
allProducts.each(function(){
if($(this).data('id') === id){
$(this).find('.productName').text(productName);
}
});
},
error: function(err){
console.log(err);
console.log('something went wront with editing the product');
}
})
} else {
$.ajax({
url: `${url}/product`,
type: 'POST',
data: {
name: productName,
price: productPrice
},
success:function(result){
$('#productName').val(null);
$('#productPrice').val(null);
$('#productList').append(`
<li class="list-group-item d-flex justify-content-between align-items-center productItem">
<span class="productName">${result.name}</span>
<div>
<button class="btn btn-info editBtn">Edit</button>
<button class="btn btn-danger removeBtn">Remove</button>
</div>
</li>
`);
},
error: function(error){
console.log(error);
console.log('something went wrong with sending the data');
}
})
}
}
})
// Edit button to fill the form with exisiting product
$('#productList').on('click', '.editBtn', function() {
event.preventDefault();
const id = $(this).parent().parent().data('id');
$.ajax({
url: `${url}/product/${id}`,
type: 'get',
dataType: 'json',
success:function(product){
$('#productName').val(product['name']);
$('#productPrice').val(product['price']);
$('#productID').val(product['_id']);
$('#addProductButton').text('Edit Product').addClass('btn-warning');
$('#heading').text('Edit Product');
editing = true;
},
error:function(err){
console.log(err);
console.log('something went wrong with getting the single product');
}
})
});
// Remove a product
$('#productList').on('click', '.removeBtn', function(){
event.preventDefault();
const id = $(this).parent().parent().data('id');
const li = $(this).parent().parent();
$.ajax({
url: `${url}/product/${id}`,
type: 'DELETE',
success:function(result){
li.remove();
},
error:function(err) {
console.log(err);
console.log('something went wrong deleting the product');
}
})
});
// Switch to login form
$('#loginTabBtn').click(function(){
event.preventDefault();
$('.nav-link').removeClass('active');
$(this).addClass('active');
$('#loginForm').show();
$('#registerForm').hide();
});
// Switch to register form
$('#registerTabBtn').click(function(){
event.preventDefault();
$('.nav-link').removeClass('active');
$(this).addClass('active');
$('#loginForm').hide();
$('#registerForm').removeClass('d-none').show();
});
// Verifying register form, request to /users
$('#registerForm').submit(function(){
event.preventDefault();
const username = $('#rUsername').val();
const email = $('#rEmail').val();
const password = $('#<PASSWORD>').val();
const confirmPassword = $('#rConfirmPassword').val();
if (username.length === 0) {
console.log('Please enter Username');
} else if (email.length === 0) {
console.log('Please enter Email');
} else if (password.length === 0) {
console.log('Please enter Password');
} else if (confirmPassword.length === 0) {
console.log('Please enter Confirmed Password');
} else if (password !== confirmPassword) {
console.log('Passwords do not match');
} else {
$.ajax({
url: `${url}/users`,
type: 'POST',
data: {
username: username,
email: email,
password: <PASSWORD>,
},
success: function(result){
console.log(result);
},
error: function(err){
console.log(err);
console.log('something wrong wit request to users');
},
})
}
});
$(document).ready(function(){
$('#authForm').modal('show');
});
<file_sep>/mongoDBServer/server.js
const express = require('express');
const app = express();
const port = 3000;
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
// Require the config file
const config = require('./config.json');
// Get the Model for our Product
const Product = require('./models/products');
const User = require('./models/users');
// Connect to Mongoose
mongoose.connect(`mongodb+srv://RissCasey:${config.MONGO_PASSWORD}@<EMAIL>/shop?retryWrites=true&w=majority`, {useNewUrlParser: true});
// Test the connection to mongoose
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('we are connected to mongo db');
});
// Convert our json data which gets sent into JS so we can process it
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
// Allow Cross Origin requests, ie http to https requests
app.use(cors());
// Create a console message showing us what request we are asking for
app.use(function(req, res, next){
console.log(`${req.method} request for ${req.url}`);
next();
});
//Home Route
app.get('/', function(req, res){
res.send('Welcome to our Products API. Use endpoints to filter out the data');
});
//Add a new Product
app.post('/product', function(req, res){
const product = new Product({
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
price: req.body.price
});
product.save().then(result => {
res.send(result);
}).catch(err => res.send(err));
});
// Get all Products
app.get('/allProducts', function(req, res){
Product.find().then(result => {
res.send(result);
})
})
//Get single Product based on ID
app.get('/product/:id', function(req, res){
const id = req.params.id;
Product.findById(id, function (err, product) {
res.send(product);
});
});
// Update a product based on id
app.patch('/product/:id', function(req, res){
const id = req.params.id;
const newProduct = {
name: req.body.name,
price: req.body.price
};
Product.updateOne({ _id : id }, newProduct).then(result => {
res.send(result);
}).catch(err => res.send(err));
})
// Delete a product based on id
app.delete('/product/:id', function(req, res){
const id = req.params.id;
Product.deleteOne({ _id: id }, function (err) {
res.send('deleted');
});
});
// Posting user registration information
app.post('/users', function(req, res){
var hash = bcrypt.hashSync(req.body.password);
const user = new User({
_id: new mongoose.Types.ObjectId(),
username: req.body.username,
email: req.body.email,
password: <PASSWORD>,
});
user.save().then(result => {
res.send(result);
}).catch(err => res.send(err));
let username = req.params.username;
User.findOne({username: username}, function (err, adventure) {
res.send(username);
console.log('found one');
});
});
// app.post('/getUser', function(req,res){
// let username = req.params.username;
// User.findOne({username: username}, function (err, adventure) {
// res.send(username);
// console.log('found one');
// });
// });
// Listen to the port number
app.listen(port, () => {
console.log(`application is running on port ${port}`)
});
|
4115a8ca0ec78277bc7b3efee39dcc08352d2794
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
risscasey/MongoStack
|
ae3d727d3a5fef4246bb2e30ddec08b7a2372459
|
4afb12f7be4a159523afd0ac71ce34b5a89b4d87
|
refs/heads/master
|
<file_sep>var passport = require('passport'),
AuthConfig = require('../etc/auth.js'),
FacebookStrategy = require('passport-facebook').Strategy,
TwitterStrategy = require('passport-twitter').Strategy,
LocalStrategy = require('passport-local').Strategy,
User = require('../models/user'),
AuthConfig = require('../etc/auth.js'),
crypto = require('crypto')
// TODO: This file needs to be refactored using promises
passport.serializeUser(function(user, done)
{
done(null, user.id)
})
passport.deserializeUser(function(id, done)
{
User.findById(id, function(err, user)
{
done(err, user)
})
})
// Facebook
passport.use(new FacebookStrategy(
{
clientID: AuthConfig.facebook.clientID,
clientSecret: AuthConfig.facebook.clientSecret,
callbackURL: AuthConfig.facebook.callbackURL,
enableProof: false,
passReqToCallback: true
},
function(req, accessToken, refreshToken, profile, done)
{
var new_user =
{
gender: profile.gender,
name: profile.name,
tokens:
{
facebook:
{
accessToken: accessToken,
refreshToken: refreshToken
}
}
}
if (profile.emails[0] != 'undefined' && profile.emails[0].value != 'undefined')
{
new_user['email'] = profile.emails[0].value
// Don't check the current user or linking accounts will throw the dup error
var where =
{
email: new_user['email']
}
if (req.user != undefined)
{
where['_id'] =
{
'$ne': req.user._id
}
}
User.findOne(where, function(err, user)
{
if (user)
{
req.flash('error', 'You already have an account registered using this email address. Accounts are not mergable you need to delete it and than link it via settings page')
}
})
}
// User exists link accounts
if (req.user)
{
User.findById(req.user._id, function(err, user)
{
var where =
{
_id: req.user._id
}
var update =
{
'$set':
{
'tokens.facebook':
{
accessToken: accessToken,
refreshToken: refreshToken
},
facebook_uid: profile.id
}
}
User.findOneAndUpdate(where, update, function(update_err, update_user)
{
return done(update_err, update_user)
})
})
}
else
{
User.findOrCreate({ facebook_uid: profile.id }, new_user, function(err, new_user)
{
// Facebook no longer returns the username so don't do the update like twitter
return done(err, new_user)
})
}
}))
// Twitter
passport.use(new TwitterStrategy(
{
consumerKey: AuthConfig.twitter.consumerKey,
consumerSecret: AuthConfig.twitter.consumerSecret,
callbackURL: AuthConfig.twitter.callbackURL,
passReqToCallback: true
},
function(req, token, tokenSecret, profile, done)
{
var new_user =
{
name: profile.name,
tokens:
{
twitter:
{
token: token,
tokenSecret: tokenSecret
}
}
}
// User exists link accounts
if (req.user)
{
log.info('User exists linking twitter account')
User.findById(req.user._id, function(err, user)
{
var where =
{
_id: req.user._id
}
var update =
{
'$set':
{
'tokens.twitter':
{
token: token,
tokenSecret: tokenSecret
},
twitter_uid: profile.id
}
}
User.findOneAndUpdate(where, update, function(update_err, update_user)
{
return done(update_err, user)
})
})
}
else
{
log.info('User does NOT exist, creating new account')
User.findOrCreate({ twitter_uid: profile.id }, new_user, function(err, user)
{
// Search for this username, if we find a duplicate do nothing
// If the username doesn't exist, update the new user to it
var where =
{
username: profile.username
}
User.findOne(where, function(err, dup_username)
{
if (! err && ! dup_username)
{
log.info('Username not found, updating user')
var where =
{
_id: user._id
}
var update =
{
'$set':
{
username: profile.username
}
}
User.findOneAndUpdate(where, update, function(update_err, update_user)
{
return done(update_err, update_user)
})
}
else
{
log.info('Username is taken by another user, skipping update')
return done(err, user)
}
})
})
}
}))
// Local
passport.use(new LocalStrategy(
{
usernameField: 'email',
passReqToCallback: true
},
function(req, email, password, done)
{
User.findOne({ email: email }, function(err, user)
{
if (err)
{
return done(err)
}
if (! user)
{
return done(null, false, { message: 'Incorrect login' })
}
user.validPassword(password, function(err, valid)
{
if (err || ! valid)
{
return done(null, false, { message: 'Incorrect login' })
}
else
{
return done(null, user)
}
})
})
}))
module.exports =
{
// TODO: Should this be a different file ?
send_forgot_password: function(forgotpassword, cb)
{
var SMTPConfig = require('../etc/smtp')
// This makes it much harder for someone to brute force password resets just based on ObjectId()
var shasum = crypto.createHash('sha1')
shasum.update(forgotpassword._id + AuthConfig.forgot_password_secret)
// TODO: Domain needs to be config
var change_url = 'http://jengo-node-boilerplate.joped.com:3000/auth/reset/' + forgotpassword._id + '/' + shasum.digest('hex')
var transporter = nodemailer.createTransport(
{
service: SMTPConfig.service,
auth:
{
user: SMTPConfig.auth.user,
pass: <PASSWORD>.auth.<PASSWORD>
}
})
transporter.sendMail(
{
from: SMTPConfig.from,
to: forgotpassword.email,
subject: features.site_title + ' Password reset',
text: 'Change your password at ' + change_url
},
function(err, info)
{
if (err)
{
log.error('SMTP failure send_forgot_password', err)
}
cb()
})
}
}
<file_sep>var features = require('../etc/features'),
bunyan = require('bunyan')
var options =
{
name: features.site_title
}
var log = bunyan.createLogger(options)
module.exports = log
<file_sep>var express = require('express')
router = express.Router(),
User = require('../../models/user'),
ForgotPassword = require('../../models/forgotpassword'),
validator = require('express-validator')
router.post('/auth/reset', function(req, res)
{
req.checkBody('email', 'Email is required').notEmpty()
req.checkBody('email', 'Email is not valid').isEmail()
User.findOne({email: req.body.email}, function(err, user)
{
if (! user)
{
req.flash('error', 'Email address not found')
return res.redirect('/auth/reset')
}
// Simple error reporting, I might expand on this in the future
var errors = req.validationErrors()
if (errors)
{
for (e in errors)
{
req.flash('error', errors[e].msg)
}
res.redirect('/auth/reset')
}
else
{
forgotpassword = new ForgotPassword()
forgotpassword.user_id = user._id
forgotpassword.email = user.email
forgotpassword.save(function(err, result)
{
if (err)
{
req.flash('error', 'Error sending confirmation email')
}
else
{
req.flash('success', 'Confirmation email has been sent')
}
res.redirect('/auth/reset')
})
}
})
})
module.exports = router
<file_sep># jengo-node-boilerplate
This project is a very early work in progress. Much of it doesn't work yet or hasn't been implemented. The goal of this project is to include a boilerplate that includes the following libraries.
- Express
- Mongoose
- Passport
- Bootstrap
- Google Analytics
- ejs
- Swagger
- Swagger UI
- Bunyan
## Features
Features that have been implemented
- User authentication with facebook, twitter and local
- Link social authentication with single account
- Unlinking social authentication from an account
- Delete own account
- Forgot password (disabled by default, requires SMTP setup)
- Simple disable feature set to quickly start integrating your site
- Static controller, fast creation of static pages that fit in your layout
- Public profile page for users
## Installation
```
npm install
node bin/www | node_modules/bunyan/bin/bunyan -o simple
```
Point your browser to http://jengo-node-boilerplate.joped.com:3000/ which is an A record to 127.0.0.1 This was done because twitter wouldn't allow me to create an app that pointed to localhost.
You can access the swaggger UI at http://jengo-node-boilerplate.joped.com:3000/swagger-ui/
## Getting started with customization
The first thing you should do with customizing this boilerplate is to change the social auth credentials. The ones provided are strictly for evaluation and demoing the boilerplate.
Next you will want to modify the etc/features.js config to disable features you don't need. This speeds up customization by not requiring you to start gutting code on day one.
After that you will want to update etc/mongodb.js to customize the database name.
It's important to note this project is a boilerplate not a framework. Once you start customizing there are no upgrades to future versions.
## Licensing
Currently the my code is released under MIT License, which is subject to change.
3rd party libraries that are included are under:
- Swagger UI (Apache license)
- Bootstrap (MIT License)
- Snipits from https://github.com/sahat/hackathon-starter (MIT License)
<file_sep>var express = require('express')
router = express.Router(),
User = require('../../models/user')
router.post('/auth/delete', function(req, res)
{
User.remove({_id: req.user._id}, function(err)
{
req.logout()
req.flash('info', 'Account has been deleted')
res.redirect('/')
})
})
module.exports = router
<file_sep>var mongoose = require('mongoose')
findOrCreate = require('mongoose-findorcreate'),
bcrypt = require('bcrypt-nodejs'),
crypto = require('crypto'),
nodemailer = require('nodemailer')
var userSchema = mongoose.Schema(
{
username:
{
type: String,
unique : true
},
facebook_uid: String,
twitter_uid: String,
email: String,
email_confirmed:
{
type: Boolean,
default: false
},
name:
{
displayName: String,
familyName: String,
givenName: String,
middleName: String
},
gender: String,
timezone: Number,
locale: String,
password: String,
tokens: {},
created_on:
{
type: Date,
default: Date.now
}
},
{
collection: 'user'
})
var swagger_def =
{
'models':
{
'User':
{
id: 'User',
properties:
{
_id:
{
type: 'string',
description: 'User ID',
minimum: 25,
maximum: 25
},
username:
{
type: 'string',
description: 'Username'
},
facebook_uid:
{
type: 'number',
description: 'Facebook User ID'
},
twitter_uid:
{
type: 'number',
description: 'Twitter User ID'
},
email:
{
type: 'string',
description: 'Email address'
},
email_confirmed:
{
type: 'boolean',
description: 'Email address confirmed'
},
gender:
{
type: 'string',
description: 'Gender'
},
// TODO: name and tokens is missing
timezone:
{
type: 'number',
description: 'Timezone'
},
locale:
{
type: 'string',
description: 'Locale'
},
password:
{
type: 'string',
description: 'Hashed password of user, when creating set as plain text and .save() will handle hashing'
},
created_on:
{
type: 'dateTime'
}
}
}
}
}
userSchema.plugin(findOrCreate)
userSchema.pre('save', function(next)
{
var user = this
if (! user.isModified('password'))
{
return next()
}
bcrypt.genSalt(5, function(err, salt)
{
if (err)
{
return next(err)
}
bcrypt.hash(user.password, salt, null, function(err, hash)
{
if (err)
{
return next(err)
}
user.password = <PASSWORD>
next()
})
})
})
userSchema.virtual('gravatar_url').get(function()
{
var md5sum = crypto.createHash('md5')
var md5 = '00000000000000000000000000000000'
if (this.email)
{
md5sum.update(this.email)
md5 = md5sum.digest('hex')
}
return 'http://www.gravatar.com/avatar/' + md5
})
// This is different from name.displayName
// Each provider returns different values for different users
userSchema.virtual('displayName').get(function()
{
if (this.name.displayName)
{
return this.name.displayName
}
else if (this.name.givenName || this.name.familyName)
{
var name = []
if (this.name.givenName)
{
name.push(this.name.givenName)
}
if (this.name.middleName)
{
name.push(this.name.middleName)
}
if (this.name.familyName)
{
name.push(this.name.familyName)
}
return name.join(' ')
}
else if (this.name.username)
{
return this.name.username
}
})
userSchema.methods.validPassword = function(password, cb)
{
bcrypt.compare(password, this.password, function(err, valid)
{
if (err)
{
return cb(err)
}
cb(null, valid)
})
}
module.exports = mongoose.model('user', userSchema)
module.exports.swagger_def = swagger_def
<file_sep>module.exports =
{
url: 'mongodb://localhost/jengo-node-boilerplate'
}
<file_sep>// These are sample configs, you should NOT use this for anything real!!
module.exports =
{
session_secret: 'jengo-node-boilerplate <PASSWORD>!',
forgot_password_expires: 86400,
forgot_password_secret: '<PASSWORD>!!',
facebook:
{
clientID: 630753057026401,
clientSecret: '<KEY>',
callbackURL: 'http://jengo-node-boilerplate.joped.com:3000/auth/facebook/callback'
},
twitter:
{
consumerKey: 'igIeaKmq4KCvJvUltNe3eJn6T',
consumerSecret: '<KEY>',
callbackURL: 'http://jengo-node-boilerplate.joped.com:3000/auth/twitter/callback'
}
}
<file_sep>var express = require('express')
router = express.Router(),
swagger = require("swagger-node-express"),
User = require('../../../models/user')
module.exports.spec =
{
description: 'Get user by id',
path: '/api/v1/user/{user_id}',
method: 'GET',
parameters:
[
swagger.pathParam('user_id', 'user_id', 'string')
],
responseMessages:
[
swagger.errors.invalid('id'),
swagger.errors.notFound('user')
],
produces : ['application/json'],
type: 'User',
nickname: 'user_get_id'
}
module.exports.action = function(req, res)
{
User.findById(req.params.user_id, function(err, user)
{
if (err)
{
res.status(400)
res.send('invalid id')
}
else if (! user)
{
res.status(404)
res.send('user not found')
}
else
{
res.status(200)
res.send(user)
}
})
}
<file_sep>var mongoose = require('mongoose'),
AuthConfig = require('../etc/auth'),
LibAuth = require('../lib/auth')
var forgotPasswordSchema = mongoose.Schema(
{
user_id: String,
email: String,
used:
{
type: Boolean,
default: false
},
expires_on:
{
type: Date,
default: new Date(new Date().getTime() + AuthConfig.forgot_password_expires * 1000)
},
created_on:
{
type: Date,
default: Date.now
}
},
{
collection: 'forgotpassword'
})
forgotPasswordSchema.pre('save', function(next)
{
LibAuth.send_forgot_password(this, function()
{
next()
})
})
var forgotpassword = mongoose.model('forgotpassword', forgotPasswordSchema)
module.exports = forgotpassword
<file_sep>var express = require('express')
router = express.Router(),
User = require('../../models/user'),
validator = require('express-validator')
router.post('/signup', function(req, res, next)
{
req.checkBody('username', 'Username is required').notEmpty()
req.checkBody('email', 'Email is required').notEmpty()
req.checkBody('email', 'Email is not valid').isEmail()
req.checkBody('password', '<PASSWORD>').notEmpty()
req.checkBody('password', 'Password must be at least 5 characters').isLength(5)
req.checkBody('password', 'Passwords do not match').equals(req.body.confirmpassword)
req.checkBody('accept_agrement', 'You must accept the user agreement').notEmpty()
User.findOne({email: req.body.email}, function(err, user)
{
if (user)
{
req.flash('error', 'Email address is already in use')
}
// Simple error reporting, I might expand on this in the future
var errors = req.validationErrors()
if (errors)
{
for (e in errors)
{
req.flash('error', errors[e].msg)
}
res.render('signup', {form: req.body})
}
else
{
user = new User()
user.username = req.body.username
user.name.givenName = req.body.givenName
user.name.familyName = req.body.familyName
user.email = req.body.email
user.password = <PASSWORD>
user.save(function(err)
{
if (err)
{
req.flash('error', 'Error creating user')
}
else
{
req.login(user, function(err)
{
if (err)
{
return next(err)
}
return res.redirect('/')
})
}
})
}
})
})
module.exports = router
<file_sep>var express = require('express')
router = express.Router(),
User = require('../../models/user')
router.post('/auth/unlink/:provider', function(req, res)
{
User.findById(req.user._id, function(err, user)
{
// TODO: refactor, this was quick code
if (req.params.provider == "twitter")
{
var where =
{
_id: req.user._id
}
var update =
{
'$unset':
{
'tokens.twitter': 1
},
'$set':
{
twitter_uid: null
}
}
User.update(where, update, function(update_err, user)
{
if (update_err)
{
req.flash('error', 'Error unlinking Twitter account')
}
else
{
req.flash('success', 'Twitter account unlinked')
}
res.redirect('/settings')
})
}
else if (req.params.provider == "facebook")
{
var where =
{
_id: req.user._id
}
var update =
{
'$unset':
{
'tokens.facebook': 1
},
'$set':
{
facebook_uid: null
}
}
User.update(where, update, function(update_err, user)
{
if (update_err)
{
req.flash('error', 'Error unlinking Facebook account')
}
else
{
req.flash('success', 'Facebook account unlinked')
}
res.redirect('/settings')
})
}
})
})
module.exports = router
<file_sep>var express = require('express')
router = express.Router(),
marked = require('marked'),
fs = require('fs')
router.get('/about', function(req, res)
{
fs.readFile('./README.md', 'utf-8', function (err, data)
{
res.render('about/index',
{
README: marked(data)
})
})
})
module.exports = router
<file_sep>var express = require('express'),
router = express.Router(),
path = require('path'),
favicon = require('serve-favicon'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
swagger = require("swagger-node-express"),
expressLayouts = require('express-ejs-layouts'),
passport = require('passport'),
flash = require('express-flash'),
auth = require('./routes/auth'),
session = require('express-session'),
MongoStore = require('connect-mongo')(session)
MongoDBConfig = require('./etc/mongodb'),
AuthConfig = require('./etc/auth'),
features = require('./etc/features'),
validator = require('express-validator'),
log = require('./lib/log')
var app = express()
require('./lib/auth')
// TODO: Create config file
var db = mongoose.connection;
mongoose.connect(MongoDBConfig.url, {db:{fsync: true}})
app.use(expressLayouts)
// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(require('express-bunyan-logger')())
app.use(require('express-bunyan-logger').errorLogger())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(session({
resave: true,
saveUninitialized: true,
secret: AuthConfig.session_secret,
store: new MongoStore(
{
url: MongoDBConfig.url,
autoReconnect: true,
collection: 'session'
})
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(flash())
app.use(validator([]));
app.use(function(req, res, next)
{
res.locals.user = req.user;
res.locals.features = features;
next();
})
app.use(express.static(__dirname + '/public'))
var swagger = require('swagger-node-express').createNew(app)
swagger.addModels(require('./models/user').swagger_def)
app.use('/', require('./routes/index'))
app.get('/about', require('./routes/about'))
if (features.enable_static_controller)
{
app.get('/static/:page', require('./routes/static'))
}
app.get('/profile/:search', require('./routes/profile'))
app.get('/settings', require('./routes/settings'))
// Authentication routes
app.get('/login', require('./routes/login'))
app.get('/logout', require('./routes/logout'))
app.get('/auth/reset', require('./routes/auth/reset'))
app.post('/auth/reset', require('./routes/auth/reset_post'))
app.get('/auth/reset/:id/:sig', require('./routes/auth/reset_id'))
app.post('/auth/reset/:id/:sig', require('./routes/auth/reset_id'))
app.post('/auth/delete', require('./routes/auth/delete_post'))
app.post('/auth/unlink/:provider', require('./routes/auth/unlink'))
app.get('/signup', require('./routes/signup'))
app.post('/signup', require('./routes/signup/post'))
// Facebook
app.get('/auth/facebook', passport.authenticate('facebook', { scope: ['email', 'user_location'] }))
app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), function(req, res)
{
res.redirect(req.session.returnTo || '/')
})
// Twitter
app.get('/auth/twitter', passport.authenticate('twitter'))
app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), function(req, res)
{
res.redirect(req.session.returnTo || '/')
})
// Local
app.post('/auth/local', passport.authenticate('local',
{
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
})
)
swagger.addGet(require('./routes/api/user/get_id'))
swagger.configureSwaggerPaths("", "/api-docs", "")
swagger.configure('http://jengo-node-boilerplate.joped.com:3000/', '0.0.1');
app.use(router);
// catch 404 and forward to error handler
app.use(function(req, res, next)
{
var err = new Error('Not Found')
err.status = 404
next(err)
})
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development')
{
app.use(function(err, req, res, next)
{
res.status(err.status || 500)
res.render('error',
{
message: err.message,
error: err
})
})
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next)
{
res.status(err.status || 500)
res.render('error',
{
message: err.message,
error: {}
})
})
module.exports = app
<file_sep>var express = require('express')
router = express.Router(),
fs = require('fs')
router.get('/static/:page', function(req, res)
{
fs.exists('./views/static/' + req.params.page + '.ejs', function(exists)
{
if (exists)
{
res.render('static/' + req.params.page)
}
else
{
var param =
{
error:
{
status: 404
},
message: 'Not found'
}
res.status(404)
res.render('error', param)
}
})
})
module.exports = router
|
68a51d7aadbf96bbdf7c4bebba389e6b2aeefc6c
|
[
"JavaScript",
"Markdown"
] | 15
|
JavaScript
|
jengo/jengo-node-boilerplate
|
fb312d377493cec5f9b2b51ecaa092053ca91796
|
e96dac3291abfb12d30ff1059e22c329678d201f
|
refs/heads/master
|
<file_sep># blueplanet-screencapture
Executes screen captures of a Blue Planet UI
Usage:
```bash
go install github.com/jgroom33/blueplanet-screencapture
~/go/bin/blueplanet-screencapture -path=https://10.182.18.132/orchestrate/#/list/resource-types -element=.main-body -file=foo.png
```
## Options
-element - https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
-file - filename to save
<file_sep>// Command screenshot is a chromedp example demonstrating how to take a
// screenshot of a specific element and of the entire browser viewport.
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"time"
"github.com/chromedp/cdproto/emulation"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
)
func RunWithTimeOut(ctx *context.Context, timeout time.Duration, tasks chromedp.Tasks) chromedp.ActionFunc {
return func(ctx context.Context) error {
timeoutContext, cancel := context.WithTimeout(ctx, timeout*time.Second)
defer cancel()
return tasks.Do(timeoutContext)
}
}
func main() {
// get flags
pathPtr := flag.String("path", "http://localhost:9980/", "url")
elementPtr := flag.String("element", ".main-body", "class to wait for and then capture")
filePtr := flag.String("file", "screenshot.png", "save as filename")
flag.Parse()
// ignore unsigned certs
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.Flag("ignore-certificate-errors", "1"),
chromedp.Flag("headless", true),
)
// create context
allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
defer cancel()
ctx, cancel := chromedp.NewContext(allocCtx, chromedp.WithLogf(log.Printf))
defer cancel()
var buf []byte
// capture entire browser viewport, returning png with quality=90
if err := chromedp.Run(ctx, RunWithTimeOut(&ctx, 30, fullScreenshot(*pathPtr, *elementPtr, 90, &buf))); err != nil {
log.Fatal(err)
}
if err := ioutil.WriteFile(*filePtr, buf, 0644); err != nil {
log.Fatal(err)
}
}
// fullScreenshot takes a screenshot of the entire browser viewport.
//
// Liberally copied from puppeteer's source.
//
// Note: this will override the viewport emulation settings.
func fullScreenshot(urlstr string, sel string, quality int64, res *[]byte) chromedp.Tasks {
if strings.Contains(urlstr, "https") {
return chromedp.Tasks{
chromedp.Navigate(urlstr),
chromedp.WaitVisible(`input[type='text']`, chromedp.ByQuery),
chromedp.SendKeys(`input[type='text']`, "<PASSWORD>", chromedp.ByQuery),
chromedp.WaitVisible(`input[type='password']`, chromedp.ByQuery),
chromedp.SendKeys(`input[type='password']`, "<PASSWORD>", chromedp.ByQuery),
chromedp.WaitVisible(sel, chromedp.ByQuery),
chromedp.Sleep(2 * time.Second),
chromedp.ActionFunc(func(ctx context.Context) error {
// get layout metrics
_, _, contentSize, err := page.GetLayoutMetrics().Do(ctx)
if err != nil {
return err
}
width, height := int64(1280), int64(720)
// force viewport emulation
err = emulation.SetDeviceMetricsOverride(width, height, 1, false).
WithScreenOrientation(&emulation.ScreenOrientation{
Type: emulation.OrientationTypePortraitPrimary,
Angle: 0,
}).
Do(ctx)
if err != nil {
return err
}
// capture screenshot
*res, err = page.CaptureScreenshot().
WithQuality(quality).
WithClip(&page.Viewport{
X: contentSize.X,
Y: contentSize.Y,
Width: 1280,
Height: 720,
Scale: 1,
}).Do(ctx)
if err != nil {
return err
}
return nil
}),
}
} else {
return chromedp.Tasks{
chromedp.Navigate(urlstr),
chromedp.WaitVisible(sel, chromedp.ByQuery),
chromedp.Sleep(2 * time.Second),
chromedp.ActionFunc(func(ctx context.Context) error {
// get layout metrics
_, _, contentSize, err := page.GetLayoutMetrics().Do(ctx)
if err != nil {
return err
}
width, height := int64(1280), int64(720)
// force viewport emulation
err = emulation.SetDeviceMetricsOverride(width, height, 1, false).
WithScreenOrientation(&emulation.ScreenOrientation{
Type: emulation.OrientationTypePortraitPrimary,
Angle: 0,
}).
Do(ctx)
if err != nil {
return err
}
// capture screenshot
*res, err = page.CaptureScreenshot().
WithQuality(quality).
WithClip(&page.Viewport{
X: contentSize.X,
Y: contentSize.Y,
Width: 1280,
Height: 720,
Scale: 1,
}).Do(ctx)
if err != nil {
return err
}
return nil
}),
}
}
}
func getValues() string {
// Social struct which contains a
// list of links
type AnsibleOutput struct {
Bp_integration_tests_token string `json:"bp_integration_tests_token"`
}
// Open our jsonFile
jsonFile, err := os.Open("localhost")
// if we os.Open returns an error then handle it
if err != nil {
fmt.Println(err)
}
fmt.Println("Successfully Opened localhost")
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
var result AnsibleOutput
// var result map[string]interface{}
json.Unmarshal([]byte(byteValue), &result)
fmt.Println(result.Bp_integration_tests_token)
return result.Bp_integration_tests_token
}
|
228ccf63af06bffe18693fe6fc8a77c516504aca
|
[
"Markdown",
"Go"
] | 2
|
Markdown
|
jgroom33/blueplanet-screencapture
|
2e02c9af4ac0c6122124173256d8e5c4d1a028fd
|
8f0eae3173ecc92bdef6f2c8a10a7fdf1d2adee2
|
refs/heads/main
|
<file_sep>$(document).ready(function(){
$("#search").click(function(){
$("#search").css('outline','none') ;
});
|
cbf1bdfdabfa804834801c9b5800700fc6b48c49
|
[
"JavaScript"
] | 1
|
JavaScript
|
rahulsingh0-0/frontendsite4
|
b6644f98251e6debf4a623543db168ae1afdd64e
|
20a08f0b52000c3de09cf7fc47da5a0a820f07c6
|
refs/heads/master
|
<file_sep># nb-quick-upload
Upload Jupyter notebooks as gists quickly and easily. And if you don't want to upload the entire thing? NO PROBLEM. Just upload a few cells!
```bash
git clone https://github.com/jsoma/nb-quick-upload.git
jupyter nbextension install nb-quick-upload --user
jupyter nbextension enable nb-quick-upload/main
```
When you're in your notebooks you'll have a brand-new icon, a little generic cloud-upload thingy. Use it to get rolling with your uploading.<file_sep>[ ] save your gist URLs
[ ] popup to ask for details
[ ] list previous gist URLs
[ ] menu item
[ ] shortcut keys<file_sep>define(['require',
'base/js/namespace',
'base/js/events',
'components/backbone/backbone-min'
], function(require, Jupyter, Events, Backbone) {
var cell_ids = [];
var button;
var popover;
var submission_text;
var submission_template = _.template('' +
'<form class="quickupload-submission">' +
'<div class="form-group">' +
'<textarea name="quickupload-desc" class="form-control" rows="3" placeholder="Write a description to be posted along with your code"></textarea>' +
'</div>' +
'<div class="quickupload-submit">' +
'<% if (cell_ids.length === 0) { %>' +
'<span class="label selected-cells label-default">Click cells to only upload selection</span>' +
'<input type="submit" class="btn btn-primary" value="Create gist">' +
'<% } else { %>' +
'<span class="label selected-cells label-info"><%= cell_ids.length %> cells selected</span>' +
'<input type="submit" class="btn btn-warning" value="Create gist">' +
'<% } %>' +
'</div>' +
'</form>')
var post_save_template = _.template('<p><a class="btn btn-info" href="<%= url %>" target="_blank">View on GitHub</a></p>')
function set_popover_content (content) {
var closer = $('<button type="button" class="close quickupload-close">' +
'<span aria-hidden="true">×</span></button>' +
'</span>')
.click(cleanup);
if(!popover || !popover.is(":visible")) {
button.popover('show')
popover = button.data("bs.popover").$tip
popover.find(".popover-title").append(closer)
}
popover.find(".popover-content").html(content)
}
function ask_for_details () {
if(popover) {
submission_text = popover.find('textarea').val()
}
var content = $(submission_template({ cell_ids: cell_ids }));
set_popover_content(content)
popover.find('textarea').val(submission_text)
content.find('textarea')
.on('focus', function () {
if (Jupyter.notebook.keyboard_manager) {
Jupyter.notebook.keyboard_manager.disable()
}
})
.on('blur', function () {
if (Jupyter.notebook.keyboard_manager) {
Jupyter.notebook.keyboard_manager.enable()
}
})
.on('keydown', function () {
submission_text = $(this).val()
})
content.submit(function() {
set_popover_content("<p><i class='fa fa-circle-o-notch fa-spin'></i> Saving...</p>")
submit();
cell_ids = [];
return false;
})
}
function fake_notebook () {
var notebook = Jupyter.notebook;
// remove the conversion indicator, which only belongs in-memory
delete notebook.metadata.orig_nbformat;
delete notebook.metadata.orig_nbformat_minor;
var cells = notebook.get_cells().filter(function(cell) {
return cell_ids.length === 0 ? true : cell_ids.indexOf(cell.cell_id) != -1
});
var ncells = cells.length;
var cell_array = cells.map(function(cell) {
return cell.toJSON(true)
})
var data = {
cells: cell_array,
metadata: notebook.metadata,
nbformat: notebook.nbformat,
nbformat_minor: notebook.nbformat_minor
};
return data;
}
function cell_selected (e, target) {
var element = $(target.cell.element).toggleClass("quickupload-selected")
var id = target.cell.cell_id;
if(element.hasClass("quickupload-selected")) {
cell_ids.push(id);
} else {
var index = cell_ids.indexOf(id);
if (index > -1) {
cell_ids.splice(index, 1);
}
}
ask_for_details();
}
function cleanup () {
button.popover('hide')
$(".quickupload-selected").removeClass("quickupload-selected")
cell_ids = [];
Events.off('select.Cell', cell_selected)
}
function start () {
ask_for_details();
cell_ids = [];
Events.on('select.Cell', cell_selected)
}
function submit () {
var fakebook = fake_notebook();
var data = {
'description': 'Uploaded from a Jupyter Notebook with with NB Quick Upload',
'public': false,
'files': {
'notebook.ipynb': {
'content': JSON.stringify(fakebook)
}
}
}
if(submission_text && submission_text != "") {
data['files']['README.md'] = { 'content': submission_text }
}
submission_text = "";
jQuery.ajax ({
url: "https://api.github.com/gists",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(result){
var content = post_save_template({ url:result.html_url })
set_popover_content(content)
}
});
}
function add_start_handler () {
var action = {
icon: 'fa-cloud-upload', // a font-awesome class used on buttons, etc
help : 'Show an alert',
help_index : 'zz',
handler : start
};
var full_action_name = Jupyter.actions.register(action, 'start-selecting', 'quickupload'); // returns 'my_extension:show-alert'
button = Jupyter.toolbar.add_buttons_group([full_action_name]);
button.popover({
placement: 'bottom',
html: true,
trigger: 'manual',
content: "<p>Sample content</p>",
title: "Quick upload"
})
document.button = button
}
function load_ipython_extension () {
load_css('./style.css')
add_start_handler();
}
function load_css (name) {
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = require.toUrl(name);
document.getElementsByTagName("head")[0].appendChild(link);
};
return {
load_ipython_extension: load_ipython_extension
};
});
|
6858c69b8d29d4c2fac5a6d4965a8661882905bb
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
jsoma/nb-quick-upload
|
93c3b6d0ad4749e6f89c1c40ee9732632970e062
|
5ec3623298436606bd417475f8418fe222bafd73
|
refs/heads/master
|
<file_sep><?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class UserController extends AbstractActionController
{
protected $_objectManager;
public function listAction()
{
$fieldsToOrder = array('id', 'email');
$order_by = $this->params()->fromRoute('order_by') ?
$this->params()->fromRoute('order_by') : 'id';
$order = $this->params()->fromRoute('order') ?
$this->params()->fromRoute('order') : 'ASC';
$users = $this->getServiceLocator()->get('entity_manager')
->getRepository('Application\Entity\User')
->findBy(array(), array($order_by => $order));
$sorting = array();
foreach($fieldsToOrder as $key=>$value)
{
$ord = 'ASC';
if($order_by == $value && $order == 'ASC')
{
$ord = 'DESC';
}
$sorting[$value] = $ord;
}
return new ViewModel(array(
'users' => $users,
'sorting' => $sorting
));
}
public function addAction()
{
/* @var $form \Application\Form\UserForm */
$form = $this->getServiceLocator()->get('formElementManager')->get('form.user');
$data = $this->prg();
if ($data instanceof \Zend\Http\PhpEnvironment\Response) {
return $data;
}
if ($data != false) {
$form->setData($data);
if ($form->isValid()) {
/* @var $user \Application\Entity\User */
$user = $form->getData();
/* @var $serviceUser \Application\Service\UserService */
$serviceUser = $this->getServiceLocator()->get('application.service.user');
$serviceUser->saveUser($user);
$this->redirect()->toRoute('users');
}
}
return new ViewModel(array(
'form' => $form
));
}
public function removeAction()
{
$id = (int) $this->params()->fromRoute('user_id', 0);
$user = $this->getObjectManager()->find('\Application\Entity\User', $id);
if ($this->request->isPost()) {
$this->getObjectManager()->remove($user);
$this->getObjectManager()->flush();
return $this->redirect()->toRoute('users');
}
return new ViewModel(array(
'user' => $user
));
}
public function editAction()
{
$form = $this->getServiceLocator()->get('formElementManager')->get('form.user');
$userToEdit = $this->getServiceLocator()->get('entity_manager')
->getRepository('Application\Entity\User')
->find($this->params()->fromRoute('user_id'));
$form->bind($userToEdit);
$form->get('firstname')->setValue($userToEdit->getFirstName());
$form->get('lastname')->setValue($userToEdit->getLastName());
$form->get('birth')->setValue($userToEdit->getBirth());
$data = $this->prg();
if ($data instanceof \Zend\Http\PhpEnvironment\Response) {
return $data;
}
if ($data != false) {
$form->setData($data);
if ($form->isValid()) {
/* @var $user \Application\Entity\User */
$user = $form->getData();
$serviceUser = $this->getServiceLocator()->get('application.service.user');
$serviceUser->saveUser($user);
//Save the user
$this->redirect()->toRoute('users');
}
}
return new ViewModel(array(
'form' => $form
));
}
protected function getObjectManager()
{
if (!$this->_objectManager) {
$this->_objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
}
return $this->_objectManager;
}
}
|
a1472fa8ae1378e5ce0e09efcf385adaf6a568bd
|
[
"PHP"
] | 1
|
PHP
|
rllomun/testtechnique
|
37e2d326f0882483c0974d1cc6ff2db4dd9e40cb
|
d891096f7a3ab64afa929955f810652f06ca18ca
|
refs/heads/master
|
<file_sep>import React from 'react';
import {MovieList} from './Movies';
import {BoatList} from './Boats';
import {
SafeAreaView,
StyleSheet,
ScrollView,
Image,
View,
Text,
StatusBar,
} from 'react-native';
const App: () => React$Node = () => {
return (
<ScrollView>
<View>
<Text>Lesson 05 Exercises</Text>
<View style = {styles.line} />
<MovieList />
<View style = {styles.line} />
<Text style = {styles.boldText}>GetABoat - For Sale{"\n"}</Text>
<BoatList />
</View>
</ScrollView>
);
};
const styles = StyleSheet.create({
boldText: {
color: 'red',
fontWeight: 'bold',
fontSize: 30
},
line:{
borderWidth: 0.5,
borderColor:'black',
}
});
export default App;
|
654d46626142413beaf6d6ac2f43cfc35c022fc3
|
[
"JavaScript"
] | 1
|
JavaScript
|
brandon1804/lesson05
|
b22ec57f3d9348328e80e2fc3fb6d9c979f5a6dc
|
f03948ab46ae9f8e246dcf1c21c0342d16af25c0
|
refs/heads/master
|
<file_sep>import React, { Component } from "react";
import "./App.css";
import contacts from "./contacts.json";
class App extends Component {
state = {
contacts: contacts.slice(0, 5)
};
getRandomActor = () => {
// add random actor
let randomActor = contacts[Math.floor(Math.random() * contacts.length)];
if (!this.state.contacts.includes(randomActor)) {
contacts: this.state.contacts.push(randomActor);
}
this.setState({});
};
filterByName = () => {
// filter by name
let contactsByName = this.state.contacts.sort((a, b) => {
return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
});
this.setState({
contacts: contactsByName
});
};
filterByPopularity = () => {
// filter by popularity
let contactsByPopularity = this.state.contacts.sort((a, b) => {
return b.popularity - a.popularity;
});
this.setState({
contacts: contactsByPopularity
});
};
removeActor = index => {
let contactMinusOne = this.state.contacts;
contactMinusOne.splice(index, 1);
this.setState({
contacts: contactMinusOne
});
};
render() {
return (
<section className="my-section">
<h1>IronContacts</h1>
<p>Totals contacts displayed: {this.state.contacts.length}</p>
<div className="filter-buttons">
<button onClick={this.getRandomActor}>Add random contact</button>
<button onClick={this.filterByName}>Sort by name</button>
<button onClick={this.filterByPopularity}>Sort by popularity</button>
</div>
<table>
<thead>
<tr>
<th>Picture</th>
<th>Name</th>
<th>Popularity</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{this.state.contacts.map((actor, index) => (
<tr>
<td>
<img src={actor.pictureUrl} />
</td>
<td>{actor.name}</td>
<td>{actor.popularity}</td>
<td>
<button onClick={() => this.removeActor(index)}>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</section>
);
}
}
export default App;
|
7c6c6ba41bb9eeb1a6688eea0da133dc7c7b837b
|
[
"JavaScript"
] | 1
|
JavaScript
|
guido-an/lab-react-ironcontacts
|
b9830289da14a863557048260a97f985b7dc1c14
|
102b9c2da6c01693c5377164987c18bc21695f20
|
refs/heads/master
|
<repo_name>PolarFox/heatpump-ui<file_sep>/heatpump.php
<?php
namespace Polaris;
class Heatpump {
const HEATPUMP_URI = 'http://127.0.0.1:8080';
const VARIABLES = [
'hvac_modes'=>[
['value'=>'heat','label'=>'Lämmitys'],
['value'=>'cool','label'=>'Viilennys'],
['value'=>'dry','label'=>'Kuivaus'],
['value'=>'auto','label'=>'Automaatti']
],
'vane_modes'=>[
['value'=>'upend','label'=>'1'],
['value'=>'up','label'=>'2'],
['value'=>'middle','label'=>'3'],
['value'=>'down','label'=>'4'],
['value'=>'downend','label'=>'5'],
['value'=>'auto','label'=>'Automaatti'],
['value'=>'swing','label'=>'Heiluri']
]
];
public function __construct() {
}
public function getStatus() {
try {
return array_merge(json_decode(file_get_contents(self::HEATPUMP_URI.'/api/status'),true),self::VARIABLES);
} catch(\Exception $e) {
throw $e;
}
}
public function setTemperature($temp=20) {
if(!is_int($temp)) {
throw new \Exception('Temperature must be integer.');
}
self::sendSettings(array('temp'=>$temp));
}
public function setMode($mode='heat') {
if($mode=='heat'||$mode=='cool'||$mode=='dry'||$mode=='auto') {
return self::sendSettings(array('hvac_mode'=>$mode));
}
throw new \Exception('Unknown mode');
}
public function setVane($vane=0) {
return self::sendSettings(array('vane'=>$vane));
throw new \Exception('Unknown vane direction');
}
public function setPower($power) {
if($power) {
$power=true;
}
return self::sendSettings(array('on'=>(bool)$power));
}
/**
* Send settings array as a JSON message to heat pump controller.
* @param array $settings
*/
private static function sendSettings($settings) {
$defaults=array('apply'=>true);
$message=json_encode(array_merge($settings,$defaults));
try {
$ch=\curl_init(self::HEATPUMP_URI.'/api/set');
curl_setopt_array($ch,array(
CURLOPT_POST=>true,
CURLOPT_RETURNTRANSFER=>true,
CURLOPT_HTTPHEADER => array(
'Authorization: '.'hips',
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => $message
));
$response = curl_exec($ch);
if($response === false) {
throw \Exception("API call failed.");
}
$responseData = json_decode($response, TRUE);
return $responseData;
} catch(\Exception $e) {
throw $e;
}
}
}
<file_sep>/fingrid.php
<?php
#curl -X GET --header 'Accept: application/json' --header 'x-api-key: <KEY>' 'https://api.fingrid.fi/v1/variable/117/events/json?start_time=2017-03-18T10%3A03%3A14Z&end_time=2017-03-25T10%3A03%3A14Z'
namespace Polaris;
class Fingrid {
const FINGRID_API='https://api.fingrid.fi/v1';
const TASESAHKO=117;
private static $cache;
public function getSevenDayAveragePrice() {
$prices=self::getSevenDayPriceData();
return (float)array_sum(array_map(function($var) {
return $var['value'];
}, $prices))/(float)count($prices);
}
public function getCurrentPrice() {
$prices=self::getSevenDayPriceData();
return $prices;
}
private static function getSevenDayPriceData() {
if(self::fetchCached()['7dayavg']['expires']<time()) {
$start_time=strftime("%Y-%m-%dT%H:%I:%SZ",strtotime('-7 days'));
$end_time=strftime("%Y-%m-%dT%H:%I:%SZ",time());
$prices=self::getJSON('/variable/117/events/json?start_time='.$start_time.'&end_time='.$end_time);
self::setCache(array('7dayavg'=>array('prices'=>$prices,'expires'=>strtotime('+1 day'))));
} else {
$prices=self::fetchCached()['7dayavg']['prices'];
}
return $prices;
}
/**
* Send settings array as a JSON message to heat pump controller.
* @param array $settings
*/
private static function getJSON($uri) {
$request_uri=self::FINGRID_API.$uri;
try {
$ch=\curl_init($request_uri);
curl_setopt_array($ch,array(
CURLOPT_RETURNTRANSFER=>true,
CURLOPT_HTTPHEADER => array(
'x-api-key: '.\Polaris\Config::get('fingrid_key'),
'Content-Type: application/json'
)
));
$response = curl_exec($ch);
if($response === false) {
throw new \Exception("API call failed: ".curl_error($ch));
}
$responseData = json_decode($response, TRUE);
return $responseData;
} catch(\Exception $e) {
throw $e;
}
}
private function fetchCached() {
self::$cache=json_decode(file_get_contents('/tmp/fingrid.json'),true);
return self::$cache;
}
private function setCache($vars) {
self::fetchCached();
foreach($vars As $key=>$value) {
self::$cache[$key]=$value;
}
file_put_contents('/tmp/fingrid.json',json_encode(self::$cache));
}
}
<file_sep>/public/index.php
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \Polaris\Heatpump;
require '../vendor/autoload.php';
\Polaris\Config::load('../config.json');
use \Slim\Views\Twig;
$app = new \Slim\App;
$container = $app->getContainer();
// Register component on container
$container['view'] = function ($container) {
$view = new \Slim\Views\Twig('../views', [
'cache' => false#'../../view_cache'
]);
// Instantiate and add Slim specific extension
$basePath = rtrim(str_ireplace('index.php', '', $container['request']->getUri()->getBasePath()), '/');
$view->addExtension(new Slim\Views\TwigExtension($container['router'], $basePath));
return $view;
};
$app->get('/', function (Request $request, Response $response) {
$sensor_data=['indoor_temp'=>20,'outdoor_temp'=>10];
$name = $request->getAttribute('name');
return $this->view->render($response, 'status.html',[
'sensors'=>$sensor_data,
'heatpump'=>\Polaris\Heatpump::getStatus()
]);
})->setName('status');
$app->get('/status.json', function (Request $request, Response $response) {
$sensor_data=['indoor_temp'=>20,'outdoor_temp'=>10];
return json_encode(\Polaris\Heatpump::getStatus());
})->setName('status');
$app->get('/set', function (Request $request, Response $response) {
$sensor_data=['indoor_temp'=>20,'outdoor_temp'=>10];
return $this->view->render($response, 'settings.html',[
'sensors'=>$sensor_data,
'heatpump'=>\Polaris\Heatpump::getStatus()
]);
})->setName('settings');
$app->post('/set/temperature', function (Request $request, Response $response) {
$data = $request->getParsedBody();
$temperature=(int)filter_var($data['temperature'],FILTER_SANITIZE_NUMBER_INT);
\Polaris\Heatpump::setTemperature($temperature);
})->setName("setTemperature");
$app->post('/set/mode', function (Request $request, Response $response) {
$data = $request->getParsedBody();
$mode=filter_var($data['mode'],FILTER_SANITIZE_STRING);
\Polaris\Heatpump::setMode($mode);
})->setName("setMode");
$app->post('/set/vane', function (Request $request, Response $response) {
$data = $request->getParsedBody();
$vane=filter_var($data['vane'],FILTER_SANITIZE_STRING);
\Polaris\Heatpump::setVane($vane);
})->setName("setVane");
$app->post('/set/power', function (Request $request, Response $response) {
$data = $request->getParsedBody();
$mode=filter_var($data['power'],FILTER_SANITIZE_NUMBER_INT);
if($mode==NULL) {
throw new \Exception("Input not boolean.");
}
\Polaris\Heatpump::setPower($mode);
})->setName("setPower");
$app->get('/cron', function (Request $request, Response $response) {
$avgprice=\Polaris\Fingrid::getSevenDayAveragePrice();
$prices=\Polaris\Fingrid::getCurrentPrice();
var_dump(array_filter($prices,function($var) {
$stt=DateTime::createFromFormat("Y-m-d\TH+",$var['start_time']);
die($stt->getTimeStamp());
if(strptime("%Y-%m-%dT%H:%I:%SZ",$var['start_time'])<time()&&strptime("%Y-%m-%dT%H:%I:%SZ",$var['end_time'])>time()) { return true; }
return false;
}));
})->setName("runCron");
$app->run();
|
d8aade93da258e7a85a60b6692f1ce58030e774d
|
[
"PHP"
] | 3
|
PHP
|
PolarFox/heatpump-ui
|
750767e84281c18a7b376f2e83f6811b0f934552
|
b10d8f365f3f4f73279eaf0521cce05a1faff58f
|
refs/heads/master
|
<file_sep>package com.rods.kine;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static android.widget.Toast.LENGTH_SHORT;
public class Registration_frag extends Fragment implements Runnable{
EditText remail;
EditText repassword;
EditText reconfirmpassword;
Button registration;
Button regback;
final String registrationURL = "https://nemet.balaz98.hu/kine/api/register";
ImageView tb_image;
ImageView mk_image;
public static final int PICK_IMAGE = 1;
public static final int PICK_IMAGE2 = 2;
String encoded_tb = "";
String encoded_mk = "";
EditText address;
EditText town;
EditText postcode;
EditText phone;
EditText name;
CheckBox privacy;
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_IMAGE) {
if (data != null) {
Uri imageuri = data.getData();
Bitmap mBitmap = null;
try {
mBitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), imageuri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
encoded_tb = Base64.encodeToString(byteArray, Base64.DEFAULT);
System.out.println(encoded_tb.length() + " tb length");
System.out.println(encoded_mk.length() + " mk length");
setFullscreen();
}
}
if (requestCode == PICK_IMAGE2) {
if (data != null) {
Uri imageuri = data.getData();
Bitmap mBitmap = null;
try {
mBitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), imageuri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
encoded_mk = Base64.encodeToString(byteArray, Base64.DEFAULT);
System.out.println(encoded_tb.length() + " tb length");
System.out.println(encoded_mk.length() + " mk length");
setFullscreen();
}
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_registration, container, false);
System.out.println("CurrentLayout: Registration_frag");
regback = (Button) view.findViewById(R.id.regback);
regback.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
((Login) getActivity()).setViewPager(0);
}
});
tb_image = view.findViewById(R.id.tb);
mk_image = view.findViewById(R.id.setmk);
address = view.findViewById(R.id.setaddress);
town = view.findViewById(R.id.settown);
postcode = view.findViewById(R.id.setpostcode);
name = view.findViewById(R.id.setregname);
phone = view.findViewById(R.id.phone);
privacy = view.findViewById(R.id.privacy);
remail = (EditText) view.findViewById(R.id.setemail);
repassword = (EditText) view.findViewById(R.id.setrepassword);
reconfirmpassword = (EditText) view.findViewById(R.id.setreconfirmpassword);
address.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
setFullscreen();
}
}
});
postcode.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
setFullscreen();
}
}
});
town.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
setFullscreen();
}
}
});
name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
setFullscreen();
}
}
});
phone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
setFullscreen();
}
}
});
remail.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
setFullscreen();
}
}
});
repassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
setFullscreen();
}
}
});
reconfirmpassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
setFullscreen();
}
}
});
registration = view.findViewById(R.id.registration);
registration.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String sendMail = remail.getText().toString();
final String sendPass = repassword.getText().toString();
String sendRePass = reconfirmpassword.getText().toString();
Log.d("REGISTRATION", "adatok: " + sendMail + ", " + sendPass + ", " + sendRePass);
if (sendPass.equals(sendRePass)) {
String saddress = address.getText().toString();
String stown = town.getText().toString();
String spostcode = postcode.getText().toString();
String sname = name.getText().toString();
String sphone = phone.getText().toString();
if(sendMail.isEmpty()) {
Toast.makeText(getActivity(), "Hiányzó felhasználónév", LENGTH_SHORT).show();
return;
}
if(sendPass.isEmpty()) {
Toast.makeText(getActivity(), "Hiányzó password", LENGTH_SHORT).show();
return;
}
if(saddress.isEmpty()) {
Toast.makeText(getActivity(), "Hiányzó address", LENGTH_SHORT).show();
return;
}
if(stown.isEmpty()) {
Toast.makeText(getActivity(), "Hiányzó town", LENGTH_SHORT).show();
return;
}
if(spostcode.isEmpty()) {
Toast.makeText(getActivity(), "Hiányzó postcode", LENGTH_SHORT).show();
return;
}
if(sname.isEmpty()) {
Toast.makeText(getActivity(), "Hianyzo nev", LENGTH_SHORT).show();
return;
}
if(sphone.isEmpty()) {
Toast.makeText(getActivity(), "Hianyzo telefonszam", LENGTH_SHORT).show();
return;
}
if(encoded_tb.isEmpty()) {
Toast.makeText(getActivity(), "Nem toltottel fel tb kártyát", LENGTH_SHORT).show();
return;
}
if(encoded_mk.isEmpty()) {
Toast.makeText(getActivity(), "Nem töltöttél fel mb kártyát", LENGTH_SHORT).show();
return;
}
if(!privacy.isChecked()) {
Toast.makeText(getActivity(), "Nem fogadtad el a privacity", LENGTH_SHORT).show();
return;
}
if (isOnline()) {
System.out.println("ONLINE VAGYUNK");
StringRequest stringRequest = new StringRequest(Request.Method.POST, registrationURL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
System.out.println(jsonObject.toString());
if (jsonObject.getInt("status") == 1) {
System.out.println("Registration send");
if (jsonObject.getInt("success") == 1) {
System.out.println("Registration success");
Toast.makeText(getActivity(), "Enregistrement réussi!", Toast.LENGTH_SHORT).show();
((Login) getActivity()).setViewPager(0);
} else {
Toast.makeText(getActivity(), jsonObject.getJSONArray("error").get(0).toString(), Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Response: " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("REGISTRATION WRONG");
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
Log.d("REGISTRATION", "adatok: " + sendMail + ", " + sendPass);
params.put("apikey", "asd123");
params.put("username", sendMail);
params.put("password", <PASSWORD>);
params.put("maganbizt_image_str", encoded_mk);
params.put("tb_image_str", encoded_tb);
params.put("address", address.getText().toString()+" "+town.getText().toString()+" "+postcode.getText().toString());
params.put("phone", phone.getText().toString());
params.put("name", name.getText().toString());
return params;
}
};
MySingleton.getInstance(getActivity()).addToRequestque(stringRequest);
} else {
Toast.makeText(getActivity(), "Pas de connexion Internet!", LENGTH_SHORT).show();
}
} else {
Toast.makeText(getActivity(), "A jelszavak nem egyeznek", LENGTH_SHORT).show();
}
}
});
tb_image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
});
mk_image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE2);
}
});
setFullscreen();
return view;
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
public void hideKeyboard(View view) {
InputMethodManager inputMethodManager =(InputMethodManager)getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
@Override
public void onDestroy() {
super.onDestroy();
exitFullscreen(getActivity());
}
public static boolean isImmersiveAvailable() {
return android.os.Build.VERSION.SDK_INT >= 19;
}
public void onWindowFocusChanged(boolean hasFocus) {
if (hasFocus) {
_handler.removeCallbacks(this);
_handler.postDelayed(this, 300);
} else {
_handler.removeCallbacks(this);
}
}
public void onKeyDown(int keyCode) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP)) {
_handler.removeCallbacks(this);
_handler.postDelayed(this, 500);
}
}
@Override
public void onStop() {
_handler.removeCallbacks(this);
super.onStop();
}
@Override
public void run() {
setFullscreen();
}
public void setFullscreen() {
setFullscreen(getActivity());
}
public void setFullscreen(Activity activity) {
if (Build.VERSION.SDK_INT > 10) {
int flags = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN;
if (isImmersiveAvailable()) {
flags |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
}
activity.getWindow().getDecorView().setSystemUiVisibility(flags);
} else {
activity.getWindow()
.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
public void exitFullscreen(Activity activity) {
if (Build.VERSION.SDK_INT > 10) {
activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
} else {
activity.getWindow()
.setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
}
}
private Handler _handler = new Handler();
}
<file_sep>package com.rods.kine;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class GridDoctorRecycleViewAdapter extends RecyclerView.Adapter<GridDoctorRecycleViewAdapter.ViewHolder> {
private ArrayList<Doctor> mData = new ArrayList<>();
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
private Context mContext;
// data is passed into the constructor
public GridDoctorRecycleViewAdapter(Context context, ArrayList<Doctor> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
this.mContext = context;
}
// inflates the cell layout from xml when needed
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.item, parent, false);
return new ViewHolder(view);
}
// binds the data to the textview in each cell
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.name.setText(mData.get(position).name);
Picasso.get().load(mData.get(position).image).placeholder(R.drawable.doctor1).fit().centerCrop().into(holder.image);
System.out.println("Loaded: "+position);
}
// total number of cells
@Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView name;
ImageView image;
ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.phone);
image = (ImageView) itemView.findViewById(R.id.image);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
Doctor getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}<file_sep>package com.rods.kine;
import android.app.Activity;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import static android.widget.Toast.LENGTH_SHORT;
import static com.rods.kine.Login_frag.KEY_PASS;
import static com.rods.kine.Login_frag.KEY_USERNAME;
import static com.rods.kine.Login_frag.editor;
import static com.rods.kine.Login_frag.profile;
import static com.rods.kine.Login_frag.sharedPreferences;
import static com.rods.kine.Login_frag.useEmail;
import static com.rods.kine.Login_frag.usePassword;
public class Main extends AppCompatActivity implements GridDoctorRecycleViewAdapter.ItemClickListener{
RecyclerView list;
GridDoctorRecycleViewAdapter gridDoctorRecycleViewAdapter;
static ArrayList<Doctor> doctors = new ArrayList<>();
final String doctorURL = "https://nemet.balaz98.hu/kine/api/doctors";
final String boxesURL ="https://nemet.balaz98.hu/kine/api/getboxes";
Button logout;
Button myappointments;
Button message;
static Activity activity;
JSONArray jsonDoctors;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hideSystemUI();
hideToolBr();
activity = this;
//FIREBASE CUCCOK
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationChannel mChannel = new NotificationChannel("mychannelid", "mychannelname",NotificationManager.IMPORTANCE_HIGH);
mChannel.setDescription("mychanneldescrition");
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[] {100,200,300,400,500,400,300,200,400});
notificationManager.createNotificationChannel(mChannel);
}
doctors.clear();
logout = (Button)findViewById(R.id.settings);
logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Main.this, Settings.class);
startActivity(intent);
}
});
message = findViewById(R.id.message);
message.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Main.this, Messages.class);
startActivity(intent);
}
});
getDoctors();
if(profile.doctorname != null) {
getBoxes();
}
myappointments = (Button) findViewById(R.id.myappointments);
myappointments.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Main.this, MyAppointments.class);
startActivity(intent);
}
});
list = (RecyclerView) findViewById(R.id.list);
int numberOfColums = 2;
list.setLayoutManager(new GridLayoutManager(this, numberOfColums));
gridDoctorRecycleViewAdapter = new GridDoctorRecycleViewAdapter(this,doctors);
gridDoctorRecycleViewAdapter.setClickListener(this);
list.setAdapter(gridDoctorRecycleViewAdapter);
System.out.println("Current Activity: MAIN");
hideSystemUI();
hideToolBr();
//getSupportActionBar().hide();
}
public void onItemClick(View view, int position) {
Intent intent = new Intent(this.getApplicationContext(), Detail.class);
intent.putExtra("doctor",gridDoctorRecycleViewAdapter.getItem(position));
startActivity(intent);
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
public static Doctor jsonObjectToDoctor(JSONObject jsonObject) {
Doctor d = new Doctor();
try {
d.id = jsonObject.getInt("id");
d.name = jsonObject.getString("name");
d.image = jsonObject.getString("image");
d.text = jsonObject.getString("text");
d.address = jsonObject.getString("address");
d.address_lat = Double.parseDouble(jsonObject.getString("address_lat"));
d.address_long = Double.parseDouble(jsonObject.getString("address_long"));
d.active = jsonObject.getInt("active");
d.added = jsonObject.getString("added");
for(int i=0; i<jsonObject.getJSONArray("reserve_types").length(); i++) {
d.reserve_types.add(jsonObjectToType(jsonObject.getJSONArray("reserve_types").getJSONObject(i)));
System.out.println(d.reserve_types.get(i));
}
Iterator<?> keys = jsonObject.getJSONObject("times").keys();
while(keys.hasNext()) {
String key = (String) keys.next();
d.days.add(key);
for(int i=0; i<jsonObject.getJSONObject("times").getJSONArray(key).length(); i++) {
d.times.add(jsonObjectToTime(jsonObject.getJSONObject("times").getJSONArray(key).getJSONObject(i)));
//System.out.println(d.times.toString());
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return d;
}
public static Doctor jsonBoxObjectToDoctor(JSONObject jsonObject) {
Doctor d = new Doctor();
try {
d.name = jsonObject.getString("text");
d.image = jsonObject.getString("image");
d.text = "BOX";
} catch (JSONException e) {
e.printStackTrace();
}
return d;
}
public static Type jsonObjectToType(JSONObject jsonObject) {
Type t = new Type();
try {
t.id = jsonObject.getInt("id");
t.doctor_id = jsonObject.getInt("doctor_id");
t.length = jsonObject.getInt("length");
t.name = jsonObject.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
return t;
}
public static Time jsonObjectToTime(JSONObject jsonObject) {
Time t = new Time();
try {
t.id = jsonObject.getInt("id");
t.day = jsonObject.getString("day");
t.time = jsonObject.getString("time");
} catch (JSONException e) {
e.printStackTrace();
}
return t;
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
hideSystemUI();
}
hideSystemUI();
}
private void hideSystemUI() {
// Enables regular immersive mode.
// For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
// Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_IMMERSIVE
// Set the content to appear under the system bars so that the
// content doesn't resize when the system bars hide and show.
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// Hide the nav bar and status bar
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
public void hideToolBr() {
// BEGIN_INCLUDE (get_current_ui_flags)
// The UI options currently enabled are represented by a bitfield.
// getSystemUiVisibility() gives us that bitfield.
int uiOptions = getWindow().getDecorView().getSystemUiVisibility();
int newUiOptions = uiOptions;
// END_INCLUDE (get_current_ui_flags)
// BEGIN_INCLUDE (toggle_ui_flags)
boolean isImmersiveModeEnabled =
((uiOptions | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) == uiOptions);
// Navigation bar hiding: Backwards compatible to ICS.
if (Build.VERSION.SDK_INT >= 14) {
newUiOptions ^= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
}
// Status bar hiding: Backwards compatible to Jellybean
if (Build.VERSION.SDK_INT >= 16) {
newUiOptions ^= View.SYSTEM_UI_FLAG_FULLSCREEN;
}
// Immersive mode: Backward compatible to KitKat.
// Note that this flag doesn't do anything by itself, it only augments the behavior
// of HIDE_NAVIGATION and FLAG_FULLSCREEN. For the purposes of this sample
// all three flags are being toggled together.
// Note that there are two immersive mode UI flags, one of which is referred to as "sticky".
// Sticky immersive mode differs in that it makes the navigation and status bars
// semi-transparent, and the UI flag does not get cleared when the user interacts with
// the screen.
if (Build.VERSION.SDK_INT >= 18) {
newUiOptions ^= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
}
getWindow().getDecorView().setSystemUiVisibility(newUiOptions);
//END_INCLUDE (set_ui_flags)
}
public void getDoctors() {
if (isOnline()) {
System.out.println("ONLINE VAGYUNK");
StringRequest stringRequest = new StringRequest(Request.Method.POST, doctorURL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getInt("status") == 1) {
System.out.println("Doctors send");
if (jsonObject.getInt("success") == 1) {
System.out.println("doctor success");
Log.d("DOCTORS RESPOND",jsonObject.toString());
//feldolgozás
jsonDoctors = jsonObject.getJSONObject("data").getJSONArray("doctors");
Log.d("DOCTORS","LENGTH: "+jsonDoctors.length());
if(jsonDoctors.length()!=0){
for(int i=0; i<jsonDoctors.length(); i++) {
doctors.add(jsonObjectToDoctor(jsonDoctors.getJSONObject(i)));
System.out.println(doctors.get(i).toString());
}
/*
for(int i=0; i<30; i++) {
doctors.add(doctors.get(0));
}
*/
Collections.sort(doctors,new SortByCost());
gridDoctorRecycleViewAdapter.notifyDataSetChanged();
}
//feldolgozás vége
} else {
Toast.makeText(Main.this, jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
System.out.println("Username: "+useEmail);
System.out.println("Password: "+usePassword);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Response: " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("REGISTRATION WRONG");
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("apikey", "asd123");
params.put("username", Login_frag.useEmail);
params.put("password", <PASSWORD>frag.usePassword);
return params;
}
};
MySingleton.getInstance(Main.this).addToRequestque(stringRequest);
} else {
Toast.makeText(Main.this, "Pas de connexion Internet!", LENGTH_SHORT).show();
}
}
public void getBoxes() {
if (isOnline()) {
System.out.println("ONLINE VAGYUNK");
StringRequest stringRequest = new StringRequest(Request.Method.POST, boxesURL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getInt("status") == 1) {
System.out.println("Boxes send");
if (jsonObject.getInt("success") == 1) {
System.out.println("Boxes success");
Log.d("Boxes RESPOND",jsonObject.toString());
//feldolgozás
jsonDoctors = jsonObject.getJSONObject("data").getJSONArray("boxes");
Log.d("Boxes","LENGTH: "+jsonDoctors.length());
if(jsonDoctors.length()!=0){
for(int i=0; i<jsonDoctors.length(); i++) {
doctors.add(jsonBoxObjectToDoctor(jsonDoctors.getJSONObject(i)));
System.out.println(doctors.get(i).toString());
}
/*
for(int i=0; i<30; i++) {
doctors.add(doctors.get(0));
}
*/
Collections.sort(doctors,new SortByCost());
gridDoctorRecycleViewAdapter.notifyDataSetChanged();
}
//feldolgozás vége
} else {
Toast.makeText(Main.this, jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Response: " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("boxes WRONG");
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("apikey", "asd123");
return params;
}
};
MySingleton.getInstance(Main.this).addToRequestque(stringRequest);
} else {
Toast.makeText(Main.this, "Pas de connexion Internet!", LENGTH_SHORT).show();
}
}
}
class SortByCost implements Comparator<Doctor> {
public int compare(Doctor a, Doctor b) {
if ( a.id > b.id ) return -1;
else if ( a.id == b.id ) return 0;
else return 1;
}
}
<file_sep>package com.rods.kine;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class AddonsView extends AppCompatActivity {
Button regback;
ImageView image;
TextView left;
TextView right;
int holvok = 0;
int meret = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addons_view);
final Message d = (Message) getIntent().getSerializableExtra("message");
final String[] urls= new String[d.addons.size()];
for(int i=0; i<d.addons.size(); i++) {
urls[i] = d.addons.get(i).url;
}
meret = urls.length;
regback = findViewById(R.id.bookback);
image = findViewById(R.id.image);
left = findViewById(R.id.left);
right = findViewById(R.id.right);
regback.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
Picasso.get().load(urls[holvok]).into(image);
right.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(holvok == meret-1) {
holvok=0;
Picasso.get().load(urls[holvok]).into(image);
}
else {
holvok++;
Picasso.get().load(urls[holvok]).into(image);
}
}
});
left.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(holvok == 0) {
holvok = meret-1;
Picasso.get().load(urls[holvok]).into(image);
}
else {
holvok --;
Picasso.get().load(urls[holvok]).into(image);
}
}
});
}
}
<file_sep>package com.rods.kine;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static android.widget.Toast.LENGTH_SHORT;
public class Messages extends AppCompatActivity implements MessagesRecycleViewAdapter.ItemClickListener {
Button mback;
RecyclerView messagelist;
MessagesRecycleViewAdapter messagesRecycleViewAdapter;
final String messagesURL = "https://nemet.balaz98.hu/kine/api/messages";
JSONArray jsonMessagesFrom;
JSONArray jsonMessagesTo;
Button plus;
ArrayList<Message> messages = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messages);
hideSystemUI();
mback = findViewById(R.id.mback);
messages.clear();
mback.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
plus = findViewById(R.id.plus);
plus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Messages.this, NewMessage.class);
startActivity(intent);
}
});
messageLekeres();
messagelist = findViewById(R.id.messaglist);
messagelist.setLayoutManager(new LinearLayoutManager(this));
messagesRecycleViewAdapter = new MessagesRecycleViewAdapter(this, messages);
messagesRecycleViewAdapter.setClickListener(this);
messagelist.setAdapter(messagesRecycleViewAdapter);
}
public void onItemClick(View view, int position) {
Intent intent = new Intent(this.getApplicationContext(), MessageDetail.class);
intent.putExtra("message",messagesRecycleViewAdapter.getItem(position));
startActivity(intent);
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
public static Message jsonObjectToMessage(JSONObject jsonObject, String where) {
Message m = new Message();
try {
m.id = jsonObject.getInt("id");
m.from = jsonObject.getInt("from");
m.to = jsonObject.getInt("to");
m.message = jsonObject.getString("message");
m.date = jsonObject.getString("date");
m.ip = jsonObject.getString("ip");
m.times_id = jsonObject.getInt("times_id");
m.from_type = jsonObject.getString("from_type");
m.to_type = jsonObject.getString("to_type");
m.where = where;
for(int i=0;i<jsonObject.getJSONArray("addons").length(); i++) {
m.addons.add(jsonObjectToAddon(jsonObject.getJSONArray("addons").getJSONObject(i)));
}
} catch (JSONException e) {
e.printStackTrace();
}
return m;
}
public static Addon jsonObjectToAddon(JSONObject jsonObject){
String nev = null;
String url = null;
try {
nev = jsonObject.getString("name");
url = jsonObject.getString("url");
} catch (JSONException e) {
e.printStackTrace();
}
Addon a = new Addon(nev, url);
return a;
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
hideSystemUI();
}
}
private void hideSystemUI() {
// Enables regular immersive mode.
// For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
// Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_IMMERSIVE
// Set the content to appear under the system bars so that the
// content doesn't resize when the system bars hide and show.
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// Hide the nav bar and status bar
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
public void messageLekeres() {
if (isOnline()) {
System.out.println("ONLINE VAGYUNK");
StringRequest stringRequest = new StringRequest(Request.Method.POST, messagesURL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getInt("status") == 1) {
System.out.println("MESSAGES send");
if (jsonObject.getInt("success") == 1) {
System.out.println("MESSAGES success");
Log.d("MESSAGES RESPOND",jsonObject.toString());
//feldolgozás
jsonMessagesFrom = jsonObject.getJSONObject("data").getJSONArray("from_me");
jsonMessagesTo = jsonObject.getJSONObject("data").getJSONArray("to_me");
if(jsonMessagesTo.length()!=0){
Log.d("MESSAGESFROMME","LENGTH: "+jsonMessagesFrom.length());
for(int i=0; i<jsonMessagesTo.length(); i++) {
messages.add(jsonObjectToMessage(jsonMessagesTo.getJSONObject(i), "to"));
System.out.println(jsonMessagesTo.getJSONObject(i).toString());
}
}
if(jsonMessagesFrom.length()!=0) {
Log.d("MESSAGESTOME","LENGTH: "+jsonMessagesTo.length());
for(int i=0; i<jsonMessagesFrom.length(); i++) {
messages.add(jsonObjectToMessage(jsonMessagesFrom.getJSONObject(i), "from"));
}
}
Collections.reverse(messages);
messagesRecycleViewAdapter.notifyDataSetChanged();
//feldolgozás vége
} else {
Toast.makeText(Messages.this, jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Response: " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("MESSAGES WRONG");
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("apikey", "asd123");
params.put("username", Login_frag.useEmail);
params.put("password", <PASSWORD>);
return params;
}
};
MySingleton.getInstance(Messages.this).addToRequestque(stringRequest);
} else {
Toast.makeText(Messages.this, "Pas de connexion Internet!", LENGTH_SHORT).show();
}
}
}
<file_sep>package com.rods.kine;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static android.widget.Toast.LENGTH_SHORT;
public class MyAppointments extends AppCompatActivity implements AppointmentsRecycleViewAdapter.ItemClickListener {
Button apoback;
RecyclerView apolist;
AppointmentsRecycleViewAdapter appointmentsRecycleViewAdapter;
final String myApoURL = "https://nemet.balaz98.hu/kine/api/previous_reserved";
final String deleteURL = "https://nemet.balaz98.hu/kine/api/delete_reserved";
JSONArray jsonAppointmens;
ArrayList<Appointment> appointments = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_appointments);
hideSystemUI();
apoback = (Button) findViewById(R.id.apoback);
apolist = (RecyclerView) findViewById(R.id.apolist);
apoback.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
if (isOnline()) {
appointments.clear();
System.out.println("ONLINE VAGYUNK");
StringRequest stringRequest = new StringRequest(Request.Method.POST, myApoURL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getInt("status") == 1) {
System.out.println("Myappointments send");
if (jsonObject.getInt("success") == 1) {
System.out.println("Myappointments success");
Log.d("MYAPPOINTMENTS RESPOND",jsonObject.toString());
//feldolgozás
jsonAppointmens = jsonObject.getJSONObject("data").getJSONArray("times");
Log.d("MYAPPOINTMENTS","LENGTH: "+jsonAppointmens.length());
if(jsonAppointmens.length()!=0){
for(int i=0; i<jsonAppointmens.length(); i++) {
appointments.add(jsonObjectToAppointment(jsonAppointmens.getJSONObject(i)));
System.out.println(appointments.get(i).toString());
}
appointmentsRecycleViewAdapter.notifyDataSetChanged();
}
//feldolgozás vége
} else {
Toast.makeText(MyAppointments.this, jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Response: " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("REGISTRATION WRONG");
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("apikey", "asd123");
params.put("username", Login_frag.useEmail);
params.put("password", <PASSWORD>_frag.usePassword);
return params;
}
};
MySingleton.getInstance(MyAppointments.this).addToRequestque(stringRequest);
} else {
Toast.makeText(MyAppointments.this, "Pas de connexion Internet!", LENGTH_SHORT).show();
}
apolist = findViewById(R.id.apolist);
apolist.setLayoutManager(new LinearLayoutManager(this));
appointmentsRecycleViewAdapter = new AppointmentsRecycleViewAdapter(this, appointments);
appointmentsRecycleViewAdapter.setClickListener(this);
apolist.setAdapter(appointmentsRecycleViewAdapter);
}
public void onItemClick(View view, final int position) {
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(MyAppointments.this);
View mView = getLayoutInflater().inflate(R.layout.lemondas, null);
TextView cancel = (TextView) mView.findViewById(R.id.cancel);
final EditText comment = (EditText) mView.findViewById(R.id.to);
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isOnline()) {
System.out.println("ONLINE VAGYUNK");
StringRequest stringRequest = new StringRequest(Request.Method.POST, deleteURL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getInt("status") == 1) {
System.out.println("DELETE send");
if (jsonObject.getInt("success") == 1) {
System.out.println("DELETE success");
finish();
Log.d("MYAPPOINTMENTS RESPOND",jsonObject.toString());
} else {
Toast.makeText(MyAppointments.this, jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Response: " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("DELETE WRONG");
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("apikey", "asd123");
params.put("username", Login_frag.useEmail);
params.put("password", Login_frag.usePassword);
params.put("reserve_id", appointmentsRecycleViewAdapter.getItem(position).id+"");
params.put("delete_comment",comment.getText().toString());
return params;
}
};
MySingleton.getInstance(MyAppointments.this).addToRequestque(stringRequest);
} else {
Toast.makeText(MyAppointments.this, "Pas de connexion Internet!", LENGTH_SHORT).show();
}
}
});
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
dialog.show();
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
public static Appointment jsonObjectToAppointment(JSONObject jsonObject) {
Appointment a = new Appointment();
try {
a.id = jsonObject.getInt("id");
a.doctors_id = jsonObject.getInt("doctors_id");
a.user_id = jsonObject.getInt("user_id");
a.date = jsonObject.getString("date");
a.timeid = jsonObject.getInt("timeid");
a.timeend = jsonObject.getInt("timeend");
a.added = jsonObject.getString("added");
a.comment = jsonObject.getString("comment");
for(int i=0; i<jsonObject.getJSONArray("addons").length(); i++) {
a.addons.add(new Addon(jsonObject.getJSONArray("addons").getJSONObject(i).getString("name"),
jsonObject.getJSONArray("addons").getJSONObject(i).getString("url")));
}
a.idopont = jsonObject.getString("idopont");
a.doctor.id = jsonObject.getJSONArray("doctor").getJSONObject(0).getInt("id");
a.doctor.name = jsonObject.getJSONArray("doctor").getJSONObject(0).getString("name");
a.doctor.image = jsonObject.getJSONArray("doctor").getJSONObject(0).getString("image");
a.doctor.text = jsonObject.getJSONArray("doctor").getJSONObject(0).getString("text");
a.doctor.address = jsonObject.getJSONArray("doctor").getJSONObject(0).getString("address");
a.doctor.address_lat = jsonObject.getJSONArray("doctor").getJSONObject(0).getDouble("address_lat");
a.doctor.address_long = jsonObject.getJSONArray("doctor").getJSONObject(0).getDouble("address_long");
a.doctor.active = jsonObject.getJSONArray("doctor").getJSONObject(0).getInt("active");
a.doctor.added = jsonObject.getJSONArray("doctor").getJSONObject(0).getString("added");
} catch (JSONException e) {
e.printStackTrace();
}
return a;
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
hideSystemUI();
}
}
private void hideSystemUI() {
// Enables regular immersive mode.
// For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
// Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_IMMERSIVE
// Set the content to appear under the system bars so that the
// content doesn't resize when the system bars hide and show.
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// Hide the nav bar and status bar
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
<file_sep>package com.rods.kine;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.squareup.picasso.Picasso;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static android.widget.Toast.LENGTH_SHORT;
import static com.rods.kine.Login_frag.KEY_PASS;
import static com.rods.kine.Login_frag.KEY_USERNAME;
import static com.rods.kine.Login_frag.editor;
import static com.rods.kine.Login_frag.profile;
import static com.rods.kine.Login_frag.sharedPreferences;
import static com.rods.kine.Login_frag.useEmail;
import static com.rods.kine.Login_frag.usePassword;
public class Settings extends AppCompatActivity {
Button back;
TextView email;
TextView name;
TextView phone;
TextView address;
TextView doctor;
Button setname;
Button setphone;
Button setaddress;
Button setdoctor;
Button privacy;
Button newpass;
Button logout;
ImageView profilepicture;
final int PICK_IMAGE = 1;
String encoded_profilepicture;
final String profileURL = "https://nemet.balaz98.hu/kine/api/profilemod";
final String newpassURL = "https://nemet.balaz98.hu/kine/api/pwmod";
final String profilepictureURL = "https://nemet.balaz98.hu/kine/api/upload_profilepicture";
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_IMAGE) {
if (data != null) {
Uri imageuri = data.getData();
Bitmap mBitmap = null;
try {
mBitmap = MediaStore.Images.Media.getBitmap(Settings.this.getContentResolver(), imageuri);
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
encoded_profilepicture = Base64.encodeToString(byteArray, Base64.DEFAULT);
if (isOnline()) {
System.out.println("ONLINE VAGYUNK");
StringRequest stringRequest = new StringRequest(Request.Method.POST, profilepictureURL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getInt("status") == 1) {
System.out.println("profilepictureupdate send");
if (jsonObject.getInt("success") == 1) {
System.out.println("profilepictureupdate success");
Toast.makeText(Settings.this, "Sikeres profilkép frissítés", Toast.LENGTH_SHORT).show();
Main.activity.finish();
Intent intent = new Intent(Settings.this, Login.class);
startActivity(intent);
finish();
} else {
Toast.makeText(Settings.this, jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Response: " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("PROFILPICTUREUPDATE WRONG");
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("apikey", "asd123");
params.put("username", useEmail);
params.put("password", <PASSWORD>);
params.put("image_str", encoded_profilepicture);
return params;
}
};
MySingleton.getInstance(Settings.this).addToRequestque(stringRequest);
} else {
Toast.makeText(Settings.this, "Pas de connexion Internet!", LENGTH_SHORT).show();
}
System.out.println(encoded_profilepicture.length() + " tb length");
FullScreencall();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
FullScreencall();
email = findViewById(R.id.email);
name = findViewById(R.id.name);
phone = findViewById(R.id.phone);
address = findViewById(R.id.address);
doctor = findViewById(R.id.doctor);
setname = findViewById(R.id.setname);
setphone = findViewById(R.id.setphone);
setaddress = findViewById(R.id.setaddress);
setdoctor = findViewById(R.id.setdoctor);
privacy = findViewById(R.id.privacy);
newpass = findViewById(R.id.newpass);
logout = findViewById(R.id.logout);
profilepicture = findViewById(R.id.profilepicture);
back = findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editor.remove(KEY_USERNAME);
editor.remove(KEY_PASS);
editor.commit();
editor.apply();
Main.activity.finish();
Intent intent = new Intent(Settings.this, Login.class);
startActivity(intent);
finish();
}
});
email.setText(profile.username);
address.setText(profile.data_address);
phone.setText(profile.data_phone);
name.setText(profile.data_name);
if (profile.doctorname == null) {
doctor.setText("No doctor chosen");
} else {
doctor.setText(profile.doctorname);
}
Picasso.get().load(profile.userimage).fit().centerCrop().into(profilepicture);
setname.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(Settings.this);
View mView = getLayoutInflater().inflate(R.layout.update_profile, null);
Button cancel = (Button) mView.findViewById(R.id.back);
Button pass = (Button) mView.findViewById(R.id.pass);
final EditText newP = (EditText) mView.findViewById(R.id.newP);
TextView change = (TextView) mView.findViewById(R.id.change);
TextView enter = (TextView) mView.findViewById(R.id.enter);
newP.setHint("New name");
change.setText("Change name");
enter.setText("Enter the new name");
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
dialog.show();
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
}
});
pass.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
profile.data_name = newP.getText().toString();
if (isOnline()) {
System.out.println("ONLINE VAGYUNK");
StringRequest stringRequest = new StringRequest(Request.Method.POST, profileURL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getInt("status") == 1) {
System.out.println("profileupdate send");
if (jsonObject.getInt("success") == 1) {
System.out.println("profileupdate success");
Toast.makeText(Settings.this, "Sikeres profil frissítés", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(Settings.this, jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Response: " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("PROFILUPDATE WRONG");
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("apikey", "asd123");
params.put("username", useEmail);
params.put("password", <PASSWORD>);
params.put("address", profile.data_address);
params.put("phone", profile.data_phone);
params.put("name", profile.data_name);
return params;
}
};
MySingleton.getInstance(Settings.this).addToRequestque(stringRequest);
} else {
Toast.makeText(Settings.this, "Pas de connexion Internet!", LENGTH_SHORT).show();
}
}
});
}
});
setphone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(Settings.this);
View mView = getLayoutInflater().inflate(R.layout.update_profile, null);
Button cancel = (Button) mView.findViewById(R.id.back);
Button pass = (Button) mView.findViewById(R.id.pass);
final EditText newP = (EditText) mView.findViewById(R.id.newP);
TextView change = (TextView) mView.findViewById(R.id.change);
TextView enter = (TextView) mView.findViewById(R.id.enter);
newP.setHint("New Phone Number");
change.setText("Change phone number");
enter.setText("Enter the new phone number");
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
dialog.show();
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
}
});
pass.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
profile.data_phone = newP.getText().toString();
if (isOnline()) {
System.out.println("ONLINE VAGYUNK");
StringRequest stringRequest = new StringRequest(Request.Method.POST, profileURL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getInt("status") == 1) {
System.out.println("profileupdate send");
if (jsonObject.getInt("success") == 1) {
System.out.println("profileupdate success");
Toast.makeText(Settings.this, "Sikeres profil frissítés", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(Settings.this, jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Response: " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("PROFILUPDATE WRONG");
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("apikey", "asd123");
params.put("username", useEmail);
params.put("password", <PASSWORD>);
params.put("address", profile.data_address);
params.put("phone", profile.data_phone);
params.put("name", profile.data_name);
return params;
}
};
MySingleton.getInstance(Settings.this).addToRequestque(stringRequest);
} else {
Toast.makeText(Settings.this, "Pas de connexion Internet!", LENGTH_SHORT).show();
}
}
});
}
});
setaddress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(Settings.this);
View mView = getLayoutInflater().inflate(R.layout.update_profile, null);
Button cancel = (Button) mView.findViewById(R.id.back);
Button pass = (Button) mView.findViewById(R.id.pass);
final EditText newP = (EditText) mView.findViewById(R.id.newP);
TextView change = (TextView) mView.findViewById(R.id.change);
TextView enter = (TextView) mView.findViewById(R.id.enter);
newP.setHint("New address");
change.setText("Change address");
enter.setText("Enter the new address");
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
dialog.show();
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
}
});
pass.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
profile.data_address = newP.getText().toString();
if (isOnline()) {
System.out.println("ONLINE VAGYUNK");
StringRequest stringRequest = new StringRequest(Request.Method.POST, profileURL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getInt("status") == 1) {
System.out.println("profileupdate send");
if (jsonObject.getInt("success") == 1) {
System.out.println("profileupdate success");
Toast.makeText(Settings.this, "Sikeres profil frissítés", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(Settings.this, jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Response: " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("PROFILUPDATE WRONG");
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("apikey", "asd123");
params.put("username", useEmail);
params.put("password", <PASSWORD>);
params.put("address", profile.data_address);
params.put("phone", profile.data_phone);
params.put("name", profile.data_name);
return params;
}
};
MySingleton.getInstance(Settings.this).addToRequestque(stringRequest);
} else {
Toast.makeText(Settings.this, "Pas de connexion Internet!", LENGTH_SHORT).show();
}
}
});
}
});
setdoctor.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
profile.doctorname = null;
doctor.setText("No doctor chosen");
}
});
final int[] status = {0};
final String[] newPassword = {""};
newpass.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(Settings.this);
View mView = getLayoutInflater().inflate(R.layout.update_profile, null);
Button cancel = (Button) mView.findViewById(R.id.back);
Button pass = (Button) mView.findViewById(R.id.pass);
final EditText newP = (EditText) mView.findViewById(R.id.newP);
TextView change = (TextView) mView.findViewById(R.id.change);
final TextView enter = (TextView) mView.findViewById(R.id.enter);
newP.setHint("Enter your password");
change.setText("Reset password");
enter.setText("Enter your current password");
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
dialog.show();
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
}
});
pass.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (usePassword != newP.getText().toString() && status[0] == 0) {
status[0]++;
Toast.makeText(Settings.this, "Hibás jelszó", LENGTH_SHORT).show();
dialog.dismiss();
}
else if (status[0] == 1) {
newP.setText("");
enter.setText("Enter your new password");
newP.setHint("New password");
status[0]++;
}
else if (status[0] == 2) {
newPassword[0] = newP.getText().toString();
newP.setText("");
enter.setText("Enter your new password again");
newP.setHint("New password again");
status[0]++;
}
else if (status[0] == 3 && newPassword[0].equals(newP.getText().toString())) {
if (isOnline()) {
System.out.println("ONLINE VAGYUNK");
StringRequest stringRequest = new StringRequest(Request.Method.POST, newpassURL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getInt("status") == 1) {
System.out.println("newpassword send");
if (jsonObject.getInt("success") == 1) {
System.out.println("newpassword success");
Toast.makeText(Settings.this, "Sikeres jelszó frissítés", Toast.LENGTH_SHORT).show();
editor.remove(KEY_USERNAME);
editor.remove(KEY_PASS);
editor.commit();
editor.apply();
Main.activity.finish();
Intent intent = new Intent(Settings.this, Login.class);
startActivity(intent);
finish();
} else {
Toast.makeText(Settings.this, jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Response: " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("PROFILUPDATE WRONG");
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("apikey", "asd123");
params.put("username", useEmail);
params.put("password", <PASSWORD>);
params.put("newpw", newP.getText().toString());
return params;
}
};
MySingleton.getInstance(Settings.this).addToRequestque(stringRequest);
} else {
Toast.makeText(Settings.this, "Pas de connexion Internet!", LENGTH_SHORT).show();
}
}
else {
Toast.makeText(Settings.this, "A jelszavak nem egyeznek", LENGTH_SHORT).show();
System.out.println();
status[0] = 0;
newPassword[0] = "";
dialog.dismiss();
}
}
});
}
});
profilepicture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
});
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
public void FullScreencall() {
if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
View v = this.getWindow().getDecorView();
v.setSystemUiVisibility(View.GONE);
} else if (Build.VERSION.SDK_INT >= 19) {
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
decorView.setSystemUiVisibility(uiOptions);
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
FullScreencall();
}
}
<file_sep>package com.rods.kine;
import android.support.annotation.NonNull;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Multimap;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
public class Doctor implements Serializable {
int id;
String name;
String image;
String text;
String address;
double address_lat;
double address_long;
int active;
String added;
ArrayList<Type> reserve_types;
ArrayList<Time> times;
ArrayList<String> days;
public Doctor() {
reserve_types = new ArrayList<>();
days = new ArrayList<>();
times = new ArrayList<>();
}
@Override
public String toString() {
return "Doctor{" +
"id=" + id +
", name='" + name + '\'' +
", image='" + image + '\'' +
", text='" + text + '\'' +
", address='" + address + '\'' +
", address_lat=" + address_lat +
", address_long=" + address_long +
", active=" + active +
", added='" + added + '\'' +
'}';
}
}
class Type implements Serializable {
int id;
int doctor_id;
String name;
int length;
public Type() {
}
@Override
public String toString() {
return "Type{" +
"id=" + id +
", doctor_id=" + doctor_id +
", name='" + name + '\'' +
", length=" + length +
'}';
}
}
class Time implements Serializable {
int id;
String day;
String time;
public Time() {
}
@Override
public String toString() {
return "Time{" +
"id=" + id +
", day='" + day + '\'' +
", time='" + time + '\'' +
'}';
}
}
<file_sep>package com.rods.kine;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class ImageViewer extends AppCompatActivity {
ImageView image;
Button left;
Button right;
Button back;
int position = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_viewer);
FullScreencall();
image = findViewById(R.id.image);
left = findViewById(R.id.left);
right = findViewById(R.id.right);
back = findViewById(R.id.mback);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
final ArrayList<Addon> addons = (ArrayList<Addon>) getIntent().getSerializableExtra("addons");
Picasso.get().load(addons.get(position).url).fit().centerInside().into(image);
left.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(position == 0) {
position = addons.size()-1;
Picasso.get().load(addons.get(position).url).fit().centerInside().into(image);
}
else {
position --;
Picasso.get().load(addons.get(position).url).fit().centerInside().into(image);
}
}
});
right.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(position == (addons.size()-1)) {
position = 0;
Picasso.get().load(addons.get(position).url).fit().centerInside().into(image);
}
else {
position ++;
Picasso.get().load(addons.get(position).url).fit().centerInside().into(image);
}
}
});
System.out.println(addons.size());
}
public void FullScreencall() {
if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
View v = this.getWindow().getDecorView();
v.setSystemUiVisibility(View.GONE);
} else if (Build.VERSION.SDK_INT >= 19) {
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
decorView.setSystemUiVisibility(uiOptions);
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
FullScreencall();
}
}
<file_sep>package com.rods.kine;
public class Profile {
int id;
String username;
String password;
String data_address;
String data_phone;
String data_name;
String userimage;
String doctorname;
public Profile() {
}
@Override
public String toString() {
return "Profile{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + <PASSWORD> + '\'' +
", data_address='" + data_address + '\'' +
", data_phone='" + data_phone + '\'' +
", data_name='" + data_name + '\'' +
", userimage='" + userimage + '\'' +
'}';
}
}
|
2176bc56562c1e86b4f3f4663a462781dab029c5
|
[
"Java"
] | 10
|
Java
|
kozmapiku/Kine
|
6464619d124bf011da08b55d03c3b737f2cb2825
|
047435d6a1382fee490b024ce8300e3430eec6c5
|
refs/heads/master
|
<repo_name>RemoteSensingFrank/ImageROICut<file_sep>/README.md
# ImageROICut
tools of get image roi
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.7)
project(GetImageROI)
set(CMAKE_CXX_STANDARD 11)
set(GTest_LIBRARY "/usr/local/lib/libgtest.a")
set(GDAL_LIBRARY "/usr/local/lib/libgdal.so")
set(GDAL_INCLUDE "/usr/local/include/")
find_package(OpenCV REQUIRED)
find_package(GTest REQUIRED)
include_directories(${GTEST_INCLUDE_DIRS})
include_directories(${GDAL_INCLUDE})
set(SOURCE_FILES main.cpp)
add_executable(GetImageROI ${SOURCE_FILES})
target_link_libraries(GetImageROI ${GTEST_LIBRARIES})
target_link_libraries(GetImageROI ${GDAL_LIBRARY})
target_link_libraries(GetImageROI ${OpenCV_LIBRARIES})
TARGET_LINK_LIBRARIES(GetImageROI -lpthread -lm)<file_sep>/main.cpp
#include <iostream>
#include "gdal_priv.h"
#include <opencv2/opencv.hpp>
#include<gtest/gtest.h>
using namespace cv;
cv::Mat org,sample,dst,img,tmp;
int count = 0;
float xscale = 1.0f;
float yscale = 1.0f;
char dir[128] = "/home/wuwei/Picture/Cut/";
bool CVLibraryTest()
{
Mat img = imread("/home/wuwei/Picture/bridge_ly.jpg");
if(img.empty())
return false;
else
return true;
}
bool GDALLibraryTest()
{
GDALAllRegister();
GDALDatasetH m_dataset = GDALOpen("/home/wuwei/Picture/bridge_ly.jpg",GA_ReadOnly);
if(m_dataset!=NULL)
return true;
else
return false;
}
TEST(TestLibrary, ALLLibTest)
{
EXPECT_EQ(true,CVLibraryTest());
EXPECT_EQ(true,GDALLibraryTest());
}
/**
* 鼠标点击世间
* @param event
* @param x
* @param y
* @param flags
* @param ustc
*/
void on_mouse(int event,int x,int y,int flags,void *ustc)//event鼠标事件代号,x,y鼠标坐标,flags拖拽和键盘操作的代号
{
static Point pre_pt = Point(-1,-1);//初始坐标
static Point cur_pt = Point(-1,-1);//实时坐标
char temp[16];
if (event == CV_EVENT_LBUTTONDOWN)//左键按下,读取初始坐标,并在图像上该点处划圆
{
sample.copyTo(img);//将原始图片复制到img中
sprintf(temp,"(%d,%d)",x,y);
pre_pt = Point(x,y);
putText(img,temp,pre_pt,FONT_HERSHEY_SIMPLEX,0.5,Scalar(0,0,0,255),1,8);//在窗口上显示坐标
circle(img,pre_pt,2,Scalar(255,0,0,0),CV_FILLED,CV_AA,0);//划圆
imshow("img",img);
}
else if (event == CV_EVENT_MOUSEMOVE && !(flags & CV_EVENT_FLAG_LBUTTON))//左键没有按下的情况下鼠标移动的处理函数
{
sample.copyTo(tmp);//将img复制到临时图像tmp上,用于显示实时坐标
sprintf(temp,"(%d,%d)",x,y);
cur_pt = Point(x,y);
putText(tmp,temp,cur_pt,FONT_HERSHEY_SIMPLEX,0.5,Scalar(0,0,0,255));//只是实时显示鼠标移动的坐标
imshow("img",tmp);
}
else if (event == CV_EVENT_MOUSEMOVE && (flags & CV_EVENT_FLAG_LBUTTON))//左键按下时,鼠标移动,则在图像上划矩形
{
sample.copyTo(tmp);
sprintf(temp,"(%d,%d)",x,y);
cur_pt = Point(x,y);
putText(tmp,temp,cur_pt,FONT_HERSHEY_SIMPLEX,0.5,Scalar(0,0,0,255));
rectangle(tmp,pre_pt,cur_pt,Scalar(0,255,0,0),1,8,0);//在临时图像上实时显示鼠标拖动时形成的矩形
imshow("img",tmp);
}
else if (event == CV_EVENT_LBUTTONUP)//左键松开,将在图像上划矩形
{
sample.copyTo(img);
sprintf(temp,"(%d,%d)",x,y);
cur_pt = Point(x,y);
putText(img,temp,cur_pt,FONT_HERSHEY_SIMPLEX,0.5,Scalar(0,0,0,255));
circle(img,pre_pt,2,Scalar(255,0,0,0),CV_FILLED,CV_AA,0);
rectangle(img,pre_pt,cur_pt,Scalar(0,255,0,0),1,8,0);//根据初始点和结束点,将矩形画到img上
imshow("img",img);
sample.copyTo(tmp);
//截取矩形包围的图像,并保存到dst中
int width = abs(pre_pt.x - cur_pt.x)/xscale;
int height = abs(pre_pt.y - cur_pt.y)/yscale;
if (width == 0 || height == 0)
{
printf("width == 0 || height == 0");
return;
}
dst = org(Rect(min(cur_pt.x,pre_pt.x)/xscale,min(cur_pt.y,pre_pt.y)/yscale,width,height));
namedWindow("dst");
imshow("dst",dst);
}
if (event == CV_EVENT_RBUTTONDOWN)
{
if(dst.empty())
return ;
else
{ //按下回车键保存
char temp[20];
char tempdesc[20]="descriptor.desc";
char path[256];
char pathdesc[256];
strcpy(path,dir);
strcpy(pathdesc,dir);
count++;
sprintf(temp,"%d.jpg",count);
strcat(path,temp);
strcat(pathdesc,tempdesc);
if(!imwrite(path,dst)){
printf("影像写入文件 %s 失败!\n",path);
count--;
}
else
{
printf("影像写入文件 %s 成功!\n",path);
FILE *fptr=fopen(pathdesc,"a+");
fprintf(fptr,"%s\n",path);
fclose(fptr);
}
cv::destroyWindow("dst");
dst.release();
}
}
}
/*
* 文件夹中文件编目情况获取
*/
bool file_catalog(char* file)
{
FILE *fptr=fopen(file,"r+");
if(fptr==NULL)
return false;
char line[256];
int num=0;
do{
fgets(line,256,fptr);
if(line!="")
num++;
}while(!feof(fptr));
count = num;
return true;
}
/*
* 将影像文件转换为二进制码
*/
bool tranImageToBinnary(char* fcatalog, char* fbinnary)
{
FILE* fcptr=fopen(fcatalog,"r+");
if(fcptr==NULL)
return false;
if(fbinnary==NULL)
return false;
FILE* fbptr=fopen(fbinnary,"wb+");
GDALAllRegister();
do{
char img[256];
fgets(img,256,fcptr);
if(img=="")
continue;
printf("转换影像:%s",img);
int len = strlen(img);
char* p = new char[len];
for(int i=0;i<len-1;++i)
p[i]=img[i];
p[len-1]='\0';
GDALDatasetH m_dataset = GDALOpen(p,GA_ReadOnly);
int xsize = GDALGetRasterXSize(m_dataset);
int ysize = GDALGetRasterYSize(m_dataset);
int bands = GDALGetRasterCount(m_dataset);
int cxsize = 64;
int cyszie = 64;
int *img_data = new int[cxsize*cyszie];
int bandIdx = 1;
//三个波段
/*
if(bands>=3)
{
for (int i = 0; i < 3; ++i) {
GDALRasterIO(GDALGetRasterBand(m_dataset,bandIdx),GF_Read,0,0,xsize,ysize,img_data,cxsize,cyszie,GDT_Int32,0,0);
fwrite(img_data,sizeof(int),cxsize*cyszie,fbptr);
bandIdx++;
}
}
else if(bands==2){
for (int i = 0; i < 3; ++i) {
GDALRasterIO(GDALGetRasterBand(m_dataset,bandIdx),GF_Read,0,0,xsize,ysize,img_data,cxsize,cyszie,GDT_Int32,0,0);
fwrite(img_data,sizeof(int),cxsize*cyszie,fbptr);
bandIdx++;
if(bandIdx>bands)
bandIdx=bandIdx%bands;
}
} else{
for (int i = 0; i < 3; ++i) {
GDALRasterIO(GDALGetRasterBand(m_dataset,bandIdx),GF_Read,0,0,xsize,ysize,img_data,cxsize,cyszie,GDT_Int32,0,0);
fwrite(img_data,sizeof(int),cxsize*cyszie,fbptr);
}
}
*/
//一个波段
GDALRasterIO(GDALGetRasterBand(m_dataset,bandIdx),GF_Read,0,0,xsize,ysize,img_data,cxsize,cyszie,GDT_Int32,0,0);
fwrite(img_data,sizeof(int),cxsize*cyszie,fbptr);
delete []img_data;img_data=NULL;
delete []p;p=NULL;
}while(!feof(fcptr));
return true;
}
int main()
{
//首先读取文件夹中记录的文件信息,确定编号
char* fcatalog = "/home/wuwei/Picture/Cut/descriptor.desc";
char* imgpath = "/home/wuwei/Picture/bridge_ly.jpg";
char* bin = "/home/wuwei/Picture/data.bin";
/*file_catalog(fcatalog);
org = imread(imgpath);
if(org.empty())
{
return -1;
}
//判断是否需要重采样
int xsize = 1080;
int ysize = 768;
if(org.cols>1080)
xscale = float(xsize)/float(org.cols);
if(org.rows>768)
yscale = float(ysize)/float(org.rows);
//重采样
resize(org,sample,Size(0,0),xscale,yscale);
sample.copyTo(img);
sample.copyTo(tmp);
namedWindow("img");//定义一个img窗口
setMouseCallback("img",on_mouse,0);//调用回调函数
imshow("img",sample);
cv::waitKey(0);*/
//转换
printf("影像重采样并转换为二进制文件...\n");
tranImageToBinnary(fcatalog,bin);
printf("转换完成!\n");
return 0;
}
|
aa58cf087bd9a5b25a466b2c709c0f6d9a388561
|
[
"Markdown",
"CMake",
"C++"
] | 3
|
Markdown
|
RemoteSensingFrank/ImageROICut
|
28caadb9b039655b4841f1f74cc8fb8bc27fc556
|
03f830ca7dbc2bdf5a05b05f2edf7550d767920a
|
refs/heads/master
|
<repo_name>CompassStudios/CompassStudios.github.io<file_sep>/secretdownload.php
<?php
session_start();
if (!isset($_SESSION['zalogowany']))
{
header('Location: thegatekeeper.php');
exit();
}
?>
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="hidden.css">
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@400;500&display=swap" rel="stylesheet">
</head>
<body>
<div id="titlebar">
<span class="red" style="letter-spacing: 1px">Welcome stranger, congratulations for ending The Game. You can now download closed alphas.</span>
<br/>
<a href="logout.php" style="color: white; text-decoration: none;">Safely exit</a>
</div>
<div id="content">
Password to archives is the same as the code :)
<br/><br/><br/>
<div class="game">
<a href="Driver.zip" style="color: white; text-decoration: none;">Driver</a>
</div>
<div class="game">
<a href="FNaU.zip" style="color: white; text-decoration: none;">Five Nights at Undertale</a>
</div>
<div class="game">
<a href="PAYDAY2.zip" style="color: white; text-decoration: none;">PAYDAY2 REMASTERED</a>
</div>
</div>
</body>
</html><file_sep>/codeengine.php
<?php
session_start();
if ((!isset($_POST['code'])))
{
header('Location: thegatekeeper.php');
exit();
}
require_once "dbconnect.php";
$connection = @new mysqli($host, $db_user, $db_password, $db_name);
if($connection->connect_errno!=0)
{
echo "Error: ".$connection->connect_errno . " Please email us about the error: <EMAIL>";
}
else
{
$code = $_POST['code'];
$code = htmlentities($code, ENT_QUOTES, "UTF-8");
$sql = "SELECT * FROM codes WHERE codes='$code'";
if ($result = @$connection->query(
sprintf("SELECT * FROM codes WHERE code='%s'",
mysqli_real_escape_string($connection,$code))))
{
$count = $result->num_rows;
if ($count>0)
{
$_SESSION['zalogowany'] = true;
$row = $result->fetch_assoc();
$_SESSION['code'] = $row['code'];
unset($_SESSION['blad']);
$result-> free_result();
header('Location: secretdownload.php');
}
else
{
header('Location: thegatekeeper.php');
}
}
$connection->close();
}
?>
|
a78739518d7f299095e584089f03148e5ad43ffe
|
[
"PHP"
] | 2
|
PHP
|
CompassStudios/CompassStudios.github.io
|
a39c1e527e03c484cb87550c39c2a821d61113db
|
5133d7eb6cacc09aede625d315ba5267d78d8bd7
|
refs/heads/master
|
<repo_name>Organic-Code/tty_screensaver<file_sep>/README.md
TTY Screensaver
========
A tiny tty screensaver, with bubbles (also works for xterms)
How to set (with zsh)
========
Compile with ``gcc screensaver.c -o screensaver``
Add the following to your .zshrc :
```
export TMOUT=xxx
TRAPALRM(){
/path/to/screensaver/screensaver $COLUMNS $LINES
}
```
Where 'xxx' is the toggle time in seconds
<br/>
I don't know how to set it on bash, but it might be possible
<file_sep>/screensaver.c
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <termios.h>
#include <stdbool.h>
#include <stdlib.h>
void visibleCursor(bool visible);
void setEcho(bool on);
char instantGetChar();
int main(int argc, char* argv[]);
void visibleCursor(bool visible)
{
if(visible)
printf("\033[?25h");
else
printf("\033[?25l");
}
void setEcho(bool on)
{
struct termios tty;
tcgetattr(STDIN_FILENO, &tty);
if (on)
tty.c_lflag |= ECHO;
else
tty.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &tty);
}
char instantGetChar()
{
char key;
struct termios original_settings, new_settings;
tcgetattr(0, &original_settings);
new_settings = original_settings;
new_settings.c_lflag &= ~ICANON;
new_settings.c_cc[VMIN] = 0;
new_settings.c_cc[VTIME] = 1;
tcsetattr(0, TCSANOW, &new_settings);
key = (char)getchar();
tcsetattr(0, TCSANOW, &original_settings);
return key;
}
int main(int argc, char* argv[]){
if (argc != 3)
return 1;
unsigned long col_nbr = strtoul(argv[1], NULL, 10) + 1;
unsigned long line_nbr = strtoul(argv[2], NULL, 10) + 1, i,j,k;
srand(time(NULL));
setEcho(false);
visibleCursor(false);
printf("\033[0m\033[34m");
for (i = line_nbr ; --i ;)
for(j = col_nbr ; --j ;)
if (rand()%550)
printf(".");
else
printf("\033[1mo\033[0m\033[34m");
do{
for( k = col_nbr; --k ;){
if (rand()%275)
printf(".");
else
{
if (rand()%2)
printf("*");
else
if (rand()%3)
printf("\033[1mo");
else
printf("\033[1m0");
printf("\033[0m\033[34m");
}
}
}while(instantGetChar() == -1);
system("clear");
setEcho(true);
visibleCursor(true);
return 0;
}
|
1abde91f99cba3d6fa065d42d3207069a2eda07f
|
[
"Markdown",
"C"
] | 2
|
Markdown
|
Organic-Code/tty_screensaver
|
54fa1058f2b94254f541fcdda42ce91a2474f6e7
|
4e523d1c7c9a864c84490f4fa7e96588722d0661
|
refs/heads/master
|
<repo_name>NShively/NewProject-Script<file_sep>/newproject.sh
generateWebTemplate()
{
echo "Web Template"
echo // <NAME>
echo // $title>> $FileName.md
echo // $(whoami) >> $FileName.md
echo // $(date) >> $FileName.md
echo // "Description" >> $FileName.md
}
generateCPPTemplate()
{
echo "Cpp Template"
echo // <NAME>
echo //$title >> $FileName.cpp
echo // $(whoami) >> $FileName.cpp
echo // $(date) >> $FileName.cpp
echo // "Description" >> $FileName.cpp
echo
echo "#include <iostream>
using namespace std;
int main()
{
cout << \"Hello World\";
return 0;
}" >> $FileName.cpp
}
generateReadme()
{
echo $title >> README.md
echo $(whoami) >> README.md
echo $(date) >> README.md
echo "===========" >> README.md
}
generateMakefile()
{
echo "$title.x: $FileName.o
g++ -g $FileName.o -o $title.x
$FileName.o:
g++ -g -c $FileName.cpp
run:
./$title.x
debug:
g++ -g $FileName.cpp
clean:
rm $title.x" > makefile
}
Git()
{
git init
for File in ~/scripts/*
do
git add *.cpp
git commit
done
}
echo "What type of project do you want to generate?"
echo "1) Web"
echo "2) CPP"
echo "Enter a number: "
read type
echo "You chose: $type"
echo "What is the project or lab name?"
read title
echo "What do you want the file to be named?"
read FileName
mkdir $title
cd $title
if [ $type == 2 ]; then
generateCPPTemplate
generateMakefile
elif [ $type == 1 ]; then
generateWebTemplate
else
echo "Invalid selection"
exit 1
fi
git init
git add -A
git commit -m "Initial Commit"
|
881d3fe9b36938279a4b1379e9df976f9c761256
|
[
"Shell"
] | 1
|
Shell
|
NShively/NewProject-Script
|
d12981437ba8ba83bfce16c03a04ba027852e571
|
a2a4a3b42c2cd1d929a305733ddb0bdecaee5c89
|
refs/heads/master
|
<repo_name>ameliepcd/TwitterPredictor<file_sep>/twitter_collect/résultat_analyse.py
import seaborn as sns
from textblob import *
sns.set(style="whitegrid")
results = sns.load_dataset('résultat_collection_sentiment')
#results doit être sous forme d'une dataframe
# Draw a nested barplot to show the repartition of neg,pos, and neu opinions for each candidate
g = sns.catplot(x="candidate", y="opinions", hue="type", data=results,
height=6, kind="bar", palette="muted")
g.despine(left=True)
g.set_ylabels('repartition of opinions')
<file_sep>/twitter_collect/test_monmodule.py
from __main__ import *
from pytest import *
def test_collect():
tweets = collect(Macron,candidat1)
data = transform_to_dataframe(tweets)
assert 'tweet_textual_content' in data.columns
print(test_collect())
<file_sep>/twitter_collect/__main__.py
from collect_candidate_actuality_tweets import *
from collect_candidate_tweet_activity import *
from Get_Queries import *
from Prise_en_main import *
from tweet_collect_whole import *
from twitter_connection_setup import *
hashtag_1=get_candidate_queries('hashtag_candidate_1.txt')
hashtag_2=get_candidate_queries('hashtag_candidate_2.txt')
keywords_1=get_candidate_queries('keywords_candidate_1.txt')
keywords_2=get_candidate_queries('keywords_candidate_2.txt')
candidat1=hashtag_1+keywords_1
candidat2=hashtag_2+keywords_2
#Pour chaque candidat et les demandes du clients associés, il retourne les réponses
# des différentes fonctions créées avant.
def collect(num_candidate,queries):
connexion= twitter_setup()
candidat_RT=get_retweets_of_candidate(num_candidate)
tweet_about_candidate=get_tweets_from_candidates_search_queries(queries)
candidate_replies=get_replies(num_candidate)
return(candidat_RT,tweet_about_candidate,candidate_replies)
<file_sep>/twitter_collect/Prise_en_main.py
#API SEARCH
from twitter_connection_setup import *
def collect():
connexion = twitter_setup()
tweets = connexion.search("<NAME>",language="french",rpp=100)
for tweet in tweets:
print(tweet)
#print(collect())
#-> affiche les tweets relatifs à un mot clé, ici avec <NAME> en français avec au max 100 tweets
#API USERS
def collect_by_user(user_id):
connexion = twitter_setup()
statuses = connexion.user_timeline(id = user_id, count = 200)
for status in statuses:
print(status.text)
return statuses
#-> affiche tous les tweets d'une personne, et au max 200
#API Streaming
#-> Si les clients dépassent un nombre limité de tentatives de connexion à l'API de
# diffusion en continu dans une fenêtre temporelle, ils recevront l'erreur 420.
# Ensuite, on peut filtrer les tweets cherchés
from textblob import TextBlob
from tweepy.streaming import StreamListener
class StdOutListener(StreamListener):
def on_data(self, data):
print(data)
return True
def on_error(self, status):
if str(status) == "420":
print(status)
print("You exceed a limited number of attempts to connect to the streaming API")
return False
else:
return True
def collect_by_streaming():
connexion = twitter_setup()
listener = StdOutListener()
stream=tweepy.Stream(auth = connexion.auth, listener=listener)
stream.filter(track=['<NAME>'])
#print(collect_by_user('Marsattacks23'))
#monty = TextBlob("We are no longer the Knights who say Ni. "
# "We are now the Knights who say Ekki ekki ekki PTANG.")
#print(monty.word_counts['ekki'])
<file_sep>/twitter_collect/Textblob.py
from tweet_collection import *
from textblob import TextBlob
from textblob import Word
def collect2():
connexion = twitter_setup()
tweets = connexion.search("<NAME>",language="french",rpp=1)
liste_tweets=[]
#Créer une liste des textes des tweets
for tweet in tweets :
liste_tweets.append(tweet.text)
return liste_tweets
def voc(tweets):
text=''
#à partir d'une liste de réponse d'API, récupère le texte des tweets dans dans une liste
text=''
for tweet in tweets:
text+=tweet.text
liste=TextBlob(text)
wordlist=liste.words
unique=[]
for word in wordlist:
w=Word(word)
#on récupère les tweets en forme de base, plus long que 2 lettres et pas trop fréquents
if w==w.lemmatize() and len(w)>2 and liste.word_counts[w]<=5 :
unique.append(w)
return(unique)
###A FINIR
#print(tweets)
#tweets=collect()
#print(voc(tweets))
from textblob.en import sentiment as pattern_sentiment
from textblob.tokenizers import word_tokenize
from textblob.decorators import requires_nltk_corpus
from textblob.base import BaseSentimentAnalyzer, DISCRETE, CONTINUOUS
#def opinion(tweet):
#prend en entrée le résultat d'une recherche API concernant un candidat
def analize_sentiment(tweets):
'''
Donne le sentiment d'un tweet donné
'''
pos=[]
neg=[]
neu=[]
for tweet in tweets:
analysis = TextBlob(tweet)
#On regarde pour chaque tweet, si il est positif au négatif, sachant que l'échelle
# va de 1 (positif)à -1 (négatif)
if analysis.sentiment.polarity > 0.2:
pos.append(analysis.sentiment.polarity)
elif analysis.sentiment.polarity < -0.2:
neg.append(analysis.sentiment.polarity)
else:
neu.append(analysis.sentiment.polarity)
print("Percentage of positive tweets: {}%".format(len(pos)*100/len(tweets)))
print("Percentage of neutral tweets: {}%".format(len(neu)*100/len(tweets)))
print("Percentage de negative tweets: {}%".format(len(neg)*100/len(tweets)))
#analize_sentiment(collect2())
<file_sep>/twitter_collect/tweet_collection.py
import json
import pandas as pd
def store_tweet(tweets,file_name):
#prend en entrée le résultat d'une recherche API
#On garde pour chacun le tweet, le hashtag, la date, à quel candidat il renvoie, l'ID du tweet
#Création d'un fichier fait d'une liste de dico contenant les différents tweets
T=[]
for tweet in tweets:
current_tweet={}
current_tweet['tweet']=tweet.text
current_tweet['Date']=str(tweet.created_at)
current_tweet['User_ID']=tweet.id
current_tweet['reply']=tweet.in_reply_to_status_id
current_tweet['likes']=tweet.favorite_count
T.append(current_tweet)
#enregistrement du fichier dans le disque dur sous le nom de file_name
with open(file_name, 'w', encoding='utf-8') as f:
json.dump(T,f)
from twitter_connection_setup import *
#####Renvoie une liste de tweet
def collect3():
connexion = twitter_setup()
tweets = connexion.search("<NAME>",language="french",rpp=1)
liste_tweets=[]
#Créer une liste des tweets correspondant à la collecte : on a donc une liste de dictionnaire
for tweet in tweets :
liste_tweets.append(tweet)
return liste_tweets
def make_dataframe(status):
#Status est le résultat d'une recherche API
Tweet=[]
Date=[]
User_ID=[]
Likes=[]
RT=[]
#### Création et remplissage des colonnes du futur tableau à partir des tweets donnés
for tweet in status:
Tweet.append(tweet.text)
Date.append(str(tweet.created_at))
User_ID.append(tweet.id)
Likes.append(int(tweet.favorite_count))
RT.append(int(tweet.retweet_count))
###Création du tableau avec les colonnes formées avant
S=pd.DataFrame({'Tweet': Tweet ,
'Date': Date ,
'User_ID': User_ID,
'likes': Likes,
'RT': RT})
return(S)
###TEST
#store_tweet(tweets,'test_1_EmmanuelMacron')
<file_sep>/twitter_collect/recup_tweet.py
from twitter_collect.twitter_connection_setup import *
#On donne la liste des recherches de tweets à faire
liste_query=['<NAME>','Emmanuel','Macron','Emmanuel AND Macron','#EnMarche','Brigitte AND Macron','Brigitte AND Emmanuel']
def collect(queries):
connexion = twitter_setup()
liste_tweets=[]
for i in range (len(liste_query)):
tweets = connexion.search(queries[i],language="french",rpp=50)
#Créer une liste des tweets correspondant à la collecte : on a donc une liste de dictionnaire
for tweet in tweets :
liste_tweets.append(tweet)
return liste_tweets
def collect_by_user(user_id):
connexion = twitter_setup()
statuses = connexion.user_timeline(id = user_id, count = 200)
for status in statuses:
print(status.text)
#print(collect_by_user(''))
print(collect(liste_query))
<file_sep>/twitter_collect/Get_Queries.py
def get_candidate_queries(file_path):
"""
Generate and return a list of string queries for the search Twitter API from the file file_path_num_candidate.txt
:param num_candidate: the number of the candidate
:param file_path: the path to the keyword and hashtag
files
:param type: type of the keyword, either "keywords" or "hashtags"
:return: (list) a list of string queries that can be done to the search API independently
"""
mon_fichier = open(file_path,'r')
queries=[]
for line in mon_fichier:
a=line.replace('\n','')
queries.append(a)
return(queries)
#print(get_candidate_queries('hashtag_candidate_2.txt'))
<file_sep>/twitter_collect/credentials.py
# Twitter app access keys for @user
#Consume :
CONSUMER_KEY = 'zUOvACJfiqo5gPTTeMhxlLffd'
CONSUMER_SECRET = '<KEY>'
#Access :
ACCESS_TOKEN = '<KEY>'
ACCESS_SECRET = '<KEY>'
<file_sep>/twitter_collect/collect_candidate_tweet_activity.py
#On recupère tous les tweets des membres de l'équipe du candidat et du candidat par leurs noms d'utilisateurs
## On récupère tous les RT et les Reply des tweets des candidates et son équipe
from twitter_connection_setup import *
from recup_tweet import *
def get_replies(user_id):
connexion = twitter_setup()
replies=[]
#recupere les messages recents du candidat user_id
for full_tweet in connexion.user_timeline(id = user_id,language="fr",rpp=100):
print(full_tweet.text)
#query pour retrouver des tweets repondant a l'utilisateur used_id
query = 'to:'+user_id
print(query)
for tweet in connexion.search(q=query, since_id=992433028155654144, result_type='recent',timeout=999999):
print(tweet.text)
#si le tweet renvoye par la requete possede un champs "in reply_to__status_id_str" cest a dire si cest une reponse a un tweet
if hasattr(tweet, 'in_reply_to_status_id_str'):
# si c'ets une reponse au tweet actuel (full_tweet) du candidat
if (tweet.in_reply_to_status_id_str==full_tweet.id_str):
replies.append(tweet.text)
print(tweet.text)
#print(get_replies('EmmanuelMacron'))
#Pour un nom de candidat donné, affiche les tweets du candidats
def get_retweets_of_candidate(num_candidate):
connexion = twitter_setup()
statuses = connexion.user_timeline(id = num_candidate, count = 200)
tweet_du_candidat=[]
#On crée la liste des tweets du candidat concerné
for status in statuses:
tweet_du_candidat.append(status.text)
#Pour chacun des tweets du candidats, on l'imprime et on affiche après les RT
for i in range (len(tweet_du_candidat)):
tweets = connexion.search(tweet_du_candidat[i],language="french",rpp=50)
print(tweet_du_candidat)
for tweet in tweets:
print(tweet.text)
#print(get_retweets_of_candidate('EmmanuelMacron'))
<file_sep>/twitter_collect/collect_candidate_actuality_tweets.py
#on récupère les tweets sur un candidat et sur son équipe en direct :
# avec l'API STREAMING
def get_tweets_from_candidates_search_queries(queries):
connexion = twitter_setup()
for i in range (len(queries)):
tweets = connexion.search(queries[i],language="french",rpp=100)
for tweet in tweets:
print(tweet.text)
<file_sep>/twitter_collect/tweet_analysis.py
import numpy as np
import matplotlib.pyplot as plt
from tweet_collection import *
from recup_tweet import *
tweets=collect()
data=make_dataframe(tweets)
print(data)
def more_likes(data):
#à partir d'un tableau de tweets, récupère le tweet avec le + de like
likes_max=np.max(data['likes'])
#Récupère la ligne complète correspondant à ce tweet
max_like= data[data.likes == likes_max].index[0]
print("The tweet with more likes is: \n{}".format(data['Tweet'][max_like]))
print("Number of likes: {}".format(max_like))
def more_RT(data):
rt_max = np.max(data['RT'])
rt = data[data.RT == rt_max].index[0]
#à partir d'un tableau de tweets, récupère le tweet avec le + de like
print("The tweet with more retweets is: \n{}".format(data['Tweet'][rt]))
print("Number of retweets: {}".format(rt_max))
print(more_likes(data))
###on fait une série avec les différents nb de likes pour les différents dates, idem avec les RT
tfav = pd.Series(data=data['likes'].values, index=data['Date'])
tret = pd.Series(data=data['RT'].values, index=data['Date'])
# Likes vs retweets visualization:
tfav.plot(figsize=(16,4), label="likes", legend=True)
tret.plot(figsize=(16,4), label="Retweets", legend=True)
plt.show()
|
3c72c9438e64b6f1aa8b688e38f6d508d6eb92a3
|
[
"Python"
] | 12
|
Python
|
ameliepcd/TwitterPredictor
|
1c1c1b4f1eaad32b59be231e39c09d61ad624a98
|
7162f9bacdb3d744cbc15cf31ecff3e4050e65aa
|
refs/heads/master
|
<file_sep>function takeANumber(katzDeliLine, name) {
katzDeliLine.push(name)
var arrayIndex = (katzDeliLine.indexOf(name) + 1);
var numberInLine = ("Welcome, " + name + ". You are number " + arrayIndex + " in line.");
return numberInLine
}
function nowServing(katzDeliLine, name) {
if (katzDeliLine[0] != undefined) {
var firstInLine = ("Currently serving " + katzDeliLine[0] + ".");
katzDeliLine.shift();
return firstInLine
} else {
var emptyLine = "There is nobody waiting to be served!";
return emptyLine
}
}
function currentLine(line) {
var newLineArray = [];
var newline = "The line is currently: ";
if (line[0] != undefined) {
for (let i = 0; i < line.length; i++) {
//lineIndex = line.indexOf(i)
newLineArray.push(" " + (i+1) + ". " + line[i])
}
return "The line is currently:" + newLineArray
} else {
var emptyLine = "The line is currently empty.";
return emptyLine
}
}
|
b1540e57e92c4a523af6a2f065d16b62465a38bb
|
[
"JavaScript"
] | 1
|
JavaScript
|
DavidRussPrater/js-deli-counter-bootcamp-prep-000
|
89d8ce33b928d72ce5dbd1a7b209551a4266609f
|
d76ff3c712b43584ac2f32e68f70df68604fbc36
|
refs/heads/master
|
<file_sep>import React, { Component } from "react";
import StockContainer from "./StockContainer";
import PortfolioContainer from "./PortfolioContainer";
import SearchBar from "../components/SearchBar";
class MainContainer extends Component {
constructor() {
super();
this.state = {
allStocks: [],
displayedStocks: [],
portfolio: [],
};
}
componentDidMount() {
fetch("http://localhost:3000/stocks")
.then((resp) => resp.json())
.then((json) => {
this.setState({
allStocks: json,
displayedStocks: json
});
});
}
buyStock = (stock) => {
if (!this.state.portfolio.includes(stock)) {
this.setState((prevState) => ({
portfolio: [...prevState.portfolio, stock],
}));
}
};
sellStock = (soldStock) => {
this.setState((prevState) => ({
portfolio: prevState.portfolio.filter((stock) => stock !== soldStock),
}));
};
handleFilter = (value) => {
this.setState({
displayedStocks: this.state.allStocks.filter((stock) => stock.type === value)
})
}
handleSort = (value) => {
if (value === "Alphabetically"){
this.setState((prevState) => ({
displayedStocks: prevState.displayedStocks.sort((a, b) => (a.name > b.name) ? 1 : -1)
}))
} else {
this.setState((prevState) => ({
displayedStocks: prevState.displayedStocks.sort((a, b) => (a.price < b.price) ? 1: -1)
}))
}
}
render() {
return (
<div>
<SearchBar
handleFilter={this.handleFilter}
handleSort={this.handleSort}
/>
<div className="row">
<div className="col-8">
<StockContainer
stocks={this.state.displayedStocks}
buyStock={this.buyStock}
portfolio={this.state.portfolio}
/>
</div>
<div className="col-4">
<PortfolioContainer
portfolio={this.state.portfolio}
sellStock={this.sellStock}
/>
</div>
</div>
</div>
);
}
}
export default MainContainer;
|
77b37d739fa116c8755360d465ca461523a34e09
|
[
"JavaScript"
] | 1
|
JavaScript
|
samgorick/React-Stocks-chicago-web-033020
|
bae482b79d9728e9f838ced197fc6cba5049fa68
|
c407e7263841d8266cfcec19a9aed2cf1f4c909a
|
refs/heads/master
|
<repo_name>bcotton/FileSetInputFormat<file_sep>/buildfile
# Generated by Buildr 1.4.6, change to your liking
# Version number for this release
VERSION_NUMBER = "1.0.0"
# Group identifier for your projects
GROUP = "com.twitter.twadoop"
# Specify Maven 2.0 remote repositories here, like this:
repositories.remote << "http://www.ibiblio.org/maven2/"
COMPILE_DEPS = 'com.google.collections:google-collections:jar:1.0',
'org.slf4j:slf4j-log4j12:jar:1.6.1',
'org.apache.hadoop:hadoop-core:jar:0.20.205.0',
'org.slf4j:slf4j-api:jar:1.6.1'
desc "The Filesetinputformat project"
define "FileSetInputFormat" do
project.version = VERSION_NUMBER
project.group = GROUP
compile.with COMPILE_DEPS
test.with COMPILE_DEPS
package(:jar, :id => 'filesetinputformat')
end
<file_sep>/README.md
An input format for processing individual Path objects one at a time. Useful for distributing large jobs that are inherently single-machine across the
entire cluster. Even if they still run on one machine, this way they get given to an under-utilized node at runtime, and there is built-in resilience to
task failure.
This input format takes a set of paths and produces a separate input split for each one. If you need to, for example, unzip a collection of five files
in HDFS, that unzipping has to happen on a single machine per file. But the set of five files can at least all be unzipped on different machines. Using
this input format lets you process each file as you wish in your mapper.
1. In your main/run method of your Hadoop job driver class, add
<pre><code>
Job job = new Job(new Configuration());
...
job.setInputFormatClass(FileSetInputFormat.class);
FileSetInputFormat.addPath("/some/path/to/a/file");
FileSetInputFormat.addPath("/some/other/path/to/a/file");
// Also see FileSetInputFormat.addAllPaths(Collection<Path> paths);
</code></pre>
2. Then, make your mapper take a Path as the key and a NullWritable as the value:
<pre><code>
public static class MyMapper extends Mapper<Path, NullWritable, ..., ...> {
protected void map(Path key, NullWritable value, Context context) throws IOException, InterruptedException {
// Do something with the path, e.g. open it and unzip it to somewhere.
...
}
}
</code></pre>
The Path keys are the same paths passed in to FileSetInputFormat.addPath and FileSetInputFormat.addAllPaths. Duplicates are stripped, and one
InputSplit is generated per unique Path. That's it!
<file_sep>/src/main/java/com/twitter/twadoop/mapreduce/input/FileSetInputSplit.java
package com.twitter.twadoop.mapreduce.input;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Arrays;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.InputSplit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileSetInputSplit extends InputSplit implements Writable {
private static final Logger LOG = LoggerFactory.getLogger(FileSetInputSplit.class);
private Path path_;
private Configuration conf_;
public FileSetInputSplit() {
conf_ = new Configuration();
}
public FileSetInputSplit(Path path, Configuration conf) {
path_ = path;
conf_ = conf;
}
public Path getPath() {
return path_;
}
@Override
public long getLength() throws IOException, InterruptedException {
return 1;
}
@Override
public String[] getLocations() throws IOException, InterruptedException {
FileSystem fs = FileSystem.get(conf_);
FileStatus fileStatus = fs.getFileStatus(path_);
BlockLocation[] blockLocations = fs.getFileBlockLocations(fileStatus, 0, fileStatus.getLen());
Set<String> hosts = Sets.newHashSet();
for (BlockLocation bl: blockLocations) {
hosts.addAll(Arrays.asList(bl.getHosts()));
}
return hosts.toArray(new String[0]);
}
public void write(DataOutput output) throws IOException {
output.writeUTF(path_.toString());
conf_.write(output);
}
public void readFields(DataInput input) throws IOException {
path_ = new Path(input.readUTF());
conf_.readFields(input);
}
}
|
8a513ef8376886d2e5cdef3f19602e9e330d5caf
|
[
"Markdown",
"Java",
"Ruby"
] | 3
|
Ruby
|
bcotton/FileSetInputFormat
|
6248eec6a7ab049bda9c6825e34ee8988f569406
|
6118701ad923485d524d8fc29e03bd641474e555
|
refs/heads/master
|
<repo_name>itcarrillo/GifMe<file_sep>/src/routes/views.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.render('home');
});
router.get('/result', (req, res) => {
res.render('result', req.body);
});
router.get('/search', (req, res) => {
res.render('search');
});
router.get('/searchByUrl', (req, res) => {
res.render('searchbyurl');
});
module.exports = {router: router};<file_sep>/src/controller/giphy.js
const apiKey = process.env.giphy_api_token;
const apiUrl = 'http://api.giphy.com';
const request = require('request');
function getGifRendered(req, res) {
let output;
const query = req.body.string;
const url = apiUrl + '/v1/gifs/search?q=' + query + '&api_key=' + apiKey + '&limit=30';
request(url, (error, response, body) => {
if (error) {
console.log('Error');
res.send(error);
}
else {
const rando = parseInt(Math.random() * 30);
try {
output = JSON.parse(body).data[rando].images.original.url;
res.render('result', {url: output});
}
catch (error) {
res.render('result', {url: 'https://media.giphy.com/media/9J7tdYltWyXIY/giphy.gif'});
}
}
});
}
function getGifUrl(req, res) {
console.log("Test Url");
let output;
const query = req.body.string;
const url = apiUrl + '/v1/gifs/search?q=' + query + '&api_key=' + apiKey + '&limit=30';
request(url, (error, response, body) => {
if (error) {
console.log('Error');
res.send(error);
}
else {
const rando = parseInt(Math.random() * 30);
output = JSON.parse(body).data[rando].images.downsized.url;
res.json({url: output, emotion: query});
}
});
}
module.exports = {getGifRendered, getGifUrl};
<file_sep>/src/routes/api.js
/*jshint esversion: 6 */
// Dependencies
const express = require('express');
const router = express.Router();
const apiHome = require('../controller/apiHome');
const clarifAi = require('../controller/clarifAi');
const giphy = require('../controller/giphy');
const twilio = require('../controller/twilio');
// API
router.get('/', apiHome.getApi);
router.post('/', apiHome.postApi);
router.post('/parseImageUrl', clarifAi.parseImageUrl);
router.post('/parseImageUrlTwilio', clarifAi.parseImageUrlTwilio);
router.post('/parseImageBase64', clarifAi.parseImageBase64);
router.post('/giphy', giphy.getGifRendered);
router.post('/giphyUrl', giphy.getGifUrl);
router.post('/twilio', twilio.receivePicture);
// Return Router
module.exports = router;
<file_sep>/README.md
# GifMe - hackNY Fall '17
## Description
Emotion recognition web app developed by first-timers at the hackNY fall '17 hackathon that integrates the Clarifai Machine
Learning API, Twilio API for MMS functionality, and Giphy API for retrieving gifs.
## URL
<http://gifmenow.com>
## Install
```
npm install
```
## Start
```
npm start
```
<file_sep>/src/controller/clarifAi.js
const Clarifai = require('clarifai');
const request = require('request');
const validUrl = require('valid-url');
const app = new Clarifai.App({
apiKey: process.env.clarifai_api_token
});
function getGreater(data) {
var maxIterator, maxValue = 0;
for (var i in data) {
if(maxValue < data[i].value){
maxValue = data[i].value;
maxIterator = i;
}
}
return data[maxIterator];
}
function parseClarafaiObject(object) {
return object.name;
}
exports.parseImageUrl = (req,res) => {
if (!validUrl.isUri(req.body.url)) {
res.render('result', {url: 'https://media.giphy.com/media/9J7tdYltWyXIY/giphy.gif'});
}
else {
// predict the contents of an image by passing in a url
app.models.predict('GifMe', req.body.url).then(
function(response) {
// console.log(response);
const emotion = parseClarafaiObject(getGreater(response.outputs[0].data.concepts));
console.log("emotion " + emotion);
var request = require('request');
request.post({
url: 'http://localhost:3000/api/giphy',
form: {string: emotion}
}, function(error, response, body){
res.send(body);
});
},
function(err) {
console.error(err);
res.json({Error: err});
});
}
}
exports.parseImageUrlTwilio = (req,res) => {
// predict the contents of an image by passing in a url
app.models.predict('GifMe', req.body.url).then(
function(response) {
// console.log(response);
const emotion = parseClarafaiObject(getGreater(response.outputs[0].data.concepts));
console.log("emotion " + emotion);
var request = require('request');
request.post({
url: 'http://localhost:3000/api/giphyUrl',
form: {string: emotion}
}, function(error, response, body){
// console.log(body);
res.send(body);
});
}, function(err) {
console.error(err);
res.json({Error: err});
});
}
exports.parseImageBase64 = (req,res) => {
// console.log("Over here");
// console.log(req.body.base64);
// predict the contents of an image by passing in a url
app.models.predict('GifMe', {base64: req.body.base64}).then(
function(response) {
// console.log(response);
const emotion = parseClarafaiObject(getGreater(response.outputs[0].data.concepts));
console.log("emotion " + emotion);
var request = require('request');
request.post({
url: 'http://localhost:3000/api/giphy',
form: { string: emotion }
}, function(error, response, body){
res.send(body);
});
// request.post('/api/giphy').form({string:emotion});
// res.json({Response: emotion});
},
function(err) {
console.error(err);
res.json({Error: err});
}
);
}
|
6deb6e5145ec367adf6a0bd5cb1643046864c4b1
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
itcarrillo/GifMe
|
3f0eff9bca6e1e3919e91dd57f7a7156ea4a6d6b
|
d9f42d3864ee2ebf9d3e2352d5169a1c989b0ded
|
refs/heads/master
|
<file_sep>#include<stdio.h>
#define M 1000000007
const int MAX = 10000001;
long long f[MAX] = {0};
long long fib(int n)
{
if (n == 0)
return 0;
if (n == 1 || n == 2)
return f[n]=1;
if (n<=10000000&&f[n])
return f[n];
int k = (n & 1)? (n+1)/2 : n/2;
long long res=(n & 1)? ((fib(k)%M*fib(k)%M)%M + (fib(k-1)%M*fib(k-1)%M)%M)%M: (((2*fib(k-1)%M)%M + fib(k)%M)%M*fib(k)%M)%M;
if(n<=10000000){
f[n]=res;
}
return res;
}
long long calculateSum(int n)
{
return (fib(n+2)%M - 1+M)%M;
}
int main()
{
int n,m,t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
printf("%llu\n",(calculateSum(m)%M-calculateSum(n-1)%M+M)%M);
}
return 0;
}
<file_sep>import java.io.*;
import java.util.*;
public class HLD
{
static int ithp[][]=new int[100200][18];
static int parents[]=new int[100200];
static int[] base=new int[100200];
static int[] posinbase=new int[100200];
static int chainhead[]=new int[100200];
static int[] chainbelong=new int[100200];
static int[] chainend=new int[100200];
static int chainno=0;
static int ptr=0;
static int[] depth=new int[100200];
static int[] subtree=new int[100200];
static boolean vis2[]=new boolean[100200];
static boolean vis1[]=new boolean[100200];
static int LCA(int a, int b)
{
if(depth[a]<depth[b])
{
return LCA(b,a);
}
int diff=depth[a]-depth[b];
int u=a;
int v=b;
for(int i=0;i<17;i++){
if((diff&(1<<i))>0){
u=ithp[u][i];
}
}
if(u==v){
return u;
}
for(int i=17;i>=0;i--)
{
if(ithp[u][i]!=ithp[v][i])
{
u=ithp[u][i];
v=ithp[v][i];
}
}
return ithp[u][0];
}
static void findd(Vector<Vector<Integer>> ve)
{
int n=ve.size();
boolean vis[]=new boolean[n+1];
Queue<Integer> st=new LinkedList<Integer>();
st.add(1);
vis[1]=true;
while(!st.isEmpty())
{
int e=st.poll();
Vector<Integer> v=ve.get(e-1);
int s=v.size();
int d=depth[e];
for(int i=0;i<s;i++)
{
if(!vis[v.get(i)])
{
depth[v.get(i)]=d+1;
parents[v.get(i)]=e;
st.add(v.get(i));
vis[v.get(i)]=true;
}
}
}
}
static int findss(int e,Vector<Vector<Integer>> ve)
{
vis2[e]=true;
Vector<Integer> v=ve.get(e-1);
int s=v.size();
for(int i=0;i<s;i++)
{
if(!vis2[v.get(i)])
{
subtree[e]=subtree[e]+findss(v.get(i),ve);
}
}
return subtree[e];
}
static void hld(int cur, Vector<Vector<Integer>> vee)
{
if(chainhead[chainno]==-1)
{
chainhead[chainno]=cur;
}
vis1[cur]=true;
posinbase[cur]=ptr;
base[ptr++]=cur;
chainbelong[cur]=chainno;
if(subtree[cur]==1)
{
chainend[chainno]=cur;
return;
}
Vector<Integer> ve=vee.get(cur-1);
int size=ve.size();
int max=Integer.MIN_VALUE;
int n=-1;
for(int i=0;i<size;i++)
{
if(subtree[ve.get(i)]>=max&&(!vis1[ve.get(i)]))
{
n=ve.get(i);
max=subtree[ve.get(i)];
}
}
if(n!=(-1))
{
hld(n,vee);
}
for(int i=0;i<size;i++)
{
if(ve.get(i)!=n&&(!vis1[ve.get(i)]))
{
chainno++;
hld(ve.get(i),vee);
}
}
}
public static void main(String[] args)
{
Reader sc=new Reader(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
Bit bit=new Bit(n);
Arrays.fill(chainhead, -1);
Vector<Vector<Integer>> ve=new Vector<Vector<Integer>>();
for(int i=0;i<n;i++)
{
ve.add(new Vector<Integer>());
subtree[i+1]=1;
}
int u,v;
for(int i=1;i<n;i++)
{
u=sc.nextInt();
v=sc.nextInt();
ve.get(u-1).add(v);
ve.get(v-1).add(u);
}
findd(ve);
findss(1,ve);
hld(1,ve);
for(int i=1;i<=n;i++)
{
ithp[i][0]=parents[i];
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=17;j++)
{
ithp[i][j]=ithp[ithp[i][j-1]][j-1];
}
}
int a,b,lca;
while(m-->0)
{
a=sc.nextInt();
b=sc.nextInt();
lca=LCA(a,b);
//System.out.println(lca);
while(chainbelong[a]!=chainbelong[lca])
{
int chain=chainbelong[a];
int head=chainhead[chain];
bit.update(posinbase[head], posinbase[a], 1);
a=parents[head];
}
bit.update(posinbase[lca], posinbase[a], 1);
while(chainbelong[b]!=chainbelong[lca])
{
int chain=chainbelong[b];
int head=chainhead[chain];
bit.update(posinbase[head], posinbase[b], 1);
b=parents[head];
}
bit.update(posinbase[lca], posinbase[b], 1);
bit.update(posinbase[lca], posinbase[lca],-1);
}
long max=Long.MIN_VALUE;
long value;
for(int i=0;i<n;i++){
value=bit.valueAt(i);
if(value>0){
max=Math.max(max, value);
}
}
System.out.println(max);
}
}
class Bit
{
long[] bit;
int n;
Bit(int n)
{
bit=new long[n+1];
this.n=n;
}
void update(int p,long v)
{
p=p+1;
for(;p<=n;p+=(p&(-p)))
{
bit[p]=(bit[p]+v);
}
}
void update(int l,int r,long v) // Adds v from l to r
{
update(l,v);
update(r+1,-v);
}
long valueAt(int b)
{
b=b+1;
long sum=0;
for(;b>0;b-=b&(-b))
{
sum=(sum+bit[b]);
}
return sum;
}
}
class Reader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public Reader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
<file_sep>import java.util.*;
import java.io.*;
class Q
{
int l,r,ind;
Q(int l,int r,int ind)
{
this.l=l;
this.r=r;
this.ind=ind;
}
}
public class Test
{
static int L,R,anss;
static int[] A=new int[1000002];
static int cont[]=new int[1000002];
static int ans[]=new int[100002];
static void remove( int i )
{
cont[ A[i] ]--;
if( cont[ A[i] ] == 0 )
anss--;
}
static void add( int i){
cont[ A[i] ]++;
if( cont[ A[i] ] == 1 )
anss++;
}
static int query(int i,Q que[]){
while(L<que[i].l)
{
remove(L);
L++;
}
while(L>que[i].l)
{
L--;
add(L);
}
while(R<que[i].r)
{
R++;
add(R);
}
while( R > que[i].r){
remove( R );
R--;
}
return anss;
}
public static void main(String args[]) throws IOException
{
Reader sc=new Reader();
int n=sc.nextInt();
int sq=(int)Math.sqrt(n);
for(int i=1;i<=n;i++)
{
A[i]=sc.nextInt();
}
int q=sc.nextInt();
Q que[]=new Q[q+1];
que[0]=new Q(-100000,-10000,0);
for(int i=1;i<=q;i++)
{
que[i]=new Q(sc.nextInt(),sc.nextInt(),i);
}
Arrays.sort(que,1, q, new quec(sq));
for(int i=1;i<=q;i++)
{
ans[que[i].ind]=query(i,que);
}
StringBuffer sb=new StringBuffer("");
for(int i=1;i<=q;i++)
{
sb.append(ans[i]+"\n");
}
System.out.println(sb);
}
}
class quec implements Comparator<Q>{
int sq;
quec(int sq){
this.sq=sq;
}
@Override
public int compare(Q o1, Q o2) {
if(o1.l/sq!=o2.l/sq)
{
return o1.l/sq-o2.l/sq;
}
return o1.r-o2.r;
}
}
class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
<file_sep>import java.util.*;
import java.io.*;
class Edge
{
int a, b, c;
Edge(int a,int b,int c)
{
this.a=a;
this.b=b;
this.c=c;
}
}
class subset
{
int parent,rank;
}
class EdgeC implements Comparator<Edge>
{
@Override
public int compare(Edge o1, Edge o2)
{
return o1.c-o2.c;
}
}
class Main
{
static int find (subset subsets[],int i)
{
if (subsets[i].parent != i)
return find(subsets, subsets[i].parent);
return i;
}
static void Union (subset subset[],int x,int y){
int xroot=find(subset,x);
int yroot=find(subset,y);
if (subset[xroot].rank < subset[yroot].rank){
subset[xroot].parent = yroot;}
else if (subset[xroot].rank > subset[yroot].rank){
subset[yroot].parent = xroot;}
else
{
subset[yroot].parent = xroot;
subset[xroot].rank++;
}
}
public static void main(String args[]) throws IOException
{
Reader sc=new Reader();
int t=sc.nextInt();
while(t-->0)
{
int p=sc.nextInt();
int n=sc.nextInt();
int m=sc.nextInt();
PriorityQueue<Edge> pq=new PriorityQueue<Edge>(new EdgeC());
subset subset[]=new subset[n+1];
for(int i=0;i<=n;i++)
{
subset[i]=new subset();
subset[i].parent=i;
subset[i].rank=0;
}
while(m-->0)
{
pq.add(new Edge(sc.nextInt(),sc.nextInt(),sc.nextInt()));
}
int c=0;
long sum=0;
while(c<(n-1))
{
Edge e=pq.poll();
if(find(subset,e.a)!=find(subset,e.b))
{
sum=sum+e.c;
c++;
Union(subset,e.a,e.b);
}
}
System.out.println(sum*p);
}
}
}
class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
<file_sep>import java.util.*;
class Bit
{
static long M=1000000007;
long[] bit;
int n;
Bit(int n)
{
bit=new long[n+1];
this.n=n;
}
void update(int p,long v)
{
p=p+1;
for(;p<=n;p+=(p&(-p)))
{
bit[p]=(bit[p]%M+v%M+M)%M;
}
}
void update(int l,int r,long v) // Adds v from l to r
{
update(l,v);
update(r+1,-v);
}
long valueAt(int b)
{
b=b+1;
long sum=0;
for(;b>0;b-=b&(-b))
{
sum=(sum%M+bit[b]%M+M)%M;
}
return sum;
}
}
public class JavaApplication5
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
int m=sc.nextInt();
int[] q=new int[m];
int[] l=new int[m];
int[] r=new int[m];
for(int i=0;i<m;i++){
q[i]=sc.nextInt();
l[i]=sc.nextInt();
r[i]=sc.nextInt();
}
Bit qc=new Bit(m);
qc.update(0, m-1, 1);
for(int i=(m-1);i>=0;i--)
{
if(q[i]==2){
qc.update(l[i]-1, r[i]-1,qc.valueAt(i));
}
}
Bit ar=new Bit(n);
ar.update(0, n-1, 0);
for(int i=0;i<m;i++)
{
if(q[i]==1)
{
ar.update(l[i]-1, r[i]-1, qc.valueAt(i));
}
}
for(int i=0;i<n;i++)
{
System.out.print(ar.valueAt(i)+" ");
}
System.out.println();
}
}
}
<file_sep>#include<bits/stdc++.h>
#define m 1000000007
using namespace std;
int possibleways(int n , int* arr)
{
long long sum[n];
long long pd[n];
long long ans[n];
sum[0]=arr[0];
for(int i=1;i<n;i++){
sum[i]=arr[i]+sum[i-1];
}
pd[0]=0;
pd[1]=0;
pd[2]=arr[0];
for(int i=3;i<n;i++){
pd[i]=arr[i-2]+pd[i-1]+sum[i-3]; //DP
}
ans[0]=arr[0];
ans[1]=arr[1];
ans[2]=arr[2]-arr[0];
for(int i=3;i<n;i++){
ans[i]=arr[i]*(i*sum[i]+arr[i]-arr[i-2]-pd[i-1]-sum[i-3]); //DP
}
int res=0;
for(int i=0;i<n;i++){
res=(res%m+ans[i]%m)%m;
}
return res;
}
int main(){
int output = 0;
int ip1_size = 0;
int ip1_i;
scanf("%d\n", &ip1_size);
int ip1[ip1_size];
for(ip1_i = 0; ip1_i < ip1_size; ip1_i++) {
int ip1_item;
scanf("%d", &ip1_item);
ip1[ip1_i] = ip1_item;
}
output = possibleways(ip1_size,ip1);
printf("%d\n", output);
return 0;
}
<file_sep>import java.io.*;
import java.util.*;
public class Test
{
public static void main(String args[] ) throws Exception
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
int m=sc.nextInt();
String arr[][]=new String[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
arr[i][j]=sc.next();
}
}
StringBuffer sb=new StringBuffer("");
int c=1;
String f=sc.next();
boolean vis[][]=new boolean[n][m];
bot b=new bot();
while(true)
{
sb.append(arr[b.i][b.j]);
vis[b.i][b.j]=true;
if(arr[b.i][b.j].compareTo(f)==0){
c=0;
break;
}
if(b.o.compareTo("right")==0)
{
if(b.i<n&&(b.j+1)<m&&vis[b.i][b.j+1]==false)
{
b.j=b.j+1;
}
else if((b.i+1)<n&&b.j<m&&vis[b.i+1][b.j]==false)
{
b.i=b.i+1;
b.o="down";
}
else{
break;
}
}
else if(b.o.compareTo("left")==0){
if(b.i<n&&(b.j-1)>=0&&vis[b.i][b.j-1]==false)
{
b.j=b.j-1;
}
else if((b.i-1)>=0&&b.j<m&&vis[b.i-1][b.j]==false)
{
b.i=b.i-1;
b.o="up";
}
else{
break;
}
}
else if(b.o.compareTo("up")==0){
if((b.i-1)>=0&&(b.j)<m&&vis[b.i-1][b.j]==false)
{
b.i=b.i-1;
}
else if((b.i)<n&&(b.j+1)<m&&vis[b.i][b.j+1]==false)
{
b.j=b.j+1;
b.o="right";
}
else{
break;
}
}
else if(b.o.compareTo("down")==0){
if((b.i+1)<n&&(b.j)<m&&vis[b.i+1][b.j]==false)
{
b.i=b.i+1;
}
else if((b.i)<n&&(b.j-1)>=0&&vis[b.i][b.j-1]==false)
{
b.j=b.j-1;
b.o="left";
}
else{
break;
}
}
}
if(c==1){
System.out.println("NO");
}
else{
System.out.println(sb);
}
}
}
}
class bot{
int i,j;
String o;
bot(){
i=0;
j=0;
o="right";
}
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
struct Node* newNode(int data)
{
struct Node* node = new Node;
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
int diameter(struct Node * tree);
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
map<int, Node*> m;
int n;
scanf("%d",&n);
struct Node *root = NULL;
struct Node *child;
while (n--)
{
Node *parent;
char lr;
int n1, n2;
scanf("%d %d %c", &n1, &n2, &lr);
if (m.find(n1) == m.end())
{
parent = newNode(n1);
m[n1] = parent;
if (root == NULL)
root = parent;
}
else
parent = m[n1];
child = newNode(n2);
if (lr == 'L')
parent->left = child;
else
parent->right = child;
m[n2] = child;
}
cout << diameter(root) << endl;
}
return 0;
}
struct Node
{
int data;
Node* left, *right;
};
int maxchildren[10001];
int c=0;
int fillChildren(Node* node)
{
if((node->left==NULL)&&(node->right==NULL)){
maxchildren[node->data] = 1;
}
else if(node->left==NULL){
maxchildren[node->data]=1+ fillChildren(node->right);
}
else if(node->right==NULL){
maxchildren[node->data]=1+fillChildren(node->left);
}
else{
maxchildren[node->data]= 1+max(fillChildren(node->left),fillChildren(node->right));
}
return maxchildren[node->data];
}
int mydiameter(Node* node)
{
if(c==0){
c=1;
for(int i=0;i<10001;i++)
{
maxchildren[i]=0;
}
fillChildren(node);
}
if(node==NULL) return 0;
if((node->left==NULL)&&(node->right==NULL)){
return 1;
}
else if((node->right==NULL)){
return max(1+maxchildren[node->left->data],mydiameter(node->left));
}
else if((node->left==NULL)){
return max(1+maxchildren[node->right->data],mydiameter(node->right));
}
return max(1+maxchildren[node->left->data]+maxchildren[node->right->data],max(mydiameter(node->left),mydiameter(node->right)));
}
int diameter(Node* node){
c=0;
return mydiameter(node);
}
int max(int a,int b){
return (a>b)?a:b;
}
|
a0ceeacb44eae99ef84930671c4893aa020c5893
|
[
"Java",
"C++"
] | 8
|
C++
|
MonuKumar0/SPOJ-is-it-a-tree-solution
|
2a9705f5cd808406d91042f273f4c96a1697ff90
|
99048aa10e1eb3a151112999c331974e3cf3258d
|
refs/heads/master
|
<file_sep>msg_hello = Hello
msg_menuClose = Close menu
msg_home = Home
msg_servers = Servers
msg_reports = Reports
msg_mapReport = Report''s Map
msg_settings = Settings
msg_about = About
msg_phones = Phones
msg_name = Name
msg_description = Description
msg_url = url
msg_title = Title
msg_cancel = Cancel
msg_save = Save
msg_noComments = There are no comments for this incident
msg_date = Date
msg_time = Time
msg_category = Category
msg_location = Concrete Location
msg_comments = Comments
msg_comment = Comment
msg_author = Author
msg_email = Email
msg_noIncidents = This server seem to have no reports approved
msg_submit_report_OK = Report added OK, waiting for approval<file_sep>
document.addEventListener("pause", onPause, false);
var pushNotification;
var serversArray = [];
var selectedServer;
var serverMode;
var selectedIncident;
var incidentMode;
var lang;
var settings;
var db;
var refresh = false;
var incident;
var police = 'tel:+34 679 956 731';
var fire = 'tel:+34 679 956 731';
var emergencies = 'tel:+34 679 956 731';
function DOMLoaded(){
console.log('DOMLoaded');
document.addEventListener("deviceready", phonegapLoaded, false);
navigator.geolocation.getCurrentPosition(onSuccessMap, onError);
}
function phonegapLoaded(){
console.log('phonegapLoaded');
init_db();
}
//INICIO FUNCIONES i18n
function multiLanguage(){
console.log('multiLanguage');
jQuery.i18n.properties({
name:'Messages',
path:'bundle/',
mode:'both',
language: lang,
callback: function() {
//Menu literals
menuLeft();
i18nIndex();
i18nServers();
i18nIncidents();
}
});
}
function menuLeft(){
$('.menuLeftClose').text(""+jQuery.i18n.prop('msg_menuClose'));
$('.menuLeftHome').text(""+jQuery.i18n.prop('msg_home'));
$('.menuLeftServers').text(""+jQuery.i18n.prop('msg_servers'));
$('.menuLeftReports').text(""+jQuery.i18n.prop('msg_reports'));
$('.menuLeftMapView').text(""+jQuery.i18n.prop('msg_mapReport'));
$('.menuLeftSettings').text(""+jQuery.i18n.prop('msg_settings'));
$('.menuLeftAbout').text(""+jQuery.i18n.prop('msg_about'));
}
function i18nIndex(){
$('#telefonos').text(""+jQuery.i18n.prop('msg_phones'));
}
function i18nServers(){
$('label[for="serverName"]').text(""+jQuery.i18n.prop('msg_name'));
$('label[for="serverDescription"]').text(""+jQuery.i18n.prop('msg_description'));
$('label[for="serverUrl"]').text(""+jQuery.i18n.prop('msg_url'));
$('#cancel').text(""+jQuery.i18n.prop('msg_cancel'));
$('#saveServer').text(""+jQuery.i18n.prop('msg_save'));
}
function i18nIncidents(){
$('#headerSubmitReport').text(""+jQuery.i18n.prop('msg_save'));
$('label[for="incidentTitle"]').text(""+jQuery.i18n.prop('msg_title'));
$('label[for="incidentDescription"]').text(""+jQuery.i18n.prop('msg_description'));
$('label[for="incidentDate"]').text(""+jQuery.i18n.prop('msg_date'));
$('label[for="incidentTime"]').text(""+jQuery.i18n.prop('msg_time'));
$('label[for="incidentCategory"]').text(""+jQuery.i18n.prop('msg_category'));
$('label[for="incidentLocation"]').text(""+jQuery.i18n.prop('msg_location'));
$('#incidentComments').text(""+jQuery.i18n.prop('msg_comments'));
$('#headerAddComent').text(""+jQuery.i18n.prop('msg_comment'));
$('#headerSaveComent').text(""+jQuery.i18n.prop('msg_save'));
$('label[for="commentAuthor"]').text(""+jQuery.i18n.prop('msg_author'));
$('label[for="commentEmail"]').text(""+jQuery.i18n.prop('msg_email'));
$('label[for="commentDescription"]').text(""+jQuery.i18n.prop('msg_description'));
}
//FIN FUNCIONES i18n
//INICIO FUNCIONES NAVEGACION
$( document ).on("pageshow", "#serversPage",function(){
$('#serverList').empty();
showServers();
});
$( document ).on("pagebeforeshow", "#reportsPage",function(){
$('#incidentList').empty();
});
$( document ).on("pageshow", "#reportsPage",function(){
$('#incidentList').empty();
showIncidents();
});
$( document ).on("pagebeforeshow", "#serverFormPage",function(){
if(serverMode == 'edit'){
$('#headerDeleteServer').show();
loadServerEditForm();
}
else{
$('#headerDeleteServer').hide();
loadServerAddForm();
}
});
$( document ).on("pageshow", "#incidentPage",function(){
if(incidentMode == 'edit'){
$('#listCommentsLink').show();
$('#headerSubmitReport').hide();
loadIncidentEditForm();
}
else{
$('#listCommentsLink').hide();
$('#headerSubmitReport').show();
loadIncidentAddForm();
}
});
$( document ).on("click", "#headerAddServer", function(){
selectedServer = null;
serverMode = 'add';
$.mobile.changePage("#serverFormPage", {
transition: "slidefade"
});
});
function goToServerForm(event){
console.log("serverForm");
selectedServer = event.target.id;
serverMode = 'edit';
$.mobile.changePage("#serverFormPage", {
transition: "slidefade"
});
}
$( document ).on("click", "#headerAddIncident", function(){
incidentMode = 'add';
$.mobile.changePage("#incidentPage", {
transition: "slidefade"
});
});
function goToIncidentForm(event){
console.log("incidentForm");
incidentMode = 'edit';
$.mobile.changePage("#incidentPage", {
transition: "slidefade"
});
}
$( document ).on("click", "#cancel", function(){
$.mobile.back();
});
$( document ).on("click", "#incidentComments", function(){
console.log('incidentComment');
$.mobile.changePage("#commentsPage", {
transition: "slidefade"
});
});
$( document ).on("pagebeforeshow", "#settingsPage",function(){
alert(settings.language);
$('#language option[value='+settings.language+']').attr("selected","selected");
$('#notifications').val(settings.notifications);
$('#userName').val(settings.userName);
$('#userSurname').val(settings.userSurname);
$('#radioAviso').val(settings.radio);
// $('#listSettings').listview('refresh');
});
$( document ).on("pagebeforeshow", "#commentsPage",function(){
$('#commentsList').empty();
getComments();
});
$( document ).on("pagebeforeshow", "#commentFormPage",function(){
$('#commentAuthor').val(settings.userName+" "+settings.userSurname);
$('#commentEmail').val("");
$('#commentDescription').val("");
});
$(document).on("pageshow", "#mapReportsPage", function(){
navigator.geolocation.getCurrentPosition(loadReportMap,onError);
});
//FIN FUNCIONES NAVEGACION
// INICIO FUNCIONES BBDD
function init_db(){
console.log('init_db');
db = window.openDatabase('DeustoEmer', '1.0', 'Deusto Emergencias', '10000000');
db.transaction(populateDB, errorCB, getServersDB);
db.transaction(populateDB, errorCB, getSettingsDB);
}
function populateDB(tx) {
console.log('populateDB');
tx.executeSql('DROP TABLE IF EXISTS SERVERS');
tx.executeSql('DROP TABLE IF EXISTS SETTINGS');
tx.executeSql('CREATE TABLE IF NOT EXISTS SERVERS (id INTEGER PRIMARY KEY, name, description, url)');
tx.executeSql('INSERT INTO SERVERS (id, name, description, url) VALUES (1, "Deusto emergencias", "Deusto emergencias", "http://deustoemer.hol.es/ushahidi")');
tx.executeSql('CREATE TABLE IF NOT EXISTS SETTINGS (id INTEGER PRIMARY KEY, language, notifications, userName, userSurname, radio INTEGER)');
}
function errorCB(err) {
console.log("Error processing SQL: "+err.code);
}
function getServersDB(){
db = window.openDatabase('DeustoEmer', '1.0', 'Deusto Emergencias', '10000000');
db.transaction(function queryDB(tx) {
tx.executeSql('SELECT * FROM SERVERS', [], getServersSuccess, errorCB);
}, errorCB);
}
//Query the success callback
function getServersSuccess(tx, results) {
var len = results.rows.length;
console.log("SERVERS table: " + len + " rows found.");
serversArray = [];
for (var i=0; i<len; i++){
console.log("Row = " + i + " ID = " + results.rows.item(i).id + " Name = " + results.rows.item(i).name
+ " Description = "+ results.rows.item(i).description + " URL = "+results.rows.item(i).url);
console.log("ITEM: "+results.rows.item(i));
serversArray[i] = { id: results.rows.item(i).id,
name: results.rows.item(i).name,
description: results.rows.item(i).description,
url: results.rows.item(i).url};
}
}
function getSettingsDB(){
db.transaction(function queryDB(tx) {
tx.executeSql('SELECT * FROM SETTINGS', [], function getSettingsSucces(tx, results){
var len = results.rows.length;
console.log("settings: " + len + " rows found.");
for (var i=0; i<len; i++){
console.log("Language = "+i+" ID = "+results.rows.item(i).language +" Notifications = "+results.rows.item(i).notifications+" UserName = " + results.rows.item(i).userName
+ " UserSurname = "+ results.rows.item(i).userSurname + " Radio = "+results.rows.item(i).radio);
console.log("ITEM: "+results.rows.item(i));
}
if(len>0){
settings = {id: results.rows.item(0).id, language: results.rows.item(0).language,
notifications: results.rows.item(0).notifications, userName: results.rows.item(0).userName,
userSurname: results.rows.item(0).userSurname, radio: results.rows.item(0).radio};
lang = settings.language;
multiLanguage();
if(settings.notifications == 'on'){
init_notifications();
}
} else{
if ( navigator && navigator.userAgent && (lang = navigator.userAgent.match(/android.*\W(\w\w)-(\w\w)\W/i))) {
lang = lang[1];
}
if (!lang && navigator) {
if (navigator.language) {
lang = navigator.language;
} else if (navigator.browserLanguage) {
lang = navigator.browserLanguage;
} else if (navigator.systemLanguage) {
lang = navigator.systemLanguage;
} else if (navigator.userLanguage) {
lang = navigator.userLanguage;
}
lang = lang.substr(0, 2);
}
insertDefaultSettings();
}
}, errorCB);
}, errorCB);
}
function insertDefaultSettings(){
db.transaction(function queryDB(tx) {
tx.executeSql("INSERT into SETTINGS (id, language, notifications, userName, userSurname, radio)"
+" values (1, '"+lang+"', 'on', '', '', 10)", [], getSettingsDB, errorCB);
}, errorCB);
}
//FIN FUNCIONES BBDD
//INICIO FUNCIONES NOTIFICACIONES GCM Y APN
function init_notifications(){
try{
pushNotification = window.plugins.pushNotification;
if (device.platform == 'android' || device.platform == 'Android') {
pushNotification.register(successHandler, errorHandler, {"senderID":"831024351421","ecb":"onNotificationGCM"}); // required!
} else {
pushNotification.register(tokenHandler, errorHandler, {"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"}); // required!
}
}
catch(err){
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
alert(txt);
}
}
function registerAndroid(){
$.ajax({
type : "GET",
url : serversArray[0].url+'/',
beforeSend : function() {$.mobile.loading('show')},
complete : function() {$.mobile.loading('hide')},
data : {},
dataType : 'text',
async: true,
success: function(response){
try{
if(response.error != null && response.error.code == '0'){
var incidents = response.payload.incidents;
for(j=0; j<incidents.length; j++){
createIncidentMarker(incidents[j]['incident']);
}
}
} catch(e){
console.log(e);
}
},
error: function(request,error){
console.log(error);
}
});
}
function successHandler (result) {
console.log("success");
}
function errorHandler (error) {
console.log("error");
}
// iOS
function onNotificationAPN(event) {
var pushNotification = window.plugins.pushNotification;
console.log("Received a notification! " + event.alert);
console.log("event sound " + event.sound);
console.log("event badge " + event.badge);
console.log("event " + event);
if (event.alert) {
navigator.notification.alert(event.alert);
}
if (event.badge) {
console.log("Set badge on " + pushNotification);
pushNotification.setApplicationIconBadgeNumber(this.successHandler, event.badge);
}
if (event.sound) {
var snd = new Media(event.sound);
snd.play();
}
}
// handle GCM notifications for Android
function onNotificationGCM(e) {
$("#app-status-ul").append('<li>EVENT -> RECEIVED:' + e.event + '</li>');
console.log(e.event);
switch( e.event ){
case 'registered':
if ( e.regid.length > 0 ){
// Your GCM push server needs to know the regID before it can push to this device
// here is where you might want to send it the regID for later use.
var request = new XMLHttpRequest();
request.open("GET", "http://deustoemer.hol.es/ushahidi/push/storeUser/"+e.regid+"/android", true);
request.onreadystatechange = function(){
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
console.log(request.response);
}
}
}
request.send();
}
break;
case 'message':
// if this flag is set, this notification happened while we were in the foreground.
// you might want to play a sound to get the user's attention, throw up a dialog, etc.
alert(e.payload.title+' - >'+e.payload.description);
break;
case 'error':
alert(e.msg);
break;
default:
alert('Unknown, an event was received and we do not know what it is</li>');
break;
}
}
//INICIO FUNCIONES NOTIFICACIONES GCM Y APN
function onPause() {
// Handle the pause event
}
//INICIO FUNCIONES GOOGLE MAPS
//Función utilizada para pintar el mapa de la página principal
function onSuccessMap(position) {
var myLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map = new google.maps.Map(document.getElementById('map_canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: myLocation,
zoom: 15,
});
google.maps.event.trigger(map, 'resize');
var currentPositionMarker = new google.maps.Marker({
position: myLocation,
map: map,
title: "Current position"
});
currentRadiusValue = 2000;
var request = { location: myLocation, radius: currentRadiusValue, types: ['policia', 'hospital', 'bomberos'] };
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
}
function loadReportMap(position){
var myLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map = new google.maps.Map(document.getElementById('map_canvas_reports'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: myLocation,
zoom: 10,
});
google.maps.event.trigger(map, 'resize');
for(var i=0; i<serversArray.length; i++){
$.ajax({
type : "GET",
url : serversArray[i].url+'/api?task=incidents',
beforeSend : function() {$.mobile.loading('show')},
complete : function() {$.mobile.loading('hide')},
data : {},
dataType : 'json',
async: true,
success: function(response){
try{
if(response.error != null && response.error.code == '0'){
var incidents = response.payload.incidents;
for(j=0; j<incidents.length; j++){
createIncidentMarker(incidents[j]['incident']);
}
}
} catch(e){
console.log(e);
}
},
error: function(request,error){
console.log(error);
}
});
}
}
function createIncidentMarker(incident){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(incident.locationlatitude, incident.locationlongitude),
map: map
});
var infowindow = new google.maps.InfoWindow({
content: 'Name<br />'+incident.incidenttitle+'<br />'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
//FIN FUNCIONES GOOGLE MAPS
//INICIO FUNCIONES PANTALLA PRINCIPAL
function callPolice(){
if (device.platform == 'android' || device.platform == 'Android') {
document.location.href = police;
} else{
window.plugins.phoneDialer.dial(police);
}
}
function callFire(){
if (device.platform == 'android' || device.platform == 'Android') {
document.location.href = fire;
} else{
window.plugins.phoneDialer.dial(fire);
}
}
function callEmergencies(){
if (device.platform == 'android' || device.platform == 'Android') {
document.location.href = emergencies;
} else{
window.plugins.phoneDialer.dial(emergencies);
}
}
//FIN FUNCIONES PANTALLA PRINCIPAL
//INICIO FUNCIONES SERVIDORES
function showServers(){
console.log("Servidores en show: "+serversArray.length);
var len = serversArray.length;
for (var i=0; i<len; i++){
console.log("Servidor en show: "+serversArray[i]);
console.log("Servidor en show id: "+serversArray[i].id);
$('#serverList').append('<li><a href="#" id="'+serversArray[i].id+'">'+serversArray[i].name+'</a></li>');
$('#'+serversArray[i].id).off('click').on('click', function(e){
console.log("Click");
goToServerForm(event);
});
}
$('#serverList').listview('refresh');
if(refresh){
$.mobile.back();
refresh = false;
}
}
function loadServerEditForm(){
console.log("loadServerEditForm");
$('#serverId').val(selectedServer);
for(var i=0; i<serversArray.length; i++){
if(selectedServer == serversArray[i].id){
console.log("Encontrado servidor");
$('#serverName').val(serversArray[i].name);
$('#serverDescription').val(serversArray[i].description);
$('#serverUrl').val(serversArray[i].url);
}
}
}
function loadServerAddForm(){
selectedServer = 1;
for(var i=0; i<serversArray.length; i++){
if(serversArray[i].id > selectedServer){
selectedServer = serversArray[i].id;
}
}
selectedServer ++;
$('#serverId').val(selectedServer);
$('#serverName').val("");
$('#serverDescription').val("");
$('#serverUrl').val("");
}
$(document).on("click","#headerDeleteServer", function(){
console.log("Delete server "+selectedServer);
db.transaction(function queryDB(tx) {
tx.executeSql('DELETE FROM SERVERS WHERE id='+selectedServer, [], okDeleteServer, errorServerDelete);
}, errorServerDelete);
});
function okDeleteServer(){
console.log("okDeleteServer");
refresh=true;
db.transaction(function queryDB(tx) {
tx.executeSql('SELECT * FROM SERVERS', [], function success(tx, results){
var len = results.rows.length;
console.log("SERVERS table: " + len + " rows found.");
serversArray = [];
for (var i=0; i<len; i++){
console.log("Row = " + i + " ID = " + results.rows.item(i).id + " Name = " + results.rows.item(i).name
+ " Description = "+ results.rows.item(i).description + " URL = "+results.rows.item(i).url);
console.log("ITEM: "+results.rows.item(i));
serversArray[i] = { id: results.rows.item(i).id,
name: results.rows.item(i).name,
description: results.rows.item(i).description,
url: results.rows.item(i).url};
}
$('#serverList').empty();
showServers();
}, errorServerDelete);
}, errorServerDelete);
}
function errorServerDelete(err){
alert("Error al borrar: "+err.code)
}
$(document).on("click","#saveServer", function(){
if($('#serverForm').valid()){
if(serverMode == 'edit'){
db.transaction(function queryDB(tx) {
tx.executeSql('Update SERVERS set name="'+$('#serverName').val()+'", description="'+$('#serverDescription').val()
+'", url="'+$('#serverUrl').val()+'" where id="'+$('#serverId').val()+'"', [], okDeleteServer, errorServerDelete);
}, errorServerDelete);
} else{
db.transaction(function queryDB(tx) {
tx.executeSql('Insert into SERVERS (id, name, description, url) values("'+$('#serverId').val()+'", "'+$('#serverName').val()+
'", "'+$('#serverDescription').val()+'", "'+$('#serverUrl').val()+'")', [], okDeleteServer, errorServerDelete);
}, errorServerDelete);
}
}
});
//FIN FUNCIONES SERVIDORES
//INICIO REPORTES
function showIncidents(){
var len = serversArray.length;
console.log(len);
for (var i=0; i<len; i++){
console.log(serversArray[i].url);
var id = serversArray[i].id;
$('#incidentList').append('<li data-role="list-divider">'+serversArray[i].name+'</li>');
response = $.ajax({
type : "GET",
url : serversArray[i].url+'/api?task=incidents',
beforeSend : function() {$.mobile.loading('show')},
complete : function() {$.mobile.loading('hide')},
data : {},
dataType : 'json',
async: false
}).responseText;
try{
addIncidentToList(JSON.parse(response), id);
} catch(e){
$('#incidentList').append('<li>'+jQuery.i18n.prop('msg_noIncidents')+'</li>');
}
}
$('#incidentList').listview('refresh');
}
function addIncidentToList(response, id){
console.log(typeof response);
console.log('Incidentes: '+response['payload']);
if(response.error != null && response.error.code == '0'){
console.log('Incidentes: '+response.payload.incidents.length);
console.log('Server id: '+id);
if(response.payload.incidents.length == 0){
console.log("Entramos por el if");
$('#incidentList').append('<li>'+jQuery.i18n.prop('msg_noIncidents')+'</li>');
} else{
console.log("Entramos por el else");
var incidents = response.payload.incidents;
for(j=0; j<incidents.length; j++){
var incident = incidents[j]['incident'];
$('#incidentList').append('<li><a href="#" id="s'+id+'i'+incident.incidentid+'">'
+'<h3 id="s'+id+'i'+incident.incidentid+'">'+incident.incidenttitle+'</h3>'
+'<p id="s'+id+'i'+incident.incidentid+'"><strong id="s'+id+'i'+incident.incidentid+'">'+incident.incidentdescription+'</strong></p>'
+'<p id="s'+id+'i'+incident.incidentid+'">'+incident.incidentdate+' '+incident.locationname+'</p>'
+'</a></li>');
$('#s'+id+'i'+incident.incidentid).off('click').on('click', function incidentClick(event){
var aux = event.target.id;
selectedIncident = aux.substring(aux.lastIndexOf('i')+1,aux.length);
selectedServer = aux.substring(1,aux.lastIndexOf('i'));
goToIncidentForm(event);
});
}
}
}else{
$('#incidentList').append('<li>'+jQuery.i18n.prop('msg_noIncidents')+'</li>');
}
}
function loadIncidentEditForm(){
var id = 0;
for(var i=0; i<serversArray.length; i++){
if(selectedServer == serversArray[i].id){
id = i;
}
}
response = $.ajax({
type : "GET",
url : serversArray[id].url+'/api?task=incidents&by=incidentid&id='+selectedIncident,
beforeSend : function() {$.mobile.loading('show')},
complete : function() {$.mobile.loading('hide')},
data : {},
dataType : 'json',
async: false
}).responseText;
responsParsed = JSON.parse(response);
console.log(responsParsed);
console.log(responsParsed[0]);
incident = responsParsed.payload.incidents[0]['incident'];
$('#incidentId').attr('readonly','readonly');
$('#incidentId').removeAttr('data-clear-btn');
$('#incidentId').textinput();
$('#incidentTitle').attr('readonly','readonly');
$('#incidentTitle').removeAttr('data-clear-btn');
$('#incidentTitle').textinput();
$('#incidentDescription').attr('readonly','readonly');
$('#incidentDescription').removeAttr('data-clear-btn');
$('#incidentLocation').attr('readonly','readonly');
$('#incidentLocation').removeAttr('data-clear-btn');
$('#incidentDate').attr('readonly','readonly');
$('#incidentDate').removeAttr('data-clear-btn');
$('#incidentTime').attr('readonly','readonly');
$('#incidentTime').removeAttr('data-clear-btn');
$('#incidentId').val(incident.incidentid);
$('#incidentTitle').val(incident.incidenttitle);
$('#incidentDescription').val(incident.incidentdescription);
$('#incidentLatitude').val(incident.locationlatitude);
$('#incidentLongitude').val(incident.locationlongitude);
$('#incidentLocation').val(incident.locationname);
var dateIncident = incident.incidentdate.substring(8,10)+'/'+incident.incidentdate.substring(5,7)+'/'+incident.incidentdate.substring(0,4);
$('#incidentDate').val(dateIncident);
$('#incidentTime').val(incident.incidentdate.substring(12,incident.incidentdate.length));
$('#listParamsIncidents').listview('refresh');
$('#incidentCategory').empty();
var categories = responsParsed.payload.incidents[0]['categories'];
for(var i=0;i<categories.length; i++){
var category = categories[i]['category'];
$('#incidentCategory').append('<option value="'+category.id+'" selected="true">'+category.title+'</option>');
}
$('#incidentCategory').selectmenu('disable');
$('#incidentCategory').selectmenu("refresh");
var incidentLocation = new google.maps.LatLng(incident.locationlatitude, incident.locationlongitude);
map = new google.maps.Map(document.getElementById('incidentMap'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: incidentLocation,
zoom: 15,
});
google.maps.event.trigger(map, 'resize');
var currentPositionMarker = new google.maps.Marker({
position: incidentLocation,
map: map,
title: incident.incidenttitle
});
}
function loadIncidentAddForm(){
$('#incidentId').removeAttr('readonly');
$('#incidentId').val("");
$('#incidentTitle').removeAttr('readonly');
$('#incidentTitle').val("");
$('#incidentDescription').removeAttr('readonly');
$('#incidentDescription').val("");
var date = new Date();
var hour = date.getHours();
var ampm = 'am';
if(hour > 12){
hour = hour - 12;
ampm = 'pm';
}
var min = date.getMinutes();
var dd = date.getDate();
if(dd < 10){
dd = '0'+dd;
}
var mm = date.getMonth() + 1;
if(mm < 10){
mm = '0'+mm;
}
var yyyy = date.getFullYear();
$('#incidentDate').val(dd+'/'+mm+'/'+yyyy);
$('#incidentTime').val(hour+':'+min+' '+ampm);
$('#incidentLatitude').val("");
$('#incidentLongitude').val("");
$('#incidentLocation').val("");
$('#incidentLocation').removeAttr('readonly');
$('#incidentCategory').empty();
$('#incidentCategory').selectmenu('enable');
var id = 0;
for(var i=0; i<serversArray.length; i++){
if(selectedServer == serversArray[i].id){
id = i;
}
}
response = $.ajax({
type : "GET",
url : serversArray[id].url+'/api?task=categories',
beforeSend : function() {$.mobile.loading('show')},
complete : function() {$.mobile.loading('hide')},
data : {},
dataType : 'json',
async: false
}).responseText;
responsParsed = JSON.parse(response);
var categories = responsParsed.payload.categories;
for(var i=0;i<categories.length; i++){
var category = categories[i]['category'];
$('#incidentCategory').append('<option value="'+category.id+'">'+category.title+'</option>');
}
$('#incidentCategory').selectmenu("refresh");
$('#listParamsIncidents').listview('refresh');
navigator.geolocation.getCurrentPosition(function onSuccessMap(position){
$('#incidentLatitude').val(position.coords.latitude);
$('#incidentLongitude').val(position.coords.longitude);
var myLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map = new google.maps.Map(document.getElementById('incidentMap'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: myLocation,
zoom: 15,
});
google.maps.event.trigger(map, 'resize');
}, onError);
}
$(document).on('change', '#incidentLocation', function(){
if ($('#incidentLocation').val() != null || $('#incidentLocation').val() != '') {
var map = new google.maps.Map(document
.getElementById('incidentMap'), {
mapTypeId : google.maps.MapTypeId.ROADMAP,
zoom : 15
});
var geocoder = new google.maps.Geocoder();
geocoder.geocode(
{
'address' : document
.getElementById('incidentLocation').value
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$('#incidentLatitude').val(results[0].geometry.location.lat());
$('#incidentLongitude').val(results[0].geometry.location.lng());
new google.maps.Marker({
position : results[0].geometry.location,
map : map
});
map.setCenter(results[0].geometry.location);
} else {
alert("No se ha encontrado ubicación");
$('#incidentLatitude').val("");
$('#incidentLongitude').val("");
}
});
google.maps.event.trigger(map, 'resize');
}
});
$(document).on('click', '#headerSubmitReport', function(){
var id = 0;
for(var i=0; i<serversArray.length; i++){
if(selectedServer == serversArray[i].id){
id = i;
}
}
if($('#incidentForm').valid()){
time = $('#incidentTime').val().toString();
date = $('#incidentDate').val().toString();
date = date.substring(3,5)+'/'+date.substring(0,2)+date.substring(5,date.length);
$.ajax({
type : "POST",
url : serversArray[id].url+'/api?task=report',
beforeSend : function() {$.mobile.loading('show')},
complete : function() {$.mobile.loading('hide')},
data: {task: "report", incident_title: $('#incidentTitle').val(),
incident_description: $('#incidentDescription').val(),
incident_date: date,
incident_hour: time.substring(0,time.lastIndexOf(':')),
incident_minute: time.substring(time.lastIndexOf(':')+1,time.lastIndexOf(' ')),
incident_ampm: time.substring(time.length-2,time.length),
incident_category: $('#incidentCategory').val().toString(),
latitude: $('#incidentLatitude').val(),
longitude: $('#incidentLongitude').val(),
location_name: $('#incidentLocation').val()},
async: true,
dataType: 'text',
success: function (response){
console.log(response);
$.mobile.back();
alert(""+jQuery.i18n.prop('msg_submit_report_OK'));
},
error: function (request,error) {
alert("Error"+error.toString());
}
});
}
});
function getComments(){
var id = 0;
for(var i=0; i<serversArray.length; i++){
if(selectedServer == serversArray[i].id){
id = i;
}
}
$.ajax({
type : "GET",
url : serversArray[id].url+'/api?task=comments&by=reportid&id='+selectedIncident,
beforeSend : function() {$.mobile.loading('show')},
complete : function() {$.mobile.loading('hide')},
data: {},
async: true,
dataType: 'json',
success: function (response){
var comments = response.payload.comments;
if(response.error.code == '0'){
for(var i=0; i<comments.length; i++){
var comment = comments[i]['comment'];
$('#commentsList').append('<li><strong>'+comment.comment_author+' </strong>('+comment.comment_date+')<br/><br/>'
+'<p>'+comment.comment_description+'</p></li>');
}
}else{
$('#commentsList').append('<li>'+jQuery.i18n.prop('msg_noComments')+'</li>');
}
$('#commentsList').listview('refresh');
},
error: function (request,error) {
alert("Error"+error);
}
});
}
$(document).on("click","#headerSaveComent", function(){
var id = 0;
for(var i=0; i<serversArray.length; i++){
if(selectedServer == serversArray[i].id){
id = i;
}
}
if($('#commentForm').valid()){
$.ajax({
type : "POST",
url : serversArray[id].url+'/api?task=comments&action=add',
beforeSend : function() {$.mobile.loading('show')},
complete : function() {$.mobile.loading('hide')},
data: {task: "comments", action: "add", incident_id: selectedIncident,
comment_description: $('#commentDescription')},
async: true,
dataType: 'text',
success: function (response){
alert(response);
console.log(response);
$.mobile.back();
},
error: function (request,error) {
alert("Error"+error);
alert(request);
}
});
}
});
//FIN REPORTES<file_sep>package com.plugin.gcm;
import java.util.List;
import com.google.android.gcm.GCMBaseIntentService;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
@SuppressLint("NewApi")
public class GCMIntentService extends GCMBaseIntentService {
public static final int NOTIFICATION_ID = 237;
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super("GCMIntentService");
}
@Override
public void onRegistered(Context context, String regId) {
Log.v(TAG, "onRegistered: " + regId);
JSONObject json;
try {
json = new JSONObject().put("event", "registered");
json.put("regid", regId);
Log.v(TAG, "onRegistered: " + json.toString());
// Send this JSON data to the JavaScript application above EVENT
// should be set to the msg type
// In this case this is the registration ID
PushPlugin.sendJavascript(json);
} catch (JSONException e) {
// No message to the user is sent, JSON failed
Log.e(TAG, "onRegistered: JSON exception");
}
}
@Override
public void onUnregistered(Context context, String regId) {
Log.d(TAG, "onUnregistered - regId: " + regId);
}
@Override
protected void onMessage(Context context, Intent intent) {
Log.d(TAG, "onMessage - context: " + context);
// Extract the payload from the message
Bundle extras = intent.getExtras();
if (extras != null) {
boolean foreground = this.isInForeground();
extras.putBoolean("foreground", foreground);
if (foreground)
PushPlugin.sendExtras(extras);
else{
if(checkProximity(extras)){
createNotification(context, extras);
}
}
}
}
public void createNotification(Context context, Bundle extras) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String appName = getAppName(this);
Intent notificationIntent = new Intent(this, PushHandlerActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent.putExtra("pushBundle", extras);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setSmallIcon(context.getApplicationInfo().icon)
.setWhen(System.currentTimeMillis()).setContentTitle(appName).setTicker(appName).setContentIntent(contentIntent);
String message = extras.getString("title");
if (message != null) {
mBuilder.setContentText(message);
} else {
mBuilder.setContentText("<missing message content>");
}
String msgcnt = extras.getString("description");
if (msgcnt != null) {
mBuilder.setContentText(msgcnt);
}
mNotificationManager.notify((String) appName, NOTIFICATION_ID, mBuilder.build());
tryPlayRingtone();
}
private void tryPlayRingtone() {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
Log.e(TAG, "failed to play notification ringtone");
}
}
public static void cancelNotification(Context context) {
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel((String) getAppName(context), NOTIFICATION_ID);
}
private static String getAppName(Context context) {
CharSequence appName = context.getPackageManager().getApplicationLabel(context.getApplicationInfo());
return (String) appName;
}
public boolean isInForeground() {
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> services = activityManager.getRunningTasks(Integer.MAX_VALUE);
if (services.get(0).topActivity.getPackageName().toString().equalsIgnoreCase(getApplicationContext().getPackageName().toString()))
return true;
return false;
}
@Override
public void onError(Context context, String errorId) {
Log.e(TAG, "onError - errorId: " + errorId);
}
public boolean checkProximity(Bundle extras) {
boolean near = false;
Location clientLocation = this.getLastBestLocation();
Location incidentLocation = new Location(LocationManager.GPS_PROVIDER);
String longitude = extras.getString("longitude");
String latitude = extras.getString("latitude");
if (longitude != null && latitude != null) {
incidentLocation.setLatitude(Double.parseDouble(latitude));
incidentLocation.setLongitude(Double.parseDouble(longitude));
if(clientLocation.distanceTo(incidentLocation) < 20*1000){
near = true;
}
}
return near;
}
/**
* @return the last know best location
*/
private Location getLastBestLocation() {
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location locationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location locationNet = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
long GPSLocationTime = 0;
if (null != locationGPS) {
GPSLocationTime = locationGPS.getTime();
}
long NetLocationTime = 0;
if (null != locationNet) {
NetLocationTime = locationNet.getTime();
}
if (0 < GPSLocationTime - NetLocationTime) {
return locationGPS;
} else {
return locationNet;
}
}
}
<file_sep>msg_hello = Hola
msg_menuClose = Cerrar Menu
msg_home = Principal
msg_servers = Servidores
msg_reports = Reportes
msg_mapReport = Mapa Reportes
msg_settings = Configuración
msg_about = Acerca de
msg_phones = Teléfonos
msg_name = Nombre
msg_description = Descripción
msg_url = url
msg_cancel = Cancelar
msg_save = Guardar
msg_noComments = No existen comentarios para este incidente
msg_date = Fecha
msg_time = Hora
msg_category = Categoría
msg_location = Ubicación
msg_comments = Comentarios
msg_comment = Comentar
msg_author = Autor
msg_noIncidents = Parece que el servidor no tiene reportes aprobados
msg_submit_report_OK = Reporte enviado correctamente, esperando aprobación
|
5f2b16492adfaa740dc42ea71c54b8daa4c8b273
|
[
"JavaScript",
"Java",
"INI"
] | 4
|
INI
|
javiermazqui/phonegap
|
72b835db0b152fe3f162cf12043f4ee900d28588
|
05e9ad65a1efa17913dfa15d9e3db1aa2930b488
|
refs/heads/master
|
<repo_name>qianbin01/weather-test<file_sep>/app/src/main/java/qb/com/weather_test/utils/DateUtils.java
package qb.com.weather_test.utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Created by qianbin on 16/8/9.
*/
public class DateUtils {
private Date date = new Date();
private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
public String setDate() {
//格式化日期
String time = sdf.format(date.getTime());
return time;
}
public String addDate(int i) {
Long time = date.getTime() - date.getDay() * 24 * 360000;
date.setTime(time + (i * 24 * 3600000));
String addTime = sdf.format(date.getTime());
return addTime;
}
}
<file_sep>/app/src/main/java/qb/com/weather_test/activity/ShowActivity.java
package qb.com.weather_test.activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.json.JSONException;
import org.json.JSONObject;
import qb.com.weather_test.R;
import qb.com.weather_test.application.MyApplication;
import qb.com.weather_test.model.ShiKuang;
import qb.com.weather_test.model.Today;
/**
* Created by qianbin on 16/8/8.
*/
public class ShowActivity extends BaseActivity {
private TextView temp, humidity, wind_direction, wind_strength, time, city, weather, temperature, date_y, week, wind, dressing_index, dressing_advice, uv_index, comfort_index, wash_index, drying_index, travel_index, exercise_index;
private Button future;
private Bundle mBundle;
private Today mToday;
private ShiKuang mShiKuang;
private Button btReturn;
private RequestQueue mQueue;
private String baseUrl = "http://v.juhe.cn/weather/index?key=<KEY>&cityname=";
private String mUrl, url;
private Gson gson;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_layout);
initView();
initData();
initEvent();
}
@Override
protected void initView() {
temp = (TextView) findViewById(R.id.temp);
humidity = (TextView) findViewById(R.id.humidity);
wind_direction = (TextView) findViewById(R.id.wind_direction);
wind_strength = (TextView) findViewById(R.id.wind_strength);
time = (TextView) findViewById(R.id.time);
city = (TextView) findViewById(R.id.city);
weather = (TextView) findViewById(R.id.weather);
temperature = (TextView) findViewById(R.id.temperature);
date_y = (TextView) findViewById(R.id.date_y);
week = (TextView) findViewById(R.id.week);
wind = (TextView) findViewById(R.id.wind);
dressing_index = (TextView) findViewById(R.id.dressing_index);
dressing_advice = (TextView) findViewById(R.id.dressing_advice);
uv_index = (TextView) findViewById(R.id.uv_index);
comfort_index = (TextView) findViewById(R.id.comfort_index);
wash_index = (TextView) findViewById(R.id.wash_index);
drying_index = (TextView) findViewById(R.id.drying_index);
travel_index = (TextView) findViewById(R.id.travel_index);
exercise_index = (TextView) findViewById(R.id.exercise_index);
future = (Button) findViewById(R.id.future);
btReturn = (Button) findViewById(R.id.btReturn);
}
@Override
protected void initData() {
mBundle = getIntent().getExtras();
mQueue = MyApplication.getHttpQueue();
mUrl = mBundle.getString("city");
url = baseUrl + mUrl;
gson = new GsonBuilder().setPrettyPrinting().create();
doVolley(url);
}
@Override
protected void setAdapter() {
if (mShiKuang != null && mToday != null) {
temp.setText("温度:"+mShiKuang.getTemp()+"℃");
humidity.setText("湿度:"+mShiKuang.getHumidity());
wind_direction.setText("风向:"+mShiKuang.getWind_direction());
wind_strength.setText("风力强度:"+mShiKuang.getWind_strength());
time.setText("更新时间:"+mShiKuang.getTime());
city.setText("城市:"+mToday.getCity());
weather.setText("天气:"+mToday.getWeather());
temperature.setText("温度区间:"+mToday.getTemperature());
date_y.setText("日期:"+mToday.getDate_y());
week.setText(mToday.getWeek());
wind.setText("风况:"+mToday.getWind());
dressing_index.setText("穿衣指数:"+mToday.getDressing_index());
dressing_advice.setText(mToday.getDressing_advice());
uv_index.setText("紫外线指数:"+mToday.getUv_index());
comfort_index.setText("舒适指数:"+mToday.getComfort_index());
wash_index.setText("洗车指数:"+mToday.getWash_index());
drying_index.setText("干燥指数:"+mToday.getDrying_index());
travel_index.setText("旅游指数:"+mToday.getTravel_index());
exercise_index.setText("锻炼指数:"+mToday.getExercise_index());
}
}
@Override
protected void initEvent() {
future.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openActivity(FutureActivity.class, mBundle);
}
});
btReturn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openActivity(MainActivity.class, mBundle);
}
});
}
private void doVolley(String url) {
JsonObjectRequest jsonobjectrequest = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
JSONObject result = null;
try {
result = response.getJSONObject("result");
JSONObject today = result.getJSONObject("today");
mToday = gson.fromJson(String.valueOf(today), Today.class);
JSONObject sk = result.getJSONObject("sk");
mShiKuang = gson.fromJson(String.valueOf(sk), ShiKuang.class);
setAdapter();//Volley封装了子线程,可直接进行UI更新
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
}
);
jsonobjectrequest.setTag(url);
mQueue.add(jsonobjectrequest);
}
@Override
protected void onStop() {
super.onStop();
mQueue.cancelAll(url);
}
}
<file_sep>/app/src/main/java/qb/com/weather_test/activity/FutureActivity.java
package qb.com.weather_test.activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import qb.com.weather_test.R;
import qb.com.weather_test.adapter.FutureAdapter;
import qb.com.weather_test.application.MyApplication;
import qb.com.weather_test.model.Future;
import qb.com.weather_test.utils.DateUtils;
/**
* Created by qianbin on 16/8/8.
*/
public class FutureActivity extends BaseActivity {
private ListView mListView;
private FutureAdapter mFutureAdapter;
private List<Future> mFutures;
private Bundle mBundle;
private Button btReturn;
private RequestQueue mQueue;
private String baseUrl = "http://v.juhe.cn/weather/index?key=<KEY>&cityname=";
private String mUrl, url;
private Gson gson;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.future_layout);
initView();
initData();
initEvent();
}
@Override
protected void initView() {
mListView = (ListView) findViewById(R.id.mListView);
btReturn = (Button) findViewById(R.id.btReturn);
}
@Override
protected void initData() {
mBundle = getIntent().getExtras();
mFutures = new ArrayList<Future>();
mQueue = MyApplication.getHttpQueue();
mUrl = mBundle.getString("city");
url = baseUrl + mUrl;
gson = new GsonBuilder().setPrettyPrinting().create();
doVolley(url);
mFutureAdapter = new FutureAdapter(this, mFutures);
}
@Override
protected void setAdapter() {
mListView.setAdapter(mFutureAdapter);
}
@Override
protected void initEvent() {
btReturn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openActivity(ShowActivity.class, mBundle);
}
});
}
private void doVolley(String url) {
JsonObjectRequest jsonobjectrequest = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject result = response.getJSONObject("result");
JSONObject future = result.getJSONObject("future");
for (int i = 0; i < 7; i++) {
JSONObject day = future.getJSONObject("day_" + new DateUtils().addDate(i));//根据不同的json接口自行判断日期
System.out.println(day.toString());
Future mFuture = gson.fromJson(String.valueOf(day), Future.class);
System.out.println(mFuture.getTemperature());
mFutures.add(mFuture);
}
mFutureAdapter.notifyDataSetChanged();
setAdapter();//Volley封装了子线程,可直接进行UI更新
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
}
);
jsonobjectrequest.setTag(url);
mQueue.add(jsonobjectrequest);
}
@Override
protected void onStop() {
super.onStop();
mQueue.cancelAll(url);
}
}
<file_sep>/README.md
# weather-test
江浙沪天气预报
使用Volley框架进行数据解析
使用聚合数据的天气接口,只剩100来次量了,若读者开发研究,可自行申请key在url处进行替换;
开发时我遇到的坑
1.Volley框架封装了子线程解析数据,可以直接进行UI更新,(多线程情况让我对象传不出去,导致我各种空指针异常)
2.该接口的未来天气预报格式实时变换,需要自行进行格式转化
代码写的个人算比较清晰,耦合相对来说还可以,
原意使用MVP的开发模式,可是Volley解析的数据不知如何传递,故将解析事件写入Activity,望高人改进后发送邮件<EMAIL>分享
谢谢!
|
fc99196fdd29db463c043fe9fa3ac8fcae9fa0de
|
[
"Markdown",
"Java"
] | 4
|
Java
|
qianbin01/weather-test
|
439a3c83cf78a2f7828b27baee5236597345f98e
|
12a17bcf6c60c43da35f5e9ed87c74d5c4245fb2
|
refs/heads/main
|
<file_sep>//import * as dat from 'dat.gui';
// Type definitions for dat.GUI 0.7
// Project: https://github.com/dataarts/dat.gui
// Definitions by: <NAME> <https://github.com/gyohk>, <NAME> <https://github.com/sonic3d>, <NAME> <https://github.com/rroylance>, <NAME> <https://github.com/singuerinc>, Teoxoy <https://github.com/teoxoy>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace dat {
export interface GUIParams {
/**
* Handles GUI's element placement for you.
* @default true
*/
autoPlace?: boolean | undefined;
/**
* If true, starts closed.
* @default false
*/
closed?: boolean | undefined;
/**
* If true, close/open button shows on top of the GUI.
* @default false
*/
closeOnTop?: boolean | undefined;
/**
* If true, GUI is closed by the "h" keypress.
* @default false
*/
hideable?: boolean | undefined;
/**
* JSON object representing the saved state of this GUI.
*/
load?: any;
/**
* The name of this GUI.
*/
name?: string | undefined;
/**
* The identifier for a set of saved values.
*/
preset?: string | undefined;
/**
* The width of GUI element.
*/
width?: number | undefined;
}
export class GUI {
static CLASS_AUTO_PLACE: string
static CLASS_AUTO_PLACE_CONTAINER: string
static CLASS_MAIN: string
static CLASS_CONTROLLER_ROW: string
static CLASS_TOO_TALL: string
static CLASS_CLOSED: string
static CLASS_CLOSE_BUTTON: string
static CLASS_CLOSE_TOP: string
static CLASS_CLOSE_BOTTOM: string
static CLASS_DRAG: string
static DEFAULT_WIDTH: number
static TEXT_CLOSED: string
static TEXT_OPEN: string
constructor(option?: GUIParams);
__controllers: GUIController[];
__folders: {[folderName: string]: GUI};
domElement: HTMLElement;
add(target: Object, propName:string, min?: number, max?: number, step?: number): GUIController;
add(target: Object, propName:string, status: boolean): GUIController;
add(target: Object, propName:string, items:string[]): GUIController;
add(target: Object, propName:string, items:number[]): GUIController;
add(target: Object, propName:string, items:Object): GUIController;
addColor(target: Object, propName:string): GUIController;
remove(controller: GUIController): void;
destroy(): void;
addFolder(propName:string): GUI;
removeFolder(subFolder:GUI):void;
open(): void;
close(): void;
hide(): void;
show(): void;
remember(target: Object, ...additionalTargets: Object[]): void;
getRoot(): GUI;
getSaveObject(): Object;
save(): void;
saveAs(presetName:string): void;
revert(gui:GUI): void;
listen(controller: GUIController): void;
updateDisplay(): void;
// gui properties in dat/gui/GUI.js
readonly parent: GUI;
readonly scrollable: boolean;
readonly autoPlace: boolean;
preset: string;
width: number;
name: string;
closed: boolean;
readonly load: Object;
useLocalStorage: boolean;
}
export class GUIController {
domElement: HTMLElement;
object: Object;
property: string;
constructor(object: Object, property: string);
options(option: any): GUIController;
name(name: string): GUIController;
listen(): GUIController;
remove(): GUIController;
onChange(fnc: (value?: any) => void): GUIController;
onFinishChange(fnc: (value?: any) => void): GUIController;
setValue(value: any): GUIController;
getValue(): any;
updateDisplay(): GUIController;
isModified(): boolean;
// NumberController
min(n: number): GUIController;
max(n: number): GUIController;
step(n: number): GUIController;
// FunctionController
fire(): GUIController;
}
}
type Fold = {
data: {
offset: number;
top: boolean;
};
remove(): void;
}
const SCALE = 100, WIDTH = 2598 / SCALE, HEIGHT = 3626 / SCALE;
class Playground {
public static CreateScene(engine: BABYLON.Engine, canvas: HTMLCanvasElement): BABYLON.Scene {
// This creates a basic Babylon Scene object (non-mesh)
const scene = new BABYLON.Scene(engine);
// This creates and positions a free camera (non-mesh)
//const camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene);
const camera = new BABYLON.ArcRotateCamera("Camera", -Math.PI / 2, Math.PI / 2, 3, BABYLON.Vector3.Zero(), scene);
// This targets the camera to scene origin
//camera.setTarget(BABYLON.Vector3.Zero());
camera.setTarget(new BABYLON.Vector3(WIDTH / 2, 0, 0));
// This attaches the camera to the canvas
camera.attachControl(canvas, true);
// This creates a light, aiming 0,1,0 - to the sky (non-mesh)
const light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene);
const light2 = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, -1, 0), scene);
const axes = this.createAxes(5, scene);
this.setVisibility(axes, false);
const oldgui = document.getElementById("datGUI");
if (oldgui != null){
oldgui.remove();
}
const gui = new dat.GUI();
gui.domElement.style.marginTop = "100px";
gui.domElement.id = "datGUI";
const folds: Fold[] = [];
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.multiple = true;
fileInput.addEventListener('change', () => {
for (const fold of folds) {
fold.remove();
}
folds.length = 0;
for (let i = fileInput.files.length - 1; i >= 0; i--) {
const file = fileInput.files[i];
folds.push(this.createFold(
scene,
gui,
URL.createObjectURL(file),
true,
file.name,
));
}
})
gui.add({ load: () => {fileInput.click();} }, 'load').name('Upload');
gui.add({ show: false }, 'show').name('Show axes?').onChange((show: boolean) => {
this.setVisibility(axes, show);
});
/*folds.push(this.createFold(
scene,
gui,
"https://ghcdn.rawgit.org/agoldstein03/HUGS/main/layers/Page_10_materials_0003s_0000_Color-Fill-14.png",
));*/
return scene;
}
private static createFold(
scene: BABYLON.Scene,
gui: dat.GUI,
path: string,
top: boolean = true,
label: string = path.match(/[A-Za-z0-9_\-\.]+\.[A-Za-z0-9]+$/)?.[0],
offset: number = 0,
width: number = WIDTH,
halfHeight: number = HEIGHT / 2,
): Fold {
const mat1 = new BABYLON.StandardMaterial(`${label} mat`, scene);
mat1.diffuseTexture = new BABYLON.Texture(path, scene);
mat1.diffuseTexture.hasAlpha = true;
const plane = BABYLON.MeshBuilder.CreatePlane(`${label} plane 0`, {
frontUVs: new BABYLON.Vector4(1, 0.5, 0, 0),
backUVs: new BABYLON.Vector4(1, 0.5, 0, 0),
width,
height: halfHeight,
sideOrientation: BABYLON.Mesh.DOUBLESIDE
}, scene);
plane.material = mat1;
plane.rotateAround(BABYLON.Vector3.Zero(), BABYLON.Vector3.Right(), Math.PI / 2);
const plane2 = BABYLON.MeshBuilder.CreatePlane(`${label} plane 1`, {
frontUVs: new BABYLON.Vector4(1, 0.5, 0, 1),
backUVs: new BABYLON.Vector4(1, 0.5, 0, 1),
width: WIDTH,
height: HEIGHT / 2,
sideOrientation: BABYLON.Mesh.DOUBLESIDE
}, scene);
plane2.material = mat1;
const folder = gui.addFolder(label),
data = { offset, top, visible: true };
const hiddenGui = folder.add(data, 'visible').name('Visible?').onChange((visible: boolean) => {
const code = visible ? 1 : 0
plane.visibility = code;
plane2.visibility = code;
});
const topGui = folder.add(data, "top", 0, HEIGHT / 4).name('Top?').onChange(onChange);
const offsetGui = folder.add(data, "offset", 0, HEIGHT / 4).name('Offset').onChange(onChange);
function onChange(): void {
let offsetY = data.top ? 0 : data.offset,
offsetZ = data.top ? data.offset : 0;
plane.position = new BABYLON.Vector3(WIDTH / 2, offsetY, (halfHeight / 2) + offsetZ);
plane2.position = new BABYLON.Vector3(width / 2, (halfHeight / 2) + offsetY, offsetZ);
}
onChange();
return {
data,
remove() {
for (const obj of [mat1, plane, plane2]) {
obj.dispose(false, true);
}
folder.remove(topGui);
folder.remove(offsetGui);
//gui.removeFolder(folder);
},
}
}
private static createAxes(size: number, scene: BABYLON.Scene): BABYLON.Mesh[] {
function makeTextPlane(text: string, color: string, size: number): BABYLON.Mesh {
const dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", 50, scene, true);
dynamicTexture.hasAlpha = true;
dynamicTexture.drawText(text, 5, 40, "bold 36px Arial", color , "transparent", true);
const plane = BABYLON.MeshBuilder.CreatePlane("TextPlane", {size, updatable: true}, scene);
const material = new BABYLON.StandardMaterial("TextPlaneMaterial", scene);
material.backFaceCulling = false;
material.specularColor = new BABYLON.Color3(0, 0, 0);
material.diffuseTexture = dynamicTexture;
plane.material = material;
return plane;
};
const axisX = BABYLON.MeshBuilder.CreateLines("axisX", {points: [
BABYLON.Vector3.Zero(), new BABYLON.Vector3(size, 0, 0), new BABYLON.Vector3(size * 0.95, 0.05 * size, 0),
new BABYLON.Vector3(size, 0, 0), new BABYLON.Vector3(size * 0.95, -0.05 * size, 0)
]}, scene);
axisX.color = new BABYLON.Color3(1, 0, 0);
const xChar = makeTextPlane("X", "red", size / 10);
xChar.position = new BABYLON.Vector3(0.9 * size, -0.05 * size, 0);
const axisY = BABYLON.MeshBuilder.CreateLines("axisY", {points: [
BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, size, 0), new BABYLON.Vector3( -0.05 * size, size * 0.95, 0),
new BABYLON.Vector3(0, size, 0), new BABYLON.Vector3( 0.05 * size, size * 0.95, 0)
]}, scene);
axisY.color = new BABYLON.Color3(0, 1, 0);
const yChar = makeTextPlane("Y", "green", size / 10);
yChar.position = new BABYLON.Vector3(0, 0.9 * size, -0.05 * size);
const axisZ = BABYLON.MeshBuilder.CreateLines("axisZ", {points: [
BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, size), new BABYLON.Vector3( 0 , -0.05 * size, size * 0.95),
new BABYLON.Vector3(0, 0, size), new BABYLON.Vector3( 0, 0.05 * size, size * 0.95)
]}, scene);
axisZ.color = new BABYLON.Color3(0, 0, 1);
const zChar = makeTextPlane("Z", "blue", size / 10);
zChar.position = new BABYLON.Vector3(0, 0.05 * size, 0.9 * size);
return [axisX, xChar, axisY, yChar, axisZ, zChar];
};
private static setVisibility(meshes: BABYLON.Mesh[], show: boolean): void {
for (const mesh of meshes) {
mesh.visibility = show ? 1 : 0;
}
}
}
<file_sep># HUGS
|
7fb6f1799cd44c783fd8a0cfe378530c32b10815
|
[
"Markdown",
"TypeScript"
] | 2
|
TypeScript
|
agoldstein03/HUGS
|
6670315e458fe27efe9fbe377d34300e6554418b
|
062e0a6e9450cdf0b505275f1467df39b359a721
|
refs/heads/master
|
<repo_name>bronzels/flink-crawldrv<file_sep>/src/main/proto/cp.sh
#!/usr/bin/env bash
cp $GOPATH/src/github.com/bronzels/pb/common.proto ./common.proto
cp $GOPATH/src/github.com/bronzels/pb/crawler.proto ./crawler.proto<file_sep>/pom.xml
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>at.bronzels</groupId>
<artifactId>flink-crawldrv</artifactId>
<version>0.0.1-SNAPSHOT</version>
<inceptionYear>2019</inceptionYear>
<properties>
<scala.version>2.11.8</scala.version>
<scala.binary.version>2.11</scala.binary.version>
<java.version>1.8</java.version>
<java.encoding>UTF-8</java.encoding>
<kafka.version>0.10.2.2</kafka.version>
<slf4j.version>1.7.28</slf4j.version>
<log4j.version>2.12.1</log4j.version>
<flink.version>1.9.0</flink.version>
<grpc.version>1.26.0</grpc.version>
<protobuf.version>3.11.1</protobuf.version>
</properties>
<repositories>
<repository>
<id>nexus</id>
<name>nexus</name>
<url>http://pro-hbase01:8081/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
</pluginRepositories>
<dependencies>
<dependency>
<groupId>at.bronzels</groupId>
<artifactId>libcdcdw</artifactId>
<version>1.0.0-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
</exclusion>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>at.bronzels</groupId>
<artifactId>libcdcdwstr</artifactId>
<version>1.0.0-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>at.bronzels</groupId>
<artifactId>libcdcdw</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
</exclusion>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<scope>runtime</scope>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<scope>runtime</scope>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<scope>runtime</scope>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-scala_${scala.binary.version}</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-streaming-scala_${scala.binary.version}</artifactId>
<version>${flink.version}</version>
</dependency>
<!--
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-table_${scala.binary.version}</artifactId>
<version>${flink.version}</version>
<scope>provided</scope>
</dependency>
-->
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-table-common</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-table-api-scala-bridge_${scala.binary.version}</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-table-api-scala_${scala.binary.version}</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-table-planner_${scala.binary.version}</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-runtime-web_${scala.binary.version}</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-connector-kafka-0.11_${scala.binary.version}</artifactId>
<version>${flink.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.flink</groupId>
<artifactId>flink-table_${scala.binary.version}</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.flink</groupId>
<artifactId>flink-streaming-java_${scala.binary.version}</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.flink</groupId>
<artifactId>flink-streaming-scala_${scala.binary.version}</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-connector-kafka_${scala.binary.version}</artifactId>
<version>${flink.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.flink</groupId>
<artifactId>flink-table_${scala.binary.version}</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.flink</groupId>
<artifactId>flink-streaming-java_${scala.binary.version}</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.flink</groupId>
<artifactId>flink-streaming-scala_${scala.binary.version}</artifactId>
</exclusion>
</exclusions>
</dependency>
-->
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>${protobuf.version}</version>
</dependency>
</dependencies>
<build>
<outputDirectory>target\classes</outputDirectory>
<testOutputDirectory>target\classes</testOutputDirectory>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.4.1.Final</version>
</extension>
</extensions>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>dev/*</exclude>
<exclude>beta/*</exclude>
<exclude>prod/*</exclude>
<exclude>followquant/*</exclude>
<exclude>betafollowquant/*</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources/${profiles.active}</directory>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.9.1</version>
</plugin>
<plugin>
<groupId>org.scala-tools</groupId>
<artifactId>maven-scala-plugin</artifactId>
<version>2.15.2</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<configuration>
<scalaVersion>${scala.version}</scalaVersion>
<args>
<arg>-target:jvm-1.8</arg>
</args>
</configuration>
</plugin>
<!--
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>false</overWriteSnapshots>
<overWriteIfNewer>true</overWriteIfNewer>
</configuration>
</execution>
</executions>
</plugin>
-->
<!--
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<configuration>
<nonFilteredFileExtensions>
<!– 过滤流程定义资源文件 –>
<nonFilteredFileExtension>xml</nonFilteredFileExtension>
<nonFilteredFileExtension>properties</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
<executions>
<execution>
<id>copy-main-res</id>
<phase>install</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}</outputDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
</excludes>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
</execution>
<execution>
<id>copy-profie-res</id>
<phase>install</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}</outputDirectory>
<resources>
<resource>
<directory>src/main/resources/${profiles.active}</directory>
<excludes>
</excludes>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
-->
<!--
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<configuration>
<createDependencyReducedPom>true</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.sf</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.dsa</exclude>
<exclude>META-INF/*.RSA</exclude>
<exclude>META-INF/*.rsa</exclude>
<exclude>META-INF/*.EC</exclude>
<exclude>META-INF/*.ec</exclude>
<exclude>META-INF/MSFTSIG.SF</exclude>
<exclude>META-INF/MSFTSIG.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.5</version>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.6.1</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.scala-tools</groupId>
<artifactId>maven-scala-plugin</artifactId>
<configuration>
<scalaVersion>${scala.version}</scalaVersion>
</configuration>
</plugin>
</plugins>
</reporting>
<profiles>
<profile>
<id>dev</id>
<properties>
<profiles.active>dev</profiles.active>
</properties>
</profile>
<profile>
<id>beta</id>
<properties>
<profiles.active>beta</profiles.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>prod</id>
<properties>
<profiles.active>prod</profiles.active>
</properties>
</profile>
<profile>
<id>followquant</id>
<properties>
<profiles.active>followquant</profiles.active>
</properties>
</profile>
<profile>
<id>betafollowquant</id>
<properties>
<profiles.active>betafollowquant</profiles.active>
</properties>
</profile>
</profiles>
</project>
<file_sep>/src/test/grpc_test.sh
kafkacat -b beta-hbase02:9092,beta-hbase03:9092,beta-hbase04:9092 \
-t crawldrv_grpc_test \
-D? \
-P <<EOF
{
"CrawlCategoryEnum": 0,
"Myasync": true,
"UserAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",
"Parallelism": 4,
"RandomDelay": 5,
"Url2Crawl": "https://finance.sina.com.cn/forex/",
"NewsEntry": "div[class^=main-content]",
"Queries2Extract":[
"h1[class=main-title]",
"div[class=top-bar-wrap]>div[class^='top-bar ani']>div[class='top-bar-inner clearfix']>div[class=date-source]>span[class=date]",
"div[class=top-bar-wrap]>div[class^='top-bar ani']>div[class='top-bar-inner clearfix']>div[class=date-source]>a[href]",
"div[class^='article-content clearfix']>div[class=article-content-left]>div[class=article][id=artibody]>p"
],
"ScriptPublishedAt": "ret = strings.replacer(\"年\", \"-\", \"月\", \"-\", \"日\", \"\").replace(\"%s\")",
"Logflag": 2
};
EOF
|
e817214fde831ad98b3ceac05aa807afaa6fa0e4
|
[
"Maven POM",
"Shell"
] | 3
|
Shell
|
bronzels/flink-crawldrv
|
2ffb735db4432b134099046c5b6cd0c5f3a36fc2
|
e218951a5bccb01b54f1aaa89060cbd5846bf220
|
refs/heads/master
|
<repo_name>akaluzny/rProjects<file_sep>/epl/parse_season.R
LoadSeason <- function(filename = "EPL games 13-14.csv") {
# Loads season from specified file containing a csv with all the games
#
# Args:
# filename: Name of file to load, defaults to "EPL 13-14.csv"
#
# Returns:
# Data frame with the following columns
# Date.Time: Date and time of when the game began
# Home.Team: Home team
# Away.Team: Away team
# Home.Score: Goals scored by the home team
# Away.Score: Goals scored by the away team
games <- read.csv(filename)
# Convert to time from format in file
games$Date.Time <- strptime(games$Date.Time, format = "%m/%d/%y %H:%M", tz = "GMT")
games
}
BuildLeagueTable <- function(games, start.time = "initial", finish.time = "final") {
# Builds a league table from individual games, including only games in the provided range
#
# Args:
# games: Data frame of individual games
# start.date: Only games from this time will be used to compute league table. Default or "initial" will start with the first game.
# finish.date: Only games up to this time will be used to compute league table. Default or "final" will finish with the last game.
#
# Returns:
# Data frame with the following columns
# Team: Team in position
# Home.Games: Number of home games played
# Home.Wins: Number of home wins
# Home.Draws: Number of home draws
# Home.Losses: Number of home losses
# Home.Scored: Number of home goals scored
# Home.Allowed: Number of home goals allowed
# Home.Goal.Difference: Difference in home goals
# Home.Points: Number of home points
# Away.Games: Number of away games played
# Away.Wins: Number of away wins
# Away.Draws: Number of away draws
# Away.Losses: Number of away losses
# Away.Scored: Number of away goals scored
# Away.Allowed: Number of away goals allowed
# Away.Goal.Difference: Difference in away goals
# Away.Points: Number of away points
# Games: Number of total games played
# Wins: Number of total wins
# Draws: Number of total draws
# Losses: Number of total losses
# Scored: Number of total goals scored
# Allowed: Number of total goals allowed
# Goal.Difference: Difference in total goals
# Points: Number of total points
# Assume all games take two hours
two.hours <- as.difftime(2, units = "hours")
if (start.time == "initial") {
# Initial time should begin with the first game
start.time <- games$Date.Time[1]
} else {
# Ongoing games should not be included
start.time <- start.time - two.hours
}
if (finish.time == "final") {
# Final time should end with the last game
finish.time <- games$Date.Time[nrow(games)]
} else {
# Ongoing games should not be included
finish.time <- finish.time - two.hours
}
# Select only games within the appropriate time interval
games <- games[games$Date.Time >= start.time & games$Date.Time <= finish.time, ]
# Table is equal to the number of teams
table <- data.frame(Team = levels(games$Home.Team))
by.home.team <- split(games, games$Home.Team)
by.away.team <- split(games, games$Away.Team)
# Calculate all home results
table$Home.Games <- sapply(by.home.team, nrow)
table$Home.Wins <- sapply(by.home.team, function(x) sum(x[, 4] > x[, 5]))
table$Home.Draws <- sapply(by.home.team, function(x) sum(x[, 4] == x[, 5]))
table$Home.Losses <- sapply(by.home.team, function(x) sum(x[, 4] < x[, 5]))
table$Home.Scored <- sapply(by.home.team, function(x) sum(x[, 4]))
table$Home.Allowed <- sapply(by.home.team, function(x) sum(x[, 5]))
table$Home.Goal.Difference <- table$Home.Scored - table$Home.Allowed
table$Home.Points <- table$Home.Wins * 3 + table$Home.Draws
# Calculate all away results
table$Away.Games <- sapply(by.away.team, nrow)
table$Away.Wins <- sapply(by.away.team, function(x) sum(x[, 4] < x[, 5]))
table$Away.Draws <- sapply(by.away.team, function(x) sum(x[, 4] == x[, 5]))
table$Away.Losses <- sapply(by.away.team, function(x) sum(x[, 4] > x[, 5]))
table$Away.Scored <- sapply(by.away.team, function(x) sum(x[, 5]))
table$Away.Allowed <- sapply(by.away.team, function(x) sum(x[, 4]))
table$Away.Goal.Difference <- table$Away.Scored - table$Away.Allowed
table$Away.Points <- table$Away.Wins * 3 + table$Away.Draws
# Calculate all total results by adding home and away
table$Games <- table$Home.Games + table$Away.Games
table$Wins <- table$Home.Wins + table$Away.Wins
table$Draws <- table$Home.Draws + table$Away.Draws
table$Losses <- table$Home.Losses + table$Away.Losses
table$Scored <- table$Home.Scored + table$Away.Scored
table$Allowed <- table$Home.Allowed + table$Away.Allowed
table$Goal.Difference <- table$Home.Goal.Difference + table$Away.Goal.Difference
table$Points <- table$Home.Points + table$Away.Points
# Sort standings by points, goal difference, and then goals
table[order(table$Points, table$Goal.Difference, table$Scored, decreasing = TRUE), ]
}
TeamRecordUpToTime <- function(games, team, last.time) {
# Returns a team's record calculated from the games provided, only including games up to provided time
#
# Args:
# games: Data frame of individual games
# team: Team whose record needs to be calculated
# last.date: Only games completed up to this time will be used to compute league table.
#
# Returns:
# Data frame with one row for the team and the following columns
# Team: Team in position
# Home.Games: Number of home games played
# Home.Wins: Number of home wins
# Home.Draws: Number of home draws
# Home.Losses: Number of home losses
# Home.Scored: Number of home goals scored
# Home.Allowed: Number of home goals allowed
# Home.Goal.Difference: Difference in home goals
# Home.Points: Number of home points
# Away.Games: Number of away games played
# Away.Wins: Number of away wins
# Away.Draws: Number of away draws
# Away.Losses: Number of away losses
# Away.Scored: Number of away goals scored
# Away.Allowed: Number of away goals allowed
# Away.Goal.Difference: Difference in away goals
# Away.Points: Number of away points
# Games: Number of total games played
# Wins: Number of total wins
# Draws: Number of total draws
# Losses: Number of total losses
# Scored: Number of total goals scored
# Allowed: Number of total goals allowed
# Goal.Difference: Difference in total goals
# Points: Number of total points
# Build a league table including games that began at least two hours before the provided time
table <- BuildLeagueTable(games[games$Date.Time < last.time - as.difftime(2, units = "hours"), ])
# Return the requested team from the table
table[table$Team == team, ]
}
|
7378bae14cbbf5f9c72186ec2b9f5623a407bacc
|
[
"R"
] | 1
|
R
|
akaluzny/rProjects
|
db7be31ac289bc0dd1b3ac5ba3b9983c2ac788f7
|
0e0dd5f3237a36076847c95699932af04dc7cac9
|
refs/heads/main
|
<file_sep>#!/bin/sh
VAULTWARDEN_HOME="$(dirname $0)"
cd "${VAULTWARDEN_HOME}"
. ./env.sh
if ! curl -fsS "http://${ROCKET_ADDRESS}:${ROCKET_PORT}/alive" >/dev/null; then
echo "vaultwarden server not alive, restarting it..."
./start.sh
fi
<file_sep>#!/bin/sh
VAULTWARDEN_HOME="$(dirname $0)"
cd "${VAULTWARDEN_HOME}"
. ./env.sh
if pgrep vaultwarden >/dev/null 2>&1; then
echo "Killing existing vaultwarden process..."
pkill vaultwarden
fi
nohup ./vaultwarden >>vaultwarden.log 2>&1 &
echo "Started vaultwarden."
<file_sep># This file is also read by a Python script, and doesn't support
# full shell syntax. Don't use quotes in values.
# The address of the vaultwarden backend. You shouldn't need to change this.
ROCKET_ADDRESS=127.0.0.1
# The port that the vaultwarden backend is configured to listen on.
# You only need to change this in the unlikely event that some other program
# on the shared host is already using this port.
ROCKET_PORT=28973
export ROCKET_ADDRESS ROCKET_PORT
<file_sep># Copyright (c) 2020-2021, <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
import sys, os
PYTHON_BIN = "/usr/bin/python3"
if sys.executable != PYTHON_BIN:
os.execl(PYTHON_BIN, PYTHON_BIN, *sys.argv)
import webob # https://pypi.org/project/WebOb/
import wsgiproxy # https://pypi.org/project/WSGIProxy2/
# Change this if you cloned the repo into a non-default directory.
VAULTWARDEN_HOME = "{}/{}".format(os.getenv("HOME"), "vaultwarden")
def getenv(key, default):
env_file = "{}/{}".format(VAULTWARDEN_HOME, "env.sh")
with open(env_file, "r") as f:
for ln in f:
ln = ln.strip()
if len(ln) == 0 or ln.startswith("#"):
# Skip blank/commented lines.
continue
toks = ln.split("=")
if len(toks) == 2:
# We're only looking for lines of the form KEY=VAL.
if key == toks[0].strip():
return toks[1].strip()
return default
BACKEND_HOST = getenv("ROCKET_ADDRESS", "127.0.0.1")
BACKEND_PORT = getenv("ROCKET_PORT", 28973)
HTTP_PREFIX = "http://"
HTTPS_PREFIX = "https://"
BACKEND_URL = "http://{}:{}".format(BACKEND_HOST, BACKEND_PORT)
PROXY = wsgiproxy.HostProxy(BACKEND_URL)
def application(environ, start_response):
req = webob.Request(environ)
if req.url.startswith(HTTP_PREFIX):
# Redirect HTTP to HTTPS.
https_url = HTTPS_PREFIX + req.url[len(HTTP_PREFIX):]
res = webob.exc.HTTPMovedPermanently(location=https_url)
else:
# Proxy the request to the backend.
res = req.get_response(PROXY)
start_response(res.status, res.headerlist)
return [res.body]
<file_sep>## Running Vaultwarden on a shared hosting service
**Note: Vaultwarden was formerly known as bitwarden_rs.**
This is not a common configuration, and not recommended compared to running
on a VPS or similar, but sometimes an organization only has access to a
shared hosting service and only wants to use that. This repo contains an
example of how that can be accomplished on
[DreamHost](https://www.dreamhost.com/) specifically, though with minor
changes, it can probably be applied to many other shared hosting services.
Shared hosting is generally geared towards running PHP apps. Many hosts also
support Ruby, Python, and/or Node.js apps, but there is generally no direct
support for reverse proxying to an arbitrary backend service. The example
provided here uses a small Python
[WSGI](https://en.wikipedia.org/wiki/Web_Server_Gateway_Interface) app to
proxy to the Vaultwarden backend.
This document assumes basic familiarity with Linux (knowing how to SSH into a
host, copy files to the host, make and change into directories, etc.).
## Prerequisites
In the DreamHost admin panel, create a new subdomain (e.g., `bw.example.org`)
and enable HTTPS and [Passenger](https://www.phusionpassenger.com/).
For more details, see [How do I enable Passenger on my domain?](https://help.dreamhost.com/hc/en-us/articles/216385637-How-do-I-enable-Passenger-on-my-domain-)
## Clone this repo
SSH into your subdomain account. From your home directory, run
$ git clone https://github.com/jjlin/vaultwarden-shared-hosting.git vaultwarden
This makes a copy of this repo in a directory called `vaultwarden`. You can use
a different directory name if you prefer, but you'll have to modify the value
of `VAULTWARDEN_HOME` in `passenger_wsgi.py` accordingly.
If the `git` command above isn't available for some reason, you can also just
download a zip file of the repo and extract it:
$ wget https://github.com/jjlin/vaultwarden-shared-hosting/archive/main.zip
$ unzip main.zip
$ mv vaultwarden-shared-hosting-main vaultwarden
Stay logged in via SSH, as the rest of the steps below will need SSH as well.
## Install Python dependencies
Run this command:
$ pip3 install WebOb WSGIProxy2
The output should look like:
Collecting WebOb
Using cached https://files.pythonhosted.org/packages/18/3c/de37900faff3c95c7d55dd557aa71bd77477950048983dcd4b53f96fde40/WebOb-1.8.6-py2.py3-none-any.whl
Collecting WSGIProxy2
Using cached https://files.pythonhosted.org/packages/2d/a5/3afac2542081b890de83e0089a0057cfb7dc9ad877ccc5594e6c6e1976b8/WSGIProxy2-0.4.6-py3-none-any.whl
Collecting six (from WSGIProxy2)
Using cached https://files.pythonhosted.org/packages/65/eb/1f97cb97bfc2390a276969c6fae16075da282f5058082d4cb10c6c5c1dba/six-1.14.0-py2.py3-none-any.whl
Installing collected packages: WebOb, six, WSGIProxy2
Successfully installed WSGIProxy2-0.4.6 WebOb-1.8.6 six-1.14.0
## Enable the Python WSGI proxy app
Copy the `passenger_wsgi.py` file in this repo into your
`/home/<user>/<subdomain>` directory.
Note that Passenger starts a persistent Python process that loads the
`passenger_wsgi.py` script. If you need to modify the script, you'll need to
kill the Python process (e.g., `pkill python3`) to force it to reload the
modified script.
For more details, see [Passenger and Python WSGI](https://help.dreamhost.com/hc/en-us/articles/215769548-Passenger-and-Python-WSGI).
If you visit your subdomain now (e.g., `https://bw.example.org`), you should
see a `502 Bad Gateway` message. This is because the Vaultwarden backend is
not yet running.
## Start the Vaultwarden backend
Make sure you're in the `vaultwarden` directory for the steps below.
### Download the Vaultwarden server and web vault
Run this command:
$ ./docker-image-extract vaultwarden/server:alpine
The output should look like the following (the layer IDs will likely all be different) :
Getting multi-arch manifest list...
Platform linux/amd64 resolved to 'sha256:deec30b3985444c8efc42338717a9b64f3185e1f3e149a7137afc98ebeb815e1'...
Getting API token...
Getting image manifest for vaultwarden/server:alpine...
Fetching and extracting layer c158987b05517b6f2c5913f3acef1f2182a32345a304fe357e3ace5fadcad715...
Fetching and extracting layer d58d1c0e0c7df3aac19cadde4e0910a04ab277976c90ab6973bd6018edd02588...
Fetching and extracting layer 630c69c2a5502c32eace11f461d2db3308aaa800b2f1207f5e194195d44b765b...
Fetching and extracting layer c655444a35c3827719e17f549f5421b211193d3bab3f1ff430ec3154651cecd4...
Fetching and extracting layer a940b1feefa501c534ededd3e6dee86cd6827fc5c100c798e07d33c4a0012097...
Fetching and extracting layer 857810bada4c372d6aa453ba9f7c0f1a029ab1a32bb20eb35790d8df76a61df2...
Image contents extracted into ./output.
This pulls the latest Vaultwarden server Docker image and extracts its files
into a directory called `output`. Move the server binary and web vault files
into your `vaultwarden` directory. The other files in `output` aren't needed,
so you can delete the directory afterwards.
$ mv output/vaultwarden output/web-vault .
$ rm -rf output
### Configure Vaultwarden
For purposes of this tutorial, start by copying `config.json.template` to
`config.json` and editing it as described below.
$ cp data/config.json.template data/config.json
$ # Now edit data/config.json with your preferred editor.
The initial `config.json` looks like
```json
{
"domain": "https://bw.example.org",
"admin_token": "<output of 'openssl rand -hex 32'>"
}
```
Do the following:
* Change the value of `domain` to the subdomain URL you selected.
* Run `openssl rand -hex 32` to generate a random 32-byte (256-bit) hex
string, and change the value of `admin_token` to this hex string. You'll
use this admin token to log into the admin page to perform further
configuration.
### Run the Vaultwarden backend server
Run this command:
$ ./start.sh
This script runs the `vaultwarden` executable in the background, with logs
saved in `vaultwarden.log`.
After this, visiting https://bw.example.org should show the Bitwarden web
vault interface, and https://bw.example.org/admin should lead to the admin
page (after you input the admin token).
You can re-run this command to restart the backend server if needed.
### Install the healthcheck script
This step is technically optional, but especially if your shared host only
allows a process to run for a certain amount of time or use a certain amount
of CPU, you'll want to set up a cron job that periodically checks that the
server process is still alive, and restarts it automatically if not.
Run this command:
$ crontab -e
Paste the contents of the `crontab` file in this repo into the editor and
save it. If you cloned this repo into a directory not named `vaultwarden`,
make sure to adjust the path in the crontab directive accordingly.
### Next steps
You'll probably want to lock down your settings a bit, and set up email
service. From the admin page, you should review at least the following
settings:
* General settings
* `Allow new signups` -- you might want to disable this so random users
can't create accounts on your server.
* `Require email verification on signups`
* SMTP Email Settings
* You can use your hosting service's SMTP server, in which case you should
consult their documentation (e.g.,
[Email client protocols and port numbers](https://help.dreamhost.com/hc/en-us/articles/215612887-Email-client-protocols-and-port-numbers)
for DreamHost).
* Your hosting service's SMTP service may not deliver email promptly. In
that case, you might consider using an external SMTP service like
[SendGrid](https://sendgrid.com/) or [MailJet](https://www.mailjet.com/).
These both provide 100-200 outgoing emails per day on their free tier,
which is probably enough for small organizations.
There are a lot more things that can be configured in Vaultwarden, and a
detailed treatment is beyond the scope of this tutorial. For more details,
the best place to start is
https://github.com/dani-garcia/vaultwarden/wiki/Configuration-overview.
### Upgrade Vaultwarden
From time to time, you may want to upgrade Vaultwarden to access bug fixes
or new features. To do this, change into the `vaultwarden` directory, stop
the Vaultwarden server, and delete the existing vaultwarden and web vault
files:
$ pkill vaultwarden
$ rm -rf vaultwarden web-vault
Then repeat the steps from
[Download the Vaultwarden server and web vault](#download-the-vaultwarden-server-and-web-vault)
and [Run the Vaultwarden backend server](#run-the-vaultwarden-backend-server).
## Limitations
This configuration currently doesn't support [WebSocket notifications](https://github.com/dani-garcia/vaultwarden/wiki/Enabling-WebSocket-notifications), though this isn't essential functionality.
But if you know how to get this to work in the shared host environment, feel free to send a PR.
<file_sep>#!/bin/sh
#
# This script pulls and extracts all files from an image in Docker Hub.
#
# Copyright (c) 2020-2023, <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
PLATFORM_DEFAULT="linux/amd64"
PLATFORM="${PLATFORM_DEFAULT}"
OUT_DIR="./output"
usage() {
echo "This script pulls and extracts all files from an image in Docker Hub."
echo
echo "$0 [OPTIONS...] IMAGE[:REF]"
echo
echo "IMAGE can be a community user image (like 'some-user/some-image') or a"
echo "Docker official image (like 'hello-world', which contains no '/')."
echo
echo "REF is either a tag name or a full SHA-256 image digest (with a 'sha256:' prefix)."
echo "The default ref is the 'latest' tag."
echo
echo "Options:"
echo
echo " -p PLATFORM Pull image for the specified platform (default: ${PLATFORM})"
echo " For a given image on Docker Hub, the 'Tags' tab lists the"
echo " platforms supported for that image."
echo " -o OUT_DIR Extract image to the specified output dir (default: ${OUT_DIR})"
echo " -h Show help with usage examples"
}
usage_detailed() {
usage
echo
echo "Examples:"
echo
echo "# Pull and extract all files in the 'hello-world' image tagged 'latest'."
echo "\$ $0 hello-world:latest"
echo
echo "# Same as above; ref defaults to the 'latest' tag."
echo "\$ $0 hello-world"
echo
echo "# Pull the 'hello-world' image for the 'linux/arm64/v8' platform."
echo "\$ $0 -p linux/arm64/v8 hello-world"
echo
echo "# Pull an image by digest."
echo "\$ $0 hello-world:sha256:90659bf80b44ce6be8234e6ff90a1ac34acbeb826903b02cfa0da11c82cbc042"
}
if [ $# -eq 0 ]; then
usage_detailed
exit 0
fi
while getopts ':ho:p:' opt; do
case $opt in
o)
OUT_DIR="${OPTARG}"
;;
p)
PLATFORM="${OPTARG}"
;;
h)
usage_detailed
exit 0
;;
\?)
echo "ERROR: Invalid option '-$OPTARG'."
echo
usage
exit 1
;;
\:) echo "ERROR: Argument required for option '-$OPTARG'."
echo
usage
exit 1
;;
esac
done
shift $(($OPTIND - 1))
if [ $# -eq 0 ]; then
echo "ERROR: Image to pull must be specified."
echo
usage
exit 1
fi
if [ -e "${OUT_DIR}" ]; then
if [ -d "${OUT_DIR}" ]; then
echo "WARNING: Output dir already exists. If it contains a previous extracted image,"
echo "there may be errors when trying to overwrite files with read-only permissions."
echo
else
echo "ERROR: Output dir already exists, but is not a directory."
exit 1
fi
fi
have_curl() {
command -v curl >/dev/null
}
have_wget() {
command -v wget >/dev/null
}
if ! have_curl && ! have_wget; then
echo "This script requires either curl or wget."
exit 1
fi
image_spec="$1"
image="${image_spec%%:*}"
if [ "${image#*/}" = "${image}" ]; then
# Docker official images are in the 'library' namespace.
image="library/${image}"
fi
ref="${image_spec#*:}"
if [ "${ref}" = "${image_spec}" ]; then
echo "Defaulting ref to tag 'latest'..."
ref=latest
fi
# Split platform (OS/arch/variant) into separate variables.
# A platform specifier doesn't always include the `variant` component.
OLD_IFS="${IFS}"
IFS=/ read -r OS ARCH VARIANT <<EOF
${PLATFORM}
EOF
IFS="${OLD_IFS}"
# Given a JSON input on stdin, extract the string value associated with the
# specified key. This avoids an extra dependency on a tool like `jq`.
extract() {
local key="$1"
# Extract "<key>":"<val>" (assumes key/val won't contain double quotes).
# The colon may have whitespace on either side.
grep -o "\"${key}\"[[:space:]]*:[[:space:]]*\"[^\"]\+\"" |
# Extract just <val> by deleting the last '"', and then greedily deleting
# everything up to '"'.
sed -e 's/"$//' -e 's/.*"//'
}
# Fetch a URL to stdout. Up to two header arguments may be specified:
#
# fetch <url> [name1: value1] [name2: value2]
#
fetch() {
if have_curl; then
if [ $# -eq 2 ]; then
set -- -H "$2" "$1"
elif [ $# -eq 3 ]; then
set -- -H "$2" -H "$3" "$1"
fi
curl -sSL "$@"
else
if [ $# -eq 2 ]; then
set -- --header "$2" "$1"
elif [ $# -eq 3 ]; then
set -- --header "$2" --header "$3" "$1"
fi
wget -qO- "$@"
fi
}
# https://docs.docker.com/docker-hub/api/latest/#tag/repositories
manifest_list_url="https://hub.docker.com/v2/repositories/${image}/tags/${ref}"
# If the ref is already a SHA-256 image digest, then we don't need to look up anything.
if [ -z "${ref##sha256:*}" ]; then
digest="${ref}"
else
echo "Getting multi-arch manifest list..."
digest=$(fetch "${manifest_list_url}" |
# Break up the single-line JSON output into separate lines by adding
# newlines before and after the chars '[', ']', '{', and '}'.
sed -e 's/\([][{}]\)/\n\1\n/g' |
# Extract the "images":[...] list.
sed -n '/"images":/,/]/ p' |
# Each image's details are now on a separate line, e.g.
# "architecture":"arm64","features":"","variant":"v8","digest":"sha256:054c85801c4cb41511b176eb0bf13a2c4bbd41611ddd70594ec3315e88813524","os":"linux","os_features":"","os_version":null,"size":828724,"status":"active","last_pulled":"2022-09-02T22:46:48.240632Z","last_pushed":"2022-09-02T00:42:45.69226Z"
# The image details are interspersed with lines of stray punctuation,
# so grep for an arbitrary string that must be in these lines.
grep architecture |
# Search for an image that matches the platform.
while read -r image; do
# Arch is probably most likely to be unique, so check that first.
arch="$(echo ${image} | extract 'architecture')"
if [ "${arch}" != "${ARCH}" ]; then continue; fi
os="$(echo ${image} | extract 'os')"
if [ "${os}" != "${OS}" ]; then continue; fi
variant="$(echo ${image} | extract 'variant')"
if [ "${variant}" = "${VARIANT}" ]; then
echo ${image} | extract 'digest'
break
fi
done)
fi
if [ -n "${digest}" ]; then
echo "Platform ${PLATFORM} resolved to '${digest}'..."
else
echo "No image digest found. Verify that the image, ref, and platform are valid."
exit 1
fi
# https://docs.docker.com/registry/spec/auth/token/#how-to-authenticate
api_token_url="https://auth.docker.io/token?service=registry.docker.io&scope=repository:$image:pull"
# https://github.com/docker/distribution/blob/master/docs/spec/api.md#pulling-an-image-manifest
manifest_url="https://registry-1.docker.io/v2/${image}/manifests/${digest}"
# https://github.com/docker/distribution/blob/master/docs/spec/api.md#pulling-a-layer
blobs_base_url="https://registry-1.docker.io/v2/${image}/blobs"
echo "Getting API token..."
token=$(fetch "${api_token_url}" | extract 'token')
auth_header="Authorization: Bearer $token"
# https://github.com/distribution/distribution/blob/main/docs/spec/manifest-v2-2.md
docker_manifest_v2="application/vnd.docker.distribution.manifest.v2+json"
# https://github.com/opencontainers/image-spec/blob/main/manifest.md
oci_manifest_v1="application/vnd.oci.image.manifest.v1+json"
# Docker Hub can return either type of manifest format. Most images seem to
# use the Docker format for now, but the OCI format will likely become more
# common as features that require that format become enabled by default
# (e.g., https://github.com/docker/build-push-action/releases/tag/v3.3.0).
accept_header="Accept: ${docker_manifest_v2},${oci_manifest_v1}"
echo "Getting image manifest for $image:$ref..."
layers=$(fetch "${manifest_url}" "${auth_header}" "${accept_header}" |
# Extract `digest` values only after the `layers` section appears.
sed -n '/"layers":/,$ p' |
extract 'digest')
if [ -z "${layers}" ]; then
echo "No layers returned. Verify that the image and ref are valid."
exit 1
fi
mkdir -p "${OUT_DIR}"
for layer in $layers; do
hash="${layer#sha256:}"
echo "Fetching and extracting layer ${hash}..."
fetch "${blobs_base_url}/${layer}" "${auth_header}" | gzip -d | tar -C "${OUT_DIR}" -xf -
# Ref: https://github.com/moby/moby/blob/master/image/spec/v1.2.md#creating-an-image-filesystem-changeset
# https://github.com/moby/moby/blob/master/pkg/archive/whiteouts.go
# Search for "whiteout" files to indicate files deleted in this layer.
OLD_IFS="${IFS}"
find "${OUT_DIR}" -name '.wh.*' | while IFS= read -r f; do
dir="${f%/*}"
wh_file="${f##*/}"
file="${wh_file#.wh.}"
# Delete both the whiteout file and the whited-out file.
rm -rf "${dir}/${wh_file}" "${dir}/${file}"
done
IFS="${OLD_IFS}"
done
echo "Image contents extracted into ${OUT_DIR}."
|
848e97bfc60fb038b4871cecce77120212883e06
|
[
"Markdown",
"Python",
"Shell"
] | 6
|
Shell
|
jjlin/bitwardenrs-shared-hosting
|
05e9ab34dfc6445fcd513507c4a956f9b79f2167
|
0459ffca6c9090e27ed09c0d2443bbee486d0a30
|
refs/heads/master
|
<file_sep>log4j.rootCategory=info,stdout,file
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[QC%-d{yyyy-MM-dd HH:mm:ss}] %p [%t] %C.%M(%L) | %m%n
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.Append=true
log4j.appender.file.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.file.File=logs/log
log4j.appender.file.Threshold=INFO
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[QC%-d{yyyy-MM-dd HH:mm:ss}] %p [%t] %C.%M(%L) | %m%n<file_sep>package cn.xiaosheng996.NettyProtobufTcpClient;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.LazyStringList;
public class ProtoPrinter {
public static void print(Object object) throws Exception {
try {
StringBuilder builder = new StringBuilder();
Class<?> objClass = object.getClass();
Class<?> builderClass = null;
for(Class<?> cls : objClass.getDeclaredClasses()) {
if("Builder".equals(cls.getSimpleName())) {
builderClass = cls;
break;
}
}
if (builderClass != null) {
for(Field field : builderClass.getDeclaredFields()) {
if(field.getName().startsWith("bitField")) {
continue;
}
if (field.getName().indexOf("Builder") >= 0) {
continue;
}
Method getter = null;
Object value = null;
if(field.getType().isAssignableFrom(String.class)) {
getter = objClass.getDeclaredMethod("get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1).replaceAll("_", ""), new Class[0]);
} else if(field.getType().isAssignableFrom(List.class)) {
getter = objClass.getDeclaredMethod("get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1).replaceAll("_", "List"), new Class[0]);
} else if(field.getType().isAssignableFrom(LazyStringList.class)) {
getter = objClass.getDeclaredMethod("get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1).replaceAll("_", "List"), new Class[0]);
} else {
//System.out.println("get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1).replaceAll("_", ""));
getter = objClass.getDeclaredMethod("get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1).replaceAll("_", ""), new Class[0]);
}
builder.append("\n" + field.getName().replaceAll("_", "") + ":");
value = getter.invoke(object, new Object[0]);
//System.out.println(value);
doPrint(value, "", builder);
}
}
System.out.println(builder.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("rawtypes")
private static void doPrint(Object object, String offset, StringBuilder result) {
try {
if(object instanceof String) {
result.append(object.toString());
} else if(object instanceof List) {
result.append("[");
List list = (List) object;
for(Object obj : list) {
doPrint(obj, offset, result);
result.append(",");
}
result.append("]");
} else if (object instanceof GeneratedMessageV3) {
Class<?> objClass = object.getClass();
result.append("{");
Class<?> builderClass = null;
for(Class<?> cls : objClass.getDeclaredClasses()) {
if("Builder".equals(cls.getSimpleName())) {
builderClass = cls;
break;
}
}
if (builderClass != null) {
for(Field field : builderClass.getDeclaredFields()) {
if("bitField0_".equals(field.getName())) {
continue;
}
Object value = null;
Method getter = null;
if(field.getType().isAssignableFrom(String.class)) {
getter = objClass.getDeclaredMethod("get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1).replaceAll("_", ""), new Class[0]);
} else if(field.getType().isAssignableFrom(List.class)) {
getter = objClass.getDeclaredMethod("get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1).replaceAll("_", "List"), new Class[0]);
} else if(field.getType().isAssignableFrom(LazyStringList.class)) {
getter = objClass.getDeclaredMethod("get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1).replaceAll("_", "List"), new Class[0]);
} else {
getter = objClass.getDeclaredMethod("get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1).replaceAll("_", ""), new Class[0]);
}
value = getter.invoke(object, new Object[0]);
result.append("\n" + offset + "\t" + field.getName().replaceAll("_", "") + ":");
doPrint(value, offset + "\t", result);
}
}
result.append("}");
} else {
result.append(object.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>package cn.xiaosheng996.NettyProtobufTcpClient;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.apache.log4j.PropertyConfigurator;
import com.google.protobuf.Message;
import proto.RoleProto.LoginReq_1001001;
/**
* Java游戏服务器编程
* @author 小圣996
* https://www.jianshu.com/u/711bb4362a2a
*/
public class App{
public static void main( String[] args ){
// 装入log4j配置信息
PropertyConfigurator.configure("src/main/resource/log4j.properties");
NettyTcpClient.instance().conect("127.0.0.1", 38996);
login();
}
//请求登录
private static void login(){
LoginReq_1001001.Builder builder = LoginReq_1001001.newBuilder();
builder.setAccount("xiaosheng996");
builder.setPassword("<PASSWORD>");
NettyTcpClient.instance().send(builder.build());
}
}
<file_sep># 使用Netty+Protobuf实现游戏TCP通信--客户端
使用Netty+Protobuf实现游戏TCP通信--客户端
|
4c87a9a2bacf7f58b8be668a74a3a6855f43b692
|
[
"Markdown",
"Java",
"INI"
] | 4
|
INI
|
zhou-hj/NettyProtobufTcpClient
|
601667e71d68f0f94ec922f5ac504a4f50bbc5ea
|
0d497b56fc1c293b81dcf8f633111d019e733c77
|
refs/heads/master
|
<file_sep>/*
AMP prototype control
Author - <NAME>
*/
#include <Servo.h>
#define pin_in_1 2 // digital out
#define pin_en_A 3 // PWM
#define pin_in_2 4 // digital out
#define pin_servo 5 // servo pwm pin
#define FORWARD 0 // forward flag
#define REVERSE 1 // reverse flag
#define R_GEAR_1_D 0.04 // 40 mm
#define R_GEAR_2_D 0.06 // 60 mm
#define WHEEL_DIAMETER 0.116 // 116 mm
#define F_GEAR_SERVO_D 0.025 // 25 mm
#define QUARTER_GEAR_CIRCUMFERENCE 0.019635 // 19.635 mm
#define STEERING_LEVER 0.030 // 30 mm
// MACROS
#define RAD_TO_DEG(x) (round((180 * x) / 3.14159))
/*
For Motor Control The Direction is Defined as:
Setup:
Red --> OUT1 on L298N
Black --> OUT2 on L298N
Control: (Looking at top of motor)
IN1 IN2 DIR
H L CW
L H CCW
MAX_SPEED W/ CURRENT CONFIG --> 0.125 m/s
MAX STEERING ANGLE -->
*/
#define RPM_POINTS 11
// Represents motor rpm for the respective pwm setting
const float rpm_values[] = {0, 5.26, 14.34, 19.0, 23.1, 26.0, 27.4, 29.1, 29.3, 30.3, 32.0};
// The pwm setting for the respective motor rpm output
const unsigned char pwm_settings[] = {0, 50, 75, 100, 125, 150, 175, 200, 225, 250, 255};
// Instantiate the servo object for control
Servo servo;
void setup() {
pinMode(pin_en_A, OUTPUT);
pinMode(pin_in_1, OUTPUT);
pinMode(pin_in_2, OUTPUT);
servo.attach(pin_servo);
Serial.begin(9600);
}
void loop() {
move_steering(-0.174533);
delay(5000);
move_steering(0.610865);
delay(5000);
}
/*
Velocity is measured from the RPM of the motor.
Example: Assuming 30 RPM on motor, the actual velocity
of the vehicle will be:
RPM @ Wheel Shaft --> (30 RPM) * (R_GEAR_1_D / R_GEAR_2_D)
Meters Per Minute --> (RPM @ Wheel Shaft) * (pi * WHEEL_DIAMETER)
Meters Per Second --> (Meters Per Minute) / 60 seconds per minute
This function takes the inverse of this and calculates what motor
RPM is necessary in order to get the desired velocity.
Going forward is a postive motor speed
Going backward is a negative motor speed
*/
void move_translation(char dir, float vel) {
// Initialize local variables
unsigned char pwm_setting = 0; // variable to hold the necessary pwm duty cycle setting
// Return if velocity is zero as that indicates no movement
if (vel == 0) {
return;
}
// Get the pwm setting necessary for the specified velocity
pwm_setting = get_pwm_value(vel);
// For forward movement, CW motor movement is needed
if (FORWARD == dir && vel > 0) {
set_vehicle_direction(FORWARD);
}
// For reverse movement, CCW motor movement is needed
else if (REVERSE == dir && vel > 0) {
set_vehicle_direction(REVERSE);
}
// Set the motor speed
analogWrite(pin_en_A, pwm_setting);
}
/*
This function moves the servo to the desired steering angle
For consistency between the ROS framework ouput and the controls
the angle will be measure in radians.
The actual calculation will be used using the cosine rule.
The movement needed will be based off of the steering angle
given by ROS system.
Going left is a positive angle in radians
Going right is a negative angle in radians
*/
void move_steering(float angle) {
// Initialize local variables
float steering_distance = 0.0; // the distance the rack needs to move on the
// steering mechanism to get the given steering angle
float angle_delta = 0.0; // the angle to be added / subtracted to get the full angle
// Calculate steering distance needed
steering_distance = sqrt((2 * (STEERING_LEVER * STEERING_LEVER)) - (2 * STEERING_LEVER * STEERING_LEVER * cos(angle)));
// Determine distance necessary servo needs to turn
// First check to see that the steering distance is not too large
// If it is reverse the vehicle
if (((F_GEAR_SERVO_D * 3.14159) / 4) < steering_distance) {
servo.write(90);
move_translation(REVERSE, 0.5);
return;
}
// Otherwise calculate the necessary servo angle
angle_delta = (steering_distance / QUARTER_GEAR_CIRCUMFERENCE) * 90;
// An angle that is greater than 90 indicates a right turn on the servo
// An angle that is less than 90 indicates a left turn on the servo
if (angle < 0) {
servo.write(90 + angle_delta);
}
else if (angle > 0) {
servo.write(90 - angle_delta);
}
else {
servo.write(90);
}
}
/*
The following function sets the motor configuration necessary
in order to either move the vehicle forward or backwards
Due to the gear reduction used movement is defined as follows:
Forward --> CCW spin on the motor
Reverse --> CW spin on the motor
*/
void set_vehicle_direction(char dir) {
// From the table in the top comment forward movement indicates CCW movement
if (FORWARD == dir) {
digitalWrite(pin_in_1, LOW);
digitalWrite(pin_in_2, HIGH);
}
// From the table in the top comment forward movement indicates CW movement
else if (REVERSE == dir) {
digitalWrite(pin_in_1, HIGH);
digitalWrite(pin_in_2, LOW);
}
return;
}
/*
This function calcuates the necessary duty cycle value
necessary in order to get the desired velocity.
The function uses linear interpolation from a set of hand
calculated values in order to determine the appropriate value.
TODO: Determine if a load factor needs to be used for the motor rpm
*/
int get_pwm_value(float vel) {
// Initialize local variables
float motor_rpm = 0.0; // variable to hold the motor rpm necessary
unsigned char pwm_setting = 0; // variable to hold the calculated pwm setting
// Calculate necessary motor rpm for the desired velocity
motor_rpm = ((vel * 60) / (PI * WHEEL_DIAMETER)) / (R_GEAR_1_D / R_GEAR_2_D);
// Perform linear interpolation on the given set of data to determine
// the correct PWM duty cycle setting necessary to drive the motor.
pwm_setting = perform_linear_interpolation(motor_rpm);
return pwm_setting;
}
/*
This function performs the linear interpolation needed to the PWM setting
necessary to spin at the specified motor RPM
*/
int perform_linear_interpolation(float motor_rpm) {
// Initialize local variables
float rpm_diff_spec_low = 0.0; // delta of specified motor rpm and low bound
float rpm_diff_high_low = 0.0; // delta of high rpm bound and low rpm bound
float pwm_diff_high_low = 0; // delta of high pwm bound and low pwm bound
unsigned char resulting_pwm = 0; // the resulting pwm setting
unsigned char i = 0; // iterator for while loop
// Find data range that the specified motor_rpm lies in
while (i < RPM_POINTS && (motor_rpm > rpm_values[i])) {
i++;
}
// Check exit / edge cases
// 1. RPM value not found or is too large for data set
// therefore return 255 pwm duty cycle setting (max speed)
if (RPM_POINTS == i) {
return 255;
}
// 2. RPM value is zero or below (error case)
// return 0
if (0 == i) {
return 0;
}
// 3. Normal case (i == 1 through i == 10)
// Calculate rpm specified to low delta
rpm_diff_spec_low = motor_rpm - rpm_values[i - 1];
// Calculate rpm high to low bound delta
rpm_diff_high_low = rpm_values[i] - rpm_values[i - 1];
// Calculate pwm high to low bound delta
pwm_diff_high_low = pwm_settings[i] - pwm_settings[i - 1];
// Adding proportional delta to the low bound of the pwm settings
resulting_pwm = ceil(pwm_settings[i - 1] + ((rpm_diff_spec_low / rpm_diff_high_low) * pwm_diff_high_low));
return resulting_pwm;
}
|
d030cf784ac71ca620dffe70a7694a0b0d530915
|
[
"C++"
] | 1
|
C++
|
dpimley/AMP-Prototype-Control
|
5f989022c4bc72a718ae2f6cb220d69fc961d612
|
124cf95c04d940de9cc920af0f17a47ff95afeec
|
refs/heads/master
|
<repo_name>angus890519/Advanced-homework13<file_sep>/Advanced-homework13.cpp
/* 計算機概論實務-進階練習作業-作業13 */
/* 製作人:郭柏鋒 */
/* 完成時間:2019/05/24 10:00 */
#include <stdio.h> //函示庫
#include <stdlib.h> //函示庫
struct company //定義結構體
{
char name[30],employee[10];
int quota;
};
struct individual //定義結構體
{
char name[10],tel[12];
int quota;
};
union client //定義結構體
{
struct company comp;
struct individual indiv;
};
int main(void)
{
printf("計算機概論實務-進階練習作業-作業13\n");
printf("製作人:郭柏鋒\n");
printf("完成時間:2019/05/24 10:40\n");
printf("-----------------------------------\n");
int choice;
union client c;
printf("請選擇1.企業團體意外保險,2.個人意外保險: ");
scanf(" %d", &choice);//輸入
if (choice==1)
{
printf("請輸入企業名稱: ");
scanf(" %s", c.comp.name);//輸入
printf("請輸入員工姓名: ");
scanf(" %s", c.comp.employee);//輸入
printf("請輸入投保金額: ");
scanf(" %d", &(c.comp.quota)); //輸入
//顯示出來
printf("企業名稱: %s\n", c.comp.name);
printf("員工姓名: %s\n", c.comp.employee);
printf("投保金額: %d\n", c.comp.quota);
}
else if (choice==2)
{
printf("請輸入個人姓名: ");
scanf(" %s", c.indiv.name);//輸入
printf("請輸入個人電話: ");
scanf(" %s", c.indiv.tel);//輸入
printf("請輸入投保金額: ");
scanf(" %d", &(c.indiv.quota));//輸入
//顯示出來
printf("個人姓名: %s\n", c.indiv.name);
printf("個人電話: %s\n", c.indiv.tel);
printf("投保金額: %d\n", c.indiv.quota);
}
else printf("輸入錯誤\n");
system("pause");//暫停視窗
return 0;//回傳值 0
}
|
97146d019baa2338d568fe929287f568c2c5dc3e
|
[
"C++"
] | 1
|
C++
|
angus890519/Advanced-homework13
|
a8ccd0ba03a76b8391df11b950271c57aa11597d
|
7eb9d846c63ab5eac0540cd40dea4c43982a0a06
|
refs/heads/master
|
<repo_name>Prangwalai994/2_6<file_sep>/MathTests 2_6/UnitTest1.cs
using System;
using Writing_a_simple_UnitTest2_6.Fandementals;
using NUnit.Framework;
namespace MathTests_2_6
{
[TestFixture]
public class MathTests
{
[Test]
public void Add_WhenCalled_ReturnTheSumOfArguments()
{
var math = new Math();
var result = math.Add(1, 2);
Assert.That(result, Is.EqualTo(3));
}
}
}
|
d611210525c321d29e02549b37512bab0195d3a0
|
[
"C#"
] | 1
|
C#
|
Prangwalai994/2_6
|
92f66e16640dc815954db0ae2e6b683397ccf6b2
|
339a2d456a52dabd64c6c3fe375a9eace26fd7bc
|
refs/heads/master
|
<file_sep>/*
* Author: <NAME>
* Date: 2019-2-25
* header of tree structure, templates defination must located in header
*/
#ifndef _BINARY_SEARCH_TREE_H_
#define _BINARY_SEARCH_TREE_H_
#include <iostream>
#include <algorithm>
#include "exceptions.h"
template <typename Comparable>
class BinarySearchTree
{
public:
BinarySearchTree() : root(nullptr)
{}
BinarySearchTree(const BinarySearchTree &rhs) : root(nullptr)
{
root = clone(rhs.root);
}
// BinarySearchTree(BinarySearchTree && rhs) : root(rhs->root)
// {
// rhs.root = nullptr;
// }
BinarySearchTree &operator=(const BinarySearchTree &rhs)
{
BinarySearchTree temp(rhs);
std::swap(*this, temp); //Effective C++ item 11
return *this; //Effective C++ item 10
}
~BinarySearchTree()
{
makeEmpty();
}
const Comparable &findMax() const
{
if(isEmpty())
{
throw UnderflowException{};
}
return findMax(root)->element;
}
const Comparable &findMin() const
{
if(isEmpty())
{
throw UnderflowException{};
}
return findMin(root)->element;
}
bool contains(const Comparable &x) const
{
return contains(x, root);
}
bool isEmpty() const
{
return root == nullptr;
}
// void printTree() const
// {
// printTree(cout, root);
// }
void makeEmpty()
{
makeEmpty(root);
}
void insert(const Comparable & x)
{
insert(x, root);
}
void remove(const Comparable & x)
{
remove(x, root);
}
private:
struct BinaryNode
{
Comparable element;
BinaryNode *left; //left child
BinaryNode *right; //right child
BinaryNode(const Comparable &x, BinaryNode *lt, BinaryNode *rt):
element(x), left(lt), right(rt){}
};
void remove(const Comparable &x, BinaryNode * & t)
{
if(t == nullptr)
return ;
else if(x < t->element)
{
remove(x, t->left);
}
else if(x > t->element)
{
remove(x, t->right);
}
else //find the element which will be removed
{
if((t->left != nullptr) && (t->right != nullptr)) //have both tow children(left child and right child).
{
t->element = findMin(t->right)->element; //get the min of right subtree
remove(t->element, t->right); //remove the min of right subtree
}
else
{
BinaryNode *oldNode = t;
if(t->left != nullptr) //left child is avaliable.
{
t = t->left;
}
else //right child is avaliable or right child is nullptr.
{
t = t->right;
}
delete oldNode; //needn't make oldNode to nullptr, cause pointer "oldNode" is a tmp object, it will release after out of range.
}
}
}
bool contains(const Comparable &x, BinaryNode *t) const
{
if(t == nullptr)
{
return false;
}
else if (x < t->element)
{
return contains(x, t->left);
}
else if(x > t->element)
{
return contains(x, t->right);
}
else
{
return true;
}
}
void makeEmpty(BinaryNode * & t)
{
if(t != nullptr)
{
makeEmpty(t->left);
makeEmpty(t->right);
delete t;
}
t = nullptr; //delete之后不要忘记赋上nullptr;
}
// void printTree(const ostream & os, BinaryNode *t)
// {
// }
BinaryNode *findMax(BinaryNode *t) const
{
if(t != nullptr)
{
while(t->right != nullptr)
{
t = t->right;
}
}
return t;
}
BinaryNode *findMin(BinaryNode *t) const
{
if(t != nullptr)
{
while(t->left != nullptr)
{
t = t->left;
}
}
return t;
}
void insert(const Comparable &x, BinaryNode *& t)
{
if(t == nullptr)
{
t = new BinaryNode{x, nullptr, nullptr};
}
else if(x < t->element)
{
insert(x, t->left);
}
else if(x > t->element)
{
insert(x, t->right);
}
else//有重复元素,不做操作
{
/* code */
}
}
BinaryNode *root;
};
//implement in function object
// template <typename Object, typename Comparable = less<Object>>
// class BinarySearchTreeWithComp
// {
// public:
// BinarySearchTree();
// BinarySearchTree(const BinarySearchTree &rhs);
// BinarySearchTree &operator=(const BinarySearchTree &rhs);
// ~BinarySearchTree();
// const Object &findMax() const;
// const Object &findMin() const;
// bool contains(const Object &x) const;
// bool isEmpty() const;
// void printTree() const;
// void makeEmpty();
// void insert(const Object & x);
// void remove(const Object & x);
// private:
// struct BinaryNode
// {
// Object element;
// BinaryNode *left; //left child
// BinaryNode *right; //right child
// BinaryNode(const Object &x, BinaryNode *lt, BinaryNode *rt):
// element(x), left(lt), right(rt){}
// };
// void remove(const Object &x, BinaryNode * & t);
// bool contains(const Object &x, BinaryNode *t) const;
// void makeEmpty(BinaryNode * & t);
// void print(BinaryNode *t);
// BinaryNode *root;
// };
#endif<file_sep>/*
* Author: <NAME>
* Date: 2019-2-25
* header of project
*/
#ifndef _DATASTRUCTUREINC_H_
#define _DATASTRUCTUREINC_H_
#include <stdio.h>
#include <stdlib.h>
#endif<file_sep>TARGET = testbinarysearchTree
OBJS = binarysearchtree.o testbinarysearchtree.o
CFLAG = -I../include -std=c++0x
all: ${OBJS}
${OBJS}: %.o: %.cpp
g++ -c -g ${CFLAG} $<
all: ${TARGET}
${TARGET}: %: %.o
g++ -o $@ $< binarysearchtree.o
clean:
rm -f ${TARGET} *.o<file_sep>/*
* Author: Chengx
* Date: 2019-3-14
* Description:
*/
#ifndef _SORT_H_
#define _SORT_H_
#include <iostream>
#include <vector>
#include <utility>
template <typename T>
class Sort
{
public:
Sort(std::vector<T> &values) : m_values(values){printValues();}//如何复制效率高?
Sort(std::vector<T> &&values) : m_values(values)
{
std::cout << "rvalues constructor..." << std::endl;
printValues();
}
void printValues()
{
for(const auto &a : m_values)
std::cout << a << " ";
std::cout << std::endl;
}
void bubbleSort()
{
printValues();
T tmp;
int count = m_values.size();
if(count <= 0)
{
return ;
}
for (int i = 0; i < count; ++i)
{
for (int j = count - 1; j >= i; j--){
if (m_values[j] < m_values[j - 1]){
// tmp = m_values[j];
// m_values[j] = m_values[j - 1];
// m_values[j - 1] = tmp;
std::swap(m_values[j], m_values[j - 1]);
}
}
}
}
void insertSort()
{
printValues();
T flag;
int count = m_values.size();
if(count == 0)
{
return ;
}
for (int i = 1; i < count; ++i)//第一个值默认有序
{
flag = std::move(m_values[i]);
int j = i;
for (; (j > 0) && (flag < m_values[j - 1]); --j)//Find the position of insertation
{
m_values[j] = std::move(m_values[j - 1]);
}
m_values[j] = std::move(flag);
}
}
void selectSort()
{
//Exchange with the smallest item in every round.
printValues();
int count = m_values.size();
if(count <= 0)
{
return ;
}
T min, tmp;
int index;
for (int i = 0; i < count; ++i)
{
min = m_values[i]; //Initial the min
index = i; //Initial the index of the min
for (int j = i; j < count; ++j)
{
if (min > m_values[j]){ //Find the min
min = m_values[j];
index = j; //Get the index of the min
}
}
// tmp = m_values[i]; //Exchange the min and the vecT[i];
// m_values[i] = m_values[index];
// m_values[index] = tmp;
std::swap(m_values[i], m_values[index]);
}
}
void heapSort();
void shellSort()
{
printValues();
int count = m_values.size();
if(count == 0)
{
return ;
}
for(int gap = count / 2; gap > 0; gap /= 2)
{
for(int i = gap; i < count; ++i)
{
T tmp = std::move(m_values[i]);
int j = i;
for(; j >= gap && tmp < m_values[j - gap]; j -= gap)
{
m_values[j] = std::move(m_values[j - gap]);
}
m_values[j] = std::move(tmp);
}
}
}
void mergeSort();
void quickSort();
//void externalSort();
private:
private:
std::vector<T> &m_values;
};
#endif<file_sep>#include "graph.h"
void BFS(GraphList g)
{
int i;
int visited[MAXVEX];
EdgeNode *p;
Queue q;
for (i = 0; i < g.numVertexes; i++)
{
visited[i] = 0;
}
InitQueue(&q);
for (i = 0; i < g.numVertexes; i++)
{
if (!visited[i])
{
visited[i] = 1;
printf("%c ",g.adjList[i].data);
EnQueue(&q,i);
while (!QueueEmtpy(q))
{
int m;
DeQueue(&q,&m);
p = g.adjList[i].firstedge;
while (p)
{
if (!visited[p->adjvex])
{
visited[p->adjvex] = 1;
printf("%c ",g.adjList[p->adjvex].data);
EnQueue(&q,p->adjvex);
}
p = p->next;
}
}
}
}
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include "graph.h"
#include "Queue.h"
void TopSort(GraphList g)
{
Queue Q;
int Counter = 0;
int V, W;
int indegree[MAXVEX]; //维护每个节点的入度(indegree),初始化时需要遍历整张图
int topNum[MAXVEX];
EdgeNode* p;
Q = CreateQueue(MAXVEX);
MakeEmpty(Q);
for (int i = 0; i < g.numVertexes; i++)
{
if (indegree[i] == 0)
Enqueue(i, Q);
}
while (!IsEmpty(Q))
{
V = Dequeue(Q); //队列的操作需要重写
topNum[V] = Counter++;
for (int i = 0; i < MAXVEX; i++)
{
p = g.adjList[i].firstedge;
//此处代码可用初始化indegree数组,表示入度
//while (p != NULL)
//{
// if (p->adjvex == V)
// indegree[V]++;
//}
while (p != NULL)
{
if (--indegree[W])
Enqueue(W,Q);
}
}
}
if (Counter != MAXVEX)
printf("Graph has a circule\n");
DisposeQueue(Q);
}
<file_sep>/*
* Author: Chengx
* Date: 2019-3-18
* Description: implement file
*/
#include "sort.h"
<file_sep>/*
* Author: <NAME>
* Date: 2019-2-25
* implement file of graph
*/
#include "datastructureinc.h"
int Locate(GraphList* g, char ch)
{
int i;
for (i = 0; i < MAXVEX; i++)
{
if (ch == g->adjList[i].data)
{
break;
}
}
if (i >= MAXVEX)
{
printf("can't find this vertex\n");
return -1;
}
return i;
}
void CreateGraph(GraphList *g)
{
int i, j, k;
EdgeNode *e;
EdgeNode *f;
printf("Enter the number of vertex and edges:\n");
scanf("%d,%d", &g->numVertexes, &g->numEdges);
for (i = 0; i < g->numVertexes; i++)
{
printf("please enter vertex %d:\n", i);
g->adjList[i].data = getchar();
g->adjList[i].firstedge = NULL;
while (g->adjList[i].data == '\n')
{
g->adjList[i].data = getchar();
}
}
for (k = 0; k<g->numEdges; k++)
{
printf("input edge<vi,vj>:\n");
char p, q;
p = getchar();
while (p == '\n')
{
p = getchar();
}
q = getchar();
while (q == '\n')
{
q = getchar();
}
int m, n;
m = Locate(g, p);
n = Locate(g, q);
if (m == -1 || n == -1)
{
return;
}
e = (EdgeNode*)malloc(sizeof(EdgeNode));
if (e == NULL)
{
printf("malloc failed!\n");
return;
}
e->adjvex = n;
e->next = g->adjList[i].firstedge;
g->adjList[m].firstedge = e;
f = (EdgeNode *)malloc(sizeof(EdgeNode));
f->next = g->adjList[i].firstedge;
g->adjList[n].firstedge = f;
}
}
void printGraph(GraphList *g)
{
int i = 0;
while (g->adjList[i].firstedge != NULL &&i<MAXVEX)
{
printf("Vertex:%c ",g->adjList[i].data);
EdgeNode* e = NULL;
e = g->adjList[i].firstedge;
while (e != NULL)
{
printf("%d ",e->adjvex);
e = e->next;
}
i++;
printf("\n");
}
}
<file_sep># DataStructureInC
# Data Structure In C by <NAME>
# Coding by dabao085
<file_sep>/*
* Author: <NAME>
* Date: 2019-2-26
* header of exception
*/
#ifndef _EXCEPTIONS_H_
#define _EXCEPTIONS_H_
class UnderflowException {};
#endif<file_sep>#include <stdio.h>
#include <string.h>
int* getPrefix(char P[]) //在自己身上找重复的子串,字符串的下标从1开始
{
int m = strlen(P);
int pi[3] = {0};
pi[1] = 0;
int k = 0;
for (int q = 2; q <= m;q++)
{
while (k > 0 && P[k + 1] != P[q])
{
k = pi[k];
}
if (P[k + 1] == P[q])
k = k + 1;
pi[q] = k;
}
return pi;
}
void KMP_Matcher(char T[],char P[],int length1,int length2)
{
int n = length1;
int m = length2;
int *ppi;
ppi= getPrefix(P, length2);
int q = 0;
for (int i = 1; i <= n; i++)
{
while (q > 0 && P[q + 1] != T[i])
{
q = ppi[q];
}
if (P[q + 1] == T[i])
{
q = q + 1;
}
if (q == m)
{
printf("Pattern occurs with shift %d\n",i-m);
q = ppi[q];
}
}
}
int main()
{
char ch1[] = " hello world! wo";
char ch2[] = " wo";
KMP_Matcher(ch1, ch2, 17, 3);
return 0;
}
<file_sep>CFLAG = -g -std=c++11
OBJS = mainTest.o sort.o
sortTest: mainTest.o sort.o
g++ ${CFLAG} -o sortTest mainTest.o sort.o
all: ${OBJS}
${OBJS}: %.o: %.cpp
g++ ${CFLAG} -c $<
clean:
rm -f *.o sortTest
<file_sep>#include "graph.h"
int visited[MAXVEX];
void DFS(GraphList g, int i)
{
EdgeNode *p;
visited[i] = 1;
printf("%c ",g.adjList[i].data);
p = g.adjList[i].firstedge;
while (p)
{
if (!visited[p->adjvex])
{
DFS(g, p->adjvex);
}
p = p->next;
}
}
void DFSTraverse(GraphList g)
{
int i;
for (i = 0; i < g.numVertexes; i++)
{
visited[i] = 0;
}
for (i = 0; i < g.numVertexes; i++)
{
if (!visited[i])
{
DFS(g,i);
}
}
}
<file_sep>/*
* Author: <NAME>
* Date: 2019-2-25
* header of graph structure
*/
#ifndef _GRAPH_H_
#define _GRAPH_H_
#include "datastructureinc.h"
#define MAXVEX 1000
typedef char VertexType;
typedef int EdgeType;
typedef struct EdgeNode
{
int adjvex;
EdgeType weight;
struct EdgeNode *next;
}EdgeNode;
typedef struct VertexNode
{
VertexType data;
EdgeNode * firstedge;
}VertexNode, AdjList[MAXVEX];
typedef struct Graph
{
AdjList adjList;
int numVertexes, numEdges;
}GraphList;
int Locate(GraphList* g, char ch);
void CreateGraph(GraphList *g);
void printGraph(GraphList *g);
#endif
<file_sep>/*
* Author: <NAME>
* Date: 2019-2-25
* test binary search tree
*/
#include "binarySearchTree.h"
using namespace std;
void printMaxAndMin(const BinarySearchTree<int> &bst)
{
cout << "min: " << bst.findMin() << endl;
cout << "max: " << bst.findMax() << endl;
}
int main()
{
BinarySearchTree<int> bst;
cout << "insert 1, 0, 2" << endl;
bst.insert(1);
bst.insert(0);
bst.insert(2);
printMaxAndMin(bst);
cout << "insert 5" << endl;
bst.insert(5);
printMaxAndMin(bst);
cout << "remove 5" << endl;
bst.remove(5);
printMaxAndMin(bst);
cout << "remove 1, 0" << endl;
bst.remove(1);
bst.remove(0);
printMaxAndMin(bst);
cout << "insert 3" << endl;
bst.insert(3);
printMaxAndMin(bst);
cout << "remove 2, 3" << endl;
bst.remove(2);
bst.remove(3);
//printMaxAndMin(bst);
if(bst.isEmpty())
{
cout << "this binary search tree is empty!" << endl;
}
return 0;
}<file_sep>/*
* Author: <NAME>
* Date: 2019-2-25
* implement of binary search tree
*/
#include "binarySearchTree.h"
//////////////////////implements of function object/////////////////////////////////
// template <typename Comparable>
// bool BinarySearchTreeWithComp::contains(const Object &x, BinaryNode *t) const
// {
// if(t == nullptr)
// {
// return false;
// }
// else if (isLessThan(x, t->element))
// {
// return contains(x, t->left);
// }
// else if(isLessThan(t->element, x))
// {
// return contains(x, t->right);
// }
// else
// {
// return true;
// }
// }
<file_sep>/*
* Author: Chengx
* Date: 2019-3-21
* Description:
*/
#include "sort.h"
using namespace std;
int main()
{
vector<int> ivec = {9,7,5,3,1,8,6,4,2};
cout << "before sort: " << endl;
Sort<int> iSort1(ivec);
iSort1.bubbleSort();
cout << "after sort: " << endl;
for(const auto &a : ivec)
cout << a << " ";
cout << endl;
cout << "before sort: " << endl;
Sort<int> iSort2({9,7,5,3,1,8,6,4,2});
iSort2.bubbleSort();
cout << "after sort: " << endl;
iSort2.printValues();
return 0;
}<file_sep>#include <stdio.h>
#include <stdlib.h>
#include "graph.h"
void TopSort(GraphList g)
{
Queue q;
int Counter = 0;
VertexNode V, W;
Q = CreateQueue(MAXVEX);
MakeEmpty(Q);
for each vertex V
if (Indegree[V] == 0)
Enqueue(V,Q);
while (!Empty(Q))
{
V = DeQueue(Q);
TopNum[V] = Counter++;// flag means this node is been visited
for each W adjacent to V
if (--Indegree[W] == 0)
Enqueue(W,Q);
}
if (Counter != MAXVEX)
printf("Graph has a cycle");
DisposeQueue(Q);
}
|
bb63318dd823322be3ae24acb668c2956a502609
|
[
"Markdown",
"C",
"Makefile",
"C++"
] | 18
|
C++
|
dabao085/DataStructureInC
|
4cbd1b3f9475d331ecdd8b60181eb4baea2c0d64
|
147d129f8614c93474ea195723901e96ca5e6251
|
refs/heads/master
|
<file_sep>var express = require('express');
var app = express();
var session = require('cookie-session');// Charge le middleware de sessions
var bodyParser = require('body-parser'); // Charge le middleware de gestion des parametres
var urlencodedParser = bodyParser.urlencoded({ extended: false });
//PostgreS
var pg = require('pg');
//MYSQL URL us-cdbr-iron-east-05.cleardb.net/heroku_f3ce5ab7bab9107 username:b48dd40b3a071b pwd:<PASSWORD>
var mysql = require('mysql');
//var pool = mysql.createPool(process.env.DATABASE_URL);
var pool = mysql.createPool({
connectionLimit : 10,
host: "sql11.freemysqlhosting.net",
user: "sql11187090",
password: "<PASSWORD>",
database: "sql11187090"
});
/*
var pool = mysql.createPool({
connectionLimit : 10,
host: "us-cdbr-iron-east-05.cleardb.net",
user: "b48dd40b3a071b",
password: "<PASSWORD>",
database: "heroku_f3ce5ab7bab9107"
});
*/
app.use(session({secret: 'todotopsecret'}))
app.use(function(req, res, next){
if (typeof(req.session.liketab) == 'undefined') {
req.session.liketab = [];
}
next();
})
pool.getConnection(function(err, connection) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
// set the port of our application
// process.env.PORT lets the port be set by Heroku
var port = process.env.PORT || 8080;
// set the view engine to ejs
app.set('view engine', 'ejs');
// make express look in the public directory for assets (css/js/img)
app.use(express.static(__dirname + '/public'));
// set the home page route
app.get('/', function(req, res) {/*
console.log("rendering home page");
// ejs render automatically looks in the views folder
res.render('index');*/
pool.getConnection(function(err, connection){
connection.query("SELECT * FROM `sql11187090`.`BAND` order by likes desc LIMIT 5", function (err, result)
{
connection.query("SELECT DISTINCT genre FROM `sql11187090`.`BAND`", function(err2,genres)
{
console.log("rendering home page");
res.render('index', {result: result, genres: genres});
if (err2) throw err2;
});
connection.release();
if (err) throw err;
});
});
});
app.post('/list',urlencodedParser,function(request,response){
//console.log("genre = "+request.body.genre);
pool.getConnection(function(err, connection){
if(request.body.genre=='all')
{
connection.query("SELECT * FROM `sql11187090`.`BAND` order by likes desc LIMIT 50", function (err, result)
{
connection.query("SELECT DISTINCT genre FROM `sql11187090`.`BAND`", function(err2,genres)
{
response.render('list.ejs', {result: result, genres: genres,genre: request.body.genre});
if (err2) throw err2;
});
connection.release();
if (err) throw err;
});
}
else
{
connection.query("SELECT * FROM `sql11187090`.`BAND` WHERE genre = ? order by likes desc LIMIT 50",[request.body.genre], function (err, result)
{
connection.query("SELECT DISTINCT genre FROM `sql11187090`.`BAND`", function(err2,genres)
{
response.render('list.ejs', {result: result, genres: genres,genre: request.body.genre});
if (err2) throw err2;
});
connection.release();
if (err) throw err;
});
}
})
});
app.post('/submit',urlencodedParser,function(request,response){
//console.log("req.genre = " + request.body.genre);
//console.log("req.otherGenre = " + request.body.otherGenre);
if(request.body.genre==undefined && request.body.otherGenre=='')
{
console.log("no genre");
}
else
{
console.log("adding band to database");
var genre = request.body.genre;
var band = request.body.name;
var comment = request.body.commentary;
if(genre==undefined)genre=request.body.otherGenre;
console.log("band = " + band +"\ngenre = "+genre+"\ncommentary = "+comment);
pool.getConnection(function(err, connection){
console.log("Connected!");
var sql = "INSERT INTO `sql11187090`.`BAND` (id,name, genre,likes,commentary) VALUES (null,?, ?, 0 , ?)";
connection.query(sql,[band,genre,comment], function (err2, result) {
if (err2)
{
throw err2;
}else
{
console.log("1 record inserted");
}
});
connection.release();
if (err) throw err;
});
}
response.redirect('/submit');
});
app.get('/list', function(req, res)
{
//connection.connect();
pool.getConnection(function(err, connection){
connection.query("SELECT * FROM `sql11187090`.`BAND` order by likes desc LIMIT 50", function (err, result)
{
connection.query("SELECT DISTINCT genre FROM `sql11187090`.`BAND`", function(err2,genres)
{
res.render('list.ejs', {result: result, genres: genres, genre: 'undefined'});
if (err2) throw err2;
});
connection.release();
if (err) throw err;
});
})
});
app.get('/submit', function(req, res) {
pool.getConnection(function(err, connection){
connection.query("SELECT DISTINCT genre FROM `sql11187090`.`BAND`", function(err2,genres)
{
res.render('submit.ejs', { genres: genres});
if (err2) throw err2;
});
});
});
app.get('/faq', function(req, res) {
res.render('faq.ejs');
});
app.get('/like/:id', function(req, res) {
//console.log('attemp to like band of id ' + req.params.id);
if (req.session.liketab[req.params.id]!=true) {
req.session.liketab[req.params.id]=true;
pool.getConnection(function(err, connection){
connection.query("UPDATE `sql11187090`.`BAND` SET likes=likes+1 where id = ?", [req.params.id], function (err, result)
{
if (err) throw err;
});
});
}
res.redirect('/list');
})
app.listen(port, function() {
console.log('Our app is running on http://localhost:' + port);
});
|
9c1cc7dc7bc40997a42196e75815ab4e6aceeecd
|
[
"JavaScript"
] | 1
|
JavaScript
|
VincentCyato/herokuApp
|
01a4ba717cd0a3b513153b245fb9ec373c4f2774
|
918b6d6ab2b7d9e1d2099fa69997f135644d2711
|
refs/heads/master
|
<repo_name>dhony05/RestAPI-ArrayFreeLibrary<file_sep>/src/main/java/com/example/ArrayFreeLibrary/Model/Book.java
package com.example.ArrayFreeLibrary.Model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "books")
public class Book {
@Id
// @GeneratedValue(strategy=GenerationType.AUTO)
// private Long id;
@Column(name = "keyword")
private String keyword;
private String name;
private String source;
private String author;
private String contributor;
private String contributor_email;
private String description ;
@ManyToOne
private Topic topic;
public Book() {
this.keyword = null;
this.name = null;
this.source = null;
this.contributor = null;
this.contributor_email = null;
this.description = null;
this.topic = null;
}
public Book(String keyword, String name,String source,String author,
String contributor,String contributor_email, String description, Topic topic) {
super();
this.keyword = keyword;
this.name = name;
this.source = source;
this.author = author;
this.contributor = contributor;
this.contributor_email = contributor_email;
this.description = description;
this.topic = new Topic(keyword,"","","","");
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getContributor() {
return contributor;
}
public void setContributor(String contributor) {
this.contributor = contributor;
}
public String getContributor_email() {
return contributor_email;
}
public void setContributor_email(String contributor_email) {
this.contributor_email = contributor_email;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Topic getTopic() {
return topic;
}
public void setTopic(Topic topic) {
this.topic = topic;
}
@Override
public String toString() {
return "Book [keyword=" + keyword + ", name=" + name + ", source=" + source + ", author=" + author
+ ", contributor=" + contributor + ", contributor_email=" + contributor_email + ", description="
+ description + ", topic=" + topic + "]";
}
}
<file_sep>/src/main/java/com/example/ArrayFreeLibrary/Services/TopicService.java
package com.example.ArrayFreeLibrary.Services;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.ArrayFreeLibrary.Model.Topic;
import com.example.ArrayFreeLibrary.Repository.TopicRepository;
@Service
public class TopicService {
private TopicRepository topicRepository;
@Autowired
public TopicService(TopicRepository newTopicRepository) {
topicRepository = newTopicRepository;
}
//business service
public List<Topic> getAllTopics(){
//return topics;
List<Topic> topics = new ArrayList<>();
// geting all the instances from table
topicRepository.findAll().forEach(topics::add); //method reference
return topics;
}
public Topic getTopic(String id) {
//return topics.stream().filter(t -> t.getId().equalsIgnoreCase(id)).findFirst().get();
return topicRepository.findById(id).get();// findOne is changed to findById and the get
}
public void addTopic(Topic newTopic) {
//topics.add(newTopic);
//System.out.println("service method" + newTopic);
topicRepository.save(newTopic); // adding to the database
}
public void updateTopic(String id, Topic newTopic) {
topicRepository.save(newTopic);
//topics.set(topics.indexOf(getTopic(id)),newTopic);
}
public void deleteTopic(String id) {
//topics.removeIf(t -> t.getId().equalsIgnoreCase(id));
topicRepository.deleteById(id);
}
}
<file_sep>/src/main/java/com/example/ArrayFreeLibrary/Services/VideoService.java
package com.example.ArrayFreeLibrary.Services;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.ArrayFreeLibrary.Model.Video;
import com.example.ArrayFreeLibrary.Repository.VideoRepository;
@Service
public class VideoService {
private VideoRepository videoRepository;
@Autowired
public VideoService(VideoRepository newVideoRepository) {
videoRepository = newVideoRepository;
}
//business service
public List<Video> getAllVideos(String id){
//return topics;
List<Video> videos = new ArrayList<>();
// geting all the instances from table
videoRepository.findByTopicKeyword(id).forEach(videos::add); //method reference
return videos;
}
public Video getVideo(String id) {
//return topics.stream().filter(t -> t.getId().equalsIgnoreCase(id)).findFirst().get();
return videoRepository.findById(id).get();// findOne is changed to findById and the get
}
public void addVideo(Video newVideo) {
//topics.add(newTopic);
//System.out.println("service method" + newTopic);
videoRepository.save(newVideo); // adding to the database
}
public void updateTopic(Video newVideo) {
videoRepository.save(newVideo);
//topics.set(topics.indexOf(getTopic(id)),newTopic);
}
public void deleteTopic(String id) {
//topics.removeIf(t -> t.getId().equalsIgnoreCase(id));
videoRepository.deleteById(id);
}
}
<file_sep>/src/main/java/com/example/ArrayFreeLibrary/Repository/TopicRepository.java
package com.example.ArrayFreeLibrary.Repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.example.ArrayFreeLibrary.Model.Topic;
@Repository
public interface TopicRepository extends CrudRepository<Topic, String> {
}
<file_sep>/src/main/java/com/example/ArrayFreeLibrary/Services/BookService.java
package com.example.ArrayFreeLibrary.Services;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.ArrayFreeLibrary.Model.Book;
import com.example.ArrayFreeLibrary.Repository.BookRepository;
@Service
public class BookService {
private BookRepository bookRepository;
@Autowired
public BookService(BookRepository newBookRepository) {
bookRepository = newBookRepository;
}
//business service
public List<Book> getAllBooks(String id){
//return topics;
List<Book> books = new ArrayList<>();
// geting all the instances from table
bookRepository.findByTopicKeyword(id).forEach(books::add); //method reference
return books;
}
public Book getBook(String id) {
//return topics.stream().filter(t -> t.getId().equalsIgnoreCase(id)).findFirst().get();
return bookRepository.findById(id).get();// findOne is changed to findById and the get
}
public void addBook(Book newBook) {
//topics.add(newTopic);
//System.out.println("service method" + newTopic);
bookRepository.save(newBook); // adding to the database
}
public void updateBook(Book newBook) {
bookRepository.save(newBook);
//topics.set(topics.indexOf(getTopic(id)),newTopic);
}
public void deleteBook(String id) {
//topics.removeIf(t -> t.getId().equalsIgnoreCase(id));
bookRepository.deleteById(id);
}
}
<file_sep>/src/main/java/com/example/ArrayFreeLibrary/RestController/VideoController.java
package com.example.ArrayFreeLibrary.RestController;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.ArrayFreeLibrary.Model.Topic;
import com.example.ArrayFreeLibrary.Model.Video;
import com.example.ArrayFreeLibrary.Services.VideoService;
@RestController
public class VideoController {
@Autowired
private VideoService videoService;
@RequestMapping("/topics/{id}/videos")
public List<Video> getAllVideos(@PathVariable String id){
return videoService.getAllVideos(id);
}
@GetMapping("/topics/{videoId}/videos/{id}")
public Video getVideo(@PathVariable String id) {
return videoService.getVideo(id);
}
//@RequestMapping(method=RequestMethod.POST,value="/topics")
@PostMapping("/topics/{topicId}/videos")
public void addVideos(@RequestBody Video newVideo,@PathVariable String topicId) {
//System.out.println("controller method: " + newVideo);
newVideo.setTopic(new Topic(topicId,"","","",""));
videoService.addVideo(newVideo);
}
@PutMapping("/topics/{topicId}/videos/{id}")
public void updateVideo(@RequestBody Video newVideo,@PathVariable String topicId , @PathVariable String id) {
//System.out.println("put method" + newVideo);
newVideo.setTopic(new Topic(topicId,"","","",""));
videoService.updateTopic(newVideo);
}
@DeleteMapping("/topics/{topicsId}/videos/{id}")
public void deleteVideo( @PathVariable String id) {
videoService.deleteTopic(id);
}
}
<file_sep>/src/main/resources/application.properties
server.port=8080
spring.main.allow-bean-definition-overriding=true
spring.jpa.hibernate.ddl-auto=none
spring.datasource.url = jdbc:mysql://localhost:3306/TopicLibrarydb?useUnicode=true&characterEncoding=utf8&useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
|
b04ce9bcfb798137482357ea2d2dba1cd0572445
|
[
"Java",
"INI"
] | 7
|
Java
|
dhony05/RestAPI-ArrayFreeLibrary
|
40657bc0f54994ecfe51eae9441f4c40fd4ef6f6
|
cff8bd29987163e372d998d233bb39fb529ea7cd
|
refs/heads/master
|
<repo_name>DongningLi/computerNetwork<file_sep>/cls_pro/cls_pro/cls_pro.cpp
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <ctime>
#include <stdio.h>
#include<fstream>
#include<iomanip>
#include<string>
#include <sstream>
#include <stdlib.h>
#include <vector>
#include<bitset>
using namespace std;
string Data; //read from file
string DataBuffer=""; //add data from each data update
LONGLONG start;
//////////////// information read from input file////////////////////////
string MD1_MTU;
string MD2_MTU;
string ND1_IF1_IP; //IP of interface1 of node1
string ND1_IF1_MASK; //mask of interface1 of node1
string ND1_IF1_ETHER;//ehter of interface1 of node1
string ND1_IF1_BANDWIDTH;//bandwidth of interface1 of node1
string ND1_IF1_CONNECTION;//connection node of interface1 of node1
string ND2_IF1_IP;
string ND2_IF1_MASK;
string ND2_IF1_ETHER;
string ND2_IF1_BANDWIDTH;
string ND2_IF1_CONNECTION;
string ND2_IF2_IP;
string ND2_IF2_MASK;
string ND2_IF2_ETHER;
string ND2_IF2_BANDWIDTH;
string ND2_IF2_CONNECTION;
string ND3_IF1_IP;
string ND3_IF1_MASK;
string ND3_IF1_ETHER;
string ND3_IF1_BANDWIDTH;
string ND3_IF1_CONNECTION;
//////////////// information read from input file////////////////////////
struct ND_Input //struct node information needed to input to routing table
{
string name;
string Network_address;
string Net_Mask;
}nodein[4];
typedef struct IP_Header //Identify the data striation of IP header
{
int Version;
int HeadLen;
int ServiceType;
int TotalLen;
int Identifier;
int Flags;
int FragOffset;
int TimeToLive;
int Protocol;
int HeadChecksum;
string SourceAddr;
string DestinAddr;
};
//***************************************************************************************************//
class Physical //struct physical layer
{
public:
void Run(int, char*);
};
class Data_link //struct data_link layer
{
public:
void Run(int, char*);
bool isbusy;
};
class Network //struct network layer
{
public:
void Run(int, char*);
};
class Transport //struct transport layer
{
public:
void Run(int, char*);
void Stop();
bool confliction;
};
struct NODE //struct node-information all from input file
{
int label;
Physical layer1;
Data_link layer2;
Network layer3;
Transport layer4;
int connection_num;
}*node;
struct Routing_table_row //struct routing table
{
int label;
string Name;
string Network_address;
string Net_Mask;
string Next_hop_IP;
int Metric;
};
//HANDLE isbusy;
LPCWSTR Medium_busy_check;
bool allset = false; // All data have been transmitted and recieved
const int MTU = 10;
const char* public_message="";
struct DATA //struct data-information needed from input file
{
int label;
int Time_stamp_ms;
string Src_node;
string Dest_node;
string message; //MTU
}data_in[3]; //set 3 masks in the input file
class Media //define media struct
{
public:
HANDLE isbusy;
void Open_connection(int);
void Transmit(char*);
void Close_connection(int);
private:
int ID;
char Message[MTU];
}Medium;
void Media::Open_connection(int id) //media function-open define
{
int ID=id;
}
void Media::Close_connection(int id) //media function-close define
{
int ID=id;
}
/////////function (d)/////////
void RT_input(int i, string Next_hop_IP)
{
int k=i;
string Next_Hop_IP= Next_hop_IP;
cout<<k<<"\t"<<nodein[k].name<<"\t\t"<<nodein[k].Network_address<<"\t"<<nodein[k].Net_Mask<<"\t"<<Next_Hop_IP<<"\t"<<"2"<<endl;
}
void Routing_tables_es(NODE Node)
{
cout<<"Node "<<Node.label <<" routing table:"<<endl;
cout<<"----------------------------------------------------------------------------------"<<endl;
cout<<"Label"<<" | "<<"Node_name:"<<" | "<<"Network_address:"<<" | "<<"Net_Mask:"<<" | "<<"Next_hop_IP:"<<" | "<<"Metric:"<<endl;
cout<<"----------------------------------------------------------------------------------"<<endl;
string Next_hop_IP;
switch ( Node.label )
{
case 1:
Next_hop_IP="10.10.20.10";
RT_input(1,Next_hop_IP);
RT_input(3,Next_hop_IP);
cout<<"----------------------------------------------------------------------------------\n\n"<<endl;
break;
case 2:
Next_hop_IP="10.10.10.10";
RT_input(0,Next_hop_IP);
Next_hop_IP="10.10.40.10";
RT_input(3,Next_hop_IP);
cout<<"----------------------------------------------------------------------------------\n\n"<<endl;
break;
case 3:
Next_hop_IP="10.10.30.10";
RT_input(0,Next_hop_IP);
RT_input(2,Next_hop_IP);
cout<<"----------------------------------------------------------------------------------\n\n"<<endl;
break;
}
}
void app(string recmsg){ //user receive message and output it
cout<<"user receive message"<<'"'<<recmsg<<'"'<<endl;
}
//*************************receive 5 to 2 **********************************//
void rec5(string recmsg,string node){ // send received message to user
app(recmsg);
}
void rec4(string recmsg,string node){ //send received message to layer5
rec5(recmsg, node);
}
void rec3(string node,string msg){ //send received message to layer4
rec4(msg,node);
}
void rec2(string node,string msg ,string i){ // send received and processed message to layer3
string str;
stringstream stream;
stream << msg[1];
str = stream.str(); // change char into string
if (node == str)
{
msg=msg.erase (0,4); // erase the mac ip address
msg=msg.erase(msg.length(),1); //erase checksum
rec3(node,msg); //keep the messge only
}else
cout<<"\nAt "<<GetTickCount()-start<<" Milliseconds Node "<<i<<" throw the data file to node "<<node<<"\n"<<endl;
}
void Receive(string node,string message, string i)
{
rec2(node,message,i);
}
char* message_t1;
char* message_t2;
char* message_t3;
//*************************send 2 to 5 **********************************//
string send2(string msg,string src,string des){ //ad mac address to message
///////////////////////////////////----------------ether checksum calculation and add to message start------------------------------///////////////////////////////////
string echecksum;
int ec1=atoi(msg.substr(0,1).c_str());
int ec2=atoi(msg.substr(1,2).c_str());
int ec3=atoi(msg.substr(2,3).c_str());
int ec4=atoi(msg.substr(3,4).c_str());
int ec5=atoi(msg.substr(4,5).c_str());
int ec6=atoi(msg.substr(5,6).c_str());
int ec=ec1+ec2+ec3+ec4+ec5+ec6;
if (ec%2==0)
echecksum="0";
else echecksum="1";
msg=msg+echecksum;
///////////////////////////////////----------------ether checksum start calculation and add to message -----------------------------///////////////////////////////////
msg=src+des+msg;
return msg;
}
string send3(string msg,string src, string des){ //ad ip adress to message
msg=src+des+msg;
return send2(msg,src,des);
}
std::vector<std::string> split(std::string str) //split the message into equal size packet
{
std::vector<std::string> result; // set up vector to store the result
int size=str.size();
int i;
for(i=0; i<size; i++)
{
int MTU=100;
std::string s=str.substr(i,MTU-4); // The new packet size is set to (MTU minus the length of two IP headers and two MAC headers), and we set the length of two headers are 2 respectively
result.push_back(s);
i=i+95; //The position of next i is set to the packet body length minus 1
}
return result;
}
string send5(string msg, string src, string des){
std::vector<std::string> result=split(msg); // receive the message from user and call split funtion
for(unsigned int i=0; i<result.size(); i++)
{
return send3(result[i],src,des); //output the split processed result with full address
}
}
//////////////////////---------------------------file print start--------------------//////////////////////////////////////////
void printfile()
{
cout<<"Tasks Pool:"<<endl;
cout<<"----------------------------------------------------------------------------------"<<endl;
cout<<"TASK_NUM"<<"\t"<<"TIME_STAMP_MS"<<"\t"<<"SRC_NODE"<<"\t"<<"MESSAGE"<<"\t\t"<<"DEST_NODE"<<endl;
for(int i=0;i<3;i++)//out put the array of structures
{
cout<<data_in[i].label<<"\t\t"<<data_in[i].Time_stamp_ms<<"\t\t"<<data_in[i].Src_node<<"\t\t"<<data_in[i].message<<"\t\t"<<data_in[i].Dest_node<<endl;
}
cout<<"----------------------------------------------------------------------------------"<<endl;
}
//////////////////////---------------------------file print end--------------------//////////////////////////////////////////
long hdchecksumt;
///////////////////////////////////----------------ipHeader define&print start------------------------------///////////////////////////////////
void hdprint(DATA data){
IP_Header ip;
int srcnode=atoi(data.Src_node.c_str()); //read information from thread
int desnode=atoi(data.Dest_node.c_str());
ip.Version=3; //4 digits
ip.HeadLen=3; //4 digits
ip.ServiceType=4; //8 digits
ip.TotalLen=5; //16 digits
ip.Identifier=3; //16 digits
ip.Flags=2; //4 digits
ip.FragOffset=5; //12 digits
ip.TimeToLive=2; //8 digits
ip.Protocol=3; //8 digits
ip.HeadChecksum=0;
ip.SourceAddr=nodein[srcnode].Network_address;
ip.DestinAddr=nodein[desnode].Network_address;
bitset<4> Version2(3); //convert normal information to binary to print
bitset<4> HeadLen2(3);
bitset<8> ServiceType2(3);
bitset<16> TotalLen2(3);
bitset<16> Identifier2(3);
bitset<4> Flags2(3);
bitset<12> FragOffset2(3);
bitset<8> TimeToLive2(3);
bitset<8> Protocol2(3);
string pp1 = ip.SourceAddr; //convert ip source address to binary coding
string ppp1[4];
for (int j=0;j<4;j++){
ppp1[j]=pp1.substr(j*3,2);
}
int ips[4]={0,0,0,0};
for(int i=0;i<4;i++){
ips[i]=atoi(ppp1[i].c_str());
}
bitset<8> bss1=ips[0];
bitset<8> bss2=ips[1];
bitset<8> bss3=ips[2];
bitset<8> bss4=ips[3];
string pp2 = ip.DestinAddr;//convert ip destination address to binary coding
string ppp2[4];
for (int j=0;j<4;j++){
ppp2[j]=pp2.substr(j*3,2);
}
int ipd[4]={0,0,0,0};
for(int i=0;i<4;i++){
ipd[i]=atoi(ppp2[i].c_str());
}
bitset<8> bsd1=ipd[0];
bitset<8> bsd2=ipd[1];
bitset<8> bsd3=ipd[2];
bitset<8> bsd4=ipd[3];
////////////////////////////-------------calculate IP_Header Checksum START----------------------------------////////////////////////////
bitset<16> a=((ip.Version<<12)|(ip.HeadLen<<8)|ip.ServiceType); //connect header coding in binary to 16-digits
bitset<16> b=TotalLen2;
bitset<16> c=Identifier2;
bitset<16> d=((ip.Flags<<12)|ip.FragOffset);
bitset<16> e=((ip.TimeToLive<<8)|ip.Protocol);
bitset<16> f=((ips[0]<<8)|ips[1]);
bitset<16> g=((ips[2]<<8)|ips[3]);
bitset<16> h=((ipd[0]<<8)|ipd[1]);
bitset<16> i=((ipd[2]<<8)|ipd[3]);
hdchecksumt=a.to_ulong()+b.to_ulong()+c.to_ulong()+d.to_ulong()+e.to_ulong()+f.to_ulong()+g.to_ulong()+h.to_ulong()+i.to_ulong();
bitset<16> hdchecksum(hdchecksumt);
////////////////////////////-------------calculate IP_Header Checksum END----------------------------------///////////////////////////
cout<<"Version:"<<Version2<<endl; //print header
cout<<"HeadLen:"<<HeadLen2<<endl;
cout<<"ServiceType:"<<ServiceType2 <<endl;
cout<<"TotalLen:"<<TotalLen2 <<endl;
cout<<"Identifier:"<<Identifier2 <<endl;
cout<<"Flags:"<<Flags2 <<endl;
cout<<"FragOffset:"<<FragOffset2<<endl;
cout<<"TimeToLive:"<<TimeToLive2<<endl;
cout<<"Protocol:"<<Protocol2 <<endl;
cout<<"Headerchecksum:"<<hdchecksum<<endl;
cout<<"SourceAddr:" <<ip.SourceAddr <<endl;
cout<<"DestinAddress:"<<ip.DestinAddr<<endl;
}
///////////////////////////////////----------------ipHeader define&print END------------------------------///////////////////////////////////
string msg2to11;
string msg2to12;
string msg2to13;
int Tasknum=4;
//******************************thread**********************************//
DWORD WINAPI Node1(LPVOID lpParamter)
{
msg2to11=data_in[0].Src_node+data_in[0].Dest_node+data_in[0].Src_node+data_in[0].Dest_node+data_in[0].message;//for receive sample test
msg2to12=data_in[1].Src_node+data_in[1].Dest_node+data_in[1].Src_node+data_in[1].Dest_node+data_in[1].message;//for receive sample test
msg2to13=data_in[2].Src_node+data_in[2].Dest_node+data_in[2].Src_node+data_in[2].Dest_node+data_in[2].message;//for receive sample test
while(Tasknum>1)
{
if (WaitForSingleObject(Medium.isbusy,0)==WAIT_OBJECT_0) //Medium is not busy Node 1 take it!
{
if(Tasknum<=0)
{
cin.get();
exit(0);
}
cout<<"\nAt "<<GetTickCount()-start<<" Milliseconds Node 1 occupies medium now!>>>>>\n"<<endl;
//*************Task begin at here!****************//
string str;
char *cstr = new char[msg2to11.length() + 1];
stringstream stream;
stream << msg2to11[1];
str = stream.str(); // change char into string
if ("1" == str)
{
strcpy(message_t1, msg2to11.c_str());
};
Medium.Open_connection(1); // Node 1 begin to transmit
hdprint(data_in[0]);
msg2to11=send5(data_in[0].message,data_in[0].Src_node,data_in[0].Dest_node); // user calls layer5 and send the message layer by layer
cout<<"user sends message with NODEIP and ETHER CHECKSUM:"<<msg2to11<<endl;
for (int i=0;i<3;i++){
Receive(data_in[i].Dest_node,msg2to13,"1");
}
Medium.Close_connection(1); // Task over
Tasknum=Tasknum-1;
ReleaseMutex(Medium.isbusy);
Sleep(3000);
}
else
{
cout<<"\nAt "<<GetTickCount()-start<<" Milliseconds Node 1 attempt has failed!\n"<<endl;
Sleep(113); // Time interval to check the medium
}
}
return 0;
}
DWORD WINAPI Node2(LPVOID lpParamter)
{
msg2to11=data_in[0].Src_node+data_in[0].Dest_node+data_in[0].Src_node+data_in[0].Dest_node+data_in[0].message; //for receive sample test
msg2to12=data_in[1].Src_node+data_in[1].Dest_node+data_in[1].Src_node+data_in[1].Dest_node+data_in[1].message;//for receive sample test
msg2to13=data_in[2].Src_node+data_in[2].Dest_node+data_in[2].Src_node+data_in[2].Dest_node+data_in[2].message;//for receive sample test
while(Tasknum>1)
{
if (WaitForSingleObject(Medium.isbusy,0)==WAIT_OBJECT_0) //Medium is not busy Node 1 take it!
{
if(Tasknum<=0)
{
cin.get();
exit(0);
}
cout<<"\nAt "<<GetTickCount()-start<<" Milliseconds Node 2 occupies medium now!>>>>>\n"<<endl;
//*************Task begin at here!****************//
string str;
char *cstr = new char[msg2to11.length() + 1];
stringstream stream;
stream << msg2to12[1];
str = stream.str(); // change char into string
//str="2";
if ("2" == str)
{
strcpy(message_t2, msg2to12.c_str());
};
Medium.Open_connection(2); // Node 2 begin to transmit
hdprint(data_in[1]);
msg2to12=send5(data_in[1].message,data_in[1].Src_node,data_in[1].Dest_node); // user calls layer5 and send the message layer by layer
cout<<"user sends message with NODEIP and ETHER CHECKSUM:"<<msg2to12<<endl;
for (int i=0;i<3;i++){
Receive(data_in[i].Dest_node,msg2to11,"2");
}
Medium.Close_connection(2); // Task over
Tasknum=Tasknum-1;
ReleaseMutex(Medium.isbusy);
Sleep(3000);
}
else
{
cout<<"\nAt "<<GetTickCount()-start<<" Milliseconds Node 2 attempt has failed!\n"<<endl;
Sleep(111); // Time interval to check the medium
}
}
return 0;
}
DWORD WINAPI Node3(LPVOID lpParamter)
{
msg2to11=data_in[0].Src_node+data_in[0].Dest_node+data_in[0].Src_node+data_in[0].Dest_node+data_in[0].message;//for receive sample test
msg2to12=data_in[1].Src_node+data_in[1].Dest_node+data_in[1].Src_node+data_in[1].Dest_node+data_in[1].message;//for receive sample test
msg2to13=data_in[2].Src_node+data_in[2].Dest_node+data_in[2].Src_node+data_in[2].Dest_node+data_in[2].message;//for receive sample test
while(Tasknum>1)
{
if (WaitForSingleObject(Medium.isbusy,0)==WAIT_OBJECT_0) //Medium is not busy Node 1 take it!
{
if(Tasknum<=0)
{
cin.get();
exit(0);
}
hdprint(data_in[2]);
cout<<"\nAt "<<GetTickCount()-start<<" Milliseconds Node 3 occupies medium now!>>>>>\n"<<endl;
//*************Task begin at here!****************//
string str;
char *cstr = new char[msg2to13.length() + 1];
stringstream stream;
stream << msg2to13[1];
str = stream.str(); // change char into string
//str="3";
if ("3" == str)
{
strcpy(message_t3, msg2to13.c_str());
};
Medium.Open_connection(3); // Node 1 begin to transmit
hdprint(data_in[2]);
msg2to13=send5(data_in[2].message,data_in[2].Src_node,data_in[2].Dest_node); // user calls layer5 and send the message layer by layer
cout<<"user sends message with NODEIP and ETHER CHECKSUM:"<<msg2to13<<endl;
for (int i=0;i<3;i++){
Receive(data_in[i].Dest_node,msg2to12,"3");
}
Medium.Close_connection(3); // Task over
Tasknum=Tasknum-1;
ReleaseMutex(Medium.isbusy);
Sleep(3000);
}
else
{
cout<<"\nAt "<<GetTickCount()-start<<" Milliseconds Node 3 attempt has failed!\n"<<endl;
Sleep(123); // Time interval to check the medium
}
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
///////////////////////////////------------------read file start------------------//////////////////////////////////////////////
ifstream fin("inputfile.txt"); //read file to stream
if( ! fin ) //in case of file not existing
{
cerr<<"Can not open datain1 file."<<endl;
cin.get();
return 1;
};
while( ! fin.eof() ) //read data from file
{
fin>>Data;
DataBuffer=DataBuffer+Data;
};
///////////////////////////////------------------read file end------------------//////////////////////////////////////////////
///////////////////////////////------------------read medias MTU from file begin------------------//////////////////////////////////////////////
int pos_MD1_MTU = DataBuffer.find("MD1_MTU", 0);// find the position of MD1_MTU
MD1_MTU = DataBuffer.substr(pos_MD1_MTU+sizeof("MD1_MTU"), 4); //fetch MD1_MTU Size
int pos_MD2_MTU = DataBuffer.find("MD2_MTU", 0);// find the position of MD2_MTU
MD2_MTU = DataBuffer.substr(pos_MD2_MTU+sizeof("MD2_MTU"), 4); //fetch MD2_MTU Size
///////////////////////////////------------------read medias MTU from file end------------------//////////////////////////////////////////////
///////////////////////////////------------------read informations about nodes from file begin------------------//////////////////////////////////////////////
int pos_ND1_IF1_IP = DataBuffer.find("ND1_IF1_IP", 0);// find the position of IP
int pos_ND2_IF1_IP = DataBuffer.find("ND2_IF1_IP", 0);
int pos_ND2_IF2_IP = DataBuffer.find("ND2_IF2_IP", 0);
int pos_ND3_IF1_IP = DataBuffer.find("ND3_IF1_IP", 0);
ND1_IF1_IP = DataBuffer.substr(pos_ND1_IF1_IP+sizeof("ND1_IF1_IP"), 11); //fetch IP Address
ND2_IF1_IP = DataBuffer.substr(pos_ND2_IF1_IP+sizeof("ND2_IF1_IP"), 11);
ND2_IF2_IP = DataBuffer.substr(pos_ND2_IF2_IP+sizeof("ND2_IF2_IP"), 11);
ND3_IF1_IP = DataBuffer.substr(pos_ND3_IF1_IP+sizeof("ND3_IF1_IP"), 11);
int pos_ND1_IF1_MASK = DataBuffer.find("ND1_IF1_MASK", 0);// find the position of MASK
int pos_ND2_IF1_MASK = DataBuffer.find("ND2_IF1_MASK", 0);
int pos_ND2_IF2_MASK = DataBuffer.find("ND2_IF2_MASK", 0);
int pos_ND3_IF1_MASK = DataBuffer.find("ND3_IF1_MASK", 0);
ND1_IF1_MASK = DataBuffer.substr(pos_ND1_IF1_MASK+sizeof("ND1_IF1_MASK"), 13); //fetch MASK Address
ND2_IF1_MASK = DataBuffer.substr(pos_ND2_IF1_MASK+sizeof("ND2_IF1_MASK"), 13);
ND2_IF2_MASK = DataBuffer.substr(pos_ND2_IF2_MASK+sizeof("ND2_IF2_MASK"), 13);
ND3_IF1_MASK = DataBuffer.substr(pos_ND3_IF1_MASK+sizeof("ND3_IF1_MASK"), 13);
int pos_ND1_IF1_ETHER = DataBuffer.find("ND1_IF1_ETHER", 0);// find the position of ETHER
int pos_ND2_IF1_ETHER = DataBuffer.find("ND2_IF1_ETHER", 0);
int pos_ND2_IF2_ETHER = DataBuffer.find("ND2_IF2_ETHER", 0);
int pos_ND3_IF1_ETHER = DataBuffer.find("ND3_IF1_ETHER", 0);
ND1_IF1_ETHER = DataBuffer.substr(pos_ND1_IF1_ETHER+sizeof("ND1_IF1_ETHER"), 10); //fetch ETHER Address
ND2_IF1_ETHER = DataBuffer.substr(pos_ND2_IF1_ETHER+sizeof("ND2_IF1_ETHER"), 10);
ND2_IF2_ETHER = DataBuffer.substr(pos_ND2_IF2_ETHER+sizeof("ND2_IF2_ETHER"), 10);
ND3_IF1_ETHER = DataBuffer.substr(pos_ND3_IF1_ETHER+sizeof("ND3_IF1_ETHER"), 10);
int pos_ND1_IF1_BANDWIDTH = DataBuffer.find("ND1_IF1_BANDWIDTH", 0);// find the position of BANDWIDTH
int pos_ND2_IF1_BANDWIDTH = DataBuffer.find("ND2_IF1_BANDWIDTH", 0);
int pos_ND2_IF2_BANDWIDTH = DataBuffer.find("ND2_IF2_BANDWIDTH", 0);
int pos_ND3_IF1_BANDWIDTH = DataBuffer.find("ND3_IF1_BANDWIDTH", 0);
ND1_IF1_BANDWIDTH = DataBuffer.substr(pos_ND1_IF1_BANDWIDTH+sizeof("ND1_IF1_BANDWIDTH"), 2); //fetch BANDWIDTH Address
ND2_IF1_BANDWIDTH = DataBuffer.substr(pos_ND2_IF1_BANDWIDTH+sizeof("ND2_IF1_BANDWIDTH"), 2);
ND2_IF2_BANDWIDTH = DataBuffer.substr(pos_ND2_IF2_BANDWIDTH+sizeof("ND2_IF2_BANDWIDTH"), 2);
ND3_IF1_BANDWIDTH = DataBuffer.substr(pos_ND3_IF1_BANDWIDTH+sizeof("ND3_IF1_BANDWIDTH"), 2);
int pos_ND1_IF1_CONNECTION = DataBuffer.find("ND1_IF1_CONNECTION", 0);// find the position of CONNECTION
int pos_ND2_IF1_CONNECTION = DataBuffer.find("ND2_IF1_CONNECTION", 0);
int pos_ND2_IF2_CONNECTION = DataBuffer.find("ND2_IF2_CONNECTION", 0);
int pos_ND3_IF1_CONNECTION = DataBuffer.find("ND3_IF1_CONNECTION", 0);
ND1_IF1_CONNECTION = DataBuffer.substr(pos_ND1_IF1_CONNECTION+sizeof("ND1_IF1_CONNECTION")+sizeof("MD"), 1); //fetch CONNECTION Address
ND2_IF1_CONNECTION = DataBuffer.substr(pos_ND2_IF1_CONNECTION+sizeof("ND2_IF1_CONNECTION")+sizeof("MD"), 1);
ND2_IF2_CONNECTION = DataBuffer.substr(pos_ND2_IF2_CONNECTION+sizeof("ND2_IF2_CONNECTION")+sizeof("MD"), 1);
ND3_IF1_CONNECTION = DataBuffer.substr(pos_ND3_IF1_CONNECTION+sizeof("ND3_IF1_CONNECTION")+sizeof("MD"), 1);
///////////////////////////////------------------read informations about nodes from file end ------------------//////////////////////////////////////////////
///////////////////////////////------------------struct node array begin------------------//////////////////////////////////////////////
nodein[0].name="NODE1"; //initial node1 according to inputfile
nodein[0].Network_address=ND1_IF1_IP;
nodein[0].Net_Mask=ND1_IF1_MASK;
nodein[1].name="NODE2";//initial node2 according to inputfile
nodein[1].Network_address=ND2_IF1_IP;
nodein[1].Net_Mask=ND2_IF1_MASK;
nodein[2].name="NODE2";//initial node2 according to inputfile
nodein[2].Network_address=ND2_IF2_IP;
nodein[2].Net_Mask=ND2_IF2_MASK;
nodein[3].name="NODE3";//initial node3 according to inputfile
nodein[3].Network_address=ND3_IF1_IP;
nodein[3].Net_Mask=ND3_IF1_MASK;
///////////////////////////////------------------struct node array end------------------//////////////////////////////////////////////
///////////////////////////////------------------read tasks from file begin------------------//////////////////////////////////////////////
int pos_FILE_MESSAGES = DataBuffer.find("FILE_MESSAGES", 0);// find the position of FILE_SIZE (KB)
for (int i=0;i<3;i++){
data_in[i].label=i;
data_in[i].Time_stamp_ms=atoi(DataBuffer.substr(pos_FILE_MESSAGES+sizeof("FILE_MESSAGES")+i*16,3).c_str());
data_in[i].Src_node=DataBuffer.substr(pos_FILE_MESSAGES+sizeof("FILE_MESSAGES")+5+i*16,1);
data_in[i].Dest_node=DataBuffer.substr(pos_FILE_MESSAGES+sizeof("FILE_MESSAGES")+8+i*16,1);
data_in[i].message=DataBuffer.substr(pos_FILE_MESSAGES+sizeof("FILE_MESSAGES")+9+i*16,6);
}
///////////////////////////////------------------read tasks from file end------------------//////////////////////////////////////////////
/////////////////***********************************////////////////////////////
NODE *node=new NODE[3];
for (int i=0;i<3;i++)
{
node[i].label=i+1;
node[i].connection_num=2; //Need value in
Routing_tables_es(node[i]);
}
/////////////////***************************************///////////////////////
printfile();
start=GetTickCount();
HANDLE Node_1 = CreateThread(NULL, 0, Node1, NULL, 0, NULL);
HANDLE Node_2 = CreateThread(NULL, 0, Node2, NULL, 0, NULL);
HANDLE Node_3 = CreateThread(NULL, 0, Node3, NULL, 0, NULL);
Medium.isbusy = CreateMutex(NULL, FALSE, Medium_busy_check); //equivalent to de-confliction (medium access control) based on the ˇ°busyˇ± signal from the medium.
CloseHandle(Node_1);
CloseHandle(Node_2);
CloseHandle(Node_3);
cin.get();
return 0;
}
|
8760c323dd0a70b9ca38f5f7f88f7186b138cfe8
|
[
"C++"
] | 1
|
C++
|
DongningLi/computerNetwork
|
e6d23c1abb7bafb801e7551435a16053a5fde0d8
|
e43262ea9a915351bb7f0f30aff5d1f22c08eec5
|
refs/heads/master
|
<file_sep>#include "find_road.h"
#include "move_car.h"
int main(int argc, char** argv)
{
float speed = 0.7;
float Ka = 1.0/200;
float max_speed = 2;
float min_speed = 0.1;
if (argc > 1) { speed = atof(argv[1]); }
if (argc > 2) { Ka = atof(argv[2]); }
if (argc > 3) { max_speed = atof(argv[3]); }
if (argc > 4) { min_speed = atof(argv[4]); }
ros::init(argc, argv, "find_road");
RoadFinder rf;
AckermannMover am;
ros::Rate rate(20);
while(ros::ok()) {
// The speed is constant, but the steering angle is proportional
//to the distance of the middle of the road from the middle of the image
ros::spinOnce();
float error = rf.imageWidth()/2 - rf.getMidpoint().x; // Error in number of pixels
float speed_command = speed; // Here you could do something smarter
ROS_INFO("Sending command speed=%f, steering_angle=%f", speed_command, error*Ka);
am.go(speed_command, error*Ka);
rate.sleep();
}
return 0;
}
<file_sep>#ifndef MOVE_CAR_H
#define MOVE_CAR_H
#include <ros/ros.h>
#include <ackermann_msgs/AckermannDrive.h>
#include <ackermann_msgs/AckermannDriveStamped.h>
#include <std_msgs/Header.h>
class AckermannMover
{
ros::NodeHandle nh_;
ros::Publisher cmd_pub_;
public:
AckermannMover() {
cmd_pub_ = nh_.advertise<ackermann_msgs::AckermannDriveStamped>("/ackermann_vehicle/ackermann_cmd", 10);
}
~AckermannMover() { }
void go(float speed, float steering_angle) {
//std_msgs::Header header;
//ackermann_msgs::AckermannDrive drive;
ackermann_msgs::AckermannDriveStamped driveStamped;
driveStamped.drive.steering_angle = steering_angle;
driveStamped.drive.speed = speed;
cmd_pub_.publish(driveStamped);
}
};
#endif
<file_sep>#include <ros/ros.h>
#include <sensor_msgs/JointState.h>
void readAngle(const sensor_msgs::JointState::ConstPtr& joint_state) {
float left_wheel_angle = joint_state->position[std::find (joint_state->name.begin(),joint_state->name.end(), "left_rear_axle") - joint_state->name.begin()];
float right_wheel_angle = joint_state->position[std::find (joint_state->name.begin(),joint_state->name.end(), "right_rear_axle") - joint_state->name.begin()];
ROS_INFO("Left wheel angle: %f", left_wheel_angle);
ROS_INFO("Right wheel angle: %f", right_wheel_angle);
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "read_whee_angles");
ros::NodeHandle nh_;
ros::Subscriber sub_ = nh_.subscribe("/ackermann_vehicle/joint_states", 10, readAngle);
ros::spin();
return 0;
}
<file_sep>#include "find_road.h"
int main(int argc, char** argv)
{
ros::init(argc, argv, "find_road");
RoadFinder rf;
ros::spin();
return 0;
}
|
cb7eace6e1185dab448ae965000163644705451f
|
[
"C++"
] | 4
|
C++
|
charlie632/ackermann_controller
|
fc608dc1fdf5df6f6d949ae17a762217733e712c
|
f50db1ef0951885c986d2ddf8dacf005e2a69d2d
|
refs/heads/master
|
<repo_name>dgro/dhl-sdk-api-bcs<file_sep>/test/Expectation/CommunicationExpectation.php
<?php
/**
* See LICENSE.md for license details.
*/
declare(strict_types=1);
namespace Dhl\Sdk\Paket\Bcs\Test\Expectation;
use PHPUnit\Framework\Assert;
use Psr\Log\Test\TestLogger;
class CommunicationExpectation
{
/**
* Mock client does not send headers, only check for request body being logged.
*
* @param string $requestXml
* @param string $responseXml
* @param TestLogger $logger
*/
public static function assertCommunicationLogged(string $requestXml, string $responseXml, TestLogger $logger): void
{
Assert::assertTrue($logger->hasInfoThatContains($requestXml), 'Logged messages do not contain request');
Assert::assertTrue($logger->hasInfoThatContains($responseXml), 'Logged messages do not contain response');
}
/**
* Mock client does not send headers, only check for request body being logged.
*
* @param string $requestXml
* @param string $responseXml
* @param TestLogger $logger
*/
public static function assertWarningsLogged(string $requestXml, string $responseXml, TestLogger $logger): void
{
Assert::assertTrue($logger->hasWarningThatContains($requestXml), 'Logged messages do not contain request');
Assert::assertTrue($logger->hasWarningThatContains($responseXml), 'Logged messages do not contain response');
}
/**
* Mock client does not send headers, only check for request body being logged.
*
* @param string $requestXml
* @param string $responseXml
* @param TestLogger $logger
*/
public static function assertErrorsLogged(string $requestXml, string $responseXml, TestLogger $logger): void
{
Assert::assertTrue($logger->hasErrorThatContains($requestXml), 'Logged messages do not contain request');
Assert::assertTrue($logger->hasErrorThatContains($responseXml), 'Logged messages do not contain response');
}
}
<file_sep>/test/Provider/ShipmentRequestProvider.php
<?php
/**
* See LICENSE.md for license details.
*/
declare(strict_types=1);
namespace Dhl\Sdk\Paket\Bcs\Test\Provider;
use Dhl\Sdk\Paket\Bcs\Exception\RequestValidatorException;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ShipmentOrderType;
use Dhl\Sdk\Paket\Bcs\RequestBuilder\ShipmentOrderRequestBuilder;
class ShipmentRequestProvider
{
/**
* @return ShipmentOrderType[]
* @throws RequestValidatorException
* @throws \Exception
*/
public static function createSingleShipmentSuccess(): array
{
$shipmentOrders = [];
$tsShip = time() + 60 * 60 * 24; // tomorrow
$requestBuilder = new ShipmentOrderRequestBuilder();
$requestBuilder->setShipperAccount('22222222220101');
$requestBuilder->setShipperAddress('Netresearch GmbH & Co.KG', 'DE', '04229', 'Leipzig', 'Nonnenstraße', '11d');
$requestBuilder->setRecipientAddress('<NAME>', 'DE', '53113', 'Bonn', 'Charles-de-Gaulle-Straße', '20');
$requestBuilder->setShipmentDetails('V01PAK', new \DateTime(date('Y-m-d', $tsShip)));
$requestBuilder->setPackageDetails(2.4);
$shipmentOrder = $requestBuilder->create();
$shipmentOrders[] = $shipmentOrder;
return $shipmentOrders;
}
/**
* @return ShipmentOrderType[]
* @throws RequestValidatorException
* @throws \Exception
*/
public static function createMultiShipmentSuccess(): array
{
$shipmentOrders = [];
$tsShip = time() + 60 * 60 * 24; // tomorrow
$requestBuilder = new ShipmentOrderRequestBuilder();
$requestBuilder->setSequenceNumber('0');
$requestBuilder->setShipperAccount('22222222220101');
$requestBuilder->setShipperAddress('Netresearch GmbH & Co.KG', 'DE', '04229', 'Leipzig', 'Nonnenstraße', '11d');
$requestBuilder->setRecipientAddress('<NAME>', 'DE', '53113', 'Bonn', 'Charles-de-Gaulle-Straße', '20');
$requestBuilder->setShipmentDetails('V01PAK', new \DateTime(date('Y-m-d', $tsShip)));
$requestBuilder->setPackageDetails(2.4);
$shipmentOrder = $requestBuilder->create();
$shipmentOrders[] = $shipmentOrder;
$requestBuilder->setSequenceNumber('1');
$requestBuilder->setShipperAccount('22222222220101');
$requestBuilder->setShipperAddress('Netresearch GmbH & Co.KG', 'DE', '04229', 'Leipzig', 'Nonnenstraße', '11d');
$requestBuilder->setRecipientAddress('<NAME>', 'DE', '53113', 'Bonn', 'Sträßchensweg', '2');
$requestBuilder->setShipmentDetails('V01PAK', new \DateTime(date('Y-m-d', $tsShip)));
$requestBuilder->setPackageDetails(1.125);
$shipmentOrder = $requestBuilder->create();
$shipmentOrders[] = $shipmentOrder;
return $shipmentOrders;
}
/**
* wrong address and "print only if codeable" is active.
*
* @return ShipmentOrderType[]
* @throws RequestValidatorException
* @throws \Exception
*/
public static function createMultiShipmentPartialSuccess(): array
{
$shipmentOrders = [];
$tsShip = time() + 60 * 60 * 24; // tomorrow
$requestBuilder = new ShipmentOrderRequestBuilder();
$requestBuilder->setPrintOnlyIfCodeable();
$requestBuilder->setSequenceNumber('0');
$requestBuilder->setShipperAccount('22222222220101');
$requestBuilder->setShipperAddress('Netresearch GmbH & Co.KG', 'DE', '04229', 'Leipzig', 'Nonnenstraße', '11d');
$requestBuilder->setRecipientAddress('<NAME>', 'DE', '53113', 'Bonn', 'Charles-de-Gaulle-Straße', '20');
$requestBuilder->setShipmentDetails('V01PAK', new \DateTime(date('Y-m-d', $tsShip)));
$requestBuilder->setPackageDetails(2.4);
$shipmentOrder = $requestBuilder->create();
$shipmentOrders[] = $shipmentOrder;
$requestBuilder->setPrintOnlyIfCodeable();
$requestBuilder->setSequenceNumber('1');
$requestBuilder->setShipperAccount('22222222220101');
$requestBuilder->setShipperAddress('Netresearch GmbH & Co.KG', 'DE', '04229', 'Leipzig', 'Nonnenstraße', '11d');
$requestBuilder->setRecipientAddress('<NAME>', 'DE', '04229', 'Bonn', 'Sträßchensweg', '2'); // wrong zip code
$requestBuilder->setShipmentDetails('V01PAK', new \DateTime(date('Y-m-d', $tsShip)));
$requestBuilder->setPackageDetails(1.125);
$shipmentOrder = $requestBuilder->create();
$shipmentOrders[] = $shipmentOrder;
return $shipmentOrders;
}
/**
* wrong address but "print only if codeable" is not active.
*
* @return ShipmentOrderType[]
* @throws RequestValidatorException
* @throws \Exception
*/
public static function createShipmentsValidationWarning(): array
{
$shipmentOrders = [];
$tsShip = time() + 60 * 60 * 24; // tomorrow
$requestBuilder = new ShipmentOrderRequestBuilder();
$requestBuilder->setSequenceNumber('0');
$requestBuilder->setShipperAccount('22222222220101');
$requestBuilder->setShipperAddress('Netresearch GmbH & Co.KG', 'DE', '04229', 'Leipzig', 'Nonnenstraße', '11d');
$requestBuilder->setRecipientAddress('<NAME>', 'DE', '53113', 'Bonn', 'Charles-de-Gaulle-Straße', '20');
$requestBuilder->setShipmentDetails('V01PAK', new \DateTime(date('Y-m-d', $tsShip)));
$requestBuilder->setPackageDetails(2.4);
$shipmentOrder = $requestBuilder->create();
$shipmentOrders[] = $shipmentOrder;
$requestBuilder->setSequenceNumber('1');
$requestBuilder->setShipperAccount('22222222220101');
$requestBuilder->setShipperAddress('Netresearch GmbH & Co.KG', 'DE', '04229', 'Leipzig', 'Nonnenstraße', '11d');
$requestBuilder->setRecipientAddress('<NAME>', 'DE', '04229', 'Bonn', 'Sträßchensweg', '2'); // wrong zip code
$requestBuilder->setShipmentDetails('V01PAK', new \DateTime(date('Y-m-d', $tsShip)));
$requestBuilder->setPackageDetails(1.125);
$shipmentOrder = $requestBuilder->create();
$shipmentOrders[] = $shipmentOrder;
return $shipmentOrders;
}
/**
* wrong address and "print only if codeable" is active.
*
* @return ShipmentOrderType[]
* @throws RequestValidatorException
* @throws \Exception
*/
public static function createSingleShipmentError(): array
{
$shipmentOrders = [];
$tsShip = time() + 60 * 60 * 24; // tomorrow
$requestBuilder = new ShipmentOrderRequestBuilder();
$requestBuilder->setPrintOnlyIfCodeable();
$requestBuilder->setSequenceNumber('0');
$requestBuilder->setShipperAccount('22222222220101');
$requestBuilder->setShipperAddress('Netresearch GmbH & Co.KG', 'DE', '04229', 'Leipzig', 'Nonnenstraße', '11d');
$requestBuilder->setRecipientAddress('<NAME>', 'DE', '04229', 'Bonn', 'Sträßchensweg', '2'); // wrong zip code
$requestBuilder->setShipmentDetails('V01PAK', new \DateTime(date('Y-m-d', $tsShip)));
$requestBuilder->setPackageDetails(1.125);
$shipmentOrder = $requestBuilder->create();
$shipmentOrders[] = $shipmentOrder;
return $shipmentOrders;
}
/**
* wrong address and "print only if codeable" is active.
*
* @return ShipmentOrderType[]
* @throws RequestValidatorException
* @throws \Exception
*/
public static function createMultiShipmentError(): array
{
$shipmentOrders = [];
$tsShip = time() + 60 * 60 * 24; // tomorrow
$requestBuilder = new ShipmentOrderRequestBuilder();
$requestBuilder->setPrintOnlyIfCodeable();
$requestBuilder->setSequenceNumber('0');
$requestBuilder->setShipperAccount('22222222220101');
$requestBuilder->setShipperAddress(
'Netresearch GmbH & Co.KG',
'DE',
'04229',
'Leipzig',
'Nonnenstraße',
'11d'
);
$requestBuilder->setRecipientAddress(
'<NAME>',
'DE',
'04229',
'Bonn',
'Charles-de-Gaulle-Straße',
'20'
); // wrong zip code
$requestBuilder->setShipmentDetails('V01PAK', new \DateTime(date('Y-m-d', $tsShip)));
$requestBuilder->setPackageDetails(2.4);
$shipmentOrder = $requestBuilder->create();
$shipmentOrders[] = $shipmentOrder;
$requestBuilder->setPrintOnlyIfCodeable();
$requestBuilder->setSequenceNumber('1');
$requestBuilder->setShipperAccount('22222222220101');
$requestBuilder->setShipperAddress('Netresearch GmbH & Co.KG', 'DE', '04229', 'Leipzig', 'Nonnenstraße', '11d');
$requestBuilder->setRecipientAddress('<NAME>', 'DE', '04229', 'Bonn', 'Sträßchensweg', '2'); // wrong zip code
$requestBuilder->setShipmentDetails('V01PAK', new \DateTime(date('Y-m-d', $tsShip)));
$requestBuilder->setPackageDetails(1.125);
$shipmentOrder = $requestBuilder->create();
$shipmentOrders[] = $shipmentOrder;
return $shipmentOrders;
}
}
<file_sep>/src/Service/ShipmentService.php
<?php
/**
* See LICENSE.md for license details.
*/
declare(strict_types=1);
namespace Dhl\Sdk\Paket\Bcs\Service;
use Dhl\Sdk\Paket\Bcs\Api\ShipmentServiceInterface;
use Dhl\Sdk\Paket\Bcs\Exception\AuthenticationErrorException;
use Dhl\Sdk\Paket\Bcs\Exception\DetailedErrorException;
use Dhl\Sdk\Paket\Bcs\Exception\ServiceExceptionFactory;
use Dhl\Sdk\Paket\Bcs\Model\Common\Version;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\CreateShipmentOrderRequest;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\CreateShipmentResponseMapper;
use Dhl\Sdk\Paket\Bcs\Model\DeleteShipment\DeleteShipmentOrderRequest;
use Dhl\Sdk\Paket\Bcs\Model\DeleteShipment\DeleteShipmentResponseMapper;
use Dhl\Sdk\Paket\Bcs\Soap\AbstractClient;
class ShipmentService implements ShipmentServiceInterface
{
/**
* @var AbstractClient
*/
private $client;
/**
* @var CreateShipmentResponseMapper
*/
private $createShipmentResponseMapper;
/**
* @var DeleteShipmentResponseMapper
*/
private $deleteShipmentResponseMapper;
public function __construct(
AbstractClient $client,
CreateShipmentResponseMapper $createShipmentResponseMapper,
DeleteShipmentResponseMapper $deleteShipmentResponseMapper
) {
$this->client = $client;
$this->createShipmentResponseMapper = $createShipmentResponseMapper;
$this->deleteShipmentResponseMapper = $deleteShipmentResponseMapper;
}
public function createShipments(array $shipmentOrders): array
{
try {
$version = new Version('3', '1');
$version->setBuild('2');
$createShipmentRequest = new CreateShipmentOrderRequest($version, array_values($shipmentOrders));
$createShipmentRequest->setLabelResponseType('B64');
$shipmentResponse = $this->client->createShipmentOrder($createShipmentRequest);
return $this->createShipmentResponseMapper->map($shipmentResponse);
} catch (AuthenticationErrorException $exception) {
throw ServiceExceptionFactory::createAuthenticationException($exception);
} catch (DetailedErrorException $exception) {
throw ServiceExceptionFactory::createDetailedServiceException($exception);
} catch (\Throwable $exception) {
// Catch all leftovers, e.g. \SoapFault, \Exception, ...
throw ServiceExceptionFactory::createServiceException($exception);
}
}
public function cancelShipments(array $shipmentNumbers): array
{
try {
$version = new Version('3', '1');
$version->setBuild('2');
$deleteShipmentRequest = new DeleteShipmentOrderRequest($version, $shipmentNumbers);
$shipmentResponse = $this->client->deleteShipmentOrder($deleteShipmentRequest);
return $this->deleteShipmentResponseMapper->map($shipmentResponse);
} catch (AuthenticationErrorException $exception) {
throw ServiceExceptionFactory::createAuthenticationException($exception);
} catch (DetailedErrorException $exception) {
throw ServiceExceptionFactory::createDetailedServiceException($exception);
} catch (\Throwable $exception) {
// Catch all leftovers, e.g. \SoapFault, \Exception, ...
throw ServiceExceptionFactory::createServiceException($exception);
}
}
}
<file_sep>/README.md
# DHL BCS API SDK
The DHL Business Customer Shipping API SDK package offers an interface to the following web services:
- Geschäftskundenversand 3.1.2
## Requirements
### System Requirements
- PHP 7.1+ with SOAP extension
### Package Requirements
- `psr/log`: PSR-3 logger interfaces
### Development Package Requirements
- `phpunit/phpunit`: Testing framework
## Installation
```bash
$ composer require dhl/sdk-api-bcs
```
## Uninstallation
```bash
$ composer remove dhl/sdk-api-bcs
```
## Testing
```bash
$ ./vendor/bin/phpunit -c test/phpunit.xml
```
## Features
The DHL BCS API SDK supports the following features:
* Create Shipment Order
* Delete Shipment Order
### Authentication
The DHL BCS API requires a two-level authentication (_HTTP Basic Authentication_
and _SOAP Header Authentication_). The API SDK offers an authentication storage
to pass credentials in.
```php
$authStorage = new \Dhl\Sdk\Paket\Bcs\Auth\AuthenticationStorage('appId', 'appToken', 'user', 'signature');
```
### Create Shipment Order
Create shipments for DHL Paket including the relevant shipping documents.
#### Public API
The library's components suitable for consumption comprise
* services:
* service factory
* shipment service
* data transfer object builder
* data transfer objects:
* authentication storage
* shipment with shipment/tracking number and label(s)
#### Usage
```php
$logger = new \Psr\Log\NullLogger();
$serviceFactory = new ServiceFactory();
$service = $serviceFactory->createShipmentService($authStorage, $logger, $sandbox = true);
$requestBuilder = new ShipmentOrderRequestBuilder();
$requestBuilder->setShipperAccount($billingNumber = '22222222220101');
$requestBuilder->setShipperAddress(
$company = 'DHL',
$country = 'DE',
$postalCode = '53113',
$city = 'Bonn',
$street = 'Charles-de-Gaulle-Straße',
$streetNumber = '20'
);
$requestBuilder->setRecipientAddress(
$recipientName = '<NAME>',
$recipientCountry = 'DE',
$recipientPostalCode = '53113',
$recipientCity = 'Bonn',
$recipientStreet = 'Sträßchensweg',
$recipientStreetNumber = '2'
);
$requestBuilder->setShipmentDetails($productCode = 'V01PAK', $shipmentDate = '2019-09-09');
$requestBuilder->setPackageDetails($weightInKg = 2.4);
$shipmentOrder = $requestBuilder->create();
$shipments = $service->createShipments([$shipmentOrder]);
```
### Delete Shipment Order
Cancel earlier created shipments.
#### Public API
The library's components suitable for consumption comprise of
* services:
* service factory
* shipment service
* data transfer objects:
* authentication storage
#### Usage
```php
$logger = new \Psr\Log\NullLogger();
$serviceFactory = new ServiceFactory();
$service = $serviceFactory->createShipmentService($authStorage, $logger, $sandbox = true);
$shipmentNumber = '222201011234567890';
$cancelled = $service->cancelShipments([$shipmentNumber]);
```
<file_sep>/src/Service/ServiceFactory.php
<?php
/**
* See LICENSE.md for license details.
*/
declare(strict_types=1);
namespace Dhl\Sdk\Paket\Bcs\Service;
use Dhl\Sdk\Paket\Bcs\Api\Data\AuthenticationStorageInterface;
use Dhl\Sdk\Paket\Bcs\Api\ServiceFactoryInterface;
use Dhl\Sdk\Paket\Bcs\Api\ShipmentServiceInterface;
use Dhl\Sdk\Paket\Bcs\Exception\ServiceException;
use Dhl\Sdk\Paket\Bcs\Serializer\ClassMap;
use Dhl\Sdk\Paket\Bcs\Soap\SoapServiceFactory;
use Psr\Log\LoggerInterface;
class ServiceFactory implements ServiceFactoryInterface
{
public function createShipmentService(
AuthenticationStorageInterface $authStorage,
LoggerInterface $logger,
bool $sandboxMode = false
): ShipmentServiceInterface {
$wsdl = sprintf(
'%s/%s/%s',
'https://cig.dhl.de/cig-wsdls/com/dpdhl/wsdl/geschaeftskundenversand-api',
'3.1.2',
'geschaeftskundenversand-api-3.1.2.wsdl'
);
$options = [
'trace' => 1,
'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
'classmap' => ClassMap::get(),
'login' => $authStorage->getApplicationId(),
'password' => $authStorage->getApplicationToken(),
];
if ($sandboxMode) {
// override wsdl's default service location
$options['location'] = self::BASE_URL_SANDBOX;
}
try {
$soapClient = new \SoapClient($wsdl, $options);
} catch (\SoapFault $soapFault) {
throw new ServiceException($soapFault->getMessage(), $soapFault->getCode(), $soapFault);
}
$soapServiceFactory = new SoapServiceFactory($soapClient);
$shipmentService = $soapServiceFactory->createShipmentService($authStorage, $logger, $sandboxMode);
return $shipmentService;
}
}
<file_sep>/src/Soap/AbstractDecorator.php
<?php
/**
* See LICENSE.md for license details.
*/
declare(strict_types=1);
namespace Dhl\Sdk\Paket\Bcs\Soap;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\CreateShipmentOrderRequest;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\CreateShipmentOrderResponse;
use Dhl\Sdk\Paket\Bcs\Model\DeleteShipment\DeleteShipmentOrderRequest;
use Dhl\Sdk\Paket\Bcs\Model\DeleteShipment\DeleteShipmentOrderResponse;
/**
* AbstractDecorator
*
* Wrapper around actual soap client to perform the following tasks:
* - add authentication
* - transform errors into exceptions
* - log communication
*/
abstract class AbstractDecorator extends AbstractClient
{
/**
* @var AbstractClient
*/
private $client;
public function __construct(AbstractClient $client)
{
$this->client = $client;
}
public function createShipmentOrder(CreateShipmentOrderRequest $requestType): CreateShipmentOrderResponse
{
return $this->client->createShipmentOrder($requestType);
}
public function deleteShipmentOrder(DeleteShipmentOrderRequest $requestType): DeleteShipmentOrderResponse
{
return $this->client->deleteShipmentOrder($requestType);
}
}
<file_sep>/test/Expectation/RequestTypeExpectation.php
<?php
/**
* See LICENSE.md for license details.
*/
declare(strict_types=1);
namespace Dhl\Sdk\Paket\Bcs\Test\Expectation;
use PHPUnit\Framework\Assert;
class RequestTypeExpectation
{
/**
* @param mixed[] $requestData
* @param string $requestXml
*/
public static function assertRequestContentsAvailable(array $requestData, string $requestXml): void
{
$request = new \SimpleXMLElement($requestXml);
$request->registerXPathNamespace('SOAP-ENV', 'http://schemas.xmlsoap.org/soap/envelope/');
$request->registerXPathNamespace('ns1', 'http://dhl.de/webservice/cisbase');
$request->registerXPathNamespace('ns2', 'http://dhl.de/webservices/businesscustomershipping/3.0');
$request = $request->xpath('/SOAP-ENV:Envelope/SOAP-ENV:Body/ns2:CreateShipmentOrderRequest')[0];
foreach ($requestData as $sequenceNumber => $shipmentOrderData) {
$shipmentOrder = $request->xpath("./ShipmentOrder[./sequenceNumber = '$sequenceNumber']")[0];
foreach ($shipmentOrderData as $key => $expectedValue) {
$expectedValue = is_bool($expectedValue) ? intval($expectedValue) : $expectedValue;
$path = XPath::get($key);
if ($key === 'shipDate') {
$expectedValue = $expectedValue->format('Y-m-d');
}
Assert::assertEquals((string) $expectedValue, (string) $shipmentOrder->xpath($path)[0]);
}
}
}
}
<file_sep>/test/Expectation/ShipmentServiceTestExpectation.php
<?php
/**
* See LICENSE.md for license details.
*/
declare(strict_types=1);
namespace Dhl\Sdk\Paket\Bcs\Test\Expectation;
use Dhl\Sdk\Paket\Bcs\Api\Data\ShipmentInterface;
use PHPUnit\Framework\Assert;
class ShipmentServiceTestExpectation
{
/**
* @param string $requestXml
* @param string $responseXml
* @param ShipmentInterface[] $result
*/
public static function assertAllShipmentsBooked(string $requestXml, string $responseXml, array $result): void
{
$request = new \SimpleXMLElement($requestXml);
$request->registerXPathNamespace('SOAP-ENV', 'http://schemas.xmlsoap.org/soap/envelope/');
$request->registerXPathNamespace('ns2', 'http://dhl.de/webservices/businesscustomershipping/3.0');
$request = $request->xpath('/SOAP-ENV:Envelope/SOAP-ENV:Body/ns2:CreateShipmentOrderRequest')[0];
$response = new \SimpleXMLElement($responseXml);
$response->registerXPathNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
$response->registerXPathNamespace('bcs', 'http://dhl.de/webservices/businesscustomershipping/3.0');
$response = $response->xpath('/soap:Envelope/soap:Body/bcs:CreateShipmentOrderResponse')[0];
// assert that all sequence numbers of the request are available in the response
$expected = $request->xpath('./ShipmentOrder/sequenceNumber');
$actual = array_map(function (ShipmentInterface $shipment) {
return $shipment->getSequenceNumber();
}, $result);
Assert::assertEmpty(array_diff($expected, $actual), 'Sequence numbers of the response do not match.');
// assert that all labels are included in the response
foreach ($result as $shipment) {
$sn = $shipment->getSequenceNumber();
$labelData = $response->xpath("./CreationState[sequenceNumber=$sn]/LabelData")[0];
$expected = $labelData->xpath("./*[substring(name(), string-length(name()) - 3) = 'Data']");
$actual = array_filter($shipment->getLabels());
Assert::assertEmpty(array_diff($expected, $actual), "Returned labels are not mapped to result for $sn.");
}
}
/**
* @param string $requestXml
* @param string $responseXml
* @param ShipmentInterface[] $result
*/
public static function assertSomeShipmentsBooked(string $requestXml, string $responseXml, array $result): void
{
$request = new \SimpleXMLElement($requestXml);
$request->registerXPathNamespace('SOAP-ENV', 'http://schemas.xmlsoap.org/soap/envelope/');
$request->registerXPathNamespace('ns2', 'http://dhl.de/webservices/businesscustomershipping/3.0');
$request = $request->xpath('/SOAP-ENV:Envelope/SOAP-ENV:Body/ns2:CreateShipmentOrderRequest')[0];
$response = new \SimpleXMLElement($responseXml);
$response->registerXPathNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
$response->registerXPathNamespace('bcs', 'http://dhl.de/webservices/businesscustomershipping/3.0');
$response = $response->xpath('/soap:Envelope/soap:Body/bcs:CreateShipmentOrderResponse')[0];
// assert that all sequence numbers of the request are available in the response
$expected = $request->xpath('./ShipmentOrder/sequenceNumber');
$actual = $response->xpath('./CreationState/sequenceNumber');
Assert::assertEmpty(array_diff($expected, $actual), 'Sequence numbers of the response do not match.');
// assert that success and error status are contained in the response
$labels = $response->xpath("./CreationState/LabelData[./Status/statusCode = '0']");
$errors = $response->xpath("./CreationState/LabelData[./Status/statusCode != '0']");
Assert::assertCount(count($expected), array_merge($labels, $errors));
// assert that shipments were created but not all of them
Assert::assertNotEmpty($result);
Assert::assertLessThan(count($expected), count($result));
}
/**
* @param string $requestXml
* @param string[] $result
*/
public static function assertAllShipmentsCancelled(string $requestXml, array $result): void
{
$request = new \SimpleXMLElement($requestXml);
$request->registerXPathNamespace('SOAP-ENV', 'http://schemas.xmlsoap.org/soap/envelope/');
$request->registerXPathNamespace('ns1', 'http://dhl.de/webservice/cisbase');
$request->registerXPathNamespace('ns2', 'http://dhl.de/webservices/businesscustomershipping/3.0');
$request = $request->xpath('/SOAP-ENV:Envelope/SOAP-ENV:Body/ns2:DeleteShipmentOrderRequest')[0];
// assert that all shipment numbers of the request are available in the response
$expected = $request->xpath('./shipmentNumber');
Assert::assertEmpty(array_diff($expected, $result), 'Shipment numbers of the response do not match.');
}
/**
* @param string $requestXml
* @param string $responseXml
* @param string[] $result
*/
public static function assertSomeShipmentsCancelled(string $requestXml, string $responseXml, array $result): void
{
$request = new \SimpleXMLElement($requestXml);
$request->registerXPathNamespace('SOAP-ENV', 'http://schemas.xmlsoap.org/soap/envelope/');
$request->registerXPathNamespace('ns1', 'http://dhl.de/webservice/cisbase');
$request->registerXPathNamespace('ns2', 'http://dhl.de/webservices/businesscustomershipping/3.0');
$request = $request->xpath('/SOAP-ENV:Envelope/SOAP-ENV:Body/ns2:DeleteShipmentOrderRequest')[0];
$response = new \SimpleXMLElement($responseXml);
$response->registerXPathNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
$response->registerXPathNamespace('bcs', 'http://dhl.de/webservices/businesscustomershipping/3.0');
$response->registerXPathNamespace('cis', 'http://dhl.de/webservice/cisbase');
$response = $response->xpath('/soap:Envelope/soap:Body/bcs:DeleteShipmentOrderResponse')[0];
// assert that all shipment numbers of the request are available in the response
$expected = $request->xpath('./ns1:shipmentNumber');
$actual = $response->xpath('./DeletionState/cis:shipmentNumber');
Assert::assertEmpty(array_diff($expected, $actual), 'Shipment numbers of the response do not match.');
// assert that success and error status are contained in the response
$cancelled = $response->xpath("./DeletionState/Status[./statusCode = '0']");
$failed = $response->xpath("./DeletionState/Status[./statusCode != '0']");
Assert::assertCount(count($expected), array_merge($cancelled, $failed));
// assert that shipments were cancelled but not all of them
Assert::assertNotEmpty($result);
Assert::assertLessThan(count($expected), count($result));
}
}
<file_sep>/src/Model/CreateShipment/RequestType/ServiceConfigurationCashOnDelivery.php
<?php
/**
* See LICENSE.md for license details.
*/
declare(strict_types=1);
namespace Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType;
class ServiceConfigurationCashOnDelivery
{
/**
* Indicates, if the option is on/off.
*
* @var int $active "0" or "1"
*/
protected $active;
/**
* Money amount to be collected. Mandatory if COD is chosen.
*
* @var float $codAmount
*/
protected $codAmount;
/**
* Configuration whether the transmission fee to be added to the COD amount or not by DHL.
*
* @var int|null $addFee "0" or "1"
*/
protected $addFee;
public function __construct(bool $active, float $codAmount)
{
$this->active = (int) $active;
$this->codAmount = $codAmount;
}
/**
* @param bool|null $addFee
*
* @return ServiceConfigurationCashOnDelivery
*/
public function setAddFee(bool $addFee = null): self
{
$this->addFee = (int) $addFee;
return $this;
}
}
<file_sep>/src/Soap/AbstractClient.php
<?php
/**
* See LICENSE.md for license details.
*/
declare(strict_types=1);
namespace Dhl\Sdk\Paket\Bcs\Soap;
use Dhl\Sdk\Paket\Bcs\Exception\AuthenticationErrorException;
use Dhl\Sdk\Paket\Bcs\Exception\DetailedErrorException;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\CreateShipmentOrderRequest;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\CreateShipmentOrderResponse;
use Dhl\Sdk\Paket\Bcs\Model\DeleteShipment\DeleteShipmentOrderRequest;
use Dhl\Sdk\Paket\Bcs\Model\DeleteShipment\DeleteShipmentOrderResponse;
abstract class AbstractClient
{
/**
* CreateShipmentOrder is the operation call used to generate shipments with the relevant DHL Paket labels.
*
* @param CreateShipmentOrderRequest $requestType
*
* @return CreateShipmentOrderResponse
*
* @throws AuthenticationErrorException
* @throws DetailedErrorException
* @throws \SoapFault
*/
abstract public function createShipmentOrder(CreateShipmentOrderRequest $requestType): CreateShipmentOrderResponse;
/**
* DeleteShipmentOrder is the operation call used to cancel created shipments.
*
* Note that cancellation is only possible before the end-of-the-day manifest.
*
* @param DeleteShipmentOrderRequest $requestType
*
* @return DeleteShipmentOrderResponse
*
* @throws AuthenticationErrorException
* @throws DetailedErrorException
* @throws \SoapFault
*/
abstract public function deleteShipmentOrder(DeleteShipmentOrderRequest $requestType): DeleteShipmentOrderResponse;
}
<file_sep>/src/Model/CreateShipment/RequestType/ShipmentService.php
<?php
/**
* See LICENSE.md for license details.
*/
declare(strict_types=1);
namespace Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType;
class ShipmentService
{
/**
* Day of Delivery for product: V06TG: Kurier Taggleich; V06WZ: Kurier Wunschzeit
*
* @var ServiceConfigurationDateOfDelivery|null $DayOfDelivery
*/
protected $DayOfDelivery = null;
/**
* Timeframe of delivery for product: V06TG: Kurier Taggleich; V06WZ: Kurier Wunschzeit
*
* @var ServiceConfigurationDeliveryTimeFrame|null $DeliveryTimeframe
*/
protected $DeliveryTimeframe = null;
/**
* Preferred Time of delivery for product: V01PAK: DHL PAKET V06PAK: DHL PAKET TAGGLEICH
*
* @var ServiceConfigurationDeliveryTimeFrame|null $PreferredTime
*/
protected $PreferredTime = null;
/**
* Individual sender requirements for product: V06TG: Kurier Taggleich V06WZ: Kurier Wunschzeit.
*
* @var ServiceConfigurationISR|null $IndividualSenderRequirement
*/
protected $IndividualSenderRequirement = null;
/**
* Service for package return.
*
* @var ServiceConfiguration|null $PackagingReturn
*/
protected $PackagingReturn = null;
/**
* Service of immediatly shipment return in case of non sucessful delivery for product: V06PAK: DHL PAKET TAGGLEICH.
*
* @var ServiceConfiguration|null $ReturnImmediately
*/
protected $ReturnImmediately = null;
/**
* Service Notice of non-deliverability.
*
* @var ServiceConfiguration|null $NoticeOfNonDeliverability
*/
protected $NoticeOfNonDeliverability = null;
/**
* Shipment handling for product: V06TG: Kurier Taggleich; V06WZ: Kurier Wunschzeit.
*
* @var ServiceConfigurationShipmentHandling|null $ShipmentHandling
*/
protected $ShipmentHandling = null;
/**
* Service "Endorsement".
*
* @var ServiceConfigurationEndorsement|null $Endorsement
*/
protected $Endorsement = null;
/**
* Service visual age check.
*
* @var ServiceConfigurationVisualAgeCheck|null $VisualCheckOfAge
*/
protected $VisualCheckOfAge = null;
/**
* Service preferred location.
*
* @var ServiceConfigurationDetails|null $PreferredLocation
*/
protected $PreferredLocation = null;
/**
* Service preferred neighbour.
*
* @var ServiceConfigurationDetails|null $PreferredNeighbour
*/
protected $PreferredNeighbour = null;
/**
* Service preferred day.
*
* @var ServiceConfigurationDetails|null $PreferredDay
*/
protected $PreferredDay = null;
/**
* GoGreen.
*
* @var ServiceConfiguration|null $GoGreen
*/
protected $GoGreen = null;
/**
* DHL Kurier Verderbliche Ware.
*
* @var ServiceConfiguration|null $Perishables
*/
protected $Perishables = null;
/**
* Invoke service personal handover.
*
* @var ServiceConfiguration|null $Personally
*/
protected $Personally = null;
/**
* Invoke service No Neighbour Delivery.
*
* @var ServiceConfiguration|null $NoNeighbourDelivery
*/
protected $NoNeighbourDelivery = null;
/**
* Invoke service Named Person Only.
*
* @var ServiceConfiguration|null $NamedPersonOnly
*/
protected $NamedPersonOnly = null;
/**
* Invoke service return receipt.
*
* @var ServiceConfiguration|null $ReturnReceipt
*/
protected $ReturnReceipt = null;
/**
* Premium for fast and safe delivery of international shipments.
*
* @var ServiceConfiguration|null $Premium
*/
protected $Premium = null;
/**
* Service Cash on delivery.
*
* @var ServiceConfigurationCashOnDelivery|null $CashOnDelivery
*/
protected $CashOnDelivery = null;
/**
* Insure shipment with higher than standard amount.
*
* @var ServiceConfigurationAdditionalInsurance|null $AdditionalInsurance
*/
protected $AdditionalInsurance = null;
/**
* Service to ship bulky goods.
*
* @var ServiceConfiguration|null $BulkyGoods
*/
protected $BulkyGoods = null;
/**
* Service configuration for IdentCheck.
*
* @var ServiceConfigurationIC|null $IdentCheck
*/
protected $IdentCheck = null;
/**
* Service configuration for ParcelOutletRouting. If email-address is not set, receiver email will be used.
*
* @var ServiceConfigurationDetailsOptional|null $ParcelOutletRouting
*/
protected $ParcelOutletRouting = null;
/**
* @param ServiceConfigurationDateOfDelivery|null $dayOfDelivery
* @return ShipmentService
*/
public function setDayOfDelivery(ServiceConfigurationDateOfDelivery $dayOfDelivery = null): self
{
$this->DayOfDelivery = $dayOfDelivery;
return $this;
}
/**
* @param ServiceConfigurationDeliveryTimeFrame|null $deliveryTimeframe
* @return ShipmentService
*/
public function setDeliveryTimeframe(ServiceConfigurationDeliveryTimeFrame $deliveryTimeframe = null): self
{
$this->DeliveryTimeframe = $deliveryTimeframe;
return $this;
}
/**
* @param ServiceConfigurationDeliveryTimeFrame|null $preferredTime
* @return ShipmentService
*/
public function setPreferredTime(ServiceConfigurationDeliveryTimeFrame $preferredTime = null): self
{
$this->PreferredTime = $preferredTime;
return $this;
}
/**
* @param ServiceConfigurationISR|null $individualSenderRequirement
* @return ShipmentService
*/
public function setIndividualSenderRequirement(ServiceConfigurationISR $individualSenderRequirement = null): self
{
$this->IndividualSenderRequirement = $individualSenderRequirement;
return $this;
}
/**
* @param ServiceConfiguration|null $packagingReturn
* @return ShipmentService
*/
public function setPackagingReturn(ServiceConfiguration $packagingReturn = null): self
{
$this->PackagingReturn = $packagingReturn;
return $this;
}
/**
* @param ServiceConfiguration|null $returnImmediately
* @return ShipmentService
*/
public function setReturnImmediately(ServiceConfiguration $returnImmediately = null): self
{
$this->ReturnImmediately = $returnImmediately;
return $this;
}
/**
* @param ServiceConfiguration|null $noticeOfNonDeliverability
* @return ShipmentService
*/
public function setNoticeOfNonDeliverability(ServiceConfiguration $noticeOfNonDeliverability = null): self
{
$this->NoticeOfNonDeliverability = $noticeOfNonDeliverability;
return $this;
}
/**
* @param ServiceConfigurationShipmentHandling|null $shipmentHandling
* @return ShipmentService
*/
public function setShipmentHandling(ServiceConfigurationShipmentHandling $shipmentHandling = null): self
{
$this->ShipmentHandling = $shipmentHandling;
return $this;
}
/**
* @param ServiceConfigurationEndorsement|null $endorsement
* @return ShipmentService
*/
public function setEndorsement(ServiceConfigurationEndorsement $endorsement = null): self
{
$this->Endorsement = $endorsement;
return $this;
}
/**
* @param ServiceConfigurationVisualAgeCheck|null $visualCheckOfAge
* @return ShipmentService
*/
public function setVisualCheckOfAge(ServiceConfigurationVisualAgeCheck $visualCheckOfAge = null): self
{
$this->VisualCheckOfAge = $visualCheckOfAge;
return $this;
}
/**
* @param ServiceConfigurationDetails|null $preferredLocation
* @return ShipmentService
*/
public function setPreferredLocation(ServiceConfigurationDetails $preferredLocation = null): self
{
$this->PreferredLocation = $preferredLocation;
return $this;
}
/**
* @param ServiceConfigurationDetails|null $preferredNeighbour
* @return ShipmentService
*/
public function setPreferredNeighbour(ServiceConfigurationDetails $preferredNeighbour = null): self
{
$this->PreferredNeighbour = $preferredNeighbour;
return $this;
}
/**
* @param ServiceConfigurationDetails|null $preferredDay
* @return ShipmentService
*/
public function setPreferredDay(ServiceConfigurationDetails $preferredDay = null): self
{
$this->PreferredDay = $preferredDay;
return $this;
}
/**
* @param ServiceConfiguration|null $goGreen
* @return ShipmentService
*/
public function setGoGreen(ServiceConfiguration $goGreen = null): self
{
$this->GoGreen = $goGreen;
return $this;
}
/**
* @param ServiceConfiguration|null $perishables
* @return ShipmentService
*/
public function setPerishables(ServiceConfiguration $perishables = null): self
{
$this->Perishables = $perishables;
return $this;
}
/**
* @param ServiceConfiguration|null $personally
* @return ShipmentService
*/
public function setPersonally(ServiceConfiguration $personally = null): self
{
$this->Personally = $personally;
return $this;
}
/**
* @param ServiceConfiguration|null $noNeighbourDelivery
* @return ShipmentService
*/
public function setNoNeighbourDelivery(ServiceConfiguration $noNeighbourDelivery = null): self
{
$this->NoNeighbourDelivery = $noNeighbourDelivery;
return $this;
}
/**
* @param ServiceConfiguration|null $namedPersonOnly
* @return ShipmentService
*/
public function setNamedPersonOnly(ServiceConfiguration $namedPersonOnly = null): self
{
$this->NamedPersonOnly = $namedPersonOnly;
return $this;
}
/**
* @param ServiceConfiguration|null $returnReceipt
* @return ShipmentService
*/
public function setReturnReceipt(ServiceConfiguration $returnReceipt = null): self
{
$this->ReturnReceipt = $returnReceipt;
return $this;
}
/**
* @param ServiceConfiguration|null $premium
* @return ShipmentService
*/
public function setPremium(ServiceConfiguration $premium = null): self
{
$this->Premium = $premium;
return $this;
}
/**
* @param ServiceConfigurationCashOnDelivery|null $cashOnDelivery
* @return ShipmentService
*/
public function setCashOnDelivery(ServiceConfigurationCashOnDelivery $cashOnDelivery = null): self
{
$this->CashOnDelivery = $cashOnDelivery;
return $this;
}
/**
* @param ServiceConfigurationAdditionalInsurance|null $additionalInsurance
* @return ShipmentService
*/
public function setAdditionalInsurance(ServiceConfigurationAdditionalInsurance $additionalInsurance = null): self
{
$this->AdditionalInsurance = $additionalInsurance;
return $this;
}
/**
* @param ServiceConfiguration|null $bulkyGoods
* @return ShipmentService
*/
public function setBulkyGoods(ServiceConfiguration $bulkyGoods = null): self
{
$this->BulkyGoods = $bulkyGoods;
return $this;
}
/**
* @param ServiceConfigurationIC|null $identCheck
* @return ShipmentService
*/
public function setIdentCheck(ServiceConfigurationIC $identCheck = null): self
{
$this->IdentCheck = $identCheck;
return $this;
}
/**
* @param ServiceConfigurationDetailsOptional|null $parcelOutletRouting
* @return ShipmentService
*/
public function setParcelOutletRouting(ServiceConfigurationDetailsOptional $parcelOutletRouting = null): self
{
$this->ParcelOutletRouting = $parcelOutletRouting;
return $this;
}
}
<file_sep>/test/Provider/ShipmentServiceTestProvider.php
<?php
/**
* See LICENSE.md for license details.
*/
declare(strict_types=1);
namespace Dhl\Sdk\Paket\Bcs\Test\Provider;
use Dhl\Sdk\Paket\Bcs\Exception\RequestValidatorException;
class ShipmentServiceTestProvider
{
/**
* Provide request and response for the test case
* - shipment(s) sent to the API, all label(s) successfully booked.
*
* @return mixed[]
* @throws RequestValidatorException
*/
public static function createShipmentsSuccess(): array
{
$wsdl = __DIR__ . '/_files/bcs-3.1.2/geschaeftskundenversand-api-3.1.2.wsdl';
$authStorage = AuthenticationStorageProvider::authSuccess();
$singleLabelRequest = ShipmentRequestProvider::createSingleShipmentSuccess();
$singleLabelResponseXml = \file_get_contents(__DIR__ . '/_files/createshipment/singleShipmentSuccess.xml');
$multiLabelRequest = ShipmentRequestProvider::createMultiShipmentSuccess();
$multiLabelResponseXml = \file_get_contents(__DIR__ . '/_files/createshipment/multiShipmentSuccess.xml');
return [
'single label success' => [$wsdl, $authStorage, $singleLabelRequest, $singleLabelResponseXml],
'multi label success' => [$wsdl, $authStorage, $multiLabelRequest, $multiLabelResponseXml],
];
}
/**
* Provide request and response for the test case
* - shipment(s) sent to the API, some label(s) successfully booked.
*
* @return mixed[]
* @throws RequestValidatorException
*/
public static function createShipmentsPartialSuccess(): array
{
$wsdl = __DIR__ . '/_files/bcs-3.1.2/geschaeftskundenversand-api-3.1.2.wsdl';
$authStorage = AuthenticationStorageProvider::authSuccess();
$labelRequest = ShipmentRequestProvider::createMultiShipmentPartialSuccess();
$labelResponse = \file_get_contents(__DIR__ . '/_files/createshipment/multiShipmentPartialSuccess.xml');
return [
'multi label partial success' => [$wsdl, $authStorage, $labelRequest, $labelResponse],
];
}
/**
* Provide request and response for the test case
* - shipment(s) sent to the API, all label(s) successfully booked, weak validation error occurred.
*
* @return mixed[]
* @throws RequestValidatorException
*/
public static function createShipmentsValidationWarning(): array
{
$wsdl = __DIR__ . '/_files/bcs-3.1.2/geschaeftskundenversand-api-3.1.2.wsdl';
$authStorage = AuthenticationStorageProvider::authSuccess();
$labelRequest = ShipmentRequestProvider::createShipmentsValidationWarning();
$labelResponse = \file_get_contents(__DIR__ . '/_files/createshipment/multiShipmentValidationWarning.xml');
return [
'multi label partial success' => [$wsdl, $authStorage, $labelRequest, $labelResponse],
];
}
/**
* Provide request and response for the test case
* - shipment(s) sent to the API, no label(s) successfully booked, hard validation error occurred.
*
* @return mixed[]
* @throws RequestValidatorException
*/
public static function createShipmentsError(): array
{
$wsdl = __DIR__ . '/_files/bcs-3.1.2/geschaeftskundenversand-api-3.1.2.wsdl';
$authStorage = AuthenticationStorageProvider::authSuccess();
$singleLabelRequest = ShipmentRequestProvider::createSingleShipmentError();
$singleLabelResponseXml = \file_get_contents(__DIR__ . '/_files/createshipment/singleShipmentError.xml');
$multiLabelRequest = ShipmentRequestProvider::createMultiShipmentError();
$multiLabelResponseXml = \file_get_contents(__DIR__ . '/_files/createshipment/multiShipmentError.xml');
return [
'single label validation error' => [$wsdl, $authStorage, $singleLabelRequest, $singleLabelResponseXml],
'multi label validation error' => [$wsdl, $authStorage, $multiLabelRequest, $multiLabelResponseXml],
];
}
/**
* Provide request and response for the test case
* - shipment(s) sent to the API, no label(s) successfully booked, server error occurred (500/1000).
*
* @return mixed[]
* @throws RequestValidatorException
*/
public static function createServerError(): array
{
$wsdl = __DIR__ . '/_files/bcs-3.1.2/geschaeftskundenversand-api-3.1.2.wsdl';
$authStorage = AuthenticationStorageProvider::authSuccess();
$labelRequest = ShipmentRequestProvider::createSingleShipmentSuccess();
$labelResponse = '';
return [
'multi label partial success' => [$wsdl, $authStorage, $labelRequest, $labelResponse],
];
}
/**
* Provide request and response for the test case
* - shipment(s) sent to the API, soap fault thrown.
*
* @return mixed[]
* @throws RequestValidatorException
*/
public static function createServerFault(): array
{
$wsdl = __DIR__ . '/_files/bcs-3.1.2/geschaeftskundenversand-api-3.1.2.wsdl';
$authStorage = AuthenticationStorageProvider::authSuccess();
$labelRequest = ShipmentRequestProvider::createSingleShipmentSuccess();
$soapFault = new \SoapFault(
'soap:Server',
'INVALID_CONFIGURATION',
null,
'System BCS3.3.0.0.0 in environment: SANDBOX is inactive'
);
return [
'server error' => [$wsdl, $authStorage, $labelRequest, $soapFault],
];
}
/**
* Provide request and response for the test case
* - shipment number(s) sent to the API, all shipment(s) successfully cancelled.
*
* @return mixed[]
*/
public static function cancelShipmentsSuccess(): array
{
$wsdl = __DIR__ . '/_files/bcs-3.1.2/geschaeftskundenversand-api-3.1.2.wsdl';
$authStorage = AuthenticationStorageProvider::authSuccess();
$singleShipmentRequest = ['222201010035559339'];
$singleShipmentResponseXml = \file_get_contents(__DIR__ . '/_files/cancelshipment/singleShipmentSuccess.xml');
$multiShipmentRequest = ['222201010035559346', '222201010035559353'];
$multiShipmentResponseXml = \file_get_contents(__DIR__ . '/_files/cancelshipment/multiShipmentSuccess.xml');
return [
'single label success' => [$wsdl, $authStorage, $singleShipmentRequest, $singleShipmentResponseXml],
'multi label success' => [$wsdl, $authStorage, $multiShipmentRequest, $multiShipmentResponseXml],
];
}
/**
* Provide request and response for the test case
* - shipment number(s) sent to the API, some shipment(s) successfully cancelled.
*
* @return mixed[]
*/
public static function cancelShipmentsPartialSuccess(): array
{
$wsdl = __DIR__ . '/_files/bcs-3.1.2/geschaeftskundenversand-api-3.1.2.wsdl';
$authStorage = AuthenticationStorageProvider::authSuccess();
$shipmentRequest = ['ABC1234567890', '222201010035559407'];
$shipmentResponseXml = \file_get_contents(__DIR__ . '/_files/cancelshipment/multiShipmentPartialSuccess.xml');
return [
'multi label partial success' => [$wsdl, $authStorage, $shipmentRequest, $shipmentResponseXml],
];
}
/**
* Provide request and response for the test case
* - shipment number(s) sent to the API, no shipment(s) successfully cancelled.
*
* @return mixed[]
*/
public static function cancelShipmentsError(): array
{
$wsdl = __DIR__ . '/_files/bcs-3.1.2/geschaeftskundenversand-api-3.1.2.wsdl';
$authStorage = AuthenticationStorageProvider::authSuccess();
$singleShipmentRequest = ['ABC1234567890'];
$singleShipmentResponseXml = \file_get_contents(__DIR__ . '/_files/cancelshipment/singleShipmentError.xml');
$multiShipmentRequest = ['ABC9876543210', 'ABC1234567890'];
$multiShipmentResponseXml = \file_get_contents(__DIR__ . '/_files/cancelshipment/multiShipmentError.xml');
return [
'single label error' => [$wsdl, $authStorage, $singleShipmentRequest, $singleShipmentResponseXml],
'multi label error' => [$wsdl, $authStorage, $multiShipmentRequest, $multiShipmentResponseXml],
];
}
/**
* Provide request and response for the test case
* - shipment number(s) sent to the API, soap fault thrown.
*
* @return mixed[]
*/
public static function cancelShipmentsValidationError(): array
{
$wsdl = __DIR__ . '/_files/bcs-3.1.2/geschaeftskundenversand-api-3.1.2.wsdl';
$authStorage = AuthenticationStorageProvider::authSuccess();
$shipmentRequest = ['ABC1234'];
$responseStatus = new \stdClass();
$responseStatus->statusCode = 11;
$responseStatus->statusMessage = 'Das verwendete XML ist ungültig.';
$responseStatus->statusText = 'Not-Wellformed or invalid XML';
$detail = new \stdClass();
$detail->ResponseStatus = $responseStatus;
$soapFault = new \SoapFault(
'env:Client',
'Invalid XML: cvc-minLength-valid.',
null,
$detail
);
return [
'server error' => [$wsdl, $authStorage, $shipmentRequest, $soapFault],
];
}
}
<file_sep>/src/Serializer/ClassMap.php
<?php
/**
* See LICENSE.md for license details.
*/
declare(strict_types=1);
namespace Dhl\Sdk\Paket\Bcs\Serializer;
use Dhl\Sdk\Paket\Bcs\Model\Common\StatusInformation;
use Dhl\Sdk\Paket\Bcs\Model\Common\Version;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\CreateShipmentOrderRequest;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\CreateShipmentOrderResponse;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\BankType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\CommunicationType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\CountryType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ExportDocPosition;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ExportDocumentType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\Ident;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\NameType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\NativeAddressType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\PackStationType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\PostfilialeType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ReceiverNativeAddressType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ReceiverType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ReceiverTypeType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfiguration;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationAdditionalInsurance;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationCashOnDelivery;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationDateOfDelivery;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationDeliveryTimeFrame;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationDetails;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationDetailsOptional;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationEndorsement;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationIC;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationISR;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationShipmentHandling;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationVisualAgeCheck;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\Shipment;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ShipmentDetailsType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ShipmentDetailsTypeType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ShipmentItemType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ShipmentNotificationType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ShipmentOrderType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ShipmentService;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ShipperType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ShipperTypeType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\ResponseType\CreationState;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\ResponseType\LabelData;
use Dhl\Sdk\Paket\Bcs\Model\DeleteShipment\DeleteShipmentOrderRequest;
use Dhl\Sdk\Paket\Bcs\Model\DeleteShipment\DeleteShipmentOrderResponse;
use Dhl\Sdk\Paket\Bcs\Model\DeleteShipment\ResponseType\DeletionState;
class ClassMap
{
/**
* Map WSDL types to PHP classes.
*
* @return string[]
*/
public static function get(): array
{
return [
// shared types
'Statusinformation' => StatusInformation::class,
'Version' => Version::class,
// DELETE SHIPMENT - request types
'DeleteShipmentOrderRequest' => DeleteShipmentOrderRequest::class,
// DELETE SHIPMENT - response types
'DeleteShipmentOrderResponse' => DeleteShipmentOrderResponse::class,
'DeletionState' => DeletionState::class,
// CREATE SHIPMENT - request types
'CreateShipmentOrderRequest' => CreateShipmentOrderRequest::class,
'ShipmentOrderType' => ShipmentOrderType::class,
'Shipment' => Shipment::class,
'ShipmentDetailsTypeType' => ShipmentDetailsTypeType::class,
'ShipmentDetailsType' => ShipmentDetailsType::class,
'ShipmentItemType' => ShipmentItemType::class,
'ShipmentService' => ShipmentService::class,
'ServiceconfigurationDateOfDelivery' => ServiceConfigurationDateOfDelivery::class,
'ServiceconfigurationDeliveryTimeframe' => ServiceConfigurationDeliveryTimeFrame::class,
'ServiceconfigurationISR' => ServiceConfigurationISR::class,
'Serviceconfiguration' => ServiceConfiguration::class,
'ServiceconfigurationShipmentHandling' => ServiceConfigurationShipmentHandling::class,
'ServiceconfigurationEndorsement' => ServiceConfigurationEndorsement::class,
'ServiceconfigurationVisualAgeCheck' => ServiceConfigurationVisualAgeCheck::class,
'ServiceconfigurationDetails' => ServiceConfigurationDetails::class,
'ServiceconfigurationCashOnDelivery' => ServiceConfigurationCashOnDelivery::class,
'ServiceconfigurationAdditionalInsurance' => ServiceConfigurationAdditionalInsurance::class,
'ServiceconfigurationIC' => ServiceConfigurationIC::class,
'Ident' => Ident::class,
'ServiceconfigurationDetailsOptional' => ServiceConfigurationDetailsOptional::class,
'ShipmentNotificationType' => ShipmentNotificationType::class,
'BankType' => BankType::class,
'ShipperType' => ShipperType::class,
'ShipperTypeType' => ShipperTypeType::class,
'NameType' => NameType::class,
'NativeAddressType' => NativeAddressType::class,
'CountryType' => CountryType::class,
'CommunicationType' => CommunicationType::class,
'ReceiverType' => ReceiverType::class,
'ReceiverTypeType' => ReceiverTypeType::class,
'ReceiverNativeAddressType' => ReceiverNativeAddressType::class,
'PackStationType' => PackStationType::class,
'cis:PostfilialeType' => PostfilialeType::class,
'ExportDocumentType' => ExportDocumentType::class,
'ExportDocPosition' => ExportDocPosition::class,
// CREATE SHIPMENT - response types
'CreateShipmentOrderResponse' => CreateShipmentOrderResponse::class,
'CreationState' => CreationState::class,
'LabelData' => LabelData::class,
];
}
}
<file_sep>/src/Soap/Client.php
<?php
/**
* See LICENSE.md for license details.
*/
declare(strict_types=1);
namespace Dhl\Sdk\Paket\Bcs\Soap;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\CreateShipmentOrderRequest;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\CreateShipmentOrderResponse;
use Dhl\Sdk\Paket\Bcs\Model\DeleteShipment\DeleteShipmentOrderRequest;
use Dhl\Sdk\Paket\Bcs\Model\DeleteShipment\DeleteShipmentOrderResponse;
class Client extends AbstractClient
{
/**
* @var \SoapClient
*/
private $soapClient;
public function __construct(\SoapClient $soapClient)
{
$this->soapClient = $soapClient;
}
/**
* CreateShipmentOrder is the operation call used to generate shipments with the relevant DHL Paket labels.
*
* @param CreateShipmentOrderRequest $requestType
*
* @return CreateShipmentOrderResponse
* @throws \SoapFault
*/
public function createShipmentOrder(CreateShipmentOrderRequest $requestType): CreateShipmentOrderResponse
{
/** @var CreateShipmentOrderResponse $response */
$response = $this->soapClient->__soapCall(__FUNCTION__, [$requestType]);
return $response;
}
/**
* @param DeleteShipmentOrderRequest $requestType
*
* @return DeleteShipmentOrderResponse
* @throws \SoapFault
*/
public function deleteShipmentOrder(DeleteShipmentOrderRequest $requestType): DeleteShipmentOrderResponse
{
/** @var DeleteShipmentOrderResponse $response */
$response = $this->soapClient->__soapCall(__FUNCTION__, [$requestType]);
return $response;
}
}
<file_sep>/CHANGELOG.md
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## 1.1.0
### Changed
- Connect to DHL Business Customer Shipping API version 3.1.2 (previously 3.0).
- Argument type of `$shipmentDate` in `ShipmentOrderRequestBuilderInterface::setShipmentDetails`
was changed from `\DateTime` to `\DateTimeInterface`.
### Removed
- PHP 7.0 support
## 1.0.1
Bugfix release
### Fixed
- Cast response status code to `int` to prevent type error, contributed by [@YiffyToys](https://github.com/YiffyToys) via [PR #1](https://github.com/netresearch/dhl-sdk-api-bcs/pull/1)
## 1.0.0
Initial release
<file_sep>/src/RequestBuilder/ShipmentOrderRequestBuilder.php
<?php
/**
* See LICENSE.md for license details.
*/
declare(strict_types=1);
namespace Dhl\Sdk\Paket\Bcs\RequestBuilder;
use Dhl\Sdk\Paket\Bcs\Api\ShipmentOrderRequestBuilderInterface;
use Dhl\Sdk\Paket\Bcs\Exception\RequestValidatorException;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\BankType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\CommunicationType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\CountryType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ExportDocPosition;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ExportDocumentType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\Ident;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\NameType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\NativeAddressType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\PackStationType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\PostfilialeType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ReceiverNativeAddressType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ReceiverType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfiguration;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationAdditionalInsurance;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationCashOnDelivery;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationDateOfDelivery;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationDeliveryTimeFrame;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationDetails;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationDetailsOptional;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationEndorsement;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationIC;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationISR;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationShipmentHandling;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ServiceConfigurationVisualAgeCheck;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\Shipment;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ShipmentDetailsTypeType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ShipmentItemType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ShipmentNotificationType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ShipmentOrderType;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ShipmentService;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ShipperType;
class ShipmentOrderRequestBuilder implements ShipmentOrderRequestBuilderInterface
{
/**
* The collected data used to build the request
*
* @var mixed[]
*/
private $data = [];
public function setSequenceNumber(string $sequenceNumber): ShipmentOrderRequestBuilderInterface
{
$this->data['sequenceNumber'] = $sequenceNumber;
return $this;
}
public function setPrintOnlyIfCodeable(): ShipmentOrderRequestBuilderInterface
{
$this->data['printOnlyIfCodeable'] = true;
return $this;
}
public function setShipperAccount(
string $billingNumber,
string $returnBillingNumber = null
): ShipmentOrderRequestBuilderInterface {
$this->data['shipper']['billingNumber'] = $billingNumber;
$this->data['shipper']['returnBillingNumber'] = $returnBillingNumber;
return $this;
}
public function setShipperAddress(
string $company,
string $country,
string $postalCode,
string $city,
string $streetName,
string $streetNumber,
string $name = null,
string $nameAddition = null,
string $email = null,
string $phone = null,
string $contactPerson = null,
string $state = null,
string $dispatchingInformation = null,
array $addressAddition = []
): ShipmentOrderRequestBuilderInterface {
$this->data['shipper']['address']['company'] = $company;
$this->data['shipper']['address']['country'] = $country;
$this->data['shipper']['address']['postalCode'] = $postalCode;
$this->data['shipper']['address']['city'] = $city;
$this->data['shipper']['address']['streetName'] = $streetName;
$this->data['shipper']['address']['streetNumber'] = $streetNumber;
$this->data['shipper']['address']['name'] = $name;
$this->data['shipper']['address']['nameAddition'] = $nameAddition;
$this->data['shipper']['address']['email'] = $email;
$this->data['shipper']['address']['phone'] = $phone;
$this->data['shipper']['address']['contactPerson'] = $contactPerson;
$this->data['shipper']['address']['state'] = $state;
$this->data['shipper']['address']['dispatchingInformation'] = $dispatchingInformation;
$this->data['shipper']['address']['addressAddition'] = $addressAddition;
return $this;
}
public function setShipperBankData(
string $accountOwner = null,
string $bankName = null,
string $iban = null,
string $bic = null,
string $accountReference = null,
array $notes = []
): ShipmentOrderRequestBuilderInterface {
$this->data['shipper']['bankData']['owner'] = $accountOwner;
$this->data['shipper']['bankData']['bankName'] = $bankName;
$this->data['shipper']['bankData']['iban'] = $iban;
$this->data['shipper']['bankData']['bic'] = $bic;
$this->data['shipper']['bankData']['accountReference'] = $accountReference;
$this->data['shipper']['bankData']['notes'] = $notes;
return $this;
}
public function setReturnAddress(
string $company,
string $country,
string $postalCode,
string $city,
string $streetName,
string $streetNumber,
string $name = null,
string $nameAddition = null,
string $email = null,
string $phone = null,
string $contactPerson = null,
string $state = null,
string $dispatchingInformation = null,
array $addressAddition = []
): ShipmentOrderRequestBuilderInterface {
$this->data['return']['address']['company'] = $company;
$this->data['return']['address']['country'] = $country;
$this->data['return']['address']['postalCode'] = $postalCode;
$this->data['return']['address']['city'] = $city;
$this->data['return']['address']['streetName'] = $streetName;
$this->data['return']['address']['streetNumber'] = $streetNumber;
$this->data['return']['address']['name'] = $name;
$this->data['return']['address']['nameAddition'] = $nameAddition;
$this->data['return']['address']['email'] = $email;
$this->data['return']['address']['phone'] = $phone;
$this->data['return']['address']['contactPerson'] = $contactPerson;
$this->data['return']['address']['state'] = $state;
$this->data['return']['address']['dispatchingInformation'] = $dispatchingInformation;
$this->data['return']['address']['addressAddition'] = $addressAddition;
return $this;
}
public function setRecipientAddress(
string $name,
string $country,
string $postalCode,
string $city,
string $streetName,
string $streetNumber,
string $company = null,
string $nameAddition = null,
string $email = null,
string $phone = null,
string $contactPerson = null,
string $state = null,
string $dispatchingInformation = null,
array $addressAddition = []
): ShipmentOrderRequestBuilderInterface {
$this->data['recipient']['address']['name'] = $name;
$this->data['recipient']['address']['country'] = $country;
$this->data['recipient']['address']['postalCode'] = $postalCode;
$this->data['recipient']['address']['city'] = $city;
$this->data['recipient']['address']['streetName'] = $streetName;
$this->data['recipient']['address']['streetNumber'] = $streetNumber;
$this->data['recipient']['address']['company'] = $company;
$this->data['recipient']['address']['nameAddition'] = $nameAddition;
$this->data['recipient']['address']['email'] = $email;
$this->data['recipient']['address']['phone'] = $phone;
$this->data['recipient']['address']['contactPerson'] = $contactPerson;
$this->data['recipient']['address']['state'] = $state;
$this->data['recipient']['address']['dispatchingInformation'] = $dispatchingInformation;
$this->data['recipient']['address']['addressAddition'] = $addressAddition;
return $this;
}
public function setRecipientNotification(string $email): ShipmentOrderRequestBuilderInterface
{
$this->data['recipient']['notification'] = $email;
return $this;
}
public function setShipmentDetails(
string $productCode,
\DateTimeInterface $shipmentDate,
string $shipmentReference = null,
string $returnReference = null,
string $costCentre = null
): ShipmentOrderRequestBuilderInterface {
$timezone = new \DateTimeZone('Europe/Berlin');
if ($shipmentDate instanceof \DateTime) {
$shipmentDate = \DateTimeImmutable::createFromMutable($shipmentDate);
$shipmentDate = $shipmentDate->setTimezone($timezone);
} elseif ($shipmentDate instanceof \DateTimeImmutable) {
$shipmentDate = $shipmentDate->setTimezone($timezone);
}
$this->data['shipmentDetails']['product'] = $productCode;
$this->data['shipmentDetails']['date'] = $shipmentDate->format('Y-m-d');
$this->data['shipmentDetails']['shipmentReference'] = $shipmentReference;
$this->data['shipmentDetails']['returnReference'] = $returnReference;
$this->data['shipmentDetails']['costCentre'] = $costCentre;
return $this;
}
public function setPackageDetails(float $weight): ShipmentOrderRequestBuilderInterface
{
$this->data['packageDetails']['weight'] = $weight;
return $this;
}
public function setPackageDimensions(int $width, int $length, int $height): ShipmentOrderRequestBuilderInterface
{
$this->data['packageDetails']['dimensions']['width'] = $width;
$this->data['packageDetails']['dimensions']['length'] = $length;
$this->data['packageDetails']['dimensions']['height'] = $height;
return $this;
}
public function setInsuredValue(float $insuredValue): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['insuredValue'] = $insuredValue;
return $this;
}
public function setCodAmount(float $codAmount, bool $addFee = null): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['cod']['codAmount'] = $codAmount;
$this->data['services']['cod']['addCodFee'] = $addFee;
return $this;
}
public function setPackstation(
string $recipientName,
string $recipientPostNumber,
string $packstationNumber,
string $countryCode,
string $postalCode,
string $city,
string $state = null,
string $country = null
): ShipmentOrderRequestBuilderInterface {
$this->data['recipient']['address']['name'] = $recipientName;
$this->data['recipient']['packstation']['postNumber'] = $recipientPostNumber;
$this->data['recipient']['packstation']['number'] = $packstationNumber;
$this->data['recipient']['packstation']['countryCode'] = $countryCode;
$this->data['recipient']['packstation']['postalCode'] = $postalCode;
$this->data['recipient']['packstation']['city'] = $city;
$this->data['recipient']['packstation']['state'] = $state;
$this->data['recipient']['packstation']['country'] = $country;
return $this;
}
public function setPostfiliale(
string $recipientName,
string $postfilialNumber,
string $countryCode,
string $postalCode,
string $city,
string $postNumber = null,
string $state = null,
string $country = null
): ShipmentOrderRequestBuilderInterface {
$this->data['recipient']['address']['name'] = $recipientName;
$this->data['recipient']['postfiliale']['number'] = $postfilialNumber;
$this->data['recipient']['postfiliale']['countryCode'] = $countryCode;
$this->data['recipient']['postfiliale']['postalCode'] = $postalCode;
$this->data['recipient']['postfiliale']['city'] = $city;
$this->data['recipient']['postfiliale']['postNumber'] = $postNumber;
$this->data['recipient']['postfiliale']['state'] = $state;
$this->data['recipient']['postfiliale']['country'] = $country;
return $this;
}
public function setShipperReference(string $reference): ShipmentOrderRequestBuilderInterface
{
$this->data['shipper']['reference'] = $reference;
return $this;
}
public function setDayOfDelivery(string $cetDate): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['dayOfDelivery'] = $cetDate;
return $this;
}
public function setDeliveryTimeFrame(string $timeFrameType): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['deliveryTimeFrame'] = $timeFrameType;
return $this;
}
public function setPreferredDay(string $cetDate): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['preferredDay'] = $cetDate;
return $this;
}
public function setPreferredTime(string $timeFrameType): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['preferredTime'] = $timeFrameType;
return $this;
}
public function setPreferredLocation(string $location): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['preferredLocation'] = $location;
return $this;
}
public function setPreferredNeighbour(string $neighbour): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['preferredNeighbour'] = $neighbour;
return $this;
}
public function setIndividualSenderRequirement(string $handlingDetails): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['individualSenderRequirement'] = $handlingDetails;
return $this;
}
public function setPackagingReturn(): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['packagingReturn'] = true;
return $this;
}
public function setReturnImmediately(): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['returnImmediately'] = true;
return $this;
}
public function setNoticeOfNonDeliverability(): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['noticeOfNonDeliverability'] = true;
return $this;
}
public function setContainerHandlingType(string $handlingType): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['shipmentHandling'] = $handlingType;
return $this;
}
public function setShipmentEndorsementType(string $endorsementType): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['endorsement'] = $endorsementType;
return $this;
}
public function setVisualCheckOfAge(string $ageType): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['visualCheckOfAge'] = $ageType;
return $this;
}
public function setGoGreen(): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['goGreen'] = true;
return $this;
}
public function setPerishables(): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['perishables'] = true;
return $this;
}
public function setPersonally(): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['personally'] = true;
return $this;
}
public function setNoNeighbourDelivery(): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['noNeighbourDelivery'] = true;
return $this;
}
public function setNamedPersonOnly(): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['namedPersonOnly'] = true;
return $this;
}
public function setReturnReceipt(): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['returnReceipt'] = true;
return $this;
}
public function setPremium(): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['premium'] = true;
return $this;
}
public function setBulkyGoods(): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['bulkyGoods'] = true;
return $this;
}
public function setIdentCheck(
string $lastName,
string $firstName,
string $dateOfBirth,
string $minimumAge
): ShipmentOrderRequestBuilderInterface {
$this->data['services']['identCheck']['surname'] = $lastName;
$this->data['services']['identCheck']['givenName'] = $firstName;
$this->data['services']['identCheck']['dateOfBirth'] = $dateOfBirth;
$this->data['services']['identCheck']['minimumAge'] = $minimumAge;
return $this;
}
public function setParcelOutletRouting(string $email = null): ShipmentOrderRequestBuilderInterface
{
$this->data['services']['parcelOutletRouting']['active'] = true;
$this->data['services']['parcelOutletRouting']['details'] = $email;
return $this;
}
public function setCustomsDetails(
string $exportType,
string $placeOfCommital,
float $additionalFee,
string $exportTypeDescription = null,
string $termsOfTrade = null,
string $invoiceNumber = null,
string $permitNumber = null,
string $attestationNumber = null,
bool $electronicExportNotification = null,
string $sendersCustomsReference = null,
string $addresseesCustomsReference = null
): ShipmentOrderRequestBuilderInterface {
if (!isset($this->data['customsDetails']['items'])) {
$this->data['customsDetails']['items'] = [];
}
$this->data['customsDetails']['exportType'] = $exportType;
$this->data['customsDetails']['exportTypeDescription'] = $exportTypeDescription;
$this->data['customsDetails']['placeOfCommital'] = $placeOfCommital;
$this->data['customsDetails']['additionalFee'] = $additionalFee;
$this->data['customsDetails']['termsOfTrade'] = $termsOfTrade;
$this->data['customsDetails']['invoiceNumber'] = $invoiceNumber;
$this->data['customsDetails']['permitNumber'] = $permitNumber;
$this->data['customsDetails']['attestationNumber'] = $attestationNumber;
$this->data['customsDetails']['electronicExportNotification'] = $electronicExportNotification;
$this->data['customsDetails']['sendersCustomsReference'] = $sendersCustomsReference;
$this->data['customsDetails']['addresseesCustomsReference'] = $addresseesCustomsReference;
return $this;
}
public function addExportItem(
int $qty,
string $description,
float $value,
float $weight,
string $hsCode,
string $countryOfOrigin
): ShipmentOrderRequestBuilderInterface {
if (!isset($this->data['customsDetails']['items'])) {
$this->data['customsDetails']['items'] = [];
}
$this->data['customsDetails']['items'][] = [
'qty' => $qty,
'description' => $description,
'weight' => $weight,
'value' => $value,
'hsCode' => $hsCode,
'countryOfOrigin' => $countryOfOrigin,
];
return $this;
}
public function create(): ShipmentOrderType
{
$sequenceNumber = $this->data['sequenceNumber'] ?? '0';
if (!isset($this->data['shipper']['reference']) && !isset($this->data['shipper']['address'])) {
throw new RequestValidatorException("No sender included with shipment order $sequenceNumber.");
}
if (isset($this->data['shipper']['address'])) {
$shipperCountry = new CountryType($this->data['shipper']['address']['country']);
$shipperName = new NameType($this->data['shipper']['address']['company']);
$shipperName->setName2($this->data['shipper']['address']['name']);
$shipperName->setName3($this->data['shipper']['address']['nameAddition']);
$shipperCommunication = new CommunicationType();
$shipperCommunication->setContactPerson($this->data['shipper']['address']['contactPerson']);
$shipperCommunication->setEmail($this->data['shipper']['address']['email']);
$shipperCommunication->setPhone($this->data['shipper']['address']['phone']);
$shipperAddress = new NativeAddressType(
$this->data['shipper']['address']['streetName'],
$this->data['shipper']['address']['streetNumber'],
$this->data['shipper']['address']['postalCode'],
$this->data['shipper']['address']['city']
);
$shipperAddress->setAddressAddition($this->data['shipper']['address']['addressAddition']);
$shipperAddress->setDispatchingInformation($this->data['shipper']['address']['dispatchingInformation']);
$shipperAddress->setProvince($this->data['shipper']['address']['state']);
$shipperAddress->setOrigin($shipperCountry);
$shipper = new ShipperType($shipperName, $shipperAddress);
$shipper->setCommunication($shipperCommunication);
$shipperReference = null;
} else {
$shipper = null;
$shipperReference = $this->data['shipper']['reference'];
}
if (!isset($this->data['recipient'])) {
throw new RequestValidatorException("No recipient included with shipment order $sequenceNumber.");
}
$receiver = new ReceiverType($this->data['recipient']['address']['name']);
if (isset($this->data['recipient']['packstation'])) {
$packstationCountry = new CountryType($this->data['recipient']['packstation']['countryCode']);
$packstationCountry->setCountry($this->data['recipient']['packstation']['country']);
$packstationCountry->setState($this->data['recipient']['packstation']['state']);
$packstation = new PackStationType(
$this->data['recipient']['packstation']['postNumber'],
$this->data['recipient']['packstation']['number'],
$this->data['recipient']['packstation']['postalCode'],
$this->data['recipient']['packstation']['city']
);
$packstation->setProvince($this->data['recipient']['packstation']['state']);
$packstation->setOrigin($packstationCountry);
$receiver->setPackstation($packstation);
} elseif (isset($this->data['recipient']['postfiliale'])) {
if (
empty($this->data['recipient']['address']['email'])
&& empty($this->data['recipient']['postfiliale']['postNumber'])
) {
$msg = 'Either recipient email or post number must be set for Postfiliale delivery.';
throw new RequestValidatorException($msg);
}
$postfilialeCountry = new CountryType($this->data['recipient']['postfiliale']['countryCode']);
$postfilialeCountry->setCountry($this->data['recipient']['postfiliale']['country']);
$postfilialeCountry->setState($this->data['recipient']['postfiliale']['state']);
$postfiliale = new PostfilialeType(
$this->data['recipient']['postfiliale']['number'],
$this->data['recipient']['postfiliale']['postalCode'],
$this->data['recipient']['postfiliale']['city']
);
$postfiliale->setPostNumber($this->data['recipient']['postfiliale']['postNumber']);
$postfiliale->setOrigin($postfilialeCountry);
$receiver->setPostfiliale($postfiliale);
} elseif (isset($this->data['recipient']['address'])) {
$receiverCountry = new CountryType($this->data['recipient']['address']['country']);
$receiverAddress = new ReceiverNativeAddressType(
$this->data['recipient']['address']['streetName'],
$this->data['recipient']['address']['streetNumber'],
$this->data['recipient']['address']['postalCode'],
$this->data['recipient']['address']['city']
);
$receiverAddress->setName2($this->data['recipient']['address']['company']);
$receiverAddress->setName3($this->data['recipient']['address']['nameAddition']);
$receiverAddress->setAddressAddition($this->data['recipient']['address']['addressAddition']);
$receiverAddress->setDispatchingInformation($this->data['recipient']['address']['dispatchingInformation']);
$receiverAddress->setProvince($this->data['recipient']['address']['state']);
$receiverAddress->setOrigin($receiverCountry);
$receiver->setAddress($receiverAddress);
}
$receiverCommunication = new CommunicationType();
$receiverCommunication->setContactPerson($this->data['recipient']['address']['contactPerson'] ?? null);
$receiverCommunication->setEmail($this->data['recipient']['address']['email'] ?? null);
$receiverCommunication->setPhone($this->data['recipient']['address']['phone'] ?? null);
$receiver->setCommunication($receiverCommunication);
$shipmentItem = new ShipmentItemType($this->data['packageDetails']['weight']);
if (isset($this->data['packageDetails']['dimensions'])) {
$shipmentItem->setLengthInCM($this->data['packageDetails']['dimensions']['length']);
$shipmentItem->setWidthInCM($this->data['packageDetails']['dimensions']['width']);
$shipmentItem->setHeightInCM($this->data['packageDetails']['dimensions']['height']);
}
$shipmentDetails = new ShipmentDetailsTypeType(
$this->data['shipmentDetails']['product'],
$this->data['shipper']['billingNumber'],
$this->data['shipmentDetails']['date'],
$shipmentItem
);
$shipmentDetails->setCustomerReference($this->data['shipmentDetails']['shipmentReference']);
$shipmentDetails->setReturnShipmentAccountNumber($this->data['shipper']['returnBillingNumber']);
$shipmentDetails->setReturnShipmentReference($this->data['shipmentDetails']['returnReference']);
$shipmentDetails->setCostCentre($this->data['shipmentDetails']['costCentre']);
if (isset($this->data['services'])) {
$services = new ShipmentService();
if (isset($this->data['services']['dayOfDelivery'])) {
$config = new ServiceConfigurationDateOfDelivery(true, $this->data['services']['dayOfDelivery']);
$services->setDayOfDelivery($config);
}
if (isset($this->data['services']['deliveryTimeFrame'])) {
$config = new ServiceConfigurationDeliveryTimeFrame(true, $this->data['services']['deliveryTimeFrame']);
$services->setDeliveryTimeframe($config);
}
if (isset($this->data['services']['preferredDay'])) {
$config = new ServiceConfigurationDetails(true, $this->data['services']['preferredDay']);
$services->setPreferredDay($config);
}
if (isset($this->data['services']['preferredTime'])) {
$config = new ServiceConfigurationDeliveryTimeFrame(true, $this->data['services']['preferredTime']);
$services->setPreferredTime($config);
}
if (isset($this->data['services']['preferredLocation'])) {
$config = new ServiceConfigurationDetails(true, $this->data['services']['preferredLocation']);
$services->setPreferredLocation($config);
}
if (isset($this->data['services']['preferredNeighbour'])) {
$config = new ServiceConfigurationDetails(true, $this->data['services']['preferredNeighbour']);
$services->setPreferredNeighbour($config);
}
if (isset($this->data['services']['individualSenderRequirement'])) {
$config = new ServiceConfigurationISR(true, $this->data['services']['individualSenderRequirement']);
$services->setIndividualSenderRequirement($config);
}
if (isset($this->data['services']['packagingReturn'])) {
$config = new ServiceConfiguration(true);
$services->setPackagingReturn($config);
}
if (isset($this->data['services']['returnImmediately'])) {
$config = new ServiceConfiguration(true);
$services->setReturnImmediately($config);
}
if (isset($this->data['services']['noticeOfNonDeliverability'])) {
$config = new ServiceConfiguration(true);
$services->setNoticeOfNonDeliverability($config);
}
if (isset($this->data['services']['shipmentHandling'])) {
$config = new ServiceConfigurationShipmentHandling(true, $this->data['services']['shipmentHandling']);
$services->setShipmentHandling($config);
}
if (isset($this->data['services']['endorsement'])) {
$config = new ServiceConfigurationEndorsement(true, $this->data['services']['endorsement']);
$services->setEndorsement($config);
}
if (isset($this->data['services']['visualCheckOfAge'])) {
$config = new ServiceConfigurationVisualAgeCheck(true, $this->data['services']['visualCheckOfAge']);
$services->setVisualCheckOfAge($config);
}
if (isset($this->data['services']['goGreen'])) {
$config = new ServiceConfiguration(true);
$services->setGoGreen($config);
}
if (isset($this->data['services']['perishables'])) {
$config = new ServiceConfiguration(true);
$services->setPerishables($config);
}
if (isset($this->data['services']['personally'])) {
$config = new ServiceConfiguration(true);
$services->setPersonally($config);
}
if (isset($this->data['services']['noNeighbourDelivery'])) {
$config = new ServiceConfiguration(true);
$services->setNoNeighbourDelivery($config);
}
if (isset($this->data['services']['namedPersonOnly'])) {
$config = new ServiceConfiguration(true);
$services->setNamedPersonOnly($config);
}
if (isset($this->data['services']['returnReceipt'])) {
$config = new ServiceConfiguration(true);
$services->setReturnReceipt($config);
}
if (isset($this->data['services']['premium'])) {
$config = new ServiceConfiguration(true);
$services->setPremium($config);
}
if (isset($this->data['services']['cod']['codAmount'])) {
$config = new ServiceConfigurationCashOnDelivery(true, $this->data['services']['cod']['codAmount']);
$config->setAddFee($this->data['services']['cod']['addCodFee']);
$services->setCashOnDelivery($config);
}
if (isset($this->data['services']['insuredValue'])) {
$config = new ServiceConfigurationAdditionalInsurance(
true,
$this->data['services']['insuredValue']
);
$services->setAdditionalInsurance($config);
}
if (isset($this->data['services']['bulkyGoods'])) {
$config = new ServiceConfiguration(true);
$services->setBulkyGoods($config);
}
if (isset($this->data['services']['identCheck'])) {
$ident = new Ident(
$this->data['services']['identCheck']['surname'],
$this->data['services']['identCheck']['givenName'],
$this->data['services']['identCheck']['dateOfBirth'],
$this->data['services']['identCheck']['minimumAge']
);
$config = new ServiceConfigurationIC(true, $ident);
$services->setIdentCheck($config);
}
if (isset($this->data['services']['parcelOutletRouting'])) {
$config = new ServiceConfigurationDetailsOptional(true);
$config->setDetails($this->data['services']['parcelOutletRouting']['details']);
$services->setParcelOutletRouting($config);
}
$shipmentDetails->setService($services);
}
if (isset($this->data['recipient']['notification'])) {
$notification = new ShipmentNotificationType($this->data['recipient']['notification']);
$shipmentDetails->setNotification($notification);
}
if (isset($this->data['shipper']['bankData'])) {
$bankData = new BankType();
$bankData->setAccountOwner($this->data['shipper']['bankData']['owner'] ?? null);
$bankData->setBankName($this->data['shipper']['bankData']['bankName'] ?? null);
$bankData->setIban($this->data['shipper']['bankData']['iban'] ?? null);
$bankData->setBic($this->data['shipper']['bankData']['bic'] ?? null);
$bankData->setAccountReference($this->data['shipper']['bankData']['accountReference'] ?? null);
$bankData->setNote1($this->data['shipper']['bankData']['notes'][0] ?? null);
$bankData->setNote2($this->data['shipper']['bankData']['notes'][1] ?? null);
$shipmentDetails->setBankData($bankData);
}
$shipment = new Shipment($shipmentDetails, $receiver, $shipper);
$shipment->setShipperReference($shipperReference);
if (isset($this->data['return']['address'], $this->data['shipper']['returnBillingNumber'])) {
// only add return receiver if account number was provided
$returnCountry = new CountryType($this->data['return']['address']['country']);
$returnName = new NameType($this->data['return']['address']['company']);
$returnName->setName2($this->data['return']['address']['name']);
$returnName->setName3($this->data['return']['address']['nameAddition']);
$returnCommunication = new CommunicationType();
$returnCommunication->setContactPerson($this->data['return']['address']['contactPerson']);
$returnCommunication->setEmail($this->data['return']['address']['email']);
$returnCommunication->setPhone($this->data['return']['address']['phone']);
$returnAddress = new NativeAddressType(
$this->data['return']['address']['streetName'],
$this->data['return']['address']['streetNumber'],
$this->data['return']['address']['postalCode'],
$this->data['return']['address']['city']
);
$returnAddress->setAddressAddition($this->data['return']['address']['addressAddition']);
$returnAddress->setDispatchingInformation($this->data['return']['address']['dispatchingInformation']);
$returnAddress->setProvince($this->data['return']['address']['state']);
$returnAddress->setOrigin($returnCountry);
$returnReceiver = new ShipperType($returnName, $returnAddress);
$returnReceiver->setCommunication($returnCommunication);
$shipment->setReturnReceiver($returnReceiver);
}
if (isset($this->data['customsDetails'])) {
$exportDocument = new ExportDocumentType(
$this->data['customsDetails']['exportType'],
$this->data['customsDetails']['placeOfCommital'],
$this->data['customsDetails']['additionalFee']
);
$exportDocument->setExportTypeDescription($this->data['customsDetails']['exportTypeDescription']);
$exportDocument->setTermsOfTrade($this->data['customsDetails']['termsOfTrade']);
$exportDocument->setInvoiceNumber($this->data['customsDetails']['invoiceNumber']);
$exportDocument->setPermitNumber($this->data['customsDetails']['permitNumber']);
$exportDocument->setAttestationNumber($this->data['customsDetails']['attestationNumber']);
$exportDocument->setAddresseesCustomsReference($this->data['customsDetails']['addresseesCustomsReference']);
$exportDocument->setSendersCustomsReference($this->data['customsDetails']['sendersCustomsReference']);
if (isset($this->data['customsDetails']['electronicExportNotification'])) {
$notification = new ServiceConfiguration($this->data['customsDetails']['electronicExportNotification']);
$exportDocument->setWithElectronicExportNtfctn($notification);
}
$exportItems = [];
foreach ($this->data['customsDetails']['items'] as $itemData) {
$exportItems[] = new ExportDocPosition(
$itemData['description'],
$itemData['countryOfOrigin'],
$itemData['hsCode'],
$itemData['qty'],
$itemData['weight'],
$itemData['value']
);
}
$exportDocument->setExportDocPosition($exportItems);
$shipment->setExportDocument($exportDocument);
}
$shipmentOrder = new ShipmentOrderType($sequenceNumber, $shipment);
if (isset($this->data['printOnlyIfCodeable'])) {
$shipmentOrder->setPrintOnlyIfCodeable(new ServiceConfiguration(true));
}
$this->data = [];
return $shipmentOrder;
}
}
<file_sep>/test/RequestBuilder/ShipmentServiceRequestBuilderTest.php
<?php
/**
* See LICENSE.md for license details.
*/
declare(strict_types=1);
namespace Dhl\Sdk\Paket\Bcs\Test\RequestBuilder;
use Dhl\Sdk\Paket\Bcs\Api\Data\AuthenticationStorageInterface;
use Dhl\Sdk\Paket\Bcs\Exception\ServiceException;
use Dhl\Sdk\Paket\Bcs\RequestBuilder\ShipmentOrderRequestBuilder;
use Dhl\Sdk\Paket\Bcs\Serializer\ClassMap;
use Dhl\Sdk\Paket\Bcs\Soap\SoapServiceFactory;
use Dhl\Sdk\Paket\Bcs\Test\Expectation\RequestTypeExpectation as Expectation;
use Dhl\Sdk\Paket\Bcs\Test\Provider\AuthenticationStorageProvider;
use Dhl\Sdk\Paket\Bcs\Test\SoapClientFake;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
class ShipmentServiceRequestBuilderTest extends TestCase
{
/**
* @return mixed[]
* @throws \Exception
*/
public function simpleDataProvider(): array
{
$tsShip = time() + 60 * 60 * 24; // tomorrow;
$wsdl = __DIR__ . '/../Provider/_files/bcs-3.1.2/geschaeftskundenversand-api-3.1.2.wsdl';
$authStorage = AuthenticationStorageProvider::authSuccess();
$requestData = [
's0' => [
'sequenceNumber' => 's0',
'billingNumber' => '22222222220101',
'shipperCountry' => 'DE',
'shipperPostalCode' => '04229',
'shipperCity' => 'Leipzig',
'shipperStreet' => 'Nonnenstraße',
'shipperStreetNumber' => '11d',
'shipperCompany' => 'Netresearch GmbH & Co.KG',
'recipientCountry' => 'DE',
'recipientPostalCode' => '53113',
'recipientCity' => 'Bonn',
'recipientStreet' => 'Charles-de-Gaulle-Straße',
'recipientStreetNumber' => '20',
'recipientName' => '<NAME>',
'productCode' => 'V01PAK',
'shipDate' => new \DateTime(date('Y-m-d', $tsShip)),
'packageWeight' => 2.4,
]
];
// response does not matter really, just to make it not fail
$responseXml = \file_get_contents(__DIR__ . '/../Provider/_files/createshipment/singleShipmentSuccess.xml');
return [
'label request' => [$wsdl, $authStorage, $requestData, $responseXml],
];
}
/**
* @return mixed[]
* @throws \Exception
*/
public function complexDataProvider(): array
{
$tsShip = time() + 60 * 60 * 24; // tomorrow
$wsdl = __DIR__ . '/../Provider/_files/bcs-3.1.2/geschaeftskundenversand-api-3.1.2.wsdl';
$authStorage = AuthenticationStorageProvider::authSuccess();
$requestData = [
's0' => [
'sequenceNumber' => 's0',
'billingNumber' => '22222222220101',
'productCode' => 'V53PAK',
'shipDate' => new \DateTime(date('Y-m-d', $tsShip)),
'shipperCompany' => 'Netresearch GmbH & Co.KG',
'shipperCountry' => 'DE',
'shipperPostalCode' => '04229',
'shipperCity' => 'Leipzig',
'shipperStreet' => 'Nonnenstraße',
'shipperStreetNumber' => '11d',
'recipientCountry' => 'US',
'recipientPostalCode' => '89109',
'recipientCity' => 'Las Vegas',
'recipientStreet' => 'S Las Vegas Blvd',
'recipientStreetNumber' => '3131',
'recipientName' => '<NAME>',
'packageWeight' => 2.4,
'exportType' => 'OTHER',
'placeOfCommital' => 'Leipzig',
'additionalFee' => 7.99,
'exportTypeDescription' => 'Lekker Double Vla',
'termsOfTrade' => 'DDU',
'invoiceNumber' => '2121212121',
'permitNumber' => 'p3rm1t n0.',
'attestationNumber' => '4tt35t4t10n n0.',
'electronicExportNotification' => false,
'exportItem1Qty' => 2,
'exportItem1Desc' => 'Export Desc 1',
'exportItem1Weight' => 3.37,
'exportItem1Value' => 29.99,
'exportItem1HsCode' => ' 42031000',
'exportItem1Origin' => 'CN',
'exportItem2Qty' => 1,
'exportItem2Desc' => 'Export Desc 2',
'exportItem2Weight' => 2.22,
'exportItem2Value' => 35,
'exportItem2HsCode' => ' 62099010',
'exportItem2Origin' => 'US',
],
's1' => [
'printOnlyIfCodeable' => true,
'sequenceNumber' => 's1',
'billingNumber' => '22222222220101',
'returnBillingNumber' => '22222222220701',
'productCode' => 'V01PAK',
'shipDate' => new \DateTime(date('Y-m-d', $tsShip)),
'customerReference' => 'Customer Reference',
'returnReference' => 'Return Shipment Reference',
'costCentre' => 'Cost Centre XY',
'shipperCompany' => 'Netresearch GmbH & Co.KG',
'shipperCountry' => 'DE',
'shipperPostalCode' => '04229',
'shipperCity' => 'Leipzig',
'shipperStreet' => 'Nonnenstraße',
'shipperStreetNumber' => '11d',
'shipperName' => '<NAME>',
'shipperNameAddition' => 'Sr.',
'shipperEmail' => '<EMAIL>',
'shipperPhone' => '+49 341 1234567890',
'shipperContactPerson' => '<NAME>',
'shipperState' => 'SN',
'shipperDispatchingInformation' => 'dispatch soon',
'shipperAddressAddition1' => 'add something',
'shipperAddressAddition2' => 'add more',
'shipperBankOwner' => 'Owen Banks',
'shipperBankName' => 'Wall Institute',
'shipperBankIban' => 'DEX123',
'shipperBankBic' => 'DEX987',
'shipperBankReference' => 'Bank Reference',
'shipperBankNote1' => 'Bank Note 1',
'shipperBankNote2' => 'Bank Note 2',
'returnCompany' => 'Returns Center',
'returnCountry' => 'DE',
'returnPostalCode' => '22419',
'returnCity' => 'Hamburg',
'returnStreet' => 'Essener Straße',
'returnStreetNumber' => '89',
'returnName' => '<NAME>',
'returnNameAddition' => 'SXO',
'returnEmail' => '<EMAIL>',
'returnPhone' => '+49 40 1234567890',
'returnContactPerson' => '<NAME>',
'returnState' => 'HH',
'returnDispatchingInformation' => 'dispatch sooner',
'returnAddressAddition1' => 'add something return',
'returnAddressAddition2' => 'add more return',
'recipientName' => '<NAME>',
'recipientCountry' => 'DE',
'recipientPostalCode' => '53113',
'recipientCity' => 'Bonn',
'recipientStreet' => 'Sträßchensweg',
'recipientStreetNumber' => '2',
'recipientNameAddition' => 'XXO',
'recipientCompany' => 'Organisation AG',
'recipientEmail' => '<EMAIL>',
'recipientPhone' => '+49 228 911110',
'recipientContactPerson' => '<NAME>',
'recipientState' => 'NW',
'recipientDispatchingInformation' => 'dispatch tomorrow',
'recipientAddressAddition1' => 'add something ship',
'recipientAddressAddition2' => 'add more ship',
'recipientNotification' => '<EMAIL>',
'packageWeight' => 1.12,
'packageValue' => 24.99,
'codAmount' => 29.99,
'addCodFee' => false,
'packageLength' => 30,
'packageWidth' => 20,
'packageHeight' => 15,
'preferredDay' => date('Y-m-d', time() + 60 * 60 * 24 * 4),
'preferredTime' => '12001400',
'preferredLocation' => 'Mailbox',
'preferredNeighbour' => 'Mr. Smith',
'senderRequirement' => 'Do not kick.',
'visualCheckOfAge' => 'A18',
'goGreen' => true,
'perishables' => true,
'personally' => true,
'noNeighbourDelivery' => true,
'namedPersonOnly' => true,
'returnReceipt' => true,
'premium' => true,
'bulkyGoods' => true,
// 'identLastName' => 'Smith',
// 'identFirstName' => 'Sam',
// 'identDob' => '1970-01-01',
// 'identMinAge' => '21',
'parcelOutletRouting' => '<EMAIL>',
],
's2' => [
'sequenceNumber' => 's2',
'billingNumber' => '22222222220101',
'productCode' => 'V53PAK',
'shipDate' => new \DateTime(date('Y-m-d', $tsShip)),
'shipperReference' => 'Shipper Reference #123',
'packstationNumber' => '139',
'packstationPostalCode' => '53113',
'packstationCity' => 'Bonn',
'packstationRecipientName' => '<NAME>',
'packstationPostNumber' => '12345678',
'packstationState' => 'NRW',
'packstationCountryCode' => 'DE',
'packstationCountry' => 'Deutschland',
'packageWeight' => 4.5,
],
's3' => [
'sequenceNumber' => 's3',
'billingNumber' => '22222222220101',
'productCode' => 'V53PAK',
'shipDate' => new \DateTime(date('Y-m-d', $tsShip)),
'shipperReference' => 'Shipper Reference #123',
'postfilialRecipientName' => '<NAME>',
'postfilialNumber' => '502',
'postfilialPostNumber' => '12345678',
'postfilialPostalCode' => '53113',
'postfilialCity' => 'Bonn',
'postfilialCountry' => 'Deutschland',
'postfilialCountryCode' => 'DE',
'postfilialState' => 'NRW',
'packageWeight' => 1.2,
],
];
// response does not matter really, just to make it not fail
$responseXml = \file_get_contents(__DIR__ . '/../Provider/_files/createshipment/singleShipmentSuccess.xml');
return [
'label request' => [$wsdl, $authStorage, $requestData, $responseXml],
];
}
/**
* @test
* @dataProvider simpleDataProvider
*
* @param string $wsdl
* @param AuthenticationStorageInterface $authStorage
* @param mixed[][] $requestData
* @param string $responseXml
* @throws ServiceException
*/
public function createMinimalShipmentRequest(
string $wsdl,
AuthenticationStorageInterface $authStorage,
array $requestData,
string $responseXml
): void {
$logger = new NullLogger();
$clientOptions = [
'trace' => 1,
'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
'classmap' => ClassMap::get(),
'login' => $authStorage->getApplicationId(),
'password' => $authStorage->getApplicationToken(),
];
/** @var \SoapClient|MockObject $soapClient */
$soapClient = $this->getMockFromWsdl($wsdl, SoapClientFake::class, '', ['__doRequest'], true, $clientOptions);
$soapClient->expects(self::once())
->method('__doRequest')
->willReturn($responseXml);
$serviceFactory = new SoapServiceFactory($soapClient);
$service = $serviceFactory->createShipmentService($authStorage, $logger, true);
$shipmentOrders = [];
$requestBuilder = new ShipmentOrderRequestBuilder();
$requestBuilder->setSequenceNumber($requestData['s0']['sequenceNumber']);
$requestBuilder->setShipperAccount($requestData['s0']['billingNumber']);
$requestBuilder->setShipperAddress(
$requestData['s0']['shipperCompany'],
$requestData['s0']['shipperCountry'],
$requestData['s0']['shipperPostalCode'],
$requestData['s0']['shipperCity'],
$requestData['s0']['shipperStreet'],
$requestData['s0']['shipperStreetNumber']
);
$requestBuilder->setRecipientAddress(
$requestData['s0']['recipientName'],
$requestData['s0']['recipientCountry'],
$requestData['s0']['recipientPostalCode'],
$requestData['s0']['recipientCity'],
$requestData['s0']['recipientStreet'],
$requestData['s0']['recipientStreetNumber']
);
$requestBuilder->setShipmentDetails(
$requestData['s0']['productCode'],
$requestData['s0']['shipDate']
);
$requestBuilder->setPackageDetails(
$requestData['s0']['packageWeight']
);
$shipmentOrder = $requestBuilder->create();
$shipmentOrders[] = $shipmentOrder;
$service->createShipments($shipmentOrders);
$requestXml = $soapClient->__getLastRequest();
Expectation::assertRequestContentsAvailable($requestData, $requestXml);
}
/**
* @test
* @dataProvider complexDataProvider
*
* @param string $wsdl
* @param AuthenticationStorageInterface $authStorage
* @param mixed[][] $requestData
* @param string $responseXml
* @throws ServiceException
*/
public function createMultiShipmentRequest(
string $wsdl,
AuthenticationStorageInterface $authStorage,
array $requestData,
string $responseXml
): void {
$logger = new NullLogger();
$clientOptions = [
'trace' => 1,
'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
'classmap' => ClassMap::get(),
'login' => $authStorage->getApplicationId(),
'password' => $authStorage->getApplicationToken(),
'cache_wsdl' => WSDL_CACHE_NONE,
];
/** @var \SoapClient|MockObject $soapClient */
$soapClient = $this->getMockFromWsdl($wsdl, SoapClientFake::class, '', ['__doRequest'], true, $clientOptions);
$soapClient->expects(self::once())
->method('__doRequest')
->willReturn($responseXml);
$serviceFactory = new SoapServiceFactory($soapClient);
$service = $serviceFactory->createShipmentService($authStorage, $logger, true);
$shipmentOrders = [];
$requestBuilder = new ShipmentOrderRequestBuilder();
// shipment order 1
$requestBuilder->setSequenceNumber($requestData['s0']['sequenceNumber']);
$requestBuilder->setShipmentDetails(
$requestData['s0']['productCode'],
$requestData['s0']['shipDate']
);
$requestBuilder->setShipperAccount($requestData['s0']['billingNumber']);
$requestBuilder->setShipperAddress(
$requestData['s0']['shipperCompany'],
$requestData['s0']['shipperCountry'],
$requestData['s0']['shipperPostalCode'],
$requestData['s0']['shipperCity'],
$requestData['s0']['shipperStreet'],
$requestData['s0']['shipperStreetNumber']
);
$requestBuilder->setRecipientAddress(
$requestData['s0']['recipientName'],
$requestData['s0']['recipientCountry'],
$requestData['s0']['recipientPostalCode'],
$requestData['s0']['recipientCity'],
$requestData['s0']['recipientStreet'],
$requestData['s0']['recipientStreetNumber']
);
$requestBuilder->setPackageDetails(
$requestData['s0']['packageWeight']
);
$requestBuilder->setCustomsDetails(
$requestData['s0']['exportType'],
$requestData['s0']['placeOfCommital'],
$requestData['s0']['additionalFee'],
$requestData['s0']['exportTypeDescription'],
$requestData['s0']['termsOfTrade'],
$requestData['s0']['invoiceNumber'],
$requestData['s0']['permitNumber'],
$requestData['s0']['attestationNumber'],
$requestData['s0']['electronicExportNotification']
);
$requestBuilder->addExportItem(
$requestData['s0']['exportItem1Qty'],
$requestData['s0']['exportItem1Desc'],
$requestData['s0']['exportItem1Value'],
$requestData['s0']['exportItem1Weight'],
$requestData['s0']['exportItem1HsCode'],
$requestData['s0']['exportItem1Origin']
);
$requestBuilder->addExportItem(
$requestData['s0']['exportItem2Qty'],
$requestData['s0']['exportItem2Desc'],
$requestData['s0']['exportItem2Value'],
$requestData['s0']['exportItem2Weight'],
$requestData['s0']['exportItem2HsCode'],
$requestData['s0']['exportItem2Origin']
);
$shipmentOrder = $requestBuilder->create();
$shipmentOrders[] = $shipmentOrder;
// shipment order 2
if ($requestData['s1']['printOnlyIfCodeable'] ?? false) {
$requestBuilder->setPrintOnlyIfCodeable();
}
$requestBuilder->setSequenceNumber($requestData['s1']['sequenceNumber']);
$requestBuilder->setShipmentDetails(
$requestData['s1']['productCode'],
$requestData['s1']['shipDate'],
$requestData['s1']['customerReference'],
$requestData['s1']['returnReference'],
$requestData['s1']['costCentre']
);
$requestBuilder->setShipperAccount(
$requestData['s1']['billingNumber'],
$requestData['s1']['returnBillingNumber']
);
$requestBuilder->setShipperAddress(
$requestData['s1']['shipperCompany'],
$requestData['s1']['shipperCountry'],
$requestData['s1']['shipperPostalCode'],
$requestData['s1']['shipperCity'],
$requestData['s1']['shipperStreet'],
$requestData['s1']['shipperStreetNumber'],
$requestData['s1']['shipperName'],
$requestData['s1']['shipperNameAddition'],
$requestData['s1']['shipperEmail'],
$requestData['s1']['shipperPhone'],
$requestData['s1']['shipperContactPerson'],
$requestData['s1']['shipperState'],
$requestData['s1']['shipperDispatchingInformation'],
[
$requestData['s1']['shipperAddressAddition1'],
$requestData['s1']['shipperAddressAddition2'],
]
);
$requestBuilder->setShipperBankData(
$requestData['s1']['shipperBankOwner'],
$requestData['s1']['shipperBankName'],
$requestData['s1']['shipperBankIban'],
$requestData['s1']['shipperBankBic'],
$requestData['s1']['shipperBankReference'],
[
$requestData['s1']['shipperBankNote1'],
$requestData['s1']['shipperBankNote2'],
]
);
$requestBuilder->setReturnAddress(
$requestData['s1']['returnCompany'],
$requestData['s1']['returnCountry'],
$requestData['s1']['returnPostalCode'],
$requestData['s1']['returnCity'],
$requestData['s1']['returnStreet'],
$requestData['s1']['returnStreetNumber'],
$requestData['s1']['returnName'],
$requestData['s1']['returnNameAddition'],
$requestData['s1']['returnEmail'],
$requestData['s1']['returnPhone'],
$requestData['s1']['returnContactPerson'],
$requestData['s1']['returnState'],
$requestData['s1']['returnDispatchingInformation'],
[
$requestData['s1']['returnAddressAddition1'],
$requestData['s1']['returnAddressAddition2'],
]
);
$requestBuilder->setRecipientAddress(
$requestData['s1']['recipientName'],
$requestData['s1']['recipientCountry'],
$requestData['s1']['recipientPostalCode'],
$requestData['s1']['recipientCity'],
$requestData['s1']['recipientStreet'],
$requestData['s1']['recipientStreetNumber'],
$requestData['s1']['recipientCompany'],
$requestData['s1']['recipientNameAddition'],
$requestData['s1']['recipientEmail'],
$requestData['s1']['recipientPhone'],
$requestData['s1']['recipientContactPerson'],
$requestData['s1']['recipientState'],
$requestData['s1']['recipientDispatchingInformation'],
[
$requestData['s1']['recipientAddressAddition1'],
$requestData['s1']['recipientAddressAddition2'],
]
);
$requestBuilder->setRecipientNotification($requestData['s1']['recipientNotification']);
$requestBuilder->setPackageDetails($requestData['s1']['packageWeight']);
$requestBuilder->setInsuredValue($requestData['s1']['packageValue']);
$requestBuilder->setCodAmount(
$requestData['s1']['codAmount'],
$requestData['s1']['addCodFee']
);
$requestBuilder->setPackageDimensions(
$requestData['s1']['packageWidth'],
$requestData['s1']['packageLength'],
$requestData['s1']['packageHeight']
);
$requestBuilder->setPreferredDay($requestData['s1']['preferredDay']);
$requestBuilder->setPreferredTime($requestData['s1']['preferredTime']);
$requestBuilder->setPreferredLocation($requestData['s1']['preferredLocation']);
$requestBuilder->setPreferredNeighbour($requestData['s1']['preferredNeighbour']);
$requestBuilder->setIndividualSenderRequirement($requestData['s1']['senderRequirement']);
$requestBuilder->setVisualCheckOfAge($requestData['s1']['visualCheckOfAge']);
$requestBuilder->setGoGreen();
$requestBuilder->setPerishables();
$requestBuilder->setPersonally();
$requestBuilder->setNoNeighbourDelivery();
$requestBuilder->setNamedPersonOnly();
$requestBuilder->setReturnReceipt();
$requestBuilder->setPremium();
$requestBuilder->setBulkyGoods();
// $requestBuilder->setIdentCheck(
// $requestData['s1']['identLastName'],
// $requestData['s1']['identFirstName'],
// $requestData['s1']['identDob'],
// $requestData['s1']['identMinAge']
// );
$requestBuilder->setParcelOutletRouting($requestData['s1']['parcelOutletRouting']);
$shipmentOrder = $requestBuilder->create();
$shipmentOrders[] = $shipmentOrder;
// shipment order 3
$requestBuilder->setSequenceNumber($requestData['s2']['sequenceNumber']);
$requestBuilder->setShipmentDetails(
$requestData['s2']['productCode'],
$requestData['s2']['shipDate']
);
$requestBuilder->setShipperAccount($requestData['s2']['billingNumber']);
$requestBuilder->setShipperReference($requestData['s2']['shipperReference']);
$requestBuilder->setPackstation(
$requestData['s2']['packstationRecipientName'],
$requestData['s2']['packstationPostNumber'],
$requestData['s2']['packstationNumber'],
$requestData['s2']['packstationCountryCode'],
$requestData['s2']['packstationPostalCode'],
$requestData['s2']['packstationCity'],
$requestData['s2']['packstationState'],
$requestData['s2']['packstationCountry']
);
$requestBuilder->setPackageDetails($requestData['s2']['packageWeight']);
$shipmentOrder = $requestBuilder->create();
$shipmentOrders[] = $shipmentOrder;
// shipment order 3
$requestBuilder->setSequenceNumber($requestData['s3']['sequenceNumber']);
$requestBuilder->setShipmentDetails(
$requestData['s3']['productCode'],
$requestData['s3']['shipDate']
);
$requestBuilder->setShipperAccount($requestData['s3']['billingNumber']);
$requestBuilder->setShipperReference($requestData['s3']['shipperReference']);
$requestBuilder->setPostfiliale(
$requestData['s3']['postfilialRecipientName'],
$requestData['s3']['postfilialNumber'],
$requestData['s3']['postfilialCountryCode'],
$requestData['s3']['postfilialPostalCode'],
$requestData['s3']['postfilialCity'],
$requestData['s3']['postfilialPostNumber'],
$requestData['s3']['postfilialState'],
$requestData['s3']['postfilialCountry']
);
$requestBuilder->setPackageDetails($requestData['s3']['packageWeight']);
$shipmentOrder = $requestBuilder->create();
$shipmentOrders[] = $shipmentOrder;
$service->createShipments($shipmentOrders);
$requestXml = $soapClient->__getLastRequest();
Expectation::assertRequestContentsAvailable($requestData, $requestXml);
}
}
<file_sep>/test/Service/ShipmentServiceCreateTest.php
<?php
/**
* See LICENSE.md for license details.
*/
declare(strict_types=1);
namespace Dhl\Sdk\Paket\Bcs\Test\Service;
use Dhl\Sdk\Paket\Bcs\Api\Data\AuthenticationStorageInterface;
use Dhl\Sdk\Paket\Bcs\Exception\AuthenticationException;
use Dhl\Sdk\Paket\Bcs\Exception\DetailedServiceException;
use Dhl\Sdk\Paket\Bcs\Exception\RequestValidatorException;
use Dhl\Sdk\Paket\Bcs\Exception\ServiceException;
use Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType\ShipmentOrderType;
use Dhl\Sdk\Paket\Bcs\Serializer\ClassMap;
use Dhl\Sdk\Paket\Bcs\Soap\SoapServiceFactory;
use Dhl\Sdk\Paket\Bcs\Test\Expectation\CommunicationExpectation;
use Dhl\Sdk\Paket\Bcs\Test\Expectation\ShipmentServiceTestExpectation as Expectation;
use Dhl\Sdk\Paket\Bcs\Test\Provider\ShipmentServiceTestProvider;
use Dhl\Sdk\Paket\Bcs\Test\SoapClientFake;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\Test\TestLogger;
class ShipmentServiceCreateTest extends TestCase
{
/**
* @param AuthenticationStorageInterface $authStorage
* @return mixed[]
*/
private function getSoapClientOptions(AuthenticationStorageInterface $authStorage): array
{
$clientOptions = [
'trace' => 1,
'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
'classmap' => ClassMap::get(),
'login' => $authStorage->getApplicationId(),
'password' => $authStorage->getApplicationToken(),
];
return $clientOptions;
}
/**
* @return mixed[]
* @throws RequestValidatorException
*/
public function successDataProvider(): array
{
return ShipmentServiceTestProvider::createShipmentsSuccess();
}
/**
* @return mixed[]
* @throws RequestValidatorException
*/
public function partialSuccessDataProvider(): array
{
return ShipmentServiceTestProvider::createShipmentsPartialSuccess();
}
/**
* @return mixed[]
* @throws RequestValidatorException
*/
public function validationWarningDataProvider(): array
{
return ShipmentServiceTestProvider::createShipmentsValidationWarning();
}
/**
* @return mixed[]
* @throws RequestValidatorException
*/
public function validationErrorDataProvider(): array
{
return ShipmentServiceTestProvider::createShipmentsError();
}
/**
* @return mixed[]
* @throws RequestValidatorException
*/
public function serverErrorDataProvider(): array
{
return ShipmentServiceTestProvider::createServerError();
}
/**
* @return mixed[]
* @throws RequestValidatorException
*/
public function serverFaultDataProvider(): array
{
return ShipmentServiceTestProvider::createServerFault();
}
/**
* Test shipment success case (all labels available, no issues).
*
* @test
* @dataProvider successDataProvider
*
* @param string $wsdl
* @param AuthenticationStorageInterface $authStorage
* @param ShipmentOrderType[] $shipmentOrders
* @param string $responseXml
*
* @throws AuthenticationException
* @throws ServiceException
*/
public function createShipmentsSuccess(
string $wsdl,
AuthenticationStorageInterface $authStorage,
array $shipmentOrders,
string $responseXml
): void {
$logger = new TestLogger();
$clientOptions = $this->getSoapClientOptions($authStorage);
/** @var \SoapClient|MockObject $soapClient */
$soapClient = $this->getMockFromWsdl($wsdl, SoapClientFake::class, '', ['__doRequest'], true, $clientOptions);
$soapClient->expects(self::once())
->method('__doRequest')
->willReturn($responseXml);
$serviceFactory = new SoapServiceFactory($soapClient);
$service = $serviceFactory->createShipmentService($authStorage, $logger, true);
$result = $service->createShipments($shipmentOrders);
// assert that all shipments were created
Expectation::assertAllShipmentsBooked(
$soapClient->__getLastRequest(),
$soapClient->__getLastResponse(),
$result
);
// assert successful communication gets logged.
CommunicationExpectation::assertCommunicationLogged(
$soapClient->__getLastRequest(),
$soapClient->__getLastResponse(),
$logger
);
}
/**
* Test shipment partial success case (some labels available).
*
* @test
* @dataProvider partialSuccessDataProvider
*
* @param string $wsdl
* @param AuthenticationStorageInterface $authStorage
* @param ShipmentOrderType[] $shipmentOrders
* @param string $responseXml
*
* @throws AuthenticationException
* @throws ServiceException
*/
public function createShipmentsPartialSuccess(
string $wsdl,
AuthenticationStorageInterface $authStorage,
array $shipmentOrders,
string $responseXml
): void {
$logger = new TestLogger();
$clientOptions = $this->getSoapClientOptions($authStorage);
/** @var \SoapClient|MockObject $soapClient */
$soapClient = $this->getMockFromWsdl($wsdl, SoapClientFake::class, '', ['__doRequest'], true, $clientOptions);
$soapClient->expects(self::once())
->method('__doRequest')
->willReturn($responseXml);
$serviceFactory = new SoapServiceFactory($soapClient);
$service = $serviceFactory->createShipmentService($authStorage, $logger, true);
$result = $service->createShipments($shipmentOrders);
// assert that shipments were created but not all of them
Expectation::assertSomeShipmentsBooked(
$soapClient->__getLastRequest(),
$soapClient->__getLastResponse(),
$result
);
// assert hard validation errors are logged.
CommunicationExpectation::assertErrorsLogged(
$soapClient->__getLastRequest(),
$soapClient->__getLastResponse(),
$logger
);
}
/**
* Test shipment success case (all labels available, warnings exist).
*
* @test
* @dataProvider validationWarningDataProvider
*
* @param string $wsdl
* @param AuthenticationStorageInterface $authStorage
* @param ShipmentOrderType[] $shipmentOrders
* @param string $responseXml
*
* @throws AuthenticationException
* @throws ServiceException
*/
public function createShipmentsValidationWarning(
string $wsdl,
AuthenticationStorageInterface $authStorage,
array $shipmentOrders,
string $responseXml
): void {
$logger = new TestLogger();
$clientOptions = $this->getSoapClientOptions($authStorage);
/** @var \SoapClient|MockObject $soapClient */
$soapClient = $this->getMockFromWsdl($wsdl, SoapClientFake::class, '', ['__doRequest'], true, $clientOptions);
$soapClient->expects(self::once())
->method('__doRequest')
->willReturn($responseXml);
$serviceFactory = new SoapServiceFactory($soapClient);
$service = $serviceFactory->createShipmentService($authStorage, $logger, true);
$result = $service->createShipments($shipmentOrders);
Expectation::assertAllShipmentsBooked(
$soapClient->__getLastRequest(),
$soapClient->__getLastResponse(),
$result
);
// assert weak validation errors are logged.
CommunicationExpectation::assertWarningsLogged(
$soapClient->__getLastRequest(),
$soapClient->__getLastResponse(),
$logger
);
}
/**
* Test shipment validation failure case (no labels available, client exception thrown).
*
* @test
* @dataProvider validationErrorDataProvider
*
* @param string $wsdl
* @param AuthenticationStorageInterface $authStorage
* @param ShipmentOrderType[] $shipmentOrders
* @param string $responseXml
*
* @throws ServiceException
*/
public function createShipmentsValidationError(
string $wsdl,
AuthenticationStorageInterface $authStorage,
array $shipmentOrders,
string $responseXml
): void {
$this->expectException(DetailedServiceException::class);
$this->expectExceptionCode(1101);
$this->expectExceptionMessage('Hard validation error occured.');
$logger = new TestLogger();
$clientOptions = $this->getSoapClientOptions($authStorage);
/** @var \SoapClient|MockObject $soapClient */
$soapClient = $this->getMockFromWsdl($wsdl, SoapClientFake::class, '', ['__doRequest'], true, $clientOptions);
$soapClient->expects(self::once())
->method('__doRequest')
->willReturn($responseXml);
$serviceFactory = new SoapServiceFactory($soapClient);
$service = $serviceFactory->createShipmentService($authStorage, $logger, true);
try {
$service->createShipments($shipmentOrders);
} catch (DetailedServiceException $exception) {
// assert hard validation errors are logged.
CommunicationExpectation::assertErrorsLogged(
$soapClient->__getLastRequest(),
$soapClient->__getLastResponse(),
$logger
);
throw $exception;
}
}
/**
* Test shipment error case (HTTP 200, 500 "service not available" or 1000 "general error" status in response).
*
* @test
* @dataProvider serverErrorDataProvider
*
* @param string $wsdl
* @param AuthenticationStorageInterface $authStorage
* @param ShipmentOrderType[] $shipmentOrders
* @param string $responseXml
*/
public function createShipmentsError(
string $wsdl,
AuthenticationStorageInterface $authStorage,
array $shipmentOrders,
string $responseXml
): void {
self::markTestIncomplete('No such response observed/recorded yet.');
}
/**
* Test shipment error case (HTTP 500, soap fault).
*
* @test
* @dataProvider serverFaultDataProvider
*
* @param string $wsdl
* @param AuthenticationStorageInterface $authStorage
* @param ShipmentOrderType[] $shipmentOrders
* @param \SoapFault $soapFault
*
* @throws ServiceException
*/
public function createShipmentsServerError(
string $wsdl,
AuthenticationStorageInterface $authStorage,
array $shipmentOrders,
\SoapFault $soapFault
): void {
$this->expectException(ServiceException::class);
$this->expectExceptionCode(0);
$this->expectExceptionMessage('INVALID_CONFIGURATION');
$logger = new TestLogger();
$clientOptions = $this->getSoapClientOptions($authStorage);
/** @var \SoapClient|MockObject $soapClient */
$soapClient = $this->getMockFromWsdl($wsdl, SoapClientFake::class, '', ['__doRequest'], true, $clientOptions);
$soapClient->expects(self::once())
->method('__doRequest')
->willThrowException($soapFault);
$serviceFactory = new SoapServiceFactory($soapClient);
$service = $serviceFactory->createShipmentService($authStorage, $logger);
try {
$service->createShipments($shipmentOrders);
} catch (ServiceException $exception) {
// assert errors are logged.
CommunicationExpectation::assertErrorsLogged(
$soapClient->__getLastRequest(),
$soapFault->getMessage(),
$logger
);
throw $exception;
}
}
}
<file_sep>/src/Model/CreateShipment/RequestType/ServiceConfigurationShipmentHandling.php
<?php
/**
* See LICENSE.md for license details.
*/
declare(strict_types=1);
namespace Dhl\Sdk\Paket\Bcs\Model\CreateShipment\RequestType;
class ServiceConfigurationShipmentHandling
{
/**
* Indicates, if the option is on/off.
*
* @var int $active "0" or "1"
*/
protected $active;
/**
* Type of shipment handling. There are the following types are allowed:
* - a: Remove content, return box
* - b: Remove content, pick up and dispose cardboard packaging
* - c: Handover parcel/box to customer – no disposal of cardboard/box
* - d: Remove bag from of cooling unit and handover to customer
* - e: Remove content, apply return label und seal box, return box
*
* @var string $type
*/
protected $type;
public function __construct(bool $active, string $type)
{
$this->active = (int) $active;
$this->type = $type;
}
}
|
c38e8db7a4ec12dc6ab3a6b9eb33093903569413
|
[
"Markdown",
"PHP"
] | 19
|
PHP
|
dgro/dhl-sdk-api-bcs
|
d247b7768628daba71fda29445998f232d2fb812
|
5499122139e55a39c51f354b706957eb6cf3b8f5
|
refs/heads/master
|
<repo_name>byu-cs329/lab0-constant-folding<file_sep>/README.md
# Objective
The objective of this lab is to implement [constant folding](https://en.wikipedia.org/wiki/Constant_folding) for a subset of Java and use black-box testing to test its functional correctness. The implementation will use the [org.eclipse.jdt.core.dom](https://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fjdt%2Fcore%2Fdom%2Fpackage-summary.html) to represent and manipulate Java. The [constant folding](https://en.wikipedia.org/wiki/Constant_folding) itself should be accomplished with a specialized [ASTVisitor](https://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fjdt%2Fcore%2Fdom%2Fpackage-summary.html). The program will take two arguments as input:
1. the Java file on which to do constant folding; and
2. an output file to write the result.
The program should only apply to a limited subset of Java defined below. It should fold any and all constants as much as possible. It should not implement **constant propagation** which is the topic of the next lab for the course.
The part of the program that does the actual folding should be specified and tested via black-box testing. A significant part of the grade is dedicated to the test framework and the tests (more so than the actual implementation), so be sure to spend time accordingly. In the end, the test framework and supporting tests are more interesting than the actual constant folding in regards to the grade.
# Reading
The [DOM-Visitor lecture](https://bitbucket.org/byucs329/byu-cs-329-lecture-notes/src/master/DOM-Visitor/) is a must read before starting this lab. You will also need the [DOMViewer](https://github.com/byu-cs329/DOMViewer.git) installed and working to view the AST for any given input file. Alternatively, there is an [ASTView plugin](https://www.eclipse.org/jdt/ui/astview/) for Eclipse available on the Eclipse Market Place that works really well. There is something similar for IntelliJ too.
# Constant Folding
[Constant folding](https://en.wikipedia.org/wiki/Constant_folding) is the process where constant expressions are reduced by the compiler before generating code.
Examples:
* `x = 3 + 7` becomes `x = 10`
* `x = 3 + (7 + 4)` becomes `x = 14`
* `x = y + (7 + 4)` becomes `x = y + 11`
Not that constant folding does not include replacing variables that reduce to constants.
```java
x = 3 + 7;
y = x;
```
Constant folding for the above gives:
```java
x = 10;
y = x;
```
Constant folding may also apply to Boolean values.
```java
if (3 > 4) {
x = 5;
} else {
x = 10;
}
```
Should reduce to
```java
if (false) {
x = 5;
} else {
x = 10;
}
```
Which should reduce to
```java
x = 10;
```
In the above example, the constant folding removed **dead code** that was not reachable on any input.
For this lab, you don't need to remove the braces -- it is more difficult that is necessary. So the above should look like:
```java
{ x = 10;
}
```
# Advandced Folding (Optional)
Be aware that [short circuit evaluation](https://en.wikipedia.org/wiki/Short-circuit_evaluation) comes into play for constant folding. For example ```a.f() && false``` cannot be reducted to ```false``` because it is not known if the call to ```a.f()``` side effects on the state of the class, so it's call must be preseved. That said, ```a.y() && false && b.y()``` can be reduced to ```a.y() && false``` since the call to ```b.y()``` will never take place. As another example, consider ```a.y() || b.y() || true || c.y()```. Here the call to ```c.y()``` will never take place so the expression reduces to ```a.y() || b.y() || true```.
It is also possible to remove literals that have no effect on the expression. For example ```a.y() && true``` reduces to ```a.y()```. Similarly, ```a.y() || false || b.y()``` reduces to ```a.y() || b.y()```. Always be aware of [short circuit evaluation](https://en.wikipedia.org/wiki/Short-circuit_evaluation) in constant folding since method calls can side-effect on the state of the class, those calls must be presered as shown in the examples above.
Here is another example of short circuit evaluation that requires some careful thought.
```java
if (a.f() || true) {
x = 10;
}
```
This code could reduce to
```java
a.f();
if (true) {
x = 10;
}
```
Which would then reduce to
```java
a.f();
x = 10;
```
That said however, the following example cannot reduce in the same way because if the call to ```a.y()``` returns true, then ```b.y()``` is never called.
```java
if (a.f() || b.y() || true) {
x = 10;
}
```
It could reduce to
```java
if (a.f() || b.y()) {
;
}
if (true) {
x = 10;
}
```
Which would then reduce to
```java
if (!a.f()) {
b.y();
}
x = 10;
```
If you implement short-circuiting of two parameters with appropriate tests, notify the instructor to receive extra credit.
# Java Subset
This course is only going to consider a very narrow [subset of Java](https://bitbucket.org/byucs329/byu-cs-329-lecture-notes/src/master/java-subset/java-subset.md) as considering all of Java is way beyond the scope and intent of this course (e.g., it would be a nightmare). The [subset of Java](https://bitbucket.org/byucs329/byu-cs-329-lecture-notes/src/master/java-subset/java-subset.md) effectively reduces to single-file programs with all the interesting language features (e.g., generics, lambdas, anonymous classes, etc.) removed. **As a general rule**, if something seems unusually hard or has an unusually large number of cases to deal with, then it probably is excluded from the [subset of Java](https://bitbucket.org/byucs329/byu-cs-329-lecture-notes/src/master/java-subset/java-subset.md) or should be excuded, so stop and ask before spending a lot of time on it.
# Required Folding
Constant folding is **only required** for the following types of `ASTNode` expressions and statements:
* `ParenthesizedExpression` that contain only a literal of any type (given as part of the base code)
* Logical not `PrefixExpression`, `!`, when applied to `BooleanLiteral`
* Numeric `InfixExpression` for `+` if and only if all the operands are of type `NumberLiteral` including the extended operands
* Binary relational `InfixExpression`, `<`, if and only if both operands are of type `NumberLiteral`
* `IfStatement` if and only if the predicate is a `BooleanLiteral`
Assume that any `NumberLiteral` instance is of type `int` always. This set of expressions and statements are much more narrow than what is allowed in the Java subset. That is OK. Folding is only applied to the above program features. Also, folding should be applied iteratively until no furter reduction is possible.
# Lab Requirements
For each required application of constant folding:
0. Write a specification
1. Write black-box tests that coincide with the specification
2. Implement the folding in its own class that implements `Folding`
3. Add the new folding technique to `ConstantFolding.fold`
After each required application of constant folding is implemented, then write some system tests for `ConstantFolding.fold` that check the iterative application of all the ways to folding to reduce an input to an expected value.
As a note, there should not be much more than 25 to 30 tests total (e.g., around 4 to 5 tests for each type of folding and one system test for `ConstantFolding.fold`) as black-box test is very functional. Excess tests will degrade your score for the lab.
## Suggested order of attack:
Approach the lab in small steps starting with the easiest type starting with `PrefixExpression` as it is similar to `ParenthesizedExpressions` that is given as part of the lab distribution.
0. Read and understand everything related to `ParenthesizedExpression`
1. Write the specification for `PrefixExpression`
2. Create the tests from the specification
3. Implement the actual visitor.
Repeat for the other ways to fold. It is **important** that the **implementation is created after the specification and tests.** Specification. Then tests. And finally the implementation.
# POM Notes
The `mvn test` uses the Surefire plugin to generat console reports and additional reports in `./target/surefire-reports`. The console report extension is configured to use the `@DisplayName` for the tests and generally works well except in the case of tests in `@Nested`, tests in `@ParameterizedTest`, or `@DynamicTest`. For these, the console report extension is less than ideal as it does not use the `@DisplayName` all the time and groups `@ParameterisedTest` and `@DynamicTest` into a single line report.
The `./target/surefire-reports/TEST-<fully qualified classname>.xml` file is the detailed report of all the tests in the class that uses the correct `@DisplayName`. The file is very useful for isolating failed parameterized or dynamic tests. The regular text files in the directory only show what Maven shows. That said, many IDEs present a tree view of the tests with additional information for `@Nested`, `@ParameterizedTest`, `@DynamicTest`, `@RepeatTest`, etc. This tree view can be generated with the JUnit `ConsoleLauncher`.
The POM in the project is setup to run the [JUnit Platform Console Standalone](https://mvnrepository.com/artifact/org.junit.platform/junit-platform-console-standalone) on the `mvn exec:java` goal in the build phase. The POM sets the arguments to scan for tests, `--scan-classpath`, with `./target/test-classes` being added to the class path. The equivalent command line (and the default defined in the POM):
```
mvn exec:java -Dexec.mainClass=org.junit.platform.console.ConsoleLauncher -Dexec.args="--class-path=./target/test-classes --scan-classpath"
```
The above is what is run with just the command `mvn exec:java`.
The `ConsoleLauncher` is able to run specific tests and classes, so it is possible to change the `--scan-path` argument, either in the POM file or by typing in the above on the command line. [Section 4.3.1](https://junit.org/junit5/docs/current/user-guide/#running-tests-console-launcher) of the JUnit 5 users lists all the options.
# What to turn in?
Create a pull request when the lab is done. Submit to Canvas the URL of the repository.
# Rubric
* **(40 points)** for each required constant folding not including `ParenthesizedExpressions`
* **(20 points)** for the system test framework for `ConstantFolding.fold`
* **(20 points)** for best practice (e.g., good names, no errors, no warnings, documented code, well grouped commits, appropriate commit messages, etc.)
Breakdown of **(40 points)** for each required folding technique
* **(15 points)** for the specification
* **(15 points)** for the tests
* **(10 points)** for the implementation
# Notes
* What would a boundary value analysis look like?
* Watch carefully what imports are added by the IDE in the testing code to be sure it is importing from the Jupiter API as behavior changes in the IDE if it grabs from the wrong JUnit API and annotations will not work as expected.
* Be sure the logger imports use the `slf4j` interface.
<file_sep>/src/main/java/edu/byu/cs329/constantfolding/Folding.java
package edu.byu.cs329.constantfolding;
import org.eclipse.jdt.core.dom.ASTNode;
public interface Folding {
public boolean fold(final ASTNode root);
}
<file_sep>/src/test/java/edu/byu/cs329/constantfolding/MoreUtils.java
package edu.byu.cs329.constantfolding;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.net.URI;
import org.eclipse.jdt.core.dom.ASTMatcher;
import org.eclipse.jdt.core.dom.ASTNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MoreUtils extends Utils {
static Logger log = LoggerFactory.getLogger(Utils.class);
public static ASTNode getASTNodeFor(final Object t, String name){
URI uri = Utils.getUri(t, name);
assertNotNull(uri);
ASTNode root = Utils.getCompilationUnit(uri);
return root;
}
public static void assertDidFold(final Object t, String rootName, String expectedName, Folding folderUnderTest) {
ASTNode root = getASTNodeFor(t, rootName);
Boolean didFold = folderUnderTest.fold(root);
log.debug(root.toString());
assertTrue(didFold);
ASTNode expected = getASTNodeFor(t, expectedName);
assertTrue(expected.subtreeMatch(new ASTMatcher(), root));
}
public static void assertDidNotFold(final Object t, String rootName, String expectedName, Folding folderUnderTest) {
ASTNode root = getASTNodeFor(t, rootName);
assertFalse(folderUnderTest.fold(root));
ASTNode expected = getASTNodeFor(t, expectedName);
assertTrue(expected.subtreeMatch(new ASTMatcher(), root));
}
}
<file_sep>/src/test/resources/parenthesizedLiterals/should_NotFoldAnything_when_ThereAreNoParenthesizedLiterals.java
package parenthesizedLiterals;
public class should_NotFoldAnything_when_ThereAreNoParenthesizedLiterals {
public int name(final int y) {
final int x = 3 + (y);
final boolean b = true;
final Integer i = null;
final char c = 'c';
final String s = new String("Hello");
final boolean t = (Name.class == Name.class);
return x;
}
}
|
e86c1699790791c3cc9235fe6ca25f4396c3c8e1
|
[
"Markdown",
"Java"
] | 4
|
Markdown
|
byu-cs329/lab0-constant-folding
|
d159dd76f4516375e651fb868910a2f9ae85db94
|
0b6f763dc601b3498eca436db749c2c46c769f6f
|
refs/heads/master
|
<file_sep>//
// ContentView.swift
// SwiftUi13
//
// Created by <NAME> on 19/07/20.
// Copyright © 2020 AccessDenied. All rights reserved.
//
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView{
HomePage().navigationBarTitle("Instagram with SwiftUI")
.navigationBarItems(leading:
Image(systemName: "camera").resizable().frame(width: 25, height: 25)
,trailing: Image(systemName: "paperplane").resizable().frame(width: 25, height: 25)
)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct HomePage:View{
var body: some View{
ScrollView(.vertical, showsIndicators: false){
VStack{
ScrollView(.horizontal,showsIndicators: false){
HStack{
ForEach(0..<20){ i in
VStack{
Image("user").resizable().frame(width: 80, height: 80).clipShape(Circle()).overlay(Circle().stroke(lineWidth: 3).fill(Color.red)).padding(5)
Text("User")
}
}
}
}
}
ForEach(0..<20){ i in
Feed()
}
}
}
}
struct Feed:View{
var body: some View{
VStack{
HStack{
Image("user").resizable().frame(width: 40, height: 40).clipShape(Circle())
Text("User")
Spacer()
Button(action: {
}) {
Image(systemName: "ellipsis").frame(width: 25, height: 25).foregroundColor(.white)
}
}.padding(8)
Image("user").resizable().frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height / 2).padding([.top,.bottom], 10)
HStack{
Image(systemName: "heart").resizable().frame(width: 25, height: 25)
Image(systemName: "message").resizable().frame(width: 25, height: 25)
Image(systemName: "paperplane").resizable().frame(width: 25, height: 25)
Spacer()
Image(systemName: "bookmark").resizable().frame(width: 25, height: 25)
}.padding(8)
HStack{
VStack(alignment:.leading){
Text("24,599 likes")
Text("view all comments").foregroundColor(.gray)
Text("18 min ago").foregroundColor(.gray)
}.padding(8)
Spacer()
}
}
}
}
|
2f635021f4b54df969d8a7ce3d444c753a10931b
|
[
"Swift"
] | 1
|
Swift
|
rohitsainier/SwiftUi13
|
f641e92e22bca45a1fb045a7c016d88332c37e2a
|
29ab47a8520e2ddf53d03147f725fec0397738f1
|
refs/heads/master
|
<file_sep>#include <stdio.h>
#define SIZE 26 /* 26 letters in the alphabet */
#define OFFSET_UPPER 65
#define OFFSET_LOWER 97
/* print histogram of frequencies of different characters */
main()
{
int c, i, j, k, max;
int arr[SIZE];
for (i = 0; i < SIZE; ++i)
{
arr[i] = 0;
}
while ((c = getchar()) != EOF)
{
/* it's a lowercase */
if ((c - OFFSET_UPPER) >= SIZE && (c - OFFSET_LOWER) < SIZE)
{
++arr[c - OFFSET_LOWER];
}
/* it's an uppercase */
else if ((c - OFFSET_UPPER) < SIZE)
{
++arr[c - OFFSET_UPPER];
}
}
/* find max */
max = arr[0];
for (i = 1; i < SIZE; ++i)
{
if (max < arr[i])
{
max = arr[i];
}
}
/* print histogram */
printf("\n\n");
k = max;
for (i = 0; i < max; ++i, --k)
{
for (j = 0; j < SIZE; ++j)
{
if (arr[j] >= k)
{
printf("*");
}
else
{
printf(" ");
}
}
printf("\n");
}
for (i = 0; i < SIZE; ++i)
{
printf("-");
}
printf("\n");
for (i = 0; i < SIZE; ++i)
{
printf("%c", i + OFFSET_UPPER);
}
printf("\n\tCHARACTERS\n");
}
<file_sep># C
Programs written in C for practice from the book C Programming Language
|
04031c3d74539fae0a3f2891448274b5f1592162
|
[
"Markdown",
"C"
] | 2
|
C
|
bsolis19/C
|
f3fcb9082276de0eca9b9f2f8caff5372047cf84
|
57139095678fec476ef5c605c5cbf11924312ecc
|
refs/heads/master
|
<file_sep>import csv
import numpy as np
import matplotlib.pyplot as plt
# figure out what data we want to use
categories = [] # these ones are the column headers in the csv
installs = [] # this is the installs rrow
ratings = [] # this is the ratings row
with open('data/googeplaystore.csv') as csvfile:
reader = csv.reader(csvfile)
line_count = 0
for row in reader:
# move the page column headers out of the actual data to get a clean dataset
if line_count is 0: # this will be text, not data
print('pushing categories in seperate array')
categories.append(row) # push the text into this array
line_count += 1 # increment the line count for the next loop
else:
# grab the ratings and push them into the ratings array
ratingsData = row[2]
ratingsData = ratingsData.replace("NaN", "0")
ratings.append(float(ratingsData)) # int will turn a string (piece of text) into a number
# print('pushing ratings data into the ratings array')
installData = row[5]
installData = installData.replace("," , "") # get rid of commas
# get rid of the trailng "+"
installs.append(np.char.strip(installData, "+"))
line_count += 1
# get some values we can work with
# how many ae 4+
# how many are below 2?
# how many are in the middle
np_ratings = np.array(ratings) # turn a plain python list into a Numpy array
popular_apps = np_ratings > 4
print("popular apps:", len(np_ratings[popular_apps]))
percent_popular = len(np_ratings[popular_apps]) / len(np_ratings) * 100
print(percent_popular)
unpopular_apps = np_ratings < 4
print("popular apps:", len(np_ratings[unpopular_apps]))
percent_unpopular = int(len(np_ratings[unpopular_apps]) / len(np_ratings) * 100)
print(percent_unpopular)
kinda_popular = 100 - (percent_popular + percent_unpopular)
print(kinda_popular)
# doa a visualization with our shiny new data
labels = "Sucks", "Meh", "Love it!!!"
sizes = [percent_unpopular, kinda_popular, percent_popular]
colors = ['yellowgreen', 'lightgreen', 'lightskyblue']
explode = (0.1, 0.2, 0.15)
plt.pie(sizes, explode=explode, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140)
plt.axis('equal')
plt.legend(labels, loc=1)
plt.title("Do we love us some apps?")
plt.xlabel("User Ratings - App Installs (10,000+ apps")
plt.show()
print('processed', line_count, 'lines of data')
print(categories)
print('first row of data:', installs[0])
print('last row of data:', installs[-1])
|
11844447d0bec312f826d8dba2ab01532e85dd27
|
[
"Python"
] | 1
|
Python
|
junior231/dataviz
|
ec11f14a64af7e4e0d6d6952da64043a0ee20ea5
|
d8e20032a0e6886606c76687e8ab64cbfb12c049
|
refs/heads/master
|
<repo_name>tetsu1026/ogiri-app<file_sep>/app/models/post.rb
class Post < ApplicationRecord
belongs_to :user
has_many :comments, dependent: :destroy
has_one_attached :image
has_many :likes, dependent: :destroy
has_many :post_likes, dependent: :destroy
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to :genre
validates :sentence, presence: true
validates :genre_id, numericality: { other_than: 1, message: 'Select'}
with_options length: {maximum:50} do
validates :sentence, presence: true
validates :title, presence: true, unless: :was_attached?
end
def was_attached?
self.image.attached?
end
end<file_sep>/spec/models/user_spec.rb
require 'rails_helper'
RSpec.describe User, type: :model do
before do
@user = FactoryBot.build(:user)
sleep 0.1
end
describe "新規登録" do
context "登録できる時" do
it "プロフィール写真以外の情報が入力されていれば登録できる" do
expect(@user).to be_valid
end
it "プロフィール写真がなくても登録できる" do
@user.image = nil
expect(@user).to be_valid
end
end
context "登録できない時" do
it "emailが空だと登録できない" do
@user.email = nil
@user.valid?
expect(@user.errors.full_messages).to include("Email can't be blank")
end
it "emailには@がないと登録できない" do
@user.email = "test<PASSWORD>"
@user.valid?
expect(@user.errors.full_messages).to include("Email is invalid")
end
it "同じemailは登録できない" do
@user.save
another_user = FactoryBot.build(:user, email: @user.email)
another_user.valid?
expect(another_user.errors.full_messages).to include("Email has already been taken")
end
it "passwordの入力がないと登録できない" do
@user.password = nil
@user.password_confirmation = nil
@user.valid?
expect(@user.errors.full_messages).to include("Password can't be blank")
end
it "パスワードは、確認用を含めて2回入力しないと登録できない" do
@user.password_confirmation = ""
@user.valid?
expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password")
end
it "パスワードは英数混合でなくては登録できない" do
@user.password = "<PASSWORD>"
@user.password_confirmation = "<PASSWORD>"
@user.valid?
expect(@user.errors.full_messages).to include("Password には半角の英字数字の両方を含めて設定してください")
end
it "パスワードは英語だけでは登録できない" do
@user.password = "<PASSWORD>"
@user.password_confirmation = "<PASSWORD>"
@user.valid?
expect(@user.errors.full_messages).to include("Password には半角の英字数字の両方を含めて設定してください")
end
it "パスワードは6文字以下では登録できない" do
@user.password = "<PASSWORD>"
@user.password_confirmation = "<PASSWORD>"
@user.valid?
expect(@user.errors.full_messages).to include("Password is too short (minimum is 6 characters)")
end
it "パスワードは全角では登録できない" do
@user.password = "<PASSWORD>"
@user.password_confirmation = "<PASSWORD>"
@user.valid?
expect(@user.errors.full_messages).to include("Password には半角の英字数字の両方を含めて設定してください")
end
it "パスワードは、2つ一致してないと登録できない" do
@user.password_confirmation = "<PASSWORD>"
@user.valid?
expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password")
end
it "nicknameがないと登録できない" do
@user.nickname = nil
@user.valid?
expect(@user.errors.full_messages).to include("Nickname can't be blank")
end
it "profileがないと登録できない" do
@user.profile = ""
@user.valid?
expect(@user.errors.full_messages).to include("Profile can't be blank")
end
end
end
end
<file_sep>/spec/factories/posts.rb
FactoryBot.define do
factory :post do
title {Faker::Lorem.sentence}
sentence {"testtest"}
genre_id {2}
association :user
end
after(:build) do |post|
post.image.attach(io: File.open('public/images/test_image.png'), filename: 'test_image.png')
end
end
<file_sep>/spec/system/users_spec.rb
require 'rails_helper'
RSpec.describe "Users", type: :system do
before do
@user = FactoryBot.build(:user)
end
context "新規登録" do
describe "新規登録できる時" do
it "正しい情報が登録できれば新規登録ができてトップページに遷移する" do
# トップページに移動する
visit root_path
# トップページに新規登録へ遷移のボタンがあることを確認する
expect(page).to have_content("新規登録")
# 新規登録ページへ移動する
visit new_user_registration_path
# ユーザー情報を入力する
fill_in "メールアドレス", with: @user.email
fill_in "パスワード(半角英数混合6文字以上)", with: <PASSWORD>, match: :first
fill_in "パスワード再入力", with: @user.password_<PASSWORD>, match: :first
image_path = Rails.root.join("public/images/test_image.png")
attach_file("user[image]", image_path, make_visible: true)
fill_in "nickname", with: @user.nickname
fill_in "プロフィール(自分を一言で表現してください)", with: @user.profile
# 新規登録ボタンをクリックするとユーザーカウントが1上がる
expect{
find('input[name="commit"]').click
}.to change { User.count }.by(1)
# トップページへ遷移したことを確認する
expect(current_path).to eq(root_path)
# トップページに新規登録ボタンやログインボタンがないことを確認する
expect(page).to have_no_content("ログイン")
expect(page).to have_no_content("新規登録")
# トップページにログアウトと出題するボタンがあることを確認する
expect(page).to have_content("ログアウト")
expect(page).to have_content("出題する")
end
end
context "新規登録できない時" do
it "誤った情報では登録できないで新規登録ページに戻ってくる" do
# トップページに移動する
visit root_path
# トップページに新規登録ボタンがあることを確認する
expect(page).to have_content("新規登録")
# 新規登録ページに移動する
visit new_user_registration_path
# ユーザー情報を登録する
fill_in "メールアドレス", with: ""
fill_in "パスワード(半角英数混合6文字以上)", with: "", match: :first
fill_in "パスワード再入力", with: "", match: :first
fill_in "nickname", with: ""
fill_in "プロフィール(自分を一言で表現してください)", with: ""
# 新規登録ボタンをクリックするとユーザーカウントが上がらないことを確認する
expect{
find('input[name="commit"]').click
}.to change { User.count }.by(0)
# 新規登録ページに戻されることを確認する
expect(current_path).to eq('/users')
end
end
end
end
RSpec.describe 'ログイン', type: :system do
before do
@user = FactoryBot.create(:user)
end
context "ログインができる時" do
it '保存されているユーザーの情報と合致すればログインができる' do
# トップページに移動する
visit root_path
# トップページにログインボタンがあることを確認する
expect(page).to have_content('ログイン')
# ログインページに遷移する
visit new_user_session_path
# 正しい情報を入力する
fill_in "メールアドレス", with: @user.email
fill_in "パスワード(半角英数混合6文字以上)", with: <PASSWORD>
# ログインボタンを押す
find('input[name="commit"]').click
# トップページに遷移することを確認する
expect(current_path).to eq(root_path)
# トップページに、ログアウトボタンと出題するボタンがあることを確認する
expect(page).to have_content("ログアウト")
expect(page).to have_content("出題する")
# トップページに新規登録ボタンやログインボタンがないことを確認する
expect(page).to have_no_content("ログイン")
expect(page).to have_no_content("新規登録")
expect(page).to have_no_content("正解のない問題たちとは?")
end
end
context "ログインできない時" do
it '保存されているユーザーの情報と合致しないとログインができない' do
# トップページに移動する
visit root_path
# トップページにログインボタンがあることを確認する
expect(page).to have_content('ログイン')
# ログインページに遷移する
visit new_user_session_path
# ユーザー情報を入力する
fill_in "メールアドレス", with: ""
fill_in "パスワード(半角英数混合6文字以上)", with: ""
# ログインボタンを押す
find('input[name="commit"]').click
# ログインページへ戻されることを確認する
expect(current_path).to eq("/users/sign_in")
end
end
end
RSpec.describe "編集する", type: :system do
before do
@user1 = FactoryBot.create(:user)
@user2 = FactoryBot.create(:user)
end
context "ユーザー情報が編集できる時" do
it "ログインしたユーザーは自分のプロフィールを編集できる" do
# ユーザー1でログインする
visit new_user_session_path
fill_in "メールアドレス", with: @user1.email
fill_in "パスワード(半角英数混合6文字以上)", with: @user1.password
find('input[name="commit"]').click
expect(current_path).to eq(root_path)
# マイページに遷移する
visit user_path(@user1)
# マイページに編集するボタンがあることを確認する
expect(page).to have_content("ユーザー情報編集")
# 編集ページに遷移する
visit edit_user_registration_path(@user1)
# すでにユーザー情報が入っているかを確認する
expect(
find('#user_email').value
).to eq"#{@user1.email}"
expect(
find('#user_nickname').value
).to eq(@user1.nickname)
expect(
find('#user_profile').value
).to eq(@user1.profile)
# プロフィール内容を変更する
fill_in "user[email]", with: "#{@user1.email}test"
fill_in "user[nickname]", with: "#{@user1.nickname}+編集したニックネーム"
fill_in "user[profile]", with: "#{@user1.profile}+編集したプロフィール"
# 編集してもユーザーカウントが上がらないことを確認する
expect {
find('input[name="commit"]').click
}.to change {User.count}.by(0)
# マイページに遷移したことを確認する
visit user_path(@user1)
# 先ほどの変更内容があるか確認する
expect(page).to have_content("#{@user1.nickname}+編集したニックネーム")
expect(page).to have_content("#{@user1.profile}+編集したプロフィール")
end
end
context "ユーザー情報が編集できない時" do
it "ログインしたユーザーは自分以外のマイページは編集できない" do
# ユーザー1でログインする
visit new_user_session_path
fill_in "メールアドレス", with: @user1.email
fill_in "パスワード(半角英数混合6文字以上)", with: @user1.password
find('input[name="commit"]').click
expect(current_path).to eq(root_path)
# ユーザー2のマイページに遷移する
visit user_path(@user2)
# ユーザー2のマイページに編集ボタンがないことを確認する
expect(page).to have_no_content("ユーザー情報編集")
end
end
end
RSpec.describe "退会する", type: :system do
before do
@user1 = FactoryBot.create(:user)
end
context "ユーザーが退会できる時" do
it "ログインしたユーザーは本人だった場合退会ができる" do
# ログインする
visit new_user_session_path
fill_in "メールアドレス", with: @user1.email
fill_in "パスワード(半角英数混合6文字以上)", with: @user<PASSWORD>
find('input[name="commit"]').click
expect(current_path).to eq(root_path)
# マイページに遷移する
visit user_path(@user1)
# マイページに編集するボタンがあることを確認する
expect(page).to have_content("ユーザー情報編集")
# 編集ページに遷移する
visit edit_user_registration_path(@user1)
# 編集ページに退会ボタンがあることを確認する
expect(page).to have_content("退会する")
# 退会するとレコードカウントが1つ下がることを確認する
expect{
find_link("退会する", href: user_path(@user1)).click
}.to change {User.count}.by(-1)
end
end
end<file_sep>/app/models/genre.rb
class Genre < ActiveHash::Base
self.data =[
{ id: 1, name: '--' },
{ id: 2, name: '文章問題' },
{ id: 3, name: '写真にタイトルをつけてください' },
]
end<file_sep>/spec/system/posts_spec.rb
require 'rails_helper'
RSpec.describe "出題する", type: :system do
before do
@user = FactoryBot.create(:user)
@post = FactoryBot.create(:post)
end
context "お題が投稿できる時" do
it "ログインしたユーザーは投稿できる" do
# ログインする
visit new_user_session_path
fill_in "メールアドレス", with: @user.email
fill_in "パスワード(半角英数混合6文字以上)", with: @user.password
find('input[name="commit"]').click
expect(current_path).to eq(root_path)
# トップページに出題するボタンがあることを確認する
expect(page).to have_content("出題する")
# お題投稿ページに遷移する
visit new_post_path
# フォームを入力する
select '文章問題', from: 'post[genre_id]'
fill_in 'お題', with: @post.title
fill_in '出題者の回答', with: @post.sentence
# 出題するボタンをクリックするとPostモデルのカウントが1つ上がる
expect {
find('input[name="commit"]') .click
}.to change { Post.count }.by(1)
# トップページへ遷移したことを確認する
visit root_path
# トップページに先ほどのお題が投稿されているか確認する
expect(page).to have_content(@post.title)
end
end
context "お題投稿ができない時" do
it "ログインしていないと出題ページに遷移できない" do
# トップページに遷移する
visit root_path
# 出題ページへのリンクがない
expect(page).to have_no_content("出題する")
end
end
end
RSpec.describe "編集する", type: :system do
before do
@post1 = FactoryBot.create(:post)
@post2 = FactoryBot.create(:post)
end
context "お題が編集できる時" do
it "ログインしたユーザーは自分が投稿したお題を編集できる" do
# 投稿1のユーザーでログインする
visit new_user_session_path
fill_in "メールアドレス", with: @post1.<EMAIL>
fill_in "パスワード(半角英数混合6文字以上)", with: <PASSWORD>
find('input[name="commit"]').click
expect(current_path).to eq(root_path)
# 投稿1のお題詳細ページに遷移する
visit post_path(@post1)
# 投稿1に編集ボタンがあることを確認する
expect(page).to have_content("編集する")
# 編集ページに遷移する
visit edit_post_path(@post1)
# すでに投稿済みの内容がフォームに入っているか確認する
expect(
find('#post_genre_id').value
).to eq"#{@post1.genre_id}"
expect(
find('#post_title').value
).to eq(@post1.title)
expect(
find('#post_sentence').value
).to eq(@post1.sentence)
# 投稿内容を編集する
fill_in "お題", with: "#{@post1.title}+編集したタイトル"
fill_in "出題者の回答", with: "#{@post1.sentence}+編集した投稿者の回答"
# 編集してもPostカウントが変わらないことを確認
expect {
find('input[name="commit"]').click
}.to change { Post.count }.by(0)
# お題詳細ページに遷移したことを確認
visit post_path(@post1)
# 先ほどの変更内容があるか確認
expect(page).to have_content("#{@post1.title}+編集したタイトル")
expect(page).to have_content("#{@post1.sentence}+編集した投稿者の回答")
end
end
context "お題編集できない時" do
it "ログインしたユーザーは自分の投稿以外は編集できない" do
# 投稿1のユーザーでログインする
visit new_user_session_path
fill_in "メールアドレス", with: @post1.user.email
fill_in "パスワード(半角英数混合6文字以上)", with: <PASSWORD>
find('input[name="commit"]').click
expect(current_path).to eq(root_path)
# 投稿2のユーザーの詳細ページに遷移する
visit post_path(@post2)
# 投稿2に編集ページがないことを確認する
expect(page).to have_no_content("編集する")
end
end
end
RSpec.describe "削除する", type: :system do
before do
@post1 = FactoryBot.create(:post)
@post2 = FactoryBot.create(:post)
end
context "お題の削除ができる時" do
it "ログインしたユーザーは自ら投稿したお題を削除できる" do
# お題1のユーザーでログインする
visit new_user_session_path
fill_in "メールアドレス", with: @post1.user.email
fill_in "パスワード(半角英数混合6文字以上)", with: <PASSWORD>
find('input[name="commit"]').click
expect(current_path).to eq(root_path)
# お題1の詳細ページに遷移する
visit post_path(@post1)
# 削除ボタンがあることを確認する
expect(page).to have_content("削除する")
# お題を削除するとレコードカウントが1つ下がることを確認する
expect{
find_link("削除する", href: post_path(@post1)).click
}.to change {Post.count}.by(-1)
# 削除するとトップページに遷移する
visit root_path
# トップページにお題1がないことを確認する
expect(page).to have_no_content("#{@post1.title}")
end
end
context "お題の削除ができない時" do
it "ログインしたユーザーは自分の投稿以外削除できない" do
# お題1のユーザーでログインする
visit new_user_session_path
fill_in "メールアドレス", with: @post1.user.email
fill_in "パスワード(半角英数混合6文字以上)", with: <PASSWORD>.user.password
find('input[name="commit"]').click
expect(current_path).to eq(root_path)
# お題2の詳細ページに遷移する
visit post_path(@post2)
# 削除ボタンがないことを確認する
expect(page).to have_no_content("削除する")
end
end
end
RSpec.describe "詳細表示", type: :system do
before do
@post = FactoryBot.create(:post)
end
it "ログインしたユーザーは詳細ページに遷移した時回答投稿が表示される" do
# ログインする
visit new_user_session_path
fill_in "メールアドレス", with: @post.user.email
fill_in "パスワード(半角英数混合6文字以上)", with: @post.user.password
find('input[name="commit"]').click
expect(current_path).to eq(root_path)
# お題詳細ページに遷移する
visit post_path(@post)
# 詳細にお題と投稿者の回答があるかを確認する
expect(page).to have_content("#{@post.title}")
expect(page).to have_content("#{@post.sentence}")
# お題詳細に回答formが存在する
expect(page).to have_selector 'form'
end
it "ログインしていない状態でお題詳細ページに遷移できるものの回答投稿formが存在しない" do
# 詳細ページに遷移する
visit post_path(@post)
# 詳細にお題と投稿者の回答があるかを確認する
expect(page).to have_content("#{@post.title}")
expect(page).to have_content("#{@post.sentence}")
# formが存在しないことを確認する
expect(page).to have_no_selector 'form'
# 「回答するにはログインが必要です」が表示されていることを確認する
expect(page).to have_content("回答するにはログインが必要です")
end
end
<file_sep>/app/controllers/comments_controller.rb
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = Comment.new(comment_params)
if @comment.save
redirect_to post_path(@comment.post)
else
@post = @comment.post
@comments = @post.comments
@comment_like = @post.comments.includes(:likes).sort {|a,b| b.likes.size <=> a.likes.size}
render "posts/show"
end
end
private
def comment_params
params.require(:comment).permit(:message).merge(user_id: current_user.id, post_id: params[:post_id])
end
end
<file_sep>/spec/models/post_spec.rb
require 'rails_helper'
RSpec.describe Post, type: :model do
before do
@post = FactoryBot.build(:post)
end
describe "お題の投稿" do
context "投稿できる時" do
it "ジャンル、お題、投稿者の回答があれば投稿できる" do
@post.image = nil
expect(@post).to be_valid
end
it "ジャンル、画像、投稿者の回答があれば投稿できる" do
@post.title = nil
expect(@post).to be_valid
end
end
context "投稿できない時" do
it "画像とお題どちらかがないと投稿できない" do
@post.image = nil
@post.title = nil
@post.valid?
expect(@post.errors.full_messages).to include("Title can't be blank")
end
it "ジャンルの選択がされていないと投稿できない" do
@post.genre_id = 1
@post.valid?
expect(@post.errors.full_messages).to include("Genre Select")
end
it "お題作成者の回答がないと投稿できない" do
@post.sentence = nil
@post.valid?
expect(@post.errors.full_messages).to include("Sentence can't be blank")
end
end
end
end
<file_sep>/README.md
# 📘 正解のない問題たち
# 🌎 アプリケーション概要
このアプリケーションは、大喜利を通じてユーザーの「発想力」を鍛えること
を目的としたアプリケーションである。
「お題の投稿」「お題に回答」「お題や回答の判定」この3つの機能を使い、「発想力」や
「表現力」を鍛えたり、自分の好きな方法で大喜利に参加できる。
## 💫 「お題の投稿」
お題は、「文章問題」か「写真にタイトルをつける」が選択する。
これは、回答するだけでなく0から1を作ることで「発想力」を鍛える。
文章問題を考えるのが苦手な方のために、写真を投稿するだけでいいカテゴリーも作成。
## 💫 「投稿されているお題から好きなものを選び回答できる」
お題に回答することで、「発想力」や「表現力」鍛える。
また、他のユーザーの回答も見ることができるため色々な考え方に触れて「発想の視野」を
広げるのも目的の1つ。
## 💫 「お題、回答の判定機能」
お題や回答を他者から評価されることにより、自分の発想がどのくらい
他者の心を動かしたか、数値で把握する。
この結果は、ランキング表に表示されるため、競争ができてモチベーションを高めることもできる。
また、お題や回答で参加するのが苦手な方も審査員としてアプリに参加できる。
# 💻 デプロイ後のURL
(https://ogiri-app-1026.herokuapp.com/)
# 👨 テスト用アカウント
ユーザー名:test
email:<EMAIL>
password:<PASSWORD>
# 🗺 DEMO
## 🌐 ログイン前のトップページ
[](https://gyazo.com/2314d12a0e3bfdc0c78f30e16007b87b)
## 🌐 アプリケーション概要ページ
[](https://gyazo.com/8cac6cee3415ac5884a1247c91a6cb2f)
## 🌐 ログイン済みトップページ
[](https://gyazo.com/3a775b2ed4c03077f8897b7a75d474de)
## 🌐 新規登録ページ
[](https://gyazo.com/9e0f1daf37eccb530416e40f62095173)
## 🌐 ログインページ
[](https://gyazo.com/f411e22e32cc25c3a581fbd155e8e6b6)
## 🌐 出題ページ
[](https://gyazo.com/9c8644e1f9ae811f455d16f1cf1ae516)
## 🌐 トップページ/投稿されたお題一覧
[](https://gyazo.com/b5598a34e7d41357837f5ad80030dd86)
## 🌐 トップページ/お題のランキング表
[](https://gyazo.com/7a12db53565b2aec1f9615bd01410191)
## 🌐 お題回答ページ上部/お題タイトル、投稿者回答、回答ランキング表
[](https://gyazo.com/1b535e54545907c1faf77e16ce52ac4b)
## 🌐 お題回答ページ下部/回答一覧
[](https://gyazo.com/65ccdc1a56d179db9b217d666c34afbe)
## 🌐 マイページ上部/ユーザー情報
[](https://gyazo.com/9f0ed95260871d7b2a0393c56d19a8ed)
## 🌐 マイページ下部/好きな投稿一覧、ユーザーの投稿一覧
[](https://gyazo.com/7aee8e11f77b144485c14a6b72a9a0c1)
## 🌐 ユーザー情報編集・退会ページ
[](https://gyazo.com/6414265c99554633fd5c9ce3b3050a5e)
# 📱 利用方法
### ログイン
1.アクセスするとトップページに遷移
2.「正解のない問題たちは?」のページに移ると内容が確認できます。
3.ヘッダー部分の「ログイン」をクリック
4.ログインページに遷移した上で、上記テスト用アカウントでログイン
### お題の投稿
1.ログイン後のトップページ画面右下に表示されている
「出題する」をクリックする
2.新規お題作成ページに遷移した上で、下記を入力する
・「写真にタイトルをつける」の場合
①ジャンルで「写真にタイトルを付ける」を選択
②写真を添付する
③出題者の回答を50字以内で入力する
④出題するをクリック
・「文章問題の場合」
①ジャンルで「文章問題」を選択
②お題のフォームに50字以内でお題を入力する
③出題者の回答を50字以内で入力する
④出題するをクリック
### お題の回答
1.トップページの「お題一覧」の下記に表示されている好きなお題を選択し「お題に挑戦する」をクリック
2.お題の詳細ページに遷移
3.ページ下記にある、「回答フォーム」に回答を入力し、「送信」をクリックする
4.送信された回答は上記の「回答一覧」に新規回答が一番上になりように表示される
### お題と回答の判定
・「お題の判定」
①トップページの中からいいと思ったお題を選択
②お題の下部に表示されている、笑顔の絵文字をクリックする
③クリックすると右の数字のカウントが1つ上がる
④もう一度クリックすると、取り消すことができる
⑤お題は上記の「お題ポイントランキング」に判定数の多い順にランキング表示される
⑥クリックしたお題は「好きなお題」としてマイページに一覧表示される
・「回答の判定」
①トップページの「お題一覧」の下記に表示されている好きなお題を選択し「お題に挑戦する」をクリック
②お題の詳細ページに遷移
③回答一覧に表示されている、面白いと思った回答を選択し右に表示されている笑顔の絵文字をクリック
④クリックすると右の数字のカウントが1つ上がる
⑤もう一度クリックすると、取り消すことができる
⑥回答は、上記の「ポイントランキング」判定数の多い順にランキング表示される
# 💭 課題解決
ゲームのような感覚で、脳のトレーニングを行いそれが数値化してわかり成長を感じられる。
大喜利を体験してみたい。
# 👍 洗い出した要件
・隙間時間を利用して、脳のトレーニングを行いたい
・「発想力」「表現力」鍛えたい
・他者の思考に触れてみたい
・自分の思考が面白いか評価を受けたい
・日常生活ではあまりできない大喜利に参加したい
・「お題」「回答」「判定」参加方法が選べる
# 🛠 機能一覧
| 機能 | 概要 |
| ------------------ | --------------------------------------------------------------- |
| ユーザー管理機能 | 新規登録・ログイン・ログアウトが可能 |
| お題投稿機能 | 文章でのとうこ投稿か写真での投稿ができる |
| お題詳細機能 | お題詳細ページより、回答ができる |
| お題編集削除機能 | 投稿者のみお題の編集・削除ができる |
| ユーザー詳細表示機能 | 各ユーザーのプロフィール、投稿一覧、「面白いと判定した投稿一覧」が見れる |
| ユーザー編集・削除機能 | 本人のみプロフィール情報の編集や退会ができる |
| 回答機能 | お題詳細ページから回答が行える、回答するとプロフィール写真と名前が表示される |
| 回答判定機能 | 回答の隣にある、絵文字をクリックするとカウントが1つ上がる、削除も可能 |
| お題判定機能 | 投稿されているお題の絵文字をクリックすると、カウントが1つ上がる、削除も可能 |
| 回答ランキング機能 | 回答されたものが、判定に応じてランキング表示される、同じ表数は同率順位で表示 |
| お題ランキング機能 | 投稿されたお題は、判定に応じてランキング表示される、同じ表数は同率順位で表示 |
# 開発環境
・VScode
・Ruby 2.6.5
・Rails 6.0.3.4
・Mysql2 0.4.4
・gem 3.0.3
・Heroku 7.47.11
# 追加予定機能
・コメントの非同期通信
・判定機能の非同期通信
・フォロー機能
# 🤖 DB設計
# ユーザー管理機能
・usersテーブル
| Column | Type | Options |
| -------------------- | ---------- | ------------------------ |
| email | string | null: false,unique: true |
| encrypted_password | string | null: false |
| nickname | string | null: false |
| profile | string | null: false |
### Association
- has_many :posts
- has_many :comments
- has_many :likes
- has_many :post_likes
# お題投稿機能
・postsテーブル
| Column | Type | Options |
| --------- | ---------- | ------------------------------ |
| title | string | null: false |
| genre_id | integer | null: false |
| sentence | string | null: false, |
| user | references | null: false, foreign_key: true |
### Association
- has_many :comments
- belongs_to :user
- has_many :likes
- has_many :post_likes
# お題回答機能
・commentsテーブル
| Column | Type | Options |
| --------- | ---------- | ------------------------------ |
| message | string | null: false |
| user | references | null: false, foreign_key: true |
| post | references | null: false, foreign_key: true |
### Association
- belongs_to :user
- belongs_to :post
- has_many :likes
- has_many :post_likes
# 回答判定機能
・likesテーブル
| Column | Type | Options |
| --------- | ---------- | ------------------------------ |
| user | references | null: false, foreign_key: true |
| post | references | null: false, foreign_key: true |
| comment | references | null: false, foreign_key: true |
### Association
- belongs_to :user
- belongs_to :post
- belongs_to :comment
# お題判定機能
・post_likesテーブル
| Column | Type | Options |
| --------- | ---------- | ------------------------------ |
| user | references | null: false, foreign_key: true |
| post | references | null: false, foreign_key: true |
### Association
- belongs_to :user
- belongs_to :post
<file_sep>/app/controllers/likes_controller.rb
class LikesController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = Comment.find(params[:comment_id])
@like = Like.create(user_id: current_user.id, post_id: @post.id, comment_id: @comment.id)
redirect_to post_path(@comment.post)
end
def destroy
@post = Post.find(params[:post_id])
@comment = Comment.find(params[:comment_id])
Like.find_by(user_id: current_user.id, post_id: @post.id, comment_id: @comment.id).destroy
redirect_to post_path(@comment.post)
end
end
<file_sep>/spec/system/comments_spec.rb
require 'rails_helper'
RSpec.describe "Comments", type: :system do
before do
@post = FactoryBot.create(:post)
@post.image = nil
@comment = Faker::Lorem.sentence
end
it "ログインしたユーザーはお題詳細ページから回答できる" do
# ログインする
visit new_user_session_path
fill_in "メールアドレス", with: @post.user.email
fill_in "パスワード(半角英数混合6文字以上)", with: @post.user.password
find('input[name="commit"]').click
expect(current_path).to eq(root_path)
# お題詳細ページに遷移する
visit post_path(@post)
# フォームにメッセージを入力する
fill_in "comment_message" , with: @comment
# 回答を送信するとコメントモデルのカウントが1つ上がる
expect{
find('input[name="commit"]').click
}.to change {Comment.count}.by(1)
# 詳細ページにリダイレクトされることを確認
expect(current_path).to eq(post_path(@post))
# 詳細ページに先ほどの回答があったことを確認
expect(page).to have_content @comment
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
devise_for :users
root to: 'posts#index'
resources :users, only: [:show, :edit, :update, :destroy]
resources :posts do
collection do
get 'indexabout'
end
resources :post_likes, only: [:create, :destroy]
resources :comments, only: :create do
resources :likes, only: [:create, :destroy]
end
end
end
<file_sep>/app/controllers/post_likes_controller.rb
class PostLikesController < ApplicationController
def create
@post = Post.find(params[:post_id])
@post_like = PostLike.create(user_id: current_user.id, post_id: @post.id)
redirect_to root_path(@post)
end
def destroy
@post = Post.find(params[:post_id])
PostLike.find_by(user_id: current_user.id, post_id: @post.id).destroy
redirect_to root_path
end
end
<file_sep>/app/controllers/users_controller.rb
class UsersController < ApplicationController
before_action :set_user
before_action :move_to_user, only: [:edit, :destroy]
before_action :authenticate_user!, only: [:edit, :destroy]
def show
@post = @user.posts
@post_like = @user.post_likes
end
def edit
end
def update
@post = @user.posts
@post_like = @user.post_likes
if @user.update(user_params)
redirect_to user_path(@user.id)
else
render "devise/registrations/edit"
end
end
def destroy
if @user.destroy
redirect_to root_path
else
render :show
end
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.fetch(:user, {}).permit(:nickname, :profile, :email, :image)
end
def move_to_user
unless user_signed_in? && current_user.id == @user.id
redirect_to root_path
end
end
end
|
ca1943f52eaf440a730f2a41962538b9ff397838
|
[
"Markdown",
"Ruby"
] | 14
|
Ruby
|
tetsu1026/ogiri-app
|
416fc5debb91d9312cd769fdd93058f5dee93774
|
486a84b6f511539a6b1e7b89cdd286724702a027
|
refs/heads/master
|
<repo_name>neeveecomm/FRDM_KL25Z_ACCESSORY_SHIELD<file_sep>/README.md
# FRDM_KL25Z_ACCESSORY_SHIELD
DF Robot Accessory Sheild MBed OS Driver for FRDM_KL25Z platform<file_sep>/u8g_com_frdmkl25z_ssd_i2c.cpp
/*
Special pin usage:
U8G_PI_I2C_OPTION additional options
U8G_PI_A0_STATE used to store the last value of the command/data register selection
U8G_PI_SET_A0 1: Signal request to update I2C device with new A0_STATE, 0: Do nothing, A0_STATE matches I2C device
U8G_PI_SCL clock line (NOT USED)
U8G_PI_SDA data line (NOT USED)
U8G_PI_RESET reset line (currently disabled, see below)
Protocol:
SLA, Cmd/Data Selection, Arguments
The command/data register is selected by a special instruction byte, which is sent after SLA
The continue bit is always 0 so that a (re)start is equired for the change from cmd to/data mode
*/
#include "u8g.h"
#if defined(U8G_FRDMKL25Z_PI)
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include "mbed.h"
#define I2C_SLA (0x3c << 1)
#define I2C_CMD_MODE 0x000
#define I2C_DATA_MODE 0x040
#define OLED_SCL D15
#define OLED_SDA D14
#if defined(U8G_WITH_PINLIST)
I2C m_i2c(D14, D15);
static unsigned char mode;
uint8_t u8g_com_frdmkl25z_ssd_start_sequence(u8g_t *u8g)
{
int len;
/* are we requested to set the a0 state? */
if ( u8g->pin_list[U8G_PI_SET_A0] == 0 )
return 1;
//m_i2c.stop();
//wait(0.100);
m_i2c.start();
if (m_i2c.write(I2C_SLA)) {
return 0;
}
if ( u8g->pin_list[U8G_PI_A0_STATE] == 0 )
{
mode = I2C_CMD_MODE;
}
else
{
mode = I2C_DATA_MODE;
}
if (m_i2c.write(mode)) {
return 0;
}
u8g->pin_list[U8G_PI_SET_A0] = 0;
return 1;
}
uint8_t u8g_com_frdmkl25z_ssd_i2c_fn (u8g_t *u8g, uint8_t msg, uint8_t arg_val, void *arg_ptr)
{
int len;
unsigned char mode;
int i;
register uint8_t buf[256];
unsigned char *aptr;
switch(msg)
{
case U8G_COM_MSG_INIT:
//mI2c = I2C(D14, D15);
u8g_i2c_init(u8g->pin_list[U8G_PI_I2C_OPTION]);
break;
case U8G_COM_MSG_STOP:
break;
case U8G_COM_MSG_RESET:
break;
case U8G_COM_MSG_CHIP_SELECT:
u8g->pin_list[U8G_PI_A0_STATE] = 0;
u8g->pin_list[U8G_PI_SET_A0] = 1; /* force a0 to set again, also forces start condition */
if(arg_val == 0) {
m_i2c.stop();
}
break;
case U8G_COM_MSG_WRITE_BYTE:
{
if ( u8g_com_frdmkl25z_ssd_start_sequence(u8g) == 0 ) {
m_i2c.stop();
return 0;
}
#if 0
buf[0] = mode;
buf[1] = arg_val;
len = m_i2c.write(I2C_SLA, (char *)&buf[0], 2);
#else
if (m_i2c.write(arg_val)) {
m_i2c.stop();
return 0;
}
#endif
break;
}
case U8G_COM_MSG_WRITE_SEQ:
{
aptr = (unsigned char *)arg_ptr;
if ( u8g_com_frdmkl25z_ssd_start_sequence(u8g) == 0 ) {
m_i2c.stop();
return 0;
}
buf[0] = mode;
for(i=0; i < arg_val; i++) {
// buf[i+1] = aptr[i];
if (m_i2c.write(aptr[i])) {
m_i2c.stop();
return 0;
}
}
#if 0
len = m_i2c.write(I2C_SLA, (char *)&buf[0], (arg_val+1));
#endif
break;
}
case U8G_COM_MSG_WRITE_SEQ_P:
{
aptr = (unsigned char *)arg_ptr;
if ( u8g_com_frdmkl25z_ssd_start_sequence(u8g) == 0 ) {
m_i2c.stop();
return 0;
}
buf[0] = mode;
for(i=0; i < arg_val; i++) {
#if 0
buf[i+1] = u8g_pgm_read(aptr);
#else
if (m_i2c.write(u8g_pgm_read(aptr))) {
m_i2c.stop();
return 0;
}
#endif
aptr++;
}
#if 0
len = m_i2c.write(I2C_SLA, (char *)&buf[0], (arg_val+1));
#endif
}
break;
case U8G_COM_MSG_ADDRESS: /* define cmd (arg_val = 0) or data mode (arg_val = 1) */
u8g->pin_list[U8G_PI_A0_STATE] = arg_val;
u8g->pin_list[U8G_PI_SET_A0] = 1; /* force a0 to set again */
#if 0
if(arg_val == 0) {
mode = I2C_CMD_MODE;
}else{
mode = I2C_DATA_MODE;
}
len = m_i2c.write(I2C_SLA, (char *)&mode, 1);
#endif
break;
}
return 1;
}
#else /* defined(U8G_WITH_PINLIST) */
uint8_t u8g_com_frdmkl25z_ssd_i2c_fn(u8g_t *u8g, uint8_t msg, uint8_t arg_val, void *arg_ptr) {
return 1;
}
#endif /* defined(U8G_WITH_PINLIST) */
void u8g_Delay(uint16_t val)
{
float mSec = val;
wait(mSec / 1000);
}
#endif
<file_sep>/AccessoryShield.h
/*
* AccessoryShield.h
*
* Created on: Mar 12, 2016
* Author: neeveecomm
*/
#ifndef SOURCES_BLUNOSHIELD_ACCESSORYSHIELD_H_
#define SOURCES_BLUNOSHIELD_ACCESSORYSHIELD_H_
#include "mbed.h"
#include "U8glib.h"
typedef enum {
JS_KEY_NONE = 0,
JS_KEY_RIGHT,
JS_KEY_LEFT,
JS_KEY_UP,
JS_KEY_DOWN,
JS_KEY_PUSH,
JS_KEY_MAX,
}JoyStick_t;
typedef struct {
int humidity;
int temperature;
int ledRed;
int ledGreen;
int ledBlue;
int knob;
JoyStick_t joyStick;
}BlunoSheildInfo_t;
typedef union {
unsigned char buffer[6];
}DhtTemp_t;
class AccessoryShield {
PwmOut red;
PwmOut green;
PwmOut blue;
DigitalOut shldBuzz;
DigitalOut shldRelay;
AnalogIn jsIn;
AnalogIn knobIn;
JoyStick_t lastKey;
DigitalInOut dhtTemp;
DhtTemp_t dht11;
DigitalOut oledDC;
DigitalOut oledRes;
I2C mI2C;
U8GLIB_SSD1306_128X64 dispOled;
int mAddr;
virtual bool DhtRead();
public:
AccessoryShield();
virtual ~AccessoryShield();
virtual void SetBuzzer(bool on);
virtual void SetRelay(bool on);
virtual void SetLedColour(float r, float g, float b);
virtual JoyStick_t GetJoyStick(void);
virtual int GetKnob(void);
virtual float readHumidity();
virtual float readTemperature();
virtual void updateOledDisp (BlunoSheildInfo_t *bsInfo);
virtual int GetRed();
virtual int GetGreen();
virtual int GetBlue();
};
#endif /* SOURCES_BLUNOSHIELD_ACCESSORYSHIELD_H_ */
<file_sep>/AccessoryShield.cpp
/*
* AccessoryShield.cpp
*
* Created on: Mar 12, 2016
* Author: neeveecomm
*/
#include "AccessoryShield.h"
/* Defintions */
#define PIN_HIGH true
#define PIN_LOW false
/* RGB LED Pin Definitions */
#define SHLD_LED_R D9
#define SHLD_LED_G D10
#define SHLD_LED_B D3
/* Buzzer Pin Definitions */
#define BUZZER D8
/* Relay Pin Definitions */
#define RELAY D11
/* JOY Stick Pin Definitions */
#define JOY_STICK A0
/* POT KNOW Pin Definitions */
#define POT_KNOB A1
/* Temperature Pin Definitions */
#define DHT11_PIN D2
#define MAXTIMINGS 85
#define DHTCOUNT 6
/* OLED Pin Definitons */
#define OLED_DC D7
#define OLED_RES D6
#define OLED_SCL D15
#define OLED_SDA D14
#define OLED_ADDR
AccessoryShield::AccessoryShield() : red(SHLD_LED_R), green(SHLD_LED_G), blue(SHLD_LED_B),
shldBuzz(BUZZER), shldRelay(RELAY), jsIn(JOY_STICK),
knobIn(POT_KNOB), dhtTemp(DHT11_PIN), oledDC(OLED_DC),
oledRes(OLED_RES), mI2C(OLED_SDA, OLED_SCL), mAddr(OLED_ADDR),
dispOled(U8G_I2C_OPT_NONE)
{
/* Initialize RGB LED */
red.period(0.001f);
green.period(0.001f);
blue.period(0.001f);
/* Initialize Joy Stick Key */
lastKey = JS_KEY_NONE;
/* Initialize DHT11 */
dhtTemp.output();
dhtTemp.write(PIN_HIGH);
/* Initialize OLED */
oledDC = 0;
oledRes = 1; wait(0.100f);
oledRes = 0; wait(0.100f);
oledRes = 1; wait(0.100f);
}
AccessoryShield::~AccessoryShield()
{
}
void AccessoryShield::SetBuzzer(bool on)
{
shldRelay = on;
}
void AccessoryShield::SetRelay(bool on)
{
shldBuzz = on;
}
void AccessoryShield::SetLedColour(float r, float g, float b)
{
red = r;
green = g;
blue = b;
}
int AccessoryShield::GetRed()
{
float r = red;
return (((1000 - r) * 100)/1000);
}
int AccessoryShield::GetGreen()
{
float r = green;
return (((1000 - r) * 100)/1000);
}
int AccessoryShield::GetBlue()
{
float r = blue;
return (((1000 - r) * 100)/1000);
}
JoyStick_t AccessoryShield::GetJoyStick(void)
{
JoyStick_t joyStick = JS_KEY_NONE;
unsigned int jsVal;
jsVal = jsIn.read_u16();
if(jsVal < 10000)
joyStick = JS_KEY_RIGHT;
else if((10000 <= jsVal) && (jsVal < 20000))
joyStick = JS_KEY_PUSH;
else if((20000 <= jsVal) && (jsVal < 32000))
joyStick = JS_KEY_UP;
else if((32000 <= jsVal) && (jsVal < 60000))
joyStick = JS_KEY_LEFT;
//else if((60000 <= jsVal) && (jsVal < 65536))
// joyStick = JS_KEY_DOWN;
if(joyStick != lastKey) {
lastKey = joyStick;
}
return joyStick;
}
int AccessoryShield::GetKnob(void)
{
unsigned int knobVal;
knobVal = knobIn.read_u16();
return (knobVal * 100)/65535;
}
float AccessoryShield::readHumidity()
{
float f = 0;
if(DhtRead()) {
f = dht11.buffer[0];
}
return f;
}
float AccessoryShield::readTemperature()
{
float f = 0;
if(DhtRead()) {
f = dht11.buffer[2];
}
return f;
}
bool AccessoryShield::DhtRead()
{
unsigned char i =0, j=0, counter = 0;
bool lastState = PIN_HIGH;
bool state;
dht11 = {0};
dhtTemp.output();
dhtTemp.write(PIN_HIGH);
wait(0.002f);
dhtTemp.write(PIN_LOW);
wait(0.020f);
dhtTemp.write(PIN_HIGH);
wait(0.000040f);
dhtTemp.input();
// read in timings
for ( i=0; i< MAXTIMINGS; i++) {
counter = 0;
while ((state = dhtTemp.read()) == lastState) {
counter++;
wait(0.000001f);
if (counter == 255) {
break;
}
}
lastState = dhtTemp.read();
if (counter == 255) break;
// ignore first 3 transitions
if ((i >= 4) && (i%2 == 0)) {
// shove each bit into the storage bytes
dht11.buffer[j/8] <<= 1;
if (counter > DHTCOUNT)
dht11.buffer[j/8] |= 1;
j++;
}
}
if ((j >= 40) &&
(dht11.buffer[4] == ((dht11.buffer[0] + dht11.buffer[1] + dht11.buffer[2] + dht11.buffer[3]) & 0xFF)) ) {
return true;
}
return false;
}
void AccessoryShield::updateOledDisp (BlunoSheildInfo_t *bsInfo)
{
dispOled.firstPage();
do{
dispOled.setFont(u8g_font_unifont_0_8 /*u8g_font_unifont*/);
dispOled.setPrintPos(10,16); //set the print position
dispOled.print("H:");
dispOled.print(bsInfo->humidity); //show the humidity on oled
dispOled.print("%");
dispOled.setPrintPos(10,32);
dispOled.print("T:"); //show the temperature on oled
dispOled.print(bsInfo->temperature);
dispOled.print("C");
dispOled.setPrintPos(88,16);
dispOled.print("R:"); //show RGBLED red value
dispOled.print(bsInfo->ledRed);
dispOled.setPrintPos(88,32);
dispOled.print("G:"); //show RGBLED green value
dispOled.print(bsInfo->ledGreen);
dispOled.setPrintPos(88,48);
dispOled.print("B:"); //show RGBLED blue value
dispOled.print(bsInfo->ledBlue);
dispOled.setPrintPos(10,48);
dispOled.print("Knob:");
dispOled.print(bsInfo->knob); //show knob(potentiometer) value read from analog pin
dispOled.print("%");
dispOled.setPrintPos(10,60);
dispOled.print("Joystick:"); //if string is null, show the state of joystick
switch (bsInfo->joyStick){
case JS_KEY_NONE:
dispOled.print("Normal");
break;
case JS_KEY_RIGHT:
dispOled.print("Right");
break;
case JS_KEY_UP:
dispOled.print("Up");
break;
case JS_KEY_LEFT:
dispOled.print("Left");
break;
case JS_KEY_DOWN:
dispOled.print("Down");
break;
case JS_KEY_PUSH:
dispOled.print("Push");
break;
default:
break;
}
}
while(dispOled.nextPage());
}
|
0da3d22cb6af4532c29ccc0bba6aeb608c740dfc
|
[
"Markdown",
"C++"
] | 4
|
Markdown
|
neeveecomm/FRDM_KL25Z_ACCESSORY_SHIELD
|
1139c928f7db504ba56d67ebe1abe48abbf65dad
|
87561339d6e0e6d350d9578b1dd37ec5d66999d7
|
refs/heads/master
|
<repo_name>mikewatford/snww<file_sep>/html/js/app.js
$(document).foundation();
//Terrill: Add class when the small viewport menu is visible
(function(){
let smallMenu = document.getElementById('topbar-center-logo');
let toggleClass = function(){
if ( smallMenu.style.display != 'none' ) {
document.body.classList.add('small-viewport-menu');
} else {
document.body.classList.remove('small-viewport-menu');
}
};
let observeMenu = function(){
let observer = new MutationObserver(function(mutations) {
let change = null;
mutations.forEach(function(mutationRecord) {
if ( mutationRecord.target == smallMenu ) {
change = true;
}
});
if (change) toggleClass();
});
observer.observe(smallMenu, { attributes : true, attributeFilter : ['style'] });
};
toggleClass();
observeMenu();
})();
<file_sep>/README.md
# Super Nerd and Wonder Woman
The ideas, ramblings, and journal of two nerds.
<file_sep>/landing-page/js/cycle.js
var words = ["food", "beer", "race", "sexy time"];
var i = 0;
var text = "dating";
function _getChangedText() {
i = (i + 1) % words.length;
return text.replace(/dating/, words[i]);
}
function _changeText() {
var txt = _getChangedText();
var d = document.getElementById("changer")
d.className = "fadeOut";
setTimeout(function(){
d.className = "";
document.getElementById("changer").innerHTML = txt;
}, 1000);
}
setInterval("_changeText()", 3000);<file_sep>/CHANGELOG.md
## 1.3.1 (3/12/19)
### Features
- Moved all static images to a subdomain
- Updated css, home, index, header, and footer image locations
## 1.3.0 (3/11/19)
### Features
- Added mod to get adjacent posts
- Now pulls in posts and CPTs
- Updated single.php with post array
- Updated STG with post array and prev/next links
## 1.2.0 (3/9/19)
### Features
- Added pagination to Author pages
- Updated functions with paginate array
- Added paginate styles
- Added overwrite styles for .wp-block-image
## 1.1.4 (3/4/19)
### Bug Fixes
- Author pages now query both wp and cpt posts
- Removed style tag with background image
- Added query to functions.php
## 1.1.3 (2/26/19)
### Features
- Journal query now searches for both wp-posts and cpt posts
## 1.1.2 (2/26/19)
### Bug Fixes
- Updated travel page with 'location' post type
## 1.1.1 (2/25/19)
### Breaking Changes
- Updated Post title size to small-10 from small-6
## 1.1.0 (2/24/19)
### Breaking Changes
- Added v-center class
- Removed 'inner' class
- Template markup updated with removed classes and div
- Created a new minified main (now main.min.css)
### Bug Fixes
- Decrease font-size for router section on small
### Features
- Removed wickedcss src in header
- Added animations to home scss
## 1.0.1 (2/22/19)
### Bug Fixes
- Decreased page heading size to 52px
- Added bottom margin to the About page
## 1.0.0 (2/19/19)
### Feature
- Added OG image to images directory
|
3fa38a4d1506ad68445692fa79cc486f2531bf63
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
mikewatford/snww
|
cde1e7adab6955ffdb5a630acda06bb0ec7138ee
|
2af65ea91ec29e0bc10aa07d5f867a8ce51362ce
|
refs/heads/master
|
<file_sep>package com.example.restclient.repository
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.SubMenu
import android.widget.EditText
import android.widget.SearchView
import androidx.core.view.get
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.recyclerview.widget.RecyclerView
import com.example.restclient.R
import com.example.restclient.bindRecyclerView
import com.example.restclient.network.*
import kotlinx.coroutines.*
import retrofit2.Call
import retrofit2.Response
import java.lang.Exception
import java.lang.IllegalArgumentException
import java.lang.NullPointerException
import java.util.*
import javax.security.auth.callback.Callback
import kotlin.collections.ArrayList
import kotlin.reflect.jvm.internal.impl.resolve.constants.NullValue
import kotlin.String as String
enum class GithubApiStatus {LOADING, ERROR, DONE}
class RepositoryViewModel : ViewModel() {
// private var _displayList = MutableLiveData<ArrayList<GithubRepository>>()
// val displayList: LiveData<ArrayList<GithubRepository>>
// get() = _displayList
// private val = ArrayList<GithubRepository>()
// val displayList: ArrayList<GithubRepository>
// get() = _displayList
//To test getting JSON.
// private val _test = MutableLiveData<String>()
// val test: LiveData<String>
// get() = _test
private val _status = MutableLiveData<GithubApiStatus>()
val status: LiveData<GithubApiStatus>
get() = _status
private val _repositories = MutableLiveData<List<GithubRepository>>()
val repositories: LiveData<List<GithubRepository>>
get() = _repositories
private val _details = MutableLiveData<GithubRepository>()
val details: LiveData<GithubRepository>
get() = _details
fun getDetails(githubRepository: GithubRepository) {
_details.value = githubRepository
}
fun getDetailsDone() {
_details.value = null
}
companion object {
private lateinit var _menu: SubMenu
}
var menu: SubMenu
get() = _menu
set(value: SubMenu) {
_menu = value
}
private var currentLanguageFilter = ""
private var currentTimeFilter = TimeFilter.DAILY
//Since we are working with coroutines, we begin by creating a job.
private val viewModelJob = Job()
private val coroutineScope = CoroutineScope(viewModelJob + Dispatchers.Main )
init {
getRepositories(currentLanguageFilter, currentTimeFilter)
}
private fun getRepositories(languageFilter: String, timeFilter: TimeFilter) {
coroutineScope.launch {
var getRepository = GithubApi.retrofitService.getProperties(languageFilter, timeFilter.value)
try {
_status.value = GithubApiStatus.LOADING
val result = getRepository.await()
_status.value = GithubApiStatus.DONE
_repositories.value = result
_menu.clear()
_menu.add("Show All")
for (language in languages) {
_menu.add(language)
}
} catch (e: Exception) {
System.out.println("here" + e.message)
_status.value = GithubApiStatus.ERROR
_repositories.value = ArrayList()
}
}
}
fun updateLanguageFilter(languageFilter: String) {
getRepositories(languageFilter, currentTimeFilter)
currentLanguageFilter = languageFilter
}
fun updateTimeFilter(timeFilter: TimeFilter) {
getRepositories(currentLanguageFilter, timeFilter)
currentTimeFilter = timeFilter
}
//To test getting JSON.
// private fun getRepositories() {
// GithubApi.retrofitService.getProperties().enqueue(object : Callback,
// retrofit2.Callback<String> {
// override fun onFailure(call: Call<String>, t: Throwable) {
// _test.value = "Failure: " + t.message
// }
//
// override fun onResponse(call: Call<String>, response: Response<String>) {
// _test.value = response.body()
// }
// })
// System.out.println("here")
// System.out.println(_test.value)
// }
fun actionSearch(menuItem: MenuItem, adapter: RepositoryAdapter) {
if(menuItem != null) {
val searchView = menuItem.actionView as SearchView
searchView.setOnQueryTextListener(object: SearchView.OnQueryTextListener{
override fun onQueryTextSubmit(p0: String?): Boolean {
return false
}
override fun onQueryTextChange(p0: String?): Boolean {
adapter.filter.filter(p0)
return true
}
})
}
}
override fun onCleared() {
super.onCleared()
viewModelJob.cancel()
}
}<file_sep>package com.example.restclient.repository
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Filter
import android.widget.Filterable
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.ListAdapter
import com.example.restclient.databinding.ListItemBinding
import com.example.restclient.network.GithubRepository
import java.util.*
import kotlin.collections.ArrayList
class RepositoryAdapter(private val onClickListener: OnClickListener): ListAdapter<GithubRepository, RepositoryAdapter.RepositoryViewHolder>(DiffCallback), Filterable {
private lateinit var filteredResults: MutableList<GithubRepository>
init {
filteredResults = currentList
Log.i("RepositoryAdapter", filteredResults.toString())
}
companion object DiffCallback: DiffUtil.ItemCallback<GithubRepository>() {
override fun areItemsTheSame(
oldItem: GithubRepository,
newItem: GithubRepository
): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(
oldItem: GithubRepository,
newItem: GithubRepository
): Boolean {
return (oldItem.author == newItem.author) && (oldItem.name == newItem.name)
}
}
class RepositoryViewHolder(private var binding: ListItemBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(githubRepository: GithubRepository) {
binding.repository = githubRepository
binding.executePendingBindings()
}
}
class OnClickListener(val clickListener: (githubRepository: GithubRepository) -> Unit) {
fun onClick(githubRepository: GithubRepository) {
clickListener(githubRepository)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RepositoryViewHolder {
return RepositoryViewHolder(ListItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
))
}
override fun onBindViewHolder(holder: RepositoryViewHolder, position: Int) {
val githubRepository = filteredResults[position]
holder.itemView.setOnClickListener {
onClickListener.onClick(githubRepository)
}
holder.bind(githubRepository)
}
override fun getItemCount(): Int {
return filteredResults.size
}
override fun getFilter(): Filter {
return object: Filter() {
override fun performFiltering(p0: CharSequence?): FilterResults {
val searchString = p0.toString().toLowerCase(Locale.getDefault())
if(searchString.isEmpty()) {
filteredResults = currentList
} else {
val temp = ArrayList<GithubRepository>()
for(repository in currentList) {
for(user in repository.builtBy) {
if (user.username.toLowerCase(Locale.getDefault()).contains(searchString)) {
if (!temp.contains(repository)) {
temp.add(repository)
}
}
}
}
filteredResults = temp
}
val filterResults = FilterResults()
filterResults.values = filteredResults
filterResults.count = filteredResults.size
return filterResults
}
override fun publishResults(p0: CharSequence?, p1: FilterResults?) {
filteredResults = p1!!.values as MutableList<GithubRepository>
notifyDataSetChanged()
}
}
}
}
<file_sep>package com.example.restclient
import android.view.View
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.net.toUri
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.restclient.network.GithubRepository
import com.example.restclient.repository.GithubApiStatus
import com.example.restclient.repository.RepositoryAdapter
//The repositories are added to adapter. It is connected to RecyclerView via XML attribute.
@BindingAdapter("listData")
fun bindRecyclerView(recyclerView: RecyclerView, data: List<GithubRepository>?) {
val adapter = recyclerView.adapter as RepositoryAdapter
adapter.submitList(data)
}
//For user's avatar.
@BindingAdapter("imageUrl")
fun bindImage(imgView: ImageView, imgUrl: String?) {
imgUrl?.let {
val imgUri = imgUrl.toUri().buildUpon().scheme("https").build()
Glide.with(imgView.context)
.load(imgUri)
.into(imgView)
}
}
@BindingAdapter("githubApiStatus")
fun bindStatus(progressBar: ProgressBar, status: GithubApiStatus?) {
when (status) {
GithubApiStatus.LOADING -> {
progressBar.visibility = View.VISIBLE
}
GithubApiStatus.ERROR -> {
progressBar.visibility = View.GONE
}
GithubApiStatus.DONE -> {
progressBar.visibility = View.GONE
}
}
}
@BindingAdapter("githubApiStatusText")
fun bindStatus(textView: TextView, status: GithubApiStatus?) {
when (status) {
GithubApiStatus.ERROR -> {
textView.visibility = View.VISIBLE
textView.text = "No Connection"
}
else -> textView.visibility = View.GONE
}
}
@BindingAdapter("languageText")
fun bindLanguage(textView: TextView, language: String?) {
if(language != null) {
textView.text = language
} else {
textView.visibility = View.GONE
}
}<file_sep>package com.example.restclient.detail
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import com.example.restclient.R
import com.example.restclient.network.GithubRepository
class DetailViewModel(githubRepository: GithubRepository, app: Application) :
AndroidViewModel(app) {
private val _repository = MutableLiveData<GithubRepository>()
val repository: LiveData<GithubRepository>
get() = _repository
init {
_repository.value = githubRepository
}
val displayPeriodStars = Transformations.map(_repository) {
app.applicationContext.getString(
R.string.display_period_stars, it.currentPeriodStars
)
}
val displayStars = Transformations.map(_repository) {
app.applicationContext.getString(
R.string.display_stars, it.stars
)
}
val displayForks = Transformations.map(_repository) {
app.applicationContext.getString(
R.string.display_forks, it.forks
)
}
}<file_sep>package com.example.restclient.repository
import android.os.Bundle
import android.telephony.SmsMessage
import android.view.*
import android.widget.SearchView
import androidx.fragment.app.Fragment
import android.widget.Toast
import androidx.core.view.get
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.fragment.findNavController
import com.example.restclient.R
import com.example.restclient.databinding.FragmentRepositoryBinding
import com.example.restclient.network.TimeFilter
import com.example.restclient.network.languages
class RepositoryFragment : Fragment() {
private val viewModel: RepositoryViewModel by lazy {
ViewModelProviders.of(this).get(RepositoryViewModel::class.java)
}
private lateinit var binding: FragmentRepositoryBinding
private lateinit var adapter: RepositoryAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentRepositoryBinding.inflate(inflater)
binding.viewModel = viewModel
binding.lifecycleOwner = this
adapter = RepositoryAdapter(RepositoryAdapter.OnClickListener {
viewModel.getDetails(it)
})
binding.repositoriesRecycle.adapter = adapter
viewModel.details.observe(viewLifecycleOwner, Observer {
if(it != null) {
this.findNavController().navigate(RepositoryFragmentDirections.actionRepositoryFragmentToDetailFragment(it))
viewModel.getDetailsDone()
}
})
setHasOptionsMenu(true)
return binding.root
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if(item.title == "Show All") {
viewModel.updateLanguageFilter("")
return true
}
if(languages.contains(item.title)) {
viewModel.updateLanguageFilter(item.title.toString())
return true
}
if(item.itemId == R.id.daily) {
viewModel.updateTimeFilter(TimeFilter.DAILY)
} else if(item.itemId == R.id.weekly) {
viewModel.updateTimeFilter(TimeFilter.WEEKLY)
} else if(item.itemId == R.id.monthly) {
viewModel.updateTimeFilter(TimeFilter.MONTHLY)
} else {
return false
}
return true
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.overflow_menu, menu)
val subMenu = menu!!.findItem(R.id.language_menu).subMenu
viewModel.menu = subMenu
val searchItem = menu!!.findItem(R.id.action_search)
viewModel.actionSearch(searchItem, adapter)
super.onCreateOptionsMenu(menu, inflater)
}
}<file_sep># Rest Client
This is a REST API project that I worked on during my Android Developer internship. Thanks to this project, I had gained hands-on experince in Kotlin and Android.
<file_sep>package com.example.restclient.network
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import kotlinx.coroutines.Deferred
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
private const val BASE_URL = "https://github-trending-api.now.sh/"
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.baseUrl(BASE_URL)
.build()
//To test getting JSON.
//private val retrofit = Retrofit.Builder()
// .addConverterFactory(ScalarsConverterFactory.create())
// .baseUrl(BASE_URL)
// .build()
enum class TimeFilter(val value: String) {DAILY("daily"), WEEKLY("weekly"), MONTHLY("monthly")}
interface GithubApiService {
@GET("repositories")
fun getProperties(@Query("language") language: String, @Query("since") since: String):
Deferred<List<GithubRepository>>
}
object GithubApi {
val retrofitService: GithubApiService by lazy {
retrofit.create(GithubApiService::class.java)
}
}<file_sep>package com.example.restclient.network
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import kotlinx.android.parcel.RawValue
val languages: ArrayList<String> = ArrayList()
@Parcelize
data class GithubRepository(
val author: String,
val name: String,
val avatar: String,
val language: String?,
val stars: Int,
val forks: Int,
val currentPeriodStars: Int,
val builtBy: List<User>) : Parcelable {
val displayName = "$author/$name"
val displayStar: String = stars.toString()
init {
addLanguage()
}
private fun addLanguage() {
if(language != null && !languages.contains(language)) {
languages.add(language)
}
}
}
@Parcelize
class User(
val username: String,
val avatar: String
) :Parcelable<file_sep>package com.example.restclient.detail
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toolbar
import androidx.core.view.doOnAttach
import androidx.databinding.adapters.ToolbarBindingAdapter
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import com.example.restclient.R
import com.example.restclient.R.*
import com.example.restclient.bindImage
import com.example.restclient.databinding.FragmentDetailBinding
import com.example.restclient.detail.DetailFragmentArgs.fromBundle
import kotlinx.android.synthetic.main.fragment_detail.view.*
import kotlinx.android.synthetic.main.user_view.view.*
class DetailFragment : Fragment() {
private lateinit var viewModel: DetailViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val application = requireNotNull(activity).application
val binding = FragmentDetailBinding.inflate(inflater, container,false)
binding.lifecycleOwner = this
//This comes from navigation.(navigation argument)
val githubRepository = fromBundle(arguments!!).selectedRepository
val viewModelFactory = DetailViewModelFactory(githubRepository, application)
binding.viewModel =
ViewModelProviders.of(this, viewModelFactory).get(DetailViewModel::class.java)
for(user in githubRepository.builtBy) {
val view =
inflater.inflate(R.layout.user_view, null)
binding.root.scroll_view.linear_view.addView(view)
bindImage(view.image, user.avatar)
view.username_text.text = user.username
}
return binding.root
}
}
|
2adf14414cd80165e77ede4522213597d2049172
|
[
"Markdown",
"Kotlin"
] | 9
|
Kotlin
|
melihaydogd/rest_client
|
789575f92fcab8c9fcad99f4d3cd53470c40a289
|
8bbb0f47c75693e85919af173688e0b386edb3cb
|
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.Windows.Forms;
using System.Data.OleDb;
namespace CrearCarpetas
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
ofdBuscarExcel = new OpenFileDialog();
ofdBuscarExcel.Filter = "Archivos Excel|*.xls;*.xlsx;*.xlsm";
//ofdBuscarExcel.ShowDialog();
if (ofdBuscarExcel.ShowDialog() == DialogResult.OK)
{
txtArchivo.Text = ofdBuscarExcel.FileName;
string con = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ofdBuscarExcel.FileName+";"+@"Extended Properties='Excel 8.0;HDR=Yes;'";
using (OleDbConnection connection = new OleDbConnection(con))
{
connection.Open();
OleDbCommand command = new OleDbCommand("select * from [Hoja1$]", connection);
using (OleDbDataReader dr = command.ExecuteReader())
{
int celdas = 0;
while (dr.Read())
{
var row1Col0 = dr[0];
//Console.WriteLine(row1Col0);
dgObras.Rows[0].Cells[celdas].Value = row1Col0;
celdas++;
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message, "Error");
}
}
private void btnGenerar_Click(object sender, EventArgs e)
{
//dgObras = new DataGridView();
/*int celdas=dgObras.RowCount;
dgObras.Rows[0].Cells[celdas].Value="000000";*/
}
}
}
|
f88f75efa550851024164560eff91cb8c634ae79
|
[
"C#"
] | 1
|
C#
|
mbrandle/CrearCarpetas
|
c73081d0351e35ce61bb6c02657eb91d56d601a0
|
3ffb04a8a34679e59fdc2b7397ed421ee1cbfd48
|
refs/heads/master
|
<repo_name>vbmaster/ZDZ-React-POC<file_sep>/ZDZCCADC/Repositories/IRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace ZDZCCADC.Repositories
{
//public interface IRepository<T> where T : class
//{
// IEnumerable<T> GetAll();
// IEnumerable<T> FindBy(Expression<Func<T, bool>> predicate);
// //IEnumerable<T> FindBy(Expression<Func<T, bool>> predicate);
// Task Add(T entity);
// Task Delete(T entity);
// void Edit(T entity);
// void Save();
//}
public interface IRepository<TEntity>
{
Task<TEntity> FindAsync(string id);
Task<TEntity> FindAsync(int? id);
IQueryable<TEntity> Find(Expression<Func<TEntity, bool>> predicate);
IQueryable<TEntity> GetAll();
void Update(TEntity entity);
void Insert(TEntity entity);
void Delete(TEntity entity);
Task SaveChangesAsync();
IQueryable<TEntity> FromSql(string sql);
//DbRawSqlQuery<TEntity> SQLQuery<TEntity>(string sql, params object[] parameters);
}
}
<file_sep>/ZDZCCADC/Models/UserRoles/ListUserRolesView.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ZDZCCADC.Models.UserRoles
{
public class ListUserRolesView
{
public string User { get; set; }
public string Role { get; set; }
}
}
<file_sep>/ZDZCCADC/Models/Roles/Role.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace ZDZCCADC.Models.Roles
{
[Table("AspNetRoles", Schema = "dbo")]
public class Role
{
public string Id { get; set; }
[Required]
public string Name { get; set; }
}
}
<file_sep>/ZDZCCADC/Models/UserRoles/UserRole.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace ZDZCCADC.UserRoles
{
[Table("AspNetUserRoles", Schema = "dbo")]
public class UserRole : IUserRole
{
public string UserId { get; set; }
public string RoleId { get; set; }
}
}
<file_sep>/ZDZCCADC/Models/Roles/IRole.cs
namespace ZDZCCADC.Models.Roles
{
public interface IRole
{
string Id { get; set; }
string Name { get; set; }
}
}<file_sep>/ZDZCCADC/Models/UserRoles/IUserRole.cs
namespace ZDZCCADC.UserRoles
{
public interface IUserRole
{
string RoleId { get; set; }
string UserId { get; set; }
}
}<file_sep>/ZDZCCADC/Repositories/Repository.cs
using ZDZCCADC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZDZCCADC.Data;
namespace ZDZCCADC.Repositories
{
public class Repository<TEntity> : BaseRepository<TEntity> where TEntity : class
{
public Repository(ApplicationDbContext context): base(context)
{
}
}
}
<file_sep>/ZDZCCADC/Controllers/ReportController.cs
using Microsoft.AspNetCore.Mvc;
using System.Net;
using System.IO;
namespace ZDZCCADC.Controllers
{
public class ReportController : AlanJuden.MvcReportViewer.ReportController
{
protected override ICredentials NetworkCredentials
{
get
{
//Custom Domain authentication (be sure to pull the info from a config file)
//return new System.Net.NetworkCredential("username", "password", "domain");
//Default domain credentials (windows authentication)
// return System.Net.CredentialCache.DefaultNetworkCredentials;
return new System.Net.NetworkCredential("vbmaster", "P@ssw0rd<PASSWORD>");
}
}
protected override string ReportServerUrl
{
get
{
//You don't want to put the full API path here, just the path to the report server's ReportServer directory that it creates (you should be able to access this path from your browser: https://YourReportServerUrl.com/ReportServer/ReportExecution2005.asmx )
return "http://192.168.127.12/ReportServer";
}
}
public IActionResult ReportViewer() {
var model = this.GetReportViewerModel(Request);
model.ReportPath = "/SampleProject/UserByEmail";
//model.AddParameter("Parameter1", namedParameter1);
//model.AddParameter("Parameter2", namedParameter2);
return View("ReportViewer", model);
}
public IActionResult DisplayUserByEmail(string Email, string LastName)
{
var model = this.GetReportViewerModel(Request);
model.ReportPath = "/SampleProject/UserByEmail";
return View("ReportViewer", model);
}
}
}<file_sep>/ZDZCCADC/Models/Users/IUser.cs
using System;
namespace ZDZCCADC.Models.Users
{
public interface IUser
{
int AccessFailedCount { get; set; }
string ConcurrencyStamp { get; set; }
string Email { get; set; }
bool EmailConfirmed { get; set; }
string FirstName { get; set; }
string Id { get; set; }
string LastName { get; set; }
bool LockoutEnabled { get; set; }
DateTimeOffset? LockoutEnd { get; set; }
string MiddleName { get; set; }
string NormalizedEmail { get; set; }
string NormalizedUserName { get; set; }
string PhoneNumber { get; set; }
bool PhoneNumberConfirmed { get; set; }
string SecurityStamp { get; set; }
bool TwoFactorEnabled { get; set; }
string UserName { get; set; }
}
}<file_sep>/ZDZCCADC/Models/Users/User.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace ZDZCCADC.Models.Users
{
[Table("AspNetUsers",Schema ="dbo")]
public class User : IUser
{
public string Id { get; set; }
public int AccessFailedCount { get; set; }
public string ConcurrencyStamp { get; set; }
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public bool LockoutEnabled { get; set; }
public DateTimeOffset? LockoutEnd { get; set; }
public string NormalizedEmail { get; set; }
public string NormalizedUserName { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public string SecurityStamp { get; set; }
public bool TwoFactorEnabled { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
}
}
<file_sep>/ZDZCCADC/Models/ClaimsPrincipalExtension.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace ZDZCCADC.ClaimsPrincipalExtension
{
public static class ClaimsPrincipalExtension
{
/// <summary>
/// Get the First Name of the user.
/// </summary>
/// <param name="principal"></param>
/// <returns></returns>
public static string GetFirstName(this ClaimsPrincipal principal)
{
var firstName = principal.Claims.FirstOrDefault(c => c.Type == "FirstName");
return firstName?.Value;
}
public static string GetClaimValue(this ClaimsPrincipal principal, string ClaimType)
{
var firstName = principal.Claims.FirstOrDefault(c => c.Type == ClaimType );
return firstName?.Value;
}
//public static void AddUpdateClaim(this ClaimsPrincipal principal, string key, string value ) {
// //var identity = principal.Identity as ClaimsIdentity;
// //identity.AddClaim(new Claim(key, value));
// //await _userManager.AddClaimAsync(user, new Claim("FirstName", user.FirstName));
//}
}
}
<file_sep>/ZDZCCADC/Models/UserRoles/UserRolesView.cs
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ZDZCCADC.Models.UserRoles
{
public class UserRolesView : IUserRolesView
{
public SelectList Users { get; set; }
public SelectList Roles { get; set; }
public string User { get; set; }
public string Role { get; set; }
}
}
<file_sep>/ZDZCCADC/Models/UserRoles/IListUserRolesView.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ZDZCCADC.Models.UserRoles
{
public interface IListUserRolesView
{
string User { get; set; }
string Role { get; set; }
}
}
<file_sep>/ZDZCCADC/Models/UserRoles/IUserRolesView.cs
using Microsoft.AspNetCore.Mvc.Rendering;
namespace ZDZCCADC.Models.UserRoles
{
public interface IUserRolesView
{
SelectList Roles { get; set; }
SelectList Users { get; set; }
string User { get; set; }
string Role { get; set; }
}
}<file_sep>/ZDZCCADC/Data/ApplicationDbContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using ZDZCCADC.Models;
using ZDZCCADC.Models.Users;
using ZDZCCADC.Models.Roles;
using ZDZCCADC.UserRoles;
using ZDZCCADC.Models.UserRoles;
using Microsoft.EntityFrameworkCore.Metadata;
namespace ZDZCCADC.Data
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public new DbSet<User> Users { get; set; }
public new DbSet<Role> Roles{get;set;}
public new DbSet<UserRole> UserRoles{ get; set; }
public DbSet<ListUserRolesView> UserRolesViews { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
//modelBuilder.Entity<Department>().HasKey(t => new { t.DepartmentID, t.Name });
builder.Entity<UserRole>().HasKey(t => new { t.RoleId, t.UserId });
builder.Entity<ListUserRolesView>().HasKey(t => new { t.Role, t.User});
builder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("ZDZCCADC.Models.ApplicationRole")
.WithMany("Users")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("ZDZCCADC.Models.ApplicationUser")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
<file_sep>/ZDZCCADC/Repositories/BaseRepository.cs
using ZDZCCADC.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using ZDZCCADC.Data;
namespace ZDZCCADC.Repositories
{
public abstract class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
protected DbSet<TEntity> DbSet;
//protected IDbSet<TEntity> IDbSet;
protected readonly ApplicationDbContext _dbContext;
public BaseRepository(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
DbSet = _dbContext.Set<TEntity>();
}
public virtual IQueryable<TEntity> GetAll()
{
return DbSet;
}
public virtual async Task<TEntity> FindAsync(string id)
{
return await DbSet.FindAsync(id);
}
public virtual async Task<TEntity> FindAsync(int? id)
{
return await DbSet.FindAsync(id);
}
public virtual IQueryable<TEntity> Find(Expression<Func<TEntity, bool>> predicate)
{
return DbSet.Where(predicate);
}
public virtual void Update(TEntity entity)
{
_dbContext.Entry(entity).State= EntityState.Modified;
}
public virtual void Insert(TEntity entity)
{
DbSet.Add(entity);
//await _dbContext.SaveChangesAsync();
}
public virtual void Delete(TEntity entity)
{
DbSet.Attach(entity);
DbSet.Remove(entity);
//await _dbContext.SaveChangesAsync();
}
public virtual async Task SaveChangesAsync() {
await _dbContext.SaveChangesAsync();
}
public virtual IQueryable<TEntity> FromSql(string sql)
{
return DbSet.FromSql(sql);
}
}
}
<file_sep>/ZDZCCADC/Controllers/UserRolesController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ZDZCCADC.Models;
using ZDZCCADC.Models.Roles;
using ZDZCCADC.Models.UserRoles;
using ZDZCCADC.Models.Users;
using ZDZCCADC.Repositories;
using ZDZCCADC.UserRoles;
namespace ZDZCCADC.Controllers
{
public class UserRolesController : Controller
{
private IRepository<User> _users;
private IUserRolesView _view;
private IRepository<Role> _roles;
private IRepository<UserRole> userRole;
private IRepository<ListUserRolesView> userRolesView;
private readonly UserManager<ApplicationUser> _userManager;
private IList<UserRolesView> lstUserRoles;
private readonly RoleManager<ApplicationRole> roleManager;
public UserRolesController(IRepository<User> user, IUserRolesView view , IRepository<Role> roles
, UserManager<ApplicationUser> userManager
, IRepository<UserRole> userRole
, IList<UserRolesView> lstUserRoles
, IRepository<ListUserRolesView> userRolesView
, RoleManager<ApplicationRole> roleManager)
{
_users = user;
_view = view;
_roles = roles;
_userManager = userManager;
this.userRole = userRole;
this.lstUserRoles = lstUserRoles;
this.userRolesView = userRolesView;
this.roleManager = roleManager;
}
//public IActionResult Index()
//{
// //var userRoles = userRole.GetAll();
// //foreach (var u in userRoles) {
// // var role = _roles.Find(r => r.Id == u.RoleId);
// // var user = _users.Find(r => r.Id == u.UserId);
// // _view.Role = role.FirstOrDefault().Name;
// // _view.User = user.FirstOrDefault().UserName;
// // lstUserRoles.Add(_view as UserRolesView);
// //}
// var result = userRolesView.FromSql("SELECT u.UserName [User], r.Name [Role] FROM AspNetUserRoles ur INNER JOIN AspNetUsers u ON u.Id= ur.UserId INNER JOIN AspNetRoles r on r.Id = ur.RoleId ORDER BY u.UserName");
// return View(result);
//}
[HttpGet]
[Authorize(Roles="Super Admin")]
public IActionResult Index()
{
List<ApplicationRoleListViewModel> model = new List<ApplicationRoleListViewModel>();
var users = userRole.GetAll().ToList();
var roles = roleManager.Roles.Select(r => new ApplicationRoleListViewModel
{
RoleName = r.Name,
Id = r.Id,
Description = r.Description
//,NumberOfUsers = //users.Select(rs => rs.RoleId== r.Id).Count() //r.Users.Count
}).ToList();
foreach (var item in roles) {
model.Add(new ApplicationRoleListViewModel {
Description= item.Description
, Id = item.Id
, NumberOfUsers = users.Where(u=>u.RoleId == item.Id).Count()
,RoleName = item.RoleName
});
}
return View(model);
}
//public IActionResult Create() {
// var users = _users.GetAll().Select(x => new { Id = x.UserName, Value = x.UserName });
// var roles = _roles.GetAll().Select(x => new { Id = x.Name, Value = x.Name });
// _view.Users = new SelectList(users, "Id", "Value");
// _view.Roles = new SelectList(roles, "Id", "Value");
// lstUserRoles.Add(_view as UserRolesView);
// return View(_view);
//}
//[HttpPost]
//[ValidateAntiForgeryToken]
//public async Task<IActionResult > Create(UserRolesView model) {
// if (model.User != "" && model.Role != "") {
// var usr = await _userManager.FindByNameAsync(model.User);
// await _userManager.AddToRoleAsync(usr, model.Role);
// }
// return RedirectToAction("Create");
//}
[HttpGet]
[Authorize(Roles = "Super Admin")]
public async Task<IActionResult> AddEditApplicationRole(string id)
{
ApplicationRoleViewModel model = new ApplicationRoleViewModel();
if (!String.IsNullOrEmpty(id))
{
ApplicationRole applicationRole = await roleManager.FindByIdAsync(id);
if (applicationRole != null)
{
model.Id = applicationRole.Id;
model.RoleName = applicationRole.Name;
model.Description = applicationRole.Description;
}
}
return PartialView("_AddEditApplicationRole", model);
}
[HttpPost]
[Authorize(Roles = "Super Admin")]
public async Task<IActionResult> AddEditApplicationRole(string id, ApplicationRoleViewModel model)
{
if (ModelState.IsValid)
{
bool isExist = !String.IsNullOrEmpty(id);
ApplicationRole applicationRole = isExist ? await roleManager.FindByIdAsync(id) :
new ApplicationRole
{
CreatedDate = DateTime.UtcNow
};
applicationRole.Name = model.RoleName;
applicationRole.Description = model.Description;
applicationRole.IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();
IdentityResult roleRuslt = isExist ? await roleManager.UpdateAsync(applicationRole)
: await roleManager.CreateAsync(applicationRole);
if (roleRuslt.Succeeded)
{
return RedirectToAction("Index");
}
}
return View(model);
}
public async Task<IActionResult> DeleteApplicationRole(string id)
{
string name = string.Empty;
if (!String.IsNullOrEmpty(id))
{
ApplicationRole applicationRole = await roleManager.FindByIdAsync(id);
if (applicationRole != null)
{
name = applicationRole.Name;
}
}
return PartialView("_DeleteApplicationRole", name);
}
[HttpPost]
public async Task<IActionResult> DeleteApplicationRole(string id, IFormCollection form)
{
if (!String.IsNullOrEmpty(id))
{
ApplicationRole applicationRole = await roleManager.FindByIdAsync(id);
if (applicationRole != null)
{
IdentityResult roleRuslt = roleManager.DeleteAsync(applicationRole).Result;
if (roleRuslt.Succeeded)
{
return RedirectToAction("Index");
}
}
}
return View();
}
}
}
|
e228de33a51f652505581019f824c8be72cb6427
|
[
"C#"
] | 17
|
C#
|
vbmaster/ZDZ-React-POC
|
cea643933ac0d818d85634b42c9ddee7086f7dbd
|
e36ff72aaa68e0a29d71458ce441a3c8e218183e
|
refs/heads/master
|
<repo_name>JeanFelipe23/AndroidStudioProjects<file_sep>/app/src/main/java/felipe/jean/jokenpo/MainActivity.kt
package felipe.jean.jokenpo
import android.media.MediaPlayer
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.content.ContextCompat
import felipe.jean.jokenpo.R.string.*
import kotlinx.android.synthetic.main.activity_main.*
import java.util.Random
class MainActivity : AppCompatActivity() {
//Dizendo que a variavel Numero Aleatorio puxa o Random e inicia setada como null(Nulo)
private var numeroAleatorio: Random? = null
//Setar variaveis antes do Override Fun
private val PEDRA = 1
private val PAPEL = 2
private val TESOURA = 3
private fun realizarJogada(JogadaPlayer:Int){
//Criando uma variavel player para buscar o som na pasta Raw
val player = MediaPlayer.create(this,R.raw.jokenpo)
//Startando a Funcion
player.start()
val jogadaPC = numeroAleatorio!!.nextInt(3)+1
when (jogadaPC){
PEDRA -> {
ivjogadaPC.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.pedra))
when (JogadaPlayer){
PAPEL -> venceu()
PEDRA -> empatou()
TESOURA -> perdeu()
}
}
PAPEL -> {
ivjogadaPC.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.papel))
when (JogadaPlayer) {
PAPEL -> empatou()
PEDRA -> venceu()
TESOURA -> perdeu()
}
}
TESOURA -> {
ivjogadaPC.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tesoura))
when (JogadaPlayer){
PAPEL -> venceu()
PEDRA -> perdeu()
TESOURA -> empatou()
}
}
}
}
private fun venceu(){
tvResultado!!.text = getString(R.string.venceu)
tvResultado!!.setTextColor(ContextCompat.getColor(this,R.color.vitoria))
}
private fun perdeu(){
tvResultado!!.text = getString(R.string.perdeu)
tvResultado!!.setTextColor(ContextCompat.getColor(this,R.color.derrota))
}
private fun empatou(){
tvResultado!!.text = getString(R.string.empatou)
tvResultado!!.setTextColor(ContextCompat.getColor(this,R.color.empate))
}
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
numeroAleatorio = Random()
//Estou dizendo que ao tocar no ImagePedra Gera uma açao de
ivPedra.setOnClickListener {
//Ao iniciar a açao de jogar a programaçao ira procurar
// A imagem do objeto escolhido em Drawable
ivjogadaPlayer!!.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.pedra))
realizarJogada(PEDRA)
}
ivPapel.setOnClickListener {
ivjogadaPlayer!!.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.papel))
realizarJogada(PAPEL)
}
ivPedra.setOnClickListener {
ivjogadaPlayer!!.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tesoura))
realizarJogada(TESOURA)
}
}
}
|
d4469e7558ba149e98895306af090add2e907d1b
|
[
"Kotlin"
] | 1
|
Kotlin
|
JeanFelipe23/AndroidStudioProjects
|
6a57c3ad94b744aeedb82bf09c2756b3d48bbebf
|
64258b1410febf2b40eb53cacad360b46aecae9d
|
refs/heads/master
|
<repo_name>panduit-suu/MCDLink<file_sep>/README.md
"# MCDLink"
<file_sep>/MCDLink/MCDLink.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace MCDLink
{
public partial class MCDLink : Form
{
public MCDLink()
{
InitializeComponent();
}
DirectoryInfo dinfo;
public class MyPanel : Panel
{
public MyPanel()
{
SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
}
protected override void OnPaint(PaintEventArgs e)
{
using (SolidBrush brush = new SolidBrush(BackColor))
{
e.Graphics.FillRectangle(brush, ClientRectangle);
}
e.Graphics.DrawRectangle(Pens.Blue, 0, 0, ClientSize.Width - 1, ClientSize.Height - 1);
}
}
public class cbxOperation
{
public string Text { get; set; }
public string Value { get; set; }
public override string ToString()
{
return Text;
}
}
private void MCDLink_Load(object sender, EventArgs e)
{
try
{
Load_cboOperations();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error in MCDLink_Load()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Load_cboOperations()
{
try
{
cboOperations.Items.Clear();
cbxOperation op = new cbxOperation();
op.Text = "Die Sink";
op.Value = "M";//Why not D?
cboOperations.Items.Add(op);
op = new cbxOperation();
op.Text = "Grinding";
op.Value = "G";
cboOperations.Items.Add(op);
op = new cbxOperation();
op.Text = "Heat Treat";
op.Value = "H";
cboOperations.Items.Add(op);
op = new cbxOperation();
op.Text = "Honing";
op.Value = "N";
cboOperations.Items.Add(op);
op = new cbxOperation();
op.Text = "Inspection";
op.Value = "I";
cboOperations.Items.Add(op);
op = new cbxOperation();
op.Text = "Jig Grind";
op.Value = "J";
cboOperations.Items.Add(op);
op = new cbxOperation();
op.Text = "Manual Grind";
op.Value = "R";
cboOperations.Items.Add(op);
op = new cbxOperation();
op.Text = "Manual Operation";
op.Value = "O";
cboOperations.Items.Add(op);
op = new cbxOperation();
op.Text = "Milling";
op.Value = "M";
cboOperations.Items.Add(op);
cboOperations.SelectedItem = op;
op = new cbxOperation();
op.Text = "Polish";
op.Value = "P";
cboOperations.Items.Add(op);
op = new cbxOperation();
op.Text = "Turning";
op.Value = "T";
cboOperations.Items.Add(op);
op = new cbxOperation();
op.Text = "Vended";
op.Value = "V";
cboOperations.Items.Add(op);
op = new cbxOperation();
op.Text = "Wire";
op.Value = "W";
cboOperations.Items.Add(op);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error in Load_cboOperations()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnShowFiles_Click(object sender, EventArgs e)
{
try
{
ShowFiles();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error in btnShowFiles_Click()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
Add();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error in btnAdd_Click()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnRemove_Click(object sender, EventArgs e)
{
try
{
FileInfo[] removeFiles = new FileInfo[lbLinkList.Items.Count];
FileInfo selFile;
int i = 0;
foreach (FileInfo selItem in lbLinkList.SelectedItems)
{
selFile = selItem as FileInfo;
removeFiles.SetValue(selFile, i);
i++;
}
foreach (FileInfo file in removeFiles)
{
lbLinkList.Items.Remove(file);
}
CheckButtonStatus();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error in btnRemove_Click()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnLink_Click(object sender, EventArgs e)
{
try
{
FileInfo addFile;
//SET THE NAME OF THE NEW FILE
string sNewFile = "";
string fileName = "";
int fCount = 0;
bool bFnd = false;
while (!bFnd)
{
fCount++;
fileName = "LINK" + fCount.ToString() + ".MCD";
sNewFile = dinfo.ToString() + "\\" + fileName;
if (!File.Exists(sNewFile))
bFnd = true;
}
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = dinfo.ToString().ToUpper();
sfd.FileName=sNewFile.ToUpper();
sfd.Filter = "Linked Files| *.mcd";
if(sfd.ShowDialog() == DialogResult.Cancel)
return;
//LOOP THRU THE SELECTED FILES AND MERGE THEM
int iFileCount = 0;
using (StreamWriter writer = File.CreateText(sfd.FileName.ToUpper()))
{
foreach (Object myItem in lbLinkList.Items)
{
addFile = myItem as FileInfo;
int lnNmStrt=0;
int lnNmStp = 2;
if (iFileCount != 0) //LINE TO START AT
lnNmStrt = 1;
if (lbLinkList.Items.Count == iFileCount + 1)//LINE TO STOP AT
lnNmStp = 0;
string[] fLines = File.ReadAllLines(addFile.FullName);
while (lnNmStrt < fLines.Length-lnNmStp)
{
writer.WriteLine(fLines[lnNmStrt]);
lnNmStrt++;
}
iFileCount++;
}
}
MessageBox.Show("The Linked Filename is " + fileName , "SUCCESS", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error in btnLink_Click()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnExit_Click(object sender, EventArgs e)
{
try
{
this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error in btnExit_Click()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void lbFileList_DoubleClick(object sender, System.EventArgs e)
{
try
{
Add();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "lbFileList_DoubleClick()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void txtItemID_TextChanged(object sender, System.EventArgs e)
{
if (txtItemID.Text.Length > 6)
btnShowFiles.Enabled = true;
else
btnShowFiles.Enabled = false;
}
private void txtItemID_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
ShowFiles();
}
private void lbLinkList_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
try
{
//if (lbLinkList.SelectedItems.Count!=1)
// return;
if (e.KeyValue == 38 && e.Modifiers == Keys.Control)//ARROW UP
{
MoveUp(lbLinkList);
}
if (e.KeyValue == 40 && e.Modifiers == Keys.Control)//ARROW DOWN
{
MoveDown(lbLinkList);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "lbLinkList_KeyPress", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ShowFiles()
{
try
{
txtItemID.Enabled = false;
lblSourceItem.Text = "";
//CLEAR THE LISTS
lbFileList.Items.Clear();
lbLinkList.Items.Clear();
CheckButtonStatus();
if ((txtItemID.Text.Length == 0) || (txtItemID.Text.Length > 12) || (txtItemID.Text.Length < 7))
{
txtItemID.Enabled = true;
return;
}
//GET THE SELECTED OPERATION
cbxOperation selOper = (cbxOperation)cboOperations.SelectedItem;
//GET THE FILES FROM THE DIRECTORY
dinfo = new DirectoryInfo(@"C:\DNC\" + txtItemID.Text + "\\" + selOper.Value);
FileInfo[] NCFiles = dinfo.GetFiles("*.nc");
FileInfo[] MCDFiles = dinfo.GetFiles("*.mcd");
foreach (FileInfo file in NCFiles)
{
if(!file.Name.ToUpper().Contains("LINK"))
lbFileList.Items.Add(file);
}
foreach (FileInfo file in MCDFiles)
{
if (!file.Name.ToUpper().Contains("LINK"))
lbFileList.Items.Add(file);
}
lblSourceItem.Text = txtItemID.Text;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error in ShowFiles()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
txtItemID.Enabled = true;
CheckButtonStatus();
}
private void Add()
{
try
{
FileInfo selFile;
foreach (Object selItem in lbFileList.SelectedItems)
{
selFile = selItem as FileInfo;
if (!lbLinkList.Items.Contains(selFile))
{
lbLinkList.Items.Add(selFile);
}
}
CheckButtonStatus();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error in Add()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CheckButtonStatus()
{
try
{
if (lbFileList.Items.Count == 0)
btnAdd.Enabled = false;
else
btnAdd.Enabled = true;
switch (lbLinkList.Items.Count)
{
case 0:
btnRemove.Enabled = false;
btnLink.Enabled = false;
break;
case 1:
btnRemove.Enabled = true;
btnLink.Enabled = false;
break;
default:
btnRemove.Enabled = true;
btnLink.Enabled = true;
break;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "CheckButtonStatus()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void MoveUp(ListBox listBox)
{
try
{
listBox.BeginUpdate();
int numberOfSelectedItems = listBox.SelectedItems.Count;
for (int i = 0; i < numberOfSelectedItems; i++)
{
// only if it's not the first item
if (listBox.SelectedIndices[i] > 0)
{
// the index of the item above the item that we wanna move up
int indexToInsertIn = listBox.SelectedIndices[i] - 1;
// insert UP the item that we want to move up
listBox.Items.Insert(indexToInsertIn, listBox.SelectedItems[i]);
// removing it from its old place
listBox.Items.RemoveAt(indexToInsertIn + 2);
// highlighting it in its new place
listBox.SelectedItem = listBox.Items[indexToInsertIn];
}
}
listBox.EndUpdate();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error in MoveUp()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void MoveDown(ListBox listBox)
{
try
{
listBox.BeginUpdate();
int numberOfSelectedItems = listBox.SelectedItems.Count;
// when going down, instead of moving through the selected items from top to bottom
// we'll go from bottom to top, it's easier to handle this way.
for (int i = numberOfSelectedItems - 1; i >= 0; i--)
{
// only if it's not the last item
if (listBox.SelectedIndices[i] < listBox.Items.Count - 1)
{
// the index of the item that is currently below the selected item
int indexToInsertIn = listBox.SelectedIndices[i] + 2;
// insert DOWN the item that we want to move down
listBox.Items.Insert(indexToInsertIn, listBox.SelectedItems[i]);
// removing it from its old place
listBox.Items.RemoveAt(indexToInsertIn - 2);
// highlighting it in its new place
listBox.SelectedItem = listBox.Items[indexToInsertIn - 1];
}
}
listBox.EndUpdate();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error in MoveDown()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void MCDLink_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
try
{
txtTip.Text = "MCD Linker";
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error in MCDLink_MouseMove()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void lbLinkList_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
try
{
txtTip.Text = "Press Ctrl-Up or Ctrl-Down to change place of selcected file.";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error in lbLinkList_MouseMove()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void lbFileList_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
try
{
txtTip.Text = "Double-Click on a file, or press 'Add' to Place it the Link List.";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error in lbFileList_MouseMove", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
|
d548c922064d50178d1bccdf99642d64251f0507
|
[
"Markdown",
"C#"
] | 2
|
Markdown
|
panduit-suu/MCDLink
|
22e992b2dbdc35c869ea97962c272e3356d2198c
|
51271078015e6ee2fa44a845ab1e9d180287b6ff
|
refs/heads/master
|
<file_sep>package com.bit;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Base {
WebDriver dr;
@Before
public void openBrowser() {
System.setProperty("webdriver.chrome.driver", "/Users/jarrellsimon/Downloads/chromedriver");
dr = new ChromeDriver();
dr.get("https://www.bestbuy.com/");
}
@After
public void closeBrowser() {
//dr.quit();
}
}
<file_sep>package com.bit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class Utility {
WebDriver dr;
Utility(WebDriver d) {
this.dr = d;
}
public void type() {
dr.findElement(By.xpath("//*[@id=\"menu0\"]")).click();
dr.findElement(By.xpath("//*[@id=\"group0\"]/div[1]/div[1]/ul/li[4]/a")).click();
//dr.findElement(By.xpath("//*[@id=\"gh-search-input\"]")).sendKeys("iphone x");
//dr.findElement(By.xpath("//*[@id=\"header\"]/div[1]/div[2]/div[2]/form/button[2]/span")).click();
}
}
|
4c2cf6dc4e03f8d66f1ed153cb94174fd5f14423
|
[
"Java"
] | 2
|
Java
|
kawsarusa/hi
|
b241766cdb34bdf267f9e85ea8b165bcb57a5488
|
3b4e72a4cb067aa71193d8ec4b0bada92497dafc
|
refs/heads/main
|
<repo_name>dhruvesh0910/Mini_LinkedIn<file_sep>/Models/WorkExperience.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace mini_linkedIn.Models
{
public class WorkExperience
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Key]
public int WorkID { get; set; }
public string Position { get; set; }
public string Area { get; set; }
public int StartYear { get; set; }
public int EndYear { get; set; }
public int YearOfExperience { get; set; }
public string Description { get; set; }
public int UserID { get; set; }
public User user { get; set; }
public ICollection<Reference> References { get; set; }
}
}
<file_sep>/Models/Education.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace mini_linkedIn.Models
{
public class Education
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int EducationID { get; set; }
public string Title { get; set; }
public string CollegeName { get; set; }
public double GPA { get; set; }
public int StartYear { get; set; }
public int EndYear { get; set; }
public int UserID { get; set; }
public User user { get; set; }
}
}
<file_sep>/Controllers/WorkExperiencesController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using mini_linkedIn.Data;
using mini_linkedIn.Models;
namespace mini_linkedIn.Controllers
{
public class WorkExperiencesController : Controller
{
private readonly LinkedInContext _context;
public WorkExperiencesController(LinkedInContext context)
{
_context = context;
}
// GET: WorkExperiences
public async Task<IActionResult> Index()
{
var linkedInContext = _context.WorkExperiences.Include(w => w.user);
return View(await linkedInContext.ToListAsync());
}
// GET: WorkExperiences/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var workExperience = await _context.WorkExperiences
.Include(w => w.user)
.FirstOrDefaultAsync(m => m.WorkID == id);
if (workExperience == null)
{
return NotFound();
}
return View(workExperience);
}
// GET: WorkExperiences/Create
public IActionResult Create()
{
ViewData["UserID"] = new SelectList(_context.Users, "UserID", "UserID");
return View();
}
// POST: WorkExperiences/Create
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("WorkID,Position,Area,StartYear,EndYear,YearOfExperience,Description,UserID")] WorkExperience workExperience)
{
if (ModelState.IsValid)
{
_context.Add(workExperience);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["UserID"] = new SelectList(_context.Users, "UserID", "UserID", workExperience.UserID);
return View(workExperience);
}
// GET: WorkExperiences/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var workExperience = await _context.WorkExperiences.FindAsync(id);
if (workExperience == null)
{
return NotFound();
}
ViewData["UserID"] = new SelectList(_context.Users, "UserID", "UserID", workExperience.UserID);
return View(workExperience);
}
// POST: WorkExperiences/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("WorkID,Position,Area,StartYear,EndYear,YearOfExperience,Description,UserID")] WorkExperience workExperience)
{
if (id != workExperience.WorkID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(workExperience);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!WorkExperienceExists(workExperience.WorkID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["UserID"] = new SelectList(_context.Users, "UserID", "UserID", workExperience.UserID);
return View(workExperience);
}
// GET: WorkExperiences/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var workExperience = await _context.WorkExperiences
.Include(w => w.user)
.FirstOrDefaultAsync(m => m.WorkID == id);
if (workExperience == null)
{
return NotFound();
}
return View(workExperience);
}
// POST: WorkExperiences/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var workExperience = await _context.WorkExperiences.FindAsync(id);
_context.WorkExperiences.Remove(workExperience);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool WorkExperienceExists(int id)
{
return _context.WorkExperiences.Any(e => e.WorkID == id);
}
}
}
<file_sep>/Models/Project.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace mini_linkedIn.Models
{
public class Project
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ProjectID { get; set; }
public string Title { get; set; }
public string TechnologyUsed { get; set; }
public string LanguageUsed { get; set; }
public int StartYear { get; set; }
public int EndYear { get; set; }
public string Description { get; set; }
public int UserID { get; set; }
public User user { get; set; }
}
}
<file_sep>/Models/User.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace mini_linkedIn.Models
{
public class User
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
//[Key]
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string PassWord { get; set; }
public long MobileNo { get; set; }
public string EmailID { get; set; }
public ICollection<WorkExperience> WorkExperiences { get; set; }
public ICollection<Education> Educations { get; set; }
public ICollection<Achievement> Achievements { get; set; }
public ICollection<Project> Projects { get; set; }
public ICollection<Interest> Interests { get; set; }
}
}
<file_sep>/Controllers/InterestsController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using mini_linkedIn.Data;
using mini_linkedIn.Models;
namespace mini_linkedIn.Controllers
{
public class InterestsController : Controller
{
private readonly LinkedInContext _context;
public InterestsController(LinkedInContext context)
{
_context = context;
}
// GET: Interests
public async Task<IActionResult> Index()
{
var linkedInContext = _context.Interests.Include(i => i.user);
return View(await linkedInContext.ToListAsync());
}
// GET: Interests/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var interest = await _context.Interests
.Include(i => i.user)
.FirstOrDefaultAsync(m => m.HobbyID == id);
if (interest == null)
{
return NotFound();
}
return View(interest);
}
// GET: Interests/Create
public IActionResult Create()
{
ViewData["UserID"] = new SelectList(_context.Users, "UserID", "UserID");
return View();
}
// POST: Interests/Create
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("HobbyID,Name,UserID")] Interest interest)
{
if (ModelState.IsValid)
{
_context.Add(interest);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["UserID"] = new SelectList(_context.Users, "UserID", "UserID", interest.UserID);
return View(interest);
}
// GET: Interests/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var interest = await _context.Interests.FindAsync(id);
if (interest == null)
{
return NotFound();
}
ViewData["UserID"] = new SelectList(_context.Users, "UserID", "UserID", interest.UserID);
return View(interest);
}
// POST: Interests/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("HobbyID,Name,UserID")] Interest interest)
{
if (id != interest.HobbyID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(interest);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!InterestExists(interest.HobbyID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["UserID"] = new SelectList(_context.Users, "UserID", "UserID", interest.UserID);
return View(interest);
}
// GET: Interests/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var interest = await _context.Interests
.Include(i => i.user)
.FirstOrDefaultAsync(m => m.HobbyID == id);
if (interest == null)
{
return NotFound();
}
return View(interest);
}
// POST: Interests/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var interest = await _context.Interests.FindAsync(id);
_context.Interests.Remove(interest);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool InterestExists(int id)
{
return _context.Interests.Any(e => e.HobbyID == id);
}
}
}
<file_sep>/Data/LinkedInContext.cs
using Microsoft.EntityFrameworkCore;
using mini_linkedIn.Models;
namespace mini_linkedIn.Data
{
public class LinkedInContext : DbContext
{
public LinkedInContext(DbContextOptions<LinkedInContext> options) : base(options)
{
}
public DbSet<Achievement> Achievements { get; set; }
public DbSet<Education> Educations { get; set; }
public DbSet<Interest> Interests { get; set; }
public DbSet<Project> Projects { get; set; }
public DbSet<Reference> References { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<WorkExperience> WorkExperiences { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Achievement>().ToTable("Achievement");
modelBuilder.Entity<Education>().ToTable("Education");
modelBuilder.Entity<Interest>().ToTable("Interest");
modelBuilder.Entity<Project>().ToTable("Project");
modelBuilder.Entity<Reference>().ToTable("Reference");
modelBuilder.Entity<User>().ToTable("User");
modelBuilder.Entity<WorkExperience>().ToTable("WorkExperience");
}
}
}
<file_sep>/Data/DbInitializer.cs
using mini_linkedIn.Models;
using System;
using System.Linq;
namespace mini_linkedIn.Data
{
public static class DbInitializer
{
public static void Initialize(LinkedInContext context)
{
context.Database.EnsureCreated();
// Look for any students.
if (context.WorkExperiences.Any())
{
return; // DB has been seeded
}
var users = new User[]
{
new User{UserID=100, FirstName="Dhruvesh", LastName="Patel", UserName="pate2306", PassWord="<PASSWORD>", MobileNo=9999999999, EmailID="<EMAIL>"},
new User{UserID=101, FirstName="Dhruvesh", LastName="Patel", UserName="pate2306", PassWord="<PASSWORD>", MobileNo=9999999999, EmailID="<EMAIL>"},
new User{UserID=102, FirstName="Dhruvesh", LastName="Patel", UserName="pate2306", PassWord="<PASSWORD>", MobileNo=9999999999, EmailID="<EMAIL>"},
new User{UserID=103, FirstName="Dhruvesh", LastName="Patel", UserName="pate2306", PassWord="<PASSWORD>", MobileNo=9999999999, EmailID="<EMAIL>"},
new User{UserID=104, FirstName="Dhruvesh", LastName="Patel", UserName="pate2306", PassWord="<PASSWORD>", MobileNo=9999999999, EmailID="<EMAIL>"},
new User{UserID=105, FirstName="Dhruvesh", LastName="Patel", UserName="pate2306", PassWord="<PASSWORD>", MobileNo=9999999999, EmailID="<EMAIL>"},
};
foreach (User user in users)
{
context.Users.Add(user);
}
context.SaveChanges();
var WorkExperineces = new WorkExperience[]
{
new WorkExperience{WorkID=1, Position="Software Developer", Area="Informatin technology", StartYear=2013, EndYear=2020, YearOfExperience=6, Description="bajsbcaj", UserID=100},
new WorkExperience{WorkID=2, Position="Software Developer", Area="Informatin technology", StartYear=2013, EndYear=2020, YearOfExperience=6, Description="bajsbcaj", UserID=100},
new WorkExperience{WorkID=3, Position="Software Developer", Area="Informatin technology", StartYear=2013, EndYear=2020, YearOfExperience=6, Description="bajsbcaj", UserID=100},
new WorkExperience{WorkID=4, Position="Software Developer", Area="Informatin technology", StartYear=2013, EndYear=2020, YearOfExperience=6, Description="bajsbcaj", UserID=100},
new WorkExperience{WorkID=5, Position="Software Developer", Area="Informatin technology", StartYear=2013, EndYear=2020, YearOfExperience=6, Description="bajsbcaj", UserID=100},
new WorkExperience{WorkID=6, Position="Software Developer", Area="Informatin technology", StartYear=2013, EndYear=2020, YearOfExperience=6, Description="bajsbcaj", UserID=100}
};
foreach (WorkExperience we in WorkExperineces)
{
context.WorkExperiences.Add(we);
}
context.SaveChanges();
var educations = new Education[]
{
new Education{EducationID=1, Title="Computer Programmer - Diploma", CollegeName="Sheridan College", GPA=3.9, StartYear=2020, EndYear=2021, UserID=100},
new Education{EducationID=2, Title="Chemical Laboratory Technician - Diploma", CollegeName="Georgian College", GPA=2.9, StartYear=2020, EndYear=2021, UserID=101},
new Education{EducationID=3, Title="Computer System Technician - Diploma", CollegeName="Sheridan College", GPA=3.1, StartYear=2020, EndYear=2021, UserID=102 },
new Education{EducationID=4, Title="Computer Programmer - Diploma", CollegeName="Humber College", GPA=4.0, StartYear=2020, EndYear=2021, UserID=102},
new Education{EducationID=5, Title="Mobile Application Development - Diploma", CollegeName="Seneca College", GPA=3.68, StartYear=2020, EndYear=2021, UserID=101}
};
foreach (Education education in educations)
{
context.Educations.Add(education);
}
context.SaveChanges();
var references = new Reference[]
{
new Reference{RefID=1, Name="<NAME>", CompanyName="JetAsprin", Role="Managing Junior Project Leaders", Position="Senior Project Manager", EmailID="<EMAIL>", WorkID=1},
new Reference{RefID=2, Name="<NAME>", CompanyName="JetAsprin", Role="Managing Junior Project Leaders", Position="Senior Project Manager", EmailID="<EMAIL>", WorkID=2},
new Reference{RefID=3, Name="<NAME>", CompanyName="JetAsprin", Role="Managing Junior Project Leaders", Position="Senior Project Manager", EmailID="<EMAIL>", WorkID=1},
new Reference{RefID=4, Name="<NAME>", CompanyName="JetAsprin", Role="Managing Junior Project Leaders", Position="Senior Project Manager", EmailID="<EMAIL>", WorkID=3},
new Reference{RefID=5, Name="<NAME>", CompanyName="JetAsprin", Role="Managing Junior Project Leaders", Position="Senior Project Manager", EmailID="<EMAIL>", WorkID=4}
};
foreach (Reference reference in references)
{
context.References.Add(reference);
}
context.SaveChanges();
var achievements = new Achievement[]
{
new Achievement{AchievementID=1, Title="Academic Excellence Award",Year=2016,Description="Securing 2nd position throught year 2015 with 9.0 CPI", UserID=100},
new Achievement{AchievementID=2,Title="Academic Excellence Award",Year=2017,Description="Securing 2nd position throught year 2016 with 8.96", UserID=100},
new Achievement{AchievementID=3,Title="Academic Excellence Award",Year=2018,Description="Securing 2nd position throught year 2017 with 9.31 CGPA", UserID=100},
new Achievement{AchievementID=4,Title="Academic Excellence Award",Year=2019,Description="Securing 2nd position throught year 2018 with 9.1 CGPA", UserID=100},
new Achievement{AchievementID=5,Title="Academic Excellence Award",Year=2012,Description="Securing 1nd position throught year 2011 with 4.0 GPA", UserID=101},
new Achievement{AchievementID=6,Title="Academic Excellence Award",Year=2013,Description="Securing 1nd position throught year 2012 with 8.96", UserID=102},
new Achievement{AchievementID=7,Title="Academic Excellence Award",Year=2014,Description="Securing 3nd position throught year 2013 with 9.31 CGPA", UserID=103},
new Achievement{AchievementID=8,Title="Academic Excellence Award",Year=2020,Description="Securing 1nd position throught year 2019 with 9.1 CGPA", UserID=101},
new Achievement{AchievementID=9,Title="Academic Excellence Award",Year=2016,Description="Devang Mehta Award", UserID=105},
new Achievement{AchievementID=10,Title="Academic Excellence Award",Year=2011,Description="Securing 2nd position throught year 2010 with 8.96", UserID=104},
new Achievement{AchievementID=11,Title="Academic Excellence Award",Year=2012,Description="Securing 3nd position throught year 2011 with 9.31 CGPA", UserID=104},
new Achievement{AchievementID=12,Title="Academic Excellence Award",Year=2009,Description="Securing 2nd position throught year 2008 with 9.1 CGPA", UserID=101}
};
foreach (Achievement achievement in achievements)
{
context.Achievements.Add(achievement);
}
context.SaveChanges();
var projects = new Project[]
{
new Project{ProjectID=1, Title="Online Mall", TechnologyUsed="Android Studio, JSON Parsing", LanguageUsed="Java, Php, Volly, JSON Parse", StartYear=2017, EndYear=2017, Description="Project as a part of study", UserID=100},
new Project{ProjectID=2, Title="MediCare", TechnologyUsed="Android Studio, JSON Parsing", LanguageUsed="Java, Php, Volly, JSON Parse", StartYear=2018, EndYear=2018, Description="Project as a part of study", UserID=101},
new Project{ProjectID=3, Title="IoT based Smart Helmet for Auto Ignition and Alcohol Detection", TechnologyUsed="Android Studio, JSON Parsing", LanguageUsed="Java, Php, Volly, JSON Parse", StartYear=2019, EndYear=2019, Description="Project as a part of study", UserID=102 },
new Project{ProjectID=4, Title="Black Jack Game", TechnologyUsed="Android Studio, JSON Parsing", LanguageUsed="Java, Php, Volly, JSON Parse", StartYear=2021, EndYear=2021, Description="Project as a part of study", UserID=102},
new Project{ProjectID=5, Title="Memory Game", TechnologyUsed="Android Studio, JSON Parsing", LanguageUsed="Java, Php, Volly, JSON Parse", StartYear=2021, EndYear=2021, Description="Project as a part of study", UserID=101}
};
foreach (Project project in projects)
{
context.Projects.Add(project);
}
context.SaveChanges();
var interests = new Interest[]
{
new Interest{HobbyID=1,Name="Playing Football", UserID=100},
new Interest{HobbyID=2, Name="Reading Novel", UserID=100},
new Interest{HobbyID=3, Name="Traveling", UserID=100},
new Interest{HobbyID=4, Name="Dancing", UserID=100},
new Interest{HobbyID=5, Name="Listening Music", UserID=100}
};
foreach (Interest hobby in interests)
{
context.Interests.Add(hobby);
}
context.SaveChanges();
}
}
}
|
b570bdd80942e8f8a9e6890912bdaf7097afb259
|
[
"C#"
] | 8
|
C#
|
dhruvesh0910/Mini_LinkedIn
|
3b73567b11e15ae06574a0380c091fb3e1445f93
|
8f624049ad646586e9361faaf812fa500616e02f
|
refs/heads/master
|
<repo_name>pragmatrix/Faser<file_sep>/Faser/Formatter/MemberPath.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Faser.Formatter
{
sealed class MemberPath : IMemberPath
{
public MemberPath(IAggregatePath parent, IMemberInfo member, IEnumerable<Attribute> attributes)
{
Parent = parent;
Member = member;
Attributes = attributes;
}
public IAggregatePath Parent { get; private set; }
public IMemberInfo Member { get; private set; }
public IEnumerable<Attribute> Attributes { get; private set; }
public override string ToString()
{
return Member.ToString();
}
}
}
<file_sep>/Faser.Tests/BasicBinaryTests.cs
using Faser.Binary;
using Faser.Tests.Formatters;
using NUnit.Framework;
namespace Faser.Tests
{
[TestFixture]
public class BasicBinaryTests : SimpleBinaryFormatter
{
sealed class OneByte
{
[Offset(0)] public byte Test;
}
[Test]
public void testSimpleEncoding()
{
var test = new OneByte {Test = 0x33};
var r = Formatter.Encode(test);
Assert.That(r, Is.EquivalentTo(new byte[1]{0x33}));
}
sealed class OneByteWithOtherMembers
{
byte Test2;
[Offset(0)] public byte Test;
public byte Test3 { get; set; }
}
[Test]
public void testPropertiesAndPrivateFieldsNotSerialized()
{
var instance = new OneByteWithOtherMembers {Test = 0x44};
var r = Formatter.Encode(instance);
Assert.That(r, Is.EquivalentTo(new byte[] { 0x44 }));
}
[Test]
public void testSimpleSerialization()
{
var test = new OneByte() {Test = 0x33};
var r = encodeDecode(test);
Assert.That(r.Test, Is.EqualTo(0x33));
}
sealed class Composite
{
[Offset(0)] public uint M1;
[Offset(4)] public byte M2;
[Offset(5)] public uint M3;
}
[Test]
public void testCompositeSerialization()
{
var c = new Composite {M1 = 0x3435, M2 = 0x83, M3 = 0x2342};
var r = encodeDecode(c);
Assert.That(r.M1, Is.EqualTo(0x3435));
Assert.That(r.M2, Is.EqualTo(0x83));
Assert.That(r.M3, Is.EqualTo(0x2342));
}
sealed class RootOfNested
{
[Offset(0)] public uint M1;
[Offset(4)] public OneByte M2;
[Offset(5)] public uint M3;
}
[Test]
public void testNestedSerialization()
{
var c = new RootOfNested() { M1 = 0x3435, M2 = new OneByte { Test = 0x83 }, M3 = 0x2342 };
var r = encodeDecode(c);
Assert.That(r.M1, Is.EqualTo(0x3435));
Assert.That(r.M2.Test, Is.EqualTo(0x83));
Assert.That(r.M3, Is.EqualTo(0x2342));
}
[Size(125)]
sealed class Regression1
{
[Offset(61)]
public uint Version;
}
[Test]
public void testRegression1()
{
var c = new Regression1();
var r = encodeDecode(c);
}
T encodeDecode<T>(T instance)
{
var serialized = Formatter.Encode(instance);
return Formatter.Decode<T>(serialized);
}
}
}
<file_sep>/Faser.Binary/Core/FixedSizeEncoder.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Faser.Binary.Core
{
sealed class FixedSizeEncoder : IAggregateEncoder<IEnumerable<byte>>
{
readonly byte[] _bytes;
uint _offset;
public FixedSizeEncoder(uint size)
{
_bytes = new byte[size];
_offset = 0;
}
public void WriteMember(IMemberPath path, IEnumerable<byte> encoded)
{
Debug.Assert(path != null && encoded != null);
uint? offset = path.offset();
uint? size = path.size();
if (offset == null)
throw new FaserException(path, "Offset not specified");
if (offset > _bytes.Length)
throw new FaserException(path, "Offset out of range");
_offset = offset.Value;
var elementArray = encoded.ToArray();
var length = elementArray.Length;
if (_offset + length > _bytes.Length)
throw new FaserException(path, "Not enough space to encode member");
if (size != null)
{
if (length > size)
throw new FaserException(path, "Encoded member length exceeds size specification");
}
Array.Copy(elementArray, 0, _bytes, _offset, length);
_offset += size != null ? size.Value : (uint) length;
}
public IEnumerable<byte> Result
{
get { return _bytes; }
}
}
}
<file_sep>/Faser.Binary/Core/FlexibleSizeEncoder.cs
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace Faser.Binary.Core
{
sealed class FlexibleSizeEncoder : IAggregateEncoder<IEnumerable<byte>>
{
readonly MemoryStream _memoryStream = new MemoryStream();
public IFaserFormatter<byte> Formatter { get; private set; }
public void WriteMember(IMemberPath path, IEnumerable<byte> elements)
{
Debug.Assert(path != null && elements != null);
var elementArray = elements.ToArray();
var length = elementArray.Length;
uint? offset = path.offset();
uint? size = path.size();
if (offset == null)
throw new FaserException(path, "Offset not specified");
var o = offset.Value;
setPosition(o);
if (size != null)
{
var s = size.Value;
if (length > s)
throw new FaserException(path, "Encoded member length exceeds size specification");
}
_memoryStream.Write(elementArray, 0, length);
if (size == null)
return;
var current = _memoryStream.Position;
var end = current - length + size.Value;
setPosition(end);
}
void setPosition(long pos)
{
if (_memoryStream.Length < pos)
_memoryStream.SetLength(pos);
_memoryStream.Position = pos;
}
public IEnumerable<byte> Result
{
get { return _memoryStream.ToArray(); }
}
}
}
<file_sep>/Faser/Formatter/TypeConfiguration.cs
using System;
using System.Diagnostics;
namespace Faser.Formatter
{
sealed class TypeConfiguration<EncodedT, TypeT> : ITypeConfiguration<EncodedT, TypeT>
{
readonly FaserFormatter<EncodedT> _formatter;
public TypeConfiguration(FaserFormatter<EncodedT> formatter)
{
_formatter = formatter;
}
public ITypeConfiguration<EncodedT, TypeT> EncodeIf(Func<IMemberPath, TypeT, bool> encodeGuard)
{
Debug.Assert(encodeGuard != null);
_formatter.EncodeIf<TypeT>(encodeGuard);
return this;
}
public ITypeConfiguration<EncodedT, TypeT> DecodeIf(Func<IMemberPath, EncodedT, bool> decodeGuard)
{
Debug.Assert(decodeGuard != null);
_formatter.DecodeIf<TypeT>(decodeGuard);
return this;
}
public ITypeConfiguration<EncodedT, TypeT> Encoder(Func<IMemberPath, TypeT, EncodedT> encoder)
{
Debug.Assert(encoder != null);
_formatter.Encoder(encoder);
return this;
}
public ITypeConfiguration<EncodedT, TypeT> Decoder(Func<IMemberPath, EncodedT, TypeT> decoder)
{
Debug.Assert(decoder != null);
_formatter.Decoder(decoder);
return this;
}
public IFaserFormatter<EncodedT> End()
{
return _formatter;
}
}
}
<file_sep>/Faser.Tests/FixedSizeTests.cs
using Faser.Binary;
using Faser.Tests.Formatters;
using NUnit.Framework;
namespace Faser.Tests
{
[TestFixture]
public class FixedSizeTests : SimpleBinaryFormatter
{
[Size(10)]
sealed class OffsetExceedsSize
{
[Offset(11)]
public byte test;
}
[Test, ExpectedException(typeof(FaserException))]
public void testOffsetExceedsSize()
{
var inst = new OffsetExceedsSize();
Formatter.Encode(inst);
}
[Size(10)]
sealed class OffsetAndLengthExceedsSize
{
[Offset(10)]
public byte test;
}
[Test, ExpectedException(typeof(FaserException))]
public void testOffsetAndLengthExceedsSize()
{
var inst = new OffsetAndLengthExceedsSize();
Formatter.Encode(inst);
}
}
}
<file_sep>/Faser/Formatter/ValueConverters.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace Faser.Formatter
{
sealed class ValueConverters
{
readonly List<ValueConverter> _valueReaders = new List<ValueConverter>();
readonly List<ValueConverter> _valueWriters = new List<ValueConverter>();
public void addReader(Func<Type, Type> typeConverter, Func<object, Type, object> valueConverter)
{
_valueReaders.Add(new ValueConverter(typeConverter, valueConverter));
}
public void addWriter(Func<Type, Type> typeConverter, Func<object, Type, object> valueConverter)
{
_valueWriters.Add(new ValueConverter(typeConverter, valueConverter));
}
public ValueConverter tryResolveReader(Type type)
{
return _valueReaders.FirstOrDefault(vc => vc.ConvertType(type) != type);
}
public ValueConverter tryResolveWriter(Type type)
{
return _valueWriters.FirstOrDefault(vc => vc.ConvertType(type) != type);
}
}
sealed class ValueConverter
{
public readonly Func<Type, Type> ConvertType;
public readonly Func<object, Type, object> ConvertValue;
public ValueConverter(Func<Type, Type> convertType, Func<object, Type, object> convertValue)
{
ConvertType = convertType;
ConvertValue = convertValue;
}
}
}
<file_sep>/Faser.Tests/Formatters/SimpleTextFormatter.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace Faser.Tests.Formatters
{
public class SimpleTextFormatter
{
public IFaserFormatter<IEnumerable<char>> Formatter;
public SimpleTextFormatter()
{
var f = Faser.CreateFormatter<IEnumerable<char>>();
configureSimpleTextFormat(f);
Formatter = f;
}
protected void configureSimpleTextFormat(IFaserFormatter<IEnumerable<char>> formatter)
{
formatter
.AggregateEncoder((path, instance) => new SimpleTextEncoder())
.AggregateDecoder((path, encoded) => new SimpleTextDecoder(path, encoded));
formatter.DefaultEncoder(
(path, obj) => Convert.ToString(obj, CultureInfo.InvariantCulture));
formatter.DefaultDecoder(
(path, encoded) =>
{
var str = new string(encoded.ToArray());
var t = path.Member.Type;
return Convert.ChangeType(str, t, CultureInfo.InvariantCulture);
}
);
}
}
}
<file_sep>/Faser/FaserException.cs
using System;
using System.Diagnostics;
namespace Faser
{
/// <summary>
/// The primary exception that is throw when anything bad happens inside the Faser library.
/// </summary>
[Serializable]
public sealed class FaserException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="FaserException" /> class.
/// </summary>
/// <param name="reason">The reason of the exception.</param>
public FaserException(string reason)
: base(reason)
{
Debug.Assert(reason != null);
}
/// <summary>
/// Initializes a new instance of the <see cref="FaserException" /> class.
/// </summary>
/// <param name="path">The member or aggregate path the exception can be associated with.</param>
/// <param name="reason">The reason why the exception happend.</param>
public FaserException(IFaserPath path, string reason)
: base(path + ": " + reason)
{
Debug.Assert(path != null && reason != null);
}
}
}
<file_sep>/Faser.Tests/BasicTextTests.cs
using System.Collections.Generic;
using System.Linq;
using Faser.Tests.Formatters;
using NUnit.Framework;
namespace Faser.Tests
{
public sealed class BasicTextTests : SimpleTextFormatter
{
const string EncodedMemberName = "EncodedMemberName";
sealed class DifferentEncodedName
{
[EncodedName(EncodedMemberName)]
public uint M1;
}
[Test]
public void testDifferentEncodedName()
{
var encoded = new DifferentEncodedName
{
M1 = 1010
};
var serialized = Formatter.Encode(encoded);
var txt = new string(serialized.ToArray());
var decoded = Formatter.Decode<DifferentEncodedName>(txt);
Assert.That(txt, Contains.Substring(EncodedMemberName));
Assert.That(decoded.M1, Is.EqualTo(encoded.M1));
}
sealed class DifferentEncodedName2
{
public uint M1;
}
[Test]
public void testDifferentEncodedNameViaConfiguration()
{
var f = Faser.CreateFormatter<IEnumerable<char>>();
configureSimpleTextFormat(f);
f.Configure<DifferentEncodedName2>()
.EncodedName(en => en.M1, EncodedMemberName)
;
var encoded = new DifferentEncodedName2();
encoded.M1 = 4242;
var serialized = f.Encode(encoded);
var txt = new string(serialized.ToArray());
var decoded = f.Decode<DifferentEncodedName2>(txt);
Assert.That(txt, Contains.Substring(EncodedMemberName));
Assert.That(decoded.M1, Is.EqualTo(encoded.M1));
}
}
}
<file_sep>/Faser/IFaserFormatter.cs
using System;
using System.Diagnostics;
namespace Faser
{
/// <summary>
/// The primary configuration interface of a Faser formatter.
/// </summary>
/// <typeparam name="EncodedT">The type that is the result of the formatting process.</typeparam>
public interface IFaserFormatter<EncodedT>
{
/// <summary>
/// Encodes the specified aggregate instance.
/// </summary>
/// <typeparam name="T">The type of the instance.</typeparam>
/// <param name="instance">The instance.</param>
/// <returns>The encoded data.</returns>
EncodedT Encode<T>(T instance);
/// <summary>
/// Decodes the specified encoded data to the instance T.
/// </summary>
/// <typeparam name="T">The instance to be decoded from the encoded data.</typeparam>
/// <param name="encoded">The encoded data.</param>
/// <returns>The decoded instance.</returns>
T Decode<T>(EncodedT encoded);
/// <summary>
/// Specifies an aggregate encoder factory function that is called
/// for every aggregate instance that needs to be encoded.
/// </summary>
/// <param name="encoder">The function that creates the aggregate encoder.</param>
IFaserFormatter<EncodedT> AggregateEncoder(Func<IAggregatePath, object, IAggregateEncoder<EncodedT>> encoder);
/// <summary>
/// Specifies an aggregate decoder factory function that is called
/// for every aggregate instance that needs to be decoded.
/// </summary>
/// <param name="decoder">The decoder function.</param>
IFaserFormatter<EncodedT> AggregateDecoder(Func<IAggregatePath, EncodedT, IAggregateDecoder<EncodedT>> decoder);
/// <summary>
/// Specifies an encoding guard for a specific value type.
/// </summary>
/// <param name="encoderGuard">The encoder guard that decides if the value should be encoded.</param>
IFaserFormatter<EncodedT> EncodeIf<ValueT>(Func<ValueT, bool> encoderGuard);
/// <summary>
/// Specifies an encoding guard for a specific value type.
/// </summary>
/// <param name="encoderGuard">The encoder guard that decides if the value should be encoded.</param>
IFaserFormatter<EncodedT> EncodeIf<ValueT>(Func<IMemberPath, ValueT, bool> encoderGuard);
/// <summary>
/// Specifies a decoding guard for a specific value type.
/// </summary>
/// <param name="decoderGuard">The decoder guard that decides if the value should be decoded.</param>
IFaserFormatter<EncodedT> DecodeIf<ValueT>(Func<EncodedT, bool> decoderGuard);
/// <summary>
/// Specifies a decoding guard for a specific value type.
/// </summary>
/// <param name="decoderGuard">The decoder guard that decides if the value should be decoded.</param>
IFaserFormatter<EncodedT> DecodeIf<ValueT>(Func<IMemberPath, EncodedT, bool> decoderGuard);
/// <summary>
/// Specifies an generic encoding guard that guards all members.
/// </summary>
/// <param name="encoderGuard">The encoder guard that decides if the value should be encoded.</param>
IFaserFormatter<EncodedT> EncodingGuard(Func<IMemberPath, object, bool> encoderGuard);
/// <summary>
/// Specifies an generic decoding guard that guards all members.
/// </summary>
/// <param name="decoderGuard">The decoder guard that decides if the value should be decoded.</param>
IFaserFormatter<EncodedT> DecodingGuard(Func<IMemberPath, EncodedT, bool> decoderGuard);
/// <summary>
/// Specifies an encoder for a specific value type.
/// </summary>
/// <param name="encoder">The encoder.</param>
IFaserFormatter<EncodedT> Encoder<ValueT>(Func<ValueT, EncodedT> encoder);
/// <summary>
/// Specifies an encoder for a specific value type.
/// </summary>
/// <param name="encoder">The encoder.</param>
IFaserFormatter<EncodedT> Encoder<ValueT>(Func<IMemberPath, ValueT, EncodedT> encoder);
/// <summary>
/// Specifies a decoder for a specific value type.
/// </summary>
/// <param name="decoder">The decoder.</param>
IFaserFormatter<EncodedT> Decoder<ValueT>(Func<EncodedT, ValueT> decoder);
/// <summary>
/// Specifies a decoder for a specific value type.
/// </summary>
/// <param name="decoder">The decoder.</param>
IFaserFormatter<EncodedT> Decoder<ValueT>(Func<IMemberPath, EncodedT, ValueT> decoder);
IFaserFormatter<EncodedT> ValueReader(
Func<Type, Type> typeConverter,
Func<object, Type, object> valueConverter);
IFaserFormatter<EncodedT> ValueWriter(
Func<Type, Type> typeConverter,
Func<object, Type, object> valueConverter);
/// <summary>
/// Specifies a default encoder that is used when no other member encoder matches.
/// </summary>
/// <param name="encoder">The encoder.</param>
IFaserFormatter<EncodedT> DefaultEncoder(Func<IMemberPath, object, EncodedT> encoder);
/// <summary>
/// Specifies a default decoder that is used when no other member encoder matches.
/// </summary>
/// <param name="decoder">The decoder.</param>
IFaserFormatter<EncodedT> DefaultDecoder(Func<IMemberPath, EncodedT, object> decoder);
/// <summary>
/// Returns a configuration interface to configure a specific aggregate type.
/// </summary>
IAggregateConfiguration<EncodedT, ObjectT> Configure<ObjectT>();
/// <summary>
/// Returns a configuration to configure a specific value type.
/// </summary>
ITypeConfiguration<EncodedT, TypeT> ForType<TypeT>();
}
public static class FaserFormatterExtensions
{
#region Enums
/// <summary>
/// Configures the Faser formatter to automatically use the underlying enum type when an enum is encoded or decoded.
/// </summary>
public static IFaserFormatter<EncodedT> UseUnderlyingEnumType<EncodedT>(this IFaserFormatter<EncodedT> _)
{
Debug.Assert(_ != null);
_.ValueReader(enumTypeConverter, Convert.ChangeType);
_.ValueWriter(enumTypeConverter, (value, type) => Enum.ToObject(type, value));
return _;
}
static Type enumTypeConverter(Type declaredType)
{
return !declaredType.IsEnum ? declaredType : declaredType.GetEnumUnderlyingType();
}
#endregion
#region Nullable Values
/// <summary>
/// Configures the Faser formatter so that Nullable values that are null are not encoded and not decoded when their encoded instance is null.
/// And in addition, configures the formatter so that the Nullable enclosed value types are used for encoding and decoding.
/// </summary>
public static IFaserFormatter<EncodedT> ManageNullableValues<EncodedT>(
this IFaserFormatter<EncodedT> _)
where EncodedT : class
{
Debug.Assert(_ != null);
return _.ManageNullableValues(encoded => encoded != null);
}
/// <summary>
/// Configures the Faser formatter so that Nullable values that are null are not encoded.
/// And in addition, configures the formatter so that the Nullable enclosed value types are used for encoding and decoding.
/// </summary>
/// <param name="nullableDecodingGuard">The decoding guard that is used to decide if a nullable value needs to be decoded.</param>
public static IFaserFormatter<EncodedT> ManageNullableValues<EncodedT>(
this IFaserFormatter<EncodedT> _,
Func<EncodedT, bool> nullableDecodingGuard)
{
Debug.Assert(_ != null);
// nullables are assignment compatible, so we only need to convert types here.
_.ValueReader(nullableTypeConverter, (value, t) => value);
_.ValueWriter(nullableTypeConverter, (value, t) => value);
_.EncodingGuard((path, value) => !isNullable(path.Member.Type) || value != null);
_.DecodingGuard((path, encoded) => !isNullable(path.Member.Type) || nullableDecodingGuard(encoded));
return _;
}
static Type nullableTypeConverter(Type declaredType)
{
bool isNullable = FaserFormatterExtensions.isNullable(declaredType);
return isNullable ? declaredType.GetGenericArguments()[0] : declaredType;
}
static bool isNullable(Type declaredType)
{
return declaredType.IsGenericType && declaredType.GetGenericTypeDefinition() == Nullable;
}
static readonly Type Nullable = typeof (Nullable<>);
#endregion
}
}
<file_sep>/Faser.Tests/SystemTests.cs
using System;
using System.Runtime.InteropServices;
using NUnit.Framework;
namespace Faser.Tests
{
[TestFixture]
public class SystemTests
{
public class OffsetOfTest
{
public uint FirstMember;
public uint SecondMember;
}
[Test, ExpectedException(typeof(ArgumentException))]
public void offsetDoesNotWorkForClasses()
{
Marshal.OffsetOf(typeof (OffsetOfTest), "SecondMember");
}
[Test, ExpectedException(typeof(AssertionException))]
public void charArrayToStringWorksAsExpected()
{
var array = new char[2] {'a', 'b'};
Assert.That(array.ToString(), Is.EqualTo("ab"));
}
}
}
<file_sep>/Faser/Formatter/AggregatePath.cs
using System;
using System.Collections.Generic;
namespace Faser.Formatter
{
sealed class AggregatePath : IAggregatePath
{
public IMemberPath Parent_ { get; private set; }
public ITypeInfo TypeInfo { get; private set; }
public AggregatePath(IMemberPath parent, ITypeInfo type, IEnumerable<Attribute> attributes)
{
Parent_ = parent;
TypeInfo = type;
Attributes = attributes;
}
public AggregatePath(ITypeInfo type, IEnumerable<Attribute> attributes)
: this(null, type, attributes)
{
}
public IEnumerable<Attribute> Attributes { get; private set; }
public override string ToString()
{
return TypeInfo.ToString();
}
}
}
<file_sep>/Faser/Properties/AssemblyInfo.cs
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Faser")]
[assembly: AssemblyDescription("Format Agnostic Serialization")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Faser")]
[assembly: AssemblyCopyright("Copyright © 2013 <NAME>")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("f6729b4f-05ea-431c-b317-2f50355a3642")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
<file_sep>/Faser/Formatter/TypeInfo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
namespace Faser.Formatter
{
sealed class TypeInfo : ITypeInfo
{
public Type Type { get; private set; }
readonly IMemberInfo[] _members;
readonly Func<object> _constructor;
public TypeInfo(Type type)
{
Type = type;
_members = Type
// do not consider consts and static members.
.GetFields(BindingFlags.Instance | BindingFlags.Public)
.Select(makeMemberInfo)
.ToArray();
var defaultConstructor = Type.GetConstructor(new Type[] {});
_constructor = defaultConstructor == null
? (Func<object>) (() => FormatterServices.GetUninitializedObject(Type))
: (() => defaultConstructor.Invoke(null));
IsObject = Type.GetTypeCode(type) == TypeCode.Object;
}
static IMemberInfo makeMemberInfo(FieldInfo fieldInfo)
{
return new AggregateMemberInfo(fieldInfo);
}
public IEnumerable<Attribute> Attributes
{
get
{
return Type.GetCustomAttributes(false).OfType<Attribute>();
}
}
public object NewInstance()
{
return _constructor();
}
public IMemberInfo[] Members
{
get { return _members; }
}
public bool IsObject { get; private set; }
public override string ToString()
{
return Type.Name;
}
}
}
<file_sep>/Faser.Binary/FaserBinary.cs
using System.Collections.Generic;
using System.Diagnostics;
using Faser.Binary.Core;
namespace Faser.Binary
{
public static class FaserBinary
{
/// <summary>
/// Creates a binary aggregate encoder.
/// </summary>
/// <param name="path">The path of the member to create an aggregate encoder for.</param>
/// <param name="instance">The instance of the member that needs to be encoded.</param>
/// <returns>The binary aggregate encoder for that instance.</returns>
public static IAggregateEncoder<IEnumerable<byte>> CreateAggregateEncoder(
IAggregatePath path,
object instance)
{
Debug.Assert(path != null && instance != null);
var sz = path.size();
// no size attribute is always treated as a flexible serialization, even though
// all members may have specified offsets and sizes.
return sz != null
? (IAggregateEncoder<IEnumerable<byte>>) new FixedSizeEncoder(sz.Value)
: new FlexibleSizeEncoder();
}
/// <summary>
/// Creates a binary aggregate decoder.
/// </summary>
/// <param name="path">The path of the member to create an aggregate decoder for.</param>
/// <param name="source">The encoded data of the aggregate.</param>
/// <returns>An aggregate encoder capable to decode the given encoded data.</returns>
public static IAggregateDecoder<IEnumerable<byte>> CreateAggregateDecoder(
IAggregatePath path,
IEnumerable<byte> source)
{
Debug.Assert(path != null && source != null);
var sz = path.size();
return sz != null
? (IAggregateDecoder<IEnumerable<byte>>) new FixedSizeDecoder(source, sz.Value)
: new FlexibleSizeDecoder(source);
}
/// <summary>
/// Prepares a Faser formatter for binary encoding and decoding.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <returns></returns>
public static IFaserFormatter<IEnumerable<byte>> PrepareForBinary(
this IFaserFormatter<IEnumerable<byte>> formatter)
{
Debug.Assert(formatter != null);
formatter
.AggregateEncoder(CreateAggregateEncoder)
.AggregateDecoder(CreateAggregateDecoder);
return formatter;
}
}
}
<file_sep>/Faser.Tests/Formatters/SimpleBinaryFormatter.cs
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Faser.Binary;
namespace Faser.Tests.Formatters
{
public class SimpleBinaryFormatter
{
public IFaserFormatter<IEnumerable<byte>> Formatter;
public SimpleBinaryFormatter()
{
var f = Faser.CreateFormatter<IEnumerable<byte>>();
configureSimpleBinaryFormat(f);
Formatter = f;
}
void configureSimpleBinaryFormat(IFaserFormatter<IEnumerable<byte>> formatter)
{
formatter.PrepareForBinary();
var nullByte = new byte[] { 0 };
formatter.Encoder<string>((path, str) =>
{
if (str == null)
return nullByte;
var bytes = Encoding.UTF8.GetBytes(str);
return bytes.Concat(nullByte);
});
formatter.Decoder<string>((path, encoded) =>
{
var bytes = encoded.TakeWhile(b => b != 0).ToArray();
return Encoding.UTF8.GetString(bytes);
});
formatter.Encoder<uint>((path, value) =>
{
var bytes = new[]
{
(byte) ((value & 0xff000000) >> 24),
(byte) ((value & 0x00ff0000) >> 16),
(byte) ((value & 0x0000ff00) >> 8),
(byte) ((value & 0x000000ff))
};
return bytes;
});
formatter.Decoder<uint>((path, encoded) =>
{
var bytes = encoded.Take(4).ToArray();
uint value =
(uint)bytes[0] << 24 |
(uint)bytes[1] << 16 |
(uint)bytes[2] << 8 |
bytes[3];
return value;
});
formatter.Encoder<byte>((path, value)
=> new[] { value });
formatter.Decoder<byte>((path, encoded)
=> encoded.First());
}
}
}
<file_sep>/Faser/Formatter/TypeInfoCache.cs
using System;
using System.Collections.Generic;
namespace Faser.Formatter
{
sealed class TypeInfoCache
{
readonly Dictionary<Type, TypeInfo> _cache = new Dictionary<Type, TypeInfo>();
TypeInfo getForType(Type type)
{
TypeInfo ti;
if (!_cache.TryGetValue(type, out ti))
{
ti = new TypeInfo(type);
_cache.Add(type, ti);
}
return ti;
}
// we don't want to make this thread static, because we need that clients
// may use this cache from a lot of different threads.
// So we go for low-level locking instead to keep the cache consistent
// among all clients.
static readonly object CacheLock = new object();
static readonly TypeInfoCache Instance = new TypeInfoCache();
public static TypeInfo forType(Type type)
{
lock (CacheLock)
{
return Instance.getForType(type);
}
}
}
}
<file_sep>/Faser.Tests/EnumTests.cs
using System.Collections.Generic;
using Faser.Binary;
using NUnit.Framework;
using Faser.Tests.Formatters;
namespace Faser.Tests
{
public class EnumTests
{
readonly IFaserFormatter<IEnumerable<byte>> BinaryFormatter;
readonly IFaserFormatter<IEnumerable<byte>> BinaryFormatterWithEnums;
public EnumTests()
{
BinaryFormatter = new SimpleBinaryFormatter().Formatter;
BinaryFormatterWithEnums = new SimpleBinaryFormatter().Formatter;
BinaryFormatterWithEnums.UseUnderlyingEnumType();
}
enum EnumOfKnownType : uint
{
Test = 12
}
sealed class ClassWithEnumOfKnownType
{
[Offset(0)]
public EnumOfKnownType EnumValue;
}
[Test, ExpectedException(typeof(FaserException), ExpectedMessage = "EnumOfKnownType EnumValue: No encoder configured")]
public void testEnumWithoutUnderlyingTypeFallback()
{
var v = new ClassWithEnumOfKnownType { EnumValue = EnumOfKnownType.Test };
var r = encodeDecodeBinary(BinaryFormatter, v);
}
[Test]
public void testEnumFallbackToKnownType()
{
var v = new ClassWithEnumOfKnownType { EnumValue = EnumOfKnownType.Test };
var r = encodeDecodeBinary(BinaryFormatterWithEnums, v);
Assert.That(r.EnumValue, Is.EqualTo(v.EnumValue));
}
T encodeDecodeBinary<T>(IFaserFormatter<IEnumerable<byte>> formatter, T instance)
{
var serialized = formatter.Encode(instance);
return formatter.Decode<T>(serialized);
}
[Test]
public void explicitEnumEncoderHasPrecedenceOverGenericRules()
{
bool usedExplicitEncoder = false;
bool usedExplicitDecoder = false;
var formatter = new SimpleBinaryFormatter().Formatter;
formatter.UseUnderlyingEnumType();
formatter.Encoder<EnumOfKnownType>((path, instance) =>
{
usedExplicitEncoder = true;
return new byte[0];
});
formatter.Decoder<EnumOfKnownType>((path, e) =>
{
usedExplicitDecoder = true;
return 0;
});
var test = new ClassWithEnumOfKnownType();
var encoded = formatter.Encode(test);
Assert.True(usedExplicitEncoder);
var decoded = formatter.Decode<ClassWithEnumOfKnownType>(encoded);
Assert.True(usedExplicitDecoder);
}
}
}
<file_sep>/Faser.Tests/Formatters/SimpleTextEncoder.cs
using System.Collections.Generic;
using System.Linq;
namespace Faser.Tests.Formatters
{
sealed class SimpleTextEncoder : IAggregateEncoder<IEnumerable<char>>
{
readonly Dictionary<string, string> _values = new Dictionary<string, string>();
public void WriteMember(IMemberPath path, IEnumerable<char> encoded)
{
_values.Add(path.EncodedName(), encoded.ToString());
}
public IEnumerable<char> Result
{
get { return encodeInstance(_values); }
}
IEnumerable<char> encodeInstance(Dictionary<string, string> instance)
{
var strings = instance.Select(kv => makeNameValue(kv.Key, kv.Value));
return string.Join(" ", strings);
}
string makeNameValue(string name, string value)
{
return name + "=" + quote(value);
}
static string quote(string value)
{
return '"' + escape(value) + '"';
}
static string escape(string value)
{
return value.Replace("\\", "\\\\").Replace("\"", "\\\"");
}
}
}
<file_sep>/Faser/Formatter/AggregateMemberInfo.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
namespace Faser.Formatter
{
sealed class AggregateMemberInfo : IMemberInfo
{
readonly FieldInfo _fieldInfo;
public AggregateMemberInfo(FieldInfo fieldInfo)
{
_fieldInfo = fieldInfo;
}
public string Name
{
get { return _fieldInfo.Name; }
}
public Type Type
{
get { return TypeInfo.Type; }
}
public ITypeInfo TypeInfo
{
get { return TypeInfoCache.forType(_fieldInfo.FieldType); }
}
public IEnumerable<Attribute> Attributes
{
get { return _fieldInfo.GetCustomAttributes(false).OfType<Attribute>(); }
}
public object Get(object instance)
{
Debug.Assert(instance != null);
return _fieldInfo.GetValue(instance);
}
public void Set(object instance, object value)
{
Debug.Assert(instance != null);
_fieldInfo.SetValue(instance, value);
}
public AttributeT TryGetAttribute<AttributeT>()
where AttributeT : Attribute
{
return _fieldInfo
.GetCustomAttributes(typeof (AttributeT), false)
.Cast<AttributeT>()
.FirstOrDefault();
}
public override string ToString()
{
return _fieldInfo.FieldType.Name + " " + Name;
}
}
}
<file_sep>/Faser/Formatter/AggregateConfiguration.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
namespace Faser.Formatter
{
sealed class AggregateConfiguration<ET, OT> : IAggregateConfiguration<ET, OT>, IAggregateConfiguration
{
readonly IFaserFormatter<ET> _formatter;
readonly List<Attribute> _aggregateAttributes = new List<Attribute>();
readonly Dictionary<string, List<Attribute>> _memberAttributes = new Dictionary<string, List<Attribute>>();
public AggregateConfiguration(IFaserFormatter<ET> formatter)
{
_formatter = formatter;
}
public IAggregateConfiguration<ET, OT> Attribute(Attribute attribute)
{
Debug.Assert(attribute != null);
_aggregateAttributes.Add(attribute);
return this;
}
public IAggregateConfiguration<ET, OT> Attribute<MemberT>(
Expression<Func<OT, MemberT>> memberAccessor, Attribute attribute)
{
Debug.Assert(memberAccessor != null && attribute != null);
var memberName = memberAccessor.getMemberInfo().Name;
List<Attribute> attributes;
if (!_memberAttributes.TryGetValue(memberName, out attributes))
{
attributes = new List<Attribute>();
_memberAttributes.Add(memberName, attributes);
}
attributes.Add(attribute);
return this;
}
public IFaserFormatter<ET> End()
{
return _formatter;
}
public IEnumerable<Attribute> GetAttributes()
{
return _aggregateAttributes;
}
public IEnumerable<Attribute> GetAttributesForMember(string name)
{
List<Attribute> attributes;
return
_memberAttributes.TryGetValue(name, out attributes)
? attributes
: Enumerable.Empty<Attribute>();
}
}
}
<file_sep>/Faser.Tests/TextTests.cs
using System;
using Faser.Tests.Formatters;
using NUnit.Framework;
namespace Faser.Tests
{
[TestFixture]
public sealed class TextTests : SimpleTextFormatter
{
class TextSimple
{
public string Value;
}
[Test]
public void testSimpleTextEncoding()
{
var simple = new TextSimple()
{
Value = "Value"
};
var encoded = Formatter.Encode(simple);
Assert.That(encoded, Is.EqualTo("Value=\"Value\""));
}
[Test]
public void testSimpleTextSerialization()
{
var simple = new TextSimple()
{
Value = "Value"
};
var decoded = encodeDecode(simple);
Assert.That(decoded.Value, Is.EqualTo("Value"));
}
class TextSer
{
public string Hello;
public string World;
public DateTime Now;
}
// note that milliseconds are not serialized.
static readonly DateTime ADate = new DateTime(1910, 10, 11, 11, 09, 3);
[Test]
public void testCompositeTextSerialization()
{
var xx = new TextSer()
{
Hello = "Hello",
World = "World",
Now = ADate
};
var decoded = encodeDecode(xx);
Assert.That(decoded.Hello, Is.EqualTo("Hello"));
Assert.That(decoded.World, Is.EqualTo("World"));
Assert.That(decoded.Now, Is.EqualTo(ADate));
}
class NestedRoot
{
public uint V1;
public TextSer Nested;
public uint V2;
}
/// Well, this works, but the encoded string may look scary.
/// So probably we need a flatten option for nested classes.
[Test]
public void testNestedTextSerialization()
{
var nr = new NestedRoot
{
V1 = 0xdeadbeef,
V2 = 0xdeadf00d,
Nested = new TextSer
{
Hello = "Hello",
World = "World",
Now = ADate
}
};
var decoded = encodeDecode(nr);
Assert.That(decoded.V1, Is.EqualTo(0xdeadbeef));
Assert.That(decoded.V2, Is.EqualTo(0xdeadf00d));
Assert.That(decoded.Nested.Hello, Is.EqualTo("Hello"));
Assert.That(decoded.Nested.World, Is.EqualTo("World"));
Assert.That(decoded.Nested.Now, Is.EqualTo(ADate));
}
const string IMustBeEscaped = "Quote \" and Backslash \\";
[Test]
public void testStringEscaping()
{
var simple = new TextSimple() {Value = IMustBeEscaped};
var decoded = encodeDecode(simple);
Assert.That(decoded.Value, Is.EqualTo(IMustBeEscaped));
}
class SimpleRoot
{
public TextSimple Nested;
}
[Test]
public void testNestedStringEscaping()
{
var root = new SimpleRoot {Nested = new TextSimple {Value = IMustBeEscaped}};
var decoded = encodeDecode(root);
Assert.That(decoded.Nested.Value, Is.EqualTo(IMustBeEscaped));
}
T encodeDecode<T>(T instance)
{
var serialized = Formatter.Encode(instance);
return Formatter.Decode<T>(serialized);
}
}
}
<file_sep>/Faser/Formatter/IAggregateConfiguration.cs
using System;
using System.Collections.Generic;
namespace Faser.Formatter
{
interface IAggregateConfiguration
{
IEnumerable<Attribute> GetAttributes();
IEnumerable<Attribute> GetAttributesForMember(string name);
}
}<file_sep>/Faser.Binary/Properties/AssemblyInfo.cs
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Faser.Binary")]
[assembly: AssemblyDescription("Format Agnostic Serialization, Binary Support")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Faser.Binary")]
[assembly: AssemblyCopyright("Copyright © 2013 <NAME>")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("3a41a17f-40df-43dc-9630-3f3176d11f50")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
<file_sep>/Faser.Binary/Attributes.cs
using System;
namespace Faser.Binary
{
/// <summary>
/// An attribute that specifies a fixed size for a class, struct, or a field.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Field, Inherited = false)]
public sealed class SizeAttribute : Attribute
{
/// <summary>
/// The size that was specified.
/// </summary>
public readonly uint Size;
/// <summary>
/// Initializes a new instance of the <see cref="SizeAttribute" /> class.
/// </summary>
/// <param name="size">The size of the class, struct, or field.</param>
public SizeAttribute(uint size)
{
Size = size;
}
}
/// <summary>
/// An attribute that specifies a fixed offset for a field.
/// </summary>
[AttributeUsage(AttributeTargets.Field, Inherited = false)]
public sealed class OffsetAttribute : Attribute
{
/// <summary>
/// The offset of the field.
/// </summary>
public readonly uint Offset;
/// <summary>
/// Initializes a new instance of the <see cref="OffsetAttribute" /> class.
/// </summary>
/// <param name="offset">The offset of the field.</param>
public OffsetAttribute(uint offset)
{
Offset = offset;
}
}
static class AttributeExtensions
{
public static uint? offset(this IMemberPath member)
{
var attr = member.TryGetAttribute<OffsetAttribute>();
return attr == null ? (uint?) null : attr.Offset;
}
public static uint? size(this IMemberPath member)
{
var attr = member.TryGetAttribute<SizeAttribute>();
return attr == null ? (uint?) null : attr.Size;
}
public static uint? size(this IAggregatePath instance)
{
var attr = instance.TryGetAttribute<SizeAttribute>();
return attr == null ? (uint?)null : attr.Size;
}
}
}
<file_sep>/Faser.Tests/Formatters/SimpleTextParser.cs
using System;
using System.Collections.Generic;
using System.Linq;
using Sprache;
namespace Faser.Tests.Formatters
{
sealed class SimpleTextParser
{
readonly Parser<IEnumerable<Tuple<string, string>>> _parser;
public SimpleTextParser()
{
var name = Parse.LetterOrDigit.Many();
var unescapedStringCharacter = Parse.AnyChar.Except(Parse.Char('\\').Or(Parse.Char('"')));
var backslashEscape = Parse.String("\\\\").Return('\\');
var quoteEscape = Parse.String("\\\"").Return('"');
var stringChar = unescapedStringCharacter
.Or(backslashEscape)
.Or(quoteEscape);
var value =
from start in Parse.Char('"')
from content in stringChar.Many()
from end in Parse.Char('"')
select content;
var nameValue =
from n in name.Text()
from eq in Parse.Char('=')
from v in value.Text()
select Tuple.Create(n, v);
var separator = Parse.Char(' ');
var nameValues =
from leading in nameValue
from rest in separator.Then(_ => nameValue).Many()
select cons(leading, rest);
var nameValueOrNothing =
nameValues.Or(Parse.Return(Enumerable.Empty<Tuple<string, string>>()));
_parser = nameValueOrNothing.End();
}
public IEnumerable<Tuple<string, string>> parse(string input)
{
return _parser.Parse(input);
}
static IEnumerable<T> cons<T>(T head, IEnumerable<T> rest)
{
yield return head;
foreach (var item in rest)
yield return item;
}
}
}
<file_sep>/Faser/IAggregateConfiguration.cs
using System;
using System.Linq.Expressions;
namespace Faser
{
/// <summary>
/// An interface to configure a specific aggregate type.
/// </summary>
/// <typeparam name="EncodedT">The encoded type.</typeparam>
/// <typeparam name="ObjectT">The aggregate type.</typeparam>
public interface IAggregateConfiguration<EncodedT, ObjectT>
{
/// <summary>
/// Specify an attribute for this aggregate.
/// </summary>
/// <param name="attribute">The attribute.</param>
/// <returns></returns>
IAggregateConfiguration<EncodedT, ObjectT> Attribute(Attribute attribute);
/// <summary>
/// Specify an attribute for a member.
/// </summary>
/// <typeparam name="MemberT">The member type.</typeparam>
/// <param name="memberAccessor">The member accessor.</param>
/// <param name="attribute">The attribute to specify for that member.</param>
/// <returns></returns>
IAggregateConfiguration<EncodedT, ObjectT>
Attribute<MemberT>(Expression<Func<ObjectT, MemberT>> memberAccessor, Attribute attribute);
}
}
<file_sep>/Faser/ITypeInfo.cs
using System;
using System.Collections.Generic;
namespace Faser
{
/// <summary>
/// Meta information for an aggregate member.
/// </summary>
public interface IMemberInfo
{
/// <summary>
/// The name of the member.
/// </summary>
string Name { get; }
/// <summary>
/// The underlying system type of this member.
/// </summary>
Type Type { get; }
/// <summary>
/// The type info of this member.
/// </summary>
ITypeInfo TypeInfo { get; }
/// <summary>
/// All the attributes of this member (static attributes and configured)
/// </summary>
IEnumerable<Attribute> Attributes { get; }
/// <summary>
/// Retrieves the member value from an aggregate instance.
/// </summary>
object Get(object instance);
/// <summary>
/// Sets the member's value in the given aggregate instance.
/// </summary>
void Set(object instance, object value);
}
/// <summary>
/// Type information for aggregate and member types.
/// </summary>
public interface ITypeInfo
{
/// <summary>
/// The underlying system type.
/// </summary>
Type Type { get; }
/// <summary>
/// All the attributes specified for that type (by static attributes or via configuration).
/// </summary>
IEnumerable<Attribute> Attributes { get; }
/// <summary>
/// All the members of this type.
/// </summary>
IMemberInfo[] Members { get; }
/// <summary>
/// Returns true when this instance is an object and not a value type.
/// </summary>
bool IsObject { get; }
/// <summary>
/// Creates an instance of this type.
/// </summary>
object NewInstance();
}
}<file_sep>/Faser/IAggregateEncoder.cs
namespace Faser
{
/// <summary>
/// An interface that every aggregate encoder must implement.
/// </summary>
/// <typeparam name="EncodedT">The encoded type.</typeparam>
public interface IAggregateEncoder<EncodedT>
{
/// <summary>
/// Writes the member to the aggregate.
/// </summary>
/// <param name="path">The member path that specifies the member that is written.</param>
/// <param name="encoded">The member to be written in encoded form.</param>
void WriteMember(IMemberPath path, EncodedT encoded);
/// <summary>
/// Gets the enocded aggregate result.
/// </summary>
EncodedT Result { get; }
}
/// <summary>
/// An interface that every aggregate decoder must implement.
/// </summary>
/// <typeparam name="EncodedT">The encoded type.</typeparam>
public interface IAggregateDecoder<out EncodedT>
{
/// <summary>
/// Reads a member from the aggregate.
/// </summary>
/// <param name="path">The path of the member that should be read.</param>
/// <returns>The member in encoded form.</returns>
EncodedT ReadMember(IMemberPath path);
}
}<file_sep>/Faser/Formatter/ExpressionExtensions.cs
using System;
using System.Linq.Expressions;
using MI = System.Reflection.MemberInfo;
namespace Faser.Formatter
{
static class ExpressionExtensions
{
public static MI getMemberInfo<ObjectT, MemberT>(
this Expression<Func<ObjectT, MemberT>> expression)
{
var memberexp = expression.Body as MemberExpression;
if (memberexp == null)
throw new Exception("Failed to derive member from Lambda Expression");
return memberexp.Member;
}
}
}
<file_sep>/Faser/Formatter/Guards.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace Faser.Formatter
{
sealed class Guards<EncodedT>
{
public delegate bool EncoderGuard(IMemberPath path, object instance);
public delegate bool DecoderGuard(IMemberPath path, EncodedT encoded);
readonly Dictionary<Type, EncoderGuard> _typeEncoderGuards = new Dictionary<Type, EncoderGuard>();
readonly Dictionary<Type, DecoderGuard> _typeDecoderGuards = new Dictionary<Type, DecoderGuard>();
readonly List<EncoderGuard> _globalEncoderGuards = new List<EncoderGuard>();
readonly List<DecoderGuard> _globalDecoderGuards = new List<DecoderGuard>();
public void add(Type t, EncoderGuard guard)
{
_typeEncoderGuards.Add(t, guard);
}
public void add(Type t, DecoderGuard guard)
{
_typeDecoderGuards.Add(t, guard);
}
public void add(EncoderGuard guard)
{
_globalEncoderGuards.Add(guard);
}
public void add(DecoderGuard guard)
{
_globalDecoderGuards.Add(guard);
}
public bool shouldEncode(IMemberPath path, object instance)
{
EncoderGuard guard;
var t = path.Member.Type;
if (_typeEncoderGuards.TryGetValue(t, out guard))
return guard(path, instance);
if (_globalEncoderGuards.Count == 0)
return true;
return _globalEncoderGuards.All(g => g(path, instance));
}
public bool shouldDecode(IMemberPath path, EncodedT encoded)
{
DecoderGuard guard;
var t = path.Member.Type;
if (_typeDecoderGuards.TryGetValue(t, out guard))
return guard(path, encoded);
if (_globalDecoderGuards.Count == 0)
return true;
return _globalDecoderGuards.All(g => g(path, encoded));
}
}
}
<file_sep>/Faser/ITypeConfiguration.cs
using System;
namespace Faser
{
/// <summary>
/// A configuration interface for a specific value type.
/// </summary>
/// <typeparam name="EncodedT">The type used to encode this type.</typeparam>
/// <typeparam name="TypeT">The type to configure.</typeparam>
public interface ITypeConfiguration<EncodedT, TypeT>
{
/// <summary>
/// Specify an encoding guard for this type.
/// </summary>
/// <param name="encodeGuard">The encoding guard that decides if the value needs to be encoded.</param>
ITypeConfiguration<EncodedT, TypeT> EncodeIf(Func<IMemberPath, TypeT, bool> encodeGuard);
/// <summary>
/// Specify a decoding guard for this type.
/// </summary>
/// <param name="decodeGuard">The decoding guard that decides if the value needs to be decoded.</param>
ITypeConfiguration<EncodedT, TypeT> DecodeIf(Func<IMemberPath, EncodedT, bool> decodeGuard);
/// <summary>
/// Specifies an encoder for this type.
/// </summary>
/// <param name="encoder">The encoder that is used to encode this type.</param>
ITypeConfiguration<EncodedT, TypeT> Encoder(Func<IMemberPath, TypeT, EncodedT> encoder);
/// <summary>
/// Specifies a decoder for this type.
/// </summary>
/// <param name="decoder">The decoder to decode this type.</param>
ITypeConfiguration<EncodedT, TypeT> Decoder(Func<IMemberPath, EncodedT, TypeT> decoder);
/// <summary>
/// Ends the configuration of this types and returns the formatter instance.
/// This method only returns the current formatter and does not have any side effects.
/// It may be useful in a fluent configuration context.
/// </summary>
IFaserFormatter<EncodedT> End();
}
/// <summary>
/// Some extensions to simplify the type configuration specification.
/// </summary>
public static class TypeConfigurationExtensions
{
public static ITypeConfiguration<EncodedT, TypeT> EncodeIf<EncodedT, TypeT>(
this ITypeConfiguration<EncodedT, TypeT> _,
Func<TypeT, bool> encodeGuard)
{
return _.EncodeIf((path, value) => encodeGuard(value));
}
public static ITypeConfiguration<EncodedT, TypeT> DecodeIf<EncodedT, TypeT>(
this ITypeConfiguration<EncodedT, TypeT> _,
Func<EncodedT, bool> decodeGuard)
{
return _.DecodeIf((path, value) => decodeGuard(value));
}
public static ITypeConfiguration<EncodedT, ValueT> Encoder<EncodedT, ValueT>(
this ITypeConfiguration<EncodedT, ValueT> _,
Func<ValueT, EncodedT> encoder)
{
return _.Encoder((path, value) => encoder(value));
}
public static ITypeConfiguration<EncodedT, ValueT> Decoder<EncodedT, ValueT>(
this ITypeConfiguration<EncodedT, ValueT> _,
Func<EncodedT, ValueT> decoder)
{
return _.Decoder((path, value) => decoder(value));
}
}
}
<file_sep>/Faser.Tests/Formatters/SimpleTextDecoder.cs
using System.Collections.Generic;
using System.Linq;
namespace Faser.Tests.Formatters
{
sealed class SimpleTextDecoder : IAggregateDecoder<IEnumerable<char>>
{
readonly Dictionary<string, string> _nameValues;
public SimpleTextDecoder(IAggregatePath path, IEnumerable<char> input)
{
_nameValues = Parser.parse(new string(input.ToArray()))
.ToDictionary(t => t.Item1, t => t.Item2);
}
public IEnumerable<char> ReadMember(IMemberPath path)
{
return _nameValues[path.EncodedName()];
}
static readonly SimpleTextParser Parser = new SimpleTextParser();
}
}
<file_sep>/Faser/IFaserPath.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace Faser
{
/// <summary>
/// A path that specifies an aggregate.
/// </summary>
public interface IAggregatePath : IFaserPath
{
/// <summary>
/// The parent member path that refers to this aggregate.
/// </summary>
IMemberPath Parent_ { get; }
/// <summary>
/// The type information of this aggregate.
/// </summary>
ITypeInfo TypeInfo { get; }
}
/// <summary>
/// A path that specifies a member of an aggregate.
/// </summary>
public interface IMemberPath : IFaserPath
{
/// <summary>
/// The parent aggregate that contains this member.
/// </summary>
IAggregatePath Parent { get; }
/// <summary>
/// The member information of this member.
/// </summary>
IMemberInfo Member { get; }
}
/// <summary>
/// Base interface for faser aggregate and member paths.
/// </summary>
public interface IFaserPath
{
/// <summary>
/// The attributes that are specified at this aggregate or member.
/// </summary>
IEnumerable<Attribute> Attributes { get; }
}
/// <summary>
/// Some useful extensions for paths.
/// </summary>
public static class FaserPathExtensions
{
/// <summary>
/// Try to get an attribute of a Faser path.
/// </summary>
public static AttributeT TryGetAttribute<AttributeT>(this IFaserPath _)
where AttributeT : Attribute
{
return _.Attributes.OfType<AttributeT>().FirstOrDefault();
}
/// <summary>
/// Returns the encoded name of the aggregate, or, if not specified, the original name.
/// </summary>
public static string EncodedName(this IAggregatePath _)
{
var attr = _.TryGetAttribute<EncodedNameAttribute>();
return attr != null
? attr.EncodedName
: _.TypeInfo.Type.Name;
}
/// <summary>
/// Returns the encoded name of an aggregate member, or, if not specified, the original name.
/// </summary>
public static string EncodedName(this IMemberPath _)
{
var attr = _.TryGetAttribute<EncodedNameAttribute>();
return attr != null
? attr.EncodedName
: _.Member.Name;
}
}
}
<file_sep>/Faser/Faser.cs
using Faser.Formatter;
namespace Faser
{
/// <summary>
/// The entry point for Faser.
/// </summary>
public static class Faser
{
/// <summary>
/// Creates a Faser formatter.
/// </summary>
/// <typeparam name="EncodedT">The type that is used for encoded instances.</typeparam>
/// <returns>A faser formatter that needs to be configured.</returns>
public static IFaserFormatter<EncodedT> CreateFormatter<EncodedT>()
{
return new FaserFormatter<EncodedT>();
}
}
}
<file_sep>/Faser.Tests/Properties/AssemblyInfo.cs
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Faser.Tests")]
[assembly: AssemblyDescription("Format Agnostic Serialization, NUnit Tests")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Faser.Tests")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("e4b0ceac-e780-4b10-87eb-f6d596add221")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
<file_sep>/Faser.Binary/Core/FlexibleSizeDecoder.cs
using System.Collections.Generic;
using System.Diagnostics;
namespace Faser.Binary.Core
{
sealed class FlexibleSizeDecoder : IAggregateDecoder<IEnumerable<byte>>
{
readonly IEnumerator<byte> _source;
readonly List<byte> dataRead = new List<byte>();
public FlexibleSizeDecoder(IEnumerable<byte> source)
{
_source = source.GetEnumerator();
}
public IEnumerable<byte> ReadMember(IMemberPath path)
{
Debug.Assert(path != null);
uint? offset = path.offset();
uint? maxSize = path.size();
if (offset == null)
throw new FaserException(path, "Offset not specified");
var o = offset.Value;
return read(path, o, maxSize);
}
IEnumerable<byte> read(IFaserPath path, uint offset, uint? maxSize)
{
var end = offset + maxSize;
while (end == null || offset != end.Value)
yield return acquireElement(path, offset++);
}
byte acquireElement(IFaserPath path, uint offset)
{
while (dataRead.Count <= offset)
{
if (!_source.MoveNext())
throw new FaserException(path, "Read past the end of the encoded stream");
dataRead.Add(_source.Current);
}
return dataRead[(int)offset];
}
public IFaserFormatter<byte> Formatter { get; private set; }
}
}
<file_sep>/Faser.Binary/Core/FixedSizeDecoder.cs
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Faser.Binary.Core
{
sealed class FixedSizeDecoder : IAggregateDecoder<IEnumerable<byte>>
{
readonly byte[] _data;
public FixedSizeDecoder(IEnumerable<byte> source, uint maxSize)
{
_data = source.Take((int) maxSize).ToArray();
}
public IEnumerable<byte> ReadMember(IMemberPath path)
{
Debug.Assert(path != null);
uint? offset = path.offset();
uint? size = path.size();
if (offset == null)
throw new FaserException(path, "Offset not specified");
var o = offset.Value;
if (size != null && o + size.Value > _data.Length)
throw new FaserException(path, "Offset plus size of member exceeds size of container");
var maxSize = size ?? (uint)_data.Length - o;
return offsetSizeEnumerator(o, maxSize);
}
IEnumerable<byte> offsetSizeEnumerator(uint offset, uint size)
{
var end = offset + size;
for (uint i = offset; i != end; ++i)
yield return _data[i];
}
}
}<file_sep>/Faser.Tests/BasicTests.cs
using System.Collections.Generic;
using System.Linq;
using Faser.Tests.Formatters;
using NUnit.Framework;
namespace Faser.Tests
{
[TestFixture]
public class BasicTests
{
[SetUp]
public void setup()
{
Formatter = new SimpleTextFormatter().Formatter;
}
IFaserFormatter<IEnumerable<char>> Formatter;
public class TestWithConstant
{
public const int TestMember = 10;
}
[Test]
public void doNotEncodeConstants()
{
var t = new TestWithConstant();
var encoded = Formatter.Encode(t);
Assert.True(!encoded.Any());
}
public class TestWithStatic
{
public static string String = "Do not encode me";
}
[Test]
public void doNotEncodeStatics()
{
var t = new TestWithStatic();
var encoded = Formatter.Encode(t);
Assert.True(!encoded.Any());
}
sealed class ComplexObject
{
public List<string> Encoded;
}
[Test]
public void supportToEncodeAggregateObjectsAsMembers()
{
Formatter.Encoder<List<string>>((path, list) => string.Join(" ", list));
var co = new ComplexObject { Encoded = new List<string>(){"Hello", "World"}};
var encoded = Formatter.Encode(co);
Assert.That(encoded, Is.EqualTo("Encoded=\"Hello World\""));
}
[Test]
public void supportToDecodeAggregateObjectsAsMembers()
{
const string Encoded = "Encoded=\"Hello World\"";
Formatter.Decoder<List<string>>((path, input) =>
{
// fake: we need to take the exact length of input bytes
var str = new string(input.Take("Hello World".Length).ToArray());
return new List<string>(str.Split(' '));
});
var co = Formatter.Decode<ComplexObject>(Encoded);
Assert.That(co.Encoded, Is.EquivalentTo(new List<string>() { "Hello", "World" }));
}
}
}
<file_sep>/Faser/Attributes.cs
using System;
using System.Linq.Expressions;
namespace Faser
{
/// <summary>
/// An attribute that specified the encoded name of a field or an aggregate.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Class, Inherited = false)]
public sealed class EncodedNameAttribute : Attribute
{
/// <summary>
/// The encoded name.
/// </summary>
public readonly string EncodedName;
/// <summary>
/// Initializes a new instance of the <see cref="EncodedNameAttribute" /> class.
/// </summary>
/// <param name="encodedName">Name of the encoded field or aggregate.</param>
public EncodedNameAttribute(string encodedName)
{
EncodedName = encodedName;
}
}
/// <summary>
/// Extension methods to specify encoded names.
/// </summary>
public static class FaserAggregateConfigurationExtensions
{
/// <summary>
/// Specify an encoded name for an aggregate.
/// </summary>
/// <typeparam name="ET">The encoded type.</typeparam>
/// <typeparam name="OT">The type of the object.</typeparam>
/// <param name="encodedName">The encoded name of the aggregate.</param>
/// <returns></returns>
public static IAggregateConfiguration<ET, OT> EncodedName<ET, OT>(
this IAggregateConfiguration<ET, OT> _,
string encodedName
)
{
return _.Attribute(new EncodedNameAttribute(encodedName));
}
/// <summary>
/// Specifies an encoded name for an aggregate member.
/// </summary>
/// <typeparam name="ET">The encoded type.</typeparam>
/// <typeparam name="OT">The type of the aggregate.</typeparam>
/// <typeparam name="MT">The type of the member.</typeparam>
/// <param name="memberAccessor">The member accessor.</param>
/// <param name="encodedName">The encoded name of the member.</param>
/// <returns></returns>
public static IAggregateConfiguration<ET, OT> EncodedName<ET, OT, MT>(
this IAggregateConfiguration<ET, OT> _,
Expression<Func<OT, MT>> memberAccessor,
string encodedName)
{
return _.Attribute<MT>(memberAccessor, new EncodedNameAttribute(encodedName));
}
}
}
<file_sep>/Faser/Formatter/FaserFormatter.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Faser.Formatter
{
sealed class FaserFormatter<EncodedT> : IFaserFormatter<EncodedT>
{
delegate EncodedT EncoderFunc(IMemberPath path, object instance);
delegate object DecoderFunc(IMemberPath path, EncodedT encoded);
readonly Dictionary<Type, EncoderFunc> _typeEncoders = new Dictionary<Type, EncoderFunc>();
readonly Dictionary<Type, DecoderFunc> _typeDecoders = new Dictionary<Type, DecoderFunc>();
EncoderFunc _defaultEncoder_;
DecoderFunc _defaultDecoder_;
Func<IAggregatePath, object, IAggregateEncoder<EncodedT>> _aggregateEncoderFactory_;
Func<IAggregatePath, EncodedT, IAggregateDecoder<EncodedT>> _aggregateDecoderFactory_;
readonly Dictionary<Type, IAggregateConfiguration> _aggregateConfigurations = new Dictionary<Type, IAggregateConfiguration>();
readonly Guards<EncodedT> _guards = new Guards<EncodedT>();
readonly ValueConverters _valueConverters = new ValueConverters();
public EncodedT Encode<T>(T instance)
{
var typeInfo = TypeInfoCache.forType(typeof (T));
var path = new AggregatePath(typeInfo, getAggregateAttributes(typeInfo));
return encode(path, instance);
}
public T Decode<T>(EncodedT encoded)
{
var typeInfo = TypeInfoCache.forType(typeof(T));
var path = new AggregatePath(typeInfo, getAggregateAttributes(typeInfo));
return (T)decode(path, encoded);
}
public IFaserFormatter<EncodedT> AggregateEncoder(Func<IAggregatePath, object, IAggregateEncoder<EncodedT>> encoder)
{
_aggregateEncoderFactory_ = encoder;
return this;
}
public IFaserFormatter<EncodedT> AggregateDecoder(Func<IAggregatePath, EncodedT, IAggregateDecoder<EncodedT>> decoder)
{
_aggregateDecoderFactory_ = decoder;
return this;
}
public IFaserFormatter<EncodedT> EncodeIf<ValueT>(Func<ValueT, bool> encoderGuard)
{
Debug.Assert(encoderGuard != null);
return EncodeIf<ValueT>((path, value) => encoderGuard(value));
}
public IFaserFormatter<EncodedT> EncodeIf<TypeT>(Func<IMemberPath, TypeT, bool> encoderGuard)
{
Debug.Assert(encoderGuard != null);
Guards<EncodedT>.EncoderGuard g = (path, instance) => encoderGuard(path, (TypeT) instance);
_guards.add(typeof(TypeT), g);
return this;
}
public IFaserFormatter<EncodedT> DecodeIf<ValueT>(Func<EncodedT, bool> decoderGuard)
{
Debug.Assert(decoderGuard != null);
return DecodeIf<ValueT>((path, value) => decoderGuard(value));
}
public IFaserFormatter<EncodedT> DecodeIf<TypeT>(Func<IMemberPath, EncodedT, bool> decoderGuard)
{
Debug.Assert(decoderGuard != null);
_guards.add(typeof(TypeT), (path, encoded) => decoderGuard(path, encoded));
return this;
}
public IFaserFormatter<EncodedT> EncodingGuard(Func<IMemberPath, object, bool> encoderGuard)
{
Debug.Assert(encoderGuard != null);
_guards.add((Guards<EncodedT>.EncoderGuard)((path, value) => encoderGuard(path, value)));
return this;
}
public IFaserFormatter<EncodedT> DecodingGuard(Func<IMemberPath, EncodedT, bool> decoderGuard)
{
Debug.Assert(decoderGuard != null);
_guards.add((path, encoded) => decoderGuard(path, encoded));
return this;
}
public IFaserFormatter<EncodedT> Encoder<ValueT>(Func<ValueT, EncodedT> encoder)
{
Debug.Assert(encoder != null);
return Encoder<ValueT>((path, value) => encoder(value));
}
public IFaserFormatter<EncodedT> Encoder<ValueT>(Func<IMemberPath, ValueT, EncodedT> encoder)
{
Debug.Assert(encoder != null);
EncoderFunc e = (path, value) => encoder(path, (ValueT) value);
_typeEncoders.Add(typeof(ValueT), e);
return this;
}
public IFaserFormatter<EncodedT> Decoder<ValueT>(Func<EncodedT, ValueT> decoder)
{
Debug.Assert(decoder != null);
return Decoder<ValueT>((path, encoded) => decoder(encoded));
}
public IFaserFormatter<EncodedT> Decoder<ValueT>(Func<IMemberPath, EncodedT, ValueT> decoder)
{
Debug.Assert(decoder != null);
DecoderFunc e = (path, encoded) => decoder(path, encoded);
_typeDecoders.Add(typeof(ValueT), e);
return this;
}
public IFaserFormatter<EncodedT> ValueReader(Func<Type, Type> typeConverter, Func<object, Type, object> valueConverter)
{
Debug.Assert(typeConverter != null && valueConverter != null);
_valueConverters.addReader(typeConverter, valueConverter);
return this;
}
public IFaserFormatter<EncodedT> ValueWriter(Func<Type, Type> typeConverter, Func<object, Type, object> valueConverter)
{
Debug.Assert(typeConverter != null && valueConverter != null);
_valueConverters.addWriter(typeConverter, valueConverter);
return this;
}
/// Configures a default encoder for any type.
public IFaserFormatter<EncodedT> DefaultEncoder(Func<IMemberPath, object, EncodedT> encoder)
{
Debug.Assert(encoder != null);
_defaultEncoder_ = (p, o) => encoder(p, o);
return this;
}
/// Configures a default decoder for any type.
public IFaserFormatter<EncodedT> DefaultDecoder(Func<IMemberPath, EncodedT, object> decoder)
{
Debug.Assert(decoder != null);
_defaultDecoder_ = (path, encoded) => decoder(path, encoded);
return this;
}
public IAggregateConfiguration<EncodedT, ObjectT> Configure<ObjectT>()
{
var t = typeof(ObjectT);
IAggregateConfiguration conf;
if (!_aggregateConfigurations.TryGetValue(t, out conf))
{
conf = new AggregateConfiguration<EncodedT, ObjectT>(this);
_aggregateConfigurations.Add(t, conf);
}
return (IAggregateConfiguration<EncodedT, ObjectT>)conf;
}
public ITypeConfiguration<EncodedT, TypeT> ForType<TypeT>()
{
return new TypeConfiguration<EncodedT, TypeT>(this);
}
#region Encoder
EncodedT encode(IAggregatePath path, object instance)
{
if (_aggregateEncoderFactory_ == null)
throw new FaserException("No aggregate encoder configured");
if (!path.TypeInfo.IsObject)
throw new FaserException(path, "Faser does not support non-composite root instances");
return encodeAggregate(path, instance);
}
EncodedT encodeAggregate(
IAggregatePath path,
object instance)
{
var thisEncoder = _aggregateEncoderFactory_(path, instance);
var typeInfo = path.TypeInfo;
Debug.Assert(typeInfo.IsObject);
foreach (var member in typeInfo.Members)
{
var memberPath = new MemberPath(path, member, getMemberAttributes(typeInfo, member));
encodeMember(thisEncoder, instance, memberPath);
}
return thisEncoder.Result;
}
void encodeMember(
IAggregateEncoder<EncodedT> aggregateEncoder,
object objectInstance,
IMemberPath memberPath)
{
var member = memberPath.Member;
var type = member.TypeInfo;
var memberInstance = member.Get(objectInstance);
var systemType = type.Type;
if (!_guards.shouldEncode(memberPath, memberInstance))
return;
var encoder_ = tryResolveMemberEncoder(systemType);
EncodedT res;
if (encoder_ == null && memberInstance != null && type.IsObject)
{
var instancePath = new AggregatePath(memberPath, type, getAggregateAttributes(type));
res = encodeAggregate(instancePath, memberInstance);
}
else
{
var memberEncoder = resolveMemberEncoder(memberPath, encoder_);
res = memberEncoder(memberPath, memberInstance);
}
aggregateEncoder.WriteMember(memberPath, res);
}
#endregion
#region Decoder
object decode(IAggregatePath path, EncodedT encoded)
{
if (_aggregateDecoderFactory_ == null)
throw new FaserException(path, "No aggregate decoder configured");
if (!path.TypeInfo.IsObject)
throw new FaserException(path, "Faser does not support non-composite root objects");
return decodeObject(path, encoded);
}
object decodeObject(IAggregatePath path, EncodedT encoded)
{
var typeInfo = path.TypeInfo;
Debug.Assert(typeInfo.IsObject);
var instance = typeInfo.NewInstance();
var aggregateDecoder = _aggregateDecoderFactory_(path, encoded);
foreach (var member in typeInfo.Members)
{
var memberPath = new MemberPath(path, member, getMemberAttributes(typeInfo, member));
decodeMember(aggregateDecoder, instance, memberPath);
}
return instance;
}
void decodeMember(
IAggregateDecoder<EncodedT> aggregateDecoder,
object objectInstance,
IMemberPath memberPath)
{
var member = memberPath.Member;
var memberType = member.TypeInfo;
object decoded;
var decoder_ = tryResolveMemberDecoder(memberType.Type);
var encoded = aggregateDecoder.ReadMember(memberPath);
if (!_guards.shouldDecode(memberPath, encoded))
return;
if (decoder_ == null && memberType.IsObject)
{
var instancePath = new AggregatePath(memberPath, memberType, getAggregateAttributes(memberType));
decoded = decodeObject(instancePath, encoded);
}
else
{
var decoder = resolveMemberDecoder(memberPath, decoder_);
decoded = decoder(memberPath, encoded);
}
member.Set(objectInstance, decoded);
}
IEnumerable<Attribute> getAggregateAttributes(ITypeInfo aggregate)
{
var staticAttributes = aggregate.Attributes;
IAggregateConfiguration ac;
if (!_aggregateConfigurations.TryGetValue(aggregate.Type, out ac))
return staticAttributes;
return ac
.GetAttributes()
.Concat(staticAttributes);
}
IEnumerable<Attribute> getMemberAttributes(ITypeInfo enclosingType, IMemberInfo mi)
{
var staticAttributes = mi.Attributes;
IAggregateConfiguration ac;
if (!_aggregateConfigurations.TryGetValue(enclosingType.Type, out ac))
return staticAttributes;
return ac
.GetAttributesForMember(mi.Name)
.Concat(staticAttributes);
}
#endregion
#region Encoder / Decoder Resolvement
EncoderFunc tryResolveMemberEncoder(Type type)
{
EncoderFunc encoder;
if (_typeEncoders.TryGetValue(type, out encoder))
return encoder;
// no explicit type encoder, can we change type?
var reader = _valueConverters.tryResolveReader(type);
if (reader == null)
return null;
var newSourceType = reader.ConvertType(type);
var targetEncoder = tryResolveMemberEncoder(newSourceType);
if (targetEncoder == null)
return null;
return (memberPath, instance) =>
{
// note: leaky abstraction here, path refers to the original type.
var converted = reader.ConvertValue(instance, type);
return targetEncoder(memberPath, converted);
};
}
EncoderFunc resolveMemberEncoder(IFaserPath path, EncoderFunc memberEncoder_)
{
if (memberEncoder_ != null)
return memberEncoder_;
if (_defaultEncoder_ != null)
return _defaultEncoder_;
throw new FaserException(path, "No encoder configured");
}
DecoderFunc tryResolveMemberDecoder(Type type)
{
DecoderFunc decoder;
if (_typeDecoders.TryGetValue(type, out decoder))
return decoder;
var writer = _valueConverters.tryResolveWriter(type);
if (writer != null)
{
var newSourceType = writer.ConvertType(type);
var targetDecoder = tryResolveMemberDecoder(newSourceType);
if (targetDecoder == null)
return null;
return (memberPath, encoded) =>
{
var decodedTarget = targetDecoder(memberPath, encoded);
return writer.ConvertValue(decodedTarget, type);
};
}
return null;
}
DecoderFunc resolveMemberDecoder(IFaserPath path, DecoderFunc memberDecoder_)
{
if (memberDecoder_ != null)
return memberDecoder_;
if (_defaultDecoder_ != null)
return _defaultDecoder_;
throw new FaserException(path, "No decoder configured");
}
#endregion
}
}
|
3a26f1349064c0efc6bc7ce84e6e25256e100167
|
[
"C#"
] | 42
|
C#
|
pragmatrix/Faser
|
9b172d4c81df34c2f610854c7bbb7a936030360a
|
b73f977e378a9d51e86bb73773b7d5105f7be617
|
refs/heads/master
|
<file_sep>CREATE DATABASE bee_crypt_bzz;
\c bee_crypt_bzz
CREATE TABLE accounts (id SERIAL PRIMARY KEY, user_name VARCHAR(255), user_email VARCHAR (255), password_digest VARCHAR (255), is_admin BOOLEAN);
\dt
|
3fba165943f3279606239fcaefb977651fb85f50
|
[
"SQL"
] | 1
|
SQL
|
spramp/secure_my_splat
|
b7de6d9ce31e64d0a1f991900a7d2e4796a52a43
|
4e9bbd9e05a0074199a8487fad243ea48c940382
|
refs/heads/master
|
<file_sep>var items={};
function remove(id){
delete items[$('#row-'+id+' .col-sm-5 p').text()];
$('#row-'+id).remove();
console.log(items);
}
$(document).ready(function() {
var id=0;
$('#add-skill').click(function(event){
var skill=$('#input-skill :selected').text();
var point=$('#input-point').val();
// console.log(skill);
if(skill in items){
return;
}
else{
items[skill]=[$('#input-skill').val(),point];
$('#skill-list').append(
'<div class="row skill-row d-flex justify-content-center" id="row-'+id+'">'+
'<div class="col-sm-5" style="text-align:center;">'+
'<p>'+skill+'</p>'+
'</div>'+
'<div class="col-sm-2" style="text-align:center;">'+
'<p>'+point+'</p>'+
'</div>'+
'<div class="col-sm-3" style="text-align:center;">'+
'<a class="skill-remove fa fa-times" style="color:rgb(255, 5, 5);font-size:35px;cursor:pointer" value="cancel" onclick="remove('+id+')"></a>'+
'</div>'+
'</div>'
);
id++;
}
});
$('#submit-job').click(function(event){
var uploaded = {};
$.each( items, function( key, value ) {
uploaded[ value[0] ] = value[1];
});
$('#job-list').val(JSON.stringify(uploaded));
});
});
<file_sep><?php
namespace App\Policies;
use App\Member;
use App\Company;
use App\Job;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Foundation\Auth\User as User;
class JobPolicy
{
use HandlesAuthorization;
/**
* Create a new policy instance.
*
* @return void
*/
public function __construct()
{
//
}
public function view(User $user)
{
return TRUE;
}
public function edit(User $user, Job $job)
{
return $user instanceof Company && $user->c_id == $job->company_id;
}
public function delete(User $user, Job $job)
{
return $user instanceof Company && $user->c_id == $job->company_id;
}
public function create(User $user)
{
return $user instanceof Company;
}
public function take(User $user)
{
return $user instanceof Member;
}
public function companyListJob(User $user)
{
return $user instanceof Company;
}
public function memberListJob(User $user)
{
return $user instanceof Member;
}
}
<file_sep>function editComment(email){
// console.log();
$('#edit-comment').val( $('td[value="'+email+'"] p').text() );
$('#save-comment').val(email);
$('#modal-comment .modal-title').text('comment for '+email);
}
function getDownloadUrl(email){
var data_send = JSON.stringify({
"job_id" : $('meta[name="job-id"]').attr('content'),
"email": email
});
$.ajax({
url: '/job/get_submission_url',
type: 'GET',
data: {data_send},
success: function (data) {
// console.log('berhasil');
console.log(data);
window.open(data['url'],'_blank');
$('a[value="'+email+'"]').removeClass('btn-warning btn-success').addClass('btn-primary');
$('p[value="'+email+'"]').removeClass('text-warning text-success').addClass('text-primary');
$('p[value="'+email+'"]').text('Viewed');
}
}).fail(function (xhr, error, thrownError) {
console.log(xhr, error, thrownError);
});
}
$(document).ready(function(){
$('#rank-table').DataTable();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#save-comment').click(function(event){
res = $('#edit-comment').val();
data_send = JSON.stringify(
{
"job_id" : $('meta[name="job-id"]').attr('content'),
"email": $('#save-comment').val(),
"comment": res
}
);
$.ajax({
url: '/job/edit_comment',
type: 'POST',
data: {data_send},
success: function (data) {
$('td[value="'+$('#save-comment').val()+'"] p').text(res);
$('#modal-comment').slideUp();
$(".modal-backdrop").slideUp();
}
}).fail(function (xhr, error, thrownError) {
console.log(xhr, error, thrownError);
});
});
//not used
// $('#submit-change').click(function(event){
// data_send = JSON.stringify({"data" : $('#rank-table').DataTable().rows().data()});
// $.ajax({
// url: '/job/update_rank',
// type: 'post',
// data: {data_send},
// success: function (data) {
// }
// }).fail(function (xhr, error, thrownError) {
// console.log(xhr, error, thrownError);
// });
// });
});
<file_sep>var data = [
{
id: 1,
text: 'website front-end'
},
{
id: 2,
text: 'website back-end'
},
{
id: 3,
text: 'mobile android'
},
{
id: 4,
text: 'mobile IOS'
}
];
var idtimer = [];
var time_list = [];
//used for changing page
var latest_query = "";
function int_to_time(detik){
var second = parseInt((detik%60));
var minute = parseInt((detik%3600)/60);
var hour = parseInt((detik/3600)%24);
var day = parseInt((detik/86400));
return ""+day+" D : "+hour+" H : "+minute+" m : "+second+" s";
}
function calcTimer(){
idtimer.length = 0;
time_list.length = 0;
$('[id^=time-]').each(function(i,element){
idtimer.push($('#time-'+i));
time_list.push(idtimer[i].attr('value'));
});
setInterval(function() {
for(var j = 0 ;j < time_list.length ; j++){
if(time_list[j] > 0){
idtimer[j].text(int_to_time(time_list[j]));
time_list[j]--;
}
else{
idtimer[j].text("time out");
}
}
}, 1000);
}
$(document).ready(function(){
var isNameFilter = true;
$("#search-select2").select2({placeholder: "search by category"});
function ajaxSearch(){
var data_send = null;
if(isNameFilter){
data_send = JSON.stringify({"type":"name-filter","query" : $('#search-text').val()});
latest_query = data_send;
}
else{
data_send = JSON.stringify({"type":"skill-filter","data" : $('#search-select2').select2('data')});
latest_query = data_send;
}
$.ajax({
url: '/job/search_query',
type: 'get',
data: {data_send},
success: function (data) {
$('#search-result').html(data);
calcTimer();
ajax_refresh();
}
}).fail(function (xhr, error, thrownError) {
console.log(xhr, error, thrownError);
});
}
$('#by-category').click(function(event){
if(isNameFilter == false){return;}
isNameFilter = false;
$('#search-text').css('display','none');
$('<select id="search-select2" style="height:100%" multiple="true"></select>')
.insertAfter('#search-text');
$("#search-select2").select2({
placeholder : "search by skill category",
data : data
});
});
$('#by-name').click(function(event){
if(isNameFilter == true){return;}
isNameFilter = true;
$("#search-select2").select2('destroy');
$("#search-select2").remove();
$('#search-text').css('display','inline-block');
});
$('#search-text').keypress(function(e) {
if(e.which == 13){
ajaxSearch();
}
});
function ajax_refresh(){
$('.pagination li a').click(function(e){
e.preventDefault();
e.stopPropagation();
data_send = latest_query;
$.ajax({
url: $(this).attr('href').slice(21),//next page url
type: 'get',
data: {data_send},
success: function(data){
$('#search-result').html(data);
calcTimer();
ajax_refresh();
}
}).fail(function(xhr, error, thrownError){
console.log(xhr, error, thrownError);
});
});
}
$("#search-btn").click( function(event) {
ajaxSearch();
});
$('.search-panel .dropdown-menu').find('a').click(function(e) {
e.preventDefault();
var param = $(this).attr("href").replace("#","");
var concept = $(this).text();
$('.search-panel span#search_concept').text(concept);
$('.input-group #search_param').val(param);
});
});
<file_sep><?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Session;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
/**
* Shows login form.
*
* @return void
*/
public function showLoginForm(){
return view('login');
}
/**
* Execute login.
*
* @param Illuminate\Http\Request $request
* @return Illuminate\Http\Request
*/
public function doLogin(Request $request){
$guards = ['member' => 'm_name', 'company' => 'c_name'];
$credentials = $request->only('email','password');
foreach($guards as $guard => $name)
{
if(Auth::guard($guard)->attempt($credentials))
{
$user = Auth::guard($guard)->user();
$request->session()->flash('alert',
'Welcome back to Wngine, '.$user->$name.'!');
$request->session()->flash('alert-type', 'success');
return redirect(route('home'));
}
}
$request->session()->flash('alert', 'Invalid Email/Password');
$request->session()->flash('alert-type', 'failed');
return redirect(route('login'));
}
/**
* Execute logout.
*
* @return Illuminate\Http\Request
*/
public function logout(){
Auth::guard('company')->logout();
Auth::guard('member')->logout();
return redirect('home');
}
}
<file_sep><?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Hash;
class ChangePasswordEmailController extends Controller
{
/*
|--------------------------------------------------------------------------
| Change Password Email Controller
|--------------------------------------------------------------------------
|
| This controller handles user's request to change their password
|
*/
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth:member,company');
}
/**
* Shows login form.
*
* @return void
*/
public function showForm(){
return view('password_change');
}
/**
* Execute change password
*
* @param Illuminate\Http\Request $request
* @return view
*/
public function doChange(Request $request)
{
$request->validate([
'old_password' => '<PASSWORD>',
'new_password' => '<PASSWORD>',
]);
$old_password = $request->old_password;
$new_password = $request->new_password;
if(!Hash::check($old_password, $request->user()->password))
return Redirect::back()->withErrors([
'old_password' => 'Old password doesn\'t match',
]);
$request->user()->fill([
'password' => <PASSWORD>::make($new_<PASSWORD>),
])->save();
$request->session()->flash('alert', 'Password successfully reset');
$request->session()->flash('alert-type', 'success');
return redirect(route('home'));
}
}
<file_sep>$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Dropzone.options.submitJob = {
headers : { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } ,
maxFiles : 1,
init : function() {
myDropzone = this;
var prevFile = null;
this.on("addedfile", function(file) {
if(prevFile != null){
this.removeFile(prevFile);
}
prevFile = file;
});
this.on('success',function(file,response){//success get response
// console.log(response);
if(response['status'] == "success"){
$('#submit-name').text("File name: "+prevFile['upload']['filename']);
$('#submit-time').text("Last submission: "+response['message']);
}
else{
}
});
}
};
$('#save-description').click(function(event){
var data_send = JSON.stringify({
"new_description": $('#edit-description').val()
});
// console.log();
$.ajax({
url: "/job/edit_description/"+$('#job-id').val(),
type: 'POST',
data: {data_send},
success: function (response) {
// console.log(response);
if(response['status'] == 'success'){
$('#jobDesc').text($('#edit-description').val());
}
alert(response['message']);
$('#dismiss-modal-desc').trigger('click');
}
}).fail(function (xhr, error, thrownError) {
alert('something wrong :(');
});
});
});
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Job;
use App\Company;
use App\Skill;
use Storage;
use Validator;
use Session;
use Illuminate\Support\Facades\Auth;
class JobController extends Controller
{
/*
status jobs
0 = belum submit
1 = sudah di cek
2 = ada update lagi
3 = sudah submit, belum di cek
4 = udah dibayar
dimunculkan di list project dengan order descending
*/
public function __construct()
{
$this->middleware('auth:company,member')
->except([
'searchQuery',
'showDescriptionJob',
'showJobSearch',
]
);
}
public function homeQuery(Request $request){
}
public function showPostingJobForm(){
$user = Auth::user();
if($user->cannot('create', Job::class))
return redirect('/home');
$skill = Skill::all();
$skill_list = array();
foreach($skill as $s)
$skill_list[$s->id] = $s->name;
return view('job.job_create', ['skill' => $skill_list]);
}
public function postingJob(Request $request){
$xx = Validator::make($request->all(),[
'name' => 'required|min:6',
'finishDate' => 'required|date_format:Y-m-d|after:'.date("Y-m-d"),
'job_list' => 'required|min:3',
'shortDescription' => 'required',
'documentnya' => 'mimes:pdf'
],
[
'job_list.required' => 'you must pay :(',
'finishDate.after' => 'the deadline must be atleast tomorrow',
'job_list.min' => 'you must put atleast one skill point reward'
]
)->validate($request->all());
$skill_list = json_decode($request->job_list, true);
$sum_point = 0;
foreach($skill_list as $s_id => $point)
{
$sum_point+=$point;
}
if($sum_point > Auth::guard('company')->user()->c_poin){
Session::flash('alert','Not enough poin in your account, please do top up :)');
Session::flash('alert-type','warning');
Session::flashInput($request->all());
$skill = Skill::all();
$skill_list = array();
foreach($skill as $s){
$skill_list[$s->id] = $s->name;
}
return view('job.job_create',['skill' => $skill_list]);
}
$targetPath = null;
if($request->has('documentnya')){
$path = Storage::putFile('public', $request->file('documentnya'));
$targetPath = date('Y-m-d-H-m-s').'-'.$request->file('documentnya')->getClientOriginalName();
Storage::move($path,'job_documents/'.$targetPath);
}
// dd($targetPath)
$company_id = Auth::guard('company')->user()->c_id;
$job = Job::create([
'name' => $request->name,
'description' => $request->shortDescription,
'upload_date' => date('Y-m-d'),
'finish_date' => $request->finishDate,
'document' => $targetPath,
'company_id' => $company_id,
]);
foreach($skill_list as $s_id => $point)
{
DB::table('job_skills')
->insert([
'job_id' => $job->id,
'skill_id' => $s_id,
'point' => $point,
]);
}
return redirect('job/detail/'.$job->id);
}
public function searchQuery(Request $request){
$data_sent = json_decode($request->data_send);
if($data_sent->type == "name-filter"){
$jobs = DB::table('jobs')
->select('jobs.*','company.c_name','company.c_image',
DB::raw('GROUP_CONCAT(job_skills.skill_id) as skill_list'),
DB::raw('GROUP_CONCAT(job_skills.point) as point_list'),
DB::raw('sum(job_skills.point) as point')
)
->join('job_skills','jobs.id','=','job_skills.job_id')
->join('skills','skills.id','=','job_skills.skill_id')
->join('company','company.c_id','=','jobs.company_id')
->where('jobs.name','like','%'.$data_sent->query.'%')
->orWhere('company.c_name','like','%'.$data_sent->query.'%')
->groupBy('jobs.id')->paginate(10);
foreach ($jobs as $job) {
$job->skill_list = preg_split("/,/",$job->skill_list);
}
//dd($jobs);
return view('job.search_result_subpage',compact('jobs'));
}
else{
$data_sent = $data_sent->data;
$skill_search = [];
foreach ($data_sent as $data) {
array_push($skill_search,$data->id);
}
$jobs = DB::table('jobs')
->select('jobs.id as jid')
->join('job_skills',function($join) use($skill_search) {
$join->on('jobs.id','=','job_skills.job_id')->whereIn('job_skills.skill_id',$skill_search);
})->distinct()->get();
$target_id = [];
foreach ($jobs as $job) {
array_push($target_id,$job->jid);
}
$jobs = DB::table('jobs')
->select('jobs.*','company.c_name','company.c_image',
DB::raw('GROUP_CONCAT(job_skills.skill_id) as skill_list'),
DB::raw('GROUP_CONCAT(job_skills.point) as point_list'),
DB::raw('sum(job_skills.point) as point')
)
->join('job_skills',function($join) use($target_id) {
$join->whereIn('jobs.id',$target_id);
$join->on('jobs.id','=','job_skills.job_id');
})
->join('company','company.c_id','=','jobs.company_id')
->groupBy('jobs.id')->paginate(10);
foreach ($jobs as $job) {
$job->skill_list = preg_split("/,/",$job->skill_list);
}
return view('job.search_result_subpage',compact('jobs'));
}
}
public function showJobSearch(){
return view('job.job_search');
}
public function showDescriptionJob($id)
{
$job = Job::find($id);
$data = array();
$data['id'] = $id;
$data['job_name'] = $job->name;
$data['start_date'] = $job->upload_date;
$data['due_date'] = $job->finish_date;
$company = Company::select('c_name','c_image')
->where('c_id', $job->company_id)
->first();
$data['company_name'] = $company->c_name;
$data['company_photo'] = asset('company_photo').'/'.$company->c_image;
$data['description'] = $job->description;
$data['document_url'] = asset('job_documents').'/'.$job->document;
$data['skills'] = array();
$job_skill = DB::table('job_skills')
->where('job_id', $job->id)
->get();
$total = 0;
foreach($job_skill as $v)
{
$skill = Skill::select('name')->where('id', $v->skill_id)->first()->name;
$data['skills'][$skill] = $v->point;
$total+=$v->point;
}
$data['total_point'] = $total;
if(Auth::guard('member')->check()){
$worker = self::getWorkerData($id);
$data['had_taken'] = false;
if($worker != null){
$data['had_taken'] = true;
$data['file_name'] = null;
$data['file_path'] = null;
$data['submit_time'] = null;
if($worker->submission_path != null){
$data['file_name'] = substr($worker->submission_path,20);
$data['file_path'] = asset('job_submissions').'/'.$worker->submission_path;
$data['submit_time'] = $worker->last_submit_time;
}
}
}
return view('job.job_description', [
'data' => $data,
'job' => $job,
]);
}
public function getWorkerData($jobId){
$res = DB::table('jobs_taken')->select('worker_email','submission_path','last_submit_time')
->where('worker_email','=',Auth::guard('member')->user()->email)
->where('job_id','=',$jobId)->first();
return $res;
}
public function takeJob(Request $request){
$job_id = json_decode($request["param"],true)['job_id'];
if($job_id != null){
$counter = DB::table('jobs_taken')->select(DB::raw('count(job_id) as job_count'))
->where('worker_email','=',Auth::guard('member')->user()->email)
->groupBy('worker_email')->first();
if($counter != null && $counter->job_count > 4){
return "Sorry, you can't take more than 5 job";
}
if(self::getWorkerData($job_id) != null){
return response()->json([
'status' => 'failed',
'message' => 'You had taken this job before'
]);
}
DB::table('jobs_taken')->insert(
['job_id' => $job_id,
'worker_email' => Auth::guard('member')->user()->email,
'status' => 0,
'comment' => '',
'last_submit_time' => date("Y-m-d H:i:s")
]
);
}
else{
return response()->json([
'status' => 'failed',
'message' => "don't try to hacking us *_*"
]);
}
return response()->json([
'status' => 'success',
'message' => "success taking the job, Do your best :)"
]);
}
public function companyProjectList(){
$user = Auth::user();
if($user->cannot('companyListJob', Job::class))
return redirect('/home');
$jobs = Job::where('company_id', $user->c_id)->get();
foreach ($jobs as $job) {
$job->isFinish = strtotime($job->finish_date) < strtotime(date('Y-m-d'));
}
return view('job.company-project-list', compact('jobs'));
}
public function memberProjectList(){
$user = Auth::user();
if($user->cannot('memberListJob', Job::class)){
Session::flash('alert','Anda belum login!');
Session::flash('alert-type','failed');
return redirect('/home');
}
$jobs = DB::table('jobs_taken')
->select('*')
->where('worker_email', $user->email)
->join('jobs','jobs.id','=','jobs_taken.job_id')->get();
foreach ($jobs as $job)
{
$job->isFinish = strtotime($job->finish_date) < strtotime(date('Y-m-d'));
if($job->last_submit_time != null)
{
$job->submission_path = asset('job_submissions').'/'.$job->submission_path;
}
}
return view('job.member-project-list', compact('jobs'));
}
public function projectAdmin($id){
$job = DB::table('jobs')->select('*')
->where('id','=',$id)
->where('company_id','=',Auth::guard('company')->user()->c_id)
->first();
if($job == null){
Session::flash('alert','Anda tidak berhak mengakses laman tersebut');
Session::flash('alert-type','failed');
return redirect(route('home'));
}
$isFinish = strtotime($job->finish_date) < strtotime(date('Y-m-d'));
$lists = DB::table('jobs_taken')->select('*')
->join('members','members.email','=','jobs_taken.worker_email')
->where('job_id','=',$id)
->orderBy('status','desc')
->get();
if($isFinish){
$skills = DB::table('job_skills')->select('*')
->where('job_id','=',$id)
->join('skills','skills.id','=','skill_id')
->get();
return view('job.project-list-detail-finished', compact('lists'))
->with(['job_id' => $id,'skills' => $skills]);
}
else{
return view('job.project-list-detail', compact('lists'))->with(['job_id' => $id]);
}
}
public function updateComment(Request $request){
$data = json_decode($request->data_send,true);
DB::table('jobs_taken')
->where('job_id','=',$data['job_id'])
->where('worker_email','=',$data['email'])
->update(['comment' => $data['comment']]);
var_dump($data);
}
public function editDescription(Request $request){
$job = Job::where('id','=',$request->id)
->where('company_id','=',Auth::guard('company')->user()->c_id);
if($job->first() == null){
Session::flash('alert','Invalid request');
Session::flash('alert-type','failed');
return redirect(route('home'));
}
$data = json_decode($request->data_send,true);
$job->update(['description' => $data['new_description']]);
return response()->json([
'status' => 'success',
'message' => 'success edit job description'
]);
}
public function submitJob(Request $request){
if($request->file('file') != null){
$path = Storage::putFile('public', $request->file('file'));
// dd($request->file('file'));
$targetPath = date('Y-m-d-H-m-s').'-'.$request->file('file')->getClientOriginalName();
// dd('errorsini2'.$request->file('file'));
$worker = self::getWorkerData($request->id);
$oldfile = $worker->submission_path;
$status = 3;
if($oldfile != null){
Storage::delete('job_submissions/'.$oldfile);
$status = 2;
}
$updateTime = date("Y-m-d H:i:s");
DB::table('jobs_taken')
->where('job_id','=',$request->id)
->where('worker_email','=',Auth::guard('member')->user()->email)
->update(
[
'submission_path' => $targetPath,
'last_submit_time' => $updateTime,
'submission_path' => 'job_submissions/'.$targetPath,
'status' => $status
]
);
Storage::move($path,'job_submissions/'.$targetPath);
return response()->json([
'status' => 'success',
'message' => $updateTime
]);
}
else{
return response()->json([
'status' => 'failed',
'message' => ''
]);
}
}
public function getSubmissionUrl(Request $request){
$data = json_decode($request->data_send,true);
DB::table('jobs_taken')
->where('worker_email','=',$data['email'])
->where('job_id','=',$data['job_id'])
->update(['status' => 1]);
$res = DB::table('jobs_taken')->select('submission_path')
->where('worker_email','=',$data['email'])
->where('job_id','=',$data['job_id'])->first();
return response()->json([
'status' => 'success',
'url' => asset('job_submissions').'/'.$res->submission_path
]);
}
public function payWorker(Request $request){
$data = json_decode($request->data_send,true);
//validasi request vs data di table, poin request <= data di table
$job_skills = DB::table('job_skills')->select('*')->where('job_id','=',$request->id)->get();
foreach ($job_skills as $skill) {
if(array_key_exists((string)$skill->skill_id, $data['skill_list']) ){
if((int)$data['skill_list'][$skill->skill_id] > $skill->point ){
Session::flash('alert','Invalid request');
Session::flash('alert-type','failed');
return redirect(route('home'));
}
}
}
$total = 0;
$check = DB::table('jobs_taken')
->where('job_id','=',$request->id)
->where('worker_email','=',$data['worker_email']);
if($check->first() == null){
Session::flash('alert','Invalid request');
Session::flash('alert-type','failed');
return redirect(route('home'));
}
$check->update(['status' => 4]);
foreach ($data['skill_list'] as $key => $value) {
DB::table('job_skills')
->where('job_id','=',$request->id)
->where('skill_id','=',$key)
->decrement('point',(int)$value);
$query = DB::table('member_points')
->where('member_id','=',$data['worker_id'])
->where('skill_id','=',$key);
if($query->first() == null){
DB::table('member_points')
->insert([
'member_id' => $data['worker_id'],
'skill_id' => $key,
'point' => (int)$value
]);
}
else{
$query->increment('point',(int)$value);
}
$total+=(int)$value;
}
DB::table('members')->where('m_id','=',$data['worker_id'])
->increment('claimable_point',$total);
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class RegistrationsCompany extends Model
{
protected $table = 'registrationsCompany';
protected $fillable = [
'rgc_email', 'rgc_name','rgc_token','rgc_address','rgc_password','rgc_telp'
];
public $timestamps = false;
}
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateJob extends Migration
{
public function up()
{
Schema::create('jobs', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 50)->unique();
$table->string('description', 250);
$table->integer('company_id')->unsigned();
$table->date('upload_date');
$table->date('finish_date');
$table->string('document',100)->nullable();
$table->foreign('company_id')->references('c_id')->on('company')
->onDelete('cascade')->onUpdate('cascade');
});
}
public function down()
{
Schema::dropIfExists('jobs');
}
}
<file_sep><?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Validator;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Validator::extend('strong_pwd', function($attribute, $value, $parameters, $validator) {
return preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).{6,}$/', (string)$value);
},"weak password");
Validator::extend('phone_number', function($attribute, $value, $parameters, $validator) {
return preg_match('/^\+[0-9]{12,15}$/', (string)$value);
},"invalid phone number");
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
<file_sep><?php
namespace App\Policies;
use App\Member;
use App\Company;
use Illuminate\Foundation\Auth\User as User;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Support\Facades\DB;
class MemberPolicy
{
use HandlesAuthorization;
public function write_testimony2(User $user, Member $member)
{
$job_done_at_company = DB::table('jobs_taken')
->join('jobs', 'jobs.id', '=', 'jobs_taken.job_id')
->where('jobs_taken.worker_email', '=', $member->email)
->where('jobs_taken.status', '=', '4')
->where('jobs.company_id', '=', $user->c_id)
->get();
return $user instanceof Company && count($job_done_at_company);
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
use App\Company;
use Illuminate\Support\Facades\Hash;
class CompanySeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Company::create([
'c_name' => '<NAME>',
'email' => '<EMAIL>',
'c_address' => 'INFORMATIKA',
'password' => <PASSWORD>('<PASSWORD>'),
'c_telp' => '1234567890',
'remember_token' => 'a',
]);
Company::create([
'c_name' => '<NAME>',
'email' => '<EMAIL>',
'c_address' => 'INFORMATIKA',
'password' => <PASSWORD>('edo'),
'c_telp' => '1234567890',
'remember_token' => 'b',
]);
}
}
<file_sep><?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Mail\Mailer as Mailer;
use Mail;
use App\Member;
use App\Company;
use Illuminate\Foundation\Auth\User as User;
use Session;
use DB;
use Validator;
use Illuminate\Support\Facades\Input;
class ForgotPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset emails and
| includes a trait which assists in sending these notifications from
| your application to your users. Feel free to explore this trait.
|
*/
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Show the reset/forgot password request form
*
* @return view
*/
public function showForm()
{
return view('password_reset');
}
/**
* Handle email checking for reset password.
* Determine which email belongs to what role.
*
* @param Illuminate\Http\Request $request
* @return view
*/
public function resetPass(Request $request)
{
$email = $request->email;
if($user = Member::where('email', $email)->get()->first()) // if email belongs to Member
{
$this->doPasswordRequest($user, 'member');
return redirect(route('home'));
}
else if($user = Company::where('email', $email)->get()->first()) // if email belongs to Company
{
$this->doPasswordRequest($user, 'company');
return redirect(route('home'));
}
else
{
$request->session()->flash('alert', 'Email couldn\'t be found.');
$request->session()->flash('alert-type', 'warning');
return redirect(route('password_reset'));
}
}
/**
* Handle sending token to user requesting password reset.
*
* @param Illuminate\Foundation\Auth\User $user
* @param string $role
* @return void
*/
protected function doPasswordRequest(User $user, string $role){
$table_name = array(
'company' => 'company_rpass',
'member' => 'member_rpass',
);
$column_name = array(
'company' => 'c_name',
'member' => 'm_name',
);
$mailer_content = array(
'company' => Mailer::$Company,
'member' => Mailer::$Member,
);
$name = $column_name[$role];
// Old reset token found, delete first
if(count(DB::table($table_name[$role])->where('email', $user->email)->get())) {
DB::table($table_name[$role])->where('email',$user->email)->delete();
}
$linkToken = sha1("ha".$user->email.((string)date("l h:i:s"))."sh");
$mailObj = new Mailer();
DB::table($table_name[$role])->insert(
array('email' => $user->email, 'token' => $linkToken)
);
$mailObj->setResetPassMail(
$user->email,
$user->$name,
$linkToken,
$mailer_content[$role]
);
Mail::to($user->email)->send($mailObj);
session()->flash('alert', 'Confirmation link sent, please check your inbox');
session()->flash('alert-type','success');
}
/**
* Show reset password form after token confirmation (Company)
*
* @param @param Illuminate\Http\Request $request
* @return view
*/
public function memberNewPwdForm(Request $request){
$userRow = DB::table('member_rpass')->where('token',$request->token)->take(1)->get();
if(count($userRow) == 0){
Session::flash('alert-type','failed');
Session::flash('alert',"Invalid token!");
redirect('home');
}
else{
return view('members.new_password');
}
}
/**
* Show reset password form after token confirmation (Company)
*
* @param @param Illuminate\Http\Request $request
* @return view
*/
public function companyNewPwdForm(Request $request){
$userRow = DB::table('company_rpass')->where('token',$request->token)->take(1)->get();
if(count($userRow) == 0){
Session::flash('alert',"Invalid confirmation token!");
Session::flash('alert-type','failed');
return redirect('home');
}
else{
return view('company.new_password');
}
}
/**
* Reseting password for member.
*
* @param @param Illuminate\Http\Request $request
* @return view
*/
public function doMemberPwdReset(Request $request){
Member::where('email',$request->email)->update(['password' => <PASSWORD>($request->password_1)]);
DB::table('member_rpass')->where('email',$request->email)->delete();
Session::flash('alert',"Password changed, you can login now");
Session::flash('alert-type','success');
return redirect('home');
}
/**
* Reseting password for company.
*
* @param @param Illuminate\Http\Request $request
* @return view
*/
public function doCompanyPwdReset(Request $request){
Company::where('email',$request->email)->update(['password' => <PASSWORD>($request->password_1)]);
DB::table('company_rpass')->where('email',$request->email)->delete();
Session::flash('alert',"Password changed, you can login now");
Session::flash('alert-type','success');
return redirect('home');
}
}
<file_sep><?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class Mailer extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* @return void
*/
public const REGISTER=0,
RESET_PWD=1;
public static $Member=0,
$Company=1;
private $name,$token,$email;
private $mailType=null,$clientType=null;
public function __construct()
{
}
public function setResetPassMail($email,$name,$token,$userType){
$this->mailType = Mailer::RESET_PWD;
$this->clientType = (($userType == Mailer::$Member)?"member":"company");
$this->name = $name;
$this->token = $token;
$this->email = $email;
}
public function setRegistMail($name,$token,$userType){
$this->mailType = Mailer::REGISTER;
$this->clientType = (($userType == Mailer::$Member)?"member":"company");
$this->name = $name;
$this->token = $token;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
if($this->mailType == Mailer::REGISTER){
return $this->from('<EMAIL>')->subject('Wngine account registration confirmation')
->view('mails.register')
->with(['name' => $this->name,
'token' => $this->token,
'type' => $this->clientType]);
}
else if($this->mailType == Mailer::RESET_PWD){
return $this->from('<EMAIL>')->subject('Wngine account registration confirmation')
->view('mails.reset_pwd')
->with(['email' => $this->email,
'name' => $this->name,
'token' => $this->token,
'type' => $this->clientType]);
}
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\DB;
use App\Company;
use App\Job;
use App\Skill;
use App\RegistrationsCompany ;
use App\Mail\Mailer;
use Session;
use Mail;
use Auth;
use Storage;
use Validator;
class CompanyController extends Controller
{
public function register()
{
return view('company.register');
}
public function confirmRegistration(Request $request)
{
$userRow = RegistrationsCompany::where('rgc_token',$request->token)->take(1)->get();
if(count($userRow) == 0){
Session::flash('alert',"Invalid confirmation token!");
Session::flash('alert-type','failed');
}
else{
$userRow=$userRow[0];
Company::create([
'c_name' => $userRow['rgc_name'],
'email' => $userRow['rgc_email'],
'c_address' => $userRow['rgc_address'],
'password' => $<PASSWORD>['<PASSWORD>'],
'c_telp' => $userRow['rgc_telp']
]);
RegistrationsCompany::where('rgc_token',$request->token)->delete();
Session::flash('alert',"Registration complete, you can login now");
Session::flash('alert-type','success');
}
return redirect('home');
}
public function requestMailVerification(Request $request)
{
$validator = $request->validate([
'name' => 'required|min:4',
'password' => '<PASSWORD>',
'email' => 'required|email|unique:company|unique:members',
'address' => 'required|min:5',
'telp' => 'required|min:8',
]);
//if ($validator->fails()) {
// return Redirect::back()->withErrors($validator);
//}
// Check company name and email
$found_company = Company::where('c_name', $request->name)
->orWhere('email', $request->email)->get();
$found_registration_company = RegistrationsCompany::where('rgc_name', $request->name)
->orWhere('rgc_email', $request->email)->get();
if (count($found_company) != 0 || count($found_registration_company) != 0) {
return Redirect::back()->withErrors([
'name' => 'Either company name or email is currently used',
'email' => 'Either company name or email is currently used',
]);
}
$linkToken = sha1("ha".$request->email.((string)date("l h:i:s"))."sh");
RegistrationsCompany::create([
'rgc_email' => $request->email,
'rgc_name' => $request->name,
'rgc_token' => $linkToken,
'rgc_address' => $request->address,
'rgc_password' => <PASSWORD>),
'rgc_telp' => $request->telp
]);
$mailObj = new Mailer();
$mailObj->setRegistMail($request->name,$linkToken,Mailer::$Company);
Mail::to($request->email)->send($mailObj);
Session::flash('alert','Please confirm the registration through email we sent to you');
Session::flash('alert-type','success');
return redirect('home');
}
public function store(Request $request)
{
}
public function getTestimony($id){
return DB::table('member_companies')->select('*')
->where('company_id','=',$id)
->join('members','members.m_id','=','member_id')->get();
}
public function showProfile()
{
if(!Auth::guard('company')->check())
return redirect(route('home'));
$company = Company::find(Auth::guard('company')->user()->c_id);
$job_list = Job::latest('id')
->select('id', 'name', 'description')
->where('company_id', $company->c_id)
->take(4)
->get();
//dd($job_list);
return view('company.viewProfile', [
'company' => $company,
'jobs' => $job_list,
'own_profile' => true,
'testimonies' => self::getTestimony($company->c_id)
]);
}
public function showProfileById(int $id)
{
$company = Company::find($id);
if(!$company)
return redirect(route('home'));
$job_list = Job::latest('id')
->select('id', 'name', 'description')
->where('company_id', $company->c_id)
->take(4)
->get();
return view('company.viewProfile', [
'company' => $company,
'jobs' => $job_list,
'own_profile' => false,
'testimonies' => self::getTestimony($company->c_id)
]);
}
public function updateProfilPict(Request $request){
$request->validate([
'file' => 'mimes:png,jpg,jpeg'
]);
if($request->file('file') != null){
$path = Storage::putFile('public', $request->file('file'));
$targetPath = date('Y-m-d-H-m-s').'-'.$request->file('file')->getClientOriginalName();
$oldfile = DB::table('company')
->select('company.c_image')
->where('c_id','=',$request->id)->first()->c_image;
if($oldfile != null){
Storage::delete('company_photo/'.$oldfile);
}
Storage::move($path,'company_photo/'.$targetPath);
DB::table('company')
->where('c_id','=',$request->id)
->update(['c_image' => $targetPath]);
return response()->json([
'status' => 'success',
'newpath' => asset('company_photo').'/'.$targetPath
]);
}
}
public function updateTestimony(Request $request){
$company = Company::find($request->id);
$data = json_decode($request->data_send,true);
if(Auth::guard('member')->user()->can('write_testimony', $company)){
$query = DB::table('member_companies')->select('*')
->where('member_id','=',Auth::guard('member')->user()->m_id)
->where('company_id','=',$company->c_id);
if($query->first() == null){
DB::table('member_companies')->insert([
'member_id' => Auth::guard('member')->user()->m_id,
'company_id' => $company->c_id,
'content' => $data['new_testimoni']
]);
}
else{
$query->update([
'content' => $data['new_testimoni']
]);
}
}
return response()->json([
'status' => 'success',
'message' => 'Thanks for your testimoni'
]);
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function(){
return redirect('/home');
});
Route::group(['middleware' => 'authUser:member'], function() {
Route::post('member/change_profile/{nick}','MemberController@updateProfilPict')->name('post.member.changePict');
Route::post('member/change_name','MemberController@updateName')->name('post.member.changeName');
Route::post('member/change_quote','MemberController@updateQuote');
Route::get('member/profile','MemberController@showProfile')->name('member.profile');
Route::get('member/job/list','JobController@memberProjectList')->name('member.job.list');
Route::post('member/job/submit/{id}','JobController@submitJob')->name('member.job.submit');
Route::post('member/job/add_company_testimony/{id}','CompanyController@updateTestimony');
});
Route::group(['middleware' => 'authUser:company'], function() {
Route::get('company/profile', 'CompanyController@showProfile')->name('company.profile');
Route::get('company/job/list','JobController@companyProjectList')->name('company.job.list');
Route::get('company/job/detail/{id}','JobController@projectAdmin')->name('company.job.detail');
Route::post('company/job/pay/{id}','JobController@payWorker')->name('company.job.pay');
Route::post('company/change_profile/{id}','CompanyController@updateProfilPict')->name('post.company.changePict');
Route::post('job/edit_description/{id}','JobController@editDescription');
Route::post('company/job/add_member_testimony/{id}','MemberController@updateTestimony');
});
// Member
Route::get('member/confirmation','MemberController@confirmRegistration')->name('member.confirmation');
Route::post('member/register', 'MemberController@requestMailVerification')->name('post.member.register');
Route::get('member/register', 'MemberController@register')->name('member.register');
Route::get('member/password/reset_confirm','Auth\ForgotPasswordController@memberNewPwdForm')->name('member.password.reset');
Route::post('member/password/reset_confirm','Auth\ForgotPasswordController@doMemberPwdReset')->name('post.member.password.reset');
Route::get('member/profile/{id}','MemberController@showProfileById')->name('member.profilebyid');
// Company
Route::get('company/register','CompanyController@register')->name('company.register');
Route::post('company/register','CompanyController@requestMailVerification')->name('post.company.register');
Route::get('company/confirmation','CompanyController@confirmRegistration')->name('company.confirmation');
Route::get('company/password/reset_confirm','Auth\ForgotPasswordController@companyNewPwdForm')->name('company.password.reset');
Route::post('company/password/reset_confirm','Auth\ForgotPasswordController@doCompanyPwdReset')->name('post.company.password.reset');
Route::get('company/profile/{id}', 'CompanyController@showProfileById');
// Home
Route::get('home', 'HomeController@index')->name('home');
// Authentication Routes
Route::get('logout', 'Auth\LoginController@logout')->name('logout');
Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@doLogin');
Route::get('password_reset', 'Auth\ForgotPasswordController@showForm')->name('password_reset');
Route::post('password_reset', 'Auth\ForgotPasswordController@resetPass');
Route::get('password_change', 'Auth\ChangePasswordEmailController@showForm')->name('password_change');
Route::post('password_change', 'Auth\ChangePasswordEmailController@doChange');
// Job
Route::post('job/edit_comment','JobController@updateComment');
Route::get('job/search','JobController@showJobSearch')->name('job.search');
Route::get('job/detail/{id}','JobController@showDescriptionJob')->name('job.detail');
Route::get('job/search_query','JobController@searchQuery');
Route::get('job/create','JobController@showPostingJobForm')->name('job.postingJob');
Route::post('job/create','JobController@postingJob')->name('post.job.postingJob');
Route::post('job/take','JobController@takeJob')->name('post.job.take');
Route::get('job/get_submission_url','JobController@getSubmissionUrl');
// });
//untuk test view apapun
// Errors
Route::get('/404', function() {
return view('errors.404');
})->name('404');
Route::get('/403', function() {
return view('errors.403');
})->name('403');
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCompany extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('company', function (Blueprint $table) {
$table->increments('c_id');
$table->string('email',50)->unique();
$table->string('password',60);
$table->string('c_name',50)->unique();
$table->string('c_address',100);
$table->string('c_telp',15);
$table->string('c_image',100)->nullable(true);
$table->string('remember_token',60);
$table->integer('c_poin')->default(0);
});
}
public function down()
{
Schema::dropIfExists('company');
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
use App\Member;
use Illuminate\Support\Facades\Hash;
class MemberSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Member::create([
'm_name' => '<NAME>',
'email' => '<EMAIL>',
'm_borndate' => '01/01/01',
'm_address' => 'INFORMATIKA',
'password' => <PASSWORD>('<PASSWORD>'),
'm_telp' => '1234567890',
'remember_token' => 'a',
]);
Member::create([
'm_name' => '<NAME>',
'email' => '<EMAIL>',
'm_borndate' => '01/01/01',
'm_address' => 'INFORMATIKA',
'password' => <PASSWORD>('edo'),
'm_telp' => '1234567890',
'remember_token' => 'b',
]);
Member::create([
'm_name' => '<NAME>',
'email' => '<EMAIL>',
'm_borndate' => '01/01/01',
'm_address' => 'INFORMATIKA',
'password' => <PASSWORD>::make('<PASSWORD>'),
'm_telp' => '1234567890',
'remember_token' => 'c',
]);
}
}
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRegistrations extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('registrations', function (Blueprint $table) {
$table->string('rg_name',50)->unique();
$table->string('rg_email',50)->unique();
$table->string('rg_token',40);
$table->date('rg_borndate');
$table->string('rg_address',100);
$table->string('rg_password',72);
$table->string('rg_telp',15);
$table->string('rg_image',100)->nullable(true);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('registrations');
}
}
<file_sep>$(document).ready(function(){
$(window).bind('scroll', function () {
// if ($(window).scrollTop() > 106 && $(window).width() > 640) {
// $('#course_bar').addClass('floating-bar');
// }
// else{
// $('#course_bar').removeClass('floating-bar');
// }
if($(window).scrollTop()>8){
$('#scroll_up').css({'visibility': 'visible'});
}
else{
$('#scroll_up').css({'visibility': 'hidden'});
}
});
$("#scroll_up").click( function(event) {
if (this.hash !== "") {
$('html, body').animate({scrollTop : 0},800);
return false;
}
});
});
<file_sep><?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticable;
class Company extends Authenticable
{
protected $primaryKey = "c_id";
protected $table = 'company';
protected $fillable = [
'c_name', 'c_address',
'password', 'email', 'c_telp','c_image','remember_token','c_poin'
];
public $timestamps = false;
}
<file_sep><?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticable;
class Member extends Authenticable
{
protected $primaryKey = "m_id";
protected $fillable = [
'm_name', 'm_borndate', 'm_address',
'password', 'email', 'm_telp','quote'
];
protected $guarded = ['m_borndate'];
public $timestamps = false;
}
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMember extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('members', function (Blueprint $table) {
$table->increments('m_id');
$table->string('m_name',50);
$table->string('email',50)->unique();
$table->date('m_borndate');
$table->string('m_address',100);
$table->string('password',72);
$table->string('m_telp',15);
$table->integer('claimable_point')->default('0');
$table->string('m_image',100)->nullable(true);
$table->string('remember_token',60);
$table->string('quote',100);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('members');
}
}
<file_sep>$(document).ready(function()
{
$("#t1").click(function()
{
$("#s1").slideToggle("slow");
});
$("#t2").click(function()
{
$("#s2").slideToggle("slow");
});
$("#t3").click(function()
{
$("#s3").slideToggle("slow");
});
$("#t4").click(function()
{
$("#s4").slideToggle("slow");
});
$("#t5").click(function()
{
$("#s5").slideToggle("slow");
});
$("#t6").click(function()
{
$("#s6").slideToggle("slow");
});
$("#t7").click(function()
{
$("#s7").slideToggle("slow");
});
$("#t8").click(function()
{
$("#s8").slideToggle("slow");
});
Dropzone.options.changePict = {
headers : { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } ,
maxFiles : 1,
init : function() {
myDropzone = this;
var prevFile = null;
this.on("addedfile", function(file) {
if(prevFile != null){
this.removeFile(prevFile);
}
prevFile = file;
});
this.on('success',function(file,response){//success get response
console.log(response);
if(response['status'] == "success"){
$('#profile-pict').attr('src',response['newpath']);
$('#dismiss-modal-pict').trigger('click');
}
else{
}
});
}
};
$('#submit-testimoni').click(function(){
data_send = JSON.stringify({"new_testimoni" : $('#edit-testimoni').val()});
console.log($('meta[name="company-id"]').attr('content'));
$.ajax({
url: "/member/job/add_company_testimony/"+$('meta[name="company-id"]').attr('content'),
type: 'POST',
data: {data_send},
success: function (response) {
alert(response['message']);
$('#dismiss-testimoni').trigger('click');
}
}).fail(function (xhr, error, thrownError) {
alert('something wrong :(');
});
});
});
<file_sep><?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Session;
class AuthUser
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next,$usertype=null)
{
// dd(Auth::guard('company')->check());
if(Auth::guard('company')->check() && $usertype == "company"){
return $next($request);
}
else if(Auth::guard('member')->check() && $usertype == "member"){
return $next($request);
}
Session::flash('alert','You are not allowed to access that page!');
Session::flash('alert-type','failed');
return redirect(route('home'));
}
}
<file_sep><?php
namespace App\Policies;
use App\Member;
use App\Company;
use Illuminate\Foundation\Auth\User as User;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Support\Facades\DB;
class CompanyPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user (member) can write a testimony
* for a certain company.
*
* @param \Illuminate\Foundation\Auth\User $user
* @return boolean
*/
public function write_testimony(User $user, Company $company)
{
$job_done_at_company = DB::table('jobs_taken')
->join('jobs', 'jobs.id', '=', 'jobs_taken.job_id')
->where('jobs_taken.worker_email', '=', $user->email)
->where('jobs_taken.status', '=', '4')
->where('jobs.company_id', '=', $company->c_id)
->get();
return $user instanceof Member && count($job_done_at_company);
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
use App\Skill;
class SkillSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Skill::create([
'name' => 'Frontend Development',
]);
Skill::create([
'name' => 'Backend Development',
]);
Skill::create([
'name' => 'Android',
]);
Skill::create([
'name' => 'IOS',
]);
}
}
<file_sep>$(document).ready(function(){
Dropzone.options.changePict = {
headers : { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } ,
maxFiles : 1,
init : function() {
myDropzone = this;
var prevFile = null;
this.on("addedfile", function(file) {
if(prevFile != null){
this.removeFile(prevFile);
}
prevFile = file;
});
this.on('success',function(file,response){//success get response
console.log(response);
if(response['status'] == "success"){
$('#profile-pict').attr('src',response['newpath']);
$('#dismiss-modal-pict').trigger('click');
}
else{
}
});
}
};
$('#submit-name').click(function(){
data_send = JSON.stringify({"new_nickname" : $('#name-input').val()});
console.log(data_send);
$.ajax({
url: "change_name/",
type: 'POST',
data: {data_send},
success: function (response) {
if(response['status'] == 'success'){
$('#username').text($('#name-input').val());
}
alert(response['message']);
$('#dismiss-change-name').trigger('click');
}
}).fail(function (xhr, error, thrownError) {
alert('something wrong :(');
});
});
$('#submit-quote').click(function(){
data_send = JSON.stringify({"new_quote" : $('#edit-quote').val()});
console.log(data_send);
$.ajax({
url: "change_quote/",
type: 'POST',
data: {data_send},
success: function (response) {
if(response['status'] == 'success'){
$('#id-quote').text($('#edit-quote').val());
}
alert(response['message']);
$('#dismiss-quote').trigger('click');
}
}).fail(function (xhr, error, thrownError) {
alert('something wrong :(');
});
});
$('#submit-testimoni').click(function(){
data_send = JSON.stringify({"new_testimoni" : $('#edit-testimoni').val()});
console.log($('meta[name="member-id"]').attr('content'));
$.ajax({
url: "/company/job/add_member_testimony/"+$('meta[name="member-id"]').attr('content'),
type: 'POST',
data: {data_send},
success: function (response) {
alert(response['message']);
$('#dismiss-testimoni').trigger('click');
}
}).fail(function (xhr, error, thrownError) {
alert('something wrong :(');
});
});
});
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Member;
use Illuminate\Support\Facades\DB;
use App\Registrations;
use App\Mail\Mailer;
use Session;
use Mail;
use Validator;
use Auth;
use Storage;
class MemberController extends Controller
{
public function register() {
return view('members.register');
}
public function confirmRegistration(Request $request){
$userRow = Registrations::where('rg_token',$request->token)->take(1)->get();
if(count($userRow) == 0){
Session::flash('alert',"Invalid confirmation token!");
Session::flash('alert-type','failed');
}
else{
$userRow=$userRow[0];
// dd($userRow['rg_email']);
Member::create([
'm_name' => $userRow['rg_name'],
'email' => $userRow['rg_email'],
'm_borndate' => $userRow['rg_borndate'],
'm_address' => $userRow['rg_address'],
'password' => $<PASSWORD>['<PASSWORD>'],
'm_telp' => $userRow['rg_telp']
]);
Registrations::where('rg_token',$request->token)->delete();
Session::flash('alert',"Registration complete, you can login now");
Session::flash('alert-type','success');
}
return redirect('home');
}
public function requestMailVerification(Request $request) {
$time = strtotime("-18 year", time());
$date = date("Y-m-d", $time);
Validator::make($request->all(),[
'name' => 'required|min:4',
'password' => '<PASSWORD>',
'password_confirmation' => '<PASSWORD>',
'email' => 'required|email|unique:members|unique:company',
'address' => 'required|min:10',
'telp' => 'required|phone_number',
'tgllahir' => 'required|date_format:Y-m-d|before:'.$date,
],
[
'tgllahir.before' => 'your age must atleast 18 years old'
]
)->validate($request->all());
$linkToken = sha1("ha".$request->email.((string)date("l h:i:s"))."sh");
Registrations::create([
'rg_email' => $request->email,
'rg_name' => $request->name,
'rg_token' => $linkToken,
'rg_borndate' => $request->tgllahir,
'rg_address' => $request->address,
'rg_password' => bcrypt($request->password),
'rg_telp' => $request->telp,
]);
$mailObj = new Mailer();
$mailObj->setRegistMail($request->name,$linkToken,Mailer::$Member);
Mail::to($request->email)->send($mailObj);
Session::flash('alert','Please confirm the registration through email we sent to you');
Session::flash('alert-type','success');
return redirect('home');
}
public function store(Request $request)
{
//Validate
$request->validate([
'title' => 'required|min:3',
'description' => 'required',
]);
$task = Task::create(['title' => $request->title,'description' => $request->description]);
return redirect('/tasks/'.$task->id);
}
function getMemberData($id){
$user = DB::table('members')
->select(
'members.*',
DB::raw('sum(member_points.point) as total_point'),
DB::raw('GROUP_CONCAT(skills.name) as skill_name'),
DB::raw('GROUP_CONCAT(skills.id) as skill_id'),
DB::raw('GROUP_CONCAT(member_points.point) as skill_point')
)
->where('m_id','=',$id)
->join('member_points','member_points.member_id','=','members.m_id')
->join('skills','skills.id','=','member_points.skill_id')
->first();
$user->skills_name = preg_split("/,/",$user->skill_name);
$user->skills_point = preg_split("/,/",$user->skill_point);
$user->skills_id = preg_split("/,/",$user->skill_id);
return $user;
}
public function showProfile()
{
return view('members.viewProfile')->with([
'user' => self::getMemberData(Auth::guard('member')->user()->m_id),
'own_profile' => true,
'canTest' => false
]);
}
public function canGiveTestimoni($member){
$job_done_at_company = DB::table('jobs_taken')
->join('jobs', 'jobs.id', '=', 'jobs_taken.job_id')
->where('jobs_taken.worker_email', '=', $member->email)
->where('jobs_taken.status', '=', '4')
->where('jobs.company_id', '=', Auth::guard('company')->user()->c_id)
->first();
return ($job_done_at_company != null);
}
public function showProfileById($id)
{
$canTest = false;
$member = self::getMemberData($id);
if(Auth::guard('company')->check()){
$canTest = self::canGiveTestimoni($member);
}
return view('members.viewProfile')->with([
'user' => $member,
'own_profile' => false,
'canTest' => $canTest
]);;
}
public function updateProfilPict(Request $request){
$request->validate([
'file' => 'mimes:png,jpg,jpeg'
]);
if($request->file('file') != null){
$path = Storage::putFile('public', $request->file('file'));
$targetPath = date('Y-m-d-H-m-s').'-'.$request->file('file')->getClientOriginalName();
$oldfile = DB::table('members')
->select('members.m_image')
->where('m_name','=',$request->nick)->first()->m_image;
if($oldfile != null){
Storage::delete('members_photo/'.$oldfile);
}
Storage::move($path,'members_photo/'.$targetPath);
DB::table('members')
->where('m_name','=',$request->nick)
->update(['m_image' => $targetPath]);
return response()->json([
'status' => 'success',
'newpath' => asset('members_photo').'/'.$targetPath
]);
}
}
public function updateName(Request $request){
$data = json_decode($request->data_send,true);
if($data['new_nickname'] != ""){
DB::table('members')
->where('m_id','=',Auth::guard('member')->user()->m_id)
->update(['m_name' => $data['new_nickname'] ]);
return response()->json([
'status' => 'success',
'message' => 'success change name'
]);
}
else{
return response()->json([
'status' => 'failed',
'message' => 'something wrong'
]);
}
}
public function updateQuote(Request $request){
$data = json_decode($request->data_send,true);
if($data['new_quote'] != ""){
DB::table('members')
->where('m_id','=',Auth::guard('member')->user()->m_id)
->update(['quote' => $data['new_quote'] ]);
return response()->json([
'status' => 'success',
'message' => 'success change quote'
]);
}
else{
return response()->json([
'status' => 'failed',
'message' => 'something wrong'
]);
}
}
public function updateTestimony(Request $request){
$member = Member::find($request->id);
$data = json_decode($request->data_send,true);
if(Auth::guard('company')->check() && self::canGiveTestimoni($member)){
$query = DB::table('company_members')->select('*')
->where('company_id','=',Auth::guard('company')->user()->c_id)
->where('member_id','=',$member->m_id);
if($query->first() == null){
DB::table('company_members')->insert([
'company_id' => Auth::guard('company')->user()->c_id,
'member_id' => $member->m_id,
'content' => $data['new_testimoni']
]);
}
else{
$query->update([
'content' => $data['new_testimoni']
]);
}
}
return response()->json([
'status' => 'success',
'message' => 'Thanks for your testimoni'
]);
}
}
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRegistrationCompany extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('registrationsCompany', function (Blueprint $table) {
$table->string('rgc_name',50)->unique();
$table->string('rgc_email',50)->unique();
$table->string('rgc_token',40);
$table->string('rgc_address',100);
$table->string('rgc_password',60);
$table->string('rgc_telp',15);
$table->string('rgc_image',100)->nullable(true);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('RegistrationCompany');
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Registrations extends Model
{
protected $fillable = [
'rg_email', 'rg_name','rg_token','rg_borndate','rg_address','rg_password','rg_telp'
];
public $timestamps = false;
}
<file_sep><?php
use Illuminate\Database\Seeder;
use App\Job;
use App\Skill;
use App\Company;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
class JobSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$skill_count = count(Skill::all());
$company_count = count(Company::all());
$faker = Faker::create();
foreach(range(1,55) as $index)
{
$job = Job::create([
'name' => $faker->name,
'description' => $faker->paragraph(1),
'company_id' => rand(1, $company_count),
'upload_date' => date('Y-m-d'),
'finish_date' => '2018-12-6',
'document' => $faker->url,
]);
$random_skill_count = rand(1, $skill_count);
$arr = range(1, $random_skill_count);
for($i=0; $i<count($arr); $i++)
{
$skill_id = rand(1, count($arr));
array_splice($arr, $skill_id, 1);
DB::table('job_skills')
->insert([
'job_id' => $job->id,
'skill_id' => $skill_id,
'point' => rand(1, 25),
]);
}
}
}
}
|
5429862e9d4acdaf6fc11b65757632a9937fdc3e
|
[
"JavaScript",
"PHP"
] | 33
|
JavaScript
|
alfian853/wngine
|
4be3b12b9a5afd9b562b8236d9ea41ecae34c475
|
f6cec9ceac7a5e0db828c2fd5c1fdd9d551682ae
|
refs/heads/master
|
<repo_name>authstr/Factorio-toolBox<file_sep>/mod界面/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace mod界面
{
public partial class MainFrom : Form
{
//Image DownIcon = Image.FromFile(Application.StartupPath + "\\程序图标\\下载.png");
Image DownIcon = global::mod界面.Properties.Resources.下一页;
public MainFrom()
{
InitializeComponent();
}
int 测试一下还原;
private void button2_Click(object sender, EventArgs e)
{
//for (int i = 0; i < 3; i++)
//{
// Panel panel_SimpleInfoShow = SimpleInfoShow(DownIcon, "我是名字" + i,
// "我是汉化情况" + i, "我是版本" + i, "我是类型" + i, "我是介绍" + i,
// "我是上传者说明" + i, 100 + i, i);
// panel_SimpleInfoShow.Name = " panel_SimpleInfoShow" + i;
// panel_SimpleInfoShow.Location = new Point(0, 36 + 70 * i);
// this.Controls.Add(panel_SimpleInfoShow);
//}
Panel aa = paging(5);
aa.Location = new Point(0, 36);
this.Controls.Add(aa);
}
public Panel SimpleInfoShow(
Image modImage,String modName,String modChinesization,
String modVersions,String modTapy,String modExplain,
String modUploader,int modDownCount,
int ordinal) {
Panel panel_SimpleInfo = new Panel();
PictureBox pictureBox_modImage = new PictureBox();
Label label_modName = new Label();
Label label_modChinesization = new Label();
Label label_modVersions = new Label();
Label label_modTapy = new Label();
Label label_modExplain = new Label();
Label label_modUploader= new Label();
Label label_modDownCount = new Label();
Button button_Down = new Button();
//
//panel_SimpleInfo
// 简要信息显示容器 设置
panel_SimpleInfo.BorderStyle = BorderStyle.Fixed3D;
panel_SimpleInfo.Controls.Add(label_modName);
panel_SimpleInfo.Controls.Add(label_modChinesization);
panel_SimpleInfo.Controls.Add(label_modVersions);
panel_SimpleInfo.Controls.Add(label_modTapy);
panel_SimpleInfo.Controls.Add(label_modExplain);
panel_SimpleInfo.Controls.Add(label_modUploader);
panel_SimpleInfo.Controls.Add(label_modDownCount);
panel_SimpleInfo.Controls.Add(button_Down);
panel_SimpleInfo.Controls.Add(pictureBox_modImage);
//panel_SimpleInfo.Location = new Point(0, 105);
panel_SimpleInfo.Name = "SimpleInfo"+ordinal;
panel_SimpleInfo.Size = new Size(640, 68);
panel_SimpleInfo.TabIndex = 12;
//
// pictureBox_modImage
// Mod的图标
pictureBox_modImage.BorderStyle = BorderStyle.Fixed3D;
pictureBox_modImage.Image = modImage;
pictureBox_modImage.Location = new Point(0, 0);
pictureBox_modImage.Name = "modImage"+ordinal;
pictureBox_modImage.Size = new Size(64, 64);
pictureBox_modImage.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox_modImage.TabIndex = 0;
pictureBox_modImage.TabStop = false;
//
// label_modName
// Mod的名字
label_modName.AutoEllipsis = true;
label_modName.BorderStyle = BorderStyle.Fixed3D;
label_modName.Font = new Font("微软雅黑", 12F, FontStyle.Bold, GraphicsUnit.Point, ((byte)(134)));
label_modName.Location = new Point(64, 0);
label_modName.Name = "modName" + ordinal;
label_modName.Size = new Size(152, 48);
label_modName.TabIndex = 1;
label_modName.Text = modName;
label_modName.TextAlign = ContentAlignment.MiddleCenter;
//
// label_modChinesization
// Mod的汉化情况
label_modChinesization.AutoEllipsis = true;
label_modChinesization.BorderStyle = BorderStyle.Fixed3D;
label_modChinesization.Font = new Font("幼圆", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(134)));
label_modChinesization.Location = new Point(64, 48);
label_modChinesization.Name = "modChinesization" + ordinal;
label_modChinesization.Size = new Size(76, 16);
label_modChinesization.TabIndex = 7;
label_modChinesization.Text = modChinesization;
label_modChinesization.TextAlign = ContentAlignment.MiddleCenter;
//
// label_modVersions
// Mod的版本
label_modVersions.AutoEllipsis = true;
label_modVersions.BorderStyle = BorderStyle.Fixed3D;
label_modVersions.Font = new Font("幼圆", 10.5F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(134)));
label_modVersions.Location = new Point(140, 48);
label_modVersions.Name = "modVersions" + ordinal;
label_modVersions.Size = new Size(76, 16);
label_modVersions.TabIndex = 3;
label_modVersions.Text = modVersions;
label_modVersions.TextAlign = ContentAlignment.MiddleCenter;
//
// label_modTapy
// Mod的类型
label_modTapy.AutoEllipsis = true;
label_modTapy.BorderStyle = BorderStyle.Fixed3D;
label_modTapy.Font = new Font("微软雅黑", 12F, FontStyle.Bold, GraphicsUnit.Point, ((byte)(134)));
label_modTapy.Location = new Point(216, 0);
label_modTapy.Name = "modTapy" + ordinal;
label_modTapy.Size = new Size(90, 64);
label_modTapy.TabIndex = 2;
label_modTapy.Text = modTapy;
label_modTapy.TextAlign = ContentAlignment.MiddleCenter;
//
//label_modExplain
// Mod的简要介绍
label_modExplain.AutoEllipsis = true;
label_modExplain.BorderStyle = BorderStyle.Fixed3D;
label_modExplain.Font = new Font("微软雅黑", 10.5F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(134)));
label_modExplain.Location = new Point(306, 0);
label_modExplain.Name = "modExplain" + ordinal;
label_modExplain.Size = new Size(184, 64);
label_modExplain.TabIndex = 8;
label_modExplain.Text = modExplain;
label_modExplain.TextAlign = ContentAlignment.MiddleCenter;
//
// label_modUploader
// Mod的上传者
label_modUploader.AutoEllipsis = true;
label_modUploader.BorderStyle = BorderStyle.Fixed3D;
label_modUploader.Font = new Font("微软雅黑", 12F, FontStyle.Bold, GraphicsUnit.Point, ((byte)(134)));
label_modUploader.ForeColor = SystemColors.ControlText;
label_modUploader.Location = new Point(500, 0);
label_modUploader.Name = "modUploader"+ordinal;
label_modUploader.Size = new Size(76, 40);
label_modUploader.TabIndex = 9;
label_modUploader.Text = modUploader;
label_modUploader.TextAlign = ContentAlignment.MiddleCenter;
//
// label_modDownCount
// Mod的下载次数
label_modDownCount.BorderStyle = BorderStyle.Fixed3D;
label_modDownCount.Font = new Font("宋体", 9F, FontStyle.Underline, GraphicsUnit.Point, ((byte)(134)));
label_modDownCount.Location = new Point(500, 40);
label_modDownCount.Name = "modDownCount"+ordinal;
label_modDownCount.Size = new Size(76, 24);
label_modDownCount.TabIndex = 10;
label_modDownCount.Text =modDownCount+"次下载";
label_modDownCount.TextAlign = ContentAlignment.MiddleCenter;
//
// button_Down
// mod下载按钮
button_Down.BackgroundImage =DownIcon;
button_Down.BackgroundImageLayout = ImageLayout.Zoom;
button_Down.Location = new System.Drawing.Point(576, 0);
button_Down.Name = "Down"+ordinal;
button_Down.Size = new Size(64, 64);
button_Down.TabIndex = 6;
button_Down.UseVisualStyleBackColor = true;
return panel_SimpleInfo;
}
public Panel paging(int nowPageCount) {
Panel panel_paging = new Panel();
Button button_nextPage = new Button();
Button button_previousPage = new Button();
Label label_textA = new Label();
Label label_textB = new Label();
NumericUpDown numericUpDown_pagingControl = new NumericUpDown();
panel_paging.BorderStyle = BorderStyle.Fixed3D;
panel_paging.Controls.Add(button_nextPage);
panel_paging.Controls.Add(button_previousPage);
panel_paging.Controls.Add(label_textA);
panel_paging.Controls.Add(label_textB);
panel_paging.Controls.Add(numericUpDown_pagingControl);
//panel_SimpleInfo.Location = new Point(0, 105);
panel_paging.Name = "paging";
panel_paging.Size = new Size(640, 48);
panel_paging.TabIndex = 12;
//
// button_nextPage
// 下一页按钮
button_nextPage.BackgroundImage = global::mod界面.Properties.Resources.下一页;
button_nextPage.BackgroundImageLayout = ImageLayout.Zoom;
button_nextPage.Location = new Point(456, 0);
button_nextPage.Name = "nextPage";
button_nextPage.Size = new Size(48, 48);
button_nextPage.TabIndex = 0;
button_nextPage.UseVisualStyleBackColor = true;
//
// button_previousPage
// 上一页按钮
button_previousPage.BackgroundImage = global::mod界面.Properties.Resources.上一页;
button_previousPage.BackgroundImageLayout = ImageLayout.Zoom;
button_previousPage.Location = new Point(136, 0);
button_previousPage.Name = "previousPage";
button_previousPage.Size = new Size(48, 48);
button_previousPage.TabIndex = 1;
button_previousPage.UseVisualStyleBackColor = true;
//
//label_textA
// 文本"跳转到第"
label_textA.Font = new Font("微软雅黑", 12F, FontStyle.Bold, GraphicsUnit.Point, ((byte)(134)));
label_textA.Location = new Point(248, 12);
label_textA.Name = "textA";
label_textA.Size = new Size(74, 24);
label_textA.TabIndex = 3;
label_textA.Text = "跳转到第";
//
//label_textB
// 文本"页"
label_textB.Font = new Font("微软雅黑", 12F, FontStyle.Bold, GraphicsUnit.Point, ((byte)(134)));
label_textB.Location = new System.Drawing.Point(368, 12);
label_textB.Name = "textB";
label_textB.Size = new Size(24, 24);
label_textB.TabIndex = 4;
label_textB.Text = "页";
//
// numericUpDown_pagingControl
// 输入 跳转的页数
numericUpDown_pagingControl.Font = new Font("微软雅黑", 10.5F, FontStyle.Bold, GraphicsUnit.Point, ((byte)(134)));
numericUpDown_pagingControl.Location = new Point(320, 12);
numericUpDown_pagingControl.Name = "pagingControl";
numericUpDown_pagingControl.Size = new Size(48, 26);
numericUpDown_pagingControl.TabIndex = 2;
numericUpDown_pagingControl.Value = nowPageCount;
return panel_paging;
}
private void MainFrom_Load(object sender, EventArgs e)
{
textBox_ModFilePath.SetWatermark("这是Mod文件的路径");
textBox_OriginalName.SetWatermark("用于生成文件名和说明");
textBox_UploaderName.SetWatermark("少侠,做好事请留名!");
textBox_UploaderEmail.SetWatermark("可以方便我们通知您哦");
//textBox6.SetWatermark("简单介绍一下Mod吧");
textBox_SingleDescribe.Text = "简单介绍一下Mod吧";
//textBox7.SetWatermark("Mod玩起来怎么样,那些地方很有趣的,有没有什么要注意的问题等等,记得要分享哦");
textBox_DetailDescribe.Text = "Mod玩起来怎么样?\r\n那些地方很有趣的?\r\n有没有什么要注意的问题?\r\n……\r\n记得要分享出来哦";
textBox_OriginaSingleDescribe.Text = "Mod原作者的info.json description说明";
textBox_OriginaDetailDescribe.Text = "Mod原作者的info.json description_original说明";
}
//用于显示Mod上传界面的输入框的某些提示文字
private void textBox_SingleDescribe_MouseDown(object sender, MouseEventArgs e)
{
if (textBox_SingleDescribe.Text== "简单介绍一下Mod吧")
{
textBox_SingleDescribe.Text = "";
}
}
private void textBox_SingleDescribe_Leave(object sender, EventArgs e)
{
if (textBox_SingleDescribe.Text == "")
{
textBox_SingleDescribe.Text = "简单介绍一下Mod吧";
}
}
private void textBox_DetailDescribe_MouseDown(object sender, MouseEventArgs e)
{
if (textBox_DetailDescribe.Text == "Mod玩起来怎么样?\r\n那些地方很有趣的?\r\n有没有什么要注意的问题?\r\n……\r\n记得要分享出来哦")
{
textBox_DetailDescribe.Text = "";
}
}
private void textBox_DetailDescribe_Leave(object sender, EventArgs e)
{
if (textBox_DetailDescribe.Text == "")
{
textBox_DetailDescribe.Text = "Mod玩起来怎么样?\r\n那些地方很有趣的?\r\n有没有什么要注意的问题?\r\n……\r\n记得要分享出来哦";
}
}
private void textBox_OriginaSingleDescribe_MouseDown(object sender, MouseEventArgs e)
{
if (textBox_OriginaSingleDescribe.Text == "Mod原作者的info.json description说明")
{
textBox_OriginaSingleDescribe.Text = "";
}
}
private void textBox_OriginaSingleDescribe_Leave(object sender, EventArgs e)
{
if (textBox_OriginaSingleDescribe.Text == "")
{
textBox_OriginaSingleDescribe.Text = "Mod原作者的info.json description说明";
}
}
private void textBox_OriginaDetailDescribe_MouseDown(object sender, MouseEventArgs e)
{
if (textBox_OriginaDetailDescribe.Text == "Mod原作者的info.json description_original说明")
{
textBox_OriginaDetailDescribe.Text = "";
}
}
private void textBox_OriginaDetailDescribe_Leave(object sender, EventArgs e)
{
if (textBox_OriginaDetailDescribe.Text == "")
{
textBox_OriginaDetailDescribe.Text = "Mod原作者的info.json description_original说明";
}
}
//
private void button_UploadModFile_Click(object sender, EventArgs e)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.ShowDialog();
}
private void button_UploadCommit_Click(object sender, EventArgs e)
{
Boolean isCompleteWrite=true;
//判断填写是否完成,并进行提示
if (textBox_ModFilePath.Text == "")
{
//应检查路径合法性
MessageBox.Show("Mod文件路径未填写", "信息未填写完哦", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
isCompleteWrite = false;
}
else {
if (textBox_OriginalName.Text == "")
{
MessageBox.Show("Mod原名称未填写", "信息未填写完哦", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
isCompleteWrite = false;
}
else {
if (comboBox_ModChinesization.Text == "")
{
MessageBox.Show("Mod汉化情况未填写", "信息未填写完哦", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
isCompleteWrite = false;
}
else {
if (comboBox_Type.Text == "")
{
MessageBox.Show("Mod的类别未填写", "信息未填写完哦", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
isCompleteWrite = false;
}
else
{
if (textBox_SingleDescribe.Text == ""|| textBox_SingleDescribe.Text == "简单介绍一下Mod吧")
{
MessageBox.Show("Mod的简述未填写", "信息未填写完哦", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
isCompleteWrite = false;
}
else
{
if (!radioButton_agree.Checked)
{
MessageBox.Show("服务条款未勾选", "信息未填写完哦", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
isCompleteWrite = false;
}
}
}
}
}
}
//
//把值获取并发送
if (isCompleteWrite)
{
//
//textBox_ModFilePath.Text;
//路径
//
//textBox_OriginalName.Text
//原名称
//
//textBox_CNName.Text;
//中文名
//
//comboBox_ModChinesization.Text;
//汉化情况
//
//comboBox_Type.Text;
//类型
//
//textBox_SingleDescribe.Text;
//简述
//
//textBox_DetailDescribe.Text;
//详述
//
//textBox_UploaderName.Text;
//上传者名字
//
//textBox_UploaderEmail.Text;
//上传者邮箱
//
//textBox_author.Text;
//作者
//
//dateTimePicker_ReleaseDate.Text;
//发布日期
//
//textBox_WebUrl.Text;
//官网链接
//
//textBox_ModDownUrl.Text;
//本体下载链接
//
//textBox_ErrorInfo.Text;
//mod错误信息
//
//textBox_FacrorioVersions.Text;
//Facrorio版本
//
//textBox_OriginaSingleDescribe.Text;
//原简述
//
//textBox_OriginaDetailDescribe.Text;
//原详述
MessageBox.Show("数据提交");
}
//
}
}
}
|
0ce91da9c672c0249c9f379620cea46dcc9bc775
|
[
"C#"
] | 1
|
C#
|
authstr/Factorio-toolBox
|
5424f8b87569cac201b3fbe3de0ebfb080668ad7
|
d2f1366f321d1cd598e40e717e8c85fa4ab7ac2c
|
refs/heads/master
|
<repo_name>afrianska/rocketline<file_sep>/spec/features/user_visits_homepage_spec.rb
require "rails_helper"
RSpec.feature "User visits homepage" do
scenario "successfull and see a logo" do
visit root_path
expect(page).to have_content "RocketLine"
end
end
|
db063921ec44361e852cefc43d51acd17e2c0c76
|
[
"Ruby"
] | 1
|
Ruby
|
afrianska/rocketline
|
591b5dd4aca5b9ea01700a80121750e4191ccaca
|
922dd4ae24b6a00e474ff529a2742818cd01f3d1
|
refs/heads/master
|
<repo_name>teraspawn/template_project<file_sep>/matlab/OrderDendrogram.R
last <- function(x) {
return( x[length(x)] )
}
first_entry <- function(x){
return(x[1])
}
dendrogram_ordering <- function(dataset, weights, filename) {
hc <- hclust(dist(dataset),method="single")
dd <- as.dendrogram(hc)
dd.reorder <- reorder(dd,weights,agglo.FUN=first_entry)
the_labels <- labels(dd.reorder)
#print(colnames(drug_data_key)[metric])
write(the_labels,file=filename,ncolumns=1)
#labels(dd.reorder) <- leaf_names[the_labels]
}
order_this_dendrogram <- function() {
require(graphics)
library(dendextend)
drug_data <- read.table('/home/scratch/testoutput/Tox_Res_Paper/collated_data.tsv')
drug_data_key <- read.csv('/home/scratch/testoutput/Tox_Res_Paper/collated_data_key.csv')
scaled <- read.table('/home/scratch/testoutput/Tox_Res_Paper/scaled_metrics.tsv')
weights <- as.vector(drug_data[,2])
drug_names <- drug_data[,1]
leaf_names <- paste(drug_names,weights)
dendrogram_ordering(scaled[,1],weights, 'order_APD90')
dendrogram_ordering(scaled[,6],weights, 'order_INa_EADs')
dendrogram_ordering(scaled[,7],weights, 'order_ICaL_EADs')
dendrogram_ordering(scaled[,8],weights, 'order_IKr_EADs')
dendrogram_ordering(scaled[,c(1,6,7,8)],weights, 'order_APD90_EADs')
dendrogram_ordering(scaled[,c(6,7,8)],weights, 'order_EADs')
dendrogram_ordering(scaled[,c(1,6)],weights, 'order_APD90_ICaL')
dendrogram_ordering(scaled[,c(2,3)],weights, 'order_Grandi_LS')
dendrogram_ordering(scaled[,c(4,5)],weights, 'order_OHara_LS')
dendrogram_ordering(drug_data[,11],weights, 'order_hERG_cmax')
}
<file_sep>/test/TestDetectAfterDepolarisations.hpp
/*
Copyright (c) 2005-2017, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TESTDETECTAFTERDEPOLARISATIONS_HPP_
#define TESTDETECTAFTERDEPOLARISATIONS_HPP_
#include <cxxtest/TestSuite.h>
#include "DetectAfterDepolarisations.hpp"
#include "ColumnDataReader.hpp"
#include "FileFinder.hpp"
class TestDetect : public CxxTest::TestSuite
{
public:
void TestDetectAfterDepolarisations() throw(Exception)
{
/* Make sure this code is only run if CVODE is installed/enabled on the computer */
#ifdef CHASTE_CVODE
double stim_start = 100;
double stim_period = 3000;
double lowlimit = 50;
double highlimit = 100;
FileFinder traces_folder("projects/BethM/test/TestTraces", RelativeTo::ChasteSourceRoot);
TS_ASSERT_EQUALS(traces_folder.IsDir(), true);
std::vector<FileFinder> traces = traces_folder.FindMatches("*.dat");
for (unsigned i=0; i<traces.size(); i++)
{
std::cout << "Running for " << traces[i].GetLeafName() << std::endl;
boost::shared_ptr<ColumnDataReader> p_reader(new ColumnDataReader(traces_folder,
traces[i].GetLeafNameNoExtension()));
std::vector<double> voltages = p_reader->GetValues("membrane_voltage");
std::vector<double> simtimes = p_reader->GetValues("Time");
double end_time = simtimes.back();
std::cout << end_time;
boost::shared_ptr<DetectAfterDepolarisations> p_AD(new DetectAfterDepolarisations);
bool AD = p_AD->FindAD(voltages, simtimes, end_time, stim_start, stim_period, lowlimit, highlimit, "TestDetectAfterdepolarisations", true);
if (traces[i].GetLeafName()[0] == 'N')
{
TS_ASSERT_EQUALS(AD,false);
}
else
{
TS_ASSERT_EQUALS(AD,true);
}
}
#else
/* CVODE is not enable or installed*/
std::cout << "Cvode is not enabled.\n";
#endif
}
};
#endif /*TESTDETECTAFTERDEPOLARISATIONS_HPP_*/
<file_sep>/src/DrugDataReader.hpp
/*
Copyright (c) 2005-2017, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DRUGDATAREADER_HPP_
#define DRUGDATAREADER_HPP_
#include <fstream>
#include <vector>
#include "UblasVectorInclude.hpp"
#include "Exception.hpp"
#include "FileFinder.hpp"
/**
* Helper class to read in data
*/
class DrugDataReader
{
private:
std::vector<std::string> mDrugNames;
std::vector<unsigned> mRedfernCategory;
std::vector<c_vector<double,7> > mIc50values;
std::vector<c_vector<double,2> > mClinicalDoseRange;
std::vector<double> mGrandiMeasure;
public:
DrugDataReader(std::string fileName)
{
LoadDrugDataFromFile(fileName);
}
DrugDataReader(FileFinder& rFileFinder)
{
LoadDrugDataFromFile(rFileFinder.GetAbsolutePath());
}
std::string GetDrugName(unsigned drugIndex)
{
assert(drugIndex < GetNumDrugs());
return mDrugNames[drugIndex];
}
unsigned GetRedfernCategory(unsigned drugIndex)
{
assert(drugIndex < GetNumDrugs());
return mRedfernCategory[drugIndex];
}
double GetGrandiMeasure(unsigned drugIndex)
{
assert(drugIndex < GetNumDrugs());
if (mGrandiMeasure[drugIndex] < -998)
{
EXCEPTION("No data available on Grandi measure for this drug.");
}
return mGrandiMeasure[drugIndex];
}
double GetIC50Value(unsigned drugIndex, unsigned channelIndex)
{
assert(drugIndex < GetNumDrugs());
assert(channelIndex<7);
double ic50 = mIc50values[drugIndex](channelIndex);
/**
* If an IC50 value takes the value
* -1 in the data file that means "effect unknown".
* -2 in the data file means "known to have no effect".
*/
if (fabs(ic50 + 2) < 1e-9)
{ // This drug is known to have no effect on this channel
// We set the IC50 value to DBL_MAX for the block calculations.
ic50 = DBL_MAX;
}
return ic50;
}
double GetClinicalDoseRange(unsigned drugIndex, unsigned lowOrHigh)
{
assert(lowOrHigh==0 || lowOrHigh==1);
assert(drugIndex < GetNumDrugs());
if (mClinicalDoseRange[drugIndex](0) < 0)
{
EXCEPTION("No data available on clinical dose for this drug.");
}
return mClinicalDoseRange[drugIndex](lowOrHigh);
}
void LoadDrugDataFromFile(std::string fileName)
{
std::ifstream indata; // indata is like cin
indata.open(fileName.c_str()); // opens the file
if(!indata)
{ // file couldn't be opened
EXCEPTION("Couldn't open data file: " + fileName);
}
bool line_is_not_blank = true;
unsigned line_counter = 0;
while (line_is_not_blank)
{
std::string this_line;
getline(indata, this_line);
std::stringstream line(this_line);
unsigned category;
//unsigned redfern_cat;
std::string name;
std::string in_redfern_figs;
c_vector<double, 7> ic50s;
c_vector<double, 2> doses;
double grandi_measure;
ic50s.clear();
doses.clear();
line >> name;
line >> ic50s(0);
line >> ic50s(1);
line >> ic50s(2);
line >> ic50s(3);
line >> ic50s(4);
line >> ic50s(5);
line >> ic50s(6);
line >> doses(0);
line >> doses(1);
//line >> redfern_cat;
//line >> in_redfern_figs;
//line >> category;
//line >> grandi_measure;
mDrugNames.push_back(name);
mRedfernCategory.push_back(category);
mIc50values.push_back(ic50s);
mClinicalDoseRange.push_back(doses);
mGrandiMeasure.push_back(grandi_measure);
line_counter++;
//std::cout << "line_counter = " <<line_counter << "\n" << std::flush;
if (indata.eof())
{
break;
}
}
}
unsigned GetNumDrugs(void)
{
assert(mDrugNames.size()==mRedfernCategory.size());
assert(mDrugNames.size()==mIc50values.size());
assert(mDrugNames.size()==mClinicalDoseRange.size());
return mDrugNames.size();
}
/**
* Calculate the probability of a channel being open given this drug, IC50 and hill coefficient.
*
* Note: A negative IC50 value is interpreted as "drug has no effect on this channel".
*
* @param rConc concentration of the drug.
* @param rIC50 IC50 value for this drug and channel
* @param hill Hill coefficient for this drug dependent inactivation curve (defaults to 1).
*
* @return proportion of channels which are still active at this drug concentration
*/
static double CalculateConductanceFactor(const double& rConc, const double& rIC50, double hill = 1.0)
{
if (rIC50 < 0)
{
return 1.0;
}
else
{
return 1.0/(1.0 + pow((rConc/rIC50), hill));
}
}
};
#endif // DRUGDATAREADER_HPP_
<file_sep>/collate_data.py
#! /usr/bin/python
# get risk categories and sort alphabetically
rf = open("redferns.tsv",'r')
redferns = rf.readlines()
redferns.sort()
a1f = open("curated_dataset_apd90.dat")
apd90 = a1f.readlines()
apd90.sort()
glf = open("curated_dataset_grandi_lancaster_sobie.dat")
grandils = glf.readlines()
grandils.sort()
olf = open("curated_dataset_ohara_lancaster_sobie.dat")
oharals = olf.readlines()
oharals.sort()
inaf = open("DruggedSteadyStateThresholds/CollatedINa.dat")
ina = inaf.readlines()
ina.sort()
icalf = open("DruggedSteadyStateThresholds/ohara_rudy_2011membrane_L_type_calcium_current_conductance_0")
ical = icalf.readlines()
ical.sort()
ikrf = open("DruggedSteadyStateThresholds/ohara_rudy_2011membrane_rapid_delayed_rectifier_potassium_current_conductance_0")
ikr = ikrf.readlines()
ikr.sort()
hergf = open("herg_block.tsv")
herg = hergf.readlines()
herg.sort()
output_file = open("collated_data.tsv",'w')
for i in range(0,len(redferns)):
output_file.write(redferns[i].split()[0]+ "\t"+ redferns[i].split()[1]+ "\t")
output_file.write(apd90[i].split()[1]+ "\t"+ grandils[i].split()[1]+ "\t"+ grandils[i].split()[2]+ "\t"+ oharals[i].split()[1]+ "\t")
output_file.write(oharals[i].split()[2]+ "\t"+ ina[i].split()[1]+ "\t"+ ical[i].split()[1]+ "\t"+ ikr[i].split()[1]+ "\t"+ herg[i].split()[1])
<file_sep>/src/Trace.cpp
/*
Copyright (c) 2005-2017, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef CHASTE_CVODE
#include "Trace.hpp"
#include <vector>
#include <fstream>
#include <iostream>
#include <stdlib.h>
Trace::Trace(){}
Trace::Trace(std::vector<double> trace)
{
this->assign (trace.begin(), trace.end());
return;
}
void Trace::operator= (std::vector<double> trace)
{
this->assign (trace.begin(), trace.end());
return;
}
double Trace::Integrate(double step_size)
{
Trace this_trace = this[0];
// use the trapezium rule to numerically integrate trace.
double sum_of_trace = 0;
for (unsigned i=0; i <= this_trace.size(); i++)
{
sum_of_trace += this_trace[i];
}
return 0.5*step_size*(sum_of_trace*2 - this_trace[0] - this_trace[this_trace.size()-1]);
}
#endif
<file_sep>/test/TestOutputTraces.hpp
/*
Copyright (c) 2005-2017, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Copyright (c) 2005-2015, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TESTOUTPUTTRACES_HPP_
#define TESTOUTPUTTRACES_HPP_
#include <cxxtest/TestSuite.h>
#include "DrugDataReader.hpp"
#include "ColumnDataReader.hpp"
#include "Trace.hpp"
#include <sstream>
#include <iomanip>
#include "AbstractCardiacCell.hpp"
#include "AbstractCvodeCell.hpp"
#include "CellProperties.hpp"
#include "OutputFileHandler.hpp"
#include "ohara_rudy_2011_endoCvode.hpp"
#include "AbstractParameterisedSystem.hpp"
#include "AbstractCvodeSystem.hpp"
#include "SteadyStateRunner.hpp"
#include "Debug.hpp"
#include "ColumnDataWriter.hpp"
class TestOutputTraces : public CxxTest::TestSuite
{
public:
void TestRunSimulation() throw(Exception)
{
/* Make sure this code is only run if CVODE is installed/enabled on the computer */
#ifdef CHASTE_CVODE
// check that command line arguments have been supplied
CommandLineArguments* p_args = CommandLineArguments::Instance();
unsigned argc = *(p_args->p_argc); // has the number of arguments.
std::cout << (argc-1)/2 << " arguments supplied.\n" << std::flush;
if (argc == 1)
{
std::cerr << "Please input arguments\n"
"--drug [0-40]\n"
"--intervention\n"
" 1: I_CaL increase\n"
"--value\n"
"--multiplier\n";
return;
}
std::string file_location = getenv("CHASTE_TEST_OUTPUT");
//Take command line arguments
unsigned drug_index = CommandLineArguments::Instance()->GetUnsignedCorrespondingToOption("--drug");
unsigned intervention = CommandLineArguments::Instance()->GetUnsignedCorrespondingToOption("--intervention");
double multiplier = CommandLineArguments::Instance()->GetDoubleCorrespondingToOption("--multiplier");
double value = CommandLineArguments::Instance()->GetDoubleCorrespondingToOption("--value");
// set up simulation
double dt = 0.1;
double start_time = 0;
double end_time = 3099;
double stim_magnitude = -25.5;
double stim_duration = 3;
double stim_start = 100;
double stim_period = 3000;
boost::shared_ptr<RegularStimulus> p_stimulus(new RegularStimulus(stim_magnitude,stim_duration,stim_period,stim_start));
boost::shared_ptr<AbstractIvpOdeSolver> p_solver;
boost::shared_ptr<AbstractCvodeCell> p_model(new Cellohara_rudy_2011_endoFromCellMLCvode(p_solver, p_stimulus));
// take in drug data
DrugDataReader drug_data("projects/EadPredict/test/curated_dataset.dat");
// make sure there are enough drugs
TS_ASSERT_DIFFERS(drug_data.GetNumDrugs(),0u);
// write down all the channel names
std::vector<std::string> ap_predict_channels;
ap_predict_channels.push_back("membrane_fast_sodium_current_conductance");
ap_predict_channels.push_back("membrane_L_type_calcium_current_conductance");
ap_predict_channels.push_back("membrane_rapid_delayed_rectifier_potassium_current_conductance");
ap_predict_channels.push_back("membrane_slow_delayed_rectifier_potassium_current_conductance");
ap_predict_channels.push_back("membrane_persistent_sodium_current_conductance");
ap_predict_channels.push_back("membrane_transient_outward_current_conductance");
ap_predict_channels.push_back("membrane_inward_rectifier_potassium_current_conductance");
// get original values for each channel
std::vector<double> original_values;
for (unsigned int i= 0; i<ap_predict_channels.size(); i++)
{
original_values.push_back(p_model->GetParameter(ap_predict_channels[i]));
}
// make sure there are enough drugs
TS_ASSERT_DIFFERS(drug_data.GetNumDrugs(),0u);
// get out the name of the drug
std::string drug_name = drug_data.GetDrugName(drug_index) ;
TS_ASSERT_DIFFERS(drug_name.length(), 0u);
std::cout << "\n" << drug_name << "\n";
double original_drug_conc = drug_data.GetClinicalDoseRange(drug_index,1u);
// loop through 26 concentrations
double drug_conc = original_drug_conc * multiplier;
for (unsigned channel_idx = 0; channel_idx < ap_predict_channels.size(); channel_idx++)
{
double conductance_factor = DrugDataReader::CalculateConductanceFactor(drug_conc,drug_data.GetIC50Value(drug_index,channel_idx));
double ic50 = drug_data.GetIC50Value(drug_index,channel_idx);
p_model->SetParameter(ap_predict_channels[channel_idx],original_values[channel_idx]*conductance_factor);
double new_value = p_model->GetParameter(ap_predict_channels[channel_idx]);
double new_multiplier = new_value / original_values[channel_idx];
std::cout << ap_predict_channels[channel_idx] << " (IC50 = " << ic50 << ")";
std::cout << " is set to ";
std::cout << new_value << ", which is ";
std::cout << new_multiplier << "x the original value\n";
}
// run to steady state
SteadyStateRunner steady_runner(p_model);
bool result = steady_runner.RunToSteadyState();
std::cout << "Running to steady state: " << result << "\n";
// do the intervention
if (intervention==1)
{
double starting_ical = p_model->GetParameter(ap_predict_channels[1]);
std::cout << "Setting " << ap_predict_channels[1] << " to " << value << "x original\n";
p_model->SetParameter(ap_predict_channels[1],starting_ical*value);
}
OdeSolution solution = p_model->Compute(start_time,end_time,dt);
std::vector<double> late_sodium_trace, calcium_trace, herg_trace, ito_trace, ik1_trace, fast_sodium_trace, iks_trace;
std::vector<double> voltage_trace;
solution.CalculateDerivedQuantitiesAndParameters(p_model.get());
voltage_trace = solution.GetAnyVariable("membrane_voltage");
calcium_trace = solution.GetAnyVariable("membrane_L_type_calcium_current");
late_sodium_trace = solution.GetAnyVariable("membrane_persistent_sodium_current");
herg_trace = solution.GetAnyVariable("membrane_rapid_delayed_rectifier_potassium_current");
ito_trace = solution.GetAnyVariable("membrane_transient_outward_current");
ik1_trace = solution.GetAnyVariable("membrane_inward_rectifier_potassium_current");
fast_sodium_trace = solution.GetAnyVariable("membrane_fast_sodium_current");
iks_trace = solution.GetAnyVariable("membrane_slow_delayed_rectifier_potassium_current_conductance");
std::ofstream trace_file;
std::stringstream file_name_stream;
file_name_stream << file_location << "Tox_Res_Paper/" << intervention << "_" << "drug_effect_traces_" << drug_name << "_" << multiplier << "_" << value;
std::string file_name = file_name_stream.str();
trace_file.open(file_name.c_str());
trace_file << "voltage\t late_sodium\t calcium\t herg\t ito\t ik1\t fast_sodium\t iks\n";
trace_file << std::setprecision(20);
for (unsigned int d=0; d < late_sodium_trace.size(); d++)
{
trace_file << voltage_trace[d] << "\t" << late_sodium_trace[d]<< "\t" << calcium_trace[d]<< "\t";
trace_file << herg_trace[d] << "\t" << ito_trace[d] << "\t" << ik1_trace[d] << "\t";
trace_file << fast_sodium_trace[d] << "\t" << iks_trace[d] << "\n";
}
trace_file.close();
#else
/* CVODE is not enable or installed*/
std::cout << "Cvode is not enabled.\n";
#endif
}
};
#endif
<file_sep>/src/DetectAfterDepolarisations.cpp
/*
Copyright (c) 2005-2017, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Copyright (c) 2005-2015, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef CHASTE_CVODE
#include "DetectAfterDepolarisations.hpp"
#include <fstream>
DetectAfterDepolarisations::DetectAfterDepolarisations() {}
bool DetectAfterDepolarisations::CausedAD(OdeSolution& solution, boost::shared_ptr<RegularStimulus> p_stimulus, std::string output_filename, bool print_trace)
{
/* get out voltage and time vectors */
std::vector<double> v_Voltage = solution.GetAnyVariable("membrane_voltage");
std::vector<double> v_Times = solution.rGetTimes();
double end_time = v_Times.back();
double stim_start = p_stimulus->GetStartTime();
double stim_period = p_stimulus->GetPeriod();
double TimeToIgnoreBeforeStimulus = 50;
double TimeToIgnoreAfterStimulus = 100;
return FindAD(v_Voltage, v_Times, end_time, stim_start, stim_period, TimeToIgnoreBeforeStimulus, TimeToIgnoreAfterStimulus, output_filename, print_trace);
}
bool DetectAfterDepolarisations::FindAD(std::vector<double> v_Voltage, std::vector<double> v_Times,
double end_time, double stim_start, double stim_period, double TimeToIgnoreBeforeStimulus, double TimeToIgnoreAfterStimulus, std::string output_filename, bool print_trace)
{
try
{
std::vector<double> v_VoltageDifference;
std::vector<double> v_TimesADIsOccurring;
for (unsigned int a=0; a < v_Voltage.size()-1; a++)
{
/* list of voltage change at each time point */
v_VoltageDifference.push_back(v_Voltage[a+1]-v_Voltage[a]);
/* if dV/dt > 1mV/ms */
if (v_VoltageDifference[a] > 0.001)
/* store the time */
v_TimesADIsOccurring.push_back(v_Times[a]);
}
/* erase depolarisations provoked by stimulus */
for (double stim_index = stim_start; stim_index < end_time; stim_index = stim_index + stim_period)
{
for (unsigned int ad_times_index = 0; ad_times_index < v_TimesADIsOccurring.size(); ad_times_index++)
{
if ((v_TimesADIsOccurring[ad_times_index] > stim_index -
TimeToIgnoreBeforeStimulus && v_TimesADIsOccurring[ad_times_index] < stim_index + TimeToIgnoreAfterStimulus ) || v_TimesADIsOccurring[ad_times_index] < 100)
{
// delete
v_TimesADIsOccurring.erase(v_TimesADIsOccurring.begin()+ad_times_index);
// Go back one to make up for the deleted element
ad_times_index--;
}
}
}
/* find times when the AD starts */
std::vector<double> v_TimeDifference;
std::vector<double> v_TimesADsBegin;
/* iterate through list of voltage upswing times*/
if (v_TimesADIsOccurring.size()>0)
{
for (unsigned int b=0; b < v_TimesADIsOccurring.size()-2; b++)
{
/* make a list of the differences */
v_TimeDifference.push_back(v_TimesADIsOccurring[b+1]-v_TimesADIsOccurring[b]);
}
/* find minimum time difference */
std::vector<double>::iterator step = std::min_element(v_TimeDifference.begin(),v_TimeDifference.end());
double minsteps = *step;
//std::cout << "MINSTEPS IS: "<< *step << "\n";
for (unsigned int d=0; d< v_TimeDifference.size(); d++)
{
/* find all points in diff(adtimes) that change more than the minimum*/
if (v_TimeDifference[d] > minsteps + 0.0001 )
{
/* store times */
v_TimesADsBegin.push_back(v_TimesADIsOccurring[d+2]);
/* std::cout << adtimes[d+2] << "\n";*/
}
}
}
if (print_trace)
{
std::ofstream outputfile;
std::string file_location = getenv("CHASTE_TEST_OUTPUT");
std::string file_name = file_location + output_filename;
outputfile.open(file_name.c_str());
outputfile << "Time(s) membrane_voltage(mV) AD\n";
for (unsigned int d=0; d < v_Voltage.size(); d++)
{
outputfile << v_Times[d] << " " << v_Voltage[d] << " ";
/*output 1 if AD, 0 if not */
bool found = 0;
for (unsigned int e=0; e < v_TimesADIsOccurring.size(); e++)
{
if (v_Times[d] == v_TimesADIsOccurring[e])
{
found = 1;
break;
}
}
outputfile << found;
outputfile << "\n";
}
outputfile.close();
}
if (v_TimesADsBegin.size()>0)
{
return 1;
}
}
catch(Exception& e)
{
std::cout << "DetectAfterdepolarisations Failed";
return 0;
}
return 0;
}
#endif
<file_sep>/src/CreateModel.hpp
/*
Copyright (c) 2005-2016, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CREATEMODEL_HPP_
#define CREATEMODEL_HPP_
#include "DrugDataReader.hpp"
#include "shannon_wang_puglisi_weber_bers_2004Cvode.hpp"
#include "fink_noble_giles_model_2008Cvode.hpp"
#include "ten_tusscher_model_2006_epiCvode.hpp"
#include "ten_tusscher_model_2006_endoCvode.hpp"
#include "ten_tusscher_model_2006_MCvode.hpp"
#include "noble_model_1998Cvode.hpp"
#include "ohara_rudy_2011_endoCvode.hpp"
#include "AbstractCvodeCell.hpp"
class CreateModel
{
public:
unsigned mInterIndex;
double mStartTime, mEndTime, mDt;
boost::shared_ptr<AbstractCvodeCell> mpModel;
boost::shared_ptr<RegularStimulus> mpStimulus;
std::vector<double> mInterventionValues;
std::vector<std::string> mDrugParameterNames, mIntervention;
std::vector<double> mDrugConductanceFactors, mSteadyStateVariables, mOldSolution, mDruggedConductanceValues, mInterventionInitialState, mLimits;
std::string mModelName, mInterventionType, mDrugName, mTraceFolder, mInterventionHardLimit;
int mConcIndex;
double mSkip, mIncrement;
CreateModel(unsigned int inter_index, unsigned int model_index, boost::shared_ptr<RegularStimulus> p_stimulus, std::vector<double> intervention_values,
double start_time, double end_time, double dt, std::string drug_name, int conc_index, std::string trace_filename);
CreateModel();
void Drug (std::vector<double>conductance_factors, std::vector<std::string>channel_names);
bool GetToSteadyState ();
bool ResetAndCheck ();
int Intervene (int c, unsigned conc_index, std::string drug_name);
int InterveneAndCheck ();
int DoTheIntervention (double intervention_value, std::string output_filename);
std::string GetIdentifier();
bool GetExpectedChange();
bool IntervalBisection(bool result);
void SetLimits(std::vector<double> coarse_threshold);
double GetThreshold();
std::vector<int> PossibleCombinations();
std::string GetModelName();
std::string GetInterventionName();
void SkipTime(double skip_time);
void ChangeIncrement(double);
};
#endif
<file_sep>/README.md
# EadPredict - Early Afterdepolarisation Prediction
This project is an extension of Chaste that is intended to be used
for simulation of drug action in cardiac electrophysiology models in
combination with EADs.
## Prerequisites
Before using this code you will need to download and install Chaste's
dependencies and the Chaste source code itself.
Please see [Getting Started] for details of how to do this
(follow instructions for "Development Code User" to keep up to date with the latest code, or a release version if you want longer-term stability).
Chaste version 3.4 is recommended for this project.
The bolt-on ApPredict project is also needed for the APD simulations. Please see the [ApPredict] github page for installation instructions.
## Installation
This repo must be cloned into
```sh
<chaste source directory>/projects/EadPredict
```
so that all the file paths can be picked up correctly (replacing ```<chaste source directory>``` with the place you have put the Chaste source code). Alternatively, you can put a sim link from the above folder to wherever you clone this repo.
The following instructions should do the cloning, note that this project pulls in a submodule from the Chaste/cellml repository, so cloning it requires the ```--recursive``` option:
```sh
$ cd <chaste source directory>/projects
$ git clone --recursive https://github.com/teraspawn/EadPredict.git
```
### Older git
N.B. on really old git versions (<1.6.5), `--recursive` doesn't work and you need to do:
```sh
$ cd <chaste source directory>/projects
$ git clone https://github.com/Chaste/EadPredict.git
$ cd EadPredict
$ git submodule init
$ git submodule update
```
[Getting Started]: <https://chaste.cs.ox.ac.uk/trac/wiki/GettingStarted>
[ApPredict]: <https://github.com/Chaste/ApPredict/releases>
### Simulations
To find EAD thresholds for the drug test pack, run
```sh
cd <chaste source directory>
scons projects/EadPredict/TestEADs.hpp
scons projects/EadPredict/TestControlEADs.hpp
```
Then run the simulation using the following command line options:
```
--model
1 = shannon_wang_puglisi_weber_bers_2004
2 = fink_noble_giles_model_2008
3 = ten_tusscher_model_2006_epi
4 = ten_tusscher_model_2006_endo
5 = ten_tusscher_model_2006_M
6 = ohara_rudy_2011
7 = grandi_pasqualini_bers_2010_ss
--intervention
1 = cytosolic_sodium_concentration
2 = membrane_rapid_delayed_rectifier_potassium_current_conductance
3 = membrane_fast_sodium_current_shift_inactivation
4 = membrane_L_type_calcium_current_conductance
5 = membrane_L_type_calcium_current_conductance_double_extracellular_potassium_concentration
6 = membrane_persistent_sodium_current_conductance
7 = membrane_rapid_delayed_rectifier_potassium_current_conductance_double_extracellular_potassium_concentration
8 = membrane_fast_sodium_current_shift_inactivation_double_extracellular_potassium_concentration
9 = membrane_L_type_calcium_current_conductance_three_quarters_extracellular_potassium_concentration
10 = membrane_rapid_delayed_rectifier_potassium_current_conductance_three_quarters_extracellular_potassium_concentration
11 = membrane_fast_sodium_current_shift_inactivation_three_quarters_extracellular_potassium_concentration
12 = membrane_fast_sodium_current_reduced_inactivation
--ll [lower limit]
--hl [higher limit]
--IP
0 = do not create intervention profile
1 = do create intervention profile
```
where "model" is the cell model to use, "intervention" is the strategy for inducing EADs, "ll" is the lower limit for the interval bisection protocol and "hl" is the upper limit (if in doubt, use 0 and 50), and "IP" creates an "intervention profile", which shows at which value of the intervention parameter an EAD is created over the whole range. For speed use "--IP 0".
To get the threshold values used for Table 2 in the paper, run:
```sh
cd <chaste source directory>
./projects/EadPredict/build/debug/TestEADsRunner --model 6 --intervention 2 --ll 0 --hl 1 --IP 0
./projects/EadPredict/build/debug/TestEADsRunner --model 6 --intervention 3 --ll 0 --hl 30 --IP 0
./projects/EadPredict/build/debug/TestEADsRunner --model 6 --intervention 4 --ll 1 --hl 30 --IP 0
./projects/EadPredict/build/debug/TestControlEADsRunner --model 6 --intervention 2 --ll 0 --hl 1 --IP 0
./projects/EadPredict/build/debug/TestControlEADsRunner --model 6 --intervention 3 --ll 0 --hl 30 --IP 0
./projects/EadPredict/build/debug/TestControlEADsRunner --model 6 --intervention 4 --ll 1 --hl 30 --IP 0
```
To get the other metrics:
```sh
cd <chaste source directory>
scons projects/EadPredict/test/TestAPD90.hpp
scons projects/EadPredict/test/TestGrandiLancasterSobie.hpp
scons projects/EadPredict/test/TestOharaLancasterSobie.hpp
scons projects/EadPredict/test/TestCqinwardMetric.hpp
scons projects/EadPredict/test/TestControlAPDs.hpp
```
To collate the data into one file for analysis:
```sh
cp projects/EadPredict/collate_data.py $CHASTE_TEST_OUTPUT
cd $CHASTE_TEST_OUTPUT
python collate_data.py
```
To scale metrics for combination use the Matlab script `OutputCombinedMetrics.m`.
To classify data into categories use the Matlab scripts `ClassifyByCqinward.m` and `Compare_Classifiers.m`.
To do five-fold validation use the Matlab scripts `Cqinward_Five_Fold_Validation.m` and `Five_Fold_Validation.m`.
To create the dendrograms, run `OrderDendrogram.R` in R followed by `SideBySideDendrograms.m` in Matlab.
To create Figures 2 and 3, run the Matlab scripts `PlotEADClassificationExamples.m` and `EADComparisonFigure.m`.
<file_sep>/src/ClassifyAfterDepolarisations.cpp
/*
Copyright (c) 2005-2017, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef CHASTE_CVODE
#include "ClassifyAfterDepolarisations.hpp"
#include <fstream>
ClassifyAfterDepolarisations::ClassifyAfterDepolarisations() {}
std::string ClassifyAfterDepolarisations::CausedAD(OdeSolution& solution, boost::shared_ptr<RegularStimulus> p_stimulus, std::string output_filename)
{
/* get out voltage and time vectors */
std::vector<double> v_Voltage = solution.GetAnyVariable("membrane_voltage");
std::vector<double> v_Times = solution.rGetTimes();
double end_time = v_Times.back();
double stim_start = p_stimulus->GetStartTime();
double stim_period = p_stimulus->GetPeriod();
double TimeToIgnoreBeforeStimulus = 50;
double TimeToIgnoreAfterStimulus = 100;
return FindAD(v_Voltage, v_Times, end_time, stim_start, stim_period, TimeToIgnoreBeforeStimulus, TimeToIgnoreAfterStimulus, output_filename);
}
std::string ClassifyAfterDepolarisations::FindAD(std::vector<double> v_Voltage, std::vector<double> v_Times,
double end_time, double stim_start, double stim_period, double TimeToIgnoreBeforeStimulus, double TimeToIgnoreAfterStimulus, std::string output_filename)
{
std::vector<double> v_VoltageDifference;
std::vector<double> v_TimesADIsOccurring;
for (unsigned int a=0; a < v_Voltage.size()-1; a++)
{
/* list of voltage change at each time point */
v_VoltageDifference.push_back(v_Voltage[a+1]-v_Voltage[a]);
/* if dV/dt > 0.1mV/ms */
if (v_VoltageDifference[a] > 0.001 )
{
/* store the time */
v_TimesADIsOccurring.push_back(v_Times[a]);
}
}
/* erase depolarisations provoked by stimulus */
for (double stim_index = stim_start; stim_index < end_time; stim_index = stim_index + stim_period)
{
for (unsigned int ad_times_index = 0; ad_times_index < v_TimesADIsOccurring.size(); ad_times_index++)
{
if ((v_TimesADIsOccurring[ad_times_index] > stim_index -
TimeToIgnoreBeforeStimulus && v_TimesADIsOccurring[ad_times_index] < stim_index + TimeToIgnoreAfterStimulus ) || v_TimesADIsOccurring[ad_times_index] < 100)
{
// delete
v_TimesADIsOccurring.erase(v_TimesADIsOccurring.begin()+ad_times_index);
// Go back one to make up for the deleted element
ad_times_index--;
}
}
}
/* find times when the AD starts */
std::vector<double> v_TimeDifference;
std::vector<double> v_TimesADsBegin;
/* iterate through list of voltage upswing times*/
if (v_TimesADIsOccurring.size()>0)
{
for (unsigned int b=0; b < v_TimesADIsOccurring.size()-2; b++)
{
/* make a list of the differences */
v_TimeDifference.push_back(v_TimesADIsOccurring[b+1]-v_TimesADIsOccurring[b]);
}
/* find minimum time difference */
std::vector<double>::iterator step = std::min_element(v_TimeDifference.begin(),v_TimeDifference.end());
double minsteps = *step;
//std::cout << "MINSTEPS IS: "<< *step << "\n";
for (unsigned int d=0; d< v_TimeDifference.size(); d++)
{
/* find all points in diff(adtimes) that change more than the minimum*/
if (v_TimeDifference[d] > minsteps + 0.0001 )
{
/* store times */
v_TimesADsBegin.push_back(v_TimesADIsOccurring[d+2]);
for (unsigned int voltage_count = 0; voltage_count < v_Voltage.size() ; voltage_count++)
{
if (v_Times[voltage_count] == v_TimesADIsOccurring[d+2])
{
mVoltagesAtWhichADsStart.push_back(v_Voltage[voltage_count-1]);
//std::cout << v_Voltage[voltage_count-1] << "\n";
}
}
}
}
}
std::vector<double> v_IgnoreTimes;
int maximum_ADs = 0;
double total_ADs = 0;
std::vector<int> counting_ADs;
for (double stim_index = stim_start; stim_index < end_time; stim_index = stim_index + stim_period)
{
int number_of_ADs = 0;
for (unsigned int q=0; q<v_TimesADsBegin.size(); q++)
{
if (v_TimesADsBegin[q] > stim_index && v_TimesADsBegin[q] < stim_index+stim_period)
{
number_of_ADs += 1;
total_ADs += 1;
}
}
if (number_of_ADs > maximum_ADs)
{
maximum_ADs = number_of_ADs;
}
counting_ADs.push_back(number_of_ADs);
}
mADCount = counting_ADs;
ADDensity = total_ADs/counting_ADs.size();
mTotalAds = total_ADs;
//std::cout << "Average number of ADs:" << ADDensity << "\n";
std::ofstream outputfile;
std::string file_location = getenv("CHASTE_TEST_OUTPUT");
std::string file_name = file_location + "CADCheck/" + output_filename;
outputfile.open(file_name.c_str());
outputfile << "Time(s) membrane_voltage(mV) Ignore AD Repolarisation Recentness \n";
bool recently_repolarised = false;
bool after_AD = true;
bool is_DAD = false;
bool AD_occurred = false;
bool repolarises = false;
for (unsigned int d=0; d < v_Voltage.size(); d++)
{
outputfile << v_Times[d] << " " << v_Voltage[d] << " ";
/*output 1 if AD, 0 if not */
bool found = 0;
for (unsigned int e=0; e < v_TimesADIsOccurring.size(); e++)
{
if (v_Times[d] == v_TimesADIsOccurring[e])
{
AD_occurred = true;
after_AD = true;
found = 1;
if (recently_repolarised)
{
is_DAD = true;
recently_repolarised = false;
}
break;
}
}
outputfile << found << " ";
bool ignore = 0;
for (double stim_index = stim_start; stim_index < end_time; stim_index = stim_index + stim_period)
{
if (v_Times[d] == stim_index+TimeToIgnoreAfterStimulus)
{
recently_repolarised = false;
after_AD = false;
}
if (v_Times[d] < stim_index+TimeToIgnoreAfterStimulus && v_Times[d] > stim_index-TimeToIgnoreBeforeStimulus)
{
ignore = 1;
break;
}
}
outputfile << ignore << " ";
if (v_Voltage[d] < -60 && !after_AD)
{
recently_repolarised = true;
}
/* output 1 if repolarised, 0 if not */
if (v_Voltage[d] < -60 && AD_occurred)
{
outputfile << "1 ";
repolarises = true;
}
else
{
outputfile << "0 ";
}
outputfile << recently_repolarised << " ";
outputfile << "\n";
}
outputfile.close();
std::string AD_type = "E";
if (is_DAD)
{
AD_type = "D";
}
if (!AD_occurred)
{
return "NNN";
}
else
{
if (repolarises)
{
if (maximum_ADs > 1)
return AD_type + "MW";
else
return AD_type + "SW";
}
else
{
if (maximum_ADs > 1)
return AD_type + "MO";
else
return AD_type + "SO";
}
}
return "XXX";
}
int ClassifyAfterDepolarisations::GetCount()
{
return mTotalAds;
}
std::vector<double> ClassifyAfterDepolarisations::GetStarts()
{
return mVoltagesAtWhichADsStart;
}
#endif
<file_sep>/test/TestCqinwardMetric.hpp
/*
Copyright (c) 2005-2017, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Copyright (c) 2005-2015, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TESTCQINWARDSMETRIC_HPP_
#define TESTCQINWARDSMETRIC_HPP_
#include <cxxtest/TestSuite.h>
#include "DrugDataReader.hpp"
#include "ColumnDataReader.hpp"
#include "Trace.hpp"
#include <sstream>
#include <iomanip>
#include "AbstractCardiacCell.hpp"
#include "AbstractCvodeCell.hpp"
#include "CellProperties.hpp"
#include "OutputFileHandler.hpp"
#include "ohara_rudy_2011_endoCvode.hpp"
#include "AbstractParameterisedSystem.hpp"
#include "AbstractCvodeSystem.hpp"
#include "SteadyStateRunner.hpp"
#include "Debug.hpp"
#include "ColumnDataWriter.hpp"
class TestCqinwardsMetric : public CxxTest::TestSuite
{
public:
void TestGetIntegrals() throw(Exception)
{
/* Make sure this code is only run if CVODE is installed/enabled on the computer */
#ifdef CHASTE_CVODE
// check that command line arguments have been supplied
CommandLineArguments* p_args = CommandLineArguments::Instance();
unsigned argc = *(p_args->p_argc); // has the number of arguments.
std::cout << (argc-1)/2 << " arguments supplied.\n" << std::flush;
if (argc == 1)
{
std::cerr << "Please input an argument\n"
"--drug [0-37]\n";
return;
}
//Take command line arguments
unsigned drug_index = CommandLineArguments::Instance()->GetUnsignedCorrespondingToOption("--drug");
// set up simulation
double dt = 0.1;
double start_time = 0;
double end_time = 3099;
double stim_magnitude = -25.5;
double stim_duration = 3;
double stim_start = 100;
double stim_period = 3000;
boost::shared_ptr<RegularStimulus> p_stimulus(new RegularStimulus(stim_magnitude,stim_duration,stim_period,stim_start));
boost::shared_ptr<AbstractIvpOdeSolver> p_solver;
boost::shared_ptr<AbstractCvodeCell> p_model(new Cellohara_rudy_2011_endoFromCellMLCvode(p_solver, p_stimulus));
// take in drug data
DrugDataReader drug_data("projects/EadPredict/test/curated_dataset.dat");
// make sure there are enough drugs
TS_ASSERT_DIFFERS(drug_data.GetNumDrugs(),0u);
// write down all the channel names
std::vector<std::string> ap_predict_channels;
ap_predict_channels.push_back("membrane_fast_sodium_current_conductance");
ap_predict_channels.push_back("membrane_L_type_calcium_current_conductance");
ap_predict_channels.push_back("membrane_rapid_delayed_rectifier_potassium_current_conductance");
ap_predict_channels.push_back("membrane_slow_delayed_rectifier_potassium_current_conductance");
ap_predict_channels.push_back("membrane_persistent_sodium_current_conductance");
ap_predict_channels.push_back("membrane_transient_outward_current_conductance");
ap_predict_channels.push_back("membrane_inward_rectifier_potassium_current_conductance");
// get original values for each channel
std::vector<double> original_values;
for (unsigned int i= 0; i<ap_predict_channels.size(); i++)
{
original_values.push_back(p_model->GetParameter(ap_predict_channels[i]));
}
// make sure there are enough drugs
TS_ASSERT_DIFFERS(drug_data.GetNumDrugs(),0u);
// get out the name of the drug
std::string drug_name = drug_data.GetDrugName(drug_index) ;
TS_ASSERT_DIFFERS(drug_name.length(), 0u);
double original_drug_conc = drug_data.GetClinicalDoseRange(drug_index,1u);
std::ofstream output_file;
std::string file_location = getenv("CHASTE_TEST_OUTPUT");
std::string filename = file_location + "cqinward_results_" + drug_name +".tsv";
output_file.open(filename.c_str());
output_file << "Drug name\t Concentration (xCmax)\t qInward\t qInward_control\t cqInward\n";
double ical_control;
double ipna_control;
// loop through 26 concentrations
for (unsigned int multiplier = 0; multiplier < 26; multiplier++)
{
output_file << drug_name << "\t";
output_file << multiplier << "\t";
double drug_conc = original_drug_conc * multiplier;
for (unsigned channel_idx = 0; channel_idx < ap_predict_channels.size(); channel_idx++)
{
double conductance_factor = DrugDataReader::CalculateConductanceFactor(drug_conc,drug_data.GetIC50Value(drug_index,channel_idx));
p_model->SetParameter(ap_predict_channels[channel_idx],original_values[channel_idx]*conductance_factor);
}
// run to steady state
SteadyStateRunner steady_runner(p_model);
bool result = steady_runner.RunToSteadyState();
std::cout << "Running to steady state: " << result << "\n";
OdeSolution solution = p_model->Compute(start_time,end_time,dt);
std::vector<double> late_sodium_trace;
std::vector<double> calcium_trace;
//for (unsigned int time_point = 0; time_point < (end_time / dt); time_point++)
//{
// double sodium = p_model->GetAnyVariable("membrane_persistent_sodium_current",time_point*dt);
// double calcium = p_model->GetAnyVariable("membrane_L_type_calcium_current",time_point*dt);
// std::cout << time_point << "\t" << sodium << "\t" << calcium << "\n";
// late_sodium_trace.push_back(sodium);
// calcium_trace.push_back(calcium);
//}
//
solution.CalculateDerivedQuantitiesAndParameters(p_model.get());
calcium_trace = solution.GetAnyVariable("membrane_L_type_calcium_current");
std::cout << "o\n";
late_sodium_trace = solution.GetAnyVariable("membrane_persistent_sodium_current");
Trace trace_ipna;
trace_ipna = late_sodium_trace;
double ipna_integral = trace_ipna.Integrate(dt);
Trace trace_ical;
trace_ical = calcium_trace;
double ical_integral = trace_ical.Integrate(dt);
if (multiplier == 0)
{
ipna_control = ipna_integral;
ical_control = ical_integral;
}
double qinward = (ipna_integral + ical_integral);
double qinward_control = ipna_control + ical_control;
double cqinward = qinward/qinward_control;
output_file << std::setprecision(20);
output_file << qinward << "\t" << qinward_control << "\t" << cqinward << "\n";
bool print_trace = false;
if (print_trace)
{
std::ofstream trace_file;
std::stringstream file_name_stream;
file_name_stream << file_location << "Qinward_traces_" << drug_name << multiplier;
std::string file_name = file_name_stream.str();
trace_file.open(file_name.c_str());
trace_file << "late_sodium\t calcium\n";
trace_file << std::setprecision(20);
// print *1000000 to convert to pA/uF
for (unsigned int d=0; d < late_sodium_trace.size(); d++)
{
trace_file << late_sodium_trace[d]*1000000 << "\t" << calcium_trace[d]*1000000 << "\n";
}
trace_file.close();
}
}
output_file.close();
#else
/* CVODE is not enable or installed*/
std::cout << "Cvode is not enabled.\n";
#endif
}
};
#endif
<file_sep>/test/TestEADs.hpp
/*
Copyright (c) 2005-2017, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Copyright (c) 2005-2015, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TESTEADS_HPP_
#define TESTEADS_HPP_
#include <cxxtest/TestSuite.h>
#include "DetectAfterDepolarisations.hpp"
#include "ThresholdIntervention.hpp"
#include "ColumnDataReader.hpp"
#include "DrugDataReader.hpp"
#include <sstream>
#include <iomanip>
#include "AbstractCardiacCell.hpp"
#include "AbstractCvodeCell.hpp"
#include "CellProperties.hpp"
#include "OutputFileHandler.hpp"
#include "CreateModel.hpp"
#include <sys/stat.h>
#include <boost/assign.hpp>
#include "SteadyStateRunner.hpp"
#include "Debug.hpp"
class TestEads : public CxxTest::TestSuite
{
public:
void TestCreateThresholdTables() throw(Exception)
{
/* Make sure this code is only run if CVODE is installed/enabled on the computer */
#ifdef CHASTE_CVODE
// check that command line arguments have been supplied
CommandLineArguments* p_args = CommandLineArguments::Instance();
unsigned argc = *(p_args->p_argc); // has the number of arguments.
std::cout << (argc-1)/2 << " arguments supplied.\n" << std::flush;
if (argc == 1)
{
std::cerr << "Please input an argument\n"
"--model\n"
" 1 = shannon_wang_puglisi_weber_bers_2004\n"
" 2 = fink_noble_giles_model_2008\n"
" 3 = ten_tusscher_model_2006_epi\n"
" 4 = ten_tusscher_model_2006_endo\n"
" 5 = ten_tusscher_model_2006_M\n"
" 6 = ohara_rudy_2011\n"
" 7 = grandi_pasqualini_bers_2010_ss\n"
"--intervention\n"
" 1 = cytosolic_sodium_concentration\n"
" 2 = membrane_rapid_delayed_rectifier_potassium_current_conductance\n"
" 3 = membrane_fast_sodium_current_shift_inactivation\n"
" 4 = membrane_L_type_calcium_current_conductance\n"
" 5 = membrane_L_type_calcium_current_conductance_double_extracellular_potassium_concentration\n"
" 6 = membrane_persistent_sodium_current_conductance\n"
" 7 = membrane_rapid_delayed_rectifier_potassium_current_conductance_double_extracellular_potassium_concentration\n"
" 8 = membrane_fast_sodium_current_shift_inactivation_double_extracellular_potassium_concentration\n"
" 9 = membrane_L_type_calcium_current_conductance_three_quarters_extracellular_potassium_concentration\n"
" 10 = membrane_rapid_delayed_rectifier_potassium_current_conductance_three_quarters_extracellular_potassium_concentration\n"
" 11 = membrane_fast_sodium_current_shift_inactivation_three_quarters_extracellular_potassium_concentration\n"
" 12 = membrane_fast_sodium_current_reduced_inactivation\n"
"--ll [lower limit]\n"
"--hl [higher limit]\n"
"--IP\n"
" 0 = do not create intervention profile \n"
" 1 = do create intervention profile \n";
return;
}
//Take command line arguments
unsigned model_index = CommandLineArguments::Instance()->GetUnsignedCorrespondingToOption("--model");
unsigned inter_index = CommandLineArguments::Instance()->GetUnsignedCorrespondingToOption("--intervention");
int conc_index = 2;
bool intervention_profile = CommandLineArguments::Instance()->GetBoolCorrespondingToOption("--IP");
int sample_inded = 1;
// put together vector of intervention values for testing
double low_limit = CommandLineArguments::Instance()->GetDoubleCorrespondingToOption("--ll");
double high_limit = CommandLineArguments::Instance()->GetDoubleCorrespondingToOption("--hl");
double step = (high_limit - low_limit)/99;
std::vector<double> intervention_values;
intervention_values.push_back(low_limit);
for (int a=1; a<100; a++)
{
intervention_values.push_back(intervention_values[a-1]+step);
}
// check that the end values line up
TS_ASSERT_DELTA(intervention_values[intervention_values.size()-1], high_limit, high_limit/100);
// take in drug data
DrugDataReader drug_data("projects/EadPredict/test/curated_dataset.dat");
// make sure there are enough drugs
TS_ASSERT_DIFFERS(drug_data.GetNumDrugs(),0u);
std::vector<std::string> ap_predict_channels;
ap_predict_channels.push_back("membrane_fast_sodium_current_conductance");
ap_predict_channels.push_back("membrane_L_type_calcium_current_conductance");
ap_predict_channels.push_back("membrane_rapid_delayed_rectifier_potassium_current_conductance");
ap_predict_channels.push_back("membrane_slow_delayed_rectifier_potassium_current_conductance");
ap_predict_channels.push_back("membrane_persistent_sodium_current_conductance");
ap_predict_channels.push_back("membrane_transient_outward_current_conductance");
ap_predict_channels.push_back("membrane_inward_rectifier_potassium_current_conductance");
// for output, check that folders exist
std::string file_location = getenv("CHASTE_TEST_OUTPUT");
std::vector<std::string> pathname;
std::string threshold_folder = "Tox_Res_Paper/DruggedSteadyStateThresholds";
std::string ip_folder = "Tox_Res_Paper/ThreeColumnInterventionProfile";
std::string trace_folder = "Tox_Res_Paper/ADCheck";
pathname.push_back(file_location + threshold_folder);
pathname.push_back(file_location + ip_folder);
pathname.push_back(file_location + trace_folder);
pathname.push_back(file_location + trace_folder + "/Bisection");
pathname.push_back(file_location + trace_folder + "/Sequential");
struct stat sb;
for (unsigned e=0; e< pathname.size(); e++)
{
//and if they don't, create them
if (stat(pathname[e].c_str(), &sb) != 0)
{
boost::filesystem::create_directories(pathname[e]);
}
TS_ASSERT(stat(pathname[e].c_str(), &sb) == 0);
}
// for running simulations
double start_time = 0.0;
double dt = 0.1;
// stimulus info
double stim_magnitude = -25.5;
double stim_duration = 3;
double stim_start = 100;
double stim_period = 3000;
double end_time = 4*stim_period;
boost::shared_ptr<RegularStimulus> p_stimulus(new RegularStimulus(stim_magnitude,stim_duration,stim_period,stim_start));
//output file for all drug results
std::ofstream fine_file;
std::stringstream fine_filestream;
std::string fine_filename;
// make sure there are enough drugs
TS_ASSERT_DIFFERS(drug_data.GetNumDrugs(),0u);
// loop through all the drugs
for (unsigned int drug_index=0; drug_index < drug_data.GetNumDrugs(); drug_index++)
{
// get out the name of the drug
std::string drug_name = drug_data.GetDrugName(drug_index) ;
TS_ASSERT_DIFFERS(drug_name.length(), 0u);
double drug_conc = drug_data.GetClinicalDoseRange(drug_index,1u);
std::cout << drug_name << "\n";
// make new model and give model_creator some more info
CreateModel model_creator(inter_index, model_index, p_stimulus, intervention_values, start_time, end_time, dt, drug_name, conc_index, trace_folder);
// create the file for recording the threshold results
if (drug_index == 0)
{
fine_filestream << file_location << threshold_folder << "/" << model_creator.GetIdentifier() << "_" << (sample_index);
fine_filename = fine_filestream.str();
fine_file.open(fine_filename.c_str());
}
// check that the file exists
TS_ASSERT_EQUALS(stat(fine_filename.c_str(), &sb),0);
fine_file << drug_name;
// calculate the proportion of the different channels which are still active
std::vector<double> conductance_factors;
for (unsigned channel_idx = 0; channel_idx < ap_predict_channels.size(); channel_idx++)
{
conductance_factors.push_back(DrugDataReader::CalculateConductanceFactor(drug_conc,drug_data.GetIC50Value(drug_index,channel_idx)));
}
// apply drug to model
model_creator.Drug(conductance_factors, ap_predict_channels);
// run to steady state
model_creator.GetToSteadyState();
//for storing threshold values
std::vector<double> coarse_threshold;
// Create an intervention profile if required
if (intervention_profile)
{
// set up file for outputting results of different levels of intervention
std::ofstream outputfile;
std::stringstream filestream;
std::string filename;
filestream << file_location << ip_folder << "/" << drug_name << (conc_index) << model_creator.GetIdentifier();
filename = filestream.str();
outputfile.open(filename.c_str());
std::cout << "\nSaving output to: " << filename << "\n";
// check that the file exists
TS_ASSERT_EQUALS(stat(filename.c_str(), &sb),0);
bool found_threshold = false;
bool expected_change = model_creator.GetExpectedChange();
////loop over intervention levels to create profile and find coarse threshold
for( int c=0; c < 100; c++)
{
model_creator.ResetAndCheck();
// apply intervention and see if there's an AD
int causes_afterdepolarisation = model_creator.Intervene(c, conc_index, drug_name);
std::cout << c << " " << intervention_values[c] << " " << causes_afterdepolarisation << "\n";
outputfile << c << " " << intervention_values[c] << " "<< causes_afterdepolarisation << "\n";
if ((causes_afterdepolarisation == expected_change) && !found_threshold)
{
// if this is the first time an AD is detected or the first time the AD disappears
coarse_threshold.push_back(intervention_values[c]);
coarse_threshold.push_back(intervention_values[c-1]);
found_threshold = true;
std::cout << "\nThe coarse threshold is: " << coarse_threshold[0] << coarse_threshold[1] << "\n\n";
}
}
if (!found_threshold)
{
coarse_threshold.push_back(low_limit);
coarse_threshold.push_back(high_limit);
std::cout << "Threshold is not between higher and lower limits\n";
}
outputfile.close();
}
else // or assume that the threshold is between the higher and lower limits
{
coarse_threshold.push_back(low_limit);
coarse_threshold.push_back(high_limit);
}
// find the exact value of the threshold
model_creator.SetLimits(coarse_threshold);
bool found_fine_threshold = false;
for (unsigned bisection_iterations = 0; bisection_iterations<100; bisection_iterations++)
{
model_creator.ResetAndCheck();
// intervention_result could be 1 (AD) 0 (no AD) or -2 (parameter value out of range error)
int intervention_result = model_creator.InterveneAndCheck();
bool result;
if (intervention_result != -2)
{
result = intervention_result;
}
// move to next interval to check
found_fine_threshold = model_creator.IntervalBisection(result);
if (found_fine_threshold)
{
std::cout << "The threshold is: " << model_creator.GetThreshold() << "\n";
fine_file << " " << model_creator.GetThreshold() << "\n";
break;
}
}
if (!found_fine_threshold)
{
fine_file << " -2\n";
std::cout << "Failed to find threshold.\n";
}
}
fine_file.close();
}
#else
/* CVODE is not enable or installed*/
std::cout << "Cvode is not enabled.\n";
#endif
};
#endif
<file_sep>/test/TestDataReaders.hpp
/*
Copyright (c) 2005-2017, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TESTDATAREADERS_HPP_
#define TESTDATAREADERS_HPP_
#include <cxxtest/TestSuite.h>
#include "DrugDataReader.hpp"
#include "AbstractDataStructure.hpp"
class TestDataReaders : public CxxTest::TestSuite
{
public:
void TestDrugDataLoading(void) throw(Exception)
{
FileFinder file("projects/EadPredict/test/curated_dataset.dat", RelativeTo::ChasteSourceRoot);
// Test the drug data loads correctly...
DrugDataReader drug_data(file);
TS_ASSERT_EQUALS(drug_data.GetNumDrugs(), 42);
unsigned ajmaline_idx = 0;
TS_ASSERT_EQUALS(drug_data.GetDrugName(ajmaline_idx),"ajmaline");
TS_ASSERT_DELTA(drug_data.GetClinicalDoseRange(ajmaline_idx,0),65,1e-4);
unsigned quinidine = 32;
unsigned cisapride =7 ;
unsigned tedisamil = 36;
unsigned propranolol = 30;
unsigned verapamil = 40;
TS_ASSERT_EQUALS(drug_data.GetDrugName(quinidine), "quinidine");
TS_ASSERT_EQUALS(drug_data.GetDrugName(cisapride), "cisapride");
TS_ASSERT_EQUALS(drug_data.GetDrugName(tedisamil), "tedisamil");
TS_ASSERT_EQUALS(drug_data.GetDrugName(propranolol), "propranolol");
TS_ASSERT_EQUALS(drug_data.GetDrugName(verapamil), "verapamil");
TS_ASSERT_DELTA(drug_data.GetIC50Value(quinidine,0), 16600, 1e-4);
TS_ASSERT_DELTA(drug_data.GetIC50Value(cisapride,2), 6.5, 1e-4);
TS_ASSERT_DELTA(drug_data.GetIC50Value(propranolol,1), 18000, 1e-4);
TS_ASSERT_DELTA(drug_data.GetIC50Value(propranolol,2), 2828, 1e-4);
TS_ASSERT_DELTA(drug_data.GetClinicalDoseRange(quinidine,0), 924, 1e-4);
TS_ASSERT_DELTA(drug_data.GetClinicalDoseRange(quinidine,1), 3237, 1e-4);
TS_ASSERT_DELTA(drug_data.GetClinicalDoseRange(cisapride,0), 2.6, 1e-4);
TS_ASSERT_DELTA(drug_data.GetClinicalDoseRange(cisapride,1), 4.9, 1e-4);
TS_ASSERT_DELTA(drug_data.GetClinicalDoseRange(verapamil,0), 25, 1e-4);
TS_ASSERT_DELTA(drug_data.GetClinicalDoseRange(verapamil,1), 81, 1e-4);
// We want a "no effect drug" to return DBL_MAX, which the CalculateConductanceFactor() method handles nicely (see below).
unsigned pentamidine = 25 ;
TS_ASSERT_EQUALS(drug_data.GetDrugName(pentamidine),"pentamidine");
TS_ASSERT_DELTA(drug_data.GetIC50Value(pentamidine,1), std::numeric_limits<double>::max(), 1e-9);
// Check how it deals with a "NA" (No effect) entry - should return DBL_MAX for the IC50.
// (i.e. a positive value which won't effect conductance so that analysis will run)
TS_ASSERT_EQUALS(drug_data.GetDrugName(tedisamil), "tedisamil");
TS_ASSERT_DELTA(drug_data.GetIC50Value(tedisamil,0), 20000, 1e-9);
TS_ASSERT_DELTA(drug_data.GetIC50Value(tedisamil,1), std::numeric_limits<double>::max(), 1e-9);
}
};
#endif // TESTDATAREADERS_HPP_
<file_sep>/test/TestCreateTraces.hpp
/*
Copyright (c) 2005-2017, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TESTCREATETRACES_HPP_
#define TESTCREATETRACES_HPP_
#include <cxxtest/TestSuite.h>
#include "DetectAfterDepolarisations.hpp"
#include "ThresholdIntervention.hpp"
#include "ColumnDataReader.hpp"
#include "DrugDataReader.hpp"
#include <sstream>
#include <iomanip>
#include "AbstractCardiacCell.hpp"
#include "AbstractCvodeCell.hpp"
#include "CellProperties.hpp"
#include "OutputFileHandler.hpp"
#include "shannon_wang_puglisi_weber_bers_2004Cvode.hpp"
#include "fink_noble_giles_model_2008Cvode.hpp"
#include "ten_tusscher_model_2006_epiCvode.hpp"
#include "ten_tusscher_model_2006_endoCvode.hpp"
#include "ten_tusscher_model_2006_MCvode.hpp"
#include "iyer_2004Cvode.hpp"
#include "noble_model_1998Cvode.hpp"
#include "ohara_rudy_2011_endoCvode.hpp"
#include "AbstractParameterisedSystem.hpp"
#include "AbstractCvodeSystem.hpp"
#include <boost/lexical_cast.hpp>
#include "SteadyStateRunner.hpp"
#include "Debug.hpp"
class TestCreateTraces : public CxxTest::TestSuite
{
public:
void TestMakeTraces() throw(Exception)
{
/* Make sure this code is only run if CVODE is installed/enabled on the computer */
#ifdef CHASTE_CVODE
// check that command line arguments have been supplied
CommandLineArguments* p_args = CommandLineArguments::Instance();
unsigned argc = *(p_args->p_argc); // has the number of arguments.
std::cout << (argc-1)/2 << " arguments supplied.\n" << std::flush;
if (argc == 1)
{
std::cerr << "Please input an argument\n"
"--model\n"
" 1 = shannon_wang_puglisi_weber_bers_2004\n"
" 2 = fink_noble_giles_model_2008\n"
" 3 = ten_tusscher_model_2006_epi\n"
" 4 = ten_tusscher_model_2006_endo\n"
" 5 = ten_tusscher_model_2006_M\n"
" 6 = ohara_rudy_2011_endo\n"
"--intervention\n"
" 1 = membrane_L_type_calcium_current_conductance\n"
" 2 = membrane_fast_sodium_current_shift_inactivation\n"
" 3 = membrane_rapid_delayed_rectifier_potassium_current_conductance\n"
"--value <intervention level>\n";
return;
}
// CommandLineArguments* p_args = CommandLineArguments::Instance();
// unsigned argc = *(p_args->p_argc); // has the number of arguments.
char* model = CommandLineArguments::Instance()->GetValueCorrespondingToOption("--model");
unsigned model_index = atoi(model);
char* inter = CommandLineArguments::Instance()->GetValueCorrespondingToOption("--intervention");
unsigned inter_index = atoi(inter);
double value = CommandLineArguments::Instance()->GetDoubleCorrespondingToOption("--value");
// for running simulations
double start_time = 0.0;
double end_time = 10000.0;
double dt = 0.1;
// stimulus and solver for all models
double stim_magnitude = -25.5;
double stim_duration = 3;
double stim_start = 100;
double stim_period = 3000;
boost::shared_ptr<RegularStimulus> p_stimulus(new RegularStimulus(stim_magnitude,stim_duration,stim_period,stim_start));
boost::shared_ptr<AbstractIvpOdeSolver> p_solver;
// make new model
boost::shared_ptr<AbstractCvodeCell> p_model;
if (model_index ==1)
{
boost::shared_ptr<AbstractCvodeCell> p_new_model(new Cellshannon_wang_puglisi_weber_bers_2004FromCellMLCvode(p_solver, p_stimulus));
p_model = p_new_model;
}
else if (model_index == 2)
{
boost::shared_ptr<AbstractCvodeCell> p_new_model(new Cellfink_noble_giles_model_2008FromCellMLCvode(p_solver, p_stimulus));
p_model = p_new_model;
}
else if (model_index == 3)
{
boost::shared_ptr<AbstractCvodeCell> p_new_model(new Cellten_tusscher_model_2006_epiFromCellMLCvode(p_solver, p_stimulus));
p_model = p_new_model;
}
else if (model_index == 4)
{
boost::shared_ptr<AbstractCvodeCell> p_new_model(new Cellten_tusscher_model_2006_endoFromCellMLCvode(p_solver, p_stimulus));
p_model = p_new_model;
}
else if (model_index == 5)
{
boost::shared_ptr<AbstractCvodeCell> p_new_model(new Cellten_tusscher_model_2006_MFromCellMLCvode(p_solver, p_stimulus));
p_model = p_new_model;
}
else if (model_index == 6)
{
boost::shared_ptr<AbstractCvodeCell> p_new_model(new Cellohara_rudy_2011_endoFromCellMLCvode(p_solver, p_stimulus));
p_model = p_new_model;
}
else
{
boost::shared_ptr<AbstractCvodeCell> p_new_model(new Cellten_tusscher_model_2006_MFromCellMLCvode(p_solver, p_stimulus));
p_model = p_new_model;
}
std::string modelname = p_model->GetSystemName();
std::string intervention;
double starting_value;
OdeSolution solution;
if (inter_index ==1)
{
intervention = "membrane_L_type_calcium_current_conductance";
starting_value = p_model->GetParameter(intervention);
}
if (inter_index == 2)
{
intervention = "membrane_fast_sodium_current_shift_inactivation";
starting_value = 1;
}
if (inter_index == 3)
{
intervention = "membrane_rapid_delayed_rectifier_potassium_current_conductance";
starting_value = p_model->GetParameter(intervention);
}
std::cout << intervention << " begins at: " << starting_value << "\n";
// run to steady state
SteadyStateRunner steady_runner(p_model);
// set parameter as constant
p_model->SetParameter(intervention,starting_value);
bool result = steady_runner.RunToSteadyState();
std::cout << "Running to steady state: " << result << "\n";
p_model->SetParameter(intervention,starting_value*value);
std::cout << "Set to " << starting_value*value << "\n";
// // for nai
// p_model->SetStateVariable("cytosolic_sodium_concentration",starting_value);
// p_stimulus->SetPeriod(1000.0);
// solution = p_model->Compute(start_time,30000,dt);
// p_stimulus->SetPeriod(4000.0);
//p_stimulus->SetPeriod(4000.0);
std::string foldername = modelname + intervention + boost::lexical_cast<std::string>(value);
solution = p_model->Compute(start_time,end_time,dt);
solution.WriteToFile(("SingleRuns/" + foldername),foldername,"ms");
#else
/* CVODE is not enable or installed*/
std::cout << "Cvode is not enabled.\n";
#endif
}
};
#endif
<file_sep>/src/CreateModel.cpp
/*
Copyright (c) 2005-2016, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef CHASTE_CVODE
#include "DrugDataReader.hpp"
#include "SteadyStateRunner.hpp"
#include "CreateModel.hpp"
#include "shannon_wang_puglisi_weber_bers_2004Cvode.hpp"
#include "fink_noble_giles_model_2008Cvode.hpp"
#include "ten_tusscher_model_2006_epiCvode.hpp"
#include "ten_tusscher_model_2006_endoCvode.hpp"
#include "ten_tusscher_model_2006_MCvode.hpp"
#include "noble_model_1998Cvode.hpp"
#include "ohara_rudy_2011_endoCvode.hpp"
#include "ohara_rudy_2011_epiCvode.hpp"
#include "grandi_pasqualini_bers_2010_ssCvode.hpp"
#include "AbstractCvodeCell.hpp"
#include "DetectAfterDepolarisations.hpp"
#include "ClassifyAfterDepolarisations.hpp"
#include "Timer.hpp"
CreateModel::CreateModel(unsigned int inter_index, unsigned int model_index,
boost::shared_ptr<RegularStimulus> p_stimulus,
std::vector<double> intervention_values,
double start_time, double end_time, double dt, std::string drug_name, int conc_index,
std::string trace_folder)
: mInterIndex(inter_index),
mStartTime(start_time),
mEndTime(end_time),
mDt(dt),
mpStimulus(p_stimulus),
mInterventionValues(intervention_values),
mDrugName(drug_name),
mTraceFolder(trace_folder),
mConcIndex(conc_index),
mSkip(0),
mIncrement(1)
{
boost::shared_ptr<AbstractIvpOdeSolver> p_solver;
// pick model
boost::shared_ptr<AbstractCvodeCell> p_model;
if (model_index == 1)
{
boost::shared_ptr<AbstractCvodeCell> p_new_model(new Cellshannon_wang_puglisi_weber_bers_2004FromCellMLCvode(p_solver, mpStimulus));
p_model = p_new_model;
}
else if (model_index == 2)
{
boost::shared_ptr<AbstractCvodeCell> p_new_model(new Cellfink_noble_giles_model_2008FromCellMLCvode(p_solver, mpStimulus));
p_model = p_new_model;
}
else if (model_index == 3)
{
boost::shared_ptr<AbstractCvodeCell> p_new_model(new Cellten_tusscher_model_2006_epiFromCellMLCvode(p_solver, mpStimulus));
p_model = p_new_model;
}
else if (model_index == 4)
{
boost::shared_ptr<AbstractCvodeCell> p_new_model(new Cellten_tusscher_model_2006_endoFromCellMLCvode(p_solver, mpStimulus));
p_model = p_new_model;
}
else if (model_index == 5)
{
boost::shared_ptr<AbstractCvodeCell> p_new_model(new Cellten_tusscher_model_2006_MFromCellMLCvode(p_solver, mpStimulus));
p_model = p_new_model;
}
else if (model_index == 6)
{
boost::shared_ptr<AbstractCvodeCell> p_new_model(new Cellohara_rudy_2011_endoFromCellMLCvode(p_solver, mpStimulus));
p_model = p_new_model;
}
else if (model_index == 7)
{
boost::shared_ptr<AbstractCvodeCell> p_new_model(new Cellgrandi_pasqualini_bers_2010_ssFromCellMLCvode(p_solver, mpStimulus));
p_model = p_new_model;
}
else if (model_index == 8)
{
boost::shared_ptr<AbstractCvodeCell> p_new_model(new Cellohara_rudy_2011_epiFromCellMLCvode(p_solver, mpStimulus));
p_model = p_new_model;
}
mpModel = p_model;
mModelName = mpModel->GetSystemName();
// set up intervention
if (mInterIndex == 1)
{
mInterventionType = "StateVariable";
mIntervention.push_back("cytosolic_sodium_concentration");
}
else if (mInterIndex == 2 or mInterIndex == 13)
{
mInterventionType = "Parameter";
mIntervention.push_back("membrane_rapid_delayed_rectifier_potassium_current_conductance");
}
else if (mInterIndex == 3)
{
mInterventionType = "Parameter";
mIntervention.push_back("membrane_fast_sodium_current_shift_inactivation");
}
else if (mInterIndex == 4 or mInterIndex == 14)
{
mInterventionType = "Parameter";
mIntervention.push_back("membrane_L_type_calcium_current_conductance");
}
else if (mInterIndex == 5)
{
mInterventionType = "TwoParameters";
mIntervention.push_back("membrane_L_type_calcium_current_conductance");
mIntervention.push_back("extracellular_potassium_concentration");
}
else if (mInterIndex == 6)
{
mInterventionType = "Parameter";
mIntervention.push_back("membrane_persistent_sodium_current_conductance");
}
else if (mInterIndex == 7)
{
mInterventionType = "TwoParameters";
mIntervention.push_back("membrane_rapid_delayed_rectifier_potassium_current_conductance");
mIntervention.push_back("extracellular_potassium_concentration");
}
else if (mInterIndex == 8)
{
mInterventionType = "TwoParameters";
mIntervention.push_back("membrane_fast_sodium_current_shift_inactivation");
mIntervention.push_back("extracellular_potassium_concentration");
}
else if (mInterIndex == 9)
{
mInterventionType = "TwoParameters";
mIntervention.push_back("membrane_L_type_calcium_current_conductance");
mIntervention.push_back("extracellular_potassium_concentration");
}
else if (mInterIndex == 10)
{
mInterventionType = "TwoParameters";
mIntervention.push_back("membrane_rapid_delayed_rectifier_potassium_current_conductance");
mIntervention.push_back("extracellular_potassium_concentration");
}
else if (mInterIndex == 11)
{
mInterventionType = "TwoParameters";
mIntervention.push_back("membrane_fast_sodium_current_shift_inactivation");
mIntervention.push_back("extracellular_potassium_concentration");
}
else if (mInterIndex == 12)
{
mInterventionType = "Parameter";
mIntervention.push_back("membrane_fast_sodium_current_reduced_inactivation");
}
else if (mInterIndex == 15)
{
mInterventionType = "Parameter";
mIntervention.push_back("membrane_slow_delayed_rectifier_potassium_current_conductance");
}
std::cout << "Model name: " << mModelName << "\n";
std::cout << "Intervention: " << mInterventionType << " " << mIntervention[0] << "\n";
}
CreateModel::CreateModel()
{
std::cout << "Empty model created\n";
}
#endif
void CreateModel::Drug (std::vector<double>conductance_factors, std::vector<std::string> channel_names)
{
// take conductance factors and apply them to the model
mDrugConductanceFactors = conductance_factors;
mDrugParameterNames = channel_names;
std::vector<double> original_values;
for (unsigned int i= 0; i<mDrugParameterNames.size(); i++)
{
try
{
original_values.push_back(mpModel->GetParameter(mDrugParameterNames[i]));
}
catch(Exception &e)
{
std::cout << "No " << mDrugParameterNames[i] << "\n";
}
}
for (unsigned int j= 0; j<mDrugParameterNames.size(); j++)
{
try
{
mpModel->SetParameter(mDrugParameterNames[j],original_values[j]*mDrugConductanceFactors[j]);
mDruggedConductanceValues.push_back(original_values[j]*mDrugConductanceFactors[j]);
}
catch(Exception &e)
{
std::cout << "\n";
}
}
// get initial intervention values
if (mInterIndex == 1)
{
mInterventionInitialState.push_back(1);
//std::cout << "Original value is: " << mpModel->GetStateVariable(mIntervention[0]) << "\n";
}
else if (mInterIndex == 2 || mInterIndex == 13)
{
mInterventionInitialState.push_back(mpModel->GetParameter(mIntervention[0]));
//std::cout << "Original value of " << mIntervention[0] << " is " << mInterventionInitialState[0] << "\n";
}
else if (mInterIndex == 3)
{
this->mInterventionInitialState.push_back(0);
}
else if (mInterIndex == 4 || mInterIndex == 14)
{
mInterventionInitialState.push_back(mpModel->GetParameter(mIntervention[0]));
//std::cout << "Original value of " << mIntervention[0] << " is " << mInterventionInitialState[0] << "\n";
}
else if (mInterIndex == 5)
{
mInterventionInitialState.push_back(mpModel->GetParameter(mIntervention[0]));
mInterventionInitialState.push_back(mpModel->GetParameter(mIntervention[1]));
}
else if (mInterIndex == 6)
{
mInterventionInitialState.push_back(mpModel->GetParameter(mIntervention[0]));
}
else if (mInterIndex == 7)
{
mInterventionInitialState.push_back(mpModel->GetParameter(mIntervention[0]));
mInterventionInitialState.push_back(mpModel->GetParameter(mIntervention[1]));
}
else if (mInterIndex == 8)
{
mInterventionInitialState.push_back(0);
mInterventionInitialState.push_back(mpModel->GetParameter(mIntervention[1]));
}
else if (mInterIndex == 9)
{
mInterventionInitialState.push_back(mpModel->GetParameter(mIntervention[0]));
mInterventionInitialState.push_back(mpModel->GetParameter(mIntervention[1]));
}
else if (mInterIndex == 10)
{
mInterventionInitialState.push_back(mpModel->GetParameter(mIntervention[0]));
mInterventionInitialState.push_back(mpModel->GetParameter(mIntervention[1]));
}
else if (mInterIndex == 11)
{
mInterventionInitialState.push_back(0);
mInterventionInitialState.push_back(mpModel->GetParameter(mIntervention[1]));
}
else if (mInterIndex == 12)
{
mInterventionInitialState.push_back(mpModel->GetParameter(mIntervention[0]));
}
else if (mInterIndex == 15)
{
mInterventionInitialState.push_back(mpModel->GetParameter(mIntervention[0]));
}
}
bool CreateModel::GetToSteadyState()
{
SteadyStateRunner steady_runner(mpModel);
bool result = steady_runner.RunToSteadyState();
// Reset intervention variable
if (mInterventionType == "StateVariable")
{
mpModel->SetStateVariable(mIntervention[0],mInterventionInitialState[0]);
}
else if (mInterventionType == "Parameter")
{
mpModel->SetParameter(mIntervention[0],mInterventionInitialState[0]);
}
else if (mInterventionType == "TwoParameters")
{
mpModel->SetParameter(mIntervention[0],mInterventionInitialState[0]);
mpModel->SetParameter(mIntervention[1],mInterventionInitialState[1]);
}
// Get all the variables out
mSteadyStateVariables = mpModel->GetStdVecStateVariables();
// For checking resetting later on
OdeSolution solution = mpModel->Compute(mStartTime,mEndTime,mDt);
mOldSolution = solution.GetAnyVariable("membrane_voltage");
return result;
}
bool CreateModel::ResetAndCheck()
{
// apply drug effects to model
for (unsigned int i = 0 ; i< mDruggedConductanceValues.size(); i++)
{
try
{
mpModel->SetParameter(mDrugParameterNames[i], mDruggedConductanceValues[i]);
}
catch(Exception &e)
{
std::cout << "No " << mDrugParameterNames[i] << "\n";
}
}
// reset state variables, including intervention state variable
mpModel->SetStateVariables(mSteadyStateVariables);
// reset intervention parameters if necessary
if (mInterventionType == "Parameter")
{
mpModel->SetParameter(mIntervention[0],mInterventionInitialState[0]);
}
else if (mInterventionType == "TwoParameters")
{
mpModel->SetParameter(mIntervention[0],mInterventionInitialState[0]);
mpModel->SetParameter(mIntervention[1],mInterventionInitialState[1]);
}
bool result = true;
return result;
}
int CreateModel::Intervene(int c, unsigned conc_index, std::string drug_name)
{
std::string output_filename;
std::stringstream output_namestream;
output_namestream << mTraceFolder << "/Sequential/" << mDrugName << mConcIndex << GetIdentifier() << c;
output_filename = output_namestream.str();
double intervention_value = mInterventionValues[c];
return DoTheIntervention(intervention_value, output_filename);
}
int CreateModel::DoTheIntervention(double intervention_value, std::string output_filename)
{
// apply the intervention to the model
if (mInterIndex == 1)
{
mpModel->SetStateVariable(mIntervention[0],intervention_value);
// check for a DELAYED afterdepolarisation
mpStimulus->SetPeriod(1000.0);
mpModel->Solve(0,30000,mpStimulus->GetDuration()); // Stimulus duration is the maximum time step to use
mpStimulus->SetPeriod(3000.0);
OdeSolution solution = mpModel->Solve(30000+mStartTime,30000+mEndTime,mpStimulus->GetDuration(),mDt);
ClassifyAfterDepolarisations AD_classify;
std::string result = AD_classify.CausedAD(solution, mpStimulus, output_filename);
if (result[0] == 'D')
{
return true;
}
else
{
return false;
}
}
else if (mInterIndex == 2)
{
mpModel->SetParameter(mIntervention[0],(mInterventionInitialState[0])*intervention_value);
}
else if (mInterIndex == 3)
{
mpModel->SetParameter(mIntervention[0],intervention_value);
}
else if (mInterIndex == 4)
{
mpModel->SetParameter(mIntervention[0],mInterventionInitialState[0]*intervention_value);
}
else if (mInterIndex == 5)
{
mpModel->SetParameter(mIntervention[0],mInterventionInitialState[0]*intervention_value);
mpModel->SetParameter(mIntervention[1],mInterventionInitialState[1]*2);
}
else if (mInterIndex == 6)
{
mpModel->SetParameter(mIntervention[0],mInterventionInitialState[0]*intervention_value);
}
else if (mInterIndex == 7)
{
mpModel->SetParameter(mIntervention[0],mInterventionInitialState[0]*intervention_value);
mpModel->SetParameter(mIntervention[1],mInterventionInitialState[1]*2);
}
else if (mInterIndex == 8)
{
mpModel->SetParameter(mIntervention[0],intervention_value);
mpModel->SetParameter(mIntervention[1],mInterventionInitialState[1]*2);
}
else if (mInterIndex == 9)
{
mpModel->SetParameter(mIntervention[0],mInterventionInitialState[0]*intervention_value);
mpModel->SetParameter(mIntervention[1],mInterventionInitialState[1]*0.75);
}
else if (mInterIndex == 10)
{
mpModel->SetParameter(mIntervention[0],mInterventionInitialState[0]*intervention_value);
mpModel->SetParameter(mIntervention[1],mInterventionInitialState[1]*0.75);
}
else if (mInterIndex == 11)
{
mpModel->SetParameter(mIntervention[0],intervention_value);
mpModel->SetParameter(mIntervention[1],mInterventionInitialState[1]*0.75);
}
else if (mInterIndex == 12)
{
mpModel->SetParameter(mIntervention[0],intervention_value);
}
else if (mInterIndex == 13)
{
mpModel->SetParameter(mIntervention[0],(mInterventionInitialState[0])+intervention_value);
}
else if (mInterIndex == 14)
{
mpModel->SetParameter(mIntervention[0],mInterventionInitialState[0]+intervention_value);
}
else if (mInterIndex == 15)
{
mpModel->SetParameter(mIntervention[0],mInterventionInitialState[0]*intervention_value);
}
// check for an afterdepolarisation
OdeSolution solution ;
try
{
if(mSkip > 0)
{
mpModel->Solve(mStartTime,mSkip,mpStimulus->GetDuration(), mDt);
}
//Timer::Reset();
// std::cout << "Begin: " << mStartTime+mSkip << "\nEnd: " << mEndTime << "\n";
solution = mpModel->Solve(mStartTime+mSkip,mEndTime,mpStimulus->GetDuration(), mDt);
//std::cout << mEndTime - mStartTime << " ms solve took " << Timer::GetElapsedTime() << "s.\n"<< std::flush;
}
catch (Exception &e)
{
std::cout << e.GetShortMessage() << std::endl;
return -2;
}
//Timer::Reset();
DetectAfterDepolarisations AD_test;
int result = AD_test.CausedAD(solution, mpStimulus, output_filename, true);
//std::cout << "AD detection took " << Timer::GetElapsedTime() << "s.\n"<< std::flush;
return result;
}
std::string CreateModel::GetIdentifier()
{
// return the name of the model and the intervention
if (mInterIndex == 5)
{
return (mModelName + mIntervention[0] + "_double_" + mIntervention[1]);
}
else if (mInterIndex == 7)
{
return (mModelName + mIntervention[0] + "_double_" + mIntervention[1]);
}
else if (mInterIndex == 8)
{
return (mModelName + mIntervention[0] + "_double_" + mIntervention[1]);
}
else if (mInterIndex == 9)
{
return (mModelName + mIntervention[0] + "_three_quarters_" + mIntervention[1]);
}
else if (mInterIndex == 10)
{
return (mModelName + mIntervention[0] + "_three_quarters_" + mIntervention[1]);
}
else if (mInterIndex == 11)
{
return (mModelName + mIntervention[0] + "_three_quarters_" + mIntervention[1]);
}
else if (mInterIndex == 14 || mInterIndex == 13)
{
return (mModelName + mIntervention[0] + "_additive");
}
return (mModelName + mIntervention[0]);
}
bool CreateModel::GetExpectedChange()
{
// Returns true if the intervention is expected to go from no AD to an AD as the intervention increases (i.e. IKr conductance)
// Returns false otherwise
if (mInterIndex == 2 || mInterIndex == 7 || mInterIndex == 10 || mInterIndex == 15)
{
return false;
}
return true;
}
void CreateModel::SetLimits(std::vector<double> coarse_threshold)
{
assert(coarse_threshold.size()==2);
mLimits = coarse_threshold;
mLimits.push_back(-2);
}
int CreateModel::InterveneAndCheck()
{
std::stringstream output_namestream;
std::string output_filename;
output_namestream << mTraceFolder << "/Bisection/" << mDrugName << mConcIndex << GetIdentifier() << mLimits[0];
output_filename = output_namestream.str();
double intervention_value = mLimits[0];
return DoTheIntervention(intervention_value, output_filename);
}
bool CreateModel::IntervalBisection(bool result)
{
// put together filename for AD checking
std::stringstream output_namestream;
std::string output_filename;
output_namestream << mTraceFolder << "/Bisection/" << mDrugName << mConcIndex << GetIdentifier(); /* is there an AD? */
output_filename = output_namestream.str();
// std::cout << "Intervention value: " << mLimits[0] << "\n2: " << mLimits[1] << "\n3: " << mLimits[2] << "\n";
bool expected_result = GetExpectedChange();
// initial values
if (mLimits[2]==-2) //first iteration
{
// mLimits = {lower_limit, upper_limit, -2}
if (result == expected_result)
{
std::cout << "Unexpected result at lower limit\n";
std::cout << "At: " << mLimits[0] << "\n";
mLimits[0] = mLimits[0] - mIncrement;
// mLimits = {new_lower_limit, upper_limit, -2}
}
else
{
double hold_upper_limit = mLimits[1];
mLimits[1] = mLimits[0];
mLimits[0] = hold_upper_limit;
mLimits[2] = -3;
// mLimits = {upper_limit, lower_limit, -3}
}
}
else if (mLimits[2]==-3) // second iteration
{
// mLimits = {upper_limit, lower_limit, -3}
if (result != expected_result)
{
std::cout << "Unexpected result at higher limit\n";
std::cout << "At: " << mLimits[0] << "\n";
mLimits[0] = mLimits[0] + mIncrement;
// mLimits = {new_upper_limit, lower_limit, -3}
}
else
{
// mLimits = {upper_limit, lower_limit, -3}
mLimits[2] = mLimits[0];
mLimits[0] = mLimits[1]+((mLimits[2]-mLimits[1])/2);
// mLimits = {middle_number, lower_limit, upper_limit}
}
}
else // all other iterations
{
if (result == expected_result) // if there is an AD
{
//calculate middle number, get rid of old upper limit
// mLimits = {middle_number, lower_limit, upper_limit}
double next_limit = mLimits[1]+((mLimits[0]-mLimits[1])/2);
mLimits[2] = mLimits[0];
mLimits[0] = next_limit;
}
else
{
// calculate middle number, get rid of old lower limit
double next_limit = mLimits[0]+((mLimits[2]-mLimits[0])/2);
mLimits[1] = mLimits[0];
mLimits[0] = next_limit;
}
if (std::abs(mLimits[2]-mLimits[1])< 0.0001) // if thresholds are converging
{
return true;
}
}
return false;
}
double CreateModel::GetThreshold()
{
return mLimits[1];
}
std::vector<int> CreateModel::PossibleCombinations()
{
// the idea is to return the total number of models and total number of interventions so that
// TestCompletenessOfData.hpp can work out how much data we don't have yet
// currently it's hard-coded
std::vector<int> inputs;
inputs.push_back(5);
inputs.push_back(12);
//inputs[0] = 5;
//inputs[1] = 12;
return inputs;
}
std::string CreateModel::GetModelName()
{
return mModelName;
}
std::string CreateModel::GetInterventionName()
{
// the idea is to return the name of the intervention we are using
// currently this is not implemented
return "hello";
}
void CreateModel::SkipTime(double skip_time)
{
mSkip = skip_time;
return;
}
void CreateModel::ChangeIncrement(double new_increment)
{
mIncrement = new_increment;
return;
}
<file_sep>/test/TestOharaAPD90.hpp
/*
Copyright (c) 2005-2017, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TESTOHARAAPD90_HPP_
#define TESTOHARAAPD90_HPP_
#include <cxxtest/TestSuite.h>
#include "DetectAfterDepolarisations.hpp"
#include "ThresholdIntervention.hpp"
#include "ColumnDataReader.hpp"
#include "DrugDataReader.hpp"
#include <sstream>
#include <iomanip>
#include "AbstractCardiacCell.hpp"
#include "AbstractCvodeCell.hpp"
#include "CellProperties.hpp"
#include "OutputFileHandler.hpp"
#include <sys/stat.h>
#include "SteadyStateRunner.hpp"
#include "ohara_rudy_2011_endoCvode.hpp"
#include "grandi_pasqualini_bers_2010_ssCvode.hpp"
#include "projects/ApPredict/src/single_cell/SingleActionPotentialPrediction.hpp"
#include "Debug.hpp"
class TestOharaAPD90 : public CxxTest::TestSuite
{
public:
void TestGetAPD90()
{
/* Make sure this code is only run if CVODE is installed/enabled on the computer */
#ifdef CHASTE_CVODE
// take in drug data
DrugDataReader drug_data("projects/EadPredict/test/curated_dataset.dat");
// make sure there are enough drugs
TS_ASSERT_DIFFERS(drug_data.GetNumDrugs(),0u);
// for running simulations
//double start_time = 0.0;
//double end_time = 10000.0;
//double dt = 0.1;
// set up a model so I can steal the default stimulus
boost::shared_ptr<AbstractIvpOdeSolver> p_solver;
boost::shared_ptr<AbstractStimulusFunction> p_stimulus;
boost::shared_ptr<AbstractCvodeCell> p_model(new Cellohara_rudy_2011_endoFromCellMLCvode(p_solver, p_stimulus));
p_stimulus = p_model->UseCellMLDefaultStimulus();
//output file for all drug results
std::ofstream apd90_file;
std::string file_location = getenv("CHASTE_TEST_OUTPUT");
std::string apd90_filename = file_location + "Tox_Res_Paper/curated_dataset_ohara_apd90.dat";
apd90_file.open(apd90_filename.c_str());
// check that the file exists
//TS_ASSERT_EQUALS(stat(apd90_filename.c_str(), &sb),0);
// loop through all the drugs
for (unsigned int drug_index=0; drug_index < drug_data.GetNumDrugs(); drug_index++)
{
// get out the name of the drug
std::string drug_name = drug_data.GetDrugName(drug_index) ;
TS_ASSERT_DIFFERS(drug_name.length(), 0u);
double drug_conc = drug_data.GetClinicalDoseRange(drug_index,1u);
// make a new model
boost::shared_ptr<AbstractCvodeCell> p_model(new Cellohara_rudy_2011_endoFromCellMLCvode(p_solver, p_stimulus));
apd90_file << drug_name;
std::vector<double> conductance_factors;
for (int b=0; b<7; b++)
{
conductance_factors.push_back(DrugDataReader::CalculateConductanceFactor(drug_conc,drug_data.GetIC50Value(drug_index,b)));
}
// take conductance factors and apply them to the model
std::vector<double> original_values;
std::vector<std::string> block_channel_names;
block_channel_names.push_back("membrane_fast_sodium_current_conductance");
block_channel_names.push_back("membrane_L_type_calcium_current_conductance");
block_channel_names.push_back("membrane_rapid_delayed_rectifier_potassium_current_conductance");
block_channel_names.push_back("membrane_slow_delayed_rectifier_potassium_current_conductance");
block_channel_names.push_back("membrane_persistent_sodium_current_conductance");
block_channel_names.push_back("membrane_transient_outward_current_conductance");
block_channel_names.push_back("membrane_inward_rectifier_potassium_current_conductance");
for (unsigned int i= 0; i<block_channel_names.size(); i++)
{
try
{
original_values.push_back(p_model->GetParameter(block_channel_names[i]));
}
catch(Exception &e)
{
original_values.push_back(-2);
std::cout << "No " << block_channel_names[i] << "\n";
}
}
for (unsigned int j= 0; j<block_channel_names.size(); j++)
{
try
{
p_model->SetParameter(block_channel_names[j],original_values[j]*conductance_factors[j]);
}
catch(Exception &e)
{
std::cout << "\n";
}
}
// run to steady state
SteadyStateRunner steady_runner(p_model);
bool result = steady_runner.RunToSteadyState();
std::cout << "Running to steady state: " << result << "\n";
SingleActionPotentialPrediction ap_runner(p_model);
ap_runner.SetMaxNumPaces(1000u);
ap_runner.RunSteadyPacingExperiment();
double apd90;
if (ap_runner.DidErrorOccur())
{
std::cout << "An error occurred\n";
}
else
{
apd90 = ap_runner.GetApd90();
}
apd90_file << "\t" << apd90 << "\n";
}
apd90_file.close();
#else
/* CVODE is not enable or installed*/
std::cout << "Cvode is not enabled.\n";
#endif
}
};
#endif
<file_sep>/src/ThresholdIntervention.cpp
/*
Copyright (c) 2005-2017, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef CHASTE_CVODE
#include "ThresholdIntervention.hpp"
#include <fstream>
#include "AbstractCvodeCell.hpp"
#include "RegularStimulus.hpp"
#include "DetectAfterDepolarisations.hpp"
#include "Debug.hpp"
#include "Debug.hpp"
ThresholdIntervention::ThresholdIntervention(){}
double ThresholdIntervention::FindAtUniformPace(boost::shared_ptr<AbstractCvodeCell> p_model,
boost::shared_ptr<RegularStimulus> p_stimulus, std::string protocol, int drug_index, int conc_index,
double new_gNa_value, double new_gCaL_value, double new_gKr_value, double new_gpNa_value)
{
// for running simulations
double start_time = 0.0;
double end_time = 10000.0;
double dt = 0.1;
bool result;
double next_limit, starting_value, test_value;
// initial values
double threshold = 0;
double limits[3] = {0,50,-2};
int numsteps = 100;
OdeSolution solution;
std::string parameter;
std::string modelname = p_model->GetSystemName();
// reset to initial conditions and set currents to drugged state
p_model->SetStateVariables(p_model->GetInitialConditions());
p_model->SetParameter("membrane_fast_sodium_current_conductance",new_gNa_value);
p_model->SetParameter("membrane_L_type_calcium_current_conductance",new_gCaL_value);
p_model->SetParameter("membrane_rapid_delayed_rectifier_potassium_current_conductance",new_gKr_value);
try
{
p_model->SetParameter("membrane_persistent_sodium_current_conductance",new_gpNa_value);
}
catch(Exception &e)
{
std::cout << "No ipNa" << "\n";
}
// solve the model for a time period to check that resetting has been successful
solution = p_model->Compute(start_time,end_time,dt);
std::vector<double> old_solution = solution.GetAnyVariable("membrane_voltage");
std::vector<double> new_solution;
// set up intervention
if (protocol=="iCaL")
{
parameter = "membrane_L_type_calcium_current_conductance";
starting_value = p_model->GetParameter(parameter);
limits[0] = 1;
}
if (protocol=="iNa")
{
parameter = "membrane_fast_sodium_current_shift_inactivation";
starting_value = 1;
}
if (protocol == "iKr")
{
parameter = "membrane_rapid_delayed_rectifier_potassium_current_conductance";
starting_value = p_model->GetParameter(parameter);
limits[0] = -1;
limits[1] = 1;
}
if (protocol == "Nai")
{
limits[0] = 1;
limits[1] = 5;
}
for(int i=0; i<numsteps; i++)
{
if (protocol != "Nai")
{
//reset to initial state and set currents to drugged state
p_model->SetStateVariables(p_model->GetInitialConditions());
p_model->SetParameter("membrane_fast_sodium_current_conductance",new_gNa_value);
p_model->SetParameter("membrane_L_type_calcium_current_conductance",new_gCaL_value);
p_model->SetParameter("membrane_rapid_delayed_rectifier_potassium_current_conductance",new_gKr_value);
try
{
p_model->SetParameter("membrane_persistent_sodium_current_conductance",new_gpNa_value);
}
catch(Exception &e)
{
std::cout << "No ipNa" << "\n";
}
// reset intervention parameter
p_model->SetParameter(parameter,starting_value);
solution = p_model->Compute(start_time,end_time,dt);
new_solution = solution.GetAnyVariable("membrane_voltage");
// test that resetting has been successful
if (i>0)
{
assert(old_solution == new_solution);
}
old_solution = new_solution;
//reset to initial state again
p_model->SetStateVariables(p_model->GetInitialConditions());
p_model->SetParameter("membrane_fast_sodium_current_conductance",new_gNa_value);
p_model->SetParameter("membrane_L_type_calcium_current_conductance",new_gCaL_value);
p_model->SetParameter("membrane_rapid_delayed_rectifier_potassium_current_conductance",new_gKr_value);
try
{
p_model->SetParameter("membrane_persistent_sodium_current_conductance",new_gpNa_value);
}
catch(Exception &e)
{
std::cout << "No ipNa" << "\n";
}
/* change intervention parameter value */
std::cout << "Iteration " << i << ": " << limits[0] << "\n";
test_value = starting_value * limits[0];
p_model->SetParameter(parameter,test_value);
// for debugging
PRINT_VARIABLE(p_model->GetParameter(parameter));
PRINT_VARIABLE(p_model->GetParameter("membrane_fast_sodium_current_conductance"));
PRINT_VARIABLE(p_model->GetParameter("membrane_L_type_calcium_current_conductance"));
PRINT_VARIABLE(p_model->GetParameter("membrane_rapid_delayed_rectifier_potassium_current_conductance"));
try
{
std::cout << "ipNa: " << p_model->GetParameter("membrane_persistent_sodium_current_conductance") << "\n";
}
catch(Exception &e)
{
std::cout << "No ipNa" << "\n";
}
/* run simulation */
solution = p_model->Compute(start_time,end_time,dt);
}
else
{
// if modifying cytosolic sodium concentration
//test_value = p_model[i]->GetStateVariable("cytosolic_sodium_concentration")*limits[0];
p_model->SetStateVariable("cytosolic_sodium_concentration",limits[0]);
boost::shared_ptr<RegularStimulus> p_regular_stim = p_model->UseCellMLDefaultStimulus();
p_regular_stim->SetPeriod(1000.0);
OdeSolution early_solution = p_model->Compute(start_time,30000.0,dt);
p_regular_stim->SetPeriod(3000.0);
solution = p_model->Compute(30000.0,40000.0,dt);
}
// put together filename for output
std::stringstream output_namestream;
std::string output_filename;
output_namestream << "CvodeCells" << protocol << modelname << "_s_" << drug_index << "_" << conc_index << "_" << limits[0];
output_filename = output_namestream.str();
/* is there an AD? */
DetectAfterDepolarisations AD_test;
result = AD_test.CausedAD(solution, p_stimulus, output_filename, false);
// based on whether there is an AD, pick a new value to test
if (limits[2]==-2) //first iteration
{
// limits = {lower_limit, upper_limit, -2}
double hold_upper_limit = limits[1];
limits[1] = limits[0];
limits[0] = hold_upper_limit;
limits[2] = -3;
// limits = {upper_limit, lower_limit, -3}
if (result)
{
limits[1]+=1;
}
}
else if (limits[2]==-3) // second iteration
{
// limits = {upper_limit, lower_limit, -3}
limits[2] = limits[0];
limits[0] = limits[1]+((limits[2]-limits[1])/2);
// limits = {middle_number, lower_limit, upper_limit}
}
else
{
if (result) // if there is an AD
{
//calculate middle number, get rid of old upper limit
// limits = {middle_number, lower_limit, upper_limit}
next_limit = limits[1]+((limits[0]-limits[1])/2);
limits[2] = limits[0];
limits[0] = next_limit;
threshold = limits[0];
}
else
{
// calculate middle number, get rid of old lower limit
next_limit = limits[0]+((limits[2]-limits[0])/2);
limits[1] = limits[0];
limits[0] = next_limit;
}
if ((limits[2]-limits[1])< 0.0001) // if thresholds are converging
{
break;
}
}
}
return threshold;
}
#endif
|
07c4957eb3d7c39bf5c5a9f92d374b7ca7e6f272
|
[
"Markdown",
"Python",
"R",
"C++"
] | 17
|
R
|
teraspawn/template_project
|
89a8e9d2a323574bd4c0390efe8c58693708f7db
|
301d4ce84fe24d4898b71f0fe5bdf9df7f133c83
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.