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 com.example.lab4_hiit; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.util.Log; import android.widget.TextView; import android.speech.tts.TextToSpeech; import java.util.ArrayList; import java.util.Locale; import static java.lang.Math.round; public class TimerActivity extends AppCompatActivity { private TextToSpeech tts = null; private TextView workoutText; private ArrayList<WorkoutPart> myWorkout; private int index = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_timer); workoutText = (TextView) findViewById(R.id.workoutInfoText); tts=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if(status != TextToSpeech.ERROR) { tts.setLanguage(Locale.UK); } } }); Intent intent = getIntent(); myWorkout = (ArrayList<WorkoutPart>) intent.getSerializableExtra(MainActivity.MESSAGE_KEY); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { TimerActivities(); } }, 1000); } private void TimerActivities() { final String workoutName = myWorkout.get(index).getName().toUpperCase(); tts.speak(workoutName, TextToSpeech.QUEUE_FLUSH, null); new CountDownTimer(myWorkout.get(index).getSeconds()*1000, 1000) { public void onTick(long millisUntilFinished) { workoutText.setText(workoutName +"\n" + round((float)millisUntilFinished / 1000)); } public void onFinish() { if(++index < myWorkout.size()) { TimerActivities(); } else finish(); } }.start(); } } <file_sep>include ':app' rootProject.name='Lab4_hiit' <file_sep>include ':app' rootProject.name='Lab3EggTimer' <file_sep>package com.example.lab3notepad; import androidx.appcompat.app.AppCompatActivity; import android.content.SharedPreferences; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; public class MainActivity extends AppCompatActivity { SharedPreferences sharedPreferences; SharedPreferences.Editor editor; private final String MY_PREFS_NAME = "MyPrefs"; private final String MY_PREFS_TEXT_KEY = "MyText"; EditText textEdit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sharedPreferences = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); editor = sharedPreferences.edit(); textEdit = (EditText) findViewById(R.id.textEdit); textEdit.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { editor.putString(MY_PREFS_TEXT_KEY, textEdit.getText().toString()); editor.apply(); } }); textEdit.setText(sharedPreferences.getString(MY_PREFS_TEXT_KEY, "")); } } <file_sep>include ':app' rootProject.name='greetingssit' <file_sep>include ':app' rootProject.name='Lab2externals' <file_sep>include ':app' rootProject.name='Lab3notepad' <file_sep>include ':app' rootProject.name='21' <file_sep>package com.example.lab3eggtimer; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.os.CountDownTimer; import android.widget.TextView; import static java.lang.Math.round; public class TimerActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_timer); Intent intent = getIntent(); String message = intent.getStringExtra(MainActivity.MESSAGE_KEY); final TextView textView = findViewById(R.id.textView); textView.setText(message); new CountDownTimer(Integer.parseInt(message)*1000, 1000) { public void onTick(long millisUntilFinished) { textView.setText("" + round((float)millisUntilFinished/1000)); } public void onFinish() { finish(); } }.start(); } }
1bdb41b6f7d674459841cac473c10eb25f15f273
[ "Java", "Gradle" ]
9
Java
rkettu/AndroidStudioExercises
1295dddc171883297b7901986b3d6acd16c964af
9c7136aaf59e6a8ead57cbfdd2ff508aaa6c5aa9
refs/heads/master
<repo_name>Knk00/it-s-all-being-smart<file_sep>/geo.py import googlemaps from firebase import firebase firebase = firebase.FirebaseApplication('https://vehnavi.firebaseio.com/') dest = firebase.get('/Location',None) newdest=dest print("Waiting for destination") while(newdest==dest): dest = firebase.get('/Location',None) print(end="") client = googlemaps.Client("<KEY>") #dest=raw_input("Where do you wanna go?") search = client.geocode(dest) latdes=search[0]['geometry']['location']['lat'] longdes=search[0]['geometry']['location']['lng'] reverse = client.reverse_geocode((latdes, longdes)) r1=reverse[0]['formatted_address'] turn=(client.directions((18.499034, 73.820753), "Mumbai")[0]['legs'][0]['steps'][1]['maneuver']) print(client.directions((18.499034, 73.820753), "Mumbai")[0]['legs'][0]['steps'][0]['distance']['text']) turn1=turn.split('-') dist1=dist.split() dis=int(dist1[0]) print(r1) <file_sep>/display.py import googlemaps import re import RPi.GPIO as gpio import time import Tkinter as tk from PIL import ImageTk, Image #This creates the main window of an application window = tk.Tk() window.title("Directions") window.geometry("300x300") window.configure(background='gray') img1 = ImageTk.PhotoImage(Image.open("uturn.jpeg")) img2 = ImageTk.PhotoImage(Image.open("straight.jpeg")) img3 = ImageTk.PhotoImage(Image.open("right.jpeg")) img4 = ImageTk.PhotoImage(Image.open("left.jpeg")) client = googlemaps.Client("<KEY>") #print(client.directions("Pune", "Mumbai")[0]['legs'][0]['steps'][0]['html_instructions']) print(re.findall('<b>[\w,-]+</b>', client.directions("Pune", "Mumbai")[0]['legs'][0]['steps'][0]['html_instructions'])[0].replace('<b>', "").replace('</b>', '')) turn=client.directions("Pune", "Mumbai")[0]['legs'][0]['steps'][1]['maneuver'] print(turn) turn_distance=client.directions("Pune", "Mumbai")[0]['legs'][0]['steps'][0]['distance']['text'] if "right" in turn and "uturn" not in turn: panel = tk.Label(window, image = img3) panel.pack(side = "bottom", fill = "both", expand = "yes") window.mainloop() tk.update() if turn_distance <= 20: pass #put in the gpio pins to turn on the indicator elif "left" in turn and "uturn" not in turn: panel = tk.Label(window, image = img4) panel.pack(side = "bottom", fill = "both", expand = "yes") tk.update() window.mainloop() if turn_distance <= 20: pass #put in the gpio pins to turn on the indicator elif turn == "uturn-left": panel = tk.Label(window, image = img1) panel.pack(side = "bottom", fill = "both", expand = "yes") tk.update() window.mainloop() if turn_distance <= 20: pass #put in the gpio pins to turn on the indicator else: panel = tk.Label(window, image = img2) panel.pack(side = "bottom", fill = "both", expand = "yes") print('Go straight') window.mainloop() tk.update() <file_sep>/flasher.py import googlemaps import re import RPi.GPIO as gpio import time import random import Tkinter as tk from PIL import ImageTk, Image #This creates the main window of an application window = tk.Tk() window.title("Directions") window.geometry("300x300") window.configure(background='red') client = googlemaps.Client("<KEY>") #canvas = Canvas(root, width = 300, height = 300) #Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object. img1 = ImageTk.PhotoImage(Image.open("uturn.jpeg")) img2 = ImageTk.PhotoImage(Image.open("straight.jpeg")) img3 = ImageTk.PhotoImage(Image.open("right.jpeg")) img4 = ImageTk.PhotoImage(Image.open("left.jpeg")) #canvas.create_image(20, 20, anchor=NW, image=img) i=1 #tk.update() while(True): turn=(client.directions("Pune", "Mumbai")[0]['legs'][0]['steps'][i]['maneuver']) print(client.directions("Pune", "Mumbai")[0]['legs'][0]['steps'][0]['distance']['text']) i=i+1 if ( turn == "turn-left" ): print("H") #panel = tk.Label(window, image = img4) panel.pack(side = "bottom", fill = "both", expand = "yes") window.update() time.sleep(1) if ( turn == "turn-right" ): print("He") panel = tk.Label(window, image = img3) panel.pack(side = "bottom", fill = "both", expand = "yes") window.update() time.sleep(1) #tk.update() if ( turn == "uturn-right" ): print("Hel") panel = tk.Label(window, image = img1) panel.pack(side = "bottom", fill = "both", expand = "yes") window.update() time.sleep(1) #tk.update() if ( turn == "uturn-right" ): print("Hell") panel = tk.Label(window, image = img2) panel.pack(side = "bottom", fill = "both", expand = "yes") window.update() time.sleep(1) <file_sep>/t.py import googlemaps import re client = googlemaps.Client("Your API key") #print(client.directions("Pune", "Mumbai")[0]['legs'][0]['steps'][0]['html_instructions']) #print(re.findall('<b>[\w,-]+</b>', client.directions("Pune", #"Mumbai")[0]['legs'][0]['steps'][0]['html_instructions'])[0].replace('<b>', "").replace('</b>', '')) print(client.directions((18.499034, 73.820753), "Mumbai")[0]['legs'][0]['steps'][1]['maneuver']) print(client.directions((18.499034, 73.820753), "Mumbai")[0]['legs'][0]['steps'][0]['distance']['text']) #turn=(client.directions(source1,destination1)[0]['legs'][0]['steps'][1]['maneuver']) #dist=(client.directions((18.499034, 73.820753), "Mumbai")[0]['legs'][0]['steps'][0]['distance']['text']) #dis=(client.directions(18.499034, 73.820753), "Mumbai")[0]['legs'][0]['steps'][0]['distance']['value']) #print(dis) #print(dist) turn_distance=client.directions("Pune", "Mumbai")[0]['legs'][0]['steps'][0]['distance']['text'] print(type(turn_distance)) turn=turn_distance.split() print(float(turn[0])) <file_sep>/ultra.py ##Code for ultrasonic sensor using raspberry pi -- for object coming close to you module import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) usecho=1 vcc=21 ust=12 lr=16 ll=20 GPIO.setup(lr,GPIO.OUT) GPIO.setup(vcc,GPIO.OUT) GPIO.setup(ll,GPIO.OUT) GPIO.setup(usecho,GPIO.IN) GPIO.setup(ust,GPIO.OUT) GPIO.output(vcc,GPIO.HIGH) GPIO.output(lr,GPIO.LOW) GPIO.output(ust,GPIO.LOW) GPIO.output(ll,GPIO.LOW) #GPIO.output(ll,GPIO.HIGH) def ultrasound(): #GPIO.output(usecho,GPIO.LOW) GPIO.output(ust,GPIO.LOW) time.sleep(1) GPIO.output(ust,GPIO.HIGH) time.sleep(0.00001) GPIO.output(ust,GPIO.LOW) while(GPIO.input(usecho)==0): start_time=time.time() while(GPIO.input(usecho)==1): end_time=time.time() total_time = end_time - start_time distance=round(17150*total_time,2) print("Distance : " ,distance, "cm") return distance destus=ultrasound() print(destus) GPIO.output(ll,GPIO.LOW) GPIO.output(lr,GPIO.LOW) <file_sep>/README.md # it-s-all-being-smart<file_sep>/fire.py from firebase import firebase firebase = firebase.FirebaseApplication('https://vehnavi.firebaseio.com/') boundry = firebase.get('/Location',None) print("Boundry System : ",boundry)
8af2153b017e22f4f1711f256789c59fa0f1456c
[ "Markdown", "Python" ]
7
Python
Knk00/it-s-all-being-smart
58a25f77935d529acfe464aa682deb2b091fb877
ca21bafc1a10ab57d5557ac2460cf4d6f5ffda2e
refs/heads/master
<file_sep>#' A data set from Carpenter (2002). #' #' @docType data #' @source Carpenter, <NAME>. 2002. ''Groups, the Media, Agency Waiting Costs, and FDA Drug Approval.'' American Journal of Political Science 46(3): 490-505. #' #' <NAME>, "Replication data for: Proportionally Difficult: Testing for Nonproportional Hazards In Cox Models". \url{http://hdl.handle.net/1902.1/17068}. V1 [Version]. #' @keywords datasets #' @format A data set with 408 observations and 32 variables. #' @name CarpenterFdaData NULL<file_sep>\name{tvc} \alias{tvc} \title{Create a time interaction variable} \usage{ tvc(data, b, tvar, tfun = "linear", pow = NULL) } \arguments{ \item{data}{a data frame} \item{b}{the non-time interacted variable's name} \item{tvar}{the time variable's name} \item{tfun}{function of time that btvc was multiplied by. Default is \code{tfun = "linear"}. Can also be \code{tfun = "log"} (natural log) and \code{tfun = "power"}. If \code{tfun = "power"} then the pow argument needs to be specified also.} \item{pow}{if \code{tfun = "power"}, then use pow to specify what power to raise the time interaction to.} } \value{ a vector } \description{ \code{tvc} creates a time interaction variable that can be used in a coxph model (or any other model with time interactions) } \details{ Interacts a variable with a specified function of time. Possible functions of time include \code{'linear'}, natural \code{'log'}, and exponentiated (\code{'power'}). } \examples{ # Load Golub & Steunenberg (2007) Data data("GolubEUPData") # Create natural log time interaction with the qmv variable GolubEUPData$Lqmv <- tvc(GolubEUPData, b = "qmv", tvar = "end", tfun = "log") } \seealso{ \code{\link{simGG.simtvc}}, \code{coxsimtvc}, \code{\link{survival}}, and \code{\link{coxph}} } \keyword{utilities} <file_sep>#' Graph fitted stratified survival curves from Cox Proportional Hazards models #' #' \code{ggfitStrata} graphs fitted survival curves created with \code{\link{survfit}} using \link{ggplot2}. #' #' @param obj a \code{survfit} object. #' @param byStrata logical, whether or not you want to include all of the stratified survival curves on one plot or separate them into a grid arranged plot. #' @param xlab a label for the plot's x-axis #' @param ylab a label of the plot's y-axis #' @param title plot title. #' @param lcolour line color. Currently only works if \code{byStrata = TRUE}. The default it \code{lcolour = "#2C7FB8"} (a bluish hexadecimal colour) #' @param rcolour confidence bounds ribbon color. Either a single color or a vector of colours. The default it \code{lcolour = "#2C7FB8"} (a bluish hexadecimal colour) #' #' @description This function largely improves \code{\link{plot.survfit}}. It plots the curves using \link{ggplot2} rather than base R graphics. One major advantage is the ability to split the survival curves into multiple plots and arrange them in a grid. This makes it easier to examine many strata at once. Otherwise they can be very bunched up. #' #' Note: the strata legend labels need to be changed manually (see \code{\link{revalue}}) in the \code{survfit} object with the \code{strata} component. #' @examples #' # dontrun #' # Load survival #' # library(survival) #' # Subset data #' # bladder1 <- bladder[bladder$enum < 5, ] #' # Estimate coxph model #' # M1 <- coxph(Surv(stop, event) ~ (rx + size + number) * strata(enum) + cluster(id), bladder1) #' # Survfit #' # M1Fit <- survfit(M1) #' # Plot strata in a grid #' # ggfitStrata(M1Fit, byStrata = TRUE) #' #' @seealso \code{\link{survfit}}, \code{\link{ggplot2}} and \code{\link{strata}} #' @import ggplot2 #' @importFrom gridExtra grid.arrange #' @export ggfitStrata <- function(obj, byStrata = FALSE, xlab = "", ylab = "", title = "", lcolour = "#2C7FB8", rcolour = "#2C7FB8") { Strata <- Lower <- Upper <- StrataC <- Time <- Survival <- NULL sFit <- obj time <- sFit$time lower <- sFit$lower upper <- sFit$upper S <- sFit$surv strata <- sFit$strata strata <- factor(rep(names(strata), strata), levels = names(strata)) TempData <- data.frame(Time = time, Lower = lower, Upper = upper, Survival = S, Strata = strata) if (byStrata == FALSE){ ggplot(data = TempData, aes(x = Time, y = Survival, color = Strata, fill = Strata)) + geom_line() + geom_ribbon(aes(ymin = Lower, ymax = Upper), alpha = I(0.1)) + xlab(xlab) + ylab(ylab) + ggtitle(title) + theme_bw() } else if (byStrata == TRUE){ TempData$StrataC <- gsub("=", "", TempData$Strata) TempData$StrataC <- gsub(" ", "", TempData$StrataC) eachStrata <- unique(TempData$StrataC) p <- list() for (i in eachStrata){ SubData <- subset(TempData, StrataC == i) p[[i]] <- ggplot(data = SubData, aes(x = Time, y = Survival)) + geom_line(colour = lcolour) + geom_ribbon(aes(ymin = Lower, ymax = Upper), alpha = I(0.1), colour = NA, fill = rcolour) + xlab("") + ylab("") + ggtitle(paste(i, "\n")) + theme_bw() } Grid <- do.call(grid.arrange, c(p, main = title, sub = xlab, left = ylab)) } }<file_sep>\name{ggfitStrata} \alias{ggfitStrata} \title{Graph fitted stratified survival curves from Cox Proportional Hazards models} \usage{ ggfitStrata(obj, byStrata = FALSE, xlab = "", ylab = "", title = "", lcolour = "#2C7FB8", rcolour = "#2C7FB8") } \arguments{ \item{obj}{a \code{survfit} object.} \item{byStrata}{logical, whether or not you want to include all of the stratified survival curves on one plot or separate them into a grid arranged plot.} \item{xlab}{a label for the plot's x-axis} \item{ylab}{a label of the plot's y-axis} \item{title}{plot title.} \item{lcolour}{line color. Currently only works if \code{byStrata = TRUE}. The default it \code{lcolour = "#2C7FB8"} (a bluish hexadecimal colour)} \item{rcolour}{confidence bounds ribbon color. Either a single color or a vector of colours. The default it \code{lcolour = "#2C7FB8"} (a bluish hexadecimal colour)} } \description{ This function largely improves \code{\link{plot.survfit}}. It plots the curves using \link{ggplot2} rather than base R graphics. One major advantage is the ability to split the survival curves into multiple plots and arrange them in a grid. This makes it easier to examine many strata at once. Otherwise they can be very bunched up. Note: the strata legend labels need to be changed manually (see \code{\link{revalue}}) in the \code{survfit} object with the \code{strata} component. } \details{ \code{ggfitStrata} graphs fitted survival curves created with \code{\link{survfit}} using \link{ggplot2}. } \examples{ # dontrun # Load survival # library(survival) # Subset data # bladder1 <- bladder[bladder$enum < 5, ] # Estimate coxph model # M1 <- coxph(Surv(stop, event) ~ (rx + size + number) * strata(enum) + cluster(id), bladder1) # Survfit # M1Fit <- survfit(M1) # Plot strata in a grid # ggfitStrata(M1Fit, byStrata = TRUE) } \seealso{ \code{\link{survfit}}, \code{\link{ggplot2}} and \code{\link{strata}} } <file_sep>#' A method for plotting simulation objects created by simPH #' #' @param obj an object created by one of simPH's simulation commands. #' @param ... arguments to be passed to methods. #' #' @seealso \code{\link{simGG.siminteract}}, \code{\link{simGG.simtvc}}, \code{\link{simGG.simlinear}}, \code{\link{simGG.simpoly}}, \code{\link{simGG.simspline}} #' @export simGG #' simGG <- function(obj, ...){ UseMethod("simGG", obj) }<file_sep>\name{coxsimtvc} \alias{coxsimtvc} \title{Simulate time-varying quantities of interest from Cox Proportional Hazards models} \usage{ coxsimtvc(obj, b, btvc, qi = "Relative Hazard", Xj = NULL, Xl = NULL, tfun = "linear", pow = NULL, nsim = 1000, from, to, by = 1, ci = 0.95, spin = FALSE) } \arguments{ \item{obj}{a \code{\link{coxph}} fitted model object with a time interaction.} \item{b}{the non-time interacted variable's name.} \item{btvc}{the time interacted variable's name.} \item{qi}{character string indicating what quantity of interest you would like to calculate. Can be \code{'Relative Hazard'}, \code{'First Difference'}, \code{'Hazard Ratio'}, \code{'Hazard Rate'}. Default is \code{qi = 'Relative Hazard'}. If \code{qi = 'First Difference'} or \code{qi = 'Hazard Ratio'} then you can set \code{Xj} and \code{Xl}.} \item{Xj}{numeric vector of fitted values for \code{b}. Must be the same length as \code{Xl} or \code{Xl} must be \code{NULL}.} \item{Xl}{numeric vector of fitted values for Xl. Must be the same length as \code{Xj}. Only applies if \code{qi = 'First Difference'} or \code{qi = 'Hazard Ratio'}.} \item{nsim}{the number of simulations to run per point in time. Default is \code{nsim = 1000}.} \item{tfun}{function of time that btvc was multiplied by. Default is "linear". It can also be "log" (natural log) and "power". If \code{tfun = "power"} then the pow argument needs to be specified also.} \item{pow}{if \code{tfun = "power"}, then use pow to specify what power the time interaction was raised to.} \item{from}{point in time from when to begin simulating coefficient values} \item{to}{point in time to stop simulating coefficient values.} \item{by}{time intervals by which to simulate coefficient values.} \item{ci}{the proportion of simulations to keep. The default is \code{ci = 0.95}, i.e. keep the middle 95 percent. If \code{spin = TRUE} then \code{ci} is the confidence level of the shortest probability interval. Any value from 0 through 1 may be used.} \item{spin}{logical, whether or not to keep only the shortest probability interval rather than the middle simulations.} } \value{ a \code{simtvc} object } \description{ \code{coxsimtvc} simulates time-varying relative hazards, first differences, and hazard ratios from models estimated with \code{\link{coxph}} using the multivariate normal distribution. These can be plotted with \code{\link{simGG}}. } \details{ Simulates time-varying relative hazards, first differences, and hazard ratios using parameter estimates from \code{coxph} models. Can also simulate hazard rates for multiple strata. Relative hazards are found using: \deqn{RH = e^{\beta_{1} + \beta_{2}f(t)}} where \eqn{f(t)} is the function of time. First differences are found using: \deqn{FD = (e^{(X_{j} - X_{l}) (\beta_{1} + \beta_{2}f(t))} - 1) * 100} where \eqn{X_{j}} and \eqn{X_{l}} are some values of \eqn{X} to contrast. Hazard ratios are calculated using: \deqn{FD = e^{(X_{j} - X_{l}) (\beta_{1} + \beta_{2}f(t))}} When simulating non-stratifed time-varying harzards \code{coxsimtvc} uses the point estimates for a given coefficient \eqn{\hat{\beta}_{x}} and its time interaction \eqn{\hat{\beta}_{xt}} along with the variance matrix (\eqn{\hat{V}(\hat{\beta})}) estimated from a \code{coxph} model. These are used to draw values of \eqn{\beta_{1}} and \eqn{\beta_{2}} from the multivariate normal distribution \eqn{N(\hat{\beta},\: \hat{V}(\hat{beta}))}. When simulating stratified time-varying hazard rates \eqn{H} for a given strata \eqn{k}, \code{coxsimtvc} uses: \deqn{H_{kxt} = \hat{\beta_{k0t}}\exp{\hat{\beta_{1}} + \beta_{2}f(t)}} The resulting simulation values can be plotted using \code{\link{simGG}}. } \examples{ # Load Golub & Steunenberg (2007) Data data("GolubEUPData") # Load survival package library(survival) # Create natural log time interactions Golubtvc <- function(x){ assign(paste0("l", x), tvc(GolubEUPData, b = x, tvar = "end", tfun = "log")) } GolubEUPData$Lcoop <-Golubtvc("coop") GolubEUPData$Lqmv <- Golubtvc("qmv") GolubEUPData$Lbacklog <- Golubtvc("backlog") GolubEUPData$Lcodec <- Golubtvc("codec") GolubEUPData$Lqmvpostsea <- Golubtvc("qmvpostsea") GolubEUPData$Lthatcher <- Golubtvc("thatcher") # Run Cox PH Model M1 <- coxph(Surv(begin, end, event) ~ qmv + qmvpostsea + qmvpostteu + coop + codec + eu9 + eu10 + eu12 + eu15 + thatcher + agenda + backlog + Lqmv + Lqmvpostsea + Lcoop + Lcodec + Lthatcher + Lbacklog, data = GolubEUPData, ties = "efron") # Create simtvc object for Relative Hazard Sim1 <- coxsimtvc(obj = M1, b = "qmv", btvc = "Lqmv", tfun = "log", from = 80, to = 2000, Xj = 1, by = 15, ci = 0.99) ## dontrun # Create simtvc object for First Difference # Sim2 <- coxsimtvc(obj = M1, b = "qmv", btvc = "Lqmv", # qi = "First Difference", Xj = 1, # tfun = "log", from = 80, to = 2000, # by = 15, ci = 0.95) # Create simtvc object for Hazard Ratio # Sim3 <- coxsimtvc(obj = M1, b = "backlog", btvc = "Lbacklog", # qi = "Hazard Ratio", Xj = c(191, 229), # Xl = c(0, 0), # tfun = "log", from = 80, to = 2000, # by = 15, ci = 0.5) } \references{ Golub, Jonathan, and <NAME>. 2007. ''How Time Affects EU Decision-Making.'' European Union Politics 8(4): 555-66. Licht, <NAME>. 2011. ''Change Comes with Time: Substantive Interpretation of Nonproportional Hazards in Event History Analysis.'' Political Analysis 19: 227-43. <NAME>, <NAME>, and <NAME>. 2000. ''Making the Most of Statistical Analyses: Improving Interpretation and Presentation.'' American Journal of Political Science 44(2): 347-61. Liu, Ying, <NAME>, and <NAME>. 2013. ''Simulation-Efficient Shortest Probability Intervals.'' Arvix. \url{http://arxiv.org/pdf/1302.2142v1.pdf}. } \seealso{ \code{\link{simGG}}, \code{\link{survival}}, \code{\link{strata}}, and \code{\link{coxph}} } <file_sep>\name{simGG.simlinear} \alias{simGG.simlinear} \title{Plot simulated linear time-constant quantities of interest from Cox Proportional Hazards Models} \usage{ \method{simGG}{simlinear} (obj, from = NULL, to = NULL, xlab = NULL, ylab = NULL, title = NULL, smoother = "auto", spalette = "Set1", leg.name = "", lcolour = "#2B8CBE", lsize = 2, pcolour = "#A6CEE3", psize = 1, palpha = 0.1, ...) } \arguments{ \item{obj}{a \code{simlinear} class object.} \item{xlab}{a label for the plot's x-axis.} \item{ylab}{a label of the plot's y-axis. The default uses the value of \code{qi}.} \item{from}{numeric time to start the plot from. Only relevant if \code{qi = "Hazard Rate"}.} \item{to}{numeric time to plot to. Only relevant if \code{qi = "Hazard Rate"}.} \item{title}{the plot's main title.} \item{smoother}{what type of smoothing line to use to summarize the plotted coefficient.} \item{spalette}{colour palette for use in \code{qi = "Hazard Rate"}. Default palette is \code{"Set1"}. See \code{\link{scale_colour_brewer}}.} \item{leg.name}{name of the stratified hazard rates legend. Only relevant if \code{qi = "Hazard Rate"}.} \item{lcolour}{character string colour of the smoothing line. The default is hexadecimal colour \code{lcolour = '#2B8CBE'}. Only relevant if \code{qi = "First Difference"}.} \item{lsize}{size of the smoothing line. Default is 2. See \code{\link{ggplot2}}.} \item{pcolour}{character string colour of the simulated points for relative hazards. Default is hexadecimal colour \code{pcolour = '#A6CEE3'}. Only relevant if \code{qi = "First Difference"}.} \item{psize}{size of the plotted simulation points. Default is \code{psize = 1}. See \code{\link{ggplot2}}.} \item{palpha}{point alpha (e.g. transparency). Default is \code{palpha = 0.05}. See \code{\link{ggplot2}}.} \item{...}{Additional arguments. (Currently ignored.)} } \value{ a \code{gg} \code{ggplot} class object } \description{ \code{simGG.simlinear} uses \link{ggplot2} to plot the quantities of interest from \code{simlinear} objects, including relative hazards, first differences, hazard ratios, and hazard rates. } \details{ Uses \link{ggplot2} to plot the quantities of interest from \code{simlinear} objects, including relative hazards, first differences, hazard ratios, and hazard rates. If there are multiple strata, the quantities of interest will be plotted in a grid by strata. Note: A dotted line is created at y = 1 (0 for first difference), i.e. no effect, for time-varying hazard ratio graphs. No line is created for hazard rates. } \examples{ ## dontrun # Load survival package # library(survival) # Load Carpenter (2002) data # data("CarpenterFdaData") # Estimate survival model # M1 <- coxph(Surv(acttime, censor) ~ prevgenx + lethal + # deathrt1 + acutediz + hosp01 + hhosleng + # mandiz01 + femdiz01 + peddiz01 + orphdum + # vandavg3 + wpnoavg3 + condavg3 + orderent + # stafcder, data = CarpenterFdaData) # Simulate and plot Hazard Ratios for stafcder variable # Sim1 <- coxsimLinear(M1, b = "stafcder", # qi = "Hazard Ratio", # Xj = seq(1237, 1600, by = 2), spin = TRUE) # simGG(Sim1) ## dontrun # Simulate and plot Hazard Rate for stafcder variable # Sim2 <- coxsimLinear(M1, b = "stafcder", nsim = 100, # qi = "Hazard Rate", Xj = c(1237, 1600)) # simGG(Sim2) } \references{ <NAME>. 2011. ''Change Comes with Time: Substantive Interpretation of Nonproportional Hazards in Event History Analysis.'' Political Analysis 19: 227-43. <NAME>. 2010. ''Proportionally Difficult: Testing for Nonproportional Hazards in Cox Models.'' Political Analysis 18(2): 189-205. <NAME>. 2002. ''Groups, the Media, Agency Waiting Costs, and FDA Drug Approval.'' American Journal of Political Science 46(3): 490-505. } \seealso{ \code{\link{coxsimLinear}}, \code{\link{simGG.simtvc}}, and \code{\link{ggplot2}} } <file_sep>\name{coxsimSpline} \alias{coxsimSpline} \title{Simulate quantities of interest for penalized splines from Cox Proportional Hazards models} \usage{ coxsimSpline(obj, bspline, bdata, qi = "Relative Hazard", Xj = 1, Xl = 0, nsim = 1000, ci = 0.95, spin = FALSE) } \arguments{ \item{obj}{a \code{\link{coxph}} class fitted model object with a penalized spline. These can be plotted with \code{\link{simGG}}.} \item{bspline}{a character string of the full \code{\link{pspline}} call used in \code{obj}. It should be exactly the same as how you entered it in \code{\link{coxph}}. You also need to enter a white spece before and after all equal (\code{=}) signs.} \item{bdata}{a numeric vector of splined variable's values.} \item{qi}{quantity of interest to simulate. Values can be \code{"Relative Hazard"}, \code{"First Difference"}, \code{"Hazard Ratio"}, and \code{"Hazard Rate"}. The default is \code{qi = "Relative Hazard"}. Think carefully before using \code{qi = "Hazard Rate"}. You may be creating very many simulated values which can be very computationally intensive to do. Adjust the number of simulations per fitted value with \code{nsim}.} \item{Xj}{numeric vector of fitted values for \code{b} to simulate for.} \item{Xl}{numeric vector of values to compare \code{Xj} to. Note if \code{qi = "Relative Hazard"} or \code{"Hazard Rate"} only \code{Xj} is relevant.} \item{nsim}{the number of simulations to run per value of \code{Xj}. Default is \code{nsim = 1000}.} \item{ci}{the proportion of simulations to keep. The default is \code{ci = 0.95}, i.e. keep the middle 95 percent. If \code{spin = TRUE} then \code{ci} is the confidence level of the shortest probability interval. Any value from 0 through 1 may be used.} \item{spin}{logical, whether or not to keep only the shortest probability interval rather than the middle simulations.} } \value{ a \code{simspline} object } \description{ \code{coxsimSpline} simulates quantities of interest from penalized splines using multivariate normal distributions. } \details{ Simulates relative hazards, first differences, hazard ratios, and hazard rates for penalized splines from Cox Proportional Hazards models. These can be plotted with \code{\link{simGG}}. A Cox PH model with one penalized spline is given by: \deqn{h(t|\mathbf{X}_{i})=h_{0}(t)\mathrm{e}^{g(x)}} where \eqn{g(x)} is the penalized spline function. For our post-estimation purposes \eqn{g(x)} is basically a series of linearly combined coefficients such that: \deqn{g(x) = \beta_{k_{1}}(x)_{1+} + \beta_{k_{2}}(x)_{2+} + \beta_{k_{3}}(x)_{3+} + \ldots + \beta_{k_{n}}(x)_{n+}} where \eqn{k} are the equally spaced spline knots with values inside of the range of observed \eqn{x} and \eqn{n} is the number of knots. We can again draw values of each \eqn{\beta_{k_{1}}, \ldots \beta_{k_{n}}} from the multivariate normal distribution described above. We then use these simulated coefficients to estimates quantities of interest for a range covariate values. For example, the first difference between two values \eqn{x_{j}} and \eqn{x_{l}} is: \deqn{\%\triangle h_{i}(t) = (\mathrm{e}^{g(x_{j}) - g(x_{l})} - 1) * 100} Relative hazards and hazard ratios can be calculated by extension. Currently \code{coxsimSpline} does not support simulating hazard rates form multiple stratified models. } \examples{ ## dontrun # Load Carpenter (2002) data # data("CarpenterFdaData") # Load survival package # library(survival) # Run basic model # From Keele (2010) replication data # M1 <- coxph(Surv(acttime, censor) ~ prevgenx + lethal + deathrt1 + # acutediz + hosp01 + pspline(hospdisc, df = 4) + # pspline(hhosleng, df = 4) + mandiz01 + femdiz01 + peddiz01 + # orphdum + natreg + vandavg3 + wpnoavg3 + # pspline(condavg3, df = 4) + pspline(orderent, df = 4) + # pspline(stafcder, df = 4), data = CarpenterFdaData) # Simulate Relative Hazards for orderent # Sim1 <- coxsimSpline(M1, bspline = "pspline(stafcder, df = 4)", # bdata = CarpenterFdaData$stafcder, # qi = "Hazard Ratio", # Xj = seq(1100, 1700, by = 10), # Xl = seq(1099, 1699, by = 10), spin = TRUE) ## dontrun # Simulate Hazard Rates for orderent # Sim2 <- coxsimSpline(M1, bspline = "pspline(orderent, df = 4)", # bdata = CarpenterFdaData$orderent, # qi = "Hazard Rate", # Xj = seq(2, 53, by = 3), # nsim = 100) } \references{ <NAME>, "Replication data for: Proportionally Difficult: Testing for Nonproportional Hazards In Cox Models", 2010, \url{http://hdl.handle.net/1902.1/17068} V1 [Version]. King, Gary, <NAME>, and <NAME>. 2000. ''Making the Most of Statistical Analyses: Improving Interpretation and Presentation.'' American Journal of Political Science 44(2): 347-61. Liu, Ying, <NAME>, and <NAME>. 2013. ''Simulation-Efficient Shortest Probability Intervals.'' Arvix. \url{http://arxiv.org/pdf/1302.2142v1.pdf}. } \seealso{ \code{\link{simGG}}, \code{\link{survival}}, \code{\link{strata}}, and \code{\link{coxph}} } <file_sep>#' Plot simulated linear time-constant quantities of interest from Cox Proportional Hazards Models #' #' \code{simGG.simlinear} uses \link{ggplot2} to plot the quantities of interest from \code{simlinear} objects, including relative hazards, first differences, hazard ratios, and hazard rates. #' #' @param obj a \code{simlinear} class object. #' @param xlab a label for the plot's x-axis. #' @param ylab a label of the plot's y-axis. The default uses the value of \code{qi}. #' @param from numeric time to start the plot from. Only relevant if \code{qi = "Hazard Rate"}. #' @param to numeric time to plot to. Only relevant if \code{qi = "Hazard Rate"}. #' @param title the plot's main title. #' @param smoother what type of smoothing line to use to summarize the plotted coefficient. #' @param spalette colour palette for use in \code{qi = "Hazard Rate"}. Default palette is \code{"Set1"}. See \code{\link{scale_colour_brewer}}. #' @param leg.name name of the stratified hazard rates legend. Only relevant if \code{qi = "Hazard Rate"}. #' @param lcolour character string colour of the smoothing line. The default is hexadecimal colour \code{lcolour = '#2B8CBE'}. Only relevant if \code{qi = "First Difference"}. #' @param lsize size of the smoothing line. Default is 2. See \code{\link{ggplot2}}. #' @param pcolour character string colour of the simulated points for relative hazards. Default is hexadecimal colour \code{pcolour = '#A6CEE3'}. Only relevant if \code{qi = "First Difference"}. #' @param psize size of the plotted simulation points. Default is \code{psize = 1}. See \code{\link{ggplot2}}. #' @param palpha point alpha (e.g. transparency). Default is \code{palpha = 0.05}. See \code{\link{ggplot2}}. #' @param ... Additional arguments. (Currently ignored.) #' #' @return a \code{gg} \code{ggplot} class object #' #' @examples #' #' ## dontrun #' # Load survival package #' # library(survival) #' # Load Carpenter (2002) data #' # data("CarpenterFdaData") #' #' # Estimate survival model #' # M1 <- coxph(Surv(acttime, censor) ~ prevgenx + lethal + #' # deathrt1 + acutediz + hosp01 + hhosleng + #' # mandiz01 + femdiz01 + peddiz01 + orphdum + #' # vandavg3 + wpnoavg3 + condavg3 + orderent + #' # stafcder, data = CarpenterFdaData) #' #' # Simulate and plot Hazard Ratios for stafcder variable #' # Sim1 <- coxsimLinear(M1, b = "stafcder", #' # qi = "Hazard Ratio", #' # Xj = seq(1237, 1600, by = 2), spin = TRUE) #' # simGG(Sim1) #' #' ## dontrun #' # Simulate and plot Hazard Rate for stafcder variable #' # Sim2 <- coxsimLinear(M1, b = "stafcder", nsim = 100, #' # qi = "Hazard Rate", Xj = c(1237, 1600)) #' # simGG(Sim2) #' #' @details Uses \link{ggplot2} to plot the quantities of interest from \code{simlinear} objects, including relative hazards, first differences, hazard ratios, and hazard rates. If there are multiple strata, the quantities of interest will be plotted in a grid by strata. #' Note: A dotted line is created at y = 1 (0 for first difference), i.e. no effect, for time-varying hazard ratio graphs. No line is created for hazard rates. #' #' @import ggplot2 #' @method simGG simlinear #' @S3method simGG simlinear #' #' @seealso \code{\link{coxsimLinear}}, \code{\link{simGG.simtvc}}, and \code{\link{ggplot2}} #' @references Licht, <NAME>. 2011. ''Change Comes with Time: Substantive Interpretation of Nonproportional Hazards in Event History Analysis.'' Political Analysis 19: 227-43. #' #' <NAME>. 2010. ''Proportionally Difficult: Testing for Nonproportional Hazards in Cox Models.'' Political Analysis 18(2): 189-205. #' #' <NAME>. 2002. ''Groups, the Media, Agency Waiting Costs, and FDA Drug Approval.'' American Journal of Political Science 46(3): 490-505. simGG.simlinear <- function(obj, from = NULL, to = NULL, xlab = NULL, ylab = NULL, title = NULL, smoother = "auto", spalette = "Set1", leg.name = "", lcolour = "#2B8CBE", lsize = 2, pcolour = "#A6CEE3", psize = 1, palpha = 0.1, ...) { Time <- HRate <- HRValue <- Xj <- QI <- NULL if (!inherits(obj, "simlinear")){ stop("must be a simlinear object") } # Find quantity of interest qi <- class(obj)[[2]] # Create y-axis label if (is.null(ylab)){ ylab <- paste(qi, "\n") } else { ylab <- ylab } # Subset simlinear object & create a data frame of important variables if (qi == "Hazard Rate"){ colour <- NULL if (is.null(obj$strata)){ objdf <- data.frame(obj$time, obj$QI, obj$HRValue) names(objdf) <- c("Time", "HRate", "HRValue") } else if (!is.null(obj$strata)) { objdf <- data.frame(obj$time, obj$QI, obj$strata, obj$HRValue) names(objdf) <- c("Time", "HRate", "Strata", "HRValue") } if (!is.null(from)){ objdf <- subset(objdf, Time >= from) } if (!is.null(to)){ objdf <- subset(objdf, Time <= to) } } else if (qi == "Hazard Ratio" | qi == "Relative Hazard" | qi == "First Difference"){ objdf <- data.frame(obj$Xj, obj$QI) names(objdf) <- c("Xj", "QI") } # Plot if (qi == "Hazard Rate"){ if (!is.null(obj$strata)) { ggplot(objdf, aes(x = Time, y = HRate, colour = factor(HRValue))) + geom_point(alpha = I(palpha), size = psize) + geom_smooth(method = smoother, size = lsize, se = FALSE) + facet_grid(.~ Strata) + xlab(xlab) + ylab(ylab) + scale_colour_brewer(palette = spalette, name = leg.name) + ggtitle(title) + guides(colour = guide_legend(override.aes = list(alpha = 1))) + theme_bw(base_size = 15) } else if (is.null(obj$strata)){ ggplot(objdf, aes(Time, HRate, colour = factor(HRValue))) + geom_point(shape = 21, alpha = I(palpha), size = psize) + geom_smooth(method = smoother, size = lsize, se = FALSE) + scale_colour_brewer(palette = spalette, name = leg.name) + xlab(xlab) + ylab(ylab) + ggtitle(title) + guides(colour = guide_legend(override.aes = list(alpha = 1))) + theme_bw(base_size = 15) } } else if (qi == "First Difference"){ ggplot(objdf, aes(Xj, QI)) + geom_point(shape = 21, alpha = I(palpha), size = psize, colour = pcolour) + geom_smooth(method = smoother, size = lsize, se = FALSE, color = lcolour) + geom_hline(aes(yintercept = 0), linetype = "dotted") + xlab(xlab) + ylab(ylab) + ggtitle(title) + guides(colour = guide_legend(override.aes = list(alpha = 1))) + theme_bw(base_size = 15) } else if (qi == "Hazard Ratio" | qi == "Relative Hazard"){ ggplot(objdf, aes(Xj, QI)) + geom_point(shape = 21, alpha = I(palpha), size = psize, colour = pcolour) + geom_smooth(method = smoother, size = lsize, se = FALSE, color = lcolour) + geom_hline(aes(yintercept = 1), linetype = "dotted") + xlab(xlab) + ylab(ylab) + ggtitle(title) + guides(colour = guide_legend(override.aes = list(alpha = 1))) + theme_bw(base_size = 15) } }<file_sep>#' Simulate time-varying quantities of interest from Cox Proportional Hazards models #' #' \code{coxsimtvc} simulates time-varying relative hazards, first differences, and hazard ratios from models estimated with \code{\link{coxph}} using the multivariate normal distribution. These can be plotted with \code{\link{simGG}}. #' @param obj a \code{\link{coxph}} fitted model object with a time interaction. #' @param b the non-time interacted variable's name. #' @param btvc the time interacted variable's name. #' @param qi character string indicating what quantity of interest you would like to calculate. Can be \code{'Relative Hazard'}, \code{'First Difference'}, \code{'Hazard Ratio'}, \code{'Hazard Rate'}. Default is \code{qi = 'Relative Hazard'}. If \code{qi = 'First Difference'} or \code{qi = 'Hazard Ratio'} then you can set \code{Xj} and \code{Xl}. #' @param Xj numeric vector of fitted values for \code{b}. Must be the same length as \code{Xl} or \code{Xl} must be \code{NULL}. #' @param Xl numeric vector of fitted values for Xl. Must be the same length as \code{Xj}. Only applies if \code{qi = 'First Difference'} or \code{qi = 'Hazard Ratio'}. #' @param nsim the number of simulations to run per point in time. Default is \code{nsim = 1000}. #' @param tfun function of time that btvc was multiplied by. Default is "linear". It can also be "log" (natural log) and "power". If \code{tfun = "power"} then the pow argument needs to be specified also. #' @param pow if \code{tfun = "power"}, then use pow to specify what power the time interaction was raised to. #' @param from point in time from when to begin simulating coefficient values #' @param to point in time to stop simulating coefficient values. #' @param by time intervals by which to simulate coefficient values. #' @param ci the proportion of simulations to keep. The default is \code{ci = 0.95}, i.e. keep the middle 95 percent. If \code{spin = TRUE} then \code{ci} is the confidence level of the shortest probability interval. Any value from 0 through 1 may be used. #' @param spin logical, whether or not to keep only the shortest probability interval rather than the middle simulations. #' #' @return a \code{simtvc} object #' #' @details Simulates time-varying relative hazards, first differences, and hazard ratios using parameter estimates from \code{coxph} models. Can also simulate hazard rates for multiple strata. #' #' Relative hazards are found using: #' \deqn{RH = e^{\beta_{1} + \beta_{2}f(t)}} #' where \eqn{f(t)} is the function of time. #' #' First differences are found using: #' \deqn{FD = (e^{(X_{j} - X_{l}) (\beta_{1} + \beta_{2}f(t))} - 1) * 100} #' where \eqn{X_{j}} and \eqn{X_{l}} are some values of \eqn{X} to contrast. #' #' Hazard ratios are calculated using: #' \deqn{FD = e^{(X_{j} - X_{l}) (\beta_{1} + \beta_{2}f(t))}} #' When simulating non-stratifed time-varying harzards \code{coxsimtvc} uses the point estimates for a given coefficient \eqn{\hat{\beta}_{x}} and its time interaction \eqn{\hat{\beta}_{xt}} along with the variance matrix (\eqn{\hat{V}(\hat{\beta})}) estimated from a \code{coxph} model. These are used to draw values of \eqn{\beta_{1}} and \eqn{\beta_{2}} from the multivariate normal distribution \eqn{N(\hat{\beta},\: \hat{V}(\hat{beta}))}. #' #' When simulating stratified time-varying hazard rates \eqn{H} for a given strata \eqn{k}, \code{coxsimtvc} uses: #' \deqn{H_{kxt} = \hat{\beta_{k0t}}\exp{\hat{\beta_{1}} + \beta_{2}f(t)}} #' The resulting simulation values can be plotted using \code{\link{simGG}}. #' #' @examples #' # Load Golub & Steunenberg (2007) Data #' data("GolubEUPData") #' #' # Load survival package #' library(survival) #' #' # Create natural log time interactions #' Golubtvc <- function(x){ #' assign(paste0("l", x), tvc(GolubEUPData, b = x, tvar = "end", tfun = "log")) #' } #' #' GolubEUPData$Lcoop <-Golubtvc("coop") #' GolubEUPData$Lqmv <- Golubtvc("qmv") #' GolubEUPData$Lbacklog <- Golubtvc("backlog") #' GolubEUPData$Lcodec <- Golubtvc("codec") #' GolubEUPData$Lqmvpostsea <- Golubtvc("qmvpostsea") #' GolubEUPData$Lthatcher <- Golubtvc("thatcher") #' #' # Run Cox PH Model #' M1 <- coxph(Surv(begin, end, event) ~ #' qmv + qmvpostsea + qmvpostteu + #' coop + codec + eu9 + eu10 + eu12 + #' eu15 + thatcher + agenda + backlog + #' Lqmv + Lqmvpostsea + Lcoop + Lcodec + #' Lthatcher + Lbacklog, #' data = GolubEUPData, #' ties = "efron") #' #' # Create simtvc object for Relative Hazard #' Sim1 <- coxsimtvc(obj = M1, b = "qmv", btvc = "Lqmv", #' tfun = "log", from = 80, to = 2000, #' Xj = 1, by = 15, ci = 0.99) #' #' ## dontrun #' # Create simtvc object for First Difference #' # Sim2 <- coxsimtvc(obj = M1, b = "qmv", btvc = "Lqmv", #' # qi = "First Difference", Xj = 1, #' # tfun = "log", from = 80, to = 2000, #' # by = 15, ci = 0.95) #' #' # Create simtvc object for Hazard Ratio #' # Sim3 <- coxsimtvc(obj = M1, b = "backlog", btvc = "Lbacklog", #' # qi = "Hazard Ratio", Xj = c(191, 229), #' # Xl = c(0, 0), #' # tfun = "log", from = 80, to = 2000, #' # by = 15, ci = 0.5) #' #' @seealso \code{\link{simGG}}, \code{\link{survival}}, \code{\link{strata}}, and \code{\link{coxph}} #' #' @import data.table #' @importFrom reshape2 melt #' @importFrom survival basehaz #' @importFrom MSBVAR rmultnorm #' @export #' #' @references Golub, Jonathan, and <NAME>. 2007. ''How Time Affects EU Decision-Making.'' European Union Politics 8(4): 555-66. #' #' Licht, <NAME>. 2011. ''Change Comes with Time: Substantive Interpretation of Nonproportional Hazards in Event History Analysis.'' Political Analysis 19: 227-43. #' #' King, Gary, <NAME>, and <NAME>. 2000. ''Making the Most of Statistical Analyses: Improving Interpretation and Presentation.'' American Journal of Political Science 44(2): 347-61. #' #' Liu, Ying, <NAME>, and <NAME>. 2013. ''Simulation-Efficient Shortest Probability Intervals.'' Arvix. \url{http://arxiv.org/pdf/1302.2142v1.pdf}. coxsimtvc <- function(obj, b, btvc, qi = "Relative Hazard", Xj = NULL, Xl = NULL, tfun = "linear", pow = NULL, nsim = 1000, from, to, by = 1, ci = 0.95, spin = FALSE) { QI <- NULL ############ Means Not Supported Yet for coxsimtvc ######## #### means code is a place holder for future versions ##### means <- FALSE # Ensure that qi is valid qiOpts <- c("Relative Hazard", "First Difference", "Hazard Rate", "Hazard Ratio") TestqiOpts <- qi %in% qiOpts if (!isTRUE(TestqiOpts)){ stop("Invalid qi type. qi must be 'Relative Hazard', 'First Difference', 'Hazard Rate', or 'Hazard Ratio'") } MeansMessage <- NULL if (isTRUE(means) & length(obj$coefficients) == 3){ means <- FALSE MeansMessage <- FALSE message("Note: means reset to FALSE. The model only includes the interaction variables.") } else if (isTRUE(means) & length(obj$coefficients) > 3){ MeansMessage <- TRUE } if (is.null(Xl) & qi != "Hazard Rate"){ Xl <- rep(0, length(Xj)) message("All Xl set to 0.") } else if (!is.null(Xl) & qi == "Relative Hazard") { message("All Xl set to 0.") } # Create time function tfunOpts <- c("linear", "log", "power") TestforTOpts <- tfun %in% tfunOpts if (!isTRUE(TestforTOpts)){ stop("Must specify tfun as 'linear', 'log', or 'power'") } if (tfun == "linear"){ tf <- seq(from = from, to = to, by = by) } else if (tfun == "log"){ tf <- log(seq(from = from, to = to, by = by)) } else if (tfun == "power"){ tf <- (seq(from = from, to = to, by = by))^pow } # Parameter estimates & Varance/Covariance matrix Coef <- matrix(obj$coefficients) VC <- vcov(obj) # Draw values from the multivariate normal distribution Drawn <- rmultnorm(n = nsim, mu = Coef, vmat = VC) DrawnDF <- data.frame(Drawn) dfn <- names(DrawnDF) # If all values aren't set for calculating the hazard rate if (!isTRUE(means)){ # Extract simulations for variables of interest bpos <- match(b, dfn) btvcpos <- match(btvc, dfn) Drawn <- data.frame(Drawn[, c(bpos, btvcpos)]) Drawn$ID <- 1:nsim # Multiply time function with btvc TVSim <- outer(Drawn[,2], tf) TVSim <- data.frame(melt(TVSim)) names(TVSim) <- c("ID", "time", "TVC") time <- 1:length(tf) TempDF <- data.frame(time, tf) TVSim <- merge(TVSim, TempDF) # Combine with non TVC version of the variable TVSim <- merge(Drawn, TVSim, by = "ID") TVSim$CombCoef <- TVSim[[2]] + TVSim$TVC # Find quantity of interest if (qi == "Relative Hazard"){ Xs <- data.frame(Xj) names(Xs) <- c("Xj") Xs$Comparison <- paste(Xs[, 1]) Simb <- merge(TVSim, Xs) Simb$QI <- exp(Simb$CombCoef * Simb$Xj) } else if (qi == "First Difference"){ if (length(Xj) != length(Xl)){ stop("Xj and Xl must be the same length.") } else { TVSim$QI <- exp(TVSim$CombCoef) Xs <- data.frame(Xj, Xl) Xs$Comparison <- paste(Xs[, 1], "vs.", Xs[, 2]) Simb <- merge(TVSim, Xs) Simb$QI <- (exp((Simb$Xj - Simb$Xl) * Simb$CombCoef) - 1) * 100 } } else if (qi == "Hazard Ratio"){ if (length(Xj) != length(Xl)){ stop("Xj and Xl must be the same length.") } else { Xs <- data.frame(Xj, Xl) Xs$Comparison <- paste(Xs[, 1], "vs.", Xs[, 2]) Simb <- merge(TVSim, Xs) Simb$QI <- exp((Simb$Xj - Simb$Xl) * Simb$CombCoef) } } else if (qi == "Hazard Rate"){ Xl <- NULL message("Xl is ignored.") if (isTRUE(MeansMessage)){ message("All variables values other than b are fitted at 0.") } Xs <- data.frame(Xj) Xs$HRValue <- paste(Xs[, 1]) Simb <- merge(TVSim, Xs) Simb$HR <- exp(Simb$Xj * Simb$CombCoef) bfit <- basehaz(obj) bfit$FakeID <- 1 Simb$FakeID <- 1 bfitDT <- data.table(bfit, key = "FakeID", allow.cartesian = TRUE) SimbDT <- data.table(Simb, key = "FakeID", allow.cartesian = TRUE) SimbCombDT <- SimbDT[bfitDT, allow.cartesian = TRUE] Simb <- data.frame(SimbCombDT) Simb$QI <- Simb$hazard * Simb$HR } } # If the user wants to calculate Hazard Rates using means for fitting all covariates other than b. else if (isTRUE(means)){ Xl <- NULL message("Xl ignored") # Set all values of b at means for data used in the analysis NotB <- setdiff(names(obj$means), b) MeanValues <- data.frame(obj$means) FittedMeans <- function(Z){ ID <- 1:nsim Temp <- data.frame(ID) for (i in Z){ BarValue <- MeanValues[i, ] DrawnCoef <- DrawnDF[, i] FittedCoef <- outer(DrawnCoef, BarValue) FCMolten <- data.frame(melt(FittedCoef)) Temp <- cbind(Temp, FCMolten[,3]) } Names <- c("ID", Z) names(Temp) <- Names Temp <- Temp[, -1] return(Temp) } FittedComb <- data.frame(FittedMeans(NotB)) ExpandFC <- do.call(rbind, rep(list(FittedComb), length(Xj))) # Set fitted values for Xj bpos <- match(b, dfn) Simb <- data.frame(DrawnDF[, bpos]) Xs <- data.frame(Xj) Xs$HRValue <- paste(Xs[, 1]) Simb <- merge(Simb, Xs) Simb$CombB <- Simb[, 1] * Simb[, 2] Simb <- Simb[, 2:4] Simb <- cbind(Simb, ExpandFC) Simb$Sum <- rowSums(Simb[, c(-1, -2)]) Simb$HR <- exp(Simb$Sum) Simb <- Simb[, c("HRValue", "HR", "Xj")] bfit <- basehaz(obj) bfit$FakeID <- 1 Simb$FakeID <- 1 bfitDT <- data.table(bfit, key = "FakeID", allow.cartesian = TRUE) SimbDT <- data.table(Simb, key = "FakeID", allow.cartesian = TRUE) SimbCombDT <- SimbDT[bfitDT, allow.cartesian = TRUE] Simb <- data.frame(SimbCombDT) Simb$QI <- Simb$hazard * Simb$HR } # Drop simulations outside of 'confidence bounds' SubVar <- c("time", "Xj") SimbPerc <- IntervalConstrict(Simb = Simb, SubVar = SubVar, qi = qi, QI = QI, spin = spin, ci = ci) # Create real time variable if (tfun == "linear"){ SimbPerc$RealTime <- SimbPerc$tf } else if (tfun == "log"){ SimbPerc$RealTime <- exp(SimbPerc$tf) } else if (tfun == "power"){ SimbPerc$RealTime <- SimbPerc$tf^(1/pow) } # Final clean up class(SimbPerc) <- c("simtvc", qi) SimbPerc } <file_sep>#' Plot simulated linear multiplicative interactions from Cox Proportional Hazards Models #' #' \code{simGG.siminteract} uses \link{ggplot2} to plot the quantities of interest from \code{siminteract} objects, including marginal effects, first differences, hazard ratios, and hazard rates. #' #' @param obj a \code{siminteract} class object #' @param xlab a label for the plot's x-axis. #' @param ylab a label of the plot's y-axis. The default uses the value of \code{qi}. #' @param from numeric time to start the plot from. Only relevant if \code{qi = "Hazard Rate"}. #' @param to numeric time to plot to. Only relevant if \code{qi = "Hazard Rate"}. #' @param title the plot's main title. #' @param smoother what type of smoothing line to use to summarize the plotted coefficient. #' @param spalette colour palette. Not relevant for \code{qi = "Marginal Effect"}. Default palette is \code{"Set1"}. See \code{\link{scale_colour_brewer}}. #' @param leg.name name of the stratified hazard rates legend. Only relevant if \code{qi = "Hazard Rate"}. #' @param lcolour character string colour of the smoothing line. The default is hexadecimal colour \code{lcolour = '#2B8CBE'}. Only relevant if \code{qi = "Marginal Effect"}. #' @param lsize size of the smoothing line. Default is 2. See \code{\link{ggplot2}}. #' @param pcolour character string colour of the simulated points for relative hazards. Default is hexadecimal colour \code{pcolour = '#A6CEE3'}. Only relevant if \code{qi = "Marginal Effect"}. #' @param psize size of the plotted simulation points. Default is \code{psize = 1}. See \code{\link{ggplot2}}. #' @param palpha point alpha (e.g. transparency). Default is \code{palpha = 0.05}. See \code{\link{ggplot2}}. #' @param ... Additional arguments. (Currently ignored.) #' #' @return a \code{gg} \code{ggplot} class object #' #' @examples #' # Load Carpenter (2002) data #' data("CarpenterFdaData") #' #' # Load survival package #' library(survival) #' #' # Run basic model #' M1 <- coxph(Surv(acttime, censor) ~ lethal*prevgenx, data = CarpenterFdaData) #' #' # Simulate Marginal Effect of lethal for multiple values of prevgenx #' Sim1 <- coxsimInteract(M1, b1 = "lethal", b2 = "prevgenx", X2 = seq(2, 115, by = 2)) #' # Change the order of the covariates to make a more easily #' # interpretable hazard ratio graph. #' M2 <- coxph(Surv(acttime, censor) ~ prevgenx*lethal, data = CarpenterFdaData) #' #' ## dontrun #' # Simulate Hazard Ratio of lethal for multiple values of prevgenx #' # Sim2 <- coxsimInteract(M2, b1 = "prevgenx", b2 = "lethal", #' # X1 = seq(2, 115, by = 2), #' # X2 = c(0, 1), #' # qi = "Hazard Ratio", ci = 0.9) #' #' # Simulate First Difference #' # Sim3 <- coxsimInteract(M2, b1 = "prevgenx", b2 = "lethal", #' # X1 = seq(2, 115, by = 2), #' # X2 = c(0, 1), #' # qi = "First Difference", spin = TRUE) #' #' # Plot quantities of interest #' simGG(Sim1, xlab = "\nprevgenx", ylab = "Marginal Effect of lethal\n") #' # simGG(Sim2) #' # simGG(Sim3) #' #' @details Uses \link{ggplot2} to plot the quantities of interest from \code{siminteract} objects, including marginal effects, first differences, hazard ratios, and hazard rates. If there are multiple strata, the quantities of interest will be plotted in a grid by strata. #' Note: A dotted line is created at y = 1 (0 for first difference), i.e. no effect, for time-varying hazard ratio graphs. No line is created for hazard rates. #' #' #' Note: if \code{qi = "Hazard Ratio"} or \code{qi = "First Difference"} then you need to have choosen more than one fitted value for \code{X1} in \code{\link{coxsimInteract}}. #' #' @import ggplot2 #' @method simGG siminteract #' @S3method simGG siminteract #' #' @seealso \code{\link{coxsimInteract}}, \code{\link{simGG.simlinear}}, and \code{\link{ggplot2}} #' @references Brambor, Thomas, <NAME>, and <NAME>. 2006. ''Understanding Interaction Models: Improving Empirical Analyses.'' Political Analysis 14(1): 63-82. #' #' Keele, Luke. 2010. ''Proportionally Difficult: Testing for Nonproportional Hazards in Cox Models.'' Political Analysis 18(2): 189-205. #' #' Carpenter, <NAME>. 2002. ''Groups, the Media, Agency Waiting Costs, and FDA Drug Approval.'' American Journal of Political Science 46(3): 490-505. simGG.siminteract <- function(obj, from = NULL, to = NULL, xlab = NULL, ylab = NULL, title = NULL, smoother = "auto", spalette = "Set1", leg.name = "", lcolour = "#2B8CBE", lsize = 2, pcolour = "#A6CEE3", psize = 1, palpha = 0.1, ...) { Time <- QI <- HRValue <- X1 <- X2 <- NULL if (!inherits(obj, "siminteract")){ stop("must be a siminteract object") } # Find quantity of interest qi <- class(obj)[[2]] # Create y-axis label if (is.null(ylab)){ ylab <- paste(qi, "\n") } else { ylab <- ylab } # Subset siminteract object & create a data frame of important variables if (qi == "Hazard Rate"){ colour <- NULL if (is.null(obj$strata)){ objdf <- data.frame(obj$time, obj$QI, obj$HRValue) names(objdf) <- c("Time", "QI", "HRValue") } else if (!is.null(obj$strata)) { objdf <- data.frame(obj$time, obj$QI, obj$strata, obj$HRValue) names(objdf) <- c("Time", "QI", "Strata", "HRValue") } if (!is.null(from)){ objdf <- subset(objdf, Time >= from) } if (!is.null(to)){ objdf <- subset(objdf, Time <= to) } } else if (qi == "Hazard Ratio"){ colour <- NULL objdf <- data.frame(obj$X1, obj$X2, obj$QI, obj$Comparison) names(objdf) <- c("X1", "X2", "QI", "Comparison") } else if (qi == "Marginal Effect"){ spalette <- NULL objdf <- data.frame(obj$X2, obj$QI) names(objdf) <- c("X2", "QI") } else if (qi == "First Difference"){ colour <- NULL objdf <- data.frame(obj$X1, obj$X2, obj$QI) names(objdf) <- c("X1", "X2", "QI") } # Plot if (qi == "Hazard Rate"){ if (!is.null(obj$strata)) { ggplot(objdf, aes(x = Time, y = QI, colour = factor(HRValue))) + geom_point(alpha = I(palpha), size = psize) + geom_smooth(method = smoother, size = lsize, se = FALSE) + facet_grid(.~ Strata) + xlab(xlab) + ylab(ylab) + scale_colour_brewer(palette = spalette, name = leg.name) + ggtitle(title) + guides(colour = guide_legend(override.aes = list(alpha = 1))) + theme_bw(base_size = 15) } else if (is.null(obj$strata)){ ggplot(objdf, aes(Time, QI, colour = factor(HRValue))) + geom_point(shape = 21, alpha = I(palpha), size = psize) + geom_smooth(method = smoother, size = lsize, se = FALSE) + scale_colour_brewer(palette = spalette, name = leg.name) + xlab(xlab) + ylab(ylab) + ggtitle(title) + guides(colour = guide_legend(override.aes = list(alpha = 1))) + theme_bw(base_size = 15) } } else if (qi == "Marginal Effect"){ ggplot(objdf, aes(X2, QI)) + geom_point(shape = 21, alpha = I(palpha), size = psize, colour = pcolour) + geom_smooth(method = smoother, size = lsize, se = FALSE, color = lcolour) + xlab(xlab) + ylab(ylab) + ggtitle(title) + guides(colour = guide_legend(override.aes = list(alpha = 1))) + theme_bw(base_size = 15) } else if (qi == "First Difference"){ X1Unique <- objdf[!duplicated(objdf[, "X1"]), ] if (nrow(X1Unique) <= 1){ message("X1 must have more than one fitted value.") } else { ggplot(objdf, aes(X1, QI, colour = factor(X2), group = factor(X2))) + geom_point(shape = 21, alpha = I(palpha), size = psize) + geom_smooth(method = smoother, size = lsize, se = FALSE) + geom_hline(aes(yintercept = 0), linetype = "dotted") + scale_colour_brewer(palette = spalette, name = leg.name) + xlab(xlab) + ylab(ylab) + ggtitle(title) + guides(colour = guide_legend(override.aes = list(alpha = 1))) + theme_bw(base_size = 15) } } else if (qi == "Hazard Ratio"){ X1Unique <- objdf[!duplicated(objdf[, "X1"]), ] if (nrow(X1Unique) <= 1){ message("X1 must have more than one fitted value.") } else { ggplot(objdf, aes(X1, QI, colour = factor(X2), group = factor(X2))) + geom_point(shape = 21, alpha = I(palpha), size = psize) + geom_smooth(method = smoother, size = lsize, se = FALSE) + geom_hline(aes(yintercept = 1), linetype = "dotted") + scale_colour_brewer(palette = spalette, name = leg.name) + xlab(xlab) + ylab(ylab) + ggtitle(title) + guides(colour = guide_legend(override.aes = list(alpha = 1))) + theme_bw(base_size = 15) } } }<file_sep>#' Plot simulated penalised spline hazards from Cox Proportional Hazards Models #' #' \code{simGG.simspline} uses \link{ggplot2} and \link{scatter3d} to plot quantities of interest from \code{simspline} objects, including relative hazards, first differences, hazard ratios, and hazard rates. #' #' @param obj a \code{simspline} class object #' @param FacetTime a numeric vector of points in time where you would like to plot Hazard Rates in a facet grid. Only relevant if \code{qi == 'Hazard Rate'}. Note: the values of Facet Time must exactly match values of the \code{time} element of \code{obj}. #' @param xlab a label for the plot's x-axis. #' @param ylab a label of the plot's y-axis. The default uses the value of \code{qi}. #' @param zlab a label for the plot's z-axis. Only relevant if \code{qi = "Hazard Rate"} and \code{FacetTime == NULL}. #' @param from numeric time to start the plot from. Only relevant if \code{qi = "Hazard Rate"}. #' @param to numeric time to plot to. Only relevant if \code{qi = "Hazard Rate"}. #' @param title the plot's main title. #' @param smoother what type of smoothing line to use to summarize the plotted coefficient. #' @param leg.name name of the stratified hazard rates legend. Only relevant if \code{qi = "Hazard Rate"}. #' @param lcolour character string colour of the smoothing line. The default is hexadecimal colour \code{lcolour = '#2B8CBE'}. Only relevant if \code{qi = "Relative Hazard"} or \code{qi = "First Difference"}. #' @param lsize size of the smoothing line. Default is 2. See \code{\link{ggplot2}}. #' @param pcolour character string colour of the simulated points for relative hazards. Default is hexadecimal colour \code{pcolour = '#A6CEE3'}. Only relevant if \code{qi = "Relative Hazard"} or \code{qi = "First Difference"}. #' @param psize size of the plotted simulation points. Default is \code{psize = 1}. See \code{\link{ggplot2}}. #' @param palpha point alpha (e.g. transparency). Default is \code{palpha = 0.05}. See \code{\link{ggplot2}}. #' @param surface plot surface. Default is \code{surface = TRUE}. Only relevant if \code{qi == 'Relative Hazard'} and \code{FacetTime = NULL}. #' @param fit one or more of \code{"linear"}, \code{"quadratic"}, \code{"smooth"}, \code{"additive"}; to display fitted surface(s); partial matching is supported e.g., \code{c("lin", "quad")}. Only relevant if \code{qi == 'Relative Hazard'} and \code{FacetTime = NULL}. #' @param ... Additional arguments. (Currently ignored.) #' #' @return a \code{gg} \code{ggplot} class object. See \code{\link{scatter3d}} for values from \code{scatter3d} calls. #' #' @details Uses \code{ggplot2} and \code{scatter3d} to plot the quantities of interest from \code{simspline} objects, including relative hazards, first differences, hazard ratios, and hazard rates. If currently does not support hazard rates for multiple strata. #' #' It can graph hazard rates as a 3D plot using \code{\link{scatter3d}} with the dimensions: Time, Hazard Rate, and the value of \code{Xj}. You can also choose to plot hazard rates for a range of values of \code{Xj} in two dimensional plots at specific points in time. Each plot is arranged in a facet grid. #' #' Note: A dotted line is created at y = 1 (0 for first difference), i.e. no effect, for time-varying hazard ratio graphs. No line is created for hazard rates. #' #' @examples #' ## dontrun #' # Load Carpenter (2002) data #' # data("CarpenterFdaData") #' #' # Load survival package #' # library(survival) #' #' # Run basic model #' # From Keele (2010) replication data #' # M1 <- coxph(Surv(acttime, censor) ~ prevgenx + lethal + deathrt1 + #' # acutediz + hosp01 + pspline(hospdisc, df = 4) + #' # pspline(hhosleng, df = 4) + mandiz01 + femdiz01 + peddiz01 + #' # orphdum + natreg + vandavg3 + wpnoavg3 + #' # pspline(condavg3, df = 4) + pspline(orderent, df = 4) + #' # pspline(stafcder, df = 4), data = CarpenterFdaData) #' #' # Simulate Relative Hazards for orderent #' # Sim1 <- coxsimSpline(M1, bspline = "pspline(stafcder, df = 4)", #' # bdata = CarpenterFdaData$stafcder, #' # qi = "Hazard Ratio", #' # Xj = seq(1100, 1700, by = 10), #' # Xl = seq(1099, 1699, by = 10), spin = TRUE) #' #' # Simulate Hazard Rate for orderent #' # Sim2 <- coxsimSpline(M1, bspline = "pspline(orderent, df = 4)", #' # bdata = CarpenterFdaData$orderent, #' # qi = "Hazard Rate", #' # Xj = seq(1, 30, by = 2), ci = 0.9, nsim = 10) #' #' # Plot relative hazard #' # simGG(Sim1, palpha = 1) #' #' # 3D plot hazard rate #' # simGG(Sim2, zlab = "orderent", fit = "quadratic") #' #' # Create a time grid plot #' # Find all points in time where baseline hazard was found #' # unique(Sim2$time) #' #' # Round time values so they can be exactly matched with FacetTime #' # Sim2$time <- round(Sim2$time, digits = 2) #' #' # Create plot #' # simGG(Sim2, FacetTime = c(6.21, 25.68, 100.64, 202.36)) #' #' # Simulated Fitted Values of stafcder #' # Sim3 <- coxsimSpline(M1, bspline = "pspline(stafcder, df = 4)", #' # bdata = CarpenterFdaData$stafcder, #' # qi = "Hazard Ratio", #' # Xj = seq(1100, 1700, by = 10), #' # Xl = seq(1099, 1699, by = 10), ci = 0.90) #' #' # Plot simulated Hazard Ratios #' # simGG(Sim3, xlab = "\nFDA Drug Review Staff", palpha = 0.2) #' #' @seealso \code{\link{coxsimLinear}}, \code{\link{simGG.simtvc}}, \code{\link{ggplot2}}, and \code{\link{scatter3d}} #' #' #' #' #' @import ggplot2 #' @importFrom car scatter3d #' @method simGG simspline #' @S3method simGG simspline simGG.simspline <- function(obj, FacetTime = NULL, from = NULL, to = NULL, xlab = NULL, ylab = NULL, zlab = NULL, title = NULL, smoother = "auto", leg.name = "", lcolour = "#2B8CBE", lsize = 2, pcolour = "#A6CEE3", psize = 1, palpha = 0.1, surface = TRUE, fit = "linear", ...) { Time <- Xj <- QI <- NULL if (!inherits(obj, "simspline")){ stop("must be a simspline object") } # Find quantity of interest qi <- class(obj)[[2]] # Create y-axis label if (is.null(ylab)){ ylab <- paste(qi, "\n") } else { ylab <- ylab } # Subset simspline object & create a data frame of important variables if (qi == "Hazard Rate"){ spallette <- NULL if (is.null(obj$strata)){ objdf <- data.frame(obj$time, obj$QI, obj$Xj) names(objdf) <- c("Time", "QI", "Xj") } # Currently does not support strata #else if (!is.null(obj$strata)) { #objdf <- data.frame(obj$time, obj$HRate, obj$strata, obj$Xj) #names(objdf) <- c("Time", "HRate", "Strata", "Xj") #} if (!is.null(from)){ objdf <- subset(objdf, Time >= from) } if (!is.null(to)){ objdf <- subset(objdf, Time <= to) } } else if (qi == "Hazard Ratio"){ objdf <- data.frame(obj$Xj, obj$QI, obj$Comparison) names(objdf) <- c("Xj", "QI", "Comparison") } else if (qi == "Relative Hazard"){ objdf <- data.frame(obj$Xj, obj$QI) names(objdf) <- c("Xj", "QI") } else if (qi == "First Difference"){ objdf <- data.frame(obj$Xj, obj$QI, obj$Comparison) names(objdf) <- c("Xj", "QI", "Comparison") } # Plots if (qi == "Relative Hazard"){ ggplot(objdf, aes(Xj, QI)) + geom_point(shape = 21, alpha = I(palpha), size = psize, colour = pcolour) + geom_smooth(method = smoother, size = lsize, se = FALSE, color = lcolour) + geom_hline(aes(yintercept = 1), linetype = "dotted") + xlab(xlab) + ylab(ylab) + ggtitle(title) + guides(colour = guide_legend(override.aes = list(alpha = 1))) + theme_bw(base_size = 15) } else if (qi == "First Difference"){ ggplot(objdf, aes(Xj, QI)) + geom_point(shape = 21, alpha = I(palpha), size = psize, colour = pcolour) + geom_smooth(method = smoother, size = lsize, se = FALSE, color = lcolour) + geom_hline(aes(yintercept = 0), linetype = "dotted") + xlab(xlab) + ylab(ylab) + ggtitle(title) + guides(colour = guide_legend(override.aes = list(alpha = 1))) + theme_bw(base_size = 15) } else if (qi == "Hazard Ratio"){ ggplot(objdf, aes(Xj, QI)) + geom_point(shape = 21, alpha = I(palpha), size = psize, colour = pcolour) + geom_smooth(method = smoother, size = lsize, se = FALSE, color = lcolour) + geom_hline(aes(yintercept = 1), linetype = "dotted") + xlab(xlab) + ylab(ylab) + ggtitle(title) + guides(colour = guide_legend(override.aes = list(alpha = 1))) + theme_bw(base_size = 15) } else if (qi == "Hazard Rate" & is.null(FacetTime)){ with(objdf, scatter3d(x = Time, y = QI, z = Xj, xlab = xlab, ylab = ylab, zlab = zlab, surface = surface, fit = fit)) } else if (qi == "Hazard Rate" & !is.null(FacetTime)){ SubsetTime <- function(f){ Time <- NULL CombObjdf <- data.frame() for (i in f){ Temps <- objdf TempsSub <- subset(Temps, Time == i) CombObjdf <- rbind(CombObjdf, TempsSub) } CombObjdf } objdfSub <- SubsetTime(FacetTime) ggplot(objdfSub, aes(Xj, QI)) + geom_point(shape = 21, alpha = I(palpha), size = psize, colour = pcolour) + geom_smooth(method = smoother, size = lsize, se = FALSE, color = lcolour) + facet_grid(.~Time) + xlab(xlab) + ylab(ylab) + ggtitle(title) + guides(colour = guide_legend(override.aes = list(alpha = 1))) + theme_bw(base_size = 15) } }<file_sep>\name{coxsimLinear} \alias{coxsimLinear} \title{Simulate quantities of interest for linear time constant covariates from Cox Proportional Hazards models} \usage{ coxsimLinear(obj, b, qi = "Relative Hazard", Xj = NULL, Xl = NULL, means = FALSE, nsim = 1000, ci = 0.95, spin = FALSE) } \arguments{ \item{obj}{a \code{\link{coxph}} class fitted model object.} \item{b}{character string name of the coefficient you would like to simulate.} \item{qi}{quantity of interest to simulate. Values can be \code{"Relative Hazard"}, \code{"First Difference"}, \code{"Hazard Ratio"}, and \code{"Hazard Rate"}. The default is \code{qi = "Relative Hazard"}. If \code{qi = "Hazard Rate"} and the \code{coxph} model has strata, then hazard rates for each strata will also be calculated.} \item{Xj}{numeric vector of fitted values for \code{b} to simulate for.} \item{Xl}{numeric vector of values to compare \code{Xj} to. Note if \code{code = "Relative Hazard"} only \code{Xj} is relevant.} \item{means}{logical, whether or not to use the mean values to fit the hazard rate for covaraiates other than \code{b}.} \item{nsim}{the number of simulations to run per value of X. Default is \code{nsim = 1000}. Note: it does not currently support models that include polynomials created by \code{\link{I}}.} \item{ci}{the proportion of simulations to keep. The default is \code{ci = 0.95}, i.e. keep the middle 95 percent. If \code{spin = TRUE} then \code{ci} is the confidence level of the shortest probability interval. Any value from 0 through 1 may be used.} \item{spin}{logical, whether or not to keep only the shortest probability interval rather than the middle simulations.} } \value{ a \code{simlinear} object } \description{ Simulates relative hazards, first differences, hazard ratios, and hazard rates for linear time-constant covariates from Cox Proportional Hazard models. These can be plotted with \code{\link{simGG}}. } \details{ \code{coxsimLinear} simulates relative hazards, first differences, and hazard ratios for time-constant covariates from models estimated with \code{\link{coxph}} using the multivariate normal distribution. These can be plotted with \code{\link{simGG}}. } \examples{ # Load Carpenter (2002) data data("CarpenterFdaData") # Load survival package library(survival) # Run basic model M1 <- coxph(Surv(acttime, censor) ~ prevgenx + lethal + deathrt1 + acutediz + hosp01 + hhosleng + mandiz01 + femdiz01 + peddiz01 + orphdum + vandavg3 + wpnoavg3 + condavg3 + orderent + stafcder, data = CarpenterFdaData) # Simulate Hazard Ratios Sim1 <- coxsimLinear(M1, b = "stafcder", Xj = c(1237, 1600), Xl = c(1000, 1000), spin = TRUE, ci = 0.99) ## dontrun # Simulate Hazard Rates # Sim2 <- coxsimLinear(M1, b = "stafcder", # qi = "Hazard Rate", # Xj = 1237, # ci = 0.99, means = TRUE) } \references{ Licht, <NAME>. 2011. ''Change Comes with Time: Substantive Interpretation of Nonproportional Hazards in Event History Analysis.'' Political Analysis 19: 227-43. King, Gary, <NAME>, and <NAME>. 2000. ''Making the Most of Statistical Analyses: Improving Interpretation and Presentation.'' American Journal of Political Science 44(2): 347-61. Liu, Ying, <NAME>, and <NAME>. 2013. ''Simulation-Efficient Shortest Probability Intervals.'' Arvix. \url{http://arxiv.org/pdf/1302.2142v1.pdf}. } \seealso{ \code{\link{simGG}}, \code{\link{survival}}, \code{\link{strata}}, and \code{\link{coxph}} } <file_sep>\name{simGG.simpoly} \alias{simGG.simpoly} \title{Plot simulated polynomial quantities of interest from Cox Proportional Hazards Models} \usage{ \method{simGG}{simpoly} (obj, from = NULL, to = NULL, xlab = NULL, ylab = NULL, title = NULL, smoother = "auto", spalette = "Set1", leg.name = "", lcolour = "#2B8CBE", lsize = 2, pcolour = "#A6CEE3", psize = 1, palpha = 0.1, ...) } \arguments{ \item{obj}{a \code{simpoly} class object.} \item{xlab}{a label for the plot's x-axis.} \item{ylab}{a label of the plot's y-axis. The default uses the value of \code{qi}.} \item{from}{numeric time to start the plot from. Only relevant if \code{qi = "Hazard Rate"}.} \item{to}{numeric time to plot to. Only relevant if \code{qi = "Hazard Rate"}.} \item{title}{the plot's main title.} \item{smoother}{what type of smoothing line to use to summarize the plotted coefficient.} \item{spalette}{colour palette for use in \code{qi = "Hazard Rate"}. Default palette is \code{"Set1"}. See \code{\link{scale_colour_brewer}}.} \item{leg.name}{name of the stratified hazard rates legend. Only relevant if \code{qi = "Hazard Rate"}.} \item{lcolour}{character string colour of the smoothing line. The default is hexadecimal colour \code{lcolour = '#2B8CBE'}. Only relevant if \code{qi = "First Difference"}.} \item{lsize}{size of the smoothing line. Default is 2. See \code{\link{ggplot2}}.} \item{pcolour}{character string colour of the simulated points for relative hazards. Default is hexadecimal colour \code{pcolour = '#A6CEE3'}. Only relevant if \code{qi = "First Difference"}.} \item{psize}{size of the plotted simulation points. Default is \code{psize = 1}. See \code{\link{ggplot2}}.} \item{palpha}{point alpha (e.g. transparency). Default is \code{palpha = 0.05}. See \code{\link{ggplot2}}.} \item{...}{Additional arguments. (Currently ignored.)} } \value{ a \code{gg} \code{ggplot} class object } \description{ \code{simGG.simpoly} uses \link{ggplot2} to plot simulated relative quantities of interest from a \code{simpoly} class object. } \details{ Uses \link{ggplot2} to plot the quantities of interest from \code{simpoly} objects. } \examples{ # Load Carpenter (2002) data data("CarpenterFdaData") # Load survival package library(survival) # Run basic model M1 <- coxph(Surv(acttime, censor) ~ prevgenx + lethal + deathrt1 + acutediz + hosp01 + hhosleng + mandiz01 + femdiz01 + peddiz01 + orphdum + natreg + I(natreg^2) + I(natreg^3) + vandavg3 + wpnoavg3 + condavg3 + orderent + stafcder, data = CarpenterFdaData) # Simulate simpoly First Difference Sim1 <- coxsimPoly(M1, b = "natreg", qi = "First Difference", pow = 3, Xj = seq(1, 150, by = 5)) # Simulate simpoly Hazard Ratio with spin probibility interval Sim2 <- coxsimPoly(M1, b = "natreg", qi = "Hazard Ratio", pow = 3, Xj = seq(1, 150, by = 5), spin = TRUE) # Plot simulations simGG(Sim1) simGG(Sim2) } \seealso{ \code{\link{coxsimPoly}} and \code{\link{ggplot2}} } <file_sep>#' Create a time interaction variable #' #' \code{tvc} creates a time interaction variable that can be used in a coxph model (or any other model with time interactions) #' @param data a data frame #' @param b the non-time interacted variable's name #' @param tvar the time variable's name #' @param tfun function of time that btvc was multiplied by. Default is \code{tfun = "linear"}. Can also be \code{tfun = "log"} (natural log) and \code{tfun = "power"}. If \code{tfun = "power"} then the pow argument needs to be specified also. #' @param pow if \code{tfun = "power"}, then use pow to specify what power to raise the time interaction to. #' @return a vector #' @details Interacts a variable with a specified function of time. Possible functions of time include \code{'linear'}, natural \code{'log'}, and exponentiated (\code{'power'}). #' @examples #' # Load Golub & Steunenberg (2007) Data #' data("GolubEUPData") #' #' # Create natural log time interaction with the qmv variable #' GolubEUPData$Lqmv <- tvc(GolubEUPData, b = "qmv", tvar = "end", tfun = "log") #' @seealso \code{\link{simGG.simtvc}}, \code{coxsimtvc}, \code{\link{survival}}, and \code{\link{coxph}} #' @keywords utilities #' @export tvc <- function(data, b, tvar, tfun = "linear", pow = NULL) { dfn <- names(data) bpos <- match(b, dfn) tvarpos <- match(tvar, dfn) tfunOpts <- c("linear", "log", "power") TestforTOpts <- tfun %in% tfunOpts if (!isTRUE(TestforTOpts)){ stop("Must specify tfun as 'linear', 'log', or 'power'") } if (tfun == "linear"){ data[[bpos]] * data[[tvarpos]] } else if (tfun == "log"){ data[[b]] * log(data[[tvarpos]]) } else if (tfun == "power") { data[[b]] * (data[[tvarpos]])^pow } } <file_sep>\name{simGG} \alias{simGG} \title{A method for plotting simulation objects created by simPH} \usage{ simGG(obj, ...) } \arguments{ \item{obj}{an object created by one of simPH's simulation commands.} \item{...}{arguments to be passed to methods.} } \description{ A method for plotting simulation objects created by simPH } \seealso{ \code{\link{simGG.siminteract}}, \code{\link{simGG.simtvc}}, \code{\link{simGG.simlinear}}, \code{\link{simGG.simpoly}}, \code{\link{simGG.simspline}} } <file_sep>#' Simulate quantities of interest for a range of values for a polynomial nonlinear effect from Cox Proportional Hazards models #' #' \code{coxsimPoly} simulates quantities of interest for polynomial covariate effects estimated from Cox Proportional Hazards models. These can be plotted with \code{\link{simGG}}. #' @param obj a \code{\link{coxph}} class fitted model object with a polynomial coefficient. These can be plotted with \code{\link{simGG}}. #' @param b character string name of the coefficient you would like to simulate. #' @param qi quantity of interest to simulate. Values can be \code{"Relative Hazard"}, \code{"First Difference"}, \code{"Hazard Ratio"}, and \code{"Hazard Rate"}. The default is \code{qi = "Relative Hazard"}. If \code{qi = "Hazard Rate"} and the \code{coxph} model has strata, then hazard rates for each strata will also be calculated. #' @param pow numeric polynomial used in \code{coxph}. #' @param Xj numeric vector of fitted values for \code{b} to simulate for. #' @param Xl numeric vector of values to compare \code{Xj} to. If \code{NULL}, then it is authomatically set to 0. #' @param nsim the number of simulations to run per value of \code{Xj}. Default is \code{nsim = 1000}. #' @param ci the proportion of simulations to keep. The default is \code{ci = 0.95}, i.e. keep the middle 95 percent. If \code{spin = TRUE} then \code{ci} is the confidence level of the shortest probability interval. Any value from 0 through 1 may be used. #' @param spin logical, whether or not to keep only the shortest probability interval rather than the middle simulations. #' #' @return a \code{simpoly} class object. #' @details Simulates quantities of interest for polynomial covariate effects. For example if a nonlinear effect is modeled with a second order polynomial--i.e. \eqn{\beta_{1}x_{i} + \beta_{2}x_{i}^{2}}--we can once again draw \eqn{n} simulations from the multivariate normal distribution for both \eqn{\beta_{1}} and \eqn{\beta_{2}}. Then we simply calculate quantities of interest for a range of values and plot the results as before. For example, we find the first difference for a second order polynomial with: #' \deqn{\%\triangle h_{i}(t) = (\mathrm{e}^{\beta_{1}x_{j-1} + \beta_{2}x_{j-l}^{2}} - 1) * 100} #' where \eqn{x_{j-l} = x_{j} - x_{l}}. #' #' Note, you must use \code{\link{I}} to create the polynomials. #' #' @examples #' # Load Carpenter (2002) data #' data("CarpenterFdaData") #' #' # Load survival package #' library(survival) #' #' # Run basic model #' M1 <- coxph(Surv(acttime, censor) ~ prevgenx + lethal + deathrt1 + acutediz + #' hosp01 + hhosleng + mandiz01 + femdiz01 + peddiz01 + orphdum + #' natreg + I(natreg^2) + I(natreg^3) + vandavg3 + wpnoavg3 + #' condavg3 + orderent + stafcder, data = CarpenterFdaData) #' #' # Simulate simpoly First Difference #' Sim1 <- coxsimPoly(M1, b = "natreg", qi = "First Difference", #' pow = 3, Xj = seq(1, 150, by = 5)) #' #' # Simulate simpoly Hazard Ratio with spin probibility interval #' Sim2 <- coxsimPoly(M1, b = "natreg", qi = "Hazard Ratio", #' pow = 3, Xj = seq(1, 150, by = 5), spin = TRUE) #' #' @references Keele, Luke. 2010. ''Proportionally Difficult: Testing for Nonproportional Hazards in Cox Models.'' Political Analysis 18(2): 189-205. #' #' Carpenter, <NAME>. 2002. ''Groups, the Media, Agency Waiting Costs, and FDA Drug Approval.'' American Journal of Political Science 46(3): 490-505. #' #' King, Gary, <NAME>, and <NAME>. 2000. ''Making the Most of Statistical Analyses: Improving Interpretation and Presentation.'' American Journal of Political Science 44(2): 347-61. #' #' Liu, Ying, <NAME>, and <NAME>. 2013. ''Simulation-Efficient Shortest Probability Intervals.'' Arvix. \url{http://arxiv.org/pdf/1302.2142v1.pdf}. #' #' @seealso \code{\link{simGG}}, \code{\link{survival}}, \code{\link{strata}}, and \code{\link{coxph}} #' @importFrom reshape2 melt #' @importFrom MSBVAR rmultnorm #' @importFrom survival basehaz #' @importFrom plyr rename #' @export coxsimPoly <- function(obj, b, qi = "Relative Hazard", pow = 2, Xj = NULL, Xl = NULL, nsim = 1000, ci = 0.95, spin = FALSE) { QI <- NULL # Ensure that qi is valid qiOpts <- c("Relative Hazard", "First Difference", "Hazard Rate", "Hazard Ratio") TestqiOpts <- qi %in% qiOpts if (!isTRUE(TestqiOpts)){ stop("Invalid qi type. qi must be 'Relative Hazard', 'Hazard Rate', 'First Difference', or 'Hazard Ratio'") } # Find X_{jl} if (length(Xj) != length(Xl) & !is.null(Xl)){ stop("Xj and Xl must be the same length.") } if (is.null(Xl) & qi != "Hazard Rate") { message("All Xl set at 0.") Xjl <- Xj } else if (!is.null(Xl) & qi == "Relative Hazard") { message("All Xl set to 0.") Xjl <- Xl } else { Xbound <- cbind(Xj, Xl) Xjl <- Xbound[, 1] - Xbound[, 2] } # Parameter estimates & Variance/Covariance matrix Coef <- matrix(obj$coefficients) VC <- vcov(obj) # Draw covariate estimates from the multivariate normal distribution Drawn <- rmultnorm(n = nsim, mu = Coef, vmat = VC) DrawnDF <- data.frame(Drawn) dfn <- names(DrawnDF) # Subset data frame to only include polynomial constitutive terms. bpos <- match(b, dfn) NamesLoc <- function(p){ Temp <- paste0("I.", b, ".", p, ".") match(Temp, dfn) } pows <- as.numeric(2:pow) NamePow <- sapply(pows, NamesLoc, simplify = TRUE) NamePow <- c(bpos, NamePow) Drawn <- data.frame(Drawn[, NamePow]) VNames <- names(Drawn) powFull <- as.numeric(1:pow) # Function to Multiply covariates by polynomials Fitted <- function(VN, x, p){ Temp <- outer(Drawn[, VN], x^p) TempDF <- data.frame(melt(Temp)) TempDF <- TempDF[, "value"] TempDF } Simb <- data.frame() for (i in Xjl){ TempComb <- mapply(Fitted, VN = VNames, x = i, p = powFull) TempComb <- data.frame(TempComb) TempComb$Xjl <- i TempComb$ID <- 1:nsim Simb <- rbind(Simb, TempComb) } # Create combined quantities of interest if (qi == "Relative Hazard"){ Simb$QI <- exp(rowSums(Simb[, VNames])) } else if (qi == "Hazard Ratio"){ Simb$QI <- exp(rowSums(Simb[, VNames])) } else if (qi == "First Difference"){ Simb$QI <- (exp(rowSums(Simb[, VNames])) - 1) * 100 } else if (qi == "Hazard Rate"){ Simb$HR <- exp(rowSums(Simb[, VNames])) bfit <- basehaz(obj) bfit$FakeID <- 1 Simb$FakeID <- 1 bfitDT <- data.table(bfit, key = "FakeID", allow.cartesian = TRUE) SimbDT <- data.table(Simb, key = "FakeID", allow.cartesian = TRUE) SimbCombDT <- SimbDT[bfitDT, allow.cartesian=TRUE] Simb <- data.frame(SimbCombDT) Simb$QI <- Simb$hazard * Simb$HR Simb <- Simb[, -1] } # Drop simulations outside of 'confidence bounds' if (qi != "Hazard Rate"){ SubVar <- "Xjl" } else if (qi == "Hazard Rate"){ Simb <- rename(Simb, replace = c("Xjl" = "HRValue")) SubVar <- c("time", "HRValue") } SimbPerc <- IntervalConstrict(Simb = Simb, SubVar = SubVar, qi = qi, QI = QI, spin = spin, ci = ci) # Clean up class(SimbPerc) <- c("simpoly", qi) SimbPerc }<file_sep>#' Constrict simulations to a defined interval #' #' \code{IntervalConstrict} is an internal function to constrict a set of simulations to user defined interval. #' #' @param Simb character string naming the data frame with the simulations. #' @param SubVar character vector the variable names to subset the simulations by. #' @param qi character vector naming the type of quantity of interest. #' @param QI character string labeling the quantitiy of interest values. #' @param spin logical for whether or not to use the shortest probability interval or the central interval. #' @param ci numeric confidence interval measure. #' #' @importFrom plyr ddply mutate #' @keywords internals #' @noRd IntervalConstrict <- function(Simb = Simb, SubVar = SubVar, qi = qi, QI = QI, spin = FALSE, ci = 0.95) { Lower <- Upper <- NULL if (qi == "Relative Hazard" |qi == "Hazard Ratio" | qi == "Hazard Ratio"){ lb <- 0 } else if (qi == "First Difference"){ lb <- -100 } else if (qi == "Marginal Effect"){ lb <- -Inf } if (!isTRUE(spin)) { Bottom <- (1 - ci)/2 Top <- 1 - Bottom SimbPerc <- eval(parse(text = paste0("ddply(Simb, SubVar, mutate, Lower = QI < quantile(QI,", Bottom, "))"))) SimbPerc <- eval(parse(text = paste0("ddply(SimbPerc, SubVar, mutate, Upper = QI > quantile(QI,", Top, "))" ))) } # Drop simulations outside of the shortest probability interval else if (isTRUE(spin)) { SimbPerc <- eval(parse(text = paste0("ddply(Simb, SubVar, mutate, Lower = QI < simPH:::SpinBounds(QI, conf = ", ci, ", lb = ", lb, ", LowUp = 1))" ))) SimbPerc <- eval(parse(text = paste0("ddply(SimbPerc, SubVar, mutate, Upper = QI > simPH:::SpinBounds(QI, conf = ", ci, ", lb = ", lb, ", LowUp = 2))" ))) } SimbPerc <- subset(SimbPerc, Lower == FALSE & Upper == FALSE) return(SimbPerc) }<file_sep>\name{simGG.simtvc} \alias{simGG.simtvc} \title{Plot simulated time-varying hazard ratios or stratified time-varying hazard rates from Cox Proportional Hazards Models} \usage{ \method{simGG}{simtvc} (obj, from = NULL, to = NULL, xlab = NULL, ylab = NULL, title = NULL, smoother = "auto", spalette = "Set1", leg.name = "", lcolour = "#2B8CBE", lsize = 2, pcolour = "#A6CEE3", psize = 1, palpha = 0.1, ...) } \arguments{ \item{obj}{a \code{simtvc} class object} \item{from}{numeric time to start the plot from.} \item{to}{numeric time to plot to.} \item{xlab}{a label for the plot's x-axis.} \item{ylab}{a label of the plot's y-axis. The default uses the value of \code{qi}.} \item{title}{the plot's main title.} \item{smoother}{what type of smoothing line to use to summarize the plotted coefficient.} \item{spalette}{colour palette for use in \code{qi = "Hazard Rate"}. Default palette is \code{"Set1"}. See \code{\link{scale_colour_brewer}}.} \item{leg.name}{name of the stratified hazard rates legend. Only relevant if \code{qi = "Hazard Rate"}.} \item{lcolour}{character string colour of the smoothing line. The default is hexadecimal colour \code{lcolour = '#2B8CBE'}. Only relevant if \code{qi = "Relative Hazard"} or \code{qi = "First Difference"}.} \item{lsize}{size of the smoothing line. Default is 2. See \code{\link{ggplot2}}.} \item{pcolour}{character string colour of the simulated points for relative hazards. Default is hexadecimal colour \code{pcolour = '#A6CEE3'}. Only relevant if \code{qi = "Relative Hazard"} or \code{qi = "First Difference"}.} \item{psize}{size of the plotted simulation points. Default is \code{psize = 1}. See \code{\link{ggplot2}}.} \item{palpha}{point alpha (e.g. transparency). Default is \code{palpha = 0.05}. See \code{\link{ggplot2}}.} \item{...}{Additional arguments. (Currently ignored.)} } \value{ a \code{gg} \code{ggplot} class object } \description{ \code{simGG.simtvc} uses \link{ggplot2} to plot the simulated hazards from a \code{simtvc} class object created by \code{\link{coxsimtvc}} using \link{ggplot2}. } \details{ Plots either a time varying hazard ratio or the hazard rates for multiple strata. Currently the strata legend labels need to be changed manually (see \code{\link{revalue}} in the \link{plyr} package) in the \code{simtvc} object with the \code{strata} component. Also, currently the x-axis tick marks and break labels must be adjusted manually for non-linear functions of time. Note: A dotted line is created at y = 1 (0 for first difference), i.e. no effect, for time-varying hazard ratio graphs. No line is created for hazard rates. } \examples{ ## dontrun # Load Golub & Steunenberg (2007) Data # data("GolubEUPData") # Load survival package # library(survival) # Create natural log time interactions #Golubtvc <- function(x){ # assign(paste0("l", x), tvc(GolubEUPData, b = x, tvar = "end", tfun = "log")) # } # GolubEUPData$Lcoop <-Golubtvc("coop") # GolubEUPData$Lqmv <- Golubtvc("qmv") # GolubEUPData$Lbacklog <- Golubtvc("backlog") # GolubEUPData$Lcodec <- Golubtvc("codec") # GolubEUPData$Lqmvpostsea <- Golubtvc("qmvpostsea") # GolubEUPData$Lthatcher <- Golubtvc("thatcher") # Run Cox PH Model # M1 <- coxph(Surv(begin, end, event) ~ # qmv + qmvpostsea + qmvpostteu + # coop + codec + eu9 + eu10 + eu12 + # eu15 + thatcher + agenda + backlog + # Lqmv + Lqmvpostsea + Lcoop + Lcodec + # Lthatcher + Lbacklog, # data = GolubEUPData, # ties = "efron") # Create simtvc object for Relative Hazard # Sim1 <- coxsimtvc(obj = M1, b = "qmv", btvc = "Lqmv", # tfun = "log", from = 80, to = 2000, # Xj = 1, by = 15, ci = 0.99) # Create simtvc object for First Difference # Sim2 <- coxsimtvc(obj = M1, b = "qmv", btvc = "Lqmv", # qi = "First Difference", Xj = 1, # tfun = "log", from = 80, to = 2000, # by = 15, ci = 0.95) # Create simtvc object for Hazard Ratio # Sim3 <- coxsimtvc(obj = M1, b = "backlog", btvc = "Lbacklog", # qi = "Hazard Ratio", Xj = c(191, 229), # Xl = c(0, 0), # tfun = "log", from = 80, to = 2000, # by = 15, ci = 0.99) # Create plots # simGG(Sim1) # simGG(Sim2) # simGG(Sim3, leg.name = "Comparision", from = 1200) } \references{ Licht, <NAME>. 2011. ''Change Comes with Time: Substantive Interpretation of Nonproportional Hazards in Event History Analysis.'' Political Analysis 19: 227-43. } <file_sep>#' Simulate quantities of interest for linear multiplicative interactions from Cox Proportional Hazards models #' #' \code{coxsimInteract} simulates quantities of interest for linear multiplicative interactions using multivariate normal distributions. These can be plotted with \code{\link{simGG}}. #' @param obj a \code{\link{coxph}} class fitted model object with a linear multiplicative interaction. #' @param b1 character string of the first constitutive variable's name. Note \code{b1} and \code{b2} must be entered in the order in which they are entered into the \code{coxph} model. #' @param b2 character string of the second constitutive variable's name. #' @param qi quantity of interest to simulate. Values can be \code{"Marginal Effect"}, \code{"First Difference"}, \code{"Hazard Ratio"}, and \code{"Hazard Rate"}. The default is \code{qi = "Hazard Ratio"}. If \code{qi = "Hazard Rate"} and the \code{coxph} model has strata, then hazard rates for each strata will also be calculated. #' @param X1 numeric vector of fitted values of \code{b1} to simulate for. If \code{qi = "Marginal Effect"} then only \code{X2} can be set. If you want to plot the results, \code{X1} should have more than one value. #' @param X2 numeric vector of fitted values of \code{b2} to simulate for. #' @param means logical, whether or not to use the mean values to fit the hazard rate for covaraiates other than \code{b1} \code{b2} and \code{b1*b2}. Note: it does not currently support models that include polynomials created by \code{\link{I}}. #' @param nsim the number of simulations to run per value of X. Default is \code{nsim = 1000}. #' @param ci the proportion of middle simulations to keep. The default is \code{ci = 0.95}, i.e. keep the middle 95 percent. If \code{spin = TRUE} then \code{ci} is the confidence level of the shortest probability interval. Any value from 0 through 1 may be used. #' @param spin logical, whether or not to keep only the shortest probability interval rather than the middle simulations. #' #' @details Simulates marginal effects, first differences, hazard ratios, and hazard rates for linear multiplicative interactions. #' Marginal effects are calculated as in Brambor et al. (2006) with the addition that we take the exponent, so that it resembles a hazard ratio. For an interaction between variables \eqn{X} and \eqn{Z} then the marginal effect for \eqn{X} is: #' \deqn{ME_{X} = exp(\beta_{X} + \beta_{XZ}Z).} #' #' Note that for First Differences the comparison is not between two values of the same variable but two values of the constitute variable and 0. #' #' @examples #' # Load Carpenter (2002) data #' data("CarpenterFdaData") #' #' # Load survival package #' library(survival) #' #' # Run basic model #' M1 <- coxph(Surv(acttime, censor) ~ lethal*prevgenx, data = CarpenterFdaData) #' #' # Simulate Marginal Effect of lethal for multiple values of prevgenx #' Sim1 <- coxsimInteract(M1, b1 = "lethal", b2 = "prevgenx", #' X2 = seq(2, 115, by = 2), spin = TRUE) #' #' ## dontrun #' # Change the order of the covariates to make a more easily #' # interpretable relative hazard graph. #' # M2 <- coxph(Surv(acttime, censor) ~ prevgenx*lethal + #' # orphdum, #' # data = CarpenterFdaData) #' #' # Simulate Hazard Ratio of lethal for multiple values of prevgenx #' # Sim2 <- coxsimInteract(M2, b1 = "prevgenx", b2 = "lethal", #' # X1 = seq(2, 115, by = 2), #' # X2 = c(0, 1), #' # qi = "Hazard Ratio", ci = 0.9) #' #' # Simulate First Difference #' # Sim3 <- coxsimInteract(M2, b1 = "prevgenx", b2 = "lethal", #' # X1 = seq(2, 115, by = 2), #' # X2 = c(0, 1), #' # qi = "First Difference", spin = TRUE) #' #' # Simulate Hazard Rate #' # Sim4 <- coxsimInteract(M2, b1 = "prevgenx", b2 = "lethal", #' # X1 = c(90), X2 = c(1), qi = "Hazard Rate", #' # means = TRUE) #' #' #' @references Brambor, Thomas, <NAME>, and <NAME>. 2006. ''Understanding Interaction Models: Improving Empirical Analyses.'' Political Analysis 14(1): 63-82. #' #' King, Gary, <NAME>, and <NAME>. 2000. ''Making the Most of Statistical Analyses: Improving Interpretation and Presentation.'' American Journal of Political Science 44(2): 347-61. #' #' Liu, Ying, <NAME>, and <NAME>. 2013. ''Simulation-Efficient Shortest Probability Intervals.'' Arvix. \url{http://arxiv.org/pdf/1302.2142v1.pdf}. #' #' @seealso \code{\link{simGG}}, \code{\link{survival}}, \code{\link{strata}}, and \code{\link{coxph}}, #' @return a \code{siminteract} class object #' @import data.table #' @importFrom reshape2 melt #' @importFrom plyr ddply mutate #' @importFrom survival basehaz #' @importFrom MSBVAR rmultnorm #' @export coxsimInteract <- function(obj, b1, b2, qi = "Marginal Effect", X1 = NULL, X2 = NULL, means = FALSE, nsim = 1000, ci = 0.95, spin = FALSE) { QI <- NULL if (qi != "Hazard Rate" & isTRUE(means)){ stop("means can only be TRUE when qi = 'Hazard Rate'.") } # Ensure that qi is valid qiOpts <- c("Marginal Effect", "First Difference", "Hazard Ratio", "Hazard Rate") TestqiOpts <- qi %in% qiOpts if (!isTRUE(TestqiOpts)){ stop("Invalid qi type. qi must be 'Marginal Effect', 'First Difference', 'Hazard Ratio', or 'Hazard Rate'") } MeansMessage <- NULL if (isTRUE(means) & length(obj$coefficients) == 3){ means <- FALSE MeansMessage <- FALSE message("Note: means reset to FALSE. The model only includes the interaction variables.") } else if (isTRUE(means) & length(obj$coefficients) > 3){ MeansMessage <- TRUE } # Parameter estimates & Variance/Covariance matrix Coef <- matrix(obj$coefficients) VC <- vcov(obj) # Draw covariate estimates from the multivariate normal distribution Drawn <- rmultnorm(n = nsim, mu = Coef, vmat = VC) DrawnDF <- data.frame(Drawn) dfn <- names(DrawnDF) bs <- c(b1, b2) bpos <- match(bs, dfn) binter <- paste0(bs[[1]], ".", bs[[2]]) binter <- match(binter, dfn) NamesInt <- c(bpos, binter) # If all values aren't set for calculating the hazard rate if (!isTRUE(means)){ # Subset data frame to only include interaction constitutive terms and Simb <- data.frame(Drawn[, NamesInt]) # Find quantity of interest if (qi == "Marginal Effect"){ if (!is.null(X1)){ stop("For Marginal Effects only X2 should be specified.") } else{ X2df <- data.frame(X2) names(X2df) <- c("X2") Simb <- merge(Simb, X2df) Simb$QI <- exp(Simb[, 1] + (Simb[, 3] * Simb[, 4])) } } else if (qi == "First Difference"){ if (is.null(X1) | is.null(X2)){ stop("For First Differences both X1 and X2 should be specified.") } else{ Xs <- merge(X1, X2) names(Xs) <- c("X1", "X2") Xs$Comparison <- paste0(Xs[, 1], ", ", Xs[, 2]) Simb <- merge(Simb, Xs) Simb$QI <- (exp((Simb$X1 * Simb[, 1]) + (Simb$X2 * Simb[, 2]) + (Simb$X1 * Simb$X2 * Simb[, 3]) - 1) * 100) } } else if (qi == "Hazard Ratio"){ if (is.null(X1) | is.null(X2)){ stop("For Hazard Ratios both X1 and X2 should be specified.") } else { Xs <- merge(X1, X2) names(Xs) <- c("X1", "X2") Xs$Comparison <- paste0(Xs[, 1], ", ", Xs[, 2]) Simb <- merge(Simb, Xs) Simb$QI <- (exp((Simb$X1 * Simb[, 1]) + (Simb$X2 * Simb[, 2]) + (Simb$X1 * Simb$X2 * Simb[, 3]))) } } else if (qi == "Hazard Rate"){ if (is.null(X1) | is.null(X2)){ stop("For Hazard Rates, both X1 and X2 should be specified.") } if (isTRUE(MeansMessage)){ message("All variables' values other than b1, b2, and b1*b2 are fitted at 0.") } Xs <- data.frame(X1, X2) Xs$HRValue <- paste0(Xs$X1, ", ", Xs$X2) Simb <- merge(Simb, Xs) Simb$HR <- exp((Simb$X1 * Simb[, 1]) + (Simb$X2 * Simb[, 2]) + (Simb$X1 * Simb$X2 * Simb[, 3])) bfit <- basehaz(obj) bfit$FakeID <- 1 Simb$FakeID <- 1 bfitDT <- data.table(bfit, key = "FakeID", allow.cartesian = TRUE) SimbDT <- data.table(Simb, key = "FakeID", allow.cartesian = TRUE) SimbCombDT <- SimbDT[bfitDT, allow.cartesian=TRUE] Simb <- data.frame(SimbCombDT) Simb$QI <- Simb$hazard * Simb$HR Simb <- Simb[, -1] } } # If the user wants to calculate Hazard Rates using means for fitting all covariates other than b. else if (isTRUE(means)){ if (is.null(X1) | is.null(X2)){ stop("For Hazard Rates, both X1 and X2 should be specified.") } if (length(X1) != 1 | length(X2) != 1){ stop("For coxsimInteract only one value of X1 and one value of X2 can be specified.") } Xs <- data.frame(X1, X2) Xs$HRValue <- paste0(Xs$X1, ", ", Xs$X2) # Set all values of b at means for data used in the analysis NotB <- setdiff(names(DrawnDF), c(b1, b2, binter)) MeanValues <- data.frame(obj$means) FittedMeans <- function(Z){ ID <- 1:nsim Temp <- data.frame(ID) for (i in Z){ BarValue <- MeanValues[i, ] DrawnCoef <- DrawnDF[, i] FittedCoef <- outer(DrawnCoef, BarValue) FCMolten <- data.frame(melt(FittedCoef)) Temp <- cbind(Temp, FCMolten[,3]) } Names <- c("ID", Z) names(Temp) <- Names Temp <- Temp[, -1] return(Temp) } FittedComb <- data.frame(FittedMeans(NotB)) ExpandFC <- do.call(rbind, rep(list(FittedComb), nrow(Xs))) # Set fitted values for X1 and X2 Simb <- data.frame(DrawnDF[, NamesInt]) Simb <- merge(Simb, Xs) Simb$PreHR <- (Simb$X1 * Simb[, 1]) + (Simb$X2 * Simb[, 2]) + (Simb$X1 * Simb$X2 * Simb[, 3]) Simb <- cbind(Simb, ExpandFC) Simb$Sum <- rowSums(Simb[, c(7, 8)]) Simb$HR <- exp(Simb$Sum) Simb <- Simb[, c("HRValue", "HR")] bfit <- basehaz(obj) bfit$FakeID <- 1 Simb$FakeID <- 1 bfitDT <- data.table(bfit, key = "FakeID", allow.cartesian = TRUE) SimbDT <- data.table(Simb, key = "FakeID", allow.cartesian = TRUE) SimbCombDT <- SimbDT[bfitDT, allow.cartesian = TRUE] Simb <- data.frame(SimbCombDT) Simb$QI <- Simb$hazard * Simb$HR } # Drop simulations outside of 'confidence bounds' if (qi == "First Difference" | qi == "Hazard Ratio"){ SubVar <- "X1" } else if (qi == "Marginal Effect"){ SubVar <- "X2" } else if (qi == "Hazard Rate"){ SubVar <- "time" } # Drop simulations outside of the middle SimbPerc <- IntervalConstrict(Simb = Simb, SubVar = SubVar, qi = qi, QI = QI, spin = spin, ci = ci) # Final clean up class(SimbPerc) <- c("siminteract", qi) SimbPerc }<file_sep>#' Plot simulated time-varying hazard ratios or stratified time-varying hazard rates from Cox Proportional Hazards Models #' #' \code{simGG.simtvc} uses \link{ggplot2} to plot the simulated hazards from a \code{simtvc} class object created by \code{\link{coxsimtvc}} using \link{ggplot2}. #' @param obj a \code{simtvc} class object #' @param from numeric time to start the plot from. #' @param to numeric time to plot to. #' @param xlab a label for the plot's x-axis. #' @param ylab a label of the plot's y-axis. The default uses the value of \code{qi}. #' @param title the plot's main title. #' @param smoother what type of smoothing line to use to summarize the plotted coefficient. #' @param spalette colour palette for use in \code{qi = "Hazard Rate"}. Default palette is \code{"Set1"}. See \code{\link{scale_colour_brewer}}. #' @param leg.name name of the stratified hazard rates legend. Only relevant if \code{qi = "Hazard Rate"}. #' @param lcolour character string colour of the smoothing line. The default is hexadecimal colour \code{lcolour = '#2B8CBE'}. Only relevant if \code{qi = "Relative Hazard"} or \code{qi = "First Difference"}. #' @param lsize size of the smoothing line. Default is 2. See \code{\link{ggplot2}}. #' @param pcolour character string colour of the simulated points for relative hazards. Default is hexadecimal colour \code{pcolour = '#A6CEE3'}. Only relevant if \code{qi = "Relative Hazard"} or \code{qi = "First Difference"}. #' @param psize size of the plotted simulation points. Default is \code{psize = 1}. See \code{\link{ggplot2}}. #' @param palpha point alpha (e.g. transparency). Default is \code{palpha = 0.05}. See \code{\link{ggplot2}}. #' @param ... Additional arguments. (Currently ignored.) #' #' @return a \code{gg} \code{ggplot} class object #' @details Plots either a time varying hazard ratio or the hazard rates for multiple strata. Currently the strata legend labels need to be changed manually (see \code{\link{revalue}} in the \link{plyr} package) in the \code{simtvc} object with the \code{strata} component. Also, currently the x-axis tick marks and break labels must be adjusted manually for non-linear functions of time. #' Note: A dotted line is created at y = 1 (0 for first difference), i.e. no effect, for time-varying hazard ratio graphs. No line is created for hazard rates. #' @examples #' ## dontrun #' # Load Golub & Steunenberg (2007) Data #' # data("GolubEUPData") #' #' # Load survival package #' # library(survival) #' #' # Create natural log time interactions #' #Golubtvc <- function(x){ #' # assign(paste0("l", x), tvc(GolubEUPData, b = x, tvar = "end", tfun = "log")) #' # } #' #' # GolubEUPData$Lcoop <-Golubtvc("coop") #' # GolubEUPData$Lqmv <- Golubtvc("qmv") #' # GolubEUPData$Lbacklog <- Golubtvc("backlog") #' # GolubEUPData$Lcodec <- Golubtvc("codec") #' # GolubEUPData$Lqmvpostsea <- Golubtvc("qmvpostsea") #' # GolubEUPData$Lthatcher <- Golubtvc("thatcher") #' #' # Run Cox PH Model #' # M1 <- coxph(Surv(begin, end, event) ~ #' # qmv + qmvpostsea + qmvpostteu + #' # coop + codec + eu9 + eu10 + eu12 + #' # eu15 + thatcher + agenda + backlog + #' # Lqmv + Lqmvpostsea + Lcoop + Lcodec + #' # Lthatcher + Lbacklog, #' # data = GolubEUPData, #' # ties = "efron") #' #' # Create simtvc object for Relative Hazard #' # Sim1 <- coxsimtvc(obj = M1, b = "qmv", btvc = "Lqmv", #' # tfun = "log", from = 80, to = 2000, #' # Xj = 1, by = 15, ci = 0.99) #' #' # Create simtvc object for First Difference #' # Sim2 <- coxsimtvc(obj = M1, b = "qmv", btvc = "Lqmv", #' # qi = "First Difference", Xj = 1, #' # tfun = "log", from = 80, to = 2000, #' # by = 15, ci = 0.95) #' #' # Create simtvc object for Hazard Ratio #' # Sim3 <- coxsimtvc(obj = M1, b = "backlog", btvc = "Lbacklog", #' # qi = "Hazard Ratio", Xj = c(191, 229), #' # Xl = c(0, 0), #' # tfun = "log", from = 80, to = 2000, #' # by = 15, ci = 0.99) #' #' # Create plots #' # simGG(Sim1) #' # simGG(Sim2) #' # simGG(Sim3, leg.name = "Comparision", from = 1200) #' #' @import ggplot2 #' @export #' @method simGG simtvc #' @S3method simGG simtvc #' #' @references Licht, <NAME>. 2011. ''Change Comes with Time: Substantive Interpretation of Nonproportional Hazards in Event History Analysis.'' Political Analysis 19: 227-43. simGG.simtvc <- function(obj, from = NULL, to = NULL, xlab = NULL, ylab = NULL, title = NULL, smoother = "auto", spalette = "Set1", leg.name = "", lcolour = "#2B8CBE", lsize = 2, pcolour = "#A6CEE3", psize = 1, palpha = 0.1, ...) { Time <- HRate <- HRValue <- QI <- Comparison <- Xj <- NULL if (!inherits(obj, "simtvc")){ stop("must be a simtvc object") } # Find quantity of interest qi <- class(obj)[[2]] # Create y-axis label if (is.null(ylab)){ ylab <- paste(qi, "\n") } else { ylab <- ylab } # Subset simtvc object & create data frame of important variables if (qi == "Hazard Rate"){ colour <- NULL if (is.null(obj$strata)){ objdf <- data.frame(obj$RealTime, obj$QI, obj$HRValue) names(objdf) <- c("Time", "HRate", "HRValue") } else if (!is.null(obj$strata)) { objdf <- data.frame(obj$RealTime, obj$QI, obj$strata, obj$HRValue) names(objdf) <- c("Time", "HRate", "Strata", "HRValue") } } else if (qi == "Hazard Ratio"){ objdf <- data.frame(obj$RealTime, obj$QI, obj$Comparison) names(objdf) <- c("Time", "QI", "Comparison") } else if (qi == "Relative Hazard"){ objdf <- data.frame(obj$RealTime, obj$QI, obj$Xj) names(objdf) <- c("Time", "QI", "Xj") } else if (qi == "First Difference"){ objdf <- data.frame(obj$RealTime, obj$QI, obj$Comparison) names(objdf) <- c("Time", "QI", "Comparison") } # Keep certain times if (!is.null(from)){ objdf <- subset(objdf, Time >= from) } if (!is.null(to)){ objdf <- subset(objdf, Time <= to) } # Plot if (qi == "Hazard Rate"){ if (!is.null(obj$strata)) { ggplot(objdf, aes(x = Time, y = HRate, colour = factor(HRValue))) + geom_point(alpha = I(palpha), size = psize) + geom_smooth(method = smoother, size = lsize, se = FALSE) + facet_grid(.~ Strata) + xlab(xlab) + ylab(ylab) + scale_colour_brewer(palette = spalette, name = leg.name) + ggtitle(title) + guides(colour = guide_legend(override.aes = list(alpha = 1))) + theme_bw(base_size = 15) } else if (is.null(obj$strata)){ ggplot(objdf, aes(Time, HRate, colour = factor(HRValue))) + geom_point(shape = 21, alpha = I(palpha), size = psize) + geom_smooth(method = smoother, size = lsize, se = FALSE) + scale_colour_brewer(palette = spalette, name = leg.name) + xlab(xlab) + ylab(ylab) + ggtitle(title) + guides(colour = guide_legend(override.aes = list(alpha = 1))) + theme_bw(base_size = 15) } } else if (qi == "Hazard Ratio"){ ggplot(objdf, aes(x = Time, y = QI, colour = factor(Comparison))) + geom_point(alpha = I(palpha), size = psize) + geom_smooth(method = smoother, size = lsize, se = FALSE) + geom_hline(aes(yintercept = 1), linetype = "dotted") + xlab(xlab) + ylab(ylab) + scale_colour_brewer(palette = spalette, name = leg.name) + ggtitle(title) + guides(colour = guide_legend(override.aes = list(alpha = 1))) + theme_bw(base_size = 15) } else if (qi == "Relative Hazard"){ ggplot(objdf, aes(x = Time, y = QI, colour = factor(Xj))) + geom_point(alpha = I(palpha), size = psize) + geom_smooth(method = smoother, size = lsize, se = FALSE) + geom_hline(aes(yintercept = 1), linetype = "dotted") + xlab(xlab) + ylab(ylab) + scale_colour_brewer(palette = spalette, name = leg.name) + ggtitle(title) + guides(colour = guide_legend(override.aes = list(alpha = 1))) + theme_bw(base_size = 15) } else if (qi == "First Difference"){ ggplot(objdf, aes(Time, QI, group = Comparison)) + geom_point(shape = 21, alpha = I(palpha), size = psize, colour = pcolour) + geom_smooth(method = smoother, size = lsize, se = FALSE, color = lcolour) + geom_hline(aes(yintercept = 0), linetype = "dotted") + xlab(xlab) + ylab(ylab) + scale_colour_brewer(palette = spalette, name = leg.name) + ggtitle(title) + guides(colour = guide_legend(override.aes = list(alpha = 1))) + theme_bw(base_size = 15) } }<file_sep>\name{coxsimInteract} \alias{coxsimInteract} \title{Simulate quantities of interest for linear multiplicative interactions from Cox Proportional Hazards models} \usage{ coxsimInteract(obj, b1, b2, qi = "Marginal Effect", X1 = NULL, X2 = NULL, means = FALSE, nsim = 1000, ci = 0.95, spin = FALSE) } \arguments{ \item{obj}{a \code{\link{coxph}} class fitted model object with a linear multiplicative interaction.} \item{b1}{character string of the first constitutive variable's name. Note \code{b1} and \code{b2} must be entered in the order in which they are entered into the \code{coxph} model.} \item{b2}{character string of the second constitutive variable's name.} \item{qi}{quantity of interest to simulate. Values can be \code{"Marginal Effect"}, \code{"First Difference"}, \code{"Hazard Ratio"}, and \code{"Hazard Rate"}. The default is \code{qi = "Hazard Ratio"}. If \code{qi = "Hazard Rate"} and the \code{coxph} model has strata, then hazard rates for each strata will also be calculated.} \item{X1}{numeric vector of fitted values of \code{b1} to simulate for. If \code{qi = "Marginal Effect"} then only \code{X2} can be set. If you want to plot the results, \code{X1} should have more than one value.} \item{X2}{numeric vector of fitted values of \code{b2} to simulate for.} \item{means}{logical, whether or not to use the mean values to fit the hazard rate for covaraiates other than \code{b1} \code{b2} and \code{b1*b2}. Note: it does not currently support models that include polynomials created by \code{\link{I}}.} \item{nsim}{the number of simulations to run per value of X. Default is \code{nsim = 1000}.} \item{ci}{the proportion of middle simulations to keep. The default is \code{ci = 0.95}, i.e. keep the middle 95 percent. If \code{spin = TRUE} then \code{ci} is the confidence level of the shortest probability interval. Any value from 0 through 1 may be used.} \item{spin}{logical, whether or not to keep only the shortest probability interval rather than the middle simulations.} } \value{ a \code{siminteract} class object } \description{ \code{coxsimInteract} simulates quantities of interest for linear multiplicative interactions using multivariate normal distributions. These can be plotted with \code{\link{simGG}}. } \details{ Simulates marginal effects, first differences, hazard ratios, and hazard rates for linear multiplicative interactions. Marginal effects are calculated as in Brambor et al. (2006) with the addition that we take the exponent, so that it resembles a hazard ratio. For an interaction between variables \eqn{X} and \eqn{Z} then the marginal effect for \eqn{X} is: \deqn{ME_{X} = exp(\beta_{X} + \beta_{XZ}Z).} Note that for First Differences the comparison is not between two values of the same variable but two values of the constitute variable and 0. } \examples{ # Load Carpenter (2002) data data("CarpenterFdaData") # Load survival package library(survival) # Run basic model M1 <- coxph(Surv(acttime, censor) ~ lethal*prevgenx, data = CarpenterFdaData) # Simulate Marginal Effect of lethal for multiple values of prevgenx Sim1 <- coxsimInteract(M1, b1 = "lethal", b2 = "prevgenx", X2 = seq(2, 115, by = 2), spin = TRUE) ## dontrun # Change the order of the covariates to make a more easily # interpretable relative hazard graph. # M2 <- coxph(Surv(acttime, censor) ~ prevgenx*lethal + # orphdum, # data = CarpenterFdaData) # Simulate Hazard Ratio of lethal for multiple values of prevgenx # Sim2 <- coxsimInteract(M2, b1 = "prevgenx", b2 = "lethal", # X1 = seq(2, 115, by = 2), # X2 = c(0, 1), # qi = "Hazard Ratio", ci = 0.9) # Simulate First Difference # Sim3 <- coxsimInteract(M2, b1 = "prevgenx", b2 = "lethal", # X1 = seq(2, 115, by = 2), # X2 = c(0, 1), # qi = "First Difference", spin = TRUE) # Simulate Hazard Rate # Sim4 <- coxsimInteract(M2, b1 = "prevgenx", b2 = "lethal", # X1 = c(90), X2 = c(1), qi = "Hazard Rate", # means = TRUE) } \references{ Brambor, Thomas, <NAME>, and <NAME>. 2006. ''Understanding Interaction Models: Improving Empirical Analyses.'' Political Analysis 14(1): 63-82. King, Gary, <NAME>, and <NAME>. 2000. ''Making the Most of Statistical Analyses: Improving Interpretation and Presentation.'' American Journal of Political Science 44(2): 347-61. <NAME>, <NAME>, and <NAME>. 2013. ''Simulation-Efficient Shortest Probability Intervals.'' Arvix. \url{http://arxiv.org/pdf/1302.2142v1.pdf}. } \seealso{ \code{\link{simGG}}, \code{\link{survival}}, \code{\link{strata}}, and \code{\link{coxph}}, } <file_sep>#' Internal function for finding the lower and upper bound of the shortest probability interval. #' #' \code{SpinBounds} internal function for finding the lower bound from SPIn. This function and documentation is largely based directly on the original \code{SPIn} command by <NAME>. #' #' @param x the name of the simulated quantities of interest variable #' @param conf numeric confidence level #' @param LowUp numeric specifying if you want to find the lower or upper bound of the interval. Possible options include \code{1} (Low) or \code{2} (High). #' @param bw scalar, the bandwidth of the weighting kernel in terms of sample points. If not specified, sqrt(n) will be used, where n is the sample size. #' @param lb,ub scalars, the lower and upper bounds of the distribution. If specified, a pseudo-sample point equal to the corresponding bound will be added. By default, \code{lb = 0} as this is the relevant lower bound for quantities of interest from survival models. \code{\link{coxsimInteract}} modifies \code{lb} to \code{-Inf} if \code{qi = "Marginal Effect"}. #' @param l,u scalars, weighting centers (if provided). #' #' @description \code{SpinBounds} is an internal function used by \code{simPH}'s simulation commands to find the shortest probability interval. It is largely drawn from Liu's (2013) \code{SPIn} command (version 1.1), with two modifications. First it returns just the lower or upper bound of the interval, rather than the whole SPIn object. Second, if there is no variation in the interval (as the hazard ratio for a fitted value of 0, e.g. all simulation values are 1) it takes the "central interval" of the simulations. Effectively it reduces the number of simulations by \code{nsim} * \code{ci}. #' #' @references Liu, Ying, <NAME>, and <NAME>. 2013. ''Simulation-Efficient Shortest Probability Intervals.'' Arvix. \url{http://arxiv.org/pdf/1302.2142v1.pdf}. #' #' @import quadprog #' @keywords internals #' @noRd SpinBounds <- function (x, conf = 0.95, LowUp = NULL, bw = 0, lb = 0, ub = Inf, l = NA, u = NA) { # Stop if all values are the same QIDups <- x[!duplicated(x)] if (length(QIDups) == 1){ Bottom <- (1 - conf)/2 Top <- 1 - Bottom if (LowUp == 1){ Lower <- x < quantile(x, Bottom) return(Lower) } else if (LowUp == 2){ Upper <- x > quantile(x, Top) return(Upper) } } else { if (lb != -Inf) x <- c(x, lb) if (ub != Inf) x <- c(x, ub) dens <- density(x) if (is.na(l)) { n.sims <- length(x) conf <- 1 - conf nn <- round(n.sims * conf) x <- sort(x) xx <- x[(n.sims - nn):n.sims] - x[1:(nn + 1)] m <- min(xx) k <- which(xx == m)[1] l <- x[k] ui <- n.sims - nn + k - 1 u <- x[ui] } else { if (sum(x == l) == 0) { x <- c(x, l) } if (sum(x == u) == 0) { x <- c(x, u) } x <- sort(x) n.sims <- length(x) } #library(quadprog) if (bw <= 0) bw <- round((sqrt(n.sims) - 1)/2) k <- which(x == l)[1] ui <- which(x == u)[1] l.l <- max(1, k - bw) l.u <- k + (k - l.l) u.u <- min(n.sims, ui + bw) u.l <- ui - (u.u - ui) n.l <- l.u - l.l + 1 n.u <- u.u - u.l + 1 D.l <- matrix(nrow = n.l, ncol = n.l) D.u <- matrix(nrow = n.u, ncol = n.u) p <- (l.l:l.u)/(n.sims + 1) q <- 1 - p Q <- quantile(x, p) d.q <- rep(0, n.l) for (r in 1:n.l) d.q[r] <- dens$y[which.min(abs(dens$x - Q[r]))] Q. <- 1/d.q diag(D.l) <- 2 * (Q^2 + p * q * Q.^2/(n.sims + 2)) d.l <- 2 * Q * l if (n.l > 1) { for (j in 1:(n.l - 1)) for (m in (j + 1):n.l) { D.l[j, m] <- Q.[j] * Q.[m] * p[j] * q[m] * 2/(n.sims + 2) + Q[j] * Q[m] * 2 D.l[m, j] <- D.l[j, m] } } p <- (u.l:u.u)/(n.sims + 1) q <- 1 - p Q <- quantile(x, p) d.q <- rep(0, n.u) for (r in 1:n.u) d.q[r] <- dens$y[which.min(abs(dens$x - Q[r]))] Q. <- 1/d.q diag(D.u) <- 2 * (Q^2 + p * q * Q.^2/(n.sims + 2)) d.u <- 2 * Q * u if (n.u > 1) { for (j in 1:(n.u - 1)) for (m in (j + 1):n.u) { D.u[j, m] <- Q.[j] * Q.[m] * p[j] * q[m] * 2/(n.sims + 2) + Q[j] * Q[m] * 2 D.u[m, j] <- D.u[j, m] } } if (k == 1) { x1 <- l w.l <- 1 } else { A.l <- matrix(0, nrow = l.u - l.l + 3, ncol = l.u - l.l + 1) A.l[1, ] <- 1 if (bw > 1) { if (k > 2) { for (j in 1:(k - l.l - 1)) { if (x[l.l + j + 1] == x[l.l + j]) { A.l[1 + j, j + 1] <- 1 A.l[1 + j, j + 2] <- -1 } else { aa <- (x[l.l + j] - x[l.l + j - 1])/(x[l.l + j + 1] - x[l.l + j]) A.l[1 + j, j] <- 1 A.l[1 + j, j + 1] <- -(aa + 1) A.l[1 + j, j + 2] <- aa } } for (j in 0:(l.u - k - 2)) { if (x[k + j + 1] == x[k + j + 2]) { A.l[k - l.l + 1 + j, k - l.l + 2 + j] <- 1 A.l[k - l.l + 1 + j, k - l.l + 3 + j] <- -1 } else { aa <- (x[k + j] - x[k + j + 1])/(x[k + j + 1] - x[k + j + 2]) A.l[k - l.l + 1 + j, k - l.l + 1 + j] <- -1 A.l[k - l.l + 1 + j, k - l.l + 2 + j] <- aa + 1 A.l[k - l.l + 1 + j, k - l.l + 3 + j] <- -aa } } } } if (x[k + 1] == x[k]) { aa <- (x[k] - x[k - 1])/(x[k + 1] - x[k] + 1e-06) } else { aa <- (x[k] - x[k - 1])/(x[k + 1] - x[k]) } A.l[l.u - l.l, k - l.l + 1] <- aa - 1 A.l[l.u - l.l, k - l.l] <- 1 A.l[l.u - l.l, k - l.l + 2] <- -aa A.l[l.u - l.l + 1, l.u - l.l] <- 1 A.l[l.u - l.l + 1, l.u - l.l + 1] <- -1 A.l[l.u - l.l + 2, 1] <- 1 A.l[l.u - l.l + 3, l.u - l.l + 1] <- 1 A.l <- t(A.l) w.l <- solve.QP(D.l, d.l, A.l, c(1, rep(0, l.u - l.l + 2)), l.u - l.l) w.l <- w.l$solution x1 <- w.l %*% x[l.l:l.u] } if (ui == n.sims) { x2 <- u w.u <- 1 } else { A.u <- matrix(0, nrow = u.u - u.l + 3, ncol = u.u - u.l + 1) A.u[1, ] <- 1 if (bw > 1) { if (ui - u.l > 1) { for (j in 1:(ui - u.l - 1)) { if (x[u.l + j + 1] == x[u.l + j]) { A.u[1 + j, j + 1] <- 1 A.u[1 + j, j + 2] <- -1 } else { aa <- (x[u.l + j] - x[u.l + j - 1])/(x[u.l + j + 1] - x[u.l + j]) A.u[1 + j, j] <- 1 A.u[1 + j, j + 1] <- -(aa + 1) A.u[1 + j, j + 2] <- aa } } i <- 0 for (j in (ui - u.l):(u.u - u.l - 2)) { if (x[ui + i + 1] == x[ui + i + 2]) { A.u[1 + j, j + 2] <- 1 A.u[1 + j, j + 3] <- -1 } else { aa <- (x[ui + i] - x[ui + i + 1])/(x[ui + i + 1] - x[ui + i + 2]) A.u[1 + j, j + 1] <- -1 A.u[1 + j, j + 2] <- aa + 1 A.u[1 + j, j + 3] <- -aa } i <- i + 1 } } } if (x[ui + 1] == x[ui]) { aa <- (x[ui] - x[ui - 1])/(x[ui + 2] - x[ui]) A.u[u.u - u.l, ui - u.l] <- 1 A.u[u.u - u.l, ui - u.l + 1] <- aa - 1 A.u[u.u - u.l, ui - u.l + 3] <- -aa } else { aa <- (x[ui] - x[ui - 1])/(x[ui + 1] - x[ui]) A.u[u.u - u.l, ui - u.l] <- 1 A.u[u.u - u.l, ui - u.l + 1] <- aa - 1 A.u[u.u - u.l, ui - u.l + 2] <- -aa } A.u[u.u - u.l + 1, u.u - u.l] <- 1 A.u[u.u - u.l + 1, u.u - u.l + 1] <- -1 A.u[u.u - u.l + 2, 1] <- 1 A.u[u.u - u.l + 3, u.u - u.l + 1] <- 1 A.u <- t(A.u) w.u <- solve.QP(D.u, d.u, A.u, c(1, rep(0, u.u - u.l + 2)), u.u - u.l) w.u <- w.u$solution x2 <- w.u %*% x[u.l:u.u] } if (LowUp == 1){ hpd <- as.numeric(x1) } else if (LowUp == 2){ hpd <- as.numeric(x2) } return(hpd) } }<file_sep>simPH ====== ### <NAME> ### Version 0.7.3 ### Please report any bugs at <https://github.com/christophergandrud/simPH/issues>. --- An R package for simulating and plotting quantities of interest (relative hazards, first differences, and hazard ratios)for linear coefficients, multiplicative interactions, polynomials, penalised splines, and non-proportional hazards, as well as stratified survival curves from Cox Proportional Hazard models. For more information plus examples, please see this [working paper](http://papers.ssrn.com/sol3/papers.cfm?abstract_id=2227226). The package includes the following functions: #### Simulation Functions - `coxsimLinear`: Simulates relative hazards, first differences, hazard ratios, and hazard rates for linear time-constant covariates from Cox Proportional Hazard models. - `coxsimtvc`: a function for simulating time-varying hazards (relative hazards, first differences, and hazard ratios) from a Cox PH model estimated using `coxph` from the [survival](http://cran.r-project.org/web/packages/survival/index.html) package. For more information see this [blog post](http://christophergandrud.blogspot.kr/2012/10/graphing-non-proportional-hazards-in-r.html). The function will calculate time-varying hazard ratios for multiple strata estimated from a stratified Cox PH model. - `coxsimSpline`: a function for simulating quantities of interest from penalised splines using multivariate normal distributions. Currently does not support simulating hazard rates from stratified models. **Note:** be extremely careful about the number of simulations you ask the function to find. It is very easy to ask for more than your computer can handle. - `coxsimPoly`: a function for simulating quantities of interest for a range of values for a polynomial nonlinear effect from Cox Proportional Hazards models. - `coxsimInteract`: a function for simulating quantities of interest for linear multiplicative interactions, including marginal effects and hazard rates. #### Plotting Functions **Important Change:** From **simPH** version 0.05 you can now use the method `simGG` for plotting all simulations rather than the old sim model object specific commands. In practical terms this means that you can now just use the command `simGG` rather than the old gg. . . commands. The old commands are deprecated and will no longer work. The syntax and capabilities of `simGG` varies depending on the sim object class you are using: - `simGG.simlinear`: plots simulated linear time-constant hazards using [ggplot2](http://ggplot2.org/). - `simGG.simtvc`: uses **ggplot2** to graph the simulated time-varying relative hazards, first differences, hazard ratios or stratified hazard rates. - `simGG.simspline`: uses **ggplot2** and `scatter3d` (from the [car](http://cran.r-project.org/web/packages/car/index.html) package) to plot quantities of interest from `simspline` objects, including relative hazards, first differences, hazard ratios, and hazard rates. - `simGG.simpoly`: uses **ggplot2** to graph the simulated polynomial quantities of interest. - `simGG.siminteract`: uses **ggplot2** to graph linear multiplicative interactions. ##### Additional styling Because in almost all cases `simGG` returns a *ggplot2* object, you can add aditional aesthetic attributes in the normal *ggplot2* way. See the [ggplot2 documentation for more details](http://docs.ggplot2.org/current/). Here is a quick example: --- #### Misc. - `tvc`: a function for creating time interactions. Currently supports `'linear'`, natural `'log'`, and exponentiation (`'power'`). - `ggfitStrata`: a function to plot fitted stratified survival curves estimated from `survfit` using **ggplot2**. This function builds on the **survival** package's `plot.survfit` command. One major advantage is the ability to split the survival curves into multiple plots and arrange them in a grid. This makes it easier to examine many strata at once. Otherwise they can be very bunched up. ## Installation Use the [devtools](https://github.com/hadley/devtools) command `install_github` to install **simPH** in R. Here is the exact code for installing the most recent development version: ```r devtools::install_github("simPH", "christophergandrud") ``` ## Tip Before running the simulation and graph commands in this package carefully consider how many simulations you are about to make. Especially for hazard rates over long periods of time and with multiple strata, you can be asking **simPH** to run very many simulations. This will be computationally intensive. --- ## Sources ### Simulating Parameter Estimates For more information about simulating parameter estimates to make interpretation of results easier see: Licht, <NAME>. 2011. [“Change Comes with Time: Substantive Interpretation of Nonproportional Hazards in Event History Analysis.”](http://pan.oxfordjournals.org/content/19/2/227.abstract) Political Analysis 19: 227–43. <NAME>, <NAME>, and <NAME>. 2000. [“Making the Most of Statistical Analyses: Improving Interpretation and Presentation.”](http://www.jstor.org/stable/2669316) American Journal of Political Science 44(2): 347–61. ### Stratified Cox PH For more information about stratified Cox PH models (and frailties, which I am working to incorporate in future versions) see: Box-Steffensmeier, <NAME>, and <NAME>. 2006. [“Repeated Events Survival Models: the Conditional Frailty Model.”](http://onlinelibrary.wiley.com/doi/10.1002/sim.2434/abstract;jsessionid=28218243DD3D6E01A3D10EEE75D96675.d01t02) Statistics in Medicine 25(20): 3518–33. ### Shortest Probability Intervals To learn more about shortest probability intervals (and also for the source of the code that made this possible in **simPH**) see: <NAME>., <NAME>., & <NAME>. (2013). ["Simulation-efficient Shortest Probablility Intervals."](http://arxiv.org/pdf/1302.2142v1.pdf) Arvix. **Also good:** <NAME>. (1996). ["Computing and Graphing Highest Density Regions."](http://www.jstor.org/stable/10.2307/2684423) The American Statistician, 50(2), 120–126. ### Interpreting Interactions For more information about interpreting interaction terms: <NAME>, <NAME>, and <NAME>. 2006. [“Understanding Interaction Models: Improving Empirical Analyses.”](http://pan.oxfordjournals.org/content/14/1/63.abstract) Political Analysis 14(1): 63–82. ### The Olden Days For an example of how non-proportional hazard results were often presented before **simPH** see (some of the problems I encountered in this paper were a major part of why I'm developing this package): <NAME>. 2013. [“The Diffusion of Financial Supervisory Governance Ideas.”](http://www.tandfonline.com/doi/full/10.1080/09692290.2012.727362) Review of International Political Economy. 20(4):881-916. --- ## Future Plans This package is in the **early stages** of development. I intend to expand the quantities of interest that can be simulated and graphed for Cox PH models. I am also currently working on functions that can simulate and graph hazard ratios estimated from [Fine and Gray competing risks models](http://www.jstor.org/stable/2670170). I am also working on a way to graph hazard ratios with frailties. <file_sep>#' Simulate quantities of interest for linear time constant covariates from Cox Proportional Hazards models #' #' \code{coxsimLinear} simulates relative hazards, first differences, and hazard ratios for time-constant covariates from models estimated with \code{\link{coxph}} using the multivariate normal distribution. These can be plotted with \code{\link{simGG}}. #' @param obj a \code{\link{coxph}} class fitted model object. #' @param b character string name of the coefficient you would like to simulate. #' @param qi quantity of interest to simulate. Values can be \code{"Relative Hazard"}, \code{"First Difference"}, \code{"Hazard Ratio"}, and \code{"Hazard Rate"}. The default is \code{qi = "Relative Hazard"}. If \code{qi = "Hazard Rate"} and the \code{coxph} model has strata, then hazard rates for each strata will also be calculated. #' @param Xj numeric vector of fitted values for \code{b} to simulate for. #' @param Xl numeric vector of values to compare \code{Xj} to. Note if \code{code = "Relative Hazard"} only \code{Xj} is relevant. #' @param means logical, whether or not to use the mean values to fit the hazard rate for covaraiates other than \code{b}. #' @param nsim the number of simulations to run per value of X. Default is \code{nsim = 1000}. Note: it does not currently support models that include polynomials created by \code{\link{I}}. #' @param ci the proportion of simulations to keep. The default is \code{ci = 0.95}, i.e. keep the middle 95 percent. If \code{spin = TRUE} then \code{ci} is the confidence level of the shortest probability interval. Any value from 0 through 1 may be used. #' @param spin logical, whether or not to keep only the shortest probability interval rather than the middle simulations. #' #' @return a \code{simlinear} object #' #' @description Simulates relative hazards, first differences, hazard ratios, and hazard rates for linear time-constant covariates from Cox Proportional Hazard models. These can be plotted with \code{\link{simGG}}. #' #' #' @examples #' # Load Carpenter (2002) data #' data("CarpenterFdaData") #' #' # Load survival package #' library(survival) #' #' # Run basic model #' M1 <- coxph(Surv(acttime, censor) ~ prevgenx + lethal + #' deathrt1 + acutediz + hosp01 + hhosleng + #' mandiz01 + femdiz01 + peddiz01 + orphdum + #' vandavg3 + wpnoavg3 + condavg3 + orderent + #' stafcder, data = CarpenterFdaData) #' #' # Simulate Hazard Ratios #' Sim1 <- coxsimLinear(M1, b = "stafcder", #' Xj = c(1237, 1600), #' Xl = c(1000, 1000), #' spin = TRUE, ci = 0.99) #' #' ## dontrun #' # Simulate Hazard Rates #' # Sim2 <- coxsimLinear(M1, b = "stafcder", #' # qi = "Hazard Rate", #' # Xj = 1237, #' # ci = 0.99, means = TRUE) #' #' @seealso \code{\link{simGG}}, \code{\link{survival}}, \code{\link{strata}}, and \code{\link{coxph}} #' @references Licht, <NAME>. 2011. ''Change Comes with Time: Substantive Interpretation of Nonproportional Hazards in Event History Analysis.'' Political Analysis 19: 227-43. #' #' King, Gary, <NAME>, and <NAME>. 2000. ''Making the Most of Statistical Analyses: Improving Interpretation and Presentation.'' American Journal of Political Science 44(2): 347-61. #' #' Liu, Ying, <NAME>, and <NAME>. 2013. ''Simulation-Efficient Shortest Probability Intervals.'' Arvix. \url{http://arxiv.org/pdf/1302.2142v1.pdf}. #' #' @import data.table #' @importFrom reshape2 melt #' @importFrom survival basehaz #' @importFrom MSBVAR rmultnorm #' @export coxsimLinear <- function(obj, b, qi = "Relative Hazard", Xj = NULL, Xl = NULL, means = FALSE, nsim = 1000, ci = 0.95, spin = FALSE) { QI <- NULL if (qi != "Hazard Rate" & isTRUE(means)){ stop("means can only be TRUE when qi = 'Hazard Rate'.") } if (is.null(Xl) & qi != "Hazard Rate"){ Xl <- rep(0, length(Xj)) message("All Xl set to 0.") } else if (!is.null(Xl) & qi == "Relative Hazard") { message("All Xl set to 0.") } # Ensure that qi is valid qiOpts <- c("Relative Hazard", "First Difference", "Hazard Rate", "Hazard Ratio") TestqiOpts <- qi %in% qiOpts if (!isTRUE(TestqiOpts)){ stop("Invalid qi type. qi must be 'Relative Hazard', 'Hazard Rate', 'First Difference', or 'Hazard Ratio'") } MeansMessage <- NULL if (isTRUE(means) & length(obj$coefficients) == 3){ means <- FALSE MeansMessage <- FALSE message("Note: means reset to FALSE. The model only includes the interaction variables.") } else if (isTRUE(means) & length(obj$coefficients) > 3){ MeansMessage <- TRUE } # Parameter estimates & Variance/Covariance matrix Coef <- matrix(obj$coefficients) VC <- vcov(obj) # Draw covariate estimates from the multivariate normal distribution Drawn <- rmultnorm(n = nsim, mu = Coef, vmat = VC) DrawnDF <- data.frame(Drawn) dfn <- names(DrawnDF) # If all values aren't set for calculating the hazard rate if (!isTRUE(means)){ # Subset simulations to only include b bpos <- match(b, dfn) Simb <- data.frame(DrawnDF[, bpos]) names(Simb) <- "Coef" # Find quantity of interest if (qi == "Relative Hazard"){ Xs <- data.frame(Xj) names(Xs) <- c("Xj") Xs$Comparison <- paste(Xs[, 1]) Simb <- merge(Simb, Xs) Simb$QI <- exp(Simb$Xj * Simb$Coef) } else if (qi == "First Difference"){ Xs <- data.frame(Xj, Xl) Simb <- merge(Simb, Xs) Simb$QI<- (exp((Simb$Xj - Simb$Xl) * Simb$Coef) - 1) * 100 } else if (qi == "Hazard Ratio"){ Xs <- data.frame(Xj, Xl) Simb <- merge(Simb, Xs) Simb$QI<- exp((Simb$Xj - Simb$Xl) * Simb$Coef) } else if (qi == "Hazard Rate"){ Xl <- NULL message("Xl is ignored.") if (isTRUE(MeansMessage)){ message("All variables values other than b are fitted at 0.") } Xs <- data.frame(Xj) Xs$HRValue <- paste(Xs[, 1]) Simb <- merge(Simb, Xs) Simb$HR <- exp(Simb$Xj * Simb$Coef) bfit <- basehaz(obj) bfit$FakeID <- 1 Simb$FakeID <- 1 bfitDT <- data.table(bfit, key = "FakeID", allow.cartesian = TRUE) SimbDT <- data.table(Simb, key = "FakeID", allow.cartesian = TRUE) SimbCombDT <- SimbDT[bfitDT, allow.cartesian=TRUE] Simb <- data.frame(SimbCombDT) Simb$QI <- Simb$hazard * Simb$HR Simb <- Simb[, -1] } } # If the user wants to calculate Hazard Rates using means for fitting all covariates other than b. else if (isTRUE(means)){ Xl <- NULL message("Xl ignored") # Set all values of b at means for data used in the analysis NotB <- setdiff(names(DrawnDF), b) MeanValues <- data.frame(obj$means) FittedMeans <- function(Z){ ID <- 1:nsim Temp <- data.frame(ID) for (i in Z){ BarValue <- MeanValues[i, ] DrawnCoef <- DrawnDF[, i] FittedCoef <- outer(DrawnCoef, BarValue) FCMolten <- data.frame(melt(FittedCoef)) Temp <- cbind(Temp, FCMolten[,3]) } Names <- c("ID", Z) names(Temp) <- Names Temp <- Temp[, -1] return(Temp) } FittedComb <- FittedMeans(NotB) ExpandFC <- do.call(rbind, rep(list(FittedComb), length(Xj))) # Set fitted values for Xj bpos <- match(b, dfn) Simb <- data.frame(DrawnDF[, bpos]) Xs <- data.frame(Xj) Xs$HRValue <- paste(Xs[, 1]) Simb <- merge(Simb, Xs) Simb$CombB <- Simb[, 1] * Simb[, 2] Simb <- Simb[, 2:4] Simb <- cbind(Simb, ExpandFC) Simb$Sum <- rowSums(Simb[, c(-1, -2)]) Simb$HR <- exp(Simb$Sum) bfit <- basehaz(obj) bfit$FakeID <- 1 Simb$FakeID <- 1 bfitDT <- data.table(bfit, key = "FakeID", allow.cartesian = TRUE) SimbDT <- data.table(Simb, key = "FakeID", allow.cartesian = TRUE) SimbCombDT <- SimbDT[bfitDT, allow.cartesian = TRUE] Simb <- data.frame(SimbCombDT) Simb$QI <- Simb$hazard * Simb$HR } # Drop simulations outside of 'confidence bounds' if (qi != "Hazard Rate"){ SubVar <- "Xj" } else if (qi == "Hazard Rate"){ SubVar <- c("time", "Xj") } SimbPerc <- IntervalConstrict(Simb = Simb, SubVar = SubVar, qi = qi, QI = QI, spin = spin, ci = ci) # Final clean up class(SimbPerc) <- c("simlinear", qi) SimbPerc }<file_sep>\name{coxsimPoly} \alias{coxsimPoly} \title{Simulate quantities of interest for a range of values for a polynomial nonlinear effect from Cox Proportional Hazards models} \usage{ coxsimPoly(obj, b, qi = "Relative Hazard", pow = 2, Xj = NULL, Xl = NULL, nsim = 1000, ci = 0.95, spin = FALSE) } \arguments{ \item{obj}{a \code{\link{coxph}} class fitted model object with a polynomial coefficient. These can be plotted with \code{\link{simGG}}.} \item{b}{character string name of the coefficient you would like to simulate.} \item{qi}{quantity of interest to simulate. Values can be \code{"Relative Hazard"}, \code{"First Difference"}, \code{"Hazard Ratio"}, and \code{"Hazard Rate"}. The default is \code{qi = "Relative Hazard"}. If \code{qi = "Hazard Rate"} and the \code{coxph} model has strata, then hazard rates for each strata will also be calculated.} \item{pow}{numeric polynomial used in \code{coxph}.} \item{Xj}{numeric vector of fitted values for \code{b} to simulate for.} \item{Xl}{numeric vector of values to compare \code{Xj} to. If \code{NULL}, then it is authomatically set to 0.} \item{nsim}{the number of simulations to run per value of \code{Xj}. Default is \code{nsim = 1000}.} \item{ci}{the proportion of simulations to keep. The default is \code{ci = 0.95}, i.e. keep the middle 95 percent. If \code{spin = TRUE} then \code{ci} is the confidence level of the shortest probability interval. Any value from 0 through 1 may be used.} \item{spin}{logical, whether or not to keep only the shortest probability interval rather than the middle simulations.} } \value{ a \code{simpoly} class object. } \description{ \code{coxsimPoly} simulates quantities of interest for polynomial covariate effects estimated from Cox Proportional Hazards models. These can be plotted with \code{\link{simGG}}. } \details{ Simulates quantities of interest for polynomial covariate effects. For example if a nonlinear effect is modeled with a second order polynomial--i.e. \eqn{\beta_{1}x_{i} + \beta_{2}x_{i}^{2}}--we can once again draw \eqn{n} simulations from the multivariate normal distribution for both \eqn{\beta_{1}} and \eqn{\beta_{2}}. Then we simply calculate quantities of interest for a range of values and plot the results as before. For example, we find the first difference for a second order polynomial with: \deqn{\%\triangle h_{i}(t) = (\mathrm{e}^{\beta_{1}x_{j-1} + \beta_{2}x_{j-l}^{2}} - 1) * 100} where \eqn{x_{j-l} = x_{j} - x_{l}}. Note, you must use \code{\link{I}} to create the polynomials. } \examples{ # Load Carpenter (2002) data data("CarpenterFdaData") # Load survival package library(survival) # Run basic model M1 <- coxph(Surv(acttime, censor) ~ prevgenx + lethal + deathrt1 + acutediz + hosp01 + hhosleng + mandiz01 + femdiz01 + peddiz01 + orphdum + natreg + I(natreg^2) + I(natreg^3) + vandavg3 + wpnoavg3 + condavg3 + orderent + stafcder, data = CarpenterFdaData) # Simulate simpoly First Difference Sim1 <- coxsimPoly(M1, b = "natreg", qi = "First Difference", pow = 3, Xj = seq(1, 150, by = 5)) # Simulate simpoly Hazard Ratio with spin probibility interval Sim2 <- coxsimPoly(M1, b = "natreg", qi = "Hazard Ratio", pow = 3, Xj = seq(1, 150, by = 5), spin = TRUE) } \references{ Keele, Luke. 2010. ''Proportionally Difficult: Testing for Nonproportional Hazards in Cox Models.'' Political Analysis 18(2): 189-205. <NAME>. 2002. ''Groups, the Media, Agency Waiting Costs, and FDA Drug Approval.'' American Journal of Political Science 46(3): 490-505. <NAME>, <NAME>, and <NAME>. 2000. ''Making the Most of Statistical Analyses: Improving Interpretation and Presentation.'' American Journal of Political Science 44(2): 347-61. Liu, Ying, <NAME>, and <NAME>. 2013. ''Simulation-Efficient Shortest Probability Intervals.'' Arvix. \url{http://arxiv.org/pdf/1302.2142v1.pdf}. } \seealso{ \code{\link{simGG}}, \code{\link{survival}}, \code{\link{strata}}, and \code{\link{coxph}} } <file_sep>\name{simGG.simspline} \alias{simGG.simspline} \title{Plot simulated penalised spline hazards from Cox Proportional Hazards Models} \usage{ \method{simGG}{simspline} (obj, FacetTime = NULL, from = NULL, to = NULL, xlab = NULL, ylab = NULL, zlab = NULL, title = NULL, smoother = "auto", leg.name = "", lcolour = "#2B8CBE", lsize = 2, pcolour = "#A6CEE3", psize = 1, palpha = 0.1, surface = TRUE, fit = "linear", ...) } \arguments{ \item{obj}{a \code{simspline} class object} \item{FacetTime}{a numeric vector of points in time where you would like to plot Hazard Rates in a facet grid. Only relevant if \code{qi == 'Hazard Rate'}. Note: the values of Facet Time must exactly match values of the \code{time} element of \code{obj}.} \item{xlab}{a label for the plot's x-axis.} \item{ylab}{a label of the plot's y-axis. The default uses the value of \code{qi}.} \item{zlab}{a label for the plot's z-axis. Only relevant if \code{qi = "Hazard Rate"} and \code{FacetTime == NULL}.} \item{from}{numeric time to start the plot from. Only relevant if \code{qi = "Hazard Rate"}.} \item{to}{numeric time to plot to. Only relevant if \code{qi = "Hazard Rate"}.} \item{title}{the plot's main title.} \item{smoother}{what type of smoothing line to use to summarize the plotted coefficient.} \item{leg.name}{name of the stratified hazard rates legend. Only relevant if \code{qi = "Hazard Rate"}.} \item{lcolour}{character string colour of the smoothing line. The default is hexadecimal colour \code{lcolour = '#2B8CBE'}. Only relevant if \code{qi = "Relative Hazard"} or \code{qi = "First Difference"}.} \item{lsize}{size of the smoothing line. Default is 2. See \code{\link{ggplot2}}.} \item{pcolour}{character string colour of the simulated points for relative hazards. Default is hexadecimal colour \code{pcolour = '#A6CEE3'}. Only relevant if \code{qi = "Relative Hazard"} or \code{qi = "First Difference"}.} \item{psize}{size of the plotted simulation points. Default is \code{psize = 1}. See \code{\link{ggplot2}}.} \item{palpha}{point alpha (e.g. transparency). Default is \code{palpha = 0.05}. See \code{\link{ggplot2}}.} \item{surface}{plot surface. Default is \code{surface = TRUE}. Only relevant if \code{qi == 'Relative Hazard'} and \code{FacetTime = NULL}.} \item{fit}{one or more of \code{"linear"}, \code{"quadratic"}, \code{"smooth"}, \code{"additive"}; to display fitted surface(s); partial matching is supported e.g., \code{c("lin", "quad")}. Only relevant if \code{qi == 'Relative Hazard'} and \code{FacetTime = NULL}.} \item{...}{Additional arguments. (Currently ignored.)} } \value{ a \code{gg} \code{ggplot} class object. See \code{\link{scatter3d}} for values from \code{scatter3d} calls. } \description{ \code{simGG.simspline} uses \link{ggplot2} and \link{scatter3d} to plot quantities of interest from \code{simspline} objects, including relative hazards, first differences, hazard ratios, and hazard rates. } \details{ Uses \code{ggplot2} and \code{scatter3d} to plot the quantities of interest from \code{simspline} objects, including relative hazards, first differences, hazard ratios, and hazard rates. If currently does not support hazard rates for multiple strata. It can graph hazard rates as a 3D plot using \code{\link{scatter3d}} with the dimensions: Time, Hazard Rate, and the value of \code{Xj}. You can also choose to plot hazard rates for a range of values of \code{Xj} in two dimensional plots at specific points in time. Each plot is arranged in a facet grid. Note: A dotted line is created at y = 1 (0 for first difference), i.e. no effect, for time-varying hazard ratio graphs. No line is created for hazard rates. } \examples{ ## dontrun # Load Carpenter (2002) data # data("CarpenterFdaData") # Load survival package # library(survival) # Run basic model # From Keele (2010) replication data # M1 <- coxph(Surv(acttime, censor) ~ prevgenx + lethal + deathrt1 + # acutediz + hosp01 + pspline(hospdisc, df = 4) + # pspline(hhosleng, df = 4) + mandiz01 + femdiz01 + peddiz01 + # orphdum + natreg + vandavg3 + wpnoavg3 + # pspline(condavg3, df = 4) + pspline(orderent, df = 4) + # pspline(stafcder, df = 4), data = CarpenterFdaData) # Simulate Relative Hazards for orderent # Sim1 <- coxsimSpline(M1, bspline = "pspline(stafcder, df = 4)", # bdata = CarpenterFdaData$stafcder, # qi = "Hazard Ratio", # Xj = seq(1100, 1700, by = 10), # Xl = seq(1099, 1699, by = 10), spin = TRUE) # Simulate Hazard Rate for orderent # Sim2 <- coxsimSpline(M1, bspline = "pspline(orderent, df = 4)", # bdata = CarpenterFdaData$orderent, # qi = "Hazard Rate", # Xj = seq(1, 30, by = 2), ci = 0.9, nsim = 10) # Plot relative hazard # simGG(Sim1, palpha = 1) # 3D plot hazard rate # simGG(Sim2, zlab = "orderent", fit = "quadratic") # Create a time grid plot # Find all points in time where baseline hazard was found # unique(Sim2$time) # Round time values so they can be exactly matched with FacetTime # Sim2$time <- round(Sim2$time, digits = 2) # Create plot # simGG(Sim2, FacetTime = c(6.21, 25.68, 100.64, 202.36)) # Simulated Fitted Values of stafcder # Sim3 <- coxsimSpline(M1, bspline = "pspline(stafcder, df = 4)", # bdata = CarpenterFdaData$stafcder, # qi = "Hazard Ratio", # Xj = seq(1100, 1700, by = 10), # Xl = seq(1099, 1699, by = 10), ci = 0.90) # Plot simulated Hazard Ratios # simGG(Sim3, xlab = "\\nFDA Drug Review Staff", palpha = 0.2) } \seealso{ \code{\link{coxsimLinear}}, \code{\link{simGG.simtvc}}, \code{\link{ggplot2}}, and \code{\link{scatter3d}} } <file_sep>\name{simGG.siminteract} \alias{simGG.siminteract} \title{Plot simulated linear multiplicative interactions from Cox Proportional Hazards Models} \usage{ \method{simGG}{siminteract} (obj, from = NULL, to = NULL, xlab = NULL, ylab = NULL, title = NULL, smoother = "auto", spalette = "Set1", leg.name = "", lcolour = "#2B8CBE", lsize = 2, pcolour = "#A6CEE3", psize = 1, palpha = 0.1, ...) } \arguments{ \item{obj}{a \code{siminteract} class object} \item{xlab}{a label for the plot's x-axis.} \item{ylab}{a label of the plot's y-axis. The default uses the value of \code{qi}.} \item{from}{numeric time to start the plot from. Only relevant if \code{qi = "Hazard Rate"}.} \item{to}{numeric time to plot to. Only relevant if \code{qi = "Hazard Rate"}.} \item{title}{the plot's main title.} \item{smoother}{what type of smoothing line to use to summarize the plotted coefficient.} \item{spalette}{colour palette. Not relevant for \code{qi = "Marginal Effect"}. Default palette is \code{"Set1"}. See \code{\link{scale_colour_brewer}}.} \item{leg.name}{name of the stratified hazard rates legend. Only relevant if \code{qi = "Hazard Rate"}.} \item{lcolour}{character string colour of the smoothing line. The default is hexadecimal colour \code{lcolour = '#2B8CBE'}. Only relevant if \code{qi = "Marginal Effect"}.} \item{lsize}{size of the smoothing line. Default is 2. See \code{\link{ggplot2}}.} \item{pcolour}{character string colour of the simulated points for relative hazards. Default is hexadecimal colour \code{pcolour = '#A6CEE3'}. Only relevant if \code{qi = "Marginal Effect"}.} \item{psize}{size of the plotted simulation points. Default is \code{psize = 1}. See \code{\link{ggplot2}}.} \item{palpha}{point alpha (e.g. transparency). Default is \code{palpha = 0.05}. See \code{\link{ggplot2}}.} \item{...}{Additional arguments. (Currently ignored.)} } \value{ a \code{gg} \code{ggplot} class object } \description{ \code{simGG.siminteract} uses \link{ggplot2} to plot the quantities of interest from \code{siminteract} objects, including marginal effects, first differences, hazard ratios, and hazard rates. } \details{ Uses \link{ggplot2} to plot the quantities of interest from \code{siminteract} objects, including marginal effects, first differences, hazard ratios, and hazard rates. If there are multiple strata, the quantities of interest will be plotted in a grid by strata. Note: A dotted line is created at y = 1 (0 for first difference), i.e. no effect, for time-varying hazard ratio graphs. No line is created for hazard rates. Note: if \code{qi = "Hazard Ratio"} or \code{qi = "First Difference"} then you need to have choosen more than one fitted value for \code{X1} in \code{\link{coxsimInteract}}. } \examples{ # Load Carpenter (2002) data data("CarpenterFdaData") # Load survival package library(survival) # Run basic model M1 <- coxph(Surv(acttime, censor) ~ lethal*prevgenx, data = CarpenterFdaData) # Simulate Marginal Effect of lethal for multiple values of prevgenx Sim1 <- coxsimInteract(M1, b1 = "lethal", b2 = "prevgenx", X2 = seq(2, 115, by = 2)) # Change the order of the covariates to make a more easily # interpretable hazard ratio graph. M2 <- coxph(Surv(acttime, censor) ~ prevgenx*lethal, data = CarpenterFdaData) ## dontrun # Simulate Hazard Ratio of lethal for multiple values of prevgenx # Sim2 <- coxsimInteract(M2, b1 = "prevgenx", b2 = "lethal", # X1 = seq(2, 115, by = 2), # X2 = c(0, 1), # qi = "Hazard Ratio", ci = 0.9) # Simulate First Difference # Sim3 <- coxsimInteract(M2, b1 = "prevgenx", b2 = "lethal", # X1 = seq(2, 115, by = 2), # X2 = c(0, 1), # qi = "First Difference", spin = TRUE) # Plot quantities of interest simGG(Sim1, xlab = "\\nprevgenx", ylab = "Marginal Effect of lethal\\n") # simGG(Sim2) # simGG(Sim3) } \references{ <NAME>, <NAME>, and <NAME>. 2006. ''Understanding Interaction Models: Improving Empirical Analyses.'' Political Analysis 14(1): 63-82. <NAME>. 2010. ''Proportionally Difficult: Testing for Nonproportional Hazards in Cox Models.'' Political Analysis 18(2): 189-205. <NAME>. 2002. ''Groups, the Media, Agency Waiting Costs, and FDA Drug Approval.'' American Journal of Political Science 46(3): 490-505. } \seealso{ \code{\link{coxsimInteract}}, \code{\link{simGG.simlinear}}, and \code{\link{ggplot2}} } <file_sep>#' Simulate quantities of interest for penalized splines from Cox Proportional Hazards models #' #' \code{coxsimSpline} simulates quantities of interest from penalized splines using multivariate normal distributions. #' @param obj a \code{\link{coxph}} class fitted model object with a penalized spline. These can be plotted with \code{\link{simGG}}. #' @param bspline a character string of the full \code{\link{pspline}} call used in \code{obj}. It should be exactly the same as how you entered it in \code{\link{coxph}}. You also need to enter a white spece before and after all equal (\code{=}) signs. #' @param bdata a numeric vector of splined variable's values. #' @param qi quantity of interest to simulate. Values can be \code{"Relative Hazard"}, \code{"First Difference"}, \code{"Hazard Ratio"}, and \code{"Hazard Rate"}. The default is \code{qi = "Relative Hazard"}. Think carefully before using \code{qi = "Hazard Rate"}. You may be creating very many simulated values which can be very computationally intensive to do. Adjust the number of simulations per fitted value with \code{nsim}. #' @param Xj numeric vector of fitted values for \code{b} to simulate for. #' @param Xl numeric vector of values to compare \code{Xj} to. Note if \code{qi = "Relative Hazard"} or \code{"Hazard Rate"} only \code{Xj} is relevant. #' @param nsim the number of simulations to run per value of \code{Xj}. Default is \code{nsim = 1000}. #' @param ci the proportion of simulations to keep. The default is \code{ci = 0.95}, i.e. keep the middle 95 percent. If \code{spin = TRUE} then \code{ci} is the confidence level of the shortest probability interval. Any value from 0 through 1 may be used. #' @param spin logical, whether or not to keep only the shortest probability interval rather than the middle simulations. #' #' @return a \code{simspline} object #' #' @details Simulates relative hazards, first differences, hazard ratios, and hazard rates for penalized splines from Cox Proportional Hazards models. These can be plotted with \code{\link{simGG}}. #' A Cox PH model with one penalized spline is given by: #' \deqn{h(t|\mathbf{X}_{i})=h_{0}(t)\mathrm{e}^{g(x)}} #' #' where \eqn{g(x)} is the penalized spline function. For our post-estimation purposes \eqn{g(x)} is basically a series of linearly combined coefficients such that: #' #' \deqn{g(x) = \beta_{k_{1}}(x)_{1+} + \beta_{k_{2}}(x)_{2+} + \beta_{k_{3}}(x)_{3+} + \ldots + \beta_{k_{n}}(x)_{n+}} #' #' where \eqn{k} are the equally spaced spline knots with values inside of the range of observed \eqn{x} and \eqn{n} is the number of knots. #' #' We can again draw values of each \eqn{\beta_{k_{1}}, \ldots \beta_{k_{n}}} from the multivariate normal distribution described above. We then use these simulated coefficients to estimates quantities of interest for a range covariate values. For example, the first difference between two values \eqn{x_{j}} and \eqn{x_{l}} is: #' #' \deqn{\%\triangle h_{i}(t) = (\mathrm{e}^{g(x_{j}) - g(x_{l})} - 1) * 100} #' #' Relative hazards and hazard ratios can be calculated by extension. #' #' Currently \code{coxsimSpline} does not support simulating hazard rates form multiple stratified models. #' #' @examples #' ## dontrun #' # Load Carpenter (2002) data #' # data("CarpenterFdaData") #' #' # Load survival package #' # library(survival) #' #' # Run basic model #' # From Keele (2010) replication data #' # M1 <- coxph(Surv(acttime, censor) ~ prevgenx + lethal + deathrt1 + #' # acutediz + hosp01 + pspline(hospdisc, df = 4) + #' # pspline(hhosleng, df = 4) + mandiz01 + femdiz01 + peddiz01 + #' # orphdum + natreg + vandavg3 + wpnoavg3 + #' # pspline(condavg3, df = 4) + pspline(orderent, df = 4) + #'# pspline(stafcder, df = 4), data = CarpenterFdaData) #' #' # Simulate Relative Hazards for orderent #' # Sim1 <- coxsimSpline(M1, bspline = "pspline(stafcder, df = 4)", #' # bdata = CarpenterFdaData$stafcder, #' # qi = "Hazard Ratio", #' # Xj = seq(1100, 1700, by = 10), #' # Xl = seq(1099, 1699, by = 10), spin = TRUE) #' #' ## dontrun #' # Simulate Hazard Rates for orderent #' # Sim2 <- coxsimSpline(M1, bspline = "pspline(orderent, df = 4)", #' # bdata = CarpenterFdaData$orderent, #' # qi = "Hazard Rate", #' # Xj = seq(2, 53, by = 3), #' # nsim = 100) #' #' #' @seealso \code{\link{simGG}}, \code{\link{survival}}, \code{\link{strata}}, and \code{\link{coxph}} #' #' @references <NAME>, "Replication data for: Proportionally Difficult: Testing for Nonproportional Hazards In Cox Models", 2010, \url{http://hdl.handle.net/1902.1/17068} V1 [Version]. #' #' King, Gary, <NAME>, and <NAME>. 2000. ''Making the Most of Statistical Analyses: Improving Interpretation and Presentation.'' American Journal of Political Science 44(2): 347-61. #' #' Liu, Ying, <NAME>, and <NAME>. 2013. ''Simulation-Efficient Shortest Probability Intervals.'' Arvix. \url{http://arxiv.org/pdf/1302.2142v1.pdf}. #' #' @import data.table #' @importFrom stringr word str_match str_replace #' @importFrom reshape2 melt #' @importFrom survival basehaz #' @importFrom MSBVAR rmultnorm #' @export coxsimSpline <- function(obj, bspline, bdata, qi = "Relative Hazard", Xj = 1, Xl = 0, nsim = 1000, ci = 0.95, spin = FALSE) { QI <- NULL # Ensure that qi is valid qiOpts <- c("Relative Hazard", "First Difference", "Hazard Rate", "Hazard Ratio") TestqiOpts <- qi %in% qiOpts if (!isTRUE(TestqiOpts)){ stop("Invalid qi type. qi must be 'Relative Hazard', 'Hazard Rate', 'First Difference', or 'Hazard Ratio'") } if (nsim > 10 & qi == "Hazard Rate"){ message(paste0("Warning: finding Hazard Rates with ", nsim, " simulations may take awhile. Consider decreasing the number of simulations with nsim.")) } if (is.null(Xl) & qi != "Hazard Rate"){ Xl <- rep(0, length(Xj)) message("All Xl set to 0.") } else if (!is.null(Xl) & qi == "Relative Hazard") { Xl <- rep(0, length(Xj)) message("All Xl set to 0.") } # Standardise pspline term with white space around '=' NoSpace1 <- grepl("[^ ]=", bspline) NoSpace2 <- grepl("[^ ]=", bspline) if (any(NoSpace1) | any(NoSpace2)){ stop(paste0("Place a white space before and after equal (=) signs in ", bspline, ".")) } # Find term number TermNum <- names(obj$pterms) bterm <- match(bspline, TermNum) if (is.na(bterm)){ stop(paste0("Unable to find ", bspline, ".")) } # Extract boundary knots for default Boundary.knots = range(x) & number of knots #### Note: these can also be found with get("cbase", environment(obj$printfun[[1]])) # (replace 1 with the spline term number #### From: http://r.789695.n4.nabble.com/help-on-pspline-in-coxph-td3431829.html OA <- obj$assign ListKnots <- OA[bterm] NumKnots <- length(unlist(ListKnots)) KnotIntervals <- levels(cut(bdata, breaks = NumKnots)) # Parameter estimates & Variance/Covariance matrix Coef <- matrix(obj$coefficients) VC <- vcov(obj) # Draw covariate estimates from the multivariate normal distribution Drawn <- rmultnorm(n = nsim, mu = Coef, vmat = VC) DrawnDF <- data.frame(Drawn) dfn <- names(DrawnDF) # Subset data frame to only spline variable coefficients. bword <- word(bspline, 1) b <- str_replace(bword, "pspline\\(", "") b <- str_replace(b, ",", "") NamesLoc <- function(p){ Temp <- paste0("ps.", b, ".", p) match(Temp, dfn) } UpLim <- 2 + NumKnots CoeNum <- as.numeric(3:UpLim) NameCoe <- sapply(CoeNum, NamesLoc, simplify = TRUE) DrawnDF <- data.frame(DrawnDF[, NameCoe]) # Match coefficients to knot interval IntervalStartAbs <- "\\(-?[0-9]*.[0-9]*e?\\+?[0-9]*," IntervalFinishAbs <- ",-?[0-9]*.[0-9]*e?\\+?[0-9]*\\]" IntervalStart <- str_match(KnotIntervals, IntervalStartAbs) IntervalStart <- str_replace(IntervalStart, "\\(", "") IntervalStart <- str_replace(IntervalStart, ",", "") IntervalStart <- as.numeric(IntervalStart) IntervalFinish <- str_match(KnotIntervals, IntervalFinishAbs) IntervalFinish <- str_replace(IntervalFinish, "\\]", "") IntervalFinish <- str_replace(IntervalFinish, ",", "") IntervalFinish <- as.numeric(IntervalFinish) CoefIntervals <- data.frame(names(DrawnDF), IntervalStart, IntervalFinish) names(CoefIntervals) <- c("CoefName", "IntervalStart", "IntervalFinish") # Melt Drawn DF to long format TempDF <- suppressMessages(data.frame(melt(DrawnDF))) names(TempDF) <- c("CoefName", "Coef") # Merge with CoefIntervals CoefIntervalsDT <- data.table(CoefIntervals, key = "CoefName") TempDT <- data.table(TempDF, key = "CoefName") TempCombDT <- TempDT[CoefIntervalsDT] TempDF <- data.frame(TempCombDT) # Merge in fitted X values MergeX <- function(f){ X <- NULL CombinedDF <- data.frame() for (i in f){ Temps <- TempDF Temps$X <- ifelse(TempDF[, 3] < i & i <= TempDF[, 4], i, NA) Temps <- subset(Temps, !is.na(X)) CombinedDF <- rbind(CombinedDF, Temps) } CombinedDF } # Find quantities of interest if (qi == "Relative Hazard" | qi == "Hazard Ratio"){ if (length(Xj) != length(Xl)){ stop("Xj and Xl must be the same length.") } Simbj <- MergeX(Xj) names(Simbj) <- c("CoefName", "Coef", "IntervalStart", "IntervalFinish", "Xj") Simbl <- MergeX(Xl) names(Simbl) <- c("CoefName", "Coef", "IntervalStart", "IntervalFinish", "Xl") if (qi == "Hazard Ratio"){ Xs <- data.frame(Xj, Xl) Simbj <- merge(Simbj, Xs, by = "Xj") Simbj$Comparison <- paste(Simbj$Xj, "vs.", Simbj$Xl) } Simbj$QI <- exp((Simbj$Xj * Simbj$Coef) - (Simbl$Xl * Simbl$Coef)) Simb <- Simbj } else if (qi == "First Difference"){ if (length(Xj) != length(Xl)){ stop("Xj and Xl must be the same length.") } else { Simbj <- MergeX(Xj) names(Simbj) <- c("CoefName", "Coef", "IntervalStart", "IntervalFinish", "Xj") Simbl <- MergeX(Xl) names(Simbl) <- c("CoefName", "Coef", "IntervalStart", "IntervalFinish", "Xl") Xs <- data.frame(Xj, Xl) Simbj <- merge(Simbj, Xs, by = "Xj") Simbj$Comparison <- paste(Simbj$Xj, "vs.", Simbj$Xl) Simbj$QI <- (exp((Simbj$Xj * Simbj$Coef) - (Simbl$Xl * Simbl$Coef)) - 1) * 100 Simb <- Simbj } } else if (qi == "Hazard Rate"){ Xl <- NULL message("Xl is ignored. All variables' values other than b fitted at 0.") Simb <- MergeX(Xj) names(Simb) <- c("CoefName", "Coef", "IntervalStart", "IntervalFinish", "Xj") Simb$HR <- exp(Simb$Xj * Simb$Coef) bfit <- basehaz(obj) ## Currently does not support strata if (!is.null(bfit$strata)){ stop("coxsimSpline currently does not support strata.") } bfit$FakeID <- 1 Simb$FakeID <- 1 bfitDT <- data.table(bfit, key = "FakeID", allow.cartesian = TRUE) SimbDT <- data.table(Simb, key = "FakeID", allow.cartesian = TRUE) SimbCombDT <- SimbDT[bfitDT, allow.cartesian = TRUE] Simb <- data.frame(SimbCombDT) Simb$QI <- Simb$hazard * Simb$HR Simb <- Simb[, -1] } # Drop simulations outside of 'confidence bounds' if (qi != "Hazard Rate"){ SubVar <- "Xj" } else if (qi == "Hazard Rate"){ SubVar <- c("time", "Xj") } if (Inf %in% Simb$QI){ if (isTRUE(spin)){ stop("spin cannot be TRUE when there are infinite values for your quantitiy of interest.") } else { message("Warning infinite values calculated for your quantity of interest. Consider changing the difference between Xj and Xl.") } } SimbPerc <- IntervalConstrict(Simb = Simb, SubVar = SubVar, qi = qi, QI = QI, spin = spin, ci = ci) # Final clean up class(SimbPerc) <- c("simspline", qi) SimbPerc } <file_sep>#' A data set from Golub & Steunenberg (2007) #' #' @docType data #' @source Golub, Jonathan, and <NAME>. 2007. ''How Time Affects EU Decision-Making.'' European Union Politics 8(4): 555-66. #' #' <NAME>, 2011, "Replication data for: Change Comes with Time". \url{http://hdl.handle.net/1902.1/15633}. IQSS Dataverse Network [Distributor] V3 [Version]. #' @keywords datasets #' @format A data set with 3001 observations and 17 variables. #' @name GolubEUPData NULL<file_sep>\docType{data} \name{CarpenterFdaData} \alias{CarpenterFdaData} \title{A data set from Carpenter (2002).} \format{A data set with 408 observations and 32 variables.} \source{ Carpenter, <NAME>. 2002. ''Groups, the Media, Agency Waiting Costs, and FDA Drug Approval.'' American Journal of Political Science 46(3): 490-505. <NAME>, "Replication data for: Proportionally Difficult: Testing for Nonproportional Hazards In Cox Models". \url{http://hdl.handle.net/1902.1/17068}. V1 [Version]. } \description{ A data set from Carpenter (2002). } \keyword{datasets}
826e537c6e7c6b830dbd9c06d8840c748716f70a
[ "Markdown", "R" ]
31
R
chihayakenji/simPH
7cad2c8d50a4e01bc868ad63d7b39c6a8fa39f02
b9e01af20fcd7eff9aacb521996f3647f24d07be
refs/heads/master
<repo_name>FuLingTaiHexiaoke/FirstStep_NewsApp<file_sep>/README.md # FirstStep_NewsApp Just a amazing News App that cloned from SXNews(https://github.com/dsxNiubility/SXNews).So thanks the Creater! #场景转换1 ![%E5%90%84%E7%A7%8D%E9%A1%B5%E9%9D%A2%E8%B7%B3%E8%BD%AC](https://github.com/FuLingTaiHexiaoke/FirstStep_NewsApp/blob/master/Pic/%E5%90%84%E7%A7%8D%E9%A1%B5%E9%9D%A2%E8%B7%B3%E8%BD%AC.gif) #场景转换2 ![%E6%96%B0%E9%97%BB%E6%A8%A1%E5%9D%97%E5%90%84%E9%A1%B5%E9%9D%A2%E8%B7%B3%E8%BD%AC.gif](https://github.com/FuLingTaiHexiaoke/FirstStep_NewsApp/blob/master/Pic/%E6%96%B0%E9%97%BB%E6%A8%A1%E5%9D%97%E5%90%84%E9%A1%B5%E9%9D%A2%E8%B7%B3%E8%BD%AC.gif) #新闻详情场景 ![%E6%96%B0%E9%97%BB%E8%AF%A6%E6%83%85%E9%A1%B5%E9%9D%A2](https://github.com/FuLingTaiHexiaoke/FirstStep_NewsApp/blob/master/Pic/%E6%96%B0%E9%97%BB%E8%AF%A6%E6%83%85%E9%A1%B5%E9%9D%A2.gif) #搜索场景 ![%E6%90%9C%E7%B4%A2%E9%A1%B5%E9%9D%A2](https://github.com/FuLingTaiHexiaoke/FirstStep_NewsApp/blob/master/Pic/%E6%90%9C%E7%B4%A2%E9%A1%B5%E9%9D%A2.gif) #相似主题场景 ![%E7%9B%B8%E4%BC%BC%E4%B8%BB%E9%A2%98%E9%A1%B5%E9%9D%A2](https://github.com/FuLingTaiHexiaoke/FirstStep_NewsApp/blob/master/Pic/%E7%9B%B8%E4%BC%BC%E4%B8%BB%E9%A2%98%E9%A1%B5%E9%9D%A2.gif) #天气场景1 ![%E5%A4%A9%E6%B0%94%E9%A1%B5%E9%9D%A21](https://github.com/FuLingTaiHexiaoke/FirstStep_NewsApp/blob/master/Pic/%E5%A4%A9%E6%B0%94%E9%A1%B5%E9%9D%A21.png) #天气场景2 ![%E5%A4%A9%E6%B0%94%E9%A1%B5%E9%9D%A22](https://github.com/FuLingTaiHexiaoke/FirstStep_NewsApp/blob/master/Pic/%E5%A4%A9%E6%B0%94%E9%A1%B5%E9%9D%A22.png)<file_sep>/NewsApp/SXEasyMacro.h // // SXEasyMacro.h // NewsApp // // Created by kiwi on 16/3/12. // Copyright © 2016年 xiaoke. All rights reserved. // #ifndef SXEasyMacro_h #define SXEasyMacro_h /** 获取硬件信息*/ #define SXSCREEN_H [UIScreen mainScreen].bounds.size.height /** 适配*/ #define SXiPhone4_OR_4s (SXSCREEN_H == 480) /** 获取硬件信息*/ #define SXSCREEN_W [UIScreen mainScreen].bounds.size.width #define SXSCREEN_H [UIScreen mainScreen].bounds.size.height /** 颜色*/ #define SXRGBColor(r,g,b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1] #endif /* SXEasyMacro_h */
89e9bb3b88d07f717c7ddadd3b1c70e924d74f98
[ "Markdown", "C" ]
2
Markdown
FuLingTaiHexiaoke/FirstStep_NewsApp
8fb0d560ee922a8fd89907db6c87b930669ea5c7
70124737acee480d3928c042eeb7c0c0fc30ab6c
refs/heads/master
<file_sep>package at.ohe.numerictextfield; /** * at.ohe.numerictextfield * ShortValidator * 29/04/2018 Oliver * <p> * An implementation of the abstract class {@link NumberValidator} * for the type {@link short} */ class ShortValidator extends NumberValidator { /** * Create an {@link ShortValidator} with the MaxValue and MinValue of an {@link short} */ ShortValidator() { super(Short.MAX_VALUE, Short.MIN_VALUE); } /** * {@inheritDoc} */ @Override public Number getNumber(String s) throws NumberFormatException { return Short.parseShort(s); } } <file_sep>package at.ohe.numerictextfield; import static java.lang.Double.parseDouble; /** * at.ohe.numerictextfield * DoubleValidator * 29/04/2018 Oliver * <p> * An implementation of the abstract class {@link NumberValidator} * for the type {@link double} */ class DoubleValidator extends NumberValidator { /** * Create an DoubleValidator with the MaxValue and MinValue of an double */ DoubleValidator() { super(Double.MAX_VALUE, Double.MIN_VALUE); } /** * {@inheritDoc} */ @Override public Number getNumber(String s) throws NumberFormatException { return parseDouble(s); } } <file_sep>package at.ohe.numerictextfield; /** * at.ohe.numerictextfield * FloatValidator * 29/04/2018 Oliver * <p> * An implementation of the abstract class {@link NumberValidator} * for the type {@link float} */ class FloatValidator extends NumberValidator { /** * Create an FloatValidator with the MaxValue and MinValue of an float */ FloatValidator() { super(Float.MAX_VALUE, Float.MIN_VALUE); } /** * {@inheritDoc} */ @Override public Number getNumber(String s) throws NumberFormatException { return Float.parseFloat(s); } } <file_sep>Do the checklist before filing an issue: ------------------------------------------------------------------ - [ ] Is this something you can **debug and fix**? Send a pull request! Bug fixes and documentation fixes are welcome. - [ ] Have an idea for a feature? Feel free to create an Issue with added 'Feature' Label If its realy an Bug. ------------------------------------------------------------------ Make sure to add **all the information needed to understand the bug** so that I can help. If the info is missing I'll add the 'Needs more information' label and close the issue until there is enough information. - [ ] Provide a **minimal code snippet** example that reproduces the bug. <file_sep>package at.ohe.numerictextfield; /** * at.ohe.numerictextfield * NumberValidator * 29/04/2018 Oliver * <p> * A implementation of the {@link INumberValidator} interface. */ abstract class NumberValidator implements INumberValidator { private double typeMaxValue; private double typeMinValue; /** * Create an Validator with the given type constrains. This constrains * are used to check the parameter in the {@code isValid} method. * * @param typeMaxValue - The maximal value that this type can have * @param typeMinValue - The minimal value that this type can have */ NumberValidator(double typeMaxValue, double typeMinValue) { this.typeMaxValue = typeMaxValue; this.typeMinValue = typeMinValue; } /** * Checks if the given {@link String} is valid. * The max and min Value will be check against the type max and min Value. * If a given value is out of range of this type, the type value will be used. * * @param s - The String that is been checked * @param maxValue - the maximal value that the parsed number allowed to be * @param minValue - the minimal value that the parsed number allowed to be * @return - true if the given String passes all constrain checks and the number is in the given range */ public boolean isValid(String s, double maxValue, double minValue) { maxValue = maxValue > typeMaxValue ? typeMaxValue : maxValue; minValue = minValue < typeMinValue ? typeMinValue : minValue; try { Number number = getNumber(s); if (number.doubleValue() < minValue || number.doubleValue() > maxValue) return false; } catch (NumberFormatException ignore) { return false; } return true; } /** * Parses an String to an {@link Number}. * * @param s - The given String that should be parsed * @return - an {@link Number} that represents the given String value * @throws NumberFormatException - Thrown if the given string couldn't be parsed */ public abstract Number getNumber(String s) throws NumberFormatException; } <file_sep>package at.ohe.numerictextfield; /** * at.ohe.numerictextfield * LongValidator * 29/04/2018 Oliver * <p> * An implementation of the abstract class {@link NumberValidator} * for the type {@link long} */ class LongValidator extends NumberValidator { /** * Create an LongValidator with the MaxValue and MinValue of an long */ LongValidator() { super(Long.MAX_VALUE, Long.MIN_VALUE); } /** * {@inheritDoc} */ @Override public Number getNumber(String s) throws NumberFormatException { return Long.parseLong(s); } } <file_sep># Numeric-TextField ## What is it? The text field is a common JavaFx text field which only allows numbers. It also has a object property for the datatype `Number`. This property reflects the input. This means that if, for example, ten is typed, the `Number` property is changed to 10 immediately afterwards. If the entry is incorrect, the text field is automatically reset to its last state. ## Give it to me! [Download Jar Here](https://github.com/HeilOliver/Numeric-TextField/releases/download/v1.0.0/numeric-textfield-1.0.0.jar) ## How can I use it? There are two different ways to use it. ``` FXML <GridPane fx:controller="sample.Controller" xmlns:fx="http://javafx.com/fxml" alignment="center"> <!-- This NumericTextField converts the input into an integer and limits the values from -10 to 10. --> <NumericTextField type="INTEGER" maxValue="10" minValue="-10"/> </GridPane> ``` ``` Code Behind void foo() { // This NumericTextField converts the input // into an integer and limits the values from -10 to 10. NumericTextField textField = new NumericTextField(-10,10,NumericTextField.NumericType.INTEGER); } ``` ## You want to validate yourself? First we need our own validator. Therefore we implement the `INumberValidator` interface. ``` new INumberValidator() { @Override public boolean isValid(String s, double maxValue, double minValue) { // some Magic here to validate the given string "s" return true; } @Override public Number getNumber(String s) throws NumberFormatException { // here also some magic to parse the string s to an number return null; } } ``` There are two different ways to use your own validator. ``` NumericTextField textField; void foo_UseTheConstructor() { textField = new NumericTextField(-10,10,yourMagicValidator); } void foo_UseTheSetMethod() { textField.setCurrValidator(yourMagicValidator); } ``` ## Bring me to the fancy stuff!! Sorry, at the moment there is nothing fancy or special in there :( But you get a little example: ``` - FXML - <?import at.ohe.numerictextfield.NumericTextField?> <?import javafx.scene.control.Label?> <?import javafx.scene.layout.VBox?> <VBox fx:controller="sample.Controller" xmlns:fx="http://javafx.com/fxml" alignment="center" > <NumericTextField fx:id="inpNumber" type="DOUBLE" maxValue="10" minValue="-10"/> <Label fx:id="lblNumber"/> </VBox> - Controller - import at.ohe.numerictextfield.NumericTextField; import javafx.fxml.FXML; import javafx.scene.control.Label; public class Controller { @FXML private NumericTextField inpNumber; @FXML private Label lblNumber; public void initialize() { inpNumber.numberProperty().addListener(((observable, oldValue, newValue) -> { lblNumber.setText(newValue.toString()); })); } } ``` What's going to happen? If something is entered in the input field, the label displays the corresponding value. If something is entered that cannot be processed, the label retains its value.
cdf5820546c6efb9e4c41b351635480951f6ec78
[ "Markdown", "Java" ]
7
Java
HeilOliver/Numeric-TextField
3b94b40cede41574a93e0683c1a714a8285c734c
381d73ba35bc7e59bd7426c02d73ea85ab7bad2b
refs/heads/master
<file_sep>import numpy as np from activation import Activation class Relu(Activation): @staticmethod def get_instance(activation_name,scope): return Relu(scope) def __init__(self,scope): Activation.__init__(self,scope, 'Relu') def fire(self,Y): ''' Apply the Activations funciton on the input :param Y: input matrix or tensor of size (d,m,n,...) d --> dimension, m,n,... the rest dimension for mini batch or filter or chanels or ... :return: matrix of size Y ''' self.inputcheck(Y,np.ndarray,'numpy ndarray') return np.maximum(Y,0) def gradient(self,Y,backprop): ''' Computing the gradient of relu w.r.t. Y. Note the graident is either 0 or 1 :param Y: input matrix or tensor :return: ''' return backprop * np.sign(self.fire(Y)) # # rel=Relu('Test') # rel.fire(None)<file_sep>from ANNs.ann import NN from Regularizers.l2_reg import * from ANNs.trainer import * from Losses.cross_entropy import * from Minimizers.sgd import * from Minimizers.lrsched import * from datasets.mnist import * from datasets.dataset import * ann=NN('TEST_ANN_For_Test_data',testmode=False) ann.addFCLayer(fan_in_size=5,fan_out_size=5,activation_name='softmax') # ann.add_layerwise_Regularizer(reg=L2_reg(0.0001)) loss=Cross_Entropy() opt_alg=SGD() lr_schd=ConstantLrSched(constant_learning_rate=1e-4) trainer=TestTrainer(ann=ann,loss=loss,opt_alg=opt_alg,lr_sched=lr_schd) # data_set=MNIST('../ds_files/mnist.pkl') data_set=Test_Data_set() test_period=0 X_test,Y_test=data_set.get_train_data() Y_nn=ann.feedforward(X_test) print 'before training:', loss.get_accuracy(Y_test,y_nn=Y_nn) trainer.trian(data_set=data_set,num_itr=20000,mini_batch_size=1) X_test,Y_test=data_set.get_train_data() Y_nn=ann.feedforward(X_test) print 'after training:', loss.get_accuracy(Y_test,y_nn=Y_nn) <file_sep> from Exceptions.error import * class Loss: @staticmethod def get_instance(loss_name): from cross_entropy import * reg_loss = {'cross_entropy': Cross_Entropy} if Loss.reg_loss[loss_name] is None: raise KeyNotExistError('loss list','loss name') return Loss.reg_loss[loss_name].get_instance() def __init__(self,name='General Losses'): self.name=name self.testmode=False def compute_loss(self, y_true, y_nn): return None def get_gradient(self,y_true,y_nn): return None def get_accuracy(self,y_true,y_nn): return None <file_sep>import numpy as np import pickle as pkl from dataset import Data_set ''' MNIST class load the mnist data set and provides methods to access train and test and validation data sets ''' class MNIST(Data_set): def __init__(self,file_path): Data_set.__init__(self,file_path=file_path,name='MNIST') # print self.valid_set[0].shape[0] def load(self,file_path): ''' Converts the label from digit to One_hot vector and separate label and images for test and train :param train_set: :param valid_set: :param test_set: :return: ''' with open(file_path,'rb') as f: ''' Each set is a tuple (Image,Label) Image is batch_size by 784 matrix Label is batch_size by 1 --> digit train_set image size is (50000,784) test_set image size is (10000,784) validation_set size is (10000,784) ''' train_set, valid_set, test_set = pkl.load(f) self.train_set_size=train_set[0].shape[0] self.test_set_size=test_set[0].shape[0] self.valid_set_size=valid_set[0].shape[0] # self.one_hot_conversion_and_separation(train_set, valid_set, test_set) f.close() self.train_label=np.zeros((self.train_set_size,10)) x=[i for i in range(0,self.train_set_size)] self.train_label[np.array(x),train_set[1]]=1 self.train_set_images=train_set[0] self.valid_label=np.zeros((self.valid_set_size,10)) x=[i for i in range(0,self.valid_set_size)] self.valid_label[np.array(x),valid_set[1]]=1 self.valid_set_images=valid_set[0] self.test_label = np.zeros((self.test_set_size, 10)) x = [i for i in range(0, self.test_set_size)] self.test_label[np.array(x), test_set[1]] = 1 self.test_set_images = test_set[0] def get_test_set_size(self): return self.test_set_size def get_train_set_size(self): return self.train_set_size def get_valid_set_size(self): return self.valid_set_size def get_train_data(self): return self.train_set_images.T,self.train_label.T def get_test_data(self): return self.test_set_images.T,self.test_label.T def get_valid_data(self): return self.valid_set_images.T,self.valid_label.T def get_next_batch(self,mini_batch_size=50): ''' Picks #mini_batch_size randomly and pick them and return the corresponding images and labels :param mini_batch_size: the mini batch size :return: ''' if mini_batch_size > self.train_set_size: return self.get_train_data() rind=np.random.randint(0,self.get_train_set_size(),mini_batch_size) # print rind return self.train_set_images[rind,:].T,self.train_label[rind,:].T # # ds=MNIST('../ds_files/mnist.pkl') # x,y=ds.get_next_batch(mini_batch_size=50) # print x.shape # print y.shape<file_sep>import numpy as np from Activations import relu from Exceptions import error from Regularizers import dropout from layer import * class Fc_Layer(Layer): def __init__(self, scope, fan_in, fan_out, activation_function=relu.Relu('Default'), prev_layer=NoneLayer(),keep_prob=1.0): ''' :param scope: scope of this layer in the arch. of NN like layer3 or l3 or fc3 :param dimension: the dimension of weights :param size: # of weights :param activation_function: Activations function, default Relu :param prev_layer: the previous layer this layer is connected too, could be NULL if this is the first layer ''' Layer.__init__(self,scope,'Fully_connected') self.actv_func=activation_function self.fan_out=fan_out self.fan_in=fan_in self.prev_layer=prev_layer self.next_layer=Identity() ''' This dictionary contains all the needed parameters and thier graidents for this layer Each element is a list: the first element is the parameter value the second is parameter gradient the thired is a flag saying if this parameter is trainable or not ''' self.param_grad_dict = {'W':[np.random.normal(np.float64(0),0.01,(fan_out,fan_in),),np.zeros((fan_out,fan_in)),True], 'b':[np.zeros((fan_out,1)),np.zeros((fan_out,1)),True], 'X':[None,None,False]} self.dropout = None self.keep_prob=keep_prob if keep_prob is not 1.0: self.dropout=dropout.Dropout(keep_prob=keep_prob,shape=(fan_out,1)) def getW(self): return self.param_grad_dict['W'][0] def getdW(self): return self.param_grad_dict['W'][1] def getb(self): return self.param_grad_dict['b'][0] def getdb(self): return self.param_grad_dict['b'][1] def getX(self): return self.param_grad_dict['X'][0] def setW(self,newW): self.param_grad_dict['W'][0]=newW def setdW(self,newdW): self.param_grad_dict['W'][1]=newdW def setb(self,newb): self.param_grad_dict['b'][0]=newb def setdb(self,newdb): self.param_grad_dict['b'][1]=newdb def setX(self,newX): self.param_grad_dict['X'][0]=newX def setKeep_prob(self,keep_prob): ''' For test time keep prob should be set to 1 again :param keep_prob: :return: ''' self.keep_prob=keep_prob def feedForward(self,X,**kwargs): ''' Compute the output of this layer and forward it to next layer :param X: datasets matrix which is the form (d,m): d --> dimension and m --> mini_batch size if X does not have the required structure this layer reshape it to required format :return: if it is the last layer it returns this layer's output otherwise it calls the output of next layer ''' if X is None: raise error.LayerInputError(self.name) if self.dropout is not None: self.dropout.update_gates() self.setX(X) if self.testmode: print self.name print 'FeedForward' print 'W_shape' print self.getW().shape print'Input shape' print X.shape print 'linear transform in feedforward' print np.add(np.dot(self.getW(),X),self.getb()) return self.next_layer.feedForward(self.actv_func.fire(np.add(np.dot(self.getW(),X),self.getb()))) def giveOutput(self, input): self.actv_func.fire(np.add(np.dot(self.getW(), input),self.getb())) def get_weight(self):return self.getW() def get_bias(self):return self.getb() def backprop(self,backPropMatrix,**kwargs): ''' This operation compute the backprop operation through this layer it compute gradient w.r.t. W and b and X It saves graidents of W and b but passes griadient w.r.t. X to previous layer if it is not null :param backPropMatrix: The chain rule result from above layers or right layers :) :param kwargs: :return: calls previous layer backprop to compute its graidient ''' if self.getX() is None: raise error.LayerInputError(self.name) # gradient of the output of the active function w.r.t. affine transform multiply to backprop # dimension of Lz is (fan_out,m): fan_out: number of output of this layer and m is mini_batch Lz=self.actv_func.gradient(np.add(np.dot(self.getW(), self.getX()) , self.getb()),backPropMatrix) d,m=Lz.shape # dw is matrix of (fan_out, fan_in) self.setdW(np.dot(Lz,self.getX().T)/np.float32(m)) self.setdb(np.sum(Lz,axis=1).reshape((Lz.shape[0],1))) if self.testmode: print self.name print 'Lz' print Lz print 'W' print self.getW() print 'b' print self.getb() print 'dw' print self.getdW() print 'db' print self.getdb() for reg in self.regList: reg_grad_dict=reg.get_gradient(**{'W':self.getW(),'b':self.getb()}) for k in reg_grad_dict.keys(): (self.param_grad_dict[k])[1]=(self.param_grad_dict[k])[1]+reg_grad_dict[k] self.prev_layer.backprop(np.dot(self.getW().T,Lz)) def get_param_grad_dict(self): return self.param_grad_dict def printParam(self): print 'W,dw\n',self.param_grad_dict['W'] # def update_param(self): # ''' # Should be called to update param after minimization operation # :return: # ''' # self.W=self.grad_dict['W'][0] # self.b = self.grad_dict['b'][0] # <file_sep>import numpy as np class Dropout: ''' This class implement the basic idea of dropout ''' def __init__(self,shape,keep_prob=0.5): ''' Initiate a dropout setting for a given layer :param shape: the shape of binary vector :param keep_prob: the keeping probability or probability of being one ''' self.keep_prob=keep_prob self.shape=shape self.gate_vector=None def get_gates(self): return self.gate_vector def update_gates(self): self.gate_vector=np.sign(np.maximum(np.random.uniform(low=0,high=1,size=self.shape)-self.keep_prob,0)) <file_sep>from Exceptions.error import * from regularizer import Regularizer class L2_reg(Regularizer): def __init__(self,decay_weights): if not isinstance(decay_weights,float): raise ParamTypeError('L2_Regularizer','weight decay','float') self.weight_decay=decay_weights Regularizer.__init__(self,'L2_Regularizer') def get_gradient(self,**kwargs): ''' it return the graident w.r.t. l2 reg for given weights :param kwargs: :return: ''' # for k in kwargs.keys(): # print k if kwargs['W'] is None: raise KeyNotExistError('Parameter of L2_reg','W') # print self.weight_decay # print type(self.weight_decay) # x= # print x return {'W':self.weight_decay*kwargs['W']} def get_weight_decay(self): return self.weight_decay<file_sep>class Data_set: def __init__(self,file_path,name='Data Set'): self.name=name self.load(file_path) def load(self,directory): return None def get_test_set_size(self): return 0 def get_train_set_size(self): return 0 def get_valid_set_size(self): return 0 def get_train_data(self): return None def get_test_data(self): return None def get_valid_data(self): return None def get_next_batch(self, mini_batch_size=50): return None import numpy as np class Test_Data_set(Data_set): def __init__(self, name='Test Data Set'): self.name = name self.train_set_images, self.train_label = np.array( [[1, 1, 1, 0, 0], [1, 2, 1, 0, 0], [1, 0, 3, 0, 0], [1,0,0,4,0], [1, 0, 0, 0, 5]]), \ np.array([[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]) def get_test_set_size(self): return 3 def get_train_set_size(self): return 5 def get_valid_set_size(self): return 2 def get_train_data(self): return self.train_set_images,self.train_label # def get_test_data(self): return np.array([[1,1,1, 1 ,1],[2,2,2,2,2],[3,3,3,3,3],[4,4,4,4,4],[5,5,5,5,5]]),\ # np.array([[1,0,0,0,0],[0,1,0,0,0],[0,0,1,0,0],[0,0,0,1,0],[0,0,0,0,1]]) def get_valid_data(self): return None def get_next_batch(self, mini_batch_size=50): rind=np.random.randint(0,self.get_train_set_size(),mini_batch_size) # print rind return self.train_set_images[rind,:].T,self.train_label[rind,:].T <file_sep>import numpy as np from loss import Loss class Cross_Entropy(Loss): @staticmethod def get_instance(loss_name): return Cross_Entropy() def __init__(self): Loss.__init__(self,'Cross_Entropy') def compute_loss(self,y_true_label,y_nn): ''' Computing the cross entropy between y_truth and y_nn :param y_true_label: is one hot probability vector or matrix of size (d,m): d ---> # of labels and m --> mini bach size :param y_nn: probability vector of size (d,m): d ---> # of labels and m --> mini bach size :return: cross entropy between y_t and y_nn ''' return np.sum(y_true_label*np.log(y_nn),axis=0) def get_gradient(self,y_true_label,y_nn): ''' Computing the gradient of this loss w.r.t. y_nn variables :param y_true_label: is one hot probability vector or matrix of size (d,m): d ---> # of labels and m --> mini bach size :param y_nn: probability vector of size (d,m): d ---> # of labels and m --> mini bach size :return: gradient matrix or vector ''' # print y_nn[:,0] return -(y_true_label*1.0)/y_nn def get_accuracy(self,y_true_label,y_nn): ''' compare the output of the network with true output :param y_true_label: true label, matrix of size (d,m): d # of label and m is mini batch size :param y_nn: nn ouput : matrix of size (d,m): d # of label and m is mini batch size y_nn is one_hot vector in classification case :return: accuracy ''' d,m=np.shape(y_nn) y_nn_max=np.int32(np.divide(np.float64(y_nn),np.max(y_nn,axis=0))) # print y_nn_max return (np.sum(y_true_label*y_nn_max)*100)/np.float32(m) <file_sep>class Regularizer: def __init__(self,name="Regularizer"): self.name=name def get_gradient(self,**kwargs): return {}<file_sep> class Layer: def __init__(self,scope=None,name='general_layer'): self.scope=str(scope) self.name=str(scope)+'_'+str(name) ''' list containing regualizers for this layer ''' self.regList=[] ''' This dictionary contains all the variables and parameters needed for a layer Each element is a list which has 3 elements in it, the parameter, its graideint and a flag to see if it is trainable or not. if it is not trainable its gradient is None ''' self.param_grad_dict = {} # this is for test mode printing in layer functions self.testmode=False def add_reg(self,reg): self.regList.append(reg) ''' return the output of this layer after applying Activations ''' def feedForward(self,X,**kwargs): return None ''' return the drivitive of this layer w.r.t variables and biases ''' def backprop(self,backPropMatrix,**kwargs): return None def giveOutput(self,input): ''' return the output of this layer after applying Activations :param input: input matrix or tensor :return: ''' return input def set_next_layer(self,layer): self.next_layer=layer def get_param_grad_dict(self): return None def printParam(self): print self.param_grad_dict ''' A centiniel layer for the last layer feedforward ''' class Identity(Layer): def feedForward(self,X,**kwargs): return X class NoneLayer(Layer): def __init__(self): self.scope='None' self.name='_'+'None' <file_sep>import numpy as np from Activations.activation import Activation class Sigmoid(Activation): @staticmethod def get_instance(activation_name, scope): return Sigmoid(scope) def __init__(self,scope): Activation.__init__(self,scope,'Sigmoid') def fire(self,Y): self.inputcheck(Y,np.ndarray,'numpy ndarray') return 1.0/(1+np.exp(-Y)) def gradient(self,Y,backprop): a=self.simoid(Y) return a*(1-a) <file_sep>from Exceptions.error import * class Activation(object): @staticmethod def reg_activation(activation_name,activation_class): Activation.reg_ac[activation_name]=activation_class @staticmethod def get_instance(activation_name,scope): from Activations import relu, sigmoid, softmax Activation.reg_ac = {'relu': relu.Relu, 'sigmoid': sigmoid.Sigmoid, 'softmax': softmax.Softmax} if Activation.reg_ac[activation_name] is None: raise KeyNotExistError('Activation List',activation_name) return Activation.reg_ac[activation_name].get_instance(activation_name,scope) def __init__(self,scope,name='general_activation_function'): self.scope=scope self.name=str(scope)+'_'+str(name) self.testmode=False def inputcheck(self,X,type,typestr): ''' Check if the input to this Activations is of the required type :param X: input :param type: class of the required type :param typestr: the string representing the type in order to print in error message :return: ''' if not isinstance(X,type): raise InputTypeError(self.scope, typestr) def fire(self,Y): ''' Apply the Activations funciton on the input :param Y: input matrix or tensor of size (d,m,n,...) d --> dimension, m,n,... the rest dimension for mini batch or filter or chanels or ... :return: matrix of size Y ''' return None def gradient(self,Y,backprop): ''' Computing the gradient of the Activations function w.r.t. Y. :param Y: input matrix or tensor :return: gradient w.r.t. Y ''' return None<file_sep> class LayerInputError(Exception): def __init__(self,layer): Exception.__init__(self,'Error: the input to the layer {0} is None'.format(layer)) class InputTypeError(Exception): def __init__(self,op,type): Exception.__init__(self,'datasets type to the {0} should be numpy {1}'.format(op,type)) # print self.messge class ParamTypeError(Exception): def __init__(self, op_name,param_name ,type_str): Exception.__init__(self, 'The input param \'{0}\' to ' 'function \'{1}\' should be of type \'{}\''.format(param_name,op_name,type_str)) class KeyNotExistError(Exception): def __init__(self,lsit_name,key_str): Exception.__init__(self,'There is no entery for \'{0}\' in \'{1}\''.format(key_str,lsit_name)) class NoneError(Exception): def __init__(self,param_name,place): Exception.__init__(self,'The {0} in the {1} should not be None'.format(param_name,place)) <file_sep>import numpy as np from activation import Activation class Softmax(Activation): @staticmethod def get_instance(activation_name, scope): return Softmax(scope) def __init__(self,scope): Activation.__init__(self,scope,'Softmax') def fire(self,Y): ''' Compute the softmax for Y. Here we can use logsumexp trick to prevent overflow :param Y: is (d,m) Matrix and m is mini_batch size. :return: softmax(Y) ''' self.inputcheck(Y,np.ndarray,'numpy ndarray') Ymax=np.max(Y,axis=0) return np.exp(Y-Ymax-np.log(np.sum(np.exp(Y-Ymax),axis=0))) def gradient(self,Y,backprop): ''' :param Y: matrix of (d,m)- d: # of output, m: mini_batch size :param backprop: back_prop from previous layer :return: gradient w.r.t. these ouput layers ''' # a=self.simoid(Y) # return a*(1-a) pz=self.fire(Y) # print 'pz is\n',pz # print 'backprop from loss\n',backprop # print 'gradient\n',pz*(backprop-np.sum(backprop*pz,axis=0)) return pz*(backprop-np.sum(backprop*pz,axis=0)) <file_sep>class LrSched: def __init__(self,name='Lr Scheduler',initial_learning_rate=1e-3): self.name=name self.lr = initial_learning_rate def get_lr(self,itr): ''' return the correct learning rate for the given iteration :param itr: :return: ''' return self.lr class ConstantLrSched(LrSched): def __init__(self,initial_learning_rate=0.0001): LrSched.__init__(self,name='Constant_lr_Schedule',initial_learning_rate=initial_learning_rate) def get_lr(self,itr): return self.lr class Grad_Reduce_LrSched(LrSched): def __init__(self,red_period=1,red_coef=0.5,initial_learning_rate=1e-3): LrSched.__init__(self,'Diminishing_lr_Schedule') self.red_period=red_period self.red_coef=red_coef self.lr=initial_learning_rate def get_lr(self,itr): if itr is not 0 and itr%self.red_period is 0: self.lr*=self.red_coef return self.lr <file_sep>import numpy as np from minimizer import * class SGD(Minimizer): def __init__(self): Minimizer.__init__(self,'SGD') def minimize(self,var_grad_dict,lr): ''' Do the SGD update :param var: variable needs to be updated :param grad: the gradient of objective function w.r.t. var :param lr: learning rate :return: ''' for k in var_grad_dict.keys(): if var_grad_dict[k][2]: (var_grad_dict[k])[0]=(var_grad_dict[k])[0]-lr*((var_grad_dict[k])[1]) <file_sep>from Activations.activation import Activation from Exceptions.error import * from Layers.fully_connected import Fc_Layer as fcl from Layers.layer import * from Regularizers.regularizer import Regularizer class NN: def __init__(self,name='ANNs',testmode=False): self.name=name self.firstLayer=NoneLayer() self.lastLayer=NoneLayer() self.layercounter=0 self.layers={} self.testmode=testmode def addFCLayer(self,fan_in_size=None,fan_out_size=None,activation_name=None): ''' Add a FC to the last layer :param fan_in_size: it needed just for the first layer :param fan_out_size: :param activation_name: registered name for an activation :return: ''' if isinstance(self.firstLayer,NoneLayer): # print 'first layer is added' if fan_in_size is None: raise NoneError('fan in size','first layer of NN') fcli=fcl(self.layercounter,fan_in_size,fan_out=fan_out_size ,activation_function=Activation.get_instance(activation_name,self.layercounter)) fcli.testmode=self.testmode self.lastLayer=fcli self.firstLayer=fcli self.layers[self.layercounter]=fcli else: fan_in=self.lastLayer.fan_out fcli = fcl(self.layercounter, fan_in, fan_out=fan_out_size ,activation_function=Activation.get_instance(activation_name, self.layercounter) ,prev_layer=self.lastLayer) fcli.testmode = self.testmode self.lastLayer.set_next_layer(fcli) self.lastLayer = fcli self.layers[self.layercounter] = fcli self.layercounter+=1 def add_layerwise_Regularizer(self,reg=Regularizer): for layer in self.layers.values(): layer.add_reg(reg) def feedforward(self,X): self.y_nn=self.firstLayer.feedForward(X) return self.y_nn # def addLoss(self,loss_name): # self.loss=loss.Loss.get_instance(loss_name) def backProp(self,Ly): ''' backProp over the network First it does a FF to compute y_nn and then backProp :param y_true: grand truth could be a matrix of size (d,m), m is mini_batch size :param X: input data :return: ''' # self.feedforward(X) # Ly=self.loss.get_gradient(y_true,self.y_nn) self.lastLayer.backprop(Ly) <file_sep>from Losses.loss import * from Losses.cross_entropy import * from ann import NN from Minimizers import sgd,lrsched import time ''' This class gets a neural net and loss function and an optimization algorithm and run training ''' class Trainer: def __init__(self,ann=NN(),loss=Loss,opt_alg=sgd.SGD,lr_sched=lrsched.ConstantLrSched): self.name='Trainer' self.ann=ann self.loss=loss self.opt_alg=opt_alg self.lrschd=lr_sched self.train_accuracy=[] self.valid_accuracy=[] self.test_accuracy=[] def trian(self,data_set,num_epoch,mini_batch_size, train_accuracy_report_period=0, valid_accuracy_report_period=0,test_accuracy_report_period=0): dss=data_set.get_train_set_size() if mini_batch_size > dss: mini_batch_size=dss for epoch in range(num_epoch): btime=time.time() print 'epoch :',epoch, for itrpe in range(np.int32(dss/mini_batch_size)): # Getting batch of data X,Y=data_set.get_next_batch(mini_batch_size=mini_batch_size) # do feedforward and compute the network output y_nn=self.ann.feedforward(X) # compute the graident of loss function w.r.t. to the output of network Ly = self.loss.get_gradient(Y,y_nn) # start backprop in the network with the graident vector w.r.t. network output self.ann.backProp(Ly) # Could be parallelized for key in self.ann.layers.keys(): layer=self.ann.layers[key] self.opt_alg.minimize(layer.get_param_grad_dict(),self.lrschd.get_lr(epoch*dss+itrpe)) # layer.update_param() self.acuracy_report(train_accuracy_report_period,X,Y,epoch,self.train_accuracy) self.acuracy_report(test_accuracy_report_period,(data_set.get_test_data())[0] ,(data_set.get_test_data())[1],epoch,self.test_accuracy) self.acuracy_report(valid_accuracy_report_period,(data_set.get_valid_data())[0] ,(data_set.get_valid_data())[1],epoch,self.valid_accuracy) etime=time.time() print 'length=',etime-btime return self.train_accuracy,self.valid_accuracy,self.test_accuracy def acuracy_report(self,period,data_set_x,data_set_label,epoch,report_list): if period is not 0: if (epoch+1) % period == 0: y_nn=self.ann.feedforward(data_set_x) report_list.append(self.loss.get_accuracy(data_set_label,y_nn)) class TestTrainer: def __init__(self,ann=NN(),loss=Loss,opt_alg=sgd.SGD,lr_sched=lrsched.ConstantLrSched): self.name='Trainer' self.ann=ann self.loss=loss self.opt_alg=opt_alg self.lrschd=lr_sched self.train_accuracy=[] self.valid_accuracy=[] self.test_accuracy=[] def trian(self,data_set,num_itr,mini_batch_size): dss=data_set.get_train_set_size() if mini_batch_size > dss: mini_batch_size=dss for epoch in range(num_itr): print 'itr :',epoch # Getting batch of data X,Y=data_set.get_next_batch(mini_batch_size=mini_batch_size) # print 'X' # print X y_nn=self.ann.feedforward(X) # compute the graident of loss function w.r.t. to the output of network # print 'y_nn is:' # print y_nn # for key in self.ann.layers.keys(): # layer=self.ann.layers[key] # layer.printParam() Ly = self.loss.get_gradient(Y,y_nn) # print 'loss of label' # print Ly # start backprop in the network with the graident vector w.r.t. network output self.ann.backProp(Ly) # Could be parallelized for key in self.ann.layers.keys(): layer=self.ann.layers[key] self.opt_alg.minimize(layer.get_param_grad_dict(),self.lrschd.get_lr(epoch)) # layer.printParam() <file_sep>from ANNs.ann import NN from Regularizers.l2_reg import * from ANNs.trainer import * from Losses.cross_entropy import * from Minimizers.sgd import * from Minimizers.lrsched import * from datasets.mnist import * from datasets.dataset import * ann=NN('TEST_ANN_For_MNIST',testmode=False) ann.addFCLayer(fan_in_size=784,fan_out_size=1024,activation_name='relu') ann.addFCLayer(fan_out_size=512,activation_name='relu') ann.addFCLayer(fan_out_size=256,activation_name='relu') ann.addFCLayer(fan_out_size=10,activation_name='softmax') ann.add_layerwise_Regularizer(reg=L2_reg(0.00001)) loss=Cross_Entropy() opt_alg=SGD() # lr_schd=Grad_Reduce_LrSched(red_coef=0.5,red_period=1000,initial_lr=5e-2) lr_schd=ConstantLrSched(initial_learning_rate=1e-2) trainer=Trainer(ann=ann,loss=loss,opt_alg=opt_alg,lr_sched=lr_schd) data_set=MNIST('../ds_files/mnist.pkl') X_test,Y_test=data_set.get_test_data() Y_nn=ann.feedforward(X_test) print 'before training:', loss.get_accuracy(Y_test,y_nn=Y_nn) test_period=10 lists=trainer.trian(data_set=data_set,num_epoch=100,mini_batch_size=150,train_accuracy_report_period=test_period, test_accuracy_report_period=test_period,valid_accuracy_report_period=test_period) X_test,Y_test=data_set.get_test_data() Y_nn=ann.feedforward(X_test) print 'after training:',loss.get_accuracy(Y_test,y_nn=Y_nn) print lists<file_sep> class Minimizer: def __init__(self,name="General_Optimizer"): self.name=name def minimize(self,var_grad_dict,lr,**kwargs): return None
cf3ca76819fe61d0866b507234d984a683119dd0
[ "Python" ]
21
Python
R3za/NeuralNetwork
ed7ce609f8884ccfc5e744ae4e1a0b8415f47592
3a73921711ce2ebe8a05f4eb5b93e01cdd839f09
refs/heads/master
<repo_name>Cool-Dude-x/image-resize-bot<file_sep>/README.md # image-resize-bot Telegram bot that resizes images for sides to be at most 512px maintaining aspect ratio. ## Usage * Clone the repo * `cp docker.sample.env docker.env` and edit docker.env * Run `docker-compose up` <file_sep>/main.py #!/usr/bin/env python from collections import deque import os from PIL import Image import requests import sys import telepot import time handled_updates = [] try: BOT_TOKEN = os.environ['BOT_TOKEN'] except KeyError: BOT_TOKEN = sys.argv[1] endpoint = f'https://api.telegram.org/bot{BOT_TOKEN}' file_endpoint = f'https://api.telegram.org/file/bot{BOT_TOKEN}' def inc_uses(): try: with open("uses.txt") as f: uses = int(f.read().split("\n")[0].strip()) except: uses = 0 with open("uses.txt", "w") as f: f.write(str(uses+1)) def resize_image(path): img = Image.open(path) ratio = 512/max(img.size) new_size = (int(img.size[0]*ratio), int(img.size[1]*ratio)) img = img.resize(new_size, Image.ANTIALIAS) img.save(path + ".png", "png") return path + ".png" def chat_handler(msg): msg_type, chat_type, chat_id = telepot.glance(msg) if "reply_to_message" in msg and "/crop" in msg["text"]: msg = msg["reply_to_message"] msg_type, chat_type, chat_id = telepot.glance(msg) elif not msg_type in ["document", "photo"]: return # Handle compressed/uncompressed images if msg_type == "document": if msg["document"]["mime_type"] in ["image/png", "image/jpeg"]: file_id = msg["document"]["file_id"] else: return elif msg_type == "photo": file_id = msg["photo"][-1]["file_id"] else: return file_path = "downloads/" + bot.getFile(file_id)["file_path"].split("/")[1] # Download file bot.download_file(file_id, file_path) # Resize and send file new_file_path = resize_image(file_path) with open(new_file_path, "rb") as f: bot.sendDocument(chat_id, f) inc_uses() # Clean up working directory os.remove(file_path) os.remove(new_file_path) if __name__ == "__main__": if not os.path.exists("downloads"): os.makedirs("downloads") # Instantiate bot bot = telepot.Bot(BOT_TOKEN) # New message listener bot.message_loop({'chat' : chat_handler}, run_forever="Bot Running...") <file_sep>/Dockerfile FROM python:3.6-alpine LABEL maintainer "<NAME> <<EMAIL>>" RUN mkdir /app COPY . /app WORKDIR /app RUN pip install pipenv RUN pipenv install --deploy --ignore-pipfile <file_sep>/docker-compose.yaml version: "3" services: bot: build: . env_file: docker.env command: pipenv run python -u main.py # -u allows for debugging in stdout volumes: - .:/app restart: always
e835327c0fd274152f3fe01afff456010871aa34
[ "Markdown", "Python", "Dockerfile", "YAML" ]
4
Markdown
Cool-Dude-x/image-resize-bot
05af9e33331feeadcdc89afe590dce0e1419128a
77d390eabaa113cfc79782a663c267ee0b8f2516
refs/heads/master
<repo_name>stefan-dhi/PhpTextFilters<file_sep>/src/TitleCaseShort.php <?php /** * selective text case converter * less than max. words: Title Case * longer than max. words: Sentence case */ namespace PhpTextFilters; class TitleCaseShort extends Base { protected $options = ['maxWords' => 6]; public function run($txt) { if (str_word_count($txt) <= $this->options['maxWords']) { return $this->mbUcWordsUnlessUc($txt); } return $this->mbUcFirst($txt); } /** * uppercase the first letter in each word unless the word is all uppercase or MixedCASE * supports multibyte alphabet * @param $txt * @return string */ protected function mbUcWordsUnlessUc($txt) { $arr = explode(' ', $txt); foreach ($arr as &$ww) { if (preg_match('@^[[:lower:]]+$@u', $ww)) { $ww = mb_convert_case($ww, MB_CASE_TITLE, 'UTF-8'); } } return implode(' ', $arr); } /** * multibyte-safe ucfirst * @return string * @param $txt */ protected function mbUcFirst($txt) { return mb_strtoupper(mb_substr($txt, 0, 1)) . mb_substr($txt, 1); } } <file_sep>/src/Length.php <?php namespace PhpTextFilters; class Length extends Base { protected $options = [ 'min' => 0, // min. length 'max' => 100, // max. length 'breakWords' => false // if false, attempt to not cut through words - does not work well if text contains extremely long words ]; /** * @inheritdoc */ public function run($txt) { $txt = trim($txt); if (strlen($txt) < $this->options['min']) { // TODO - not sure what should happen if text is too short? return ''; } if (strlen($txt) <= $this->options['max']) { return $txt; } if ($this->options['breakWords']) { // cut through the middle of a word to get to exactly max. characters return mb_substr($txt, 0, $this->options['max']); } // try to cut at a natural word boundary return self::truncate($txt, $this->options['max']); } /** * @param string $txt * @param int $len * @return string */ protected static function truncate($txt, $len) { $txt = rtrim($txt); $words = explode(' ', $txt); $txt = ''; $actual = ''; foreach ($words as $ii => $word) { if (mb_strlen($actual . $word) <= $len) { $actual .= $word . ' '; } else { if ($ii == 0) { // first word is already longer than the limit... return mb_substr($word, 0, $len); } if ($actual != '') { $txt .= rtrim($actual); } $actual = $word; $actual .= ' '; } } return trim($txt); } } <file_sep>/src/PrefixPostfix.php <?php namespace PhpTextFilters; class PrefixPostfix extends Base { protected $options = [ 'prefix' => '', 'postfix' => '' ]; public function run($txt) { return $this->options['prefix'] . $txt . $this->options['postfix']; } } <file_sep>/src/Base.php <?php namespace PhpTextFilters; abstract class Base { /** * @var array */ protected $options = []; /** * Base constructor. * @param array $options */ public function __construct($options = []) { $this->options = array_merge($this->options, $options); } /** * Run the filter on a string. * @param string $txt * @return string */ abstract public function run($txt); } <file_sep>/tests/test.php <?php require_once __DIR__ . '/../vendor/autoload.php'; use PhpTextFilters\HtmlEntities; use PhpTextFilters\PrefixPostfix; use PhpTextFilters\Length; use PhpTextFilters\RegexReplace; use PhpTextFilters\TitleCaseShort; $text = 'Umlaut Ä - Alpha α - Quote " - Pound £ - Russian Ж - Brace ( - SQuote \' - Tick `'; $fHtml = new HtmlEntities(); $fPref = new PrefixPostfix( [ 'prefix' => '<< ', 'postfix' => ' >>' ] ); $fTitle = new TitleCaseShort([ 'maxWords' => 4 ]); $fRegex = new RegexReplace(); $fLength = new Length(['max' => 25]); print_r( [ // should encode various special characters as HTML entities 'html' => $fHtml->run($text), // should wrap into pairs of pointy brackets 'prefix' => $fPref->run('hello world'), // should replace all characters except letter & numbers 'regex' => $fRegex->run('Hi! This will be $300.'), // should titlecase all words except USA 'title1' => $fTitle->run('hello from the USA'), // should uppercase the first letter 'title2' => $fTitle->run('łorem ipsum dolor amet unicum est.'), // should cut on word boundary below 25 char 'length1' => $fLength->run('łorem ipsum dolor amet unicum est.'), // should cut after 'y' 'length2' => $fLength->run('abcdefghijklmnopqrstuvwxyz'), ] ); <file_sep>/src/HtmlEntities.php <?php namespace PhpTextFilters; class HtmlEntities extends Base { /** * @var array */ protected static $transTable = []; /** * @inheritdoc */ protected $options = [ 'htmlVersion' => 'HTML4', 'numeric' => false // use XML-type numeric entity references? ]; /** * @var string */ protected $htmlVersion; /** * @inheritdoc */ public function __construct(array $options = []) { parent::__construct($options); $this->versionToConst(); if ($this->options['numeric']) { self::$transTable = self::buildTransTable($this->htmlVersion); } } /** * @inheritdoc */ public function run($txt) { $txt = htmlentities($txt, ENT_COMPAT | $this->htmlVersion, 'UTF-8', false); if ($this->options['numeric']) { $txt = str_replace(array_keys(self::$transTable), self::$transTable, $txt); } return $txt; } /** * assigns the appropriate PHP constant * @throws \InvalidArgumentException */ protected function versionToConst() { switch ($this->options['htmlVersion']) { case 'HTML4': // this seems to work best $v = ENT_HTML401; break; case 'HTML5': // ENT_HTML5 converts all sorts of useless stuff like commas, brackets and full stops $v = ENT_HTML5; break; case 'XML': $v = ENT_XML1; break; case 'XHTML': $v = ENT_XHTML; break; default: throw new \InvalidArgumentException('Unsupported HTML version option: ' . $str); } $this->htmlVersion = $v; } /** * build a translation table that maps HTML entity references (e.g. &alpha; or &trade;) * to their numeric equivalent (e.g. &#0945; or &#8482;) * @param int $vv * @return array */ protected static function buildTransTable($vv) { $tt = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES | $vv); $qq = []; foreach ($tt as $kk => $vv) { $k0 = mb_convert_encoding($kk, 'UCS-2LE', 'UTF-8'); $k1 = ord(substr($k0, 0, 1)); $k2 = ord(substr($k0, 1, 1)); $qq[$vv] = '&#' . sprintf('%04d',$k2 * 256 + $k1) . ';'; } unset($tt); return $qq; } } <file_sep>/src/RegexReplace.php <?php namespace PhpTextFilters; class RegexReplace extends Base { protected $options = ['pattern' => '@[^[:alnum:]]@ui', 'replacement' => '']; public function run($txt) { return preg_replace($this->options['pattern'], $this->options['replacement'], $txt); } } <file_sep>/README.md # PhpTextFilters as set of simple text filters
3f8fff4e20aa04ba9f3ebd49fb725c970a50a8c7
[ "Markdown", "PHP" ]
8
PHP
stefan-dhi/PhpTextFilters
d0b5dfb98e4932c3fad440144bc7c454acdfcc5a
a9f9585bb938298cb72acea22342999195048e90
refs/heads/master
<file_sep>package com.webtestautomationjava.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.PageFactory; public class LoginPage extends Base { @FindBy(how = How.ID, using = "user_login") public WebElement userNameField; @FindBy(how = How.ID, using = "user_pass") public WebElement passwordField; @FindBy(how = How.ID, using = "rememberme") public WebElement rememberMeRadio; @FindBy(how = How.ID, using = "wp-submit") public WebElement loginButton; public LoginPage(WebDriver webDriver) { driver = webDriver; PageFactory.initElements(driver, this); } @Override protected void load() { driver.get(baseUrl + "/login"); } @Override protected void isLoaded() throws Error { if (!driver.getTitle().contentEquals("WordPress.com › Log In")) { throw new Error("Title was not 'WordPress.com › Log In' it was " + driver.getTitle()); } } public void loginWith(String userName, String password) { userNameField.sendKeys(userName); passwordField.sendKeys(<PASSWORD>); loginButton.click(); } } <file_sep>package com.webtestautomationjava.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.PageFactory; public class HomePage extends Base { @FindBy(how = How.ID, using = "wpbody-content") public WebElement wpbodyContent; public HomePage(WebDriver webDriver) { driver = webDriver; PageFactory.initElements(driver, this); } @Override protected void isLoaded() throws Error { if (!driver.getTitle().contentEquals("Dashboard ‹ " + getProperty.Config().getProperty("homePage.name") + " — WordPress")) { throw new Error("Title was not 'Dashboard ‹ " + getProperty.Config().getProperty("homePage.name") + " — WordPress' it was " + driver.getTitle()); } } } <file_sep>package com.webtestautomationjava.webdriver.cucumber; import cucumber.api.junit.Cucumber; import org.junit.runner.RunWith; @RunWith(Cucumber.class) @Cucumber.Options(features = "src/test/resources/features/", tags = {"@selenium"}, format = {"html:target/cucumber-report/selenium"}) public class SearchAT { } <file_sep>baseUrl=https://wordpress.com testUsername=<EMAIL> testPassword=<PASSWORD> homePage.name=infoatrubygemtsl<file_sep>package com.webtestautomationjava.pages; import com.webtestautomationjava.utils.ReadPropertiesFile; import com.webtestautomationjava.manager.junit.Driver; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.LoadableComponent; import org.openqa.selenium.support.ui.WebDriverWait; public class Base extends LoadableComponent<Base> { WebDriver driver = Driver.get(); WebDriverWait wait = new WebDriverWait(driver,10); public static ReadPropertiesFile getProperty = new ReadPropertiesFile(); String baseUrl = getProperty.Config().getProperty("baseUrl"); @Override protected void load() { } @Override protected void isLoaded() throws Error { } } <file_sep>package com.webtestautomationjava.manager.junit; import org.openqa.selenium.WebDriver; public class Driver extends Thread { private static WebDriver selectedDriver = null; public static final String BROWSER = "browser"; public static WebDriver get() { String browserToUse = ""; if (System.getProperties().containsKey(BROWSER)) { browserToUse = System.getProperty(BROWSER); } if (selectedDriver == null) { switch (browserToUse) { case "firefox": selectedDriver = DriverManager.createFirefoxDriver(); return selectedDriver; case "htmlunit": selectedDriver = DriverManager.createHtmlUnitDriver(); return selectedDriver; case "chrome": selectedDriver = DriverManager.createChromeDriver(); return selectedDriver; case "iphone5s": selectedDriver = DriverManager.createIphone5Driver(); return selectedDriver; case "ipadair": selectedDriver = DriverManager.createIPadAirDriver(); return selectedDriver; case "nexus7": selectedDriver = DriverManager.createAndroidNexus7Driver(); return selectedDriver; default: selectedDriver = DriverManager.createFirefoxDriver(); return selectedDriver; } } System.out.println("Test to be executed using " + browserToUse.toUpperCase()); return selectedDriver; } } <file_sep>package com.webtestautomationjava.utils; import java.io.InputStream; import java.util.Properties; public class Message { private static final Properties locators; static { locators = new Properties(); InputStream is = Message.class.getResourceAsStream("/environment.properties"); try { locators.load(is); } catch (Exception e) { System.out.println(e.getMessage()); } } public static String getMessage(String locatorName) { return locators.getProperty(locatorName); } }<file_sep># test-automation-java ready made Java based test automation suite for Desktop, Mobile and Tablet Web based appilcations.
92aa34e2bc80b81486712c6c6b21c42bf46a9f91
[ "Markdown", "Java", "INI" ]
8
Java
RubyGemTSL/test-automation-java
328b79837080cff7c411b1379c6738daa53323ea
609230bf667a26d4bd7181c3b60c468ba4f1012a
refs/heads/master
<file_sep><?php /** * @package Vertice_Subscribe * @version 1.0.0 */ /* Plugin Name: Vertice Subscribe Plugin URI: http://vertice.com/plugins/vt-subscribe/ Description: Create a popup subscribe form and integrate it with mailchimp API. Author: <NAME> Version: 1.0.0 Author URI: http://vertice.com */ // Make sure we don't expose any info if called directly if ( !function_exists( 'add_action' ) ) { echo 'Hi there! I\'m just a plugin, not much I can do when called directly.'; exit; } define( 'VT_SUBSCRIBE_VERSION', '1.0.0' ); define( 'VT_SUBSCRIBE__MINIMUM_WP_VERSION', '4.0' ); define( 'VT_SUBSCRIBE__PLUGIN_DIR', plugin_dir_path( __FILE__ ) ); global $vt_subscribe_version; $vt_subscribe_version = '1.0'; /** * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook() * @static */ function plugin_activation() { if ( version_compare( $GLOBALS['wp_version'], VT_SUBSCRIBE__MINIMUM_WP_VERSION, '<' ) ) { load_plugin_textdomain( 'vtsubscribe' ); $message = '<strong>'.sprintf(esc_html__( 'Vertice Subscribe %s requires WordPress %s or higher.' , 'vtsubscribe' ), VT_SUBSCRIBE_VERSION, VT_SUBSCRIBE__MINIMUM_WP_VERSION ).'</strong> '.sprintf(__('Please <a href="%1$s">upgrade WordPress</a> to a current version.', 'vtsubscribe'), 'https://codex.wordpress.org/Upgrading_WordPress'); wp_die($message); exit; } global $wpdb; global $vt_subscribe_version; $table_name = $wpdb->prefix . 'vt_subscribe'; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE IF NOT EXISTS $table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, email tinytext NOT NULL, subscribe_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id) ) $charset_collate;"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); add_option( 'vt_subscribe_version', $vt_subscribe_version ); } /** * Removes all connection options * @static */ function plugin_deactivation( ) { } function vt_subscribe_register_settings() { add_option( 'vt_subscribe_username', ''); add_option( 'vt_subscribe_api_key', ''); add_option( 'vt_subscribe_data_center', ''); add_option( 'vt_subscribe_audience_id', ''); add_option( 'vt_subscribe_title_popup', ''); add_option( 'vt_subscribe_description_popup', ''); register_setting( 'vt_subscribe_options_group', 'vt_subscribe_username' ); register_setting( 'vt_subscribe_options_group', 'vt_subscribe_description_popup' ); register_setting( 'vt_subscribe_options_group', 'vt_subscribe_title_popup' ); register_setting( 'vt_subscribe_options_group', 'vt_subscribe_api_key' ); register_setting( 'vt_subscribe_options_group', 'vt_subscribe_data_center' ); register_setting( 'vt_subscribe_options_group', 'vt_subscribe_audience_id' ); } function vt_subscribe_register_options_page() { add_options_page('Vertice Subscribe Setting', 'VT Subscribe', 'manage_options', 'vtsubscribe', 'vt_subscribe_options_page'); } function vt_subscribe_options_page() { ?> <div class="wrap"> <h1 class="wp-heading-inline">Vertice Subscribe Setting</h1> <hr> <form method="post" action="options.php"> <?php settings_fields( 'vt_subscribe_options_group' ); ?> <h4>Text pop up display</h4> <table class="form-table"> <tr valign="top"> <th scope="row"><label for="vt_subscribe_title_popup">Title Popup</label></th> <td> <input class="regular-text" type="text" id="vt_subscribe_title_popup" name="vt_subscribe_title_popup" value="<?php echo get_option('vt_subscribe_title_popup'); ?>" /> </td> </tr> <tr valign="top"> <th scope="row"><label for="vt_subscribe_description_popup">Description Popup</label></th> <td> <input class="regular-text" type="text" id="vt_subscribe_description_popup" name="vt_subscribe_description_popup" value="<?php echo get_option('vt_subscribe_description_popup'); ?>" /> </td> </tr> </table> <hr> <h4>Setting required informations for Mailchimp API 3.0</h4> <table class="form-table"> <tr valign="top"> <th scope="row"><label for="vt_subscribe_username">Mailchimp Username</label></th> <td> <input class="regular-text" type="text" id="vt_subscribe_username" name="vt_subscribe_username" value="<?php echo get_option('vt_subscribe_username'); ?>" /> <p>Can be found on your mailchimp profile setting</p> </td> </tr> <tr valign="top"> <th scope="row"><label for="vt_subscribe_api_key">Mailchimp API Key</label></th> <td> <input class="regular-text" type="text" id="vt_subscribe_api_key" name="vt_subscribe_api_key" value="<?php echo get_option('vt_subscribe_api_key'); ?>" /> <p>API Key without <b>-data_center</b> eg: 0192213daf13-us6 | <b>no need -us6</b> <br> Read more about <a href="https://mailchimp.com/help/about-api-keys" target="_blank">API Keys</a></p> </td> </tr> <tr valign="top"> <th scope="row"><label for="vt_subscribe_data_center">Data Center</label></th> <td> <input class="regular-text" type="text" id="vt_subscribe_data_center" name="vt_subscribe_data_center" value="<?php echo get_option('vt_subscribe_data_center'); ?>" /> <p>Subdomain URL from your mailchimp account. eg: https://<b>us3</b>.admin.mailchimp.com/ | <b>us3</b> is the data center</p> </td> </tr> <tr valign="top"> <th scope="row"><label for="vt_subscribe_audience_id">Audience ID</label></th> <td> <input class="regular-text" type="text" id="vt_subscribe_audience_id" name="vt_subscribe_audience_id" value="<?php echo get_option('vt_subscribe_audience_id'); ?>" /> <p>How to know your <a target="_blank" href="https://mailchimp.com/help/find-audience-id/">Audience ID</a></p> </td> </tr> </table> <hr> <?php submit_button(); ?> </form> </div> <?php } function vtsubscribe_init() { // wp_die(wp_get_current_user()->ID); if ( ! is_admin() ) { add_action('wp_enqueue_scripts', 'vtsubscribe_enqueue_script'); add_action( 'wp_footer', 'popup_subscribe', 100 ); } add_action( 'admin_init', 'vt_subscribe_register_settings' ); add_action('admin_menu', 'vt_subscribe_register_options_page'); } function vtsubscribe_enqueue_script() { wp_register_script( 'vt-subscribe-script', plugins_url( 'vt-subscribe/assets/js/vt-subscribe.js' ), array('jquery'), '1.0.3', true ); wp_enqueue_script( 'vt-subscribe-script' ); wp_register_style( 'vt-subscribe-style', plugins_url( 'vt-subscribe/assets/css/vt-subscribe.css' ), array(), '1.0.4', 'all' ); wp_enqueue_style( 'vt-subscribe-style' ); $jsData = [ 'ajax_url' => admin_url( 'admin-ajax.php' ), 'logged_in' => (wp_get_current_user()->ID > 0) ? 1 : 0, 'ajax_nonce' => wp_create_nonce('vt_subscribe_nonce') ]; wp_localize_script( 'vt-subscribe-script', 'vtJsData', $jsData ); } function popup_subscribe() { $title = get_option('vt_subscribe_title_popup'); $desc = get_option('vt_subscribe_description_popup'); $popup = '<div id="popup-vt-subscribe" class="overlay"> <div class="popup"> <a class="close popup-vt-subscribe-close" href="javascript:void(0)">&times;</a> <div id="dialog" class="window"> <div class="box"> <div class="newletter-title"> <h2>' . $title . '</h2> </div> <div class="box-content newleter-content"> <label>' . $desc . '</label> <div id="frm_subscribe"> <form name="subscribe" id="vt_subscribe_popup_form"> <div> <!-- <span class="required">*</span><span>Email</span>--> <input placeholder="<EMAIL>" type="email" value="" name="email_field" id="popup-vt-subscribe-email"> <div id="popup-vt-subscribe-notification"></div> <button type="submit" disabled id="vt_subscribe_popup_btn" class="button"><span>Submit</span></button> </div> </form> </div> <!-- /#frm_subscribe --> </div> <!-- /.box-content --> </div> </div> </div> </div>'; echo $popup; // return $content.$popup; // return 'AAA'; } function vt_subscribe() { check_ajax_referer( 'vt_subscribe_nonce', 'security' ); $email = urldecode($_POST['email']); $api_username = get_option('vt_subscribe_username'); $api_key = get_option('vt_subscribe_api_key');https: $url = 'https://' . get_option('vt_subscribe_data_center') . '.api.mailchimp.com/3.0/lists/' . get_option('vt_subscribe_audience_id') . '/members'; $data = array( 'email_address' => $email, 'status' => 'subscribed' ); $response = wp_remote_post( $url, array( 'body' => json_encode($data), 'headers' => array( 'Authorization' => 'Basic ' . base64_encode( $api_username . ':' . $api_key ), ), ) ); if( is_wp_error($response) ) { echo json_encode(array('status' => 'failed')); exit; } global $wpdb; if( $wpdb->insert('wp_vt_subscribe', array( 'email' => $email, )) ) { echo json_encode(array('status' => 'ok')); } else { echo json_encode(array('status' => 'failed')); } exit; } register_activation_hook( __FILE__, 'plugin_activation' ); register_deactivation_hook( __FILE__, 'plugin_deactivation' ); add_action( 'wp_ajax_vt_subscribe', 'vt_subscribe' ); add_action( 'wp_ajax_nopriv_vt_subscribe', 'vt_subscribe' ); add_action( 'init', 'vtsubscribe_init' );<file_sep>jQuery(document).ready(function($) { function setCookie(cname, cvalue, min) { // var d = new Date(); // d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); var expired = new Date(); expired.setMinutes( expired.getMinutes() + min ); var expires = "expires="+expired; document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; document.cookie = cname + '-exp' + "=" + expired + ";" + expires + ";path=/"; } function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } var closedPopup = getCookie("popup-vt-subscribe-hide"); var closedPopupExpire = getCookie("popup-vt-subscribe-hide-exp"); console.log(vtJsData.logged_in); if((closedPopup == '' || new Date(closedPopupExpire) < new Date()) && vtJsData.logged_in == 0) { setTimeout(function() { jQuery('#popup-vt-subscribe').addClass('popshow'); }, 5000); } jQuery('.popup-vt-subscribe-close').on('click', function() { jQuery('#popup-vt-subscribe').removeClass('popshow'); setCookie('popup-vt-subscribe-hide', 'hide', 5); }); jQuery('#popup-vt-subscribe-email').on('keyup', function(e) { if(jQuery(e.target).val().trim() != '') { jQuery('#vt_subscribe_popup_btn').removeAttr('disabled'); } else { jQuery('#vt_subscribe_popup_btn').attr('disabled', true); } }); jQuery('#vt_subscribe_popup_form').on('submit', function(e) { e.preventDefault(); var emailInput = jQuery('#popup-vt-subscribe-email').val().trim(); if(emailInput == '') { return; } //TODO: create ajax request front and back jQuery.ajax({ url: vtJsData.ajax_url, type: "POST", data: { action: "vt_subscribe", email: emailInput, security: vtJsData.ajax_nonce }, success: function(e) { console.log(e); var result = JSON.parse(e); if(result.status == 'ok') { jQuery('#popup-vt-subscribe-notification').append('<p style="text-align: center;"><strong>Thank you, for subscribe!</strong></p>'); setTimeout(function() { jQuery('#popup-vt-subscribe').removeClass('popshow'); setCookie('popup-vt-subscribe-hide', 'hide', 5000); }, 1500); } } }); }); });
5b63e5bf0f5c54f74db49fe36531a719d6d5f14a
[ "JavaScript", "PHP" ]
2
PHP
firmlab/vt-subscribe
0b62a5c091a0f82bb4fe1f1fc7b1e9a8db73edce
fdf84a8dbf4a6e59fe8e75a112d92b0c76b43d9d
refs/heads/master
<file_sep><?php namespace Xmon\SonataMediaProviderVideoBundle\Provider; // use Symfony\Component\HttpFoundation\File\UploadedFile; //use Symfony\Component\HttpFoundation\Response; //use Symfony\Component\HttpFoundation\StreamedResponse; //use Symfony\Component\Form\FormBuilder; //use Symfony\Component\Form\Form; //use Sonata\AdminBundle\Validator\ErrorElement; //use Sonata\MediaBundle\Entity\BaseMedia as Media; //use Gaufrette\Adapter\Local; use Symfony\Component\Filesystem\Filesystem as Fs; use Sonata\MediaBundle\Provider\FileProvider; use Sonata\MediaBundle\Model\MediaInterface; use Sonata\MediaBundle\Resizer\ResizerInterface; use Sonata\CoreBundle\Model\Metadata; use Sonata\MediaBundle\CDN\CDNInterface; use Sonata\MediaBundle\Generator\GeneratorInterface; use Sonata\MediaBundle\Thumbnail\ThumbnailInterface; use Sonata\MediaBundle\Metadata\MetadataBuilderInterface; use Sonata\AdminBundle\Form\FormMapper; use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Constraints\NotNull; use Doctrine\ORM\EntityManager; use Gaufrette\Filesystem; use FFMpeg\FFMpeg; use FFMpeg\FFProbe; use FFMpeg\Coordinate\TimeCode; use FFMpeg\Coordinate\Dimension; use FFMpeg\Format\Video; use Symfony\Component\DependencyInjection\ContainerInterface as Container; use GetId3\GetId3Core as GetId3; class VideoProvider extends FileProvider { protected $allowedExtensions; protected $allowedMimeTypes; protected $metadata; protected $getId3; protected $ffprobe; protected $ffmpeg; protected $container; protected $configImageFrame; protected $configVideoWidth; protected $configMp4; protected $configOgg; protected $configWebm; protected $entityManager; protected $thumbnail; /** * @param string $name * @param \Gaufrette\Filesystem $filesystem * @param \Sonata\MediaBundle\CDN\CDNInterface $cdn * @param \Sonata\MediaBundle\Generator\GeneratorInterface $pathGenerator * @param \Sonata\MediaBundle\Thumbnail\ThumbnailInterface $thumbnail * @param array $allowedExtensions * @param array $allowedMimeTypes * @param \Sonata\MediaBundle\Resizer\ResizerInterface $resizer * @param \Sonata\MediaBundle\Metadata\MetadataBuilderInterface $metadata * @param \FFMpeg\FFMpeg $FFMpeg * @param \FFMpeg\FFProbe $FFProbe * @param \Symfony\Component\DependencyInjection\ContainerInterface $container * @param \Doctrine\ORM\EntityManager $entityManager */ public function __construct($name, Filesystem $filesystem, CDNInterface $cdn, GeneratorInterface $pathGenerator, ThumbnailInterface $thumbnail, array $allowedExtensions = array(), array $allowedMimeTypes = array(), ResizerInterface $resizer, MetadataBuilderInterface $metadata = null, FFMpeg $FFMpeg, FFProbe $FFProbe, Container $container, EntityManager $entityManager) { parent::__construct($name, $filesystem, $cdn, $pathGenerator, $thumbnail, $allowedExtensions, $allowedMimeTypes, $metadata); $this->allowedExtensions = $allowedExtensions; $this->allowedMimeTypes = $allowedMimeTypes; $this->metadata = $metadata; $this->resizer = $resizer; $this->getId3 = new GetId3; $this->ffprobe = $FFProbe; $this->ffmpeg = $FFMpeg; $this->container = $container; $this->em = $entityManager; $this->thumbnail = $thumbnail; // configuración $this->configImageFrame = $this->container->getParameter('xmon_ffmpeg.image_frame'); $this->configVideoWidth = $this->container->getParameter('xmon_ffmpeg.video_width'); $this->configMp4 = $this->container->getParameter('xmon_ffmpeg.mp4'); $this->configOgg = $this->container->getParameter('xmon_ffmpeg.ogg'); $this->configWebm = $this->container->getParameter('xmon_ffmpeg.webm'); } /** * {@inheritdoc} */ public function buildCreateForm(FormMapper $formMapper) { $formMapper->add('binaryContent', 'file', array( 'constraints' => array( new NotBlank(), new NotNull(), ) )); $formMapper->add('thumbnailCapture', 'integer', array( 'mapped' => false, 'required' => false, 'label' => 'Thumbnail generator (set value in seconds)', )); } /** * {@inheritdoc} */ public function buildEditForm(FormMapper $formMapper) { parent::buildEditForm($formMapper); $formMapper->add('thumbnailCapture', 'integer', array( 'mapped' => false, 'required' => false, 'label' => 'Thumbnail generator (set value in seconds)', )); } /** * {@inheritdoc} */ protected function doTransform(MediaInterface $media) { parent::doTransform($media); if (!is_object($media->getBinaryContent()) && !$media->getBinaryContent()) { return; } $stream = $this->ffprobe ->streams($media->getBinaryContent()->getRealPath()) ->videos() ->first(); //$framecount = $stream->get('nb_frames'); $duration = $stream->get('duration'); $height = $stream->get('height'); $width = $stream->get('width'); /* // para recuperar las dimensiones de los vídeos codificados // las calculo aquí para guardarlas en la tabla, en lugar de // las dimensiones reales del vídeo original // estoy hay que eliminarlo en el momento en el que consiga pasar variables // a las plantillas twig $width = $this->configVideoWidth; $height = round($this->configVideoWidth * $heightOriginal / $widthOriginal); */ if ($media->getBinaryContent()) { $media->setContentType($media->getBinaryContent()->getMimeType()); $media->setSize($media->getBinaryContent()->getSize()); $media->setWidth($width); $media->setHeight($height); $media->setLength($duration); } $media->setProviderName($this->name); $media->setProviderStatus(MediaInterface::STATUS_OK); } /** * @throws \RuntimeException * * @param \Sonata\MediaBundle\Model\MediaInterface $media * * @return */ protected function fixBinaryContent(MediaInterface $media) { if ($media->getBinaryContent() === null) { return; } // if the binary content is a filename => convert to a valid File if (!$media->getBinaryContent() instanceof File) { if (!is_file($media->getBinaryContent())) { throw new \RuntimeException('The file does not exist : ' . $media->getBinaryContent()); } $binaryContent = new File($media->getBinaryContent()); $media->setBinaryContent($binaryContent); } } /** * @param \Sonata\MediaBundle\Model\MediaInterface $media * * @return string */ protected function generateReferenceName(MediaInterface $media) { return sha1($media->getName() . rand(11111, 99999)) . '.' . $media->getBinaryContent()->guessExtension(); } /** * {@inheritdoc} */ public function getProviderMetadata() { return new Metadata($this->getName(), $this->getName() . '.description', false, 'SonataMediaBundle', array('class' => 'fa fa fa-video-camera')); } /** * {@inheritdoc} */ public function requireThumbnails() { return $this->getResizer() !== null; } /** * {@inheritdoc} */ public function generateThumbnails(MediaInterface $media, $ext = 'jpg') { $this->generateReferenceImage($media); if (!$this->requireThumbnails()) { return; } $referenceImage = $this->getReferenceImage($media); foreach ($this->getFormats() as $format => $settings) { if (substr($format, 0, strlen($media->getContext())) == $media->getContext() || $format === 'admin') { $this->getResizer()->resize( $media, $referenceImage, $this->getFilesystem()->get($this->generateThumbsPrivateUrl($media, $format, $ext), true), $ext, $settings ); } } } /** * {@inheritdoc} */ public function generateVideos(MediaInterface $media) { // obtengo la ruta del archivo original $source = sprintf('%s/%s/%s', $this->getFilesystem()->getAdapter()->getDirectory(), $this->generatePath($media), $media->getProviderReference()); // determino las dimensiones del vídeo $height = round($this->configVideoWidth * $media->getHeight() / $media->getWidth()); // corrección para que el alto no sea impar, si es impar PETA ffmpeg if($height % 2 != 0){ $height = $height-1; } $video = $this->ffmpeg->open($source); $video ->filters() ->resize(new Dimension($this->configVideoWidth, $height)) ->synchronize(); if ($this->configMp4) { // genero los nombres de archivos de cada uno de los formatos $pathMp4 = sprintf('%s/%s/videos_mp4_%s', $this->getFilesystem()->getAdapter()->getDirectory(), $this->generatePath($media), $media->getId().'.mp4'); $mp4 = preg_replace('/\.[^.]+$/', '.' . 'mp4', $pathMp4); $video->save(new Video\X264('aac'), $mp4); $media->setProviderMetadata(['filename_mp4' => $mp4]); } if ($this->configOgg) { $pathOgg = sprintf('%s/%s/videos_ogg_%s', $this->getFilesystem()->getAdapter()->getDirectory(), $this->generatePath($media), $media->getId().'.ogg'); $ogg = preg_replace('/\.[^.]+$/', '.' . 'ogg', $pathOgg); $video->save(new Video\Ogg(), $ogg); } if ($this->configWebm) { $pathWebm = sprintf('%s/%s/videos_webm_%s', $this->getFilesystem()->getAdapter()->getDirectory(), $this->generatePath($media), $media->getId().'.webm'); $webm = preg_replace('/\.[^.]+$/', '.' . 'webm', $pathWebm); $video->save(new Video\WebM(), $webm); } //If no conversion format available simply duplicate file with the right name if (!$this->configMp4 && !$this->configOgg && !$this->configOgg) { $filename = sprintf('videos_mp4_%s', $media->getId().'.mp4'); $path = sprintf('%s/%s/', $this->getFilesystem()->getAdapter()->getDirectory(), $this->generatePath($media)); $fs = new Fs(); $fs->copy($path.'/'.$media->getProviderReference(), $path.'/'.$filename, true); } } /** * {@inheritdoc} */ public function generateThumbsPrivateUrl($media, $format, $ext = 'jpg') { return sprintf('%s/thumb_%s_%s.%s', $this->generatePath($media), $media->getId(), $format, $ext ); } /** * {@inheritdoc} */ public function generatePrivateUrl(MediaInterface $media, $format) { $path = $this->generateUrl($media, $format); return $path; } /** * {@inheritdoc} */ public function generatePublicUrl(MediaInterface $media, $format) { $path = $this->generateUrl($media, $format); return $this->getCdn()->getPath($path, $media->getCdnIsFlushable()); } private function generateUrl(MediaInterface $media, $format){ if ($format == 'reference') { $path = sprintf('%s/%s', $this->generatePath($media), $media->getProviderReference()); } elseif ($format == 'admin') { $path = sprintf('%s/%s', $this->generatePath($media), str_replace($this->getExtension($media), 'jpg', $media->getProviderReference())); } elseif ($format == 'thumb_admin') { $path = sprintf('%s/thumb_%d_%s.jpg', $this->generatePath($media), $media->getId(), 'admin'); } elseif ($format == 'videos_ogg') { $path = sprintf('%s/%s_%s', $this->generatePath($media), $format, str_replace($media->getExtension(), 'ogg', $media->getId().'.ogg')); } elseif ($format == 'videos_webm') { $path = sprintf('%s/%s_%s', $this->generatePath($media), $format, str_replace($media->getExtension(), 'webm', $media->getId().'.webm' )); } elseif ($format == 'videos_mp4') { $path = sprintf('%s/%s_%s', $this->generatePath($media), $format, str_replace($media->getExtension(), 'mp4', $media->getId().'.mp4')); } else { $path = sprintf('%s/thumb_%d_%s.jpg', $this->generatePath($media), $media->getId(), $format ); } return $path; } /** * {@inheritdoc} */ public function getHelperProperties(MediaInterface $media, $format, $options = array()) { if ($format == 'reference') { $box = $media->getBox(); } else { $resizerFormat = $this->getFormat($format); if ($resizerFormat === false) { throw new \RuntimeException(sprintf('The image format "%s" is not defined. Is the format registered in your ``sonata_media`` configuration?', $format)); } $box = $this->resizer->getBox($media, $resizerFormat); } return array_merge(array( 'id' => key_exists("id", $options) ? $options["id"] : $media->getId(), 'alt' => $media->getName(), 'title' => $media->getName(), 'thumbnail' => $this->getReferenceImage($media), 'src' => $this->generatePublicUrl($media, $format), 'file' => $this->generatePublicUrl($media, $format), 'realref' => $media->getProviderReference(), 'width' => $box->getWidth(), 'height' => $box->getHeight(), 'duration' => $media->getLength(), 'video_mp4' => $this->generatePublicUrl($media, "videos_mp4"), 'video_ogg' => $this->generatePublicUrl($media, "videos_ogg"), 'video_webm' => $this->generatePublicUrl($media, "videos_webm") ), $options); } /** * {@inheritdoc} */ public function getReferenceImage(MediaInterface $media) { return $this->getFilesystem()->get(sprintf('%s/%s', $this->generatePath($media), str_replace($this->getExtension($media), 'jpg', $media->getProviderReference())), true); } /** * {@inheritdoc} */ public function generateReferenceImage(MediaInterface $media) { $path = sprintf( '%s/%s/%s', $this->getFilesystem()->getAdapter()->getDirectory(), $this->generatePath($media), $media->getProviderReference() ); $stream = $this->ffprobe ->streams($path) ->videos() ->first(); /* $framecount = $stream->get('nb_frames'); $duration = $stream->get('duration'); $height = $stream->get('height'); $width = $stream->get('width'); */ $video = $this->ffmpeg->open($path); if (!$media->getProviderReference()) { $media->setProviderReference($this->generateReferenceName($media)); } // recojo el punto de extracción de la imagen definido en la configuración $seconds_extract = $this->configImageFrame; // conocemos la duración del vídeo $duration = $stream->get('duration'); // compruebo que el punto de extracción está dentro de la duración del video // si no está dentro, entonces calculo la mitad de la duración if ($seconds_extract > $duration) { $seconds_extract = $duration / 2; } $timecode = TimeCode::fromSeconds($seconds_extract); $frame = $video->frame($timecode); if (!$frame) { echo "Thumbnail Generation Failed"; exit; } $thumnailPath = sprintf( '%s/%s/%s', $this->getFilesystem()->getAdapter()->getDirectory(), $this->generatePath($media), str_replace( $this->getExtension($media), 'jpg', $media->getProviderReference() ) ); $frame->save($thumnailPath); } private function updateConfigFrameValue($media){ $uniqid = $this->container->get('request_stack')->getCurrentRequest()->query->get('uniqid'); $formData = $this->container->get('request_stack')->getCurrentRequest()->get($uniqid); if (!empty($formData['thumbnailCapture'])) { if ($formData['thumbnailCapture'] <= round($media->getLength())) { $this->configImageFrame = $formData['thumbnailCapture']; } } } private function setProviderMetadataAvailableVideoFormat(MediaInterface $media){ $this->updateConfigFrameValue($media); $metadata = $media->getProviderMetadata('filename'); // genero los nombres de archivos de cada uno de los formatos if ($this->configMp4) { $metadata['mp4_available'] = true; } if ($this->configOgg) { $metadata['ogg_available'] = true; } if ($this->configWebm) { $metadata['webm_available'] = true; } if (!$this->configMp4 && !$this->configOgg && !$this->configOgg) { $metadata['mp4_available'] = true; } $media->setProviderMetadata($metadata); } private function getAvailableFormatToUpdateOrDelete(){ if ($this->configMp4) { $this->addFormat('videos_mp4', 'mp4'); } if ($this->configOgg) { $this->addFormat('videos_ogg', 'ogg'); } if ($this->configWebm) { $this->addFormat('videos_webm', 'webm'); } if (!$this->configMp4 && !$this->configOgg && !$this->configOgg) { $this->addFormat('videos_mp4', 'mp4'); } $this->addFormat('reference', 'reference'); $this->addFormat('thumb_admin', 'thumb_admin'); } /** * {@inheritdoc} */ public function prePersist(MediaInterface $media) { if (!$media->getBinaryContent()) { return; } $this->setProviderMetadataAvailableVideoFormat($media); } /** * {@inheritdoc} */ public function postPersist(MediaInterface $media) { if (!$media->getBinaryContent()) { return; } $this->setFileContents($media); $this->generateThumbnails($media); $this->generateVideos($media); } /** * {@inheritdoc} */ public function preRemove(MediaInterface $media) { // arreglo para eliminar la relación del video con la galería if ($galleryHasMedias = $media->getGalleryHasMedias()) { foreach ($galleryHasMedias as $galleryHasMedia) { $this->em->remove($galleryHasMedia); } } $this->getAvailableFormatToUpdateOrDelete(); $path = $this->getReferenceImage($media)->getKey(); if ($this->getFilesystem()->has($path)) { $this->getFilesystem()->delete($path); } if ($this->requireThumbnails()) { $this->thumbnail->delete($this, $media); } } /** * {@inheritdoc} */ public function postRemove(MediaInterface $media) { // QUIZÁS el lugar donde eliminar los archivos } /** * {@inheritdoc} */ public function preUpdate(MediaInterface $media) { if (!$media->getBinaryContent()) { return; } $this->setProviderMetadataAvailableVideoFormat($media); } /** * {@inheritdoc} */ public function postUpdate(MediaInterface $media) { if (!$media->getBinaryContent() instanceof \SplFileInfo) { return; } // Delete the current file from the FS $oldMedia = clone $media; $oldMedia->setProviderReference($media->getPreviousProviderReference()); $this->getAvailableFormatToUpdateOrDelete(); if ($this->getFilesystem()->has($oldMedia)) { $this->getFilesystem()->delete($oldMedia); } if ($this->requireThumbnails()) { $this->thumbnail->delete($this, $oldMedia); } $this->fixBinaryContent($media); $this->setFileContents($media); $this->generateThumbnails($media); $this->generateVideos($media); } /** * {@inheritdoc} */ public function updateMetadata(MediaInterface $media, $force = false) { $file = sprintf('%s/%s/%s', $this->getFilesystem()->getAdapter()->getDirectory(), $this->generatePath($media), $media->getProviderReference()); $fileinfos = new ffmpeg_movie($file, false); $img_par_s = $fileinfos->getFrameCount() / $fileinfos->getDuration(); // Récupère l'image $frame = $fileinfos->getFrame(15 * $img_par_s); //$media->setContentType($media->getProviderReference()->getMimeType()); $media->setContentType(mime_content_type($file)); $media->setSize(filesize($file)); $media->setWidth($frame->getWidth()); $media->setHeight($frame->getHeight()); $media->setLength($fileinfos->getDuration()); $media->setMetadataValue('bitrate', $fileinfos->getBitRate()); } /** * @param \Sonata\MediaBundle\Model\MediaInterface $media * * @return string the file extension for the $media, or the $defaultExtension if not available */ protected function getExtension(MediaInterface $media) { $ext = $media->getExtension(); if (!is_string($ext) || strlen($ext) < 2) { $ext = "mp4"; } return $ext; } //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// // CON PROBLEMAS //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// /** * {@inheritdoc} public function getDownloadResponse(MediaInterface $media, $format, $mode, array $headers = array()) { // build the default headers $headers = array_merge(array( 'Content-Type' => $media->getContentType(), 'Content-Disposition' => sprintf('attachment; filename="%s"', $media->getMetadataValue('filename')), ), $headers); if (!in_array($mode, array('http', 'X-Sendfile', 'X-Accel-Redirect'))) { throw new \RuntimeException('Invalid mode provided'); } if ($mode == 'http') { $provider = $this; return new StreamedResponse(function() use ($provider, $media, $format) { if ($format == 'reference') { echo $provider->getReferenceFile($media)->getContent(); } else { echo $provider->getFilesystem()->get($provider->generatePrivateUrl($media, $format))->getContent(); } }, 200, $headers); } if (!$this->getFilesystem()->getAdapter() instanceof \Sonata\MediaBundle\Filesystem\Local) { throw new \RuntimeException('Cannot use X-Sendfile or X-Accel-Redirect with non \Sonata\MediaBundle\Filesystem\Local'); } $headers[$mode] = sprintf('%s/%s', $this->getFilesystem()->getAdapter()->getDirectory(), $this->generatePrivateUrl($media, $format) ); return new Response('', 200, $headers); } */ /** * {@inheritdoc} public function getReferenceFile(MediaInterface $media) { return $this->getFilesystem()->get(sprintf('%s/%s', $this->generatePath($media), $media->getProviderReference()), true); } */ /* * NO SE USA * public function getReferencePath(MediaInterface $media, $format) { return $this->getFilesystem()->get(sprintf('%s/%s_%s', $this->generatePath($media), $format, $media->getProviderReference()), true); } */ /** public function setLogger($logger) { $this->logger = $logger; }*/ }
352ef5c4f42f76220f6eb46f45111a5360942d14
[ "PHP" ]
1
PHP
veliseev/SonataMediaProviderVideoBundle
d3dca94b302d77c5406951ca9c1432508cbf2f42
349f0be1db996909317520b21e6e46d8e332ab75
refs/heads/master
<file_sep>test: build mocha --compilers coffee:coffee-script --timeout 10000 --require should # --grep 'Source|MarkdownBinder|DataPublisher' build: build-src build-template build-src: mkdir -p lib/parsers # cp src/parsers/showdown-prettify.js lib/parsers/showdown-prettify.js # cp src/parsers/showdown-table.js lib/parsers/showdown-table.js coffee -m -o lib/ -c src/ build-template: mkdir -p template/asset/ref cp submodules/templates/styles/layout.less template/asset/ref/layout.less cp submodules/templates/styles/markdown.less template/asset/ref/markdown.less cp submodules/templates/styles/todo.less template/asset/ref/todo.less lessc template/asset/layout.less template/asset/layout.css lessc template/asset/content.less template/asset/content.css clean: rm -rf lib rm -rf node_modules watch-src: build start fswatch src "make reload" watch-template: fswatch template "make build-template" reload: stop build-src start start: coffee -c samples/sample.coffee forever start samples/sample.js stop: forever stopall forever list rm samples/sample.js<file_sep># Later... # Update Log ### 0.3.6 - hotfix error : Cannot call method 'indexOf' of undefined ### 0.3.5 - change markdown module : from showdown to marked ### 0.3.4 - added api : add TodoParser. It is parse `.todo` file from "PlainTask" plugin on Sublime Text - added `TodoParser` - added `content.less` - changed `document.jade` - added api : JadeParser. It is parse `.jade` (with `.json`) files - added `JadeParser` - changed from `Parser.parse(source)` to `Parser.parse(source, [file])` - fixed bug : remove dependent `helper.extensionToContentType` - removed `helper.extensionToContentType` - changed from `Source.addParser(extension, parser)` to `Source.addParser(extension, contentType, parser)` - fixed bug : `JadeTemplatePublisher` - update Makefile ### 0.3.3 - changed api : title, description setting moved from JadeTemplatePublisher, DataPublisher to MarkdownBinder - removed `JadeTemplatePublisher.title, description` - removed `DataPublisher.rss.title, description` - changed from `Publisher.publish(req, res, source, error)` to `Publisher.publish(req, res, source, error, title, description)` - changed from `MarkdownBinder(@source, @publishers)` to `MarkdownBinder(@source, @publishers, @title, @description)` ### 0.3.2 - fixed bug : encodeURI rss, sitemap links<file_sep>/* Copyright (c) 2011 <NAME>, http://www.jason-palmer.com/ 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. */ jQuery.fn.DefaultValue = function (text, activeColor, inactiveColor) { if (activeColor === null || activeColor === undefined) { activeColor = '#000000'; } if (inactiveColor === null || inactiveColor === undefined) { inactiveColor = '#aaaaaa'; } return this.each(function () { //Store reference to input field var $input_obj = jQuery(this); //See if text is supplied or contained in label property var default_val = text || $input_obj.attr("label"); //Make sure we're dealing with text-based form fields switch (this.type) { case 'text': case 'password': case 'textarea': break; default: return; } //Set value initially if none are specified if ($input_obj.val() == '') { $input_obj.val(default_val); this.style.color = inactiveColor; } else { //Other value exists - ignore return; } //Remove values on focus $input_obj.bind('focus', function () { if ($input_obj.val() == default_val || $input_obj.val() == '') { $input_obj.val(''); this.style.color = activeColor; } }); //Place values back on blur $input_obj.bind('blur', function () { if ($input_obj.val() == default_val || $input_obj.val() == '') { $input_obj.val(default_val); this.style.color = inactiveColor; } }); //Capture parent form submission //Remove field values that are still default $input_obj.parents("form").each(function () { //Bind parent form submit jQuery(this).bind('submit', function () { if ($input_obj.val() == default_val && jQuery.fn.DefaultValue.settings.clear_defaults_on_submit == true) { $input_obj.val(''); } }); }); }); }; jQuery.fn.DefaultValue.settings = { 'clear_defaults_on_submit': true };
bfb6243625903ee55b12ccefff31fe7cdd19e953
[ "Markdown", "JavaScript", "Makefile" ]
3
Makefile
iamssen/markdown-binder
8b7d0f52f373573507293337cf448972251aa5b3
a8fa3bf4bfa8deff82042e0653430c69a3bbaee5
refs/heads/master
<file_sep><?php namespace Org\Util; class EthCommon { protected $host, $port, $version; protected $id = 0; public $base = "1000000000000000000";//1e18 wei 基本单位 //高精度函数参考http://www.jb51.net/article/80726.htm /** * 构造函数 * Common constructor. * @param $host * @param string $port * @param string $version */ function __construct($host, $port = "80",$version) { $this->host = $host; $this->port = $port; $this->version = $version; } /** * 发送请求 * @author qiuphp2 * @since 2017-9-21 * @param $method * @param array $params * @return mixed */ function request($method, $params = array()) { $data = array(); $data['jsonrpc'] = $this->version; $data['id'] = $this->id + 1; $data['method'] = $method; $data['params'] = $params; //@SaveLog('EthPayLocal', "params_".$method.json_encode($data), __FUNCTION__); //echo json_encode($data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->host); curl_setopt($ch, CURLOPT_PORT, $this->port); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); $ret = curl_exec($ch); //echo "$ret".$ret; //返回结果 if ($ret) { curl_close($ch); return json_decode($ret, true); } else { $error = curl_errno($ch); //echo $error; curl_close($ch); return false; //throw new Exception("curl出错,错误码:$error"); } } /** * @author qiuphp2 * @since 2017-9-21 * @param $weiNumber 16进制wei单位 * @return float|int 10进制eth单位【正常单位】 */ function fromWei($weiNumber) { $tenNumber = base_convert($weiNumber, 16, 10); //echo $tenNumber."<br/>"; $ethNumber = bcdiv($tenNumber,$this->base,8); return $ethNumber; } function fromWei2($weiNumber) { $ethNumber = bcdiv($weiNumber,$this->base,8);//高精度浮点数相除 return $ethNumber; } function fromWei3($weiNumber) { $tenNumber = base_convert($weiNumber, 16, 10); //echo $tenNumber."<br/>"; $ethNumber = bcdiv($tenNumber,100000000,8); return $ethNumber; } /** * @author qiuphp2 * @since 2017-9-21 * @param $ethNumber 10进制eth单位 * @return string 16进制wei单位 */ function toWei($ethNumber) { //echo "ethNumber".$ethNumber; //echo "base".$this->base; $tenNumer=bcmul($ethNumber,$this->base);//高精度浮点数相乘 //echo $tenNumer;die(); $weiNumber = base_convert($tenNumer, 10, 16); return '0x'.$weiNumber; } function toWei3($ethNumber) { //echo "ethNumber".$ethNumber; //echo "base".$this->base; $tenNumer=bcmul($ethNumber,100000000);//高精度浮点数相乘 //echo $tenNumer;die(); $weiNumber = base_convert($tenNumer, 10, 16); return '0x'.$weiNumber; } /** * @param $ethNumber * @return string start 10 end 10 */ function toWei2($ethNumber) { $weiNumber = bcmul($ethNumber,$this->base); return $weiNumber; } /** * 判断是否是16进制 * @author qiuphp2 * @since 2017-9-21 * @param $a * @return int */ function assertIsHex($a) { if (ctype_xdigit($a)) { return true; } else { return false; } } } <file_sep><?php namespace Home\Controller; class ChartController extends HomeController { public function specialty() { // TODO: SEPARATE $input = I('get.'); $market = (is_array(C('market')[$input['market']]) ? trim($input['market']) : C('market_mr')); $this->assign('market', $market); $this->display(); } public function getMarketOrdinaryJson() { // TODO: SEPARATE $input = I('get.'); $market = (is_array(C('market')[$input['market']]) ? trim($input['market']) : C('market_mr')); $timearr = array(1, 3, 5, 10, 15, 30, 60, 120, 240, 360, 720, 1440, 10080); if (in_array($input['time'], $timearr)) { $time = $input['time']; } else { $time = 5; } $timeaa = (APP_DEBUG ? null : S('ChartgetMarketOrdinaryJsontime' . $market . $time)); if (($timeaa + 60) < time()) { S('ChartgetMarketOrdinaryJson' . $market . $time, null); S('ChartgetMarketOrdinaryJsontime' . $market . $time, time()); } $tradeJson = (APP_DEBUG ? null : S('ChartgetMarketOrdinaryJson' . $market . $time)); if (!$tradeJson) { $tradeJson = M('TradeJson')->where(array( 'market' => $market, 'type' => $time, 'data' => array('neq', '') ))->order('id desc')->limit(100)->select(); S('ChartgetMarketOrdinaryJson' . $market . $time, $tradeJson); } krsort($tradeJson); foreach ($tradeJson as $k => $v) { $json_data[] = json_decode($v['data'], true); } exit(json_encode($json_data)); } public function getMarketSpecialtyJson() { // TODO: SEPARATE $input = I('get.'); $market = (is_array(C('market')[$input['market']]) ? trim($input['market']) : C('market_mr')); $timearr = array(5, 15, 30, 60, 360, 1440); if (in_array($input['step'] / 60, $timearr)) { $time = $input['step'] / 60; } else { $time = 5; } $timeaa = (APP_DEBUG ? null : S('ChartgetMarketSpecialtyJsontime' . $market . $time)); if (($timeaa + 60) < time()) { S('ChartgetMarketSpecialtyJson' . $market . $time, null); S('ChartgetMarketSpecialtyJsontime' . $market . $time, time()); } $tradeJson = (APP_DEBUG ? null : S('ChartgetMarketSpecialtyJson' . $market . $time)); if (!$tradeJson) { $tradeJson = M('TradeJson')->where(array( 'market' => $market, 'type' => $time, 'data' => array('neq', '') ))->order('id asc')->select(); S('ChartgetMarketSpecialtyJson' . $market . $time, $tradeJson); } $json_data = $data = array(); foreach ($tradeJson as $k => $v) { $json_data[] = json_decode($v['data'], true); } foreach ($json_data as $k => $v) { $data[$k][0] = $v[0]; $data[$k][1] = 0; $data[$k][2] = 0; $data[$k][3] = $v[2]; $data[$k][4] = $v[5]; $data[$k][5] = $v[3]; $data[$k][6] = $v[4]; $data[$k][7] = $v[1]; } exit(json_encode($data)); } } ?><file_sep><?php namespace Common\Model; class FinanceModel extends \Think\Model { protected $keyS = 'Finance'; public function check_install() { } public function updata($userid = NULL, $coinname = NULL, $type = NULL, $remark = NULL) { } } ?><file_sep><include file="Public:header" /> <div class="content"> <div class="clearfix window-wrap w1500 c2c-page"> <include file="User:left" /> <div class="c2c-page-right pull-right"> <div class="c2c-cont"> <div class="c2c-cont-head clearfix"> <h3 class="c2c-cont-head-title pull-left"> {$Think.Lang.V_FINANCE_COMMISSION_TITLE} </h3> </div> <div class="c2c-order"> <div class="c2c-order-table"> <table class="c2c-table" id="investLog_content"> <thead> <tr> <th style="width: 0.2rem"> <img src="__UPLOAD__/coin/{$coin_list[$market_list[$market]['xnb']]['img']}" alt="" class="icon-bi" style="width: 0.2rem;"/> </th> <th> <select name="market-selectTest" id="market-selectTest" class="select1 vhide"> <option value="">{$Think.Lang.V_FINANCE_COMMISSION_ALL}</option> <volist name="market_list" id="vo"> <eq name="market" value="$key"> <option value="{$vo['name']}t" selected="selected">{$coin_list[$vo['xnb']]['title']}({$vo['xnb']|strtoupper}/{$vo['rmb']|strtoupper}T)</option> <else /> <option value="{$vo['name']}t">{$coin_list[$vo['xnb']]['title']}({$vo['xnb']|strtoupper}/{$vo['rmb']|strtoupper}T)</option> </eq> </volist> </select></th> <th>{$Think.Lang.V_FINANCE_COMMISSION_TIME}</th> <th><select name="type-selectTest" id="type-selectTest" class="select3 vhide"> <option value="0"<eq name="type" value="0">selected</eq>>{$Think.Lang.V_FINANCE_COMMISSION_ALL} </option> <option value="1"<eq name="type" value="1">selected</eq>>{$Think.Lang.V_FINANCE_COMMISSION_BUY} </option> <option value="2"<eq name="type" value="2">selected</eq>>{$Think.Lang.V_FINANCE_COMMISSION_SHELL} </option> </select></th> <th>{$Think.Lang.V_FINANCE_COMMISSION_PRICE}</th> <th>{$Think.Lang.V_FINANCE_COMMISSION_NUM}</th> <th>{$Think.Lang.V_FINANCE_COMMISSION_NUM_COMPLETE}</th> <th> <select name="status-selectTest" id="status-selectTest" class="select4 vhide"> <option value="0"<eq name="status" value="0">selected</eq>>{$Think.Lang.V_FINANCE_COMMISSION_ALL} </option> <option value="1"<eq name="status" value="1">selected</eq>>{$Think.Lang.V_FINANCE_COMMISSION_TRAN} </option> <option value="2"<eq name="status" value="2">selected</eq>>{$Think.Lang.V_FINANCE_COMMISSION_COMPLETE} </option> <option value="3"<eq name="status" value="3">selected</eq>>{$Think.Lang.V_FINANCE_COMMISSION_CANCEL} </option> </select> </th> </tr> </thead> <tbody> <volist name="list" id="vo"> <tr> <td colspan="2">{$coin_list[$market_list[$vo['market']]['xnb']]['title']} ({$market_list[$vo['market']]['xnb']|strtoupper}/{$market_list[$vo['market']]['rmb']|strtoupper}T)</td> <td>{$vo.addtime|date='m-d H:i:s',###}</td> <td><eq name="vo.type" value="1"> <font class="buy">{$Think.Lang.V_FINANCE_COMMISSION_BUY}</font> <else /> <font class="sell">{$Think.Lang.V_FINANCE_COMMISSION_SHELL}</font></eq></td> <td>{$vo['price']|NumToStr}</td> <td>{$vo['num']|NumToStr}</td> <td>{$vo['deal']|NumToStr}</td> <td><eq name="vo.status" value="0"><span class="cb94e50">{$Think.Lang.V_FINANCE_COMMISSION_TRAN}</span> | <a class="cancel" id="{$vo.id}" href="javascript:void(0);">{$Think.Lang.V_FINANCE_COMMISSION_DO_CANCEL}</a></eq> <eq name="vo.status" value="1"><span class="c00ffff">{$Think.Lang.V_FINANCE_COMMISSION_COMPLETE}</span></eq> <eq name="vo.status" value="2">{$Think.Lang.V_FINANCE_COMMISSION_CANCEL}</eq></td> </tr> </volist> </tbody> </table> <div class="pages">{$page}</div> </div> </div> <div> <notempty name="prompt_text"> <div class="mytips"> <h6 style="color: #ff8000;">{$Think.Lang.V_SHARE_WARN}</h6> {$prompt_text} </div> </notempty> </div> </div> </div> </div> </div> <script> $('.select1').select2({ minimumResultsForSearch: -1, dropdownAutoWidth: true }); $('.select3').select2({ minimumResultsForSearch: -1, dropdownAutoWidth: true }); $('.select4').select2({ minimumResultsForSearch: -1, dropdownAutoWidth: true }); $("#type-selectTest,#status-selectTest,#market-selectTest").change(function(){ var type=$("#type-selectTest option:selected").val(); var status=$("#status-selectTest option:selected").val(); var market=$("#market-selectTest option:selected").val(); window.location='/Finance/mywt/type/'+type+'/status/'+status+'/market/'+market+'.html'; }); $('.cancel').click(function(){ $.post("{:U('Trade/chexiao')}",{id : $(this).attr('id'), },function(data){ if(data.status==1){ layer.msg(data.info,{icon : 1 }); window.setTimeout("window.location.reload()",1000); }else{ layer.msg(data.info,{icon : 2 }); } }); }); </script> <include file="Public:footer" /><file_sep><?php /** * Created by PhpStorm. * User: BBB * Date: 2018/8/29 * Time: 14:35 */ namespace Home\Controller; class GoogleController extends HomeController { public function index(){ if (!userid()) { redirect('/Login'); } $this->display(); } }<file_sep><?php namespace Home\Controller; class LoginController extends HomeController { public function index() { if(userid()){ if(C('DEFAULT_V_LAYER') == 'Mview'){ redirect('/Finance'); }else{ redirect('/User'); } }else{ $this->display(); } } public function getuid() { $arr["userid"] = userid(); $arr["moble"] = username(userid()); $arr["nickName"] = session("nickName"); echo json_encode($arr); } public function register() { if(userid()){ if(C('DEFAULT_V_LAYER') == 'Mview'){ redirect('/Finance'); }else{ redirect('/User'); } }else{ if($_GET['invit']){ session('invit',$_GET['invit']); } $this->assign('invitCode', $_GET['invit']);//显示邀请码 $this->display(); } } public function webreg() { $this->display(); } public function upregister($username = '', $password = '', $repassword = '', $verify = '', $invit = '', $moble = '', $moble_verify = '') { if(userid()){ redirect('/User'); } if (M_ONLY == 0) { // if (!check_verify(strtoupper($verify))) { // $this->error('图形验证码错误!'); // } if (!check($moble, 'moble')) { $this->error('手机号码格式错误!'); } if (!check($password, 'password')) { $this->error('登录密码格式错误!'); } if ($password != $repassword) { $this->error('确认登录密码错误!'); } } else { if (!check($password, 'password')) { $this->error('登录密码格式错误!'); } } $moble = $this->_replace_china_mobile($moble); $username = $moble; if (!check($moble, 'moble')) { $this->error('手机号码格式错误!'); } if (!check($moble_verify, 'd')) { $this->error('短信验证码格式错误!'); } $this->_verify_count_check($moble_verify,session('real_verify')); if (M('User')->where(array('moble' => $moble))->find()) { $this->error('手机号码已存在!'); } if(session('register_mobile_validation') != md5($moble)){ $this->error('手机号码错误'); } if (M('User')->where(array('username' => $username))->find()) { $this->error('用户名已存在'); } if (!$invit) { $invit = session('invit'); } $invituser = M('User')->where(array('invit' => $invit))->find(); if (!$invituser) { $invituser = M('User')->where(array('id' => $invit))->find(); } if (!$invituser) { $invituser = M('User')->where(array('username' => $invit))->find(); } if (!$invituser) { $invituser = M('User')->where(array('moble' => $invit))->find(); } if ($invituser) { $invit_1 = $invituser['id']; $invit_2 = $invituser['invit_1']; $invit_3 = $invituser['invit_2']; } else { $invit_1 = 0; $invit_2 = 0; $invit_3 = 0; } for (; true;) { $tradeno = tradenoa(); if (!M('User')->where(array('invit' => $tradeno))->find()) { break; } } $mo = M(); $mo->execute('set autocommit=0'); //$mo->execute('lock tables qq3479015851_user write , qq3479015851_user_coin write '); $rs = array(); $rs[] = $mo->table('qq3479015851_user')->add(array('username' => $username, 'moble' => $moble, 'mobletime' => time(), 'password' => <PASSWORD>, 'invit' => $tradeno, 'tpwdsetting' => 1, 'invit_1' => $invit_1, 'invit_2' => $invit_2, 'invit_3' => $invit_3, 'addip' => get_client_ip(), 'addr' => get_city_ip(), 'addtime' => time(), 'endtime' => time(), 'status' => 1)); $rs[] = $mo->table('qq3479015851_user_coin')->add(array('userid' => $rs[0], 'doge' => 100)); //推荐赠送cnut+doge,冻结 // $istj = M()->query("SELECT count(id) as coun FROM `qq3479015851_user` where invit_1 = '".$invit_1."' "); // $tj_num = $istj[0]['coun']; // if($tj_num){ // $pri = 100; // M()->execute("UPDATE `qq3479015851_user_coin` SET `cnutd` = cnutd+$pri,`doged` = doged+$pri WHERE userid ='".$invit_1."';"); // M()->execute("UPDATE `qq3479015851_user` SET `isnrt` = $tj_num WHERE id ='".$invit_1."';"); // // // } if (check_arr($rs)) { $mo->execute('commit'); //$mo->execute('unlock tables'); session('reguserId', $rs[0]); session('real_verify',null); $this->success('注册成功!'); } else { $mo->execute('rollback'); session('real_verify', null); $this->error('注册失败!'); } } public function check_moble($moble = 0) { $moble = $this->_replace_china_mobile($moble); if (!check($moble, 'moble')) { $this->error('手机号码格式错误!'); } if (M('User')->where(array('moble' => $moble))->find()) { $this->error('手机号码已存在!'); } $this->success(''); } public function check_mail($email = ''){ if (!check($email, 'email')) { $this->error('邮箱格式错误!'); } if (M('User')->where(array('email' => $email))->find()) { $this->error('邮箱已存在!'); } $this->success(''); } /** * 邮箱发送验证码 * @param $email * @param $verifyEmail */ public function real_mail($email, $verifyEmail) { if (!check_verify(strtoupper($verifyEmail))) { $this->error('图形验证码错误!'); } if (!check($email, 'email')) { $this->error('邮箱格式错误!'); } if (M('User')->where(array('email' => $email))->find()) { $this->error('邮箱已存在!'); } $code = rand(111111, 999999); session('real_email_verify', $code); session('verify#time', time()); $content = 'CC注册,your code:' . $code; SendEmail(array('to'=>$email, 'subject'=>'CC注册', 'content'=>$content));//发送邮件 session('register_email_validation', md5($email)); if (MOBILE_CODE == 0) { $this->success('目前是演示模式,请输入' . $code); } else { $this->success('验证码已发送'); } } public function upregisterEmail($username = '', $password = '', $repassword = '', $verify = '', $invit = '', $email = '', $emailVerify = '') { if (M_ONLY == 0) { if (!check($password, 'password')) { $this->error('登录密码格式错误!'); } } else { if (!check($password, 'password')) { $this->error('登录密码格式错误!'); } } if (!check($email, 'email')) { $this->error('邮件格式错误!'); } $username = $email; if (!check($emailVerify, 'd')) { $this->error('邮箱验证码格式错误!'); } if(session('register_email_validation') != md5($email)){ $this->error('邮箱错误!'); } $this->_verify_email_count_check($emailVerify,session('real_email_verify')); if (M('User')->where(array('email' => $email))->find()) { $this->error('邮箱已存在!'); } if (M('User')->where(array('username' => $username))->find()) { $this->error('用户名已存在'); } if (!$invit) { $invit = session('invit'); } $invituser = M('User')->where(array('invit' => $invit))->find(); if (!$invituser) { $invituser = M('User')->where(array('id' => $invit))->find(); } if (!$invituser) { $invituser = M('User')->where(array('username' => $invit))->find(); } if (!$invituser) { $invituser = M('User')->where(array('moble' => $invit))->find(); } if ($invituser) { $invit_1 = $invituser['id']; $invit_2 = $invituser['invit_1']; $invit_3 = $invituser['invit_2']; } else { $invit_1 = 0; $invit_2 = 0; $invit_3 = 0; } for (; true;) { $tradeno = tradenoa(); if (!M('User')->where(array('invit' => $tradeno))->find()) { break; } } $mo = M(); $mo->execute('set autocommit=0'); //$mo->execute('lock tables qq3479015851_user write , qq3479015851_user_coin write '); $rs = array(); $moble = ''; $rs[] = $mo->table('qq3479015851_user')->add(array('username' => $username,'email' => $email, 'moble' => $moble, 'mobletime' => time(), 'password' => <PASSWORD>, 'invit' => $tradeno, 'tpwdsetting' => 1, 'invit_1' => $invit_1, 'invit_2' => $invit_2, 'invit_3' => $invit_3, 'addip' => get_client_ip(), 'addr' => get_city_ip(), 'addtime' => time(), 'endtime' => time(), 'status' => 1)); $rs[] = $mo->table('qq3479015851_user_coin')->add(array('userid' => $rs[0], 'doge' => 100)); //推荐赠送cnut+doge,冻结 // $istj = M()->query("SELECT count(id) as coun FROM `qq3479015851_user` where invit_1 = '".$invit_1."' "); // $tj_num = $istj[0]['coun']; // if($tj_num){ // $pri = 100; // M()->execute("UPDATE `qq3479015851_user_coin` SET `cnutd` = cnutd+$pri,`doged` = doged+$pri WHERE userid ='".$invit_1."';"); // M()->execute("UPDATE `qq3479015851_user` SET `isnrt` = $tj_num WHERE id ='".$invit_1."';"); // // // } if (check_arr($rs)) { $mo->execute('commit'); //$mo->execute('unlock tables'); session('reguserId', $rs[0]); session('real_email_verify', null); $this->success('注册成功!'); } else { $mo->execute('rollback'); session('real_email_verify', null); $this->error('注册失败!'.$rs); } } public function check_pwdmoble($moble = 0) { $moble = $this->_replace_china_mobile($moble); if (!check($moble, 'moble')) { $this->error('手机号码格式错误!'); } if (!M('User')->where(array('moble' => $moble))->find()) { $this->error('手机号码不存在!'); } $this->success(''); } public function check_pwdemail($email = '') { if (!check($email, 'email')) { $this->error('邮箱格式错误!'); } if (!M('User')->where(array('email' => $email))->find()) { $this->error('邮箱不存在!'); } $this->success(''); } public function real($moble, $verify) { if (!check_verify(strtoupper($verify))) { $this->error('图形验证码错误!'); } if (!check($moble, 'moble')) { $this->error('手机号码格式错误!'); } $moble = $this->_replace_china_mobile($moble); if (M('User')->where(array('moble' => $moble))->find()) { $this->error('手机号码已存在!'); } $code = rand(111111, 999999); session('real_verify', $code); session('verify#time', time()); $content = 'CC注册,your code:' . $code; //$sen = send_moble($moble, $content); if (SendText($moble, $code, "reg")) { session('register_mobile_validation', md5($moble)); if (MOBILE_CODE == 0) { $this->success('目前是演示模式,请输入' . $code); } else { $this->success('验证码已发送'); } } else { //echo '-----------'; //var_dump($aaa); //die; $this->error('验证码发送失败,请重发'); } } public function register2() { if (!session('reguserId')) { redirect('/Login'); } $this->display(); } public function paypassword() { if (!session('reguserId')) { redirect('/Login'); } $this->display(); } public function upregister2($paypassword, $repaypassword) { if (!check($paypassword, 'password')) { $this->error('交易密码格式错误!'); } if ($paypassword != $repaypassword) { $this->error('确认密码错误!'); } if (!session('reguserId')) { $this->error('非法访问!'); } if (M('User')->where(array('id' => session('reguserId'), 'password' => $<PASSWORD>))->find()) { $this->error('交易密码不能和登录密码一样!'); } if (M('User')->where(array('id' => session('reguserId')))->save(array('paypassword' => $paypassword))) { $this->success('成功!'); } else { $this->error('失败!'); } } public function register3() { if (!session('reguserId')) { redirect('/Login'); } $this->display(); } public function truename() { if (!session('reguserId')) { redirect('/Login'); } $this->display(); } public function upregister3($truename, $idcard) { if (!check($truename, 'truename')) { $this->error('真实姓名格式错误!'); } $idcard = preg_replace('# #', '', $idcard); if (!check($idcard, 'idcard')) { $this->error('身份证号格式错误!'); } if (!session('reguserId')) { $this->error('非法访问!'); } $user = M('User')->where(array('idcard' => $idcard))->find(); if ($user) { $this->error('您的身份证号码已经认证<br>认证账号为:' . $user["username"] . '!'); } if (M('User')->where(array('id' => session('reguserId')))->save(array('truename' => $truename, 'idcard' => $idcard))) { $this->success('成功!'); } else { $this->error('失败!'); } } public function register4() { if (!session('reguserId')) { redirect('/Login'); } $user = M('User')->where(array('id' => session('reguserId')))->find(); if (!$user) { $this->error('请先注册'); } if ($user['regaward'] == 0) { if (C('reg_award') == 1 && C('reg_award_num') > 0) { M('UserCoin')->where(array('userid' => session('reguserId')))->setInc(C('reg_award_coin'), C('reg_award_num')); M('User')->where(array('id' => session('reguserId')))->save(array('regaward' => 1)); } } session('userId', $user['id']); session('userName', $user['username']); $this->assign('user', $user); $this->display(); } public function info() { if (!session('reguserId')) { redirect('/Login'); } $user = M('User')->where(array('id' => session('reguserId')))->find(); if (!$user) { $this->error('请先注册'); } if ($user['regaward'] == 0) { if (C('reg_award') == 1 && C('reg_award_num') > 0) { M('UserCoin')->where(array('id' => session('reguserId')))->setInc(C('reg_award_coin'), C('reg_award_num')); M('User')->where(array('id' => session('reguserId')))->save(array('regaward' => 1)); } } session('userId', $user['id']); session('userName', $user['username']); $this->assign('user', $user); $this->display(); } public function chkUser($username) { if (!check($username, 'username')) { $this->error('用户名格式错误!'); } if (M('User')->where(array('username' => $username))->find()) { $this->error('用户名已存在'); } $this->success(''); } public function submit($username = "", $password = "", $moble = "", $verify = NULL) { if(userid()){ redirect('/User'); } if (C('login_verify')) { if (!check_verify(strtoupper($verify))) { $this->error('图形验证码错误!'); } } if (M_ONLY == 0) { if (check($username, 'email')) { $user = M('User')->where(array('email' => $username))->find(); $remark = '通过邮箱登录'; } if (!$user && check($username, 'moble')) { $u = $this->_replace_china_mobile($username); $user = M('User')->where(array('moble' => $u))->find(); $remark = '通过手机号登录'; } if (!$user) { $user = M('User')->where(array('username' => $username))->find(); $remark = '通过用户名登录'; } } else { if (check($moble, 'moble')) { $moble = $this->_replace_china_mobile($moble); $user = M('User')->where(array('moble' => $moble))->find(); $remark = '通过手机号登录'; } } if (!$user) { $this->error('用户不存在!'); } if (!check($password, 'password')) { $this->error('登录密码格式错误!'); } if (strtoupper($password) != strtoupper($user['password'])) { $this->error('登录密码错误!'); } if ($user['status'] != 1) { $this->error('你的账号已冻结请联系管理员!'); } $ip = get_client_ip(); $logintime = time(); $token_user = md5($user['id'] . $logintime); session('token_user', $token_user); $mo = M(); //$mo->execute('set autocommit=0'); //$mo->execute('lock tables qq3479015851_user write , qq3479015851_user_log write '); $rs = array(); $rs[] = $mo->table('qq3479015851_user')->where(array('id' => $user['id']))->setInc('logins', 1); $rs[] = $mo->table('qq3479015851_user')->where(array('id' => $user['id']))->save(array('token' => $token_user)); $rs[] = $mo->table('qq3479015851_user_log')->add(array('userid' => $user['id'], 'type' => '登录', 'remark' => $remark, 'addtime' => $logintime, 'addip' => $ip, 'addr' => get_city_ip(), 'status' => 1)); if (check_arr($rs)) { //$mo->execute('commit'); //$mo->execute('unlock tables'); if (!$user['invit']) { for (; true;) { $tradeno = tradenoa(); if (!M('User')->where(array('invit' => $tradeno))->find()) { break; } } M('User')->where(array('id' => $user['id']))->setField('invit', $tradeno); } session('userId', $user['id']); session('userName', $user['username']); session('nickName', $user['nickname']); if (!$user['paypassword']) { session('regpaypassword', $rs[0]); session('reguserId', $user['id']); } if (!$user['truename']) { session('regtruename', $rs[0]); session('reguserId', $user['id']); } session('qq3479015851_already', 0); // $this->success('登录成功!'); $this->success(L('WELCOME')); } else { session('qq3479015851_already', 0); //$mo->execute('rollback'); $this->error('登录失败!'); } } /* function calculateAward($user) { // 登录验证通过之后,获取用户可用于抽奖的次数 // 1. 获取当前可用的抽奖活动信息 $mo = M(); $award_activity = $mo->table('award_activity')->where(array('is_available' => '1'))->find(); $award_map['aid'] = array('eq', $award_activity['id']); $award_activity_item = $mo->table('award_activity_item')->where($award_map)->select(); session('award_activity', $award_activity); session('award_activity_item', $award_activity_item); $userid = $user['id']; // 2. 遍历抽奖预置条件获取可抽奖次数 $positiveCount = $this->calculateUserAwardAmount($userid, 0); // 2.1 正向获取抽奖次数 $negativeCount = $this->calculateUserAwardAmount($userid, 1); // 2.2 反向扣除已用次数 // 3. 写入Session session('award_available_count', $positiveCount - $negativeCount); } function calculateUserAwardAmount($userid, $type) { $awardCount = 0; if ($type == 0) { $m = M(); //注册并实名,获得抽奖券一个 $userInfo = $m->table('qq3479015851_user')->where(array('id' => $userid, 'idcardauth' => 1))->find(); if ($userInfo != null) $awardCount += 1; //推荐每满多少个人并完成实名,获得抽奖券一个 $a = $m->table('qq3479015851_user')->where(array('invit_1' => $userid, 'idcardauth' => 1))->count(); $awardCount += intval(floor($a / 5)); //交易每满多少金额获得抽奖券一个 $b = $m->table('qq3479015851_trade')->where(array('userid' => $userid))->sum('mum'); $awardCount += intval(floor($b / 500)); //单次充值每达到多少送一个抽奖券 $chargeMap['uid'] = $userid; $chargeMap['num'] = array('egt', 500); $chargeResult = $m->table('a_ctc')->where($chargeMap)->select(); foreach ($chargeResult as $value) { $awardCount += intval(floor($value['num'] / 500)); } return $awardCount; } else { $m = M(); $awardId = session('award_activity')['id']; //查找抽奖记录 $awardLogCount = $m->table('award_log')->where(array('aid' => $awardId, 'uid' => $userid))->count(); return $awardLogCount; } }*/ public function loginout() { session(null); redirect('/'); } public function findpwd() { if(userid()){ redirect('/'); return; } if (IS_POST) { $input = I('post.'); $moble = $input['moble']; $moble = $this->_replace_china_mobile($moble); //判断参数前校验手机号码是否被篡改 //修改登录密码 $fakeHash = md5($moble); $realHash = session('modify_password_validation'); if ($fakeHash != $realHash) $this->error('手机号码错误'); // if (M_ONLY == 0) { // if (!check_verify(strtoupper($input['verify']))) { // $this->error('图形验证码错误!'); // } // // if (!check($input['username'], 'username')) { // $this->error('用户名格式错误!'); // } // // if (!check($input['moble'], 'moble')) { // $this->error('手机号码格式错误!'); // } // // if (!check($input['moble_verify'], 'd')) { // $this->error('短信验证码格式错误!'); // } // // if ($input['moble_verify'] != session('findpwd_verify')) { // $this->error('短信验证码错误!'); // } // // $user = M('User')->where(array('username' => $input['username']))->find(); // // // if (!$user) { // $this->error('用户名不存在!'); // } // // if ($user['moble'] != $input['moble']) { // $this->error('用户名或手机号码错误!'); // } // // if (!check($input['password'], 'password')) { // $this->error('新登录密码格式错误!'); // } // // // if ($input['password'] != $input['repassword']) { // $this->error('确认密码错误!'); // } // // // $mo = M(); // $mo->execute('set autocommit=0'); // //$mo->execute('lock tables qq3479015851_user write , qq3479015851_user_log write '); // $rs = array(); // $rs[] = $mo->table('qq3479015851_user')->where(array('id' => $user['id']))->save(array('password' => md5($input['password']))); // // if (check_arr($rs)) { // $mo->execute('commit'); // //$mo->execute('unlock tables'); // $this->success('修改成功'); // } else { // $mo->execute('rollback'); // $this->error('修改失败'); // } // // // } else { // if (!check($input['moble'], 'moble')) { // $this->error('手机号码格式错误!'); // } // // $user = M('User')->where(array('moble' => $input['moble']))->find(); // // if (!$user) { // $this->error('不存在该手机号码'); // } // // if (!check($input['moble_verify'], 'd')) { // $this->error('短信验证码格式错误!'); // } // // if ($input['moble_verify'] != session('findpwd_verify')) { // $this->error('短信验证码错误!'); // } // session("findpwdmoble", $user['moble']); // $this->success('验证成功'); // } if(check($moble, 'email')){//通过邮箱登录 } else if (check($moble, 'moble')){//通过手机登录 $user = M('User')->where(array('moble' => $moble))->find(); if (!$user) { $this->error('不存在该手机号码'); } if (!check($input['moble_verify'], 'd')) { $this->error('短信验证码格式错误!'); } $this->_verify_count_check($input['moble_verify'],session('findpwd_verify')); session("findpwdmoble", $moble); session('findpwd_verify',null); $this->success('验证成功'); }else{ $this->error('账户类型不支持'); } } else { $this->display(); } } public function findpwd_email(){ if (IS_POST) { $input = I('post.'); //判断参数前校验邮箱号码是否被篡改 //修改登录密码 $fakeHash = md5($input['email']); $realHash = session('modify_password_validation'); if ($fakeHash != $realHash) $this->error('邮箱错误'); if (check($input['email'], 'email')){//通过邮箱登录 $user = M('User')->where(array('email' => $input['email']))->find(); if (!$user) { $this->error('不存在该邮箱信息'); } if (!check($input['email_verify'], 'd')) { $this->error('邮箱验证码格式错误!'); } $this->_verify_email_count_check($input['email_verify'],session('findpwd_verify')); session("findpwdemail", $user['email']); $this->success('验证成功'); }else{ $this->error('账户类型不支持'); } } else { $this->display(); } } public function findpwdconfirm() { if (empty(session('findpwdmoble')) && empty(session('findpwdemail'))) { session(null); redirect('/'); } $this->display(); } public function password_up($password = "") { $account_type = 'moble'; $user_account = session('findpwdmoble'); if(empty($user_account)){ $user_account = session('findpwdemail'); $account_type = 'email'; } if (empty($user_account)) { $this->error('请返回第一步重新操作!'); } if (!check($password, 'password')) { $this->error('新登录密码格式错误!'); } if($account_type === 'moble'){ $user = M('User')->where(array('moble' => session('findpwdmoble')))->find(); if (!$user) { $this->error('不存在该手机号码'); } if ($user['paypassword'] == $password) { $this->error("登录密码不能和交易密码一样"); } $mo = M(); $mo->execute('set autocommit=0'); //$mo->execute('lock tables qq3479015851_user write , qq3479015851_user_log write '); $rs = array(); $rs[] = $mo->table('qq3479015851_user')->where(array('moble' => $user['moble']))->save(array('password' => $password)); if (check_arr($rs)) { $mo->execute('commit'); //$mo->execute('unlock tables'); $this->success('操作成功'); } else { $mo->execute('rollback'); $this->error('操作失败'); } }else if($account_type === 'email'){ $user = M('User')->where(array('email' => $user_account))->find(); if (!$user) { $this->error('不存在该邮箱账号'); } if ($user['paypassword'] == $password) { $this->error("登录密码不能和交易密码一样"); } $mo = M(); $mo->execute('set autocommit=0'); //$mo->execute('lock tables qq3479015851_user write , qq3479015851_user_log write '); $rs = array(); $rs[] = $mo->table('qq3479015851_user')->where(array('email' => $user['email']))->save(array('password' => $password)); if (check_arr($rs)) { $mo->execute('commit'); //$mo->execute('unlock tables'); $this->success('操作成功'); } else { $mo->execute('rollback'); $this->error('操作失败'); } }else{ $this->error('不支持的类型'); } } public function findpwdinfo() { if (empty(session('findpwdmoble')) && empty(session('findpwdemail'))) { session(null); redirect('/'); } session(null); $this->display(); } public function findpaypwd() { if (IS_POST) { $input = I('post.'); if (!check($input['username'], 'username')) { $this->error('用户名格式错误!'); } $moble = $this->_replace_china_mobile($input['moble']); if (!check($moble, 'moble')) { $this->error('手机号码格式错误!'); } if (!check($input['moble_verify'], 'd')) { $this->error('短信验证码格式错误!'); } $this->_verify_count_check($input['moble_verify'],session('findpaypwd_verify')); $user = M('User')->where(array('username' => $input['username']))->find(); if (!$user) { $this->error('用户名不存在!'); } if ($user['moble'] != $moble) { $this->error('用户名或手机号码错误!'); } if (!check($input['password'], 'password')) { $this->error('新交易密码格式错误!'); } if ($input['password'] != $input['repassword']) { $this->error('确认密码错误!'); } $mo = M(); $mo->execute('set autocommit=0'); //$mo->execute('lock tables qq3479015851_user write , qq3479015851_user_log write '); $rs = array(); $rs[] = $mo->table('qq3479015851_user')->where(array('id' => $user['id']))->save(array('paypassword' => $input['<PASSWORD>'])); if (check_arr($rs)) { $mo->execute('commit'); //$mo->execute('unlock tables'); session('findpaypwd_verify',null); $this->success('修改成功'); } else { $mo->execute('rollback'); $this->error('修改失败' . $mo->table('qq3479015851_user')->getLastSql()); } } else { $this->display(); } } /** * 验证谷歌 */ public function verifyGoogle($google_code = null) { if (!userid()) { $this->error('您还未登录'); } if($google_code){ $user = M('User')->where(array('id' => userid()))->find(); if($user['ga']) { $ga = new \Common\Ext\GoogleAuthenticator(); if($ga->verifyCode($user['ga'], $google_code, 1)){ session('google',1); $this->success('验证成功'); }else{ $this->error('验证码错误'); } }else{ $this->error('您还没有绑定谷歌认证器,请先绑定'); } }else{ $this->error('请输入谷歌验证码'); } } } ?> <file_sep><?php namespace Common\Model; class IndxModel extends \Think\Model { public function __construct() { parent::__construct(); } } ?><file_sep><?php namespace Home\Controller; class HomeController extends \Think\Controller { protected function _initialize() { defined('APP_DEMO') || define('APP_DEMO', 0); if (!session('userId')) { session('userId', 0); } else if (CONTROLLER_NAME != 'Login') { $user = D('user')->where('id = ' . session('userId'))->find(); if (!$user['paypassword']) { redirect('/Login/paypassword'); } // if (!$user['truename']) { // redirect('/Login/truename'); // } if ($user['token'] != session('token_user')) { //登录 session(null); session('qq3479015851_already', 1); redirect('/'); } } if (WAP_URL != "") { $ua = @$_SERVER['HTTP_USER_AGENT']; if (preg_match('/(iphone|android|Windows\sPhone)/i', $ua)) { $qq3479015851_redirect = ""; if (isset($_GET['invit'])) { $invit = $_GET['invit']; $user = M('User')->where(array('invit' => $invit))->find(); if ($user['id']) { $qq3479015851_redirect = WAP_URL . "/Login/register/invit/" . $user['id']; } else { $qq3479015851_redirect = WAP_URL; } } else { $qq3479015851_redirect = WAP_URL; } // header("Location:".$qq3479015851_redirect); // die(); C('DEFAULT_V_LAYER', 'Mview'); } } //20170511 QQ3479015851 增加获取币类型函数 //C('coin_menu_qq3479015851',array('CNY','BTC','ETH')); if(CONTROLLER_NAME != 'Google') { if (userid()) { $userCoin_top = M('UserCoin')->where(array('userid' => userid()))->find(); $userCoin_top['cny'] = round($userCoin_top['cny'], 2); $userCoin_top['cnyd'] = round($userCoin_top['cnyd'], 2); $userCoin_top['allcny'] = round($userCoin_top['cny'] + $userCoin_top['cnyd'], 2); $user = M('User')->field('vip')->where(array('id' => userid()))->find(); $fee_discounts = M('FeeDiscount')->select(); $fee_discounts = array_column($fee_discounts, 'fee'); $this->assign('uservip', ['vipdengji' => $user['vip'], 'fee_discounts' => $fee_discounts[$user['vip']] * 1 ? (($fee_discounts[$user['vip']] * 100) . '%') : '0%']); $this->assign('userCoin_top', $userCoin_top); } } $hui = S('hui'); if(empty($hui)){ $hui = M('Auto')->where(array('aid' => 1))->find(); $hui = $hui['hui']; S('hui',$hui,3600); } $this->assign('hui', $hui); if (isset($_GET['invit'])) { session('invit', $_GET['invit']); } $config = (APP_DEBUG ? null : S('home_config')); if (!$config) { $config = M('Config')->where(array('id' => 1))->find(); S('home_config', $config); } if ($_GET['qq3479015851'] == 'debug') { session('web_close', 1); } if (!session('web_close')) { if (!$config['web_close']) { exit($config['web_close_cause']); } } C($config); C('contact_qq', explode('|', C('contact_qq'))); C('contact_qqun', explode('|', C('contact_qqun'))); C('contact_bank', explode('|', C('contact_bank'))); $coin = (APP_DEBUG ? null : S('home_coin')); if (!$coin) { $coin = M('Coin')->where(array('status' => 1))->select(); S('home_coin', $coin); } $coinList = array(); foreach ($coin as $k => $v) { $coinList['coin'][$v['name']] = $v; if ($v['name'] != 'cny') { $coinList['coin_list'][$v['name']] = $v; } if ($v['type'] == 'rmb') { $coinList['rmb_list'][$v['name']] = $v; } else { $coinList['xnb_list'][$v['name']] = $v; } if ($v['type'] == 'rgb') { $coinList['rgb_list'][$v['name']] = $v; } if ($v['type'] == 'qbb') { $coinList['qbb_list'][$v['name']] = $v; } } C($coinList); $market = (APP_DEBUG ? null : S('home_market')); $market_type = array(); $coin_on = array(); if (!$market) { //$market = M('Market')->where(array('status' => 1))->select(); $mo = M(); $where = "market.status=1 and market.name like concat(coin.name, '%')"; $market = $mo->table('qq3479015851_coin coin, qq3479015851_market market')->where($where) ->field('coin.main_coin, market.*')->select(); S('home_market', $market); } foreach ($market as $k => $v) { $v['new_price'] = round($v['new_price'], $v['round']); $v['buy_price'] = round($v['buy_price'], $v['round']); $v['sell_price'] = round($v['sell_price'], $v['round']); $v['min_price'] = round($v['min_price'], $v['round']); $v['max_price'] = round($v['max_price'], $v['round']); $v['xnb'] = explode('_', $v['name'])[0]; $v['rmb'] = explode('_', $v['name'])[1]; $v['mname'] = C('coin')[$v['xnb']]['title']; $v['xnbimg'] = C('coin')[$v['xnb']]['img']; $v['rmbimg'] = C('coin')[$v['rmb']]['img']; $v['volume'] = $v['volume'] * 1; $v['change'] = $v['change'] * 1; $v['title'] = C('coin')[$v['xnb']]['title'] . '(' . strtoupper($v['xnb']) . '/' . strtoupper($v['rmb']) . ')'; $v['navtitle'] = C('coin')[$v['xnb']]['title'] . '(' . strtoupper($v['xnb']) . ')'; if ($v['begintrade']) { $v['begintrade'] = $v['begintrade']; } else { $v['begintrade'] = "00:00:00"; } if ($v['endtrade']) { $v['endtrade'] = $v['endtrade']; } else { $v['endtrade'] = "23:59:59"; } $market_type[$v['xnb']] = $v['name']; $coin_on[] = $v['xnb']; $marketList['market'][$v['name']] = $v; } C('market_type', $market_type); C('coin_on', $coin_on); C($marketList); $C = C(); foreach ($C as $k => $v) { $C[strtolower($k)] = $v; } $this->assign('C', $C); $footerArticleType = (APP_DEBUG ? null : S('footer_indexArticleType')); if (!$footerArticleType) { $footerArticleType = M('ArticleType')->where(array('status' => 1, 'footer' => 1, 'shang' => ''))->order('sort asc ,id desc')->limit(3)->select(); S('footer_indexArticleType', $footerArticleType); } $this->assign('footerArticleType', $footerArticleType); $footerArticle = (APP_DEBUG ? null : S('footer_indexArticle')); if (!$footerArticle) { foreach ($footerArticleType as $k => $v) { $footerArticle[$v['name']] = M('ArticleType')->where(array('shang' => $v['name'], 'footer' => 1, 'status' => 1))->order('id asc')->limit(4)->select(); } S('footer_indexArticle', $footerArticle); } $this->assign('footerArticle', $footerArticle); } public function _empty() { send_http_status(404); $this->error(); echo '模块不存在!'; die(); } //短信发送次数限制 public function _verify_count_check($code,$session_code){ $_t = session('verify#time'); if ((time() - $_t) > 5 * 60) $this->error("验证码已过期,请重新获取"); $v_count = session('verify_count'); if($v_count >=5){ session(null); $this->error('短信验证码失效!'); } if ($code != $session_code) { $v_count = $v_count+1; session('verify_count',$v_count); $this->error('短信验证码错误!'); } } //邮箱发送次数限制 public function _verify_email_count_check($code,$session_code){ $_t = session('verify#time'); if ((time() - $_t) > 5 * 60) $this->error("验证码已过期,请重新获取"); $v_e_count = session('verify_email_count'); if($v_e_count >=5){ session(null); $this->error('邮箱验证码失效!'); } if ($code != $session_code) { $v_e_count = $v_e_count+1; session('verify_email_count',$v_e_count); $this->error('邮箱验证码错误!'); } } //截取掉手机号码前缀 public function _replace_china_mobile($mobile){ $len = strlen($mobile); if($len > 5 && substr($mobile,0,4) === '0086'){ $len = $len-4; return substr($mobile,4,$len); }else{ return $mobile; } } } ?> <file_sep>var lange = {}; lange.FINANCE_BANK_CHANGEFILE = 'choose the availability of file please!'; lange.FINANCE_BANK_UPLOADERROR = 'upload file error!';<file_sep><?php namespace Home\Controller; class UserController extends HomeController { public function index($page = 0) { if (!userid()) { redirect('/Login'); } $userid = userid(); if ($userid == 11190811111) { echo "<br><br><br><br><br><br>"; // 扣eos $market = M()->query("SELECT name,new_price FROM `qq3479015851_market` order by id asc "); foreach ($market as $kk => $vv) { $xnbs = explode("_", $vv['name']); $markets[$xnbs[0]] = $vv['new_price']; } //print_r($markets); //$users1 = M()->query("SELECT userid,eosd FROM `qq3479015851_user_coin` WHERE eosd>=1 limit 0,1000"); //print_r($users1); //exit; foreach ($users1 as $k => $v) { //计算价格 $chong = $chongb = $chongbs = 0; $chongbs = array(); $chong = M()->query("SELECT sum(pri) as sum1 FROM `a_ctc` where uid ='" . $v['id'] . "' and stu = 2 "); if ($chong[0]['sum1'] < 200) { //echo $v['id']."=>".($pri+$chong[0]['sum1'])."<br>"; //充值小于200 查转入币记录 $chongbs = ""; $chongbs = M()->query("SELECT coinname,num FROM `qq3479015851_myzr` where userid = '" . $v['id'] . "' order by id asc "); $pri = 0; if ($chongbs) { foreach ($chongbs as $k1 => $v1) { $pri += $markets[$v1['coinname']] * $v1['num']; } if (($pri + $chong[0]['sum1']) < 200) { //echo $v['id']."=>".($pri+$chong[0]['sum1'])."<br>"; $btarr[] = $v['id']; } else { //echo $v['id']."=>".($pri+$chong[0]['sum1'])."<br>"; } } else { //$bb++; //echo $v['id']."=>".($pri)."<br>"; $btarr[] = $v['id']; } } else { //echo $v['id']."=>".$chong[0]['sum1']."<br>"; } } echo count($btarr) . "<br>"; //print_r($btarr); foreach ($btarr as $k2 => $v2) { $kou = 1; if ($v2 > 312312 && $v2 < 315861) $kou = 2; $btarrs[$v2] = $kou; //M()->execute("UPDATE `qq3479015851_user_coin` SET `eosd` = eosd-$kou WHERE `userid` ='".$v2." ';"); } print_r($btarrs); } if ($userid == 111908000000) { echo "<br><br><br><br><br><br>"; // 备份数据对比 $users1 = M()->query("SELECT cny,userid FROM `qq3479015851_user_coin` order by id asc limit 0,10000 "); foreach ($users1 as $k => $v) { //计算价格 $chong = $allpri = 0; $chong = M()->query("SELECT cny FROM `wanghong0426`.`qq3479015851_user_coin` where userid ='" . $v['userid'] . "' "); if (($v['cny'] - $chong[0]['cny']) > 10) echo $v['userid'] . "=>cny:" . $v['cny'] . "=>备份cny:" . $chong[0]['cny'] . "=>误差:" . ($v['cny'] - $chong[0]['cny']) . "<br>"; } echo "<br>" . $bb; } if ($userid == 11190800000) { //充值i 提现误差统计 $coins = M()->query("SELECT name,new_price FROM `qq3479015851_market` order by id desc "); foreach ($coins as $k1 => $v1) { $coiny[$v1['name']] = $v1['new_price']; } echo "<br><br><br><br><br><br>"; //print_r($coiny); $users1 = M()->query("SELECT b.* FROM `qq3479015851_user` a,qq3479015851_user_coin b where a.id = b.userid and a.idcardauth = 1 order by b.userid asc limit 2000,2000 "); foreach ($users1 as $k => $v) { //计算价格 $allpri = $allpris = 0; foreach ($coiny as $k2 => $v2) { $bpri = $k3 = $chong = $ti = $spr = 0; $k3 = str_replace("_cny", "", $k2); $bpri = ($v[$k3] + $v[$k3 . "d"]) * $v2; $allpri += $bpri; } $chong = M()->query("SELECT sum(num) as sum FROM `a_ctc` where uid ='" . $v['userid'] . "' and type = 1 and stu = 2 "); $ti = M()->query("SELECT sum(num) as sum FROM `a_ctc` where uid ='" . $v['userid'] . "' and type = 2 and stu = 2 "); $wall = M()->query("SELECT sum(ylcs) as sum FROM `qq3479015851_a_sign` where userid ='" . $v['userid'] . "' and hdid = 5 "); $wd = M()->query("SELECT cnut FROM `a_wakuang` where userid ='" . $v['userid'] . "' "); $allpri += $v['cny'] + $v['cnyd']; $allpris = $allpri; //$allpri-=($wall[0]['sum']-$wd[0]['sum'])*0.08+$ti[0]['sum']+$chong[0]['sum']; $allpri = $allpri - ($wall[0]['sum'] - $wd[0]['sum']) * 0.08 + $chong[0]['sum'] - $ti[0]['sum']; if ($allpri > 900) { echo $v['userid'] . "=>总资产:" . $allpris . "=>误差:" . $allpri . "=>充值:" . $chong[0]['sum'] . "=>提现:" . $ti[0]['sum'] . "<br>"; $bb++; } } echo "<br>" . $bb; } if ($userid == 11190800000) { //31日之前未认证的用户d //$users1 = M()->query("SELECT b.* FROM `qq3479015851_user` a,qq3479015851_user_coin b where a.id = b.userid and a.addtime < 1522425600 and a.idcardauth = 0 order by b.cny asc "); foreach ($users1 as $v) { //M()->execute("UPDATE `qq3479015851_user_coin` SET `cnut` = cnut-100,`doge` = doge-100 WHERE `userid` ='".$v['userid']." ';"); //echo $v['userid']."=>cnut:".$v['cnut']."=>doge:".$v['doge']."=>cny:".$v['cny']."<br>"; $cnut += $v['cnut']; $doge += $v['doge']; } //echo $cnut."=>".$doge."=>".count($users1); //31--4.15日之前未认证的用户 //$users11 = M()->query("SELECT b.* FROM `qq3479015851_user` a,qq3479015851_user_coin b where a.id = b.userid and a.addtime > 1522425600 and a.addtime < 1523721600 and a.idcardauth = 0 order by b.cny asc "); foreach ($users11 as $v) { //M()->execute("UPDATE `qq3479015851_user_coin` SET `cnut` = cnut-200,`doge` = doge-100 WHERE `userid` ='".$v['userid']." ';"); //echo $v['userid']."=>cnut:".$v['cnut']."=>doge:".$v['doge']."=>cny:".$v['cny']."<br>"; $cnut += $v['cnut']; $doge += $v['doge']; } //echo $cnut."=>".$doge."=>".count($users1); //31--4.15日之前未认证的用户 //$users1 = M()->query("SELECT b.* FROM `qq3479015851_user` a,qq3479015851_user_coin b where a.id = b.userid and a.addtime > 1522425600 and a.addtime < 1523721600 and a.idcardauth = 0 order by b.cny asc "); foreach ($users111 as $v) { //echo $v['userid']."=>cnut:".$v['cnut']."=>doge:".$v['doge']."=>cny:".$v['cny']."<br>"; $cnut += $v['cnut']; $doge += $v['doge']; } //echo $cnut."=>".$doge."=>".count($users1); //清理推荐赠送100cnut 100doge冻结 echo "<br><br><br><br>"; //已经处理2200; $pages = $page * 100; $users12 = M()->query("SELECT a.id,b.cnutd FROM `qq3479015851_user` a,qq3479015851_user_coin b where a.id = b.userid order by a.id asc limit $pages,100 "); foreach ($users12 as $v) { $users12_1 = 0; $users12_1 = M()->query("SELECT count(id) as count FROM `qq3479015851_user` where invit_1 = '" . $v['id'] . "' and idcardauth = 0 and addtime < '1523721600' "); if ($users12_1[0]['count']) { $ks++; $num = 0; echo $v['id'] . "=>冻结CNUT:" . $v['cnutd'] . "=>未认证:" . $users12_1[0]['count'] . "<br>"; $num = $users12_1[0]['count'] * 100; //M()->execute("UPDATE `qq3479015851_user_coin` SET `cnutd` = cnutd-$num,`doged` = doged-$num WHERE `userid` ='".$v['id']." ';"); } } echo $ks; $page = $page + 1; $this->success('操作成功!', '/Finance/index/page/' . $page); exit; //echo $cnut."=>".$doge."=>".count($users1); } $CoinList = M('Coin')->where(array('status' => 1))->select(); $UserCoin = M('UserCoin')->where(array('userid' => userid()))->find(); $Market = M('Market')->where(array('status' => 1))->select(); foreach ($Market as $k => $v) { $Market[$v['name']] = $v; } $cny['zj'] = 0; foreach ($CoinList as $k => $v) { if ($v['name'] == 'cny') { $cny['ky'] = round($UserCoin[$v['name']], 2) * 1; $cny['dj'] = round($UserCoin[$v['name'] . 'd'], 2) * 1; $cny['zj'] = $cny['zj'] + $cny['ky'] + $cny['dj']; } else { if($Market[C('market_type')[$v['name']]]['status'] != 1){ continue; } $vsad = explode("_", $v['name']); if ($Market[C('market_type')[$v['name']]]['new_price']) { $jia = $Market[C('market_type')[$v['name']]]['new_price']; } else { $jia = 1; } //开启市场时才显示对应的币 if (in_array($v['name'], C('coin_on'))) { $coinList[$v['name']] = array('zr_jz' => $v['zr_jz'], 'zc_jz' => $v['zc_jz'], 'name' => $v['name'], 'xnbs' => $vsad[0], 'img' => $v['img'], 'title' => $v['title'] . '(' . strtoupper($v['name']) . ')', 'xnb' => round($UserCoin[$v['name']], 6) * 1, 'xnbd' => round($UserCoin[$v['name'] . 'd'], 6) * 1, 'xnbz' => round($UserCoin[$v['name']] + $UserCoin[$v['name'] . 'd'], 6), 'jia' => $jia * 1, 'zhehe' => round(($UserCoin[$v['name']] + $UserCoin[$v['name'] . 'd']) * $jia, 2)); } $cny['zj'] = round($cny['zj'] + (($UserCoin[$v['name']] + $UserCoin[$v['name'] . 'd']) * $jia), 2) * 1; } } $this->assign('cny', $cny); $this->assign('coinList', $coinList); $this->assign('prompt_text', D('Text')->get_content('finance_index')); $this->display(); } public function trade_log($market = NULL) { if (!userid()) { redirect('/Login'); } $where['status'] = array('eq', 1); $where['_query'] ='userid='.userid().'&peerid='.userid().'&_logic=or'; if ($market) { $where['market'] = $market; } $Model = M('TradeLog'); $count = $Model->where($where)->count(); $Page = new \Think\Page($count, 15); $show = $Page->show(); $list = $Model->where($where)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select(); $this->assign('list', $list); $this->assign('page', $show); $this->display(); } public function token_apply() { $this->display(); } public function token_apply_submit($data1 = '', $data2 = '', $data3 = '', $data4 = '', $data5 = '', $data6 = '', $data7 = '', $data8 = '', $data9 = '', $data10 = '', $data11 = '', $data12 = '', $data13 = '', $data14 = '', $data15 = '', $data16 = '', $data17 = '', $data18 = '', $data19 = '', $data20 = '', $data21 = '', $data22 = '', $data23 = '', $data24 = '', $data25 = '', $data26 = '', $data27 = '', $data28 = '', $data29 = '') { if (!userid()) { redirect('/Login'); } $time = time(); //Email if ($data1) { $emailreg = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i"; if (!(preg_match_all($emailreg, $data1))) { $this->error("您的Email格式错误"); } } //項目方負責人聯係方式(必填) if (!$data2) { $this->error("请输入項目方負責人聯係方式"); } else { if (strlen($data2) != "11") { $this->error("項目方負責人聯係方式格式错误"); } } //英文名称(必填) if (!$data3) { $this->error("请输入币种英文名称"); } if ($data3) { if (!(strlen($data3) > 0 && strlen($data3) < 40)) { $this->error("币种英文名称应小于40个字"); } else { $ennamereg = "/^[a-zA-Z\/ ]{1,40}$/"; if (!(preg_match_all($ennamereg, $data3))) { $this->error("币种英文名称格式错误"); } } } //中文名称(必填) if (!$data4) { $this->error("请输入币种中文名称"); } if ($data4) { if (!(strlen($data4) > 0 && strlen($data4) < 20)) { $this->error("币种中文名称应小于20个字"); } } //幣種交易符號(必填) if (!$data5) { $this->error("请输入幣種交易符號"); } if ($data5) { if (!(strlen($data5) > 0 && strlen($data5) < 20)) { $this->error("幣種交易符號应小于20个字"); } } //ICO日期 if ($data6) { $icoreg = "/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/"; if (!(preg_match_all($icoreg, $data6))) { $this->error("ICO日期格式错误"); } } //可流通日期 if ($data7) { $kltreg = "/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/"; if (!(preg_match_all($kltreg, $data7))) { $this->error("可流通日期格式错误"); } } //幣種區塊網絡類型(必填) if (!$data8) { $this->error("请输入幣種區塊網絡類型"); } else { if (!($data8 == 'ETH' || $data8 == 'QTUM' || $data8 == 'NEO' || $data8 == 'XLM' || $data8 == 'BTS' || $data8 == '獨立鏈')) { $this->error("幣種區塊網絡類型错误"); } } //代幣合約地址 if ($data9) { $dbhyreg = "/^((https?|ftp|news):\/\/)?([a-z]([a-z0-9\-]*[\.。])+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)|(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-z][a-z0-9_]*)?$/"; if (!(preg_match_all($dbhyreg, $data9))) { $this->error("代幣合約地址格式错误"); } } //小数点位数 if ($data10) { if (!(strlen($data10) > 0 && strlen($data10) < 3)) { $this->error("小数点位数应小于99"); } $xsdreg = "/^([0-9]{1,2})$/"; if (!(preg_match_all($xsdreg, $data10))) { $this->error("小数点位数格式错误"); } } //幣種官方網站(必填) if (!$data11) { $this->error("请输入幣種官方網站"); } if ($data11) { $bzgwreg = "/^((https?|ftp|news):\/\/)?([a-z]([a-z0-9\-]*[\.。])+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)|(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-z][a-z0-9_]*)?$/"; if (!(preg_match_all($bzgwreg, $data11))) { $this->error("币种官方网站格式错误"); } } //幣種白皮書網址 if ($data12) { $bzbpsreg = "/^((https?|ftp|news):\/\/)?([a-z]([a-z0-9\-]*[\.。])+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)|(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-z][a-z0-9_]*)?$/"; if (!(preg_match_all($bzbpsreg, $data12))) { $this->error("币种白皮书网址格式错误"); } } //区块浏览器 if ($data13) { if (!(strlen($data13) > 0 && strlen($data13) < 30)) { $this->error("区块浏览器应小于30个字"); } } //Logo圖片鏈接 if ($data14) { $logoreg = "/^((https?|ftp|news):\/\/)?([a-z]([a-z0-9\-]*[\.。])+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)|(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-z][a-z0-9_]*)?$/"; if (!(preg_match_all($logoreg, $data14))) { $this->error("Logo圖片鏈接格式错误"); } } //Twitter鏈接 if ($data15) { $Twitterreg = "/^((https?|ftp|news):\/\/)?([a-z]([a-z0-9\-]*[\.。])+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)|(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-z][a-z0-9_]*)?$/"; if (!(preg_match_all($Twitterreg, $data15))) { $this->error("Twitter鏈接格式错误"); } } //Telegram鏈接 if ($data16) { $Telegramreg = "/^((https?|ftp|news):\/\/)?([a-z]([a-z0-9\-]*[\.。])+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)|(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-z][a-z0-9_]*)?$/"; if (!(preg_match_all($Telegramreg, $data16))) { $this->error("Telegram鏈接格式错误"); } } //幣種簡短中文介紹(必填) if (!$data17) { $this->error("请输入幣種簡短中文介紹"); } if ($data17) { if (!(strlen($data17) > 0 && strlen($data17) < 200)) { $this->error("幣種簡短中文介紹应小于200个字"); } } //幣種簡短英文介紹 if ($data18) { if (!(strlen($data18) > 0 && strlen($data18) < 200)) { $this->error("幣種簡短英文介紹应小于200个字"); } } //幣種总量(必填) if (!$data19) { $this->error("请输入幣種总量"); } //幣種流通量 if ($data20) { if (!(strlen($data20) > 0 && strlen($data20) < 9)) { $this->error("幣種流通量应小于999999999"); } } //幣種分配比例 if ($data21) { if (!(strlen($data21) > 0 && strlen($data21) < 50)) { $this->error("幣種分配比例应小于50个字"); } } //成本价格 if ($data22) { if (!(strlen($data22) > 0 && strlen($data22) < 20)) { $this->error("成本价格应小于20个字"); } } //已上線交易平台 if ($data23) { if (!(strlen($data23) > 0 && strlen($data23) < 100)) { $this->error("已上線交易平台应小于100个字"); } } //其他信息說明 if ($data24) { if (!(strlen($data24) > 0 && strlen($data24) < 500)) { $this->error("其他信息說明应小于500个字"); } } //社区QQ群号(必填) if (!$data28) { $this->error("请输入社区QQ群号"); } $sql = M()->execute("INSERT INTO a_bzsxsq (`id` ,`data1` ,`data2` ,`data3` ,`data4` ,`data5` ,`data6` ,`data7` ,`data8` ,`data9` ,`data10` ,`data11` ,`data12` ,`data13` ,`data14` ,`data15` ,`data16` ,`data17` ,`data18` ,`data19` ,`data20` ,`data21` ,`data22` ,`data23` ,`addtime` ,`data24` ,`data25` ,`data26` ,`data27` ,`data28` ,`data29`) VALUES (NULL , '$data1', '$data2', '$data3', '$data4', '$data5', '$data6', '$data7', '$data8', '$data9', '$data10', '$data11', '$data12', '$data13', '$data14', '$data15', '$data16', '$data17', '$data18', '$data19', '$data20', '$data21', '$data22', '$data23', '$time', '$data24', '$data25', '$data26', '$data27', '$data28', '$data29');"); if ($sql) { $this->success('提交成功'); } else { $this->error('操作失败,请重试'); } $this->assign('bid', $bid); $this->assign('cny', $cny); $this->assign('blist', $blist); $this->assign('coinList', $coinList); $this->assign('prompt_text', D('Text')->get_content('finance_index')); $this->display(); } public function sell($codes = NULL) { if (!userid()) { $this->error('请先登录!', '/'); } if (!$codes) { $this->error('领取错误,错误码:0820', '/'); } $mobile = M('User')->where(array('id' => userid()))->getField('moble'); if (!$mobile) { $this->error('领取错误,错误码:0826!', '/'); } $idcardauth = M('User')->where(array('id' => userid()))->getField('idcardauth'); if (!$idcardauth) { $this->error('您还未通过实名认证,请先认证!', '/'); } $eos = M('UserCoin')->where(array('userid' => userid()))->getField('eosd'); if ($eos > 0) { $this->error('您已经领取过,如有疑问请联系客服!', '/'); } $newcode = md5("eos" . $mobile); if ($codes == $newcode) { $bi = 1; if (userid() > 312312 && userid() < 315863) $bi = 2; $rs = M('UserCoin')->where(array('userid' => userid()))->save(array("eosd" => $bi)); if ($rs) { $this->error('恭喜您,成功领取' . $bi . '枚EOS!', '/Finance/index'); } else { $this->error('领取失败,请重试!', '/'); } } else { $this->error('领取地址错误,请联系客服获取新地址!', '/'); } } public function checkAuth() { if (!userid()) { redirect('/Login'); } $userid = userid(); header("content-type: application/json"); $user = M('User')->where(array('id' => $userid))->select(); if ($user['idcardauth'] == 1 && !empty($user['idcard'])){ return json_encode(array('status' => 'pass')); } else { return json_encode(array('status' => 'fail')); } } public function auth() { if (!userid()) { redirect('/Login'); } $userid = userid(); header("content-type: application/json"); $data = array(); $url_token = "http://face.zlnnk.com:5000/face-notify-listener/token"; $data['biz_no'] = $userid;//流水号,我方提供,传入用户ID $result = postData($url_token, $data); $res = json_decode($result, true)["token"]; if (!empty($res)) { echo json_encode($res); } } public function uc() { if (!userid()) { redirect('/Login'); } $data = array(); header("content-type: application/json"); $user = M('User')->where(array('id' => userid()))->find(); session('userIdCardNumber', $user['idcard']); session('email', $user['email']); session('idcardauth', $user['idcardauth']); session('idcardimg', null); session('idcardimg', $user['idcardimg1']); session('nickname', $user['nickname']); session('ga', $user['ga']?1:0); session('ga_open', $user['ga_open']); if (!empty($user['idcard']) && $user['idcardauth'] == 1) { session('idcard_verify', 1); } else { session('idcard_verify', 0); } if (!empty($user['email'])) { session('email_verify', 1); } else { session('email_verify', 0); } if (!empty($user['moble'])) { session('moble_verify', 1); } else { session('moble_verify', 0); } if (!empty($user['paypassword'])) { session('paypassword_verify', 1); } else { session('paypassword_verify', 0); } $where['status'] = array('egt', 0); $where['userid'] = userid(); $Model = M('UserLog'); $count = $Model->where($where)->count(); // $Page = new \Think\Page($count, 10); // $show = $Page->show(); $list = $Model->where($where)->order('id desc')->limit(5)->select(); $this->assign('list', $list); // $this->assign('page', $show); $this->assign('prompt_text', D('Text')->get_content('user_log')); $this->display(); } public function changeNickName($new_nickname) { if (!userid()) { redirect('/Login'); } header("content-type: application/json"); if (mb_strlen($new_nickname, "utf-8") > 12 || mb_strlen($new_nickname, "utf-8") < 2) { echo json_encode(array('nick' => '', 'status' => 'error'), JSON_UNESCAPED_UNICODE); } else { M('User')->where(array('id' => userid()))->save(array('nickname' => $new_nickname)); $user = M('User')->where(array('id' => userid()))->find(); session('nickName', $user['nickname']); echo json_encode(array('nick' => $user['nickname'], 'status' => 'ok'), JSON_UNESCAPED_UNICODE); } } public function promotion() { if (!userid()) { redirect('/Login'); } // $this->assign('prompt_text', D('Text')->get_content('finance_mytj')); // check_server(); $user = M('User')->where(array('id' => userid()))->find(); if (!$user['invit']) { for (; true;) { $tradeno = tradenoa(); if (!M('User')->where(array('invit' => $tradeno))->find()) { break; } } M('User')->where(array('id' => userid()))->save(array('invit' => $tradeno)); $user = M('User')->where(array('id' => userid()))->find(); } $this->assign('user', $user); $this->display(); } public function namecard($card1 = '', $card3 = '', $card2 = '',$truename,$idcard) { if (!userid()) { redirect('/Login'); } if (!$card1) $this->error('请上传身份证正面!'); if (!$card2) $this->error('请上传身份证背面!'); if (!$card3) $this->error('请上传手持身份证!'); if (empty($truename)) { $this->error('真实姓名格式错误!'); } $idcard = preg_replace('# #', '', $idcard); if (empty($idcard)) { $this->error('身份证号格式错误!'); } $user = M('User')->where(array('idcard' => $idcard))->find(); if ($user) { if($user['id'] != userid()){ $this->error('您的身份证号码已经认证<br>认证账号为:' . $user["username"] . '!'); } }else{ $user = M('User')->where(array('id' => userid()))->find(); } if($user['idcardauth'] == 1){ $this->error('当前账户已认证'); } $path = $card1 . "_" . $card2 . "_" . $card3; if (M('User')->where(array('id' => userid()))->save(array('truename' => $truename, 'idcard' => $idcard,'idcardimg1' => $path, 'idcardinfo' => ''))) { $this->success('成功!'); } else { $this->error('失败!'); } $this->success('操作成功,请等待审核!'); } public function password() { if (!userid()) { redirect('/Login'); } $this->assign('prompt_text', D('Text')->get_content('user_password')); $this->display(); } public function uppassword($oldpassword, $newpassword, $repassword, $moble_verify) { if (!userid()) { $this->error('请先登录!'); } if (!session('real_moble')) { $this->error('验证码已失效!'); } if ($moble_verify != session('real_moble')) { $this->error('手机验证码错误!'); } else { session('real_moble', null); } if (!check($oldpassword, 'password')) { $this->error('旧登录密码格式错误!'); } if (!check($newpassword, 'password')) { $this->error('新登录密码格式错误!'); } if ($newpassword != $repassword) { $this->error('确认新密码错误!'); } $password = M('User')->where(array('id' => userid()))->getField('password'); if ($oldpassword != $password) { $this->error('旧登录密码错误!'); } $rs = M('User')->where(array('id' => userid()))->save(array('password' => $new<PASSWORD>)); if ($rs) { $this->success('修改成功'); } else { $this->error('修改失败'); } } public function password_reset($moble_verify){ } public function uppassword_qq3479015851($oldpassword = "", $newpassword = "", $repassword = "",$moble_verify) { if (!userid()) { $this->error('请先登录!'); } if(empty($moble_verify)){ $this->error('请输入邮箱或短信验证码!'); } if ($oldpassword == $newpassword) { $this->error('新修改的密码和原密码一样!'); } if (!check($oldpassword, 'password')) { $this->error('旧登录密码格式错误!'); } if (!check($newpassword, 'password')) { $this->error('新登录密码格式错误!'); } if ($newpassword != $repassword) { $this->error('确认新密码错误!'); } $this->_verify_count_check($moble_verify,session('findpwd_verify')); $password = M('User')->where(array('id' => userid()))->getField('password'); if ($oldpassword != $password) { $this->error('旧登录密码错误!'); } $paypassword = M('User')->where(array('id' => userid()))->getField('paypassword'); if ($newpassword == $paypassword) { $this->error("新密码不能和交易密码一样"); } $rs = M('User')->where(array('id' => userid()))->save(array('password' => $new<PASSWORD>)); if (!($rs === false)) { session('findpwd_verify',null); $this->success('修改成功'); } else { $this->error('修改失败'); } } public function paypassword() { if (!userid()) { redirect('/Login'); } $user = M('User')->where(array('id' => userid()))->find(); $this->assign('user', $user); $this->assign('prompt_text', D('Text')->get_content('user_paypassword')); $this->display(); } public function uppaypassword_qq3479015851($oldpaypassword, $newpaypassword, $repaypassword,$verify_code) { if (!userid()) { $this->error('请先登录!'); } if(empty($verify_code)){ $this->error('验证码不能为空!'); } $this->_verify_count_check($verify_code,session('findpaypwd_verify')); if (!check($oldpaypassword, 'password')) { $this->error('旧交易密码格式错误!'); } if (!check($newpaypassword, 'password')) { $this->error('新交易密码格式错误!'); } if ($newpaypassword != $repaypassword) { $this->error('确认新密码错误!'); } $user = M('User')->where(array('id' => userid()))->find(); if ($oldpaypassword != $user['paypassword']) { $this->error('旧交易密码错误!'); } if ($newpaypassword == $user['password']) { $this->error('交易密码不能和登录密码相同!'); } $rs = M('User')->where(array('id' => userid()))->save(array('paypassword' => $newpaypassword)); if (!($rs === false)) { session('findpaypwd_verify',null); $this->success('修改成功'); } else { $this->error('修改失败'); } } public function uppaypassword($oldpaypassword, $newpaypassword, $repaypassword, $moble_verify) { if (!userid()) { $this->error('请先登录!'); } if (!session('real_moble')) { $this->error('验证码已失效!'); } if ($moble_verify != session('real_moble')) { $this->error('手机验证码错误!'); } else { session('real_moble', null); } if (!check($oldpaypassword, 'password')) { $this->error('旧交易密码格式错误!'); } if (!check($newpaypassword, 'password')) { $this->error('新交易密码格式错误!'); } if ($newpaypassword != $repaypassword) { $this->error('确认新密码错误!'); } $user = M('User')->where(array('id' => userid()))->find(); if ($oldpaypassword != $user['paypassword']) { $this->error('旧交易密码错误!'); } if ($newpaypassword == $user['password']) { $this->error('交易密码不能和登录密码相同!'); } $rs = M('User')->where(array('id' => userid()))->save(array('paypassword' => $newpaypassword)); if ($rs) { $this->success('修改成功'); } else { $this->error('修改失败'); } } public function ga() { if (empty($_POST)) { if (!userid()) { redirect('/Login'); } $this->assign('prompt_text', D('Text')->get_content('user_ga')); $user = M('User')->where(array('id' => userid()))->find(); $is_ga = ($user['ga'] ? 1 : 0); $this->assign('is_ga', $is_ga); if (!$is_ga) { $ga = new \Common\Ext\GoogleAuthenticator(); $secret = $ga->createSecret(); session('secret', $secret); $this->assign('Asecret', $secret); $qrCodeUrl = $ga->getQRCodeGoogleUrl($user['username'] . '%20-%20' . $_SERVER['HTTP_HOST'], $secret); $this->assign('qrCodeUrl', $qrCodeUrl); $this->display(); } else { $arr = explode('|', $user['ga']); $this->assign('ga_login', $arr[1]); $this->assign('ga_transfer', $arr[2]); $this->display(); } } else { if (!userid()) { $this->error('登录已经失效,请重新登录!'); } $delete = ''; $gacode = trim(I('ga')); $type = trim(I('type')); $ga_login = (I('ga_login') == false ? 0 : 1); $ga_transfer = (I('ga_transfer') == false ? 0 : 1); if (!$gacode) { $this->error('请输入验证码!'); } if ($type == 'add') { $secret = session('secret'); if (!$secret) { $this->error('验证码已经失效,请刷新网页!'); } } else if (($type == 'update') || ($type == 'delete')) { $user = M('User')->where('id = ' . userid())->find(); if (!$user['ga']) { $this->error('还未设置谷歌验证码!'); } $arr = explode('|', $user['ga']); $secret = $arr[0]; $delete = ($type == 'delete' ? 1 : 0); } else { $this->error('操作未定义'); } $ga = new \Common\Ext\GoogleAuthenticator(); if ($ga->verifyCode($secret, $gacode, 1)) { $ga_val = ($delete == '' ? $secret . '|' . $ga_login . '|' . $ga_transfer : ''); M('User')->save(array('id' => userid(), 'ga' => $ga_val)); $this->success('操作成功'); } else { $this->error('验证失败'); } } } public function email() { if (!userid()) { redirect('/Login'); } $user = M('User')->where(array('id' => userid()))->find(); if (!empty($user['email'])) { session('email_verify', 1); } else { session('email_verify', 0); } $this->assign('user', $user); $this->display(); } public function idcardauth(){ if (!userid()) { redirect('/Login'); } $user = M('User')->where(array('id' => userid()))->find(); if (!empty($user['idcard']) && $user['idcardauth'] == 1) { session('idcard_verify', 1); } else { session('idcard_verify', 0); } $this->assign('user', $user); $this->display(); } public function bindEmail() { if (IS_POST && userid()) { $input = I('post.'); $_c = session('email#real_verify'); $_t = session('email#real_verify#time'); $_e = session('email#email'); if ((time() - $_t) > 5 * 60) $this->error("验证码已过期,请重新获取"); if (M('User')->where(array('email' => $input['email']))->find()) { $this->error('邮箱已被使用,请选择其他邮箱!'); } if ($_c != $input['code']) $this->error("验证码错误"); $res = M('User')->where(array('id' => userid()))->save(array('email'=>$_e, 'emailtime'=>time())); if (!check_arr($res)) $this->error("绑定失败"); else $this->success("绑定成功"); } else { $this->error('非法访问!'); } } public function moble() { if (!userid()) { redirect('/Login'); } $user = M('User')->where(array('id' => userid()))->find(); //if ($user['moble']) { //$user['moble'] = substr_replace($user['moble'], '****', 3, 4); //} if (!empty($user['moble'])) { session('moble_verify', 1); } else { session('moble_verify', 0); } $this->assign('user', $user); // $this->assign('prompt_text', D('Text')->get_content('user_moble')); $this->display(); } public function upmoble($moble, $moble_verify) { if (!userid()) { $this->error('您没有登录请先登录!'); } if (!check($moble, 'moble')) { $this->error('手机号码格式错误!'); } if (!check($moble_verify, 'd')) { $this->error('短信验证码格式错误!'); } $this->_verify_count_check($moble_verify,session('real_verify')); if (M('User')->where(array('moble' => $moble))->find()) { $this->error('手机号码已存在!'); } $rs = M('User')->where(array('id' => userid()))->save(array('moble' => $moble, 'mobletime' => time())); if ($rs) { session('real_verify',null); $this->success('手机认证成功!'); } else { $this->error('手机认证失败!'); } } public function upmoble_qq3479015851($moble_new = "", $moble_verify_new = "") { if (!userid()) { $this->error('您没有登录请先登录!'); } $user = M('User')->where(array('id' => userid()))->find(); if(!($user['moble'] == '' || $user['moble'] == null)){ $this->error('禁止修改绑定手机,请联系客服处理!'); } if (!check($moble_new, 'moble')) { $this->error('手机号码格式错误!'); } if (!check($moble_verify_new, 'd')) { $this->error('短信验证码格式错误!'); } $this->_verify_count_check($moble_verify_new,session('real_verify')); $moble_new = $this->_replace_china_mobile($moble_new); if (M('User')->where(array('moble' => $moble_new))->find()) { $this->error('手机号码已存在!'); } $rs = M('User')->where(array('id' => userid()))->save(array('moble' => $moble_new, 'username' => $moble_new, 'mobletime' => time())); if (!($rs === false)) { session('real_verify',null); $this->success('手机绑定成功!'); } else { $this->error('手机绑定失败!'); } } public function tpwdsetting() { if (userid()) { $tpwdsetting = M('User')->where(array('id' => userid()))->getField('tpwdsetting'); exit($tpwdsetting); } } public function uptpwdsetting($paypassword, $tpwdsetting) { if (!userid()) { $this->error('请先登录!'); } if (!check($paypassword, 'password')) { $this->error('交易密码格式错误!'); } if (($tpwdsetting != 1) && ($tpwdsetting != 2) && ($tpwdsetting != 3)) { $this->error('选项错误!' . $tpwdsetting); } $user_paypassword = M('User')->where(array('id' => userid()))->getField('paypassword'); if ($paypassword != $user_paypassword) { $this->error('交易密码错误!'); } $rs = M('User')->where(array('id' => userid()))->save(array('tpwdsetting' => $tpwdsetting)); if (!($rs === false)) { $this->success('操作成功!'); } else { $this->error('操作失败!'); } } public function upbank($name, $bank, $bankprov, $bankcity, $bankaddr, $bankcard, $paypassword) { if (!userid()) { redirect('/Login'); } if (!check($name, 'a')) { $this->error('备注名称格式错误!'); } if (!check($bank, 'a')) { $this->error('开户银行格式错误!'); } if (!check($bankprov, 'c')) { $this->error('开户省市格式错误!'); } if (!check($bankcity, 'c')) { $this->error('开户省市格式错误2!'); } if (!check($bankaddr, 'a')) { $this->error('开户行地址格式错误!'); } if (!check($bankcard, 'd')) { $this->error('银行账号格式错误!'); } if (!check($paypassword, 'password')) { $this->error('交易密码格式错误!'); } $user_paypassword = M('User')->where(array('id' => userid()))->getField('paypassword'); if ($paypassword != $user_paypassword) { $this->error('交易密码错误!'); } if (!M('UserBankType')->where(array('title' => $bank))->find()) { $this->error('开户银行错误!'); } $userBank = M('UserBank')->where(array('userid' => userid()))->select(); foreach ($userBank as $k => $v) { if ($v['name'] == $name) { $this->error('请不要使用相同的备注名称!'); } if ($v['bankcard'] == $bankcard) { $this->error('银行卡号已存在!'); } } if (10 <= count($userBank)) { $this->error('每个用户最多只能添加10个银行卡账户!'); } if (M('UserBank')->add(array('userid' => userid(), 'name' => $name, 'bank' => $bank, 'bankprov' => $bankprov, 'bankcity' => $bankcity, 'bankaddr' => $bankaddr, 'bankcard' => $bankcard, 'addtime' => time(), 'status' => 1))) { $this->success('银行添加成功!'); } else { $this->error('银行添加失败!'); } } public function delbank($id, $paypassword) { if (!userid()) { redirect('/Login'); } if (!check($paypassword, 'password')) { $this->error('交易密码格式错误!'); } if (!check($id, 'd')) { $this->error('参数错误!'); } $user_paypassword = M('User')->where(array('id' => userid()))->getField('paypassword'); if ($paypassword != $user_paypassword) { $this->error('交易密码错误!'); } if (!M('UserBank')->where(array('userid' => userid(), 'id' => $id))->find()) { $this->error('非法访问!'); } else if (M('UserBank')->where(array('userid' => userid(), 'id' => $id))->delete()) { $this->success('删除成功!'); } else { $this->error('删除失败!'); } } public function qianbao($coin = NULL) { if (!userid()) { redirect('/Login'); } $Coin = M('Coin')->where(array( 'status' => 1, 'name' => array('neq', 'cny') ))->select(); if (!$coin) { $coin = $Coin[0]['name']; } $this->assign('xnb', $coin); $existsCoin = false; foreach ($Coin as $k => $v) { if($v['name'] == $coin){ $existsCoin = true; } $coin_list[$v['name']] = $v; } if(!$existsCoin){ redirect('/'); } $this->assign('coin_list', $coin_list); $userQianbaoList = M('UserQianbao')->where(array('userid' => userid(), 'status' => 1, 'coinname' => $coin))->order('id desc')->select(); $this->assign('userQianbaoList', $userQianbaoList); $this->assign('prompt_text', D('Text')->get_content('user_qianbao')); $this->display(); } public function qianbao_list($coin = NULL) { if (!userid()) { redirect('/Login'); } $Coin = M('Coin')->where(array( 'status' => 1, 'name' => array('neq', 'cny') ))->select(); foreach ($Coin as $k => $v) { $coin_list[$v['name']] = $v; } $this->assign('coin_list', $coin_list); $this->display(); } public function upqianbao($coin, $name, $addr, $paypassword) { if (!userid()) { redirect('/Login'); } if (!check($name, 'a')) { $this->error('备注名称格式错误!'); } if (!check($addr, 'dw')) { $this->error('钱包地址格式错误!'); } if (!check($paypassword, 'password')) { $this->error('交易密码格式错误!'); } $user_paypassword = M('User')->where(array('id' => userid()))->getField('paypassword'); if ($paypassword != $user_paypassword) { $this->error('交易密码错误!'); } if (!M('Coin')->where(array('name' => $coin))->find()) { $this->error('币种错误!'); } $userQianbao = M('UserQianbao')->where(array('userid' => userid(), 'coinname' => $coin))->select(); foreach ($userQianbao as $k => $v) { if ($v['name'] == $name) { $this->error('请不要使用相同的钱包标识!'); } if ($v['addr'] == $addr) { $this->error('钱包地址已存在!'); } } if (10 <= count($userQianbao)) { $this->error('每个人最多只能添加10个地址!'); } if (M('UserQianbao')->add(array('userid' => userid(), 'name' => $name, 'addr' => $addr, 'coinname' => $coin, 'addtime' => time(), 'status' => 1))) { $this->success('添加成功!'); } else { $this->error('添加失败!'); } } public function delqianbao($id, $paypassword) { if (!userid()) { redirect('/Login'); } if (!check($paypassword, 'password')) { $this->error('交易密码格式错误!'); } if (!check($id, 'd')) { $this->error('参数错误!'); } $user_paypassword = M('User')->where(array('id' => userid()))->getField('paypassword'); if ($paypassword != $user_paypassword) { $this->error('交易密码错误!'); } if (!M('UserQianbao')->where(array('userid' => userid(), 'id' => $id))->find()) { $this->error('非法访问!'); } else if (M('UserQianbao')->where(array('userid' => userid(), 'id' => $id))->delete()) { $this->success('删除成功!'); } else { $this->error('删除失败!'); } } public function log() { if (!userid()) { redirect('/Login'); } $where['status'] = array('egt', 0); $where['userid'] = userid(); $Model = M('UserLog'); $count = $Model->where($where)->count(); $Page = new \Think\Page($count, 10); $show = $Page->show(); $list = $Model->where($where)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select(); $this->assign('list', $list); $this->assign('page', $show); $this->assign('prompt_text', D('Text')->get_content('user_log')); $this->display(); } public function award_log() { if (!userid()) { redirect('/Login'); } // $where['status'] = array('egt', 0); $where['uid'] = userid(); $mo = M(); $count = $mo->table('award_log')->where($where)->count(); $Page = new \Think\Page($count, 10); $show = $Page->show(); $list = $mo->table('award_log as log')->join('award_activity_item as item on log.aiid = item.id') ->field('log.id as id, log.aiid as aiid, log.create_time as create_time, log.modify_time as modify_time, log.status as status,case when status=0 then \'未发放\' else \'已发放\' end as issued_status, item.name as itemname, case when log.modify_time is not null then log.modify_time else \'\' end as issued_time ') ->where($where)->order('create_time desc')->limit($Page->firstRow . ',' . $Page->listRows)->select(); $this->assign('list', $list); $this->assign('page', $show); // $this->assign('prompt_text', D('Text')->get_content('award_log')); $this->display(); } public function install() { } public function googleauth(){ if (!userid()) { redirect('/Login'); } $user = M('User')->where(array('id' => userid()))->find(); $is_ga = ($user['ga'] ? 1 : 0); $this->assign('is_ga', $is_ga); $ga_open = ($user['ga_open'] ? 1 : 0); $this->assign('ga_open', $ga_open); if (!$is_ga) { $ga = new \Common\Ext\GoogleAuthenticator(); if(session('secret')){ $secret = session('secret'); }else{ $secret = $ga->createSecret(); session('secret', $secret); } $qrCodeUrl = $ga->getQRCodeGoogleUrl(rawurlencode($user['username']." - ".date('Y-m-d h:i:s')), $secret,'BJS'); $this->assign('qrCodeUrl', $qrCodeUrl); $this->assign('Asecret', $secret); } if($user['moble']){ $this->assign('moble',$user['moble']); } if($user['email']){ $this->assign('email',$user['email']); } $this->display(); } /** * 绑定谷歌认证器 */ public function bind_google($google_code = null ,$moble_code=null ,$email_code=null){ if (!userid()) { redirect('/Login'); } $user = M('User')->where(array('id' => userid()))->find(); if($user['ga']){ $this->error('验证器已绑定!'); } if($google_code){ if($user['moble']){ if($moble_code != session('google_code_moble_verify')){ $this->error('手机验证码错误'); } } if($user['email']){ if($email_code != session('google_code_email_verify')){ $this->error('邮箱验证码错误'); } } $secret = session('secret'); if (!$secret) { $this->error('验证码已经失效,请刷新网页!'); } $ga = new \Common\Ext\GoogleAuthenticator(); if($ga->verifyCode($secret, $google_code, 1)){ M('User')->where(array('id' => userid()))->save(['ga'=>$secret,'ga_open'=>1]); session('secret', null); session('google_code_moble_verify',null); session('google_code_email_verify',null); $this->success('认证成功!'); }else{ $this->error('验证码不正确!'); } }else{ $this->error('验证码不能为空!'); } } public function send_msg($type=null){ if (!userid()) { redirect('/Login'); } $user = M('User')->where(array('id' => userid()))->find(); $code = rand(111111, 999999); switch ($type){ case 'message': if($user['moble']){ if(SendText($user['moble'], $code, "cur")){ session('google_code_moble_verify', $code); if (MOBILE_CODE == 0) { $this->success('目前是演示模式,短信验证码请输入' . $code); } else { $this->success('验证码已发送'); } } }else{ $this->error('手机号未绑定!'); } break; case 'email': if($user['email']){ $content = 'CC认证器绑定,your code:' . $code; SendEmail(array('to'=>$user['email'], 'subject'=>'CC认证器绑定', 'content'=>$content));//发送邮件 session('google_code_email_verify', $code); if (MOBILE_CODE == 0) { $this->success('目前是演示模式,邮箱验证码请输入' . $code); } else { $this->success('邮件已发送'); } }else{ $this->error('邮箱地址未绑定!'); } break; default: $this->error('参数错误!'); } } /** * 开启/关闭谷歌验证 */ public function open_google($google_code = null ,$moble_code=null ,$email_code=null ,$type = null){ if (!userid()) { redirect('/Login'); } $user = M('User')->where(array('id' => userid()))->find(); if(empty($user)){ $this->error('参数错误'); } if(!$user['ga']){ $this->error('请先绑定谷歌认证器,后再操作'); } if(!in_array($type,[1,0])){ $this->error('参数错误'); } if($user['ga_open'] == $type){ $this->success('操作成功'); } if($google_code){ if($user['moble']){ if(!$moble_code){ $this->error('请输入手机验证码'); } if($moble_code != session('google_code_moble_verify')){ $this->error('手机验证码错误'); } } if($user['email']){ if(!$email_code){ $this->error('请输入邮箱验证码'); } if($email_code != session('google_code_email_verify')){ $this->error('邮箱验证码错误'); } } $ga = new \Common\Ext\GoogleAuthenticator(); if($ga->verifyCode($user['ga'], $google_code, 1)){ M('User')->where(array('id' => userid()))->save(['ga_open'=>$type]); session('google_code_moble_verify',null); session('google_code_email_verify',null); session('google',null); $this->success('操作成功!'); }else{ $this->error('验证码不正确!'); } }else{ $this->error('验证码不能为空!'); } } } ?> <file_sep><?php namespace Home\Controller; class FinanceController extends HomeController { /** *手机端个人中心 */ public function index() { if (!userid()) { redirect('/login'); } $CoinList = M('Coin')->where(array('status' => 1))->select(); $UserCoin = M('UserCoin')->where(array('userid' => userid()))->find(); $Market = M('Market')->where(array('status' => 1))->select(); foreach ($Market as $k => $v) { $Market[$v['name']] = $v; } $cny['zj'] = 0; foreach ($CoinList as $k => $v) { if ($v['name'] == 'cny') { $cny['ky'] = round($UserCoin[$v['name']], 2) * 1; $cny['dj'] = round($UserCoin[$v['name'] . 'd'], 2) * 1; $cny['zj'] = $cny['zj'] + $cny['ky'] + $cny['dj']; } else { /* if ($Market[$v['name'] . '_cny']['new_price']) { $jia = $Market[$v['name'] . '_cny']['new_price']; } */ if ($Market[C('market_type')[$v['name']]]['new_price']) { $jia = $Market[C('market_type')[$v['name']]]['new_price']; } else { $jia = 1; } if(in_array($v['name'],C('coin_on'))){ $coinList[$v['name']] = array('name' => $v['name'], 'img' => $v['img'], 'title' => $v['title'] . '(' . strtoupper($v['name']) . ')', 'xnb' => round($UserCoin[$v['name']], 6) * 1, 'xnbd' => round($UserCoin[$v['name'] . 'd'], 6) * 1, 'xnbz' => round($UserCoin[$v['name']] + $UserCoin[$v['name'] . 'd'], 6), 'jia' => $jia * 1, 'zhehe' => round(($UserCoin[$v['name']] + $UserCoin[$v['name'] . 'd']) * $jia, 2)); } $cny['zj'] = round($cny['zj'] + (($UserCoin[$v['name']] + $UserCoin[$v['name'] . 'd']) * $jia), 2) * 1; } } $this->assign('cny', $cny); $this->assign('coinList', $coinList); $this->assign('prompt_text', D('Text')->get_content('finance_index')); $this->display(); } /** * 手机页面(我的账户) */ public function index_list(){ $this->display(); } /** * 手机(我的资产) */ public function details() { if (!userid()) { redirect('/login'); } $CoinList = M('Coin')->where(array('status' => 1))->select(); $UserCoin = M('UserCoin')->where(array('userid' => userid()))->find(); $Market = M('Market')->where(array('status' => 1))->select(); foreach ($Market as $k => $v) { $Market[$v['name']] = $v; } $cny['zj'] = 0; $cny['ky_zj'] = 0; foreach ($CoinList as $k => $v) { if ($v['name'] == 'cny') { $cny['ky'] = round($UserCoin[$v['name']], 2) * 1;//可用数量 $cny['dj'] = round($UserCoin[$v['name'] . 'd'], 2) * 1;//冻结数量 $cny['ky_zj'] = $cny['ky_zj'] + $cny['ky'];//计算预估总可用资产 $cny['zj'] = $cny['zj'] + $cny['ky'] + $cny['dj'];//计算预估总资产 } else { if($Market[C('market_type')[$v['name']]]['status'] != 1){ continue; } if ($Market[C('market_type')[$v['name']]]['new_price']) { $jia = $Market[C('market_type')[$v['name']]]['new_price']; } else { $jia = 1; } if(in_array($v['name'],C('coin_on'))){ $coinList[$v['name']] = array( 'zr_jz' => $v['zr_jz'], 'zc_jz' => $v['zc_jz'], 'name' => $v['name'], 'img' => $v['img'], 'title' => $v['title'] . '(' . strtoupper($v['name']) . ')', 'url' => $v['name'].'_cnyt', 'xnb' => round($UserCoin[$v['name']], 6) * 1,//可用数量 'xnbd' => round($UserCoin[$v['name'] . 'd'], 6) * 1,//冻结数量 'xnbz' => round($UserCoin[$v['name']] + $UserCoin[$v['name'] . 'd'], 6), 'jia' => $jia * 1, 'zhehe' => round(($UserCoin[$v['name']] + $UserCoin[$v['name'] . 'd']) * $jia, 2)); } $cny['ky_zj'] = round($cny['ky_zj'] + ($UserCoin[$v['name']] * $jia), 2) * 1;//计算预估总可用资产 $cny['zj'] = round($cny['zj'] + (($UserCoin[$v['name']] + $UserCoin[$v['name'] . 'd']) * $jia), 2) * 1;//计算预估总资产 } } $this->assign('cny', $cny); $this->assign('coinList', $coinList); $this->assign('prompt_text', D('Text')->get_content('finance_index')); $this->display(); } public function asset_detail($coin = 'btc'){ if($coin){ if (!userid()) { redirect('/Login'); } $Market = M('Market')->where(array('status' => 1,'name'=>$coin.'_cny'))->find(); $UserCoin = M('UserCoin')->where(array('userid' => userid()))->find(); $jia = $Market['new_price']; if(in_array($coin,C('coin_on'))){ $coin_info = [ 'num' => $UserCoin[$coin], 'num_d' => $UserCoin[$coin . "d"], 'zh' => round((($UserCoin[$coin] + $UserCoin[$coin . 'd']) * $jia), 2) * 1]; } $where['userid'] = userid(); $where['coinname'] = $coin; $Moble = M('Myzr'); //查询充币 $list1 = $Moble->field("*,IF(id IS NOT NULL,1,1) AS direction")->where($where)->order('id desc')->select(); $Moble = M('Myzc'); //查询提币 $list2 = $Moble->field("*,IF(id IS NOT NULL,2,2) AS direction")->where($where)->order('id desc')->select(); if($list1 && $list2) { $list = array_merge($list1, $list2); $times = array(); foreach ($list as $value) { $times[] = $value['addtime']; } array_multisort($times, SORT_DESC, $list); }else{ $list = array_merge($list1, $list2); } $this->assign('coin_info',$coin_info); $this->assign('xnb', $coin); $this->assign('list', $list); $this->display(); } } /** * 邀请反佣页面 */ public function promotion() { if (!userid()) { redirect('/Login'); } // $this->assign('prompt_text', D('Text')->get_content('finance_mytj')); // check_server(); $user = M('User')->where(array('id' => userid()))->find(); if (!$user['invit']) { for (; true;) { $tradeno = tradenoa(); if (!M('User')->where(array('invit' => $tradeno))->find()) { break; } } M('User')->where(array('id' => userid()))->save(array('invit' => $tradeno)); $user = M('User')->where(array('id' => userid()))->find(); } //获取奖励排序 $yqlist = M('FenhongMyyq')->alias('f')->field('u.username,SUM(f.num) as num') ->join("__USER__ as u on u.id = f.userid","LEFT") ->order('SUM(f.num) desc') ->group('f.userid') ->page(1,3) ->select(); foreach ($yqlist as $key=>$value){ $yqlist[$key]['num']=round($value['num'],2); } $this->assign('yqlist', $yqlist); $this->assign('user', $user); $this->display(); } public function myc2c($type = NULL, $num = NULL, $tpl = NULL) { if (!userid()) { $this->error('请先登录!'); } $userid = userid(); $time = time(); if ($tpl == 1) { if ($num < 500) $this->error('最低买入500.00 CNYT!'); if ($num % 100) $this->error('买入CNYT需为100的倍数!'); $pri = $num * 1; } elseif ($tpl == 2) { //$this->error('C2C维护中!'); $user = M('User')->where(array('id' => userid()))->find(); if (!$user['idcardauth']) { $this->error('您还没有认证,请先认证!'); } $isc = M()->query("SELECT cid FROM a_ctc where uid = '$userid' and type = '1' and stu = 2; "); $isz = M()->query("SELECT id FROM qq3479015851_myzr where userid = '$userid' ; "); if (!$isc && !$isz) $this->error('未查询到您的充值记录,卖出失败!'); //检验是否绑定了银行卡 if ($num >= 10000) { $iscard = M()->query("SELECT id, bankcard, bank FROM qq3479015851_user_bank where status = 1 and bank like '%银行%' and bankcard is not null limit 1"); if (!$iscard) $this->error('卖出超过10000.00 CNYT必须绑定银行卡!'); } if ($num < 500) $this->error('最低卖出500.00 CNYT!'); if ($num % 100) $this->error('卖出CNYT需为100的倍数!'); $pri = $num * 0.995; $user_coin = M('UserCoin')->where(array('userid' => $userid))->find(); if ($user_coin['cny'] < $num) $this->error('可卖出余额不足!'); } else { $this->error('参数错误!'); } $mycz = M()->query("SELECT cid FROM a_ctc where uid = '$userid' and type = '$tpl' and stu = 1; "); if ($mycz) { $this->error('您有未完成的订单!' . $userid); } if (!check($num, 'cny')) { $this->error('交易金额格式错误!'); } if (100000 < $num) { $this->error('交易金额不能大于100000元!'); } if ($type == "alipay") { $type1 = M()->query("SELECT * FROM qq3479015851_user_bank where bank = '支付宝' and userid='" . userid() . "' "); if (!$type1) $this->error('您还没有绑定支付宝!'); $myczType = M('MyczType')->where(array('title' => '支付宝', 'status' => 1))->select(); } elseif ($type == "bank") { $type1 = M()->query("SELECT * FROM qq3479015851_user_bank where bank like '%银行%' and userid='" . userid() . "' "); if (!$type1) $this->error('您还没有绑定银行卡!'); $myczType = M('MyczType')->where(array('title' => '银行卡', 'status' => 1))->select(); } elseif ($type == "weixin") { $this->error('交易方式错误!'); if ($tpl == 2) $this->error('交易方式错误!'); $type1 = M()->query("SELECT * FROM qq3479015851_user_bank where bank like '%微信%' and userid='" . userid() . "' "); if (!$type1) $this->error('您还没有绑定微信!'); $myczType = M('MyczType')->where(array('title' => '微信', 'status' => 1))->select(); } else { $this->error('交易方式不存在1!'); } if (!$myczType) { $this->error('交易方式不存在2!'); } $sjs = rand(0, count($myczType) - 1); $tid = $myczType[$sjs]['id']; if (!$tid) { $this->error('交易方式不存在3!'); } if ($tpl == 2) { M()->execute("UPDATE `qq3479015851_user_coin` SET `cny` = cny-$num,`cnyd` = cnyd+$num WHERE `userid` ='$userid';"); M()->execute("INSERT INTO `a_ctc` (`cid`, `uid`, `pri`, `num`, `tid`, `type`, `typec`, `typer`, `uptime`) VALUES (NULL, '$userid', '$pri', '$num', '$tid','2', '1', '1', '$time');"); } else { M()->execute("INSERT INTO `a_ctc` (`cid`, `uid`, `pri`, `num`, `tid`, `type`, `typec`, `typer`, `uptime`) VALUES (NULL, '$userid', '$pri', '$num', '$tid','1', '1', '1', '$time');"); } $this->success('交易订单创建成功!'); if ($mycz) { $this->success('交易订单创建成功!'); } else { $this->error('提现订单创建失败!'); } } public function mycz($status = NULL) { if (!userid()) { redirect('/Login'); } // $otime = time() - 48 * 60 * 60; $userid = userid(); $user_coin = M('UserCoin')->where(array('userid' => userid()))->find(); $user_coin['cny'] = round($user_coin['cny'], 2); $user_coin['cnyd'] = round($user_coin['cnyd'], 2); $this->assign('user_coin', $user_coin); $list = M()->query("SELECT * FROM a_ctc a,qq3479015851_mycz_type b where a.tid = b.id and a.uid = '$userid' order by a.cid desc limit 0,10; ");//大于时间范围 and a.uptime > $otime foreach ($list as $k => $v) { if ($v['type'] == 1) { $list[$k]['tpl'] = '买入'; $list[$k]['status'] = $v['typer']; } else { $list[$k]['tpl'] = '卖出'; $list[$k]['status'] = $v['typec']; } if ($v['typer'] == 1 && $v['typec'] == 1) $list[$k]['pp'] = 1; if ($v['stu'] == 2) $list[$k]['status'] = 99; if ($v['stu'] == 0) $list[$k]['status'] = 0; } $this->assign('list', $list); $this->display(); } public function mycz_list(){ if (!userid()) { redirect('/Login'); } // $otime = time() - 48 * 60 * 60; $userid = userid(); $count = M()->query("SELECT count(*) as count FROM a_ctc a,qq3479015851_mycz_type b where a.tid = b.id and a.uid = '$userid' order by a.cid desc; ")[0]['count']; $Page = new \Think\Page($count, 15); $show = $Page->show(); $list = M()->query("SELECT * FROM a_ctc a,qq3479015851_mycz_type b where a.tid = b.id and a.uid = ".$userid." order by a.cid desc limit ".$Page->firstRow .",".$Page->listRows.";");//大于时间范围 and a.uptime > $otime foreach ($list as $k => $v) { if ($v['type'] == 1) { $list[$k]['tpl'] = '买入'; $list[$k]['status'] = $v['typer']; } else { $list[$k]['tpl'] = '卖出'; $list[$k]['status'] = $v['typec']; } if ($v['typer'] == 1 && $v['typec'] == 1) $list[$k]['pp'] = 1; if ($v['stu'] == 2) $list[$k]['status'] = 99; if ($v['stu'] == 0) $list[$k]['status'] = 0; } $this->assign('page', $show); $this->assign('list', $list); $this->display(); } public function mycz_del($id = 0) { if (!userid()) { redirect('/Login'); } $userid = userid(); if ($id > 0) { $mycz = M()->query("SELECT * FROM a_ctc where uid = '$userid' and cid = '$id' and stu = 1; "); if ($mycz) { if ($mycz[0]['type'] == 1) { M()->execute("UPDATE `a_ctc` SET `typer` = 0,stu = 0 WHERE `cid` ='$id';"); } else { $this->error('卖单不可撤销!'); // M()->execute("UPDATE `a_ctc` SET `typec` = 0,stu = 0 WHERE `cid` ='$id';"); // $num = $mycz[0]['num']; // M()->execute("UPDATE `qq3479015851_user_coin` SET `cny` = cny+$num,`cnyd` = cnyd-$num WHERE `userid` ='$userid';"); } $this->success('操作成功!'); } else { $this->error('操作失败!'); } } } public function mycz_q($id) { if (!userid()) { redirect('/Login'); } $userid = userid(); $mycz = M()->query("SELECT * FROM a_ctc where uid = '$userid' and cid = '$id' and stu = 1; "); if ($mycz) { if ($mycz[0]['type'] == 1) { M()->execute("UPDATE `a_ctc` SET `typer` = 2 WHERE `cid` ='$id';"); } else { $this->error('操作失败!'); // M()->execute("UPDATE `a_ctc` SET `typec` = 2,stu=2 WHERE `cid` ='$id';"); // $num = $mycz[0]['num']; // M()->execute("UPDATE `qq3479015851_user_coin` SET `cnyd` = cnyd-$num WHERE `userid` ='$userid';"); } $this->success('操作成功!'); } else { $this->error('操作失败!'); } } public function bank() { if (!userid()) { redirect('/Login'); } $UserBankType = M('UserBankType')->where(array('status' => 1))->order('id desc')->select(); $this->assign('UserBankType', $UserBankType); $truename = M('User')->where(array('id' => userid()))->getField('truename'); $this->assign('truename', $truename); $userbank = M()->query("SELECT * FROM qq3479015851_user_bank where bank like '%银行%' and userid='" . userid() . "' order by id desc LIMIT 1"); $useralipay = M()->query("SELECT * FROM qq3479015851_user_bank where bank like '%支付宝%' and userid='" . userid() . "' order by id desc LIMIT 1"); $userweixin = M()->query("SELECT * FROM qq3479015851_user_bank where bank like '%微信%' and userid='" . userid() . "' order by id desc LIMIT 1"); $useralipay[0]['backimg'] = $useralipay[0]['backimg'] ? "Upload/pay/" . $useralipay[0]['backimg'] : "Upload/pay/alipay.jpg"; $userweixin[0]['backimg'] = $userweixin[0]['backimg'] ? "Upload/pay/" . $userweixin[0]['backimg'] : "Upload/pay/weixin.jpg"; if ($useralipay[0]['imgm']) { $useralipay[0]['backimg'] = WAP_URL . $useralipay[0]['backimg']; } else { $useralipay[0]['backimg'] = PC_URL . $useralipay[0]['backimg']; } if ($userweixin[0]['imgm']) { $userweixin[0]['backimg'] = WAP_URL . $userweixin[0]['backimg']; } else { $userweixin[0]['backimg'] = PC_URL . $userweixin[0]['backimg']; } // print_r($userbank[0]); // print_r($useralipay[0]); // print_r($userweixin[0]); // exit(); $this->assign('userbank', $userbank[0]); $this->assign('useralipay', $useralipay[0]); $this->assign('userweixin', $userweixin[0]); $this->assign('prompt_text', D('Text')->get_content('user_bank')); $this->display(); } public function address(){ if (!userid()) { redirect('/Login'); } $this->display(); } public function bankup($bank = '', $bankaddr = '', $bankcard = '', $bankpwd = '', $type = '', $bankimg = '') { if (!userid()) { redirect('/Login'); } if (!$bankpwd) { $this->error('支付密码格式错误!'); } if ($type == 1) { $if_userbank1 = M()->query("SELECT id FROM qq3479015851_user_bank where bank like '%银行%' and userid='" . userid() . "' order by id desc LIMIT 1"); if ($if_userbank1) $this->error('上传过的银行卡不可修改'); if (strlen($bankcard) < 16 || strlen($bankcard) > 19) { $this->error('银行卡号格式错误!'); } if (!$bankaddr) { $this->error('开户支行格式错误!'); } $userbank = M()->query("SELECT id FROM qq3479015851_user_bank where bank like '%银行%' and userid='" . userid() . "' order by id desc LIMIT 1"); } elseif ($type == 2) { $if_userbank2 = M()->query("SELECT id FROM qq3479015851_user_bank where bank like '%支付宝%' and userid='" . userid() . "' order by id desc LIMIT 1"); if ($if_userbank2) $this->error('上传过的支付宝不可修改'); if (strlen($bankcard) < 5) { $this->error('支付宝格式错误!'); } if (!$bankimg) { $this->error('请上传支付宝收款码!'); } $bank = "支付宝"; $userbank = M()->query("SELECT id FROM qq3479015851_user_bank where bank like '%支付宝%' and userid='" . userid() . "' order by id desc LIMIT 1"); } elseif ($type == 3) { $if_userbank3 = M()->query("SELECT id FROM qq3479015851_user_bank where bank like '%微信%' and userid='" . userid() . "' order by id desc LIMIT 1"); if ($if_userbank3) $this->error('上传过的微信不可修改'); if (strlen($bankcard) < 2) { $this->error('微信格式错误!'); } if (!$bankimg) { $this->error('请上传微信收款码!'); } $bank = "微信"; $userbank = M()->query("SELECT id FROM qq3479015851_user_bank where bank like '%微信%' and userid='" . userid() . "' order by id desc LIMIT 1"); } $user_paypassword = M('User')->where(array('id' => userid()))->getField('paypassword'); if ($bankpwd != $user_paypassword) { $this->error('交易密码错误!'); } if ($userbank) { $bankid = $userbank[0]['id']; M()->execute("UPDATE `qq3479015851_user_bank` SET `bank` = '$bank',`bankaddr` = '$bankaddr',`bankcard` = '$bankcard',`backimg` = '$bankimg',`imgm` = '0' WHERE `id` ='$bankid';"); $this->success('更新成功!'); } else { if (M('UserBank')->add(array('userid' => userid(), 'name' => $bank, 'bank' => $bank, 'bankprov' => 0, 'bankcity' => 0, 'bankaddr' => $bankaddr, 'backimg' => $bankimg, 'bankcard' => $bankcard, 'addtime' => time(), 'status' => 1))) { $this->success('添加成功!'); } else { $this->error('添加失败!'); } } } public function upbank($name = NULL, $bank = NULL, $bankprov = NULL, $bankcity = NULL, $bankaddr = NULL, $bankcard = NULL, $paypassword = NULL) { if (!userid()) { redirect('/Login'); } if (!check($name, 'a')) { $this->error('备注名称格式错误!'); } if (!check($bank, 'a')) { $this->error('开户银行格式错误!'); } // if (!check($bankprov, 'c')) { // $this->error('开户省市格式错误!'); // } // // if (!check($bankcity, 'c')) { // $this->error('开户省市格式错误2!'); // } if (!check($bankaddr, 'a')) { if ($bank != '支付宝') $this->error('开户行地址格式错误!'); } if (!check($bankcard, 'd')) { if ($bank != '支付宝') $this->error('银行账号格式错误!'); } if (strlen($bankcard) < 16 || strlen($bankcard) > 19) { if ($bank != '支付宝') $this->error('银行账号格式错误!'); } if ($bank == "支付宝" && strlen($bankcard) < 5) { $this->error('支付宝账号格式错误!'); } if (!check($paypassword, 'password')) { $this->error('交易密码格式错误!'); } $user_paypassword = M('User')->where(array('id' => userid()))->getField('paypassword'); if ($paypassword != $user_paypassword) { $this->error('交易密码错误!'); } if (!M('UserBankType')->where(array('title' => $bank))->find()) { $this->error('开户银行错误!'); } if ($bank == "支付宝") { $type1 = M()->query("SELECT * FROM qq3479015851_user_bank where bank = '支付宝' and userid='" . userid() . "' "); if ($type1) $this->error('支付宝已添加!'); } else { $type1 = M()->query("SELECT * FROM qq3479015851_user_bank where bank like '%银行%' and userid='" . userid() . "' "); if ($type1) $this->error('银行卡已添加!'); } $userBank = M('UserBank')->where(array('userid' => userid()))->select(); foreach ($userBank as $k => $v) { if ($v['name'] == $name) { $this->error('请不要使用相同的备注名称!'); } if ($v['bankcard'] == $bankcard) { $this->error('银行卡号已存在!'); } if ($v['bank'] == $bank) { $this->error($bank . '卡已存在!'); } } if (2 <= count($userBank)) { $this->error('每个用户最多只能添加2个账户!'); } if (M('UserBank')->add(array('userid' => userid(), 'name' => $name, 'bank' => $bank, 'bankprov' => $bankprov, 'bankcity' => $bankcity, 'bankaddr' => $bankaddr, 'bankcard' => $bankcard, 'addtime' => time(), 'status' => 1))) { $this->success('银行添加成功!'); } else { $this->error('银行添加失败!'); } } public function delbank($id, $paypassword) { if (!userid()) { redirect('/Login'); } if (!check($paypassword, 'password')) { $this->error('交易密码格式错误!'); } if (!check($id, 'd')) { $this->error('参数错误!'); } $user_paypassword = M('User')->where(array('id' => userid()))->getField('paypassword'); if ($paypassword != $user_paypassword) { $this->error('交易密码错误!'); } if (!M('UserBank')->where(array('userid' => userid(), 'id' => $id))->find()) { $this->error('非法访问!'); } else if (M('UserBank')->where(array('userid' => userid(), 'id' => $id))->delete()) { $this->success('删除成功!'); } else { $this->error('删除失败!'); } } public function myczChakan($id = NULL) { if (!userid()) { $this->error('请先登录!'); } if (!check($id, 'd')) { $this->error('参数错误!'); } $mycz = M('Mycz')->where(array('id' => $id))->find(); if (!$mycz) { $this->error('充值订单不存在!'); } if ($mycz['userid'] != userid()) { $this->error('非法操作!'); } if ($mycz['status'] != 0) { $this->error('订单已经处理过!'); } $rs = M('Mycz')->where(array('id' => $id))->save(array('status' => 3)); if ($rs) { $this->success('', array('id' => $id)); } else { $this->error('操作失败!'); } } public function myczUp($type, $num, $tpl = NULL) { if (!userid()) { $this->error('请先登录!'); } $mycz = M('Mycz')->where(array('userid' => userid(), 'status' => 0))->find(); if ($mycz) { $this->error('您有未完成的订单!'); } $tpl = $tpl ? 2 : 1; if (!check($type, 'n')) { $this->error('交易方式格式错误!'); } if (!check($num, 'cny')) { $this->error('充值金额格式错误!'); } if ($num < 100) { $this->error('充值金额不能小于100元!'); } if (100000 < $num) { $this->error('充值金额不能大于100000元!'); } if ($type == "alipay") { $myczType = M('MyczType')->where(array('title' => '支付宝', 'status' => 1))->select(); } elseif ($type == "bank") { $myczType = M('MyczType')->where(array('title' => '银行卡', 'status' => 1))->select(); } else { $this->error('交易方式不存在1!'); } if (!$myczType) { $this->error('交易方式不存在2!'); } $sjs = rand(0, count($myczType) - 1); $tid = $myczType[$sjs]['id']; if (!$tid) { $this->error('交易方式不存在3!'); } for (; true;) { $tradeno = tradeno(); if (!M('Mycz')->where(array('tradeno' => $tradeno))->find()) { break; } } $mycz = M('Mycz')->add(array('userid' => userid(), 'num' => $num, 'type' => $type, 'tid' => $tid, 'tpl' => $tpl, 'tradeno' => $tradeno, 'addtime' => time(), 'status' => 0)); if ($mycz) { $this->success('交易订单创建成功!', array('id' => $mycz)); } else { $this->error('提现订单创建失败!'); } } public function mytxUp($moble_verify, $num, $paypassword, $type) { if (!userid()) { $this->error('请先登录!'); } if (!check($moble_verify, 'd')) { $this->error('短信验证码格式错误!'); } if (!check($num, 'd')) { $this->error('提现金额格式错误!'); } if (!check($paypassword, 'password')) { $this->error('交易密码格式错误!'); } if (!check($type, 'd')) { $this->error('提现方式格式错误!'); } $this->_verify_count_check($moble_verify,session('mytx_verify')); $userCoin = M('UserCoin')->where(array('userid' => userid()))->find(); if ($userCoin['cny'] < $num) { $this->error('可用人民币余额不足!'); } $user = M('User')->where(array('id' => userid()))->find(); if ($paypassword != $user['paypassword']) { $this->error('交易密码错误!'); } $userBank = M('UserBank')->where(array('id' => $type))->find(); if (!$userBank) { $this->error('提现地址错误!'); } $mytx_min = (C('mytx_min') ? C('mytx_min') : 1); $mytx_max = (C('mytx_max') ? C('mytx_max') : 1000000); $mytx_bei = C('mytx_bei'); $mytx_fee = C('mytx_fee'); if ($num < $mytx_min) { $this->error('每次提现金额不能小于' . $mytx_min . '元!'); } if ($mytx_max < $num) { $this->error('每次提现金额不能大于' . $mytx_max . '元!'); } if ($mytx_bei) { if ($num % $mytx_bei != 0) { $this->error('每次提现金额必须是' . $mytx_bei . '的整倍数!'); } } $fee = round(($num / 100) * $mytx_fee, 2); $mum = round(($num / 100) * (100 - $mytx_fee), 2); $mo = M(); $mo->execute('set autocommit=0'); //$mo->execute('lock tables qq3479015851_mytx write , qq3479015851_user_coin write ,qq3479015851_finance write'); $rs = array(); $finance = $mo->table('qq3479015851_finance')->where(array('userid' => userid()))->order('id desc')->find(); $finance_num_user_coin = $mo->table('qq3479015851_user_coin')->where(array('userid' => userid()))->find(); $rs[] = $mo->table('qq3479015851_user_coin')->where(array('userid' => userid()))->setDec('cny', $num); $rs[] = $finance_nameid = $mo->table('qq3479015851_mytx')->add(array('userid' => userid(), 'num' => $num, 'fee' => $fee, 'mum' => $mum, 'name' => $userBank['name'], 'truename' => $user['truename'], 'bank' => $userBank['bank'], 'bankprov' => $userBank['bankprov'], 'bankcity' => $userBank['bankcity'], 'bankaddr' => $userBank['bankaddr'], 'bankcard' => $userBank['bankcard'], 'addtime' => time(), 'status' => 0)); $finance_mum_user_coin = $mo->table('qq3479015851_user_coin')->where(array('userid' => userid()))->find(); $finance_hash = md5(userid() . $finance_num_user_coin['cny'] . $finance_num_user_coin['cnyd'] . $mum . $finance_mum_user_coin['cny'] . $finance_mum_user_coin['cnyd'] . MSCODE . 'auth.qq3479015851.com'); $finance_num = $finance_num_user_coin['cny'] + $finance_num_user_coin['cnyd']; if ($finance['mum'] < $finance_num) { $finance_status = (1 < ($finance_num - $finance['mum']) ? 0 : 1); } else { $finance_status = (1 < ($finance['mum'] - $finance_num) ? 0 : 1); } $rs[] = $mo->table('qq3479015851_finance')->add(array('userid' => userid(), 'coinname' => 'cny', 'num_a' => $finance_num_user_coin['cny'], 'num_b' => $finance_num_user_coin['cnyd'], 'num' => $finance_num_user_coin['cny'] + $finance_num_user_coin['cnyd'], 'fee' => $num, 'type' => 2, 'name' => 'mytx', 'nameid' => $finance_nameid, 'remark' => '人民币提现-申请提现', 'mum_a' => $finance_mum_user_coin['cny'], 'mum_b' => $finance_mum_user_coin['cnyd'], 'mum' => $finance_mum_user_coin['cny'] + $finance_mum_user_coin['cnyd'], 'move' => $finance_hash, 'addtime' => time(), 'status' => $finance_status)); if (check_arr($rs)) { session('mytx_verify', null); $mo->execute('commit'); //$mo->execute('unlock tables'); session('mytx_verify',null); $this->success('提现订单创建成功!'); } else { $mo->execute('rollback'); $this->error('提现订单创建失败!'); } } public function mytxChexiao($id) { if (!userid()) { $this->error('请先登录!'); } if (!check($id, 'd')) { $this->error('参数错误!'); } $mytx = M('Mytx')->where(array('id' => $id))->find(); if (!$mytx) { $this->error('提现订单不存在!'); } if ($mytx['userid'] != userid()) { $this->error('非法操作!'); } if ($mytx['status'] != 0) { $this->error('订单不能撤销!'); } $mo = M(); $mo->execute('set autocommit=0'); //$mo->execute('lock tables qq3479015851_user_coin write,qq3479015851_mytx write,qq3479015851_finance write'); $rs = array(); $finance = $mo->table('qq3479015851_finance')->where(array('userid' => $mytx['userid']))->order('id desc')->find(); $finance_num_user_coin = $mo->table('qq3479015851_user_coin')->where(array('userid' => $mytx['userid']))->find(); $rs[] = $mo->table('qq3479015851_user_coin')->where(array('userid' => $mytx['userid']))->setInc('cny', $mytx['num']); $rs[] = $mo->table('qq3479015851_mytx')->where(array('id' => $mytx['id']))->setField('status', 2); $finance_mum_user_coin = $mo->table('qq3479015851_user_coin')->where(array('userid' => $mytx['userid']))->find(); $finance_hash = md5($mytx['userid'] . $finance_num_user_coin['cny'] . $finance_num_user_coin['cnyd'] . $mytx['num'] . $finance_mum_user_coin['cny'] . $finance_mum_user_coin['cnyd'] . MSCODE . 'auth.qq3479015851.com'); $finance_num = $finance_num_user_coin['cny'] + $finance_num_user_coin['cnyd']; if ($finance['mum'] < $finance_num) { $finance_status = (1 < ($finance_num - $finance['mum']) ? 0 : 1); } else { $finance_status = (1 < ($finance['mum'] - $finance_num) ? 0 : 1); } $rs[] = $mo->table('qq3479015851_finance')->add(array('userid' => $mytx['userid'], 'coinname' => 'cny', 'num_a' => $finance_num_user_coin['cny'], 'num_b' => $finance_num_user_coin['cnyd'], 'num' => $finance_num_user_coin['cny'] + $finance_num_user_coin['cnyd'], 'fee' => $mytx['num'], 'type' => 1, 'name' => 'mytx', 'nameid' => $mytx['id'], 'remark' => '人民币提现-撤销提现', 'mum_a' => $finance_mum_user_coin['cny'], 'mum_b' => $finance_mum_user_coin['cnyd'], 'mum' => $finance_mum_user_coin['cny'] + $finance_mum_user_coin['cnyd'], 'move' => $finance_hash, 'addtime' => time(), 'status' => $finance_status)); if (check_arr($rs)) { $mo->execute('commit'); //$mo->execute('unlock tables'); $this->success('操作成功!'); } else { $mo->execute('rollback'); $this->error('操作失败!'); } } public function myzr($coin = NULL) { if (!userid()) { redirect('/Login'); } $this->assign('prompt_text', D('Text')->get_content('finance_myzr')); if (C('coin')[$coin]) { $coin = trim($coin); } else { $coin = C('xnb_mr'); } $this->assign('xnb', $coin); $Coin = M('Coin')->where(array( 'status' => 1, 'name' => array('neq', 'cny') ))->select(); foreach ($Coin as $k => $v) { $coin_list[$v['name']] = $v; } $this->assign('coin_list', $coin_list); $user_coin = M('UserCoin')->where(array('userid' => userid()))->find(); $user_coin[$coin] = round($user_coin[$coin], 6); $this->assign('user_coin', $user_coin); $Coin = M('Coin')->where(array('name' => $coin))->find(); $this->assign('zr_jz', $Coin['zr_jz']); $qq3479015851_getCoreConfig = qq3479015851_getCoreConfig(); if (!$qq3479015851_getCoreConfig) { $this->error('核心配置有误'); } $this->assign("qq3479015851_opencoin", $qq3479015851_getCoreConfig['qq3479015851_opencoin']); if ($qq3479015851_getCoreConfig['qq3479015851_opencoin'] == 1) { if (!$Coin['zr_jz']) { $qianbao = '当前币种禁止转入!'; } else { $qbdz = $coin . 'b'; if (!$user_coin[$qbdz]) { if ($Coin['type'] == 'rgb') { $qianbao = md5(username() . $coin); $rs = M('UserCoin')->where(array('userid' => userid()))->save(array($qbdz => $qianbao)); if (!$rs) { $this->error('生成钱包地址出错!'); } } //eth QQ357898628 if ($Coin['type'] == 'eth') { $heyue = $Coin['dj_yh'];//合约地址 $EthCommon = new \Org\Util\EthCommon(COIN_ADDR, COIN_PORT, "2.0"); $EthPayLocal = new \Org\Util\EthPayLocal(COIN_ADDR, COIN_PORT, "2.0", COIN_CAIWU); if (!$heyue) { //eth //调用接口生成新钱包地址 $qianbao = $EthPayLocal->personal_newAccount(COIN_KEY); if ($qianbao) { $rs = M('UserCoin')->where(array('userid' => userid()))->save(array($qbdz => $qianbao)); } else { $this->error('生成钱包地址出错2!'); } } else { //eth合约 $rs1 = M('UserCoin')->where(array('userid' => userid()))->find(); if ($rs1['ethb']) { $qianbao = $rs1['ethb']; $rs = M('UserCoin')->where(array('userid' => userid()))->save(array($qbdz => $qianbao)); } else { //调用接口生成新钱包地址 $qianbao = $EthPayLocal->personal_newAccount(COIN_KEY); if ($qianbao) { $rs = M('UserCoin')->where(array('userid' => userid()))->save(array($qbdz => $qianbao, "ethb" => $qianbao)); } else { $this->error('生成钱包地址出错2!'); } } } } //eth QQ357898628 if ($Coin['type'] == 'qbb') { $dj_username = $Coin['dj_yh']; $dj_password = $<PASSWORD>['<PASSWORD>']; $dj_address = $Coin['dj_zj']; $dj_port = $Coin['dj_dk']; $CoinClient = CoinClient($dj_username, $dj_password, $dj_address, $dj_port, 5, array(), 1); $json = $CoinClient->getinfo(); if (!isset($json['version']) || !$json['version']) { $this->error('钱包链接失败!'); } $qianbao_addr = $CoinClient->getaddressesbyaccount(username()); if (!is_array($qianbao_addr)) { $qianbao_ad = $CoinClient->getnewaddress(username()); if (!$qianbao_ad) { $this->error('生成钱包地址出错1!'); } else { $qianbao = $qianbao_ad; } } else { $qianbao = $qianbao_addr[0]; } if (!$qianbao) { $this->error('生成钱包地址出错2!'); } $rs = M('UserCoin')->where(array('userid' => userid()))->save(array($qbdz => $qianbao)); if (!$rs) { $this->error('钱包地址添加出错3!'); } } } else { $qianbao = $user_coin[$coin . 'b']; } } } else { if (!$Coin['zr_jz']) { $qianbao = '当前币种禁止转入!'; } else { $qianbao = $Coin['qq3479015851_coinaddress']; $moble = M('User')->where(array('id' => userid()))->getField('moble'); if ($moble) { $moble = substr_replace($moble, '****', 3, 4); } else { redirect(U('Home/User/moble')); exit(); } $this->assign('moble', $moble); } } $this->assign('qianbao', $qianbao); $where['userid'] = userid(); $where['coinname'] = $coin; $Moble = M('Myzr'); $count = $Moble->where($where)->count(); $Page = new \Think\Page($count, 10); $show = $Page->show(); $list = $Moble->where($where)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select(); $this->assign('list', $list); $this->assign('page', $show); $this->display(); } /** * 我的推荐 */ public function mywd() { if (!userid()) { redirect('/#login'); } $this->assign('prompt_text', D('Text')->get_content('finance_mywd')); check_server(); $where['invit_1'] = userid(); $Model = M('User'); $count = $Model->where($where)->count(); $Page = new \Think\Page($count, 10); if ($_GET['p'] == '') { $_GET['p'] = 1; } $uppage=$_GET['p']-1; $dopage=$_GET['p']+1; if ($count <= 10) { $Page->setConfig('theme', ''); } else if ($_GET['p'] == 1) { $Page->setConfig('theme', '<a href="/Finance/mywd/p/'.$dopage.'">»</a>'); } else if ($_GET['p'] == ceil($count / 10)) { $Page->setConfig('theme', '<a href="/Finance/mywd/p/'.$uppage.'">«</a>'); } else if ($_GET['p'] > 1) { $Page->setConfig('theme', '<a href="/Finance/mywd/p/'.$uppage.'">«</a><a href="/Finance/mywd/p/'.$dopage.'">»</a>'); } $Page->setConfig('prev', '上一页'); $Page->setConfig('next', '下一页'); $show = $Page->show(); if(C('DEFAULT_V_LAYER') == 'Mview'){ $list = $Model->where($where)->order('id asc')->field('id,username,moble,addtime,invit_1,idcardauth')->select(); }else { $list = $Model->where($where)->order('id asc')->field('id,username,moble,addtime,invit_1,idcardauth')->limit($Page->firstRow . ',' . $Page->listRows)->select(); } foreach ($list as $k => $v) { $list[$k]['invits'] = M('User')->where(array('invit_1' => $v['id']))->order('id asc')->field('id,username,moble,addtime,invit_1,idcardauth')->select(); $list[$k]['invitss'] = count($list[$k]['invits']); foreach ($list[$k]['invits'] as $kk => $vv) { $list[$k]['invits'][$kk]['invits'] = M('User')->where(array('invit_1' => $vv['id']))->order('id asc')->field('id,username,moble,addtime,invit_1,idcardauth')->select(); $list[$k]['invits'][$kk]['invitss'] = count($list[$k]['invits'][$kk]['invits']); } } $s_count = 0; if(is_array($list)){ foreach($list as $k => $v){ $s_count++; foreach($v['invits'] as $kk => $vv){ $s_count++; foreach($vv['invits'] as $kkk=>$vvv){ $s_count++; } } } } //echo $s_count; //die; //print_r($list[0]['invits']); //die; //$this->assign('s_count_1', $s_count_1); //$this->assign('s_count_2', $s_count_2); //$this->assign('s_count_3', $s_count_3); $this->assign('s_count', $s_count); $this->assign('list', $list); $this->assign('page', $show); $this->display(); } /** * 我的奖品 */ public function myjp() { if (!userid()) { redirect('/#login'); } $this->assign('prompt_text', D('Text')->get_content('finance_myjp')); check_server(); $where['userid'] = userid(); $Model = M('Invit'); $count = $Model->where($where)->count(); $Page = new \Think\Page($count, 10); $show = $Page->show(); $list = $Model->where($where)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select(); foreach ($list as $k => $v) { $list[$k]['invit'] = M('User')->where(array('id' => $v['invit']))->getField('id'); } $s_count = 0; $s_count = $Model->where($where)->sum('fee'); //$s_count = round($s_count,2); $this->assign('s_count', $s_count); $this->assign('list', $list); $this->assign('page', $show); $this->display(); } /** * 最新活动 */ public function myzc($coin = NULL,$addr = NULL) { if (!userid()) { redirect('/Login'); } $user = M('User')->where(array('id' => userid()))->find(); if (!$user['idcardauth']) { $this->error('您还没有认证,请先认证!', "/user/nameauth.html"); } $this->assign('prompt_text', D('Text')->get_content('finance_myzc')); if (C('coin')[$coin]) { $coin = trim($coin); } else { $coin = C('xnb_mr'); } $this->assign('xnb', $coin); $Coin = M('Coin')->where(array( 'status' => 1, 'name' => array('neq', 'cny') ))->select(); foreach ($Coin as $k => $v) { $coin_list[$v['name']] = $v; } $this->assign('coin_list', $coin_list); $user_coin = M('UserCoin')->where(array('userid' => userid()))->find(); $user_coin[$coin] = round($user_coin[$coin], 6); $this->assign('user_coin', $user_coin); if (!$coin_list[$coin]['zc_jz']) { $this->assign('zc_jz', '当前币种禁止转出!'); } else { $userQianbaoList = M('UserQianbao')->where(array('userid' => userid(), 'status' => 1, 'coinname' => $coin))->order('id desc')->select(); $this->assign('userQianbaoList', $userQianbaoList); $moble = M('User')->where(array('id' => userid()))->getField('moble'); if ($moble) { $moble = substr_replace($moble, '****', 3, 4); } else { redirect(U('Home/User/moble')); exit(); } $this->assign('moble', $moble); } $where['userid'] = userid(); $where['coinname'] = $coin; $Moble = M('Myzc'); $count = $Moble->where($where)->count(); $Page = new \Think\Page($count, 10); $show = $Page->show(); $list = $Moble->where($where)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select(); $this->assign('list', $list); $this->assign('page', $show); $this->assign('addr', $addr); $this->display(); } public function upmyzc($coin, $num, $addr, $paypassword, $moble_verify) { if (!userid()) { $this->error('您没有登录请先登录!'); } $userid = userid(); $isc = M()->query("SELECT cid FROM a_ctc where uid = '$userid' and type = '1' and stu = 2; "); $isz = M()->query("SELECT id FROM qq3479015851_myzr where userid = '$userid' ; "); if (!$isc && !$isz) $this->error('未查询到您的充值、转入记录,转出失败!'); if (!check($moble_verify, 'd')) { $this->error('短信验证码格式错误!'); } $this->_verify_count_check($moble_verify,session('myzc_verify')); $num = abs($num); if (!check($num, 'currency')) { $this->error('数量格式错误!'); } if (!check($addr, 'dw')) { $this->error('钱包地址格式错误!'); } if (!check($paypassword, 'password')) { $this->error('交易密码格式错误!'); } if (!check($coin, 'n')) { $this->error('币种格式错误!'); } if (!C('coin')[$coin]) { $this->error('币种错误!'); } $Coin = M('Coin')->where(array('name' => $coin))->find(); if (!$Coin) { $this->error('币种错误!'); } $myzc_min = ($Coin['zc_min'] ? abs($Coin['zc_min']) : 0.0001); $myzc_max = ($Coin['zc_max'] ? abs($Coin['zc_max']) : 10000000); if ($num < $myzc_min) { $this->error('转出数量超过系统最小限制!'); } if ($myzc_max < $num) { $this->error('转出数量超过系统最大限制!'); } $user = M('User')->where(array('id' => userid()))->find(); if ($paypassword != $user['paypassword']) { $this->error('交易密码错误!'); } $user_coin = M('UserCoin')->where(array('userid' => userid()))->find(); if ($user_coin[$coin] < $num) { $this->error('可用余额不足'); } $qbdz = $coin . 'b'; $fee_user = M('UserCoin')->where(array($qbdz => $Coin['zc_user']))->find(); // if ($fee_user) { // $fee = round(($num / 100) * $Coin['zc_fee'], 8); // $mum = round($num - $fee, 8); // // if ($mum < 0) { // $this->error('转出手续费错误!'); // } // // if ($fee < 0) { // $this->error('转出手续费设置错误!'); // } // } // else { // $fee = 0; // $mum = $num; // } //eth 系列转出手续费重新计算,扣除个数 if ($fee_user) { $fee = $Coin['zc_fee']; $mum = round($num - $fee, 8); if ($mum < 0) { $this->error('转出手续费错误!'); } if ($fee < 0) { $this->error('转出手续费设置错误!'); } } else { $fee = 0; $mum = $num; } //eth 系列转出手续费重新计算,扣除个数end $mo = M(); //eth 357898628 if ($Coin['type'] == 'eth') { $heyue = $Coin['dj_yh']; // $mo = M(); // $peer = M('UserCoin')->where(array($qbdz => $addr))->find(); $peer = $mo->table('qq3479015851_user_coin')->where(array($qbdz => $addr))->find(); if ($peer) { $mo = M(); $rs = array(); $rs[] = $mo->table('qq3479015851_user_coin')->where(array('userid' => userid()))->setDec($coin, $num); $rs[] = $mo->table('qq3479015851_user_coin')->where(array('userid' => $peer['userid']))->setInc($coin, $mum); $rs[] = $mo->table('qq3479015851_myzc')->add(array('userid' => userid(), 'username' => $addr, 'coinname' => $coin, 'txid' => md5($addr . $user_coin[$coin . 'b'] . time()), 'num' => $num, 'fee' => $fee, 'mum' => $mum, 'addtime' => time(), 'status' => 1)); $rs[] = $mo->table('qq3479015851_myzr')->add(array('userid' => $peer['userid'], 'username' => $user_coin[$coin . 'b'], 'coinname' => $coin, 'txid' => md5($user_coin[$coin . 'b'] . $addr . time()), 'num' => $num, 'fee' => $fee, 'mum' => $mum, 'addtime' => time(), 'status' => 1)); $this->success('您已提币成功,后台审核后将自动转出!'); } else { //eth 钱包转出 $heyue = $Coin['dj_yh'];//合约地址 $auto_status = ($Coin['zc_zd'] && ($num < $Coin['zc_zd']) ? 1 : 0); $mo = M(); $rs = array(); $rs[] = $r = $mo->table('qq3479015851_user_coin')->where(array('userid' => userid()))->setDec($coin, $num); $rs[] = $aid = $mo->table('qq3479015851_myzc')->add(array('userid' => userid(), 'username' => $addr, 'coinname' => $coin, 'num' => $num, 'fee' => $fee, 'mum' => $mum, 'addtime' => time(), 'status' => $auto_status)); if ($auto_status) { $EthCommon = new \Org\Util\EthCommon(COIN_ADDR, COIN_PORT, "2.0"); $EthPayLocal = new \Org\Util\EthPayLocal(COIN_ADDR, COIN_PORT, "2.0", COIN_CAIWU); if ($heyue) { //合约地址转出 $zhuan['toaddress'] = $addr; $zhuan['token'] = $<PASSWORD>; $zhuan['type'] = $coin; $zhuan['amount'] = floatval($mum); $sendrs = $EthPayLocal->eth_ercsendTransaction($zhuan); } else { //eth $zhuan['toaddress'] = $addr; $zhuan['amount'] = floatval($mum); $sendrs = $EthPayLocal->eth_sendTransaction($zhuan); } if ($sendrs && $aid) { $arr = json_decode($sendrs, true); $hash = $arr['result'] ? $arr['result'] : $arr['error']['message']; if ($hash) M()->execute("UPDATE `qq3479015851_myzc` SET `hash` = '$hash' WHERE id = '$aid' "); } $this->success('您已提币成功,后台审核后将自动转出!' . $mum); } $this->success('您已提币成功,后台审核后将自动转出!'); } } //eth 357898628 if ($Coin['type'] == 'rgb') { debug($Coin, '开始认购币转出'); // $peer = M('UserCoin')->where(array($qbdz => $addr))->find(); $peer = $mo->table('qq3479015851_user_coin')->where(array($qbdz => $addr))->find(); if (!$peer) { $this->error('转出认购币地址不存在!'); } $mo = M(); $mo->execute('set autocommit=0'); //$mo->execute('lock tables qq3479015851_user_coin write , qq3479015851_myzc write , qq3479015851_myzr write , qq3479015851_myzc_fee write'); $rs = array(); $rs[] = $mo->table('qq3479015851_user_coin')->where(array('userid' => userid()))->setDec($coin, $num); $rs[] = $mo->table('qq3479015851_user_coin')->where(array('userid' => $peer['userid']))->setInc($coin, $mum); if ($fee) { if ($mo->table('qq3479015851_user_coin')->where(array($qbdz => $Coin['zc_user']))->find()) { $rs[] = $mo->table('qq3479015851_user_coin')->where(array($qbdz => $Coin['zc_user']))->setInc($coin, $fee); debug(array('msg' => '转出收取手续费' . $fee), 'fee'); } else { $rs[] = $mo->table('qq3479015851_user_coin')->add(array($qbdz => $Coin['zc_user'], $coin => $fee)); debug(array('msg' => '转出收取手续费' . $fee), 'fee'); } } $rs[] = $mo->table('qq3479015851_myzc')->add(array('userid' => userid(), 'username' => $addr, 'coinname' => $coin, 'txid' => md5($addr . $user_coin[$coin . 'b'] . time()), 'num' => $num, 'fee' => $fee, 'mum' => $mum, 'addtime' => time(), 'status' => 1)); $rs[] = $mo->table('qq3479015851_myzr')->add(array('userid' => $peer['userid'], 'username' => $user_coin[$coin . 'b'], 'coinname' => $coin, 'txid' => md5($user_coin[$coin . 'b'] . $addr . time()), 'num' => $num, 'fee' => $fee, 'mum' => $mum, 'addtime' => time(), 'status' => 1)); if ($fee_user) { $rs[] = $mo->table('qq3479015851_myzc_fee')->add(array('userid' => $fee_user['userid'], 'username' => $Coin['zc_user'], 'coinname' => $coin, 'txid' => md5($user_coin[$coin . 'b'] . $Coin['zc_user'] . time()), 'num' => $num, 'fee' => $fee, 'type' => 1, 'mum' => $mum, 'addtime' => time(), 'status' => 1)); } if (check_arr($rs)) { $mo->execute('commit'); //$mo->execute('unlock tables'); session('myzc_verify', null); $this->success('转账成功!'); } else { $mo->execute('rollback'); $this->error('转账失败!'); } } if ($Coin['type'] == 'qbb') { // $mo = M(); // $peer = M('UserCoin')->where(array($qbdz => $addr))->find(); $peer = $mo->table('qq3479015851_user_coin')->where(array($qbdz => $addr))->find(); if ($peer) { $mo = M(); $rs = array(); $rs[] = $mo->table('qq3479015851_user_coin')->where(array('userid' => userid()))->setDec($coin, $num); $rs[] = $mo->table('qq3479015851_user_coin')->where(array('userid' => $peer['userid']))->setInc($coin, $mum); $rs[] = $mo->table('qq3479015851_myzc')->add(array('userid' => userid(), 'username' => $addr, 'coinname' => $coin, 'txid' => md5($addr . $user_coin[$coin . 'b'] . time()), 'num' => $num, 'fee' => $fee, 'mum' => $mum, 'addtime' => time(), 'status' => 1)); $rs[] = $mo->table('qq3479015851_myzr')->add(array('userid' => $peer['userid'], 'username' => $user_coin[$coin . 'b'], 'coinname' => $coin, 'txid' => md5($user_coin[$coin . 'b'] . $addr . time()), 'num' => $num, 'fee' => $fee, 'mum' => $mum, 'addtime' => time(), 'status' => 1)); $this->success('您已提币成功,后台审核后将自动转出!'); } else { $dj_username = $Coin['dj_yh']; $dj_password = $Coin['<PASSWORD>']; $dj_address = $Coin['dj_zj']; $dj_port = $Coin['dj_dk']; $CoinClient = CoinClient($dj_username, $dj_password, $dj_address, $dj_port, 5, array(), 1); $json = $CoinClient->getinfo(); if (!isset($json['version']) || !$json['version']) { //$this->error('钱包链接失败!'); } $valid_res = $CoinClient->validateaddress($addr); if (!$valid_res['isvalid']) { $this->error($addr . '不是一个有效的钱包地址!'); } $auto_status = ($Coin['zc_zd'] && ($num < $Coin['zc_zd']) ? 1 : 0); if ($json['balance'] < $num) { //$this->error('钱包余额不足'); } $mo = M(); $rs = array(); $rs[] = $r = $mo->table('qq3479015851_user_coin')->where(array('userid' => userid()))->setDec($coin, $num); $rs[] = $aid = $mo->table('qq3479015851_myzc')->add(array('userid' => userid(), 'username' => $addr, 'coinname' => $coin, 'num' => $num, 'fee' => $fee, 'mum' => $mum, 'addtime' => time(), 'status' => $auto_status)); if ($auto_status) { $sendrs = $CoinClient->sendtoaddress($addr, floatval($mum)); $this->success('您已提币成功,后台审核后将自动转出!'); } else { $this->success('您已提币成功,后台审核后将自动转出!'); } session('myzc_verify',null); } } } public function mywt($market = NULL, $type = NULL, $status = NULL) { if (!userid()) { redirect('/Login'); } if($market != null){ $market = str_replace("cnyt", "cny", $market); } $this->assign('prompt_text', D('Text')->get_content('finance_mywt')); check_server(); $Coin = M('Coin')->where(array('status' => 1))->select(); foreach ($Coin as $k => $v) { $coin_list[$v['name']] = $v; } $this->assign('coin_list', $coin_list); $Market = M('Market')->where(array('status' => 1))->select(); foreach ($Market as $k => $v) { $v['xnb'] = explode('_', $v['name'])[0]; $v['rmb'] = explode('_', $v['name'])[1]; $market_list[$v['name']] = $v; } $this->assign('market_list', $market_list); if($market != null) { if (!$market_list[$market]) { $market = $Market[0]['name']; } $where['market'] = $market; } if (($type == 1) || ($type == 2)) { $where['type'] = $type; } if (($status == 1) || ($status == 2) || ($status == 3)) { $where['status'] = $status - 1; } $where['userid'] = userid(); $this->assign('market', $market); $this->assign('type', $type); $this->assign('status', $status); $Moble = M('Trade'); $count = $Moble->where($where)->count(); $Page = new \Think\Page($count, 15); $Page->parameter .= 'type=' . $type . '&status=' . $status . '&market=' . $market . '&'; $show = $Page->show(); $list = $Moble->where($where)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select(); foreach ($list as $k => $v) { $list[$k]['num'] = $v['num'] * 1; $list[$k]['price'] = $v['price'] * 1; $list[$k]['deal'] = $v['deal'] * 1; } $this->assign('status', $status); $this->assign('list', $list); $this->assign('page', $show); $this->display(); } public function introduce_main(){//主区介绍页面 $this->display(); } public function introduce_new(){//创新区介绍页面 $this->display(); } public function introduce_experiment(){//实验区介绍页面 $this->display(); } public function myzr_list(){//用户转入币记录 if (!userid()) { redirect('/Login'); } $where['userid'] = userid(); $Moble = M('Myzr'); $count = $Moble->where($where)->count(); $Page = new \Think\Page($count, 20); $show = $Page->show(); $list = $Moble->where($where)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select(); $this->assign('list', $list); $this->assign('page', $show); $this->display(); } public function myzc_list(){//用户转出币记录 if (!userid()) { redirect('/Login'); } $where['userid'] = userid(); $Moble = M('Myzc'); $count = $Moble->where($where)->count(); $Page = new \Think\Page($count, 20); $show = $Page->show(); $list = $Moble->where($where)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select(); $this->assign('list', $list); $this->assign('page', $show); $this->display(); } public function zcdb(){ $now_time = time(); if (!userid()) { redirect('/Login'); } if(check_activity(userid(),'zcdb')){ $is_activity=1; }else{ $is_activity=0; } $where['userid'] = userid(); $Moble = M('LockCoin'); $count = $Moble->where($where)->count(); $Page = new \Think\Page($count, 10); $show = $Page->show(); $zcdb_set = M('LockSet')->where(array('id' => 1))->find(); $list=[]; foreach (json_decode($zcdb_set['parameter'],true) as $key => $value){ $list[]=['length_day'=>$key,'proportion'=>$value]; } $zcdb_set['list'] = $list; $list = $Moble->where($where)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select(); $where=['status'=>1, [['name'=>'eth_cny'], ['name'=>$zcdb_set['currency'].'_cny'], '_logic'=>'OR']]; $Market = M('Market')->where($where)->select(); foreach ($Market as $key => $value){ $Market[$value['name']]=$value; } foreach ($list as $key => $value){ if($value['status']==3){ $list[$key]['shouyi'] = $value['num_profit'].$value['currency_profit']; }else{ $list[$key]['shouyi']="¥".round($value['mum_profit'],2)." ≈ ".round($value['mum_profit']/$Market[$value['currency_profit'].'_cny']['new_price'],4).$value['currency_profit']; } if($value['status'] == 1){ if($now_time > $value['end_time']){ $status = 1; }else{ $status = 0; } }else{ $status = $value['status']; } $status_texts=['对标中','对标结束','已申请,待审核','已结算']; $list[$key]['status_text']=$status_texts[$status]; $list[$key]['status']=$status; } $userCoin = M('UserCoin')->where(array('userid' => userid()))->find(); $currency_lock_num = $userCoin[$zcdb_set['currency']]; $this->assign('currency_lock_num', floatval($currency_lock_num)); $this->assign('zcdb_set', $zcdb_set); $this->assign('currency_lock_new_price', $Market[$zcdb_set['currency'].'_cny']['new_price']); $this->assign('currency_profit_new_price',$Market['eth_cny']['new_price']); $this->assign('list', $list); $this->assign('is_activity', $is_activity); $this->assign('page', $show); $this->display(); } /** * 开通资产对标活动 */ public function open_activity($type=null){ if (!userid()) { redirect('/Login'); } switch ($type){ case 'lock': $filed = 'zcdb'; $set = M('LockSet')->where(['id'=>1])->find(); break; default: return; } if(open_activity(userid(),$filed,$set['threshold'])){ $this->success('开通成功!'); }else{ $this->error('开通失败,积分不足'); } } public function zcdb_submit(){ if (!userid()) { $this->error('请先登录!'); } $now_time=time(); $num = intval($_POST['num']); $day = intval($_POST['day']); if($num <= 0){ $this->error('请输入500或500倍数的锁仓数量'); } if($num%500 != 0){ $this->error('请输入500或500倍数的锁仓数量'); } $zcdb_set = M('LockSet')->where(array('id' => 1))->find(); $UserCoin = M('UserCoin')->where(array('userid' => userid()))->find(); if($UserCoin[$zcdb_set['currency']]<$num){ $this->error($zcdb_set['currency'].'数量不足'); } $days=[]; foreach (json_decode($zcdb_set['parameter'],true) as $key => $value){ $days[$key]=$value; } // $days=[90=>0.15,180=>0.4,360=>1]; if(!array_key_exists($day,$days)){ $this->error('数据错误'); } $where=['status'=>1, [['name'=>'eth_cny'], ['name'=>$zcdb_set['currency'].'_cny'], '_logic'=>'OR']]; $Market = M('Market')->where($where)->select(); foreach ($Market as $key => $value){ $Market[$value['name']]=$value; } $start_time = $now_time; $end_time = strtotime('+'.$day.'day'); $add=[ 'userid'=>userid(), 'currency_lock'=>$zcdb_set['currency'], 'num_lock'=>$num, 'value_lock'=>$num * $Market[$zcdb_set['currency'].'_cny']['new_price'], 'currency_profit'=>'eth', 'mum_profit'=>$num * $Market[$zcdb_set['currency'].'_cny']['new_price'] * $days[$day], 'proportion'=>$days[$day], 'start_time'=>$start_time, 'end_time'=>$end_time, 'length_day'=>$day ]; $mo = M(); $mo->execute('set autocommit=0'); $rs = array(); $rs[] = $mo->table('qq3479015851_user_coin')->where(array('userid' => userid()))->setDec($zcdb_set['currency'], $num);; $rs[] = $mo->table('qq3479015851_lock_coin')->add($add); if (check_arr($rs)) { $mo->execute('commit'); $this->success('锁仓成功!'); }else{ $mo->execute('rollback'); $this->error('锁仓失败'); } } /** * 申请结算 */ public function apply_settle($id=null){ if (!userid()) { $this->error('请先登录!'); } if($id){ $info = M('LockCoin')->where(['id'=>$id,'userid'=>userid(),'status'=>1,'end_time'=>['lt',time()]])->find(); if(empty($info)){ $this->error('数据错误'); } M('LockCoin')->where(['id'=>$id])->save(['status'=>2]); $this->success('申请成功!'); }else{ $this->error('数据错误'); } } } ?> <file_sep>var lange = {}; lange.ALL_OK = '确定'; lange.ALL_CANCEL = '取消'; lange.ALL_CANCEL_CONFIRM = '确认取消?'; lange.ALL_CONFIRM = '请确认?'; lange.ALL_WEBSOCKET_SUCCESS = 'websocket握手成功,发送登录数据:'; lange.FINANCE_BANK_CHANGEFILE = '请选择正确的文件类型和大小!'; lange.FINANCE_BANK_UPLOADERROR = '上传出错!'; lange.FINANCE_MYCZ_ACCOUNT = '账户:'; lange.FINANCE_MYCZ_COPY_SUCCESS = '复制成功'; lange.FINANCE_MYCZ_TIP_INPUT_NUM = '请输入数字'; lange.FINANCE_MYCZ_TIP_INPUT_NUM2 = '最低买入500.0CNYT'; lange.FINANCE_MYCZ_TIP_INPUT_NUM3 = '买入CNYT需为100的倍数'; lange.FINANCE_MYCZ_TIP_INPUT_NUM4 = '最低卖出500.0CNYT'; lange.FINANCE_MYCZ_TIP_INPUT_NUM5 = '卖出CNYT需为100的倍数'; lange.FINANCE_MYCZ_CHOOSE_PAYTYPE = '请选择交易方式'; lange.FINANCE_MYCZ_CHOOSE_BUYNUM = '请输入买入量'; lange.FINANCE_MYCZ_CHOOSE_SELLNUM = '请输入卖出量' lange.FINANCE_MYCZ_LOADING = '加载中,请勿重复点击...'; lange.ALL_PAY_CONFIRM = '确认已支付?'; lange.FINANCE_OUT_SENDSMS = '发送短信验证码'; lange.FINANCE_OUT_SENDSMS2 = '秒可再次发送'; lange.FINANCE_OUT_SENDSMS3 = '发送短信验证码'; lange.FINANCE_OUT_CHECK1 = '请输入短信验证码'; lange.FINANCE_OUT_CHECK2 = '请输入转出数量'; lange.FINANCE_OUT_CHECK3 = '请选择转出地址'; lange.FINANCE_OUT_CHECK4 = '请输入交易密码'; lange.FINANCE_OUT_CHECK5 = '请选择币种'; lange.FINANCE_OUT_CHECK6 = '输入谷歌验证码,并确认'; lange.FINANCE_OUT_LOADING = '加载中,请勿重复点击...'; lange.FINANCE_ZCDB_1 = '请输入500或500倍数'; lange.FINANCE_ZCDB_2 = '收益'; lange.FINANCE_ZCDB_3 = '输入错误'; lange.FINANCE_ZCDB_4 = '请输入500或500倍数的锁仓数量'; lange.FINANCE_ZCDB_5 = '锁仓币种:CNUT<br>锁仓时长:'; lange.FINANCE_ZCDB_6 = '天<br>锁仓数量:'; lange.FINANCE_ZCDB_7 = '确定锁仓'; lange.FINANCE_ZCDB_8 = '是否确认开通资产对标'; lange.FINDPWD_FINDPWD_1 = '发送验证码'; lange.FINDPWD_FINDPWD_2 = '请输入图形验证码'; lange.FINDPWD_FINDPWD_3 = '请选择验证类型'; lange.FINDPWD_FINDPWD_5 = '发送短信验证码'; lange.FINDPWD_FINDPWD_6 = '请输入验证码'; lange.FINDPWD_FINDPWDCONFIRM_1 = '请输入新密码'; lange.FINDPWD_FINDPWDCONFIRM_2 = '请输入确认密码'; lange.FINDPWD_FINDPWDCONFIRM_3 = '确认密码错误'; lange.LOGIN_FINDPAYPWD_1 = '请输入手机号'; lange.LOGIN_FINDPAYPWD_2 = '点击发送验证码'; lange.LOGIN_FINDPWD_1 = '请输入账号'; lange.LOGIN_FINDPWD_2 = '获取验证码'; lange.LOGIN_FINDPWD_4 = '账户类型不支持'; lange.LOGIN_FINDPWD_6 = '获取验证码'; lange.LOGIN_FINDPWD_12 = '请输入邮箱'; lange.LOGIN_FINDPWD_13 = '不支持的账号'; lange.LOGIN_FINDPWDCONFIRM_1 = '请输入新密码'; lange.LOGIN_FINDPWDCONFIRM_2 = '请输入确认密码'; lange.LOGIN_FINDPWDCONFIRM_3 = '确认密码错误'; lange.LOGIN_INDEX_1 = '请输入登录账号'; lange.LOGIN_INDEX_2 = '请输入登录密码'; lange.LOGIN_PAYPASSWORD_1 = '请输入交易密码'; lange.LOGIN_PAYPASSWORD_2 = '请输入确认密码'; lange.LOGIN_PAYPASSWORD_3 = '确认密码错误'; lange.LOGIN_REGISTER_1 = '用户注册协议'; lange.LOGIN_REGISTER_5 = '请输入密码'; lange.LOGIN_REGISTER_6 = '请确认两次密码相同'; lange.LOGIN_REGISTER_7 = '请勾选用户注册协议'; lange.LOGIN_REGISTER_8 = '请输入邮箱验证码'; lange.LOGIN_REGISTER3_1 = '请输入真实姓名'; lange.LOGIN_REGISTER3_2 = '请输入身份证号'; lange.TRADE_INDEX_1 = '万'; lange.TRADE_INDEX_2 = '亿'; lange.TRADE_INDEX_3 = '当前无数据!'; lange.TRADE_INDEX_4 = '昨日收盘价:'; lange.TRADE_INDEX_5 = '今日涨幅限制:'; lange.TRADE_INDEX_6 = '今日跌幅限制:'; lange.TRADE_INDEX_7 = '今日买入最小交易价:'; lange.TRADE_INDEX_8 = '今日卖出最大交易价:'; lange.TRADE_INDEX_9 = '今日行情'; lange.TRADE_INDEX_10 = '请输入交易密码'; lange.TRADE_INDEX_11 = '请输入选择一个'; lange.TRADE_INDEX_12 = '设置成功'; lange.TRADE_INDEX_13 = '不要重复提交'; lange.TRADE_INDEX_14 = '请输入内容'; lange.TRADE_INDEX_15 = '买入'; lange.TRADE_INDEX_16 = '卖出'; lange.TRADE_INDEX_17 = '登录'; lange.TRADE_INDEX_18 = '交易密码输入设置'; lange.TRADE_INDEX_19 = '保存'; lange.TRADE_INDEX_20 = '退出了'; lange.TRADE_INDEX_21 = ''; lange.TRADE_INDEX_22 = ''; lange.TRADE_INDEX_23 = ''; lange.TRADE_INDEX_24 = ''; <file_sep>/** * @desc 绘制折线图 * @param {Object} defaultParam 配置参数 * @param {Object} el canvas el * @param {Array } data 折线数据点 * @param {Object} styleSet 样式设置 可省略 * @eg: * var canvas2 = Charts({ * el:obj, * data:[20,60,60,80,100,120,140,60,100], * styleSet:{ * lineColor:'#8a93fe', * } * }) */ ;(function(window,undefined){ function Charts(defaultParam){ //获取canvas var can1 = defaultParam.el; //手机端自适应 设置canvas绘制元素宽度(默认300) //获取canvas绘制元素高度 can1.height = can1.height; height = can1.height - 5, ctx = can1.getContext("2d"), //初始数据 nums = defaultParam.data, //默认颜色 setDefault = { styleSet:{ lineColor:'#ff984e', } } return new Charts.prototype.init(defaultParam,ctx,nums,can1.width,height); } Charts.prototype = { init: function(defaultParam,ctx,nums,wd,ht){ //去除边界宽度 var wid = wd; //获取数据的最大值并设置峰值0.88比例 var maxPoint = this.maxData(nums) / 0.9; //参数合并 defaultParam = this.extend(setDefault,defaultParam); //执行绘制函数 this.drawLinearGradient(defaultParam,ctx,nums,wd,ht,wid,maxPoint); this.drawLine(defaultParam,ctx,nums,wd,ht,wid,maxPoint); this.drawOpacity(defaultParam,ctx,nums,wd,ht,wid,maxPoint); return this; }, drawLine: function(defaultParam,ctx,nums,wd,ht,wid,maxPoint){ for (i = 0;i < nums.length-1;i ++){ //起始坐标 var axiosY = ht - ht*nums[i]/maxPoint, averNum= (wid/nums.length), axiosX = i * averNum + 2, //终止坐标 axiosNY = ht - ht*nums[i+1]/maxPoint, axiosNX = (i+1) * averNum + 2; //划线 ctx.beginPath(); ctx.moveTo(axiosX,axiosY); ctx.lineTo(axiosNX,axiosNY); ctx.lineWidth = 2; ctx.strokeStyle = defaultParam.styleSet.lineColor; ctx.setLineDash([0]); ctx.closePath(); ctx.stroke(); } }, drawLinearGradient: function(defaultParam,ctx,nums,wd,ht,wid,maxPoint){ ctx.beginPath(); ctx.lineWidth = 1; var x0 = 0; for (i = 0;i < nums.length-1;i ++){ //起始坐标 var axiosY = ht - ht*nums[i]/maxPoint -1, averNum= (wid/nums.length), axiosX = i * averNum + 2, //终止坐标 axiosNY = ht - ht*nums[i+1]/maxPoint -1, axiosNX = (i+1) * averNum + 2; //划线 if(!i){ x0 = axiosX; } } var my_gradient = ctx.createLinearGradient(0,0,0,ht+5); my_gradient.addColorStop(0,defaultParam.styleSet.topColor); my_gradient.addColorStop(1,defaultParam.styleSet.bottomColor); ctx.fillStyle = my_gradient; ctx.fillRect(x0,0,axiosNX-x0,ht+5); }, drawOpacity: function(defaultParam,ctx,nums,wd,ht,wid,maxPoint){ ctx.beginPath(); for (i = 0;i < nums.length-1;i ++){ //起始坐标 var axiosY = ht - ht*nums[i]/maxPoint -1, averNum= (wid/nums.length), axiosX = i * averNum + 2, //终止坐标 axiosNY = ht - ht*nums[i+1]/maxPoint -1, axiosNX = (i+1) * averNum + 2; //划线 if(!i){ ctx.moveTo(axiosX,0); } ctx.lineTo(axiosX,axiosY); } ctx.lineTo(axiosNX+2,axiosNY); ctx.lineTo(axiosNX+2,0); ctx.fillStyle = '#000000'; ctx.globalCompositeOperation = "destination-out"; ctx.closePath(); ctx.fill(); ctx.globalCompositeOperation = 'source-over'; }, maxData:function(arr){ return Math.max.apply(null,arr) }, minData:function(arr){ return Math.min.apply(null,arr) }, extend: function(defaults,newObj){     for (var i in newObj) {       defaults[i] = newObj[i];     }     return defaults; } } Charts.prototype.init.prototype = Charts.prototype; if(!window.Charts){ window.Charts = Charts; } })(window,undefined);<file_sep><?php /** * Created by PhpStorm. * User: BBB * Date: 2018/8/14 * Time: 11:40 */ namespace Home\Controller; class TaskController extends HomeController { public function index(){ $this->display(); } public function lists($type=NULL) { $userid=userid(); if (!userid()) { redirect('/#login'); } //if($userid !=111908) $this->error('暂未开启,敬请期待'); $where['userid'] = $userid; $where['start'] = 2; $allname = "发放类型"; if($type=="myyq"){ $name = "C计划-邀请奖励"; $list = M('FenhongMyyq')->where($where)->order('id desc')->limit(0 , 40)->select(); foreach($list as $k=>$v){ $list[$k]['name'] = "邀请奖励"; $list[$k]['num'] = round($v['num'],5); $list[$k]['tps'] = $v['uid']; } } if($type=="mywk"){ $name = "C计划-挖矿解冻"; $list = M()->query("SELECT * FROM `b_wakuang` where userid = '$userid' "); foreach($list as $k=>$v){ $list[$k]['name'] = $v['cnut']; $list[$k]['addtime'] = $v['jdtime']; $list[$k]['num'] = round($v['cnut']/100,4); $list[$k]['tps'] = round($v['cnut']/100*$v['yci'],2); } } if($type=="myfh"){ $name = "C计划-持币分红"; $list = M('FenhongMyfh')->where($where)->order('id desc')->limit(0 , 40)->select(); foreach($list as $k=>$v){ $list[$k]['name'] = "持币分红"; $list[$k]['num'] = round($v['num'],5); $list[$k]['tps'] = $v['allnum'] > 0 ? "自己":"推荐"; } } if($type=="myjy"){ $name = "C计划-交易分红"; //$count = M('FenhongMyjy')->where($where)->count(); //$Page = new \Think\Page($count, 40); //$show = $Page->show(); //$list = M('FenhongMyjy')->where($where)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select(); $list = M('FenhongMyjy')->where($where)->order('id desc')->limit(0 , 40)->select(); foreach($list as $k=>$v){ $list[$k]['name'] = "交易分红"; $list[$k]['num'] = round($v['num'],5); $list[$k]['tps'] = $v['allnum'] > 0 ? "自己":"推荐"; } } $this->assign('type', $type); $this->assign('name', $name); $this->assign('list', $list); $this->assign('page', $show); $this->display(); } public function settings(){ $this->display(); } }<file_sep><?php namespace Common\Model; class FenhongModel extends \Think\Model { protected $keyS = 'Fenhong'; } ?><file_sep><?php namespace Home\Controller; class VerifyController extends HomeController { public function __construct() { parent::__construct(); } public function code() { ob_clean(); $config['useNoise'] = false; $config['length'] = 4; $config['codeSet'] = '0123456789'; $verify = new \Think\Verify($config); $verify->entry(1); } public function real($moble, $verify) { if (!userid()) { redirect('/Login'); } if (!check_verify(strtoupper($verify))) { $this->error('图形验证码错误!'); } if (!check($moble, 'moble')) { $this->error('手机号码格式错误!'); } if (M('User')->where(array('moble' => $moble))->find()) { $this->error('手机号码已存在!'); } $code = rand(111111, 999999); session('real_verify', $code); session('verify#time', time()); $content = 'CC找密码,your code:' . $code; if (SendText($moble, $code, 'fog')) { $this->success('短信验证码已发送到你的手机,请查收'); } else { $this->error('短信验证码发送失败,请重新点击发送'); } } public function real_qq3479015851($moble,$moble_new) { if (!userid()) { $this->error('请先登录!'); } if (!check($moble, 'moble')) { $this->error('手机号码格式错误!'); } if (!check($moble_new, 'moble')) { $this->error('新手机号码格式错误!'); } $moble = $this->_replace_china_mobile($moble); $moble_new = $this->_replace_china_mobile($moble_new); if (M('User')->where(array('moble' => $moble_new))->find()) { $this->error('更换绑定的手机号码已经注册过账户!'); } $code = rand(111111, 999999); session('real_verify', $code); session('verify#time', time()); $content = 'CC换手机,your code:' . $code; if (SendText($moble, $code, 'chg')) { if(MOBILE_CODE ==0 ){ $this->success('目前是演示模式,请输入'.$code); }else{ $this->success('短信验证码已发送到你的手机,请查收'); } } else { $this->error('短信验证码发送失败,请重新点击发送'); } } public function moble(){ if (!userid()) { redirect('/Login'); } if (session('real_moble')) { $this->success('短信验证码已发送到你的手机,请注意查收'); } $moble = M('User')->where(array('id' => userid()))->getField('moble'); if (!$moble) { $this->error('手机号码未绑定!',U('User/moble')); } $code = rand(111111, 999999); session('real_moble',$code); $content = '您正在进行手机操作,您的验证码是' . $code; if (SendText($moble, $code, 'chg')) { $this->success('短信验证码已发送到你的手机,请查收'); } else { $this->error('短信验证码发送失败,请重新点击发送'); } } public function mytx() { if (!userid()) { $this->error('请先登录'); } $moble = M('User')->where(array('id' => userid()))->getField('moble'); if (!$moble) { $this->error('你的手机没有认证'); } $code = rand(111111, 999999); session('mytx_verify', $code); session('verify#time', time()); $content = 'CC提币,your code:' . $code; if (SendText($moble, $code, 'cur')) { if(MOBILE_CODE ==0 ){ $this->success('目前是演示模式,请输入'.$code); }else{ $this->success('短信验证码已发送到你的手机,请查收'); } } else { $this->error('短信验证码发送失败,请重新点击发送'); } } public function sendMobileCode() { if (IS_POST) { $input = I('post.'); if (!check_verify(strtoupper($input['verify']))) { $this->error('图形验证码错误!', 'mobile_verify'); } if (!check($input['mobile'], 'moble')) { $this->error('手机号码格式错误!', 'mobile'); } if (M('User')->where(array('moble' => $input['mobile']))->find()) { $this->error('手机号码已存在!'); } if ((session('mobile#mobile') == $input['mobile']) && (time() < (session('mobile#real_verify#time') + 600))) { $code = session('mobile#real_verify'); session('mobile#real_verify', $code); } else { $code = rand(111111, 999999); session('mobile#real_verify#time', time()); session('mobile#mobile', $input['mobile']); session('mobile#real_verify', $code); } $content = '您正在进行手机操作,您的验证码是' . $code; if (1) { $this->success('短信验证码已发送到你的手机,请查收' . $code); } else { $this->error('短信验证码发送失败,请重新点击发送'); } } else { $this->error('非法访问!'); } } public function sendEmailCode() { if (IS_POST && userid()) { $input = I('post.'); if (!check($input['email'], 'email')) { $this->error('邮箱格式错误!'); } if (M('User')->where(array('email' => $input['email']))->find()) { $this->error('邮箱已被使用,请选择其他邮箱!'); } $code = rand(111111, 999999); session('email#real_verify#time', time()); session('email#email', $input['email']); session('email#real_verify', $code); $content = '您正在进行邮箱注册操作,您的验证码是' . $code; $data = array("to"=>$input['email'], "subject"=>"绑定邮箱验证码", "content"=>$content); if (SendEmail($data)) { $this->success('邮箱验证码已发送到你的邮箱,请前往查收'); } else { $this->error('邮箱验证码发送失败,请重新点击发送'); } } else { $this->error('非法访问!'); } } /* * 这个被弃用了 * */ public function findpwd() { $this->error("fatal error"); if (IS_POST) { $input = I('post.'); if (!check_verify(strtoupper($input['verify']))) { $this->error('图形验证码错误!'); } if (!check($input['username'], 'username')) { $this->error('用户名格式错误!'); } $moble = $this->_replace_china_mobile($input['moble']); if (!check($moble, 'moble')) { $this->error('手机号码格式错误!'); } $user = M('User')->where(array('username' => $input['username']))->find(); if (!$user) { $this->error('用户名不存在!'); } if ($user['moble'] != $moble) { $this->error('用户名或手机号码错误!'); } $code = rand(111111, 999999); session('findpwd_verify', $code); session('verify#time', time()); $content = 'CC找密码,your code:' . $code; if (SendText($moble, $code, 'fog')) { $this->success('短信验证码已发送到你的手机,请查收'); } else { $this->error('短信验证码发送失败,请重新点击发送'); } } } /** * 找回密码时,发送短信验证码(未登录) */ public function moble_findpwd() { if (IS_POST) { $input = I('post.'); if (!check_verify(strtoupper($input['verify']))) { $this->error('图形验证码错误!'); } if (userid()) { $user = M('User')->where(array('id' => userid()))->find(); if (!$user) { $this->error('用户名不存在!'); } $moble = $user['moble']; if(empty($moble)){ $this->error('当前手机不可用!'); } if (!check($moble, 'moble')) { $this->error('手机号码格式错误!'); } }else{ $moble = $this->_replace_china_mobile($input['moble']); if (!check($moble, 'moble')) { $this->error('手机号码格式错误!'); } $user = M('User')->where(array('moble' => $moble))->find(); if (!$user) { $this->error('手机号码不存在!'); } } $code = rand(111111, 999999); session('findpwd_verify', $code); session('verify#time', time()); //手机号码和Code做MD5写入Session //防止发送短信后篡改用户手机,重置他人密码 session('modify_password_validation', md5($moble)); $content = 'CC找密码,your code:' . $code; if (SendText($moble, $code, 'fog')) { if(MOBILE_CODE ==0 ){ $this->success('目前是演示模式,请输入'.$code); }else{ $this->success('短信验证码已发送到你的手机,请查收'); } } else { $this->error('短信验证码发送失败,请重新点击发送2'); //$this->error('短信验证码发送失败,请重新点击发送'); } } } /** * 找回密码时,发送邮箱验证码(未登录) */ public function email_findpwd() { if (IS_POST) { $input = I('post.'); if (!check_verify(strtoupper($input['verify']))) { $this->error('图形验证码错误!'); } if (userid()) { $user = M('User')->where(array('id' => userid()))->find(); if (!$user) { $this->error('用户不存在!'); } $email = $user['email']; if(empty($email)){ $this->error('当前无可用邮箱!'); } if (!check($email, 'email')) { $this->error('邮箱格式错误!'); } }else{ if (!check($input['email'], 'email')) { $this->error('邮箱格式错误!'); } $user = M('User')->where(array('email' => $input['email']))->find(); if (!$user) { $this->error('邮箱账号不存在!'); } $email = $user['email']; } $code = rand(111111, 999999); session('findpwd_verify', $code); session('verify#time', time()); //邮箱码和Code做MD5写入Session session('modify_password_validation', md5($user['email'])); $content = 'CC找密码,your code:' . $code; $data = array("to"=>$email, "subject"=>"找回密码验证码", "content"=>$content); if (SendEmail($data)) { if(MOBILE_CODE ==0 ){ $this->success('目前是演示模式,请输入'.$code); }else{ $this->success('邮箱验证码已发送到你的邮箱,请前往查收'); } } else { $this->error('邮箱验证码发送失败,请重新点击发送'); } } } //当前登录用户手机找回支付密码时发送验证码 public function moble_send_findpaypwd() { if (!userid()) { redirect('/Login'); } $input = I('post.'); if (!check_verify(strtoupper($input['verify']))) { $this->error('图形验证码错误!'); } $user = M('User')->where(array('id' => userid()))->find(); if (!$user) { $this->error('用户名不存在!'); } $moble = $user['moble']; if(empty($moble)){ $this->error('当前手机不可用!'); } if (!check($moble, 'moble')) { $this->error('手机号码格式错误!'); } $code = rand(111111, 999999); session('findpaypwd_verify', $code); session('verify#time', time()); $content = 'CC找密码,your code:' . $code; if (SendText($moble, $code, 'fog')) { if(MOBILE_CODE ==0 ){ $this->success('目前是演示模式,请输入'.$code); }else{ $this->success('短信验证码已发送到你的手机,请查收'); } } else { $this->error('短信验证码发送失败,请重新点击发送'); } } //当前登录用户邮箱找回支付密码时发送验证码 public function email_send_findpaypwd() { if (!userid()) { redirect('/Login'); } $input = I('post.'); if (!check_verify(strtoupper($input['verify']))) { $this->error('图形验证码错误!'); } $user = M('User')->where(array('id' => userid()))->find(); if (!$user) { $this->error('用户不存在!'); } $email = $user['email']; if(empty($email)){ $this->error('当前无可用邮箱!'); } if (!check($email, 'email')) { $this->error('邮箱格式错误!'); } $code = rand(111111, 999999); session('findpaypwd_verify', $code); session('verify#time', time()); $content = '您正在进行邮箱找回支付密码,您的验证码是' . $code; $data = array("to"=>$email, "subject"=>"找回支付密码验证码", "content"=>$content); if (SendEmail($data)) { if(MOBILE_CODE ==0 ){ $this->success('目前是演示模式,请输入'.$code); }else{ $this->success('邮箱验证码已发送到你的邮箱,请前往查收'); } } else { $this->error('邮箱验证码发送失败,请重新点击发送'); } } public function myzc() { if (!userid()) { $this->error('您没有登录请先登录!'); } $moble = M('User')->where(array('id' => userid()))->getField('moble'); if (!$moble) { $this->error('你的手机没有认证'); } $code = rand(111111, 999999); session('myzc_verify', $code); session('verify#time', time()); $content = 'CC提币,your code:' . $code; if (SendText($moble, $code, 'cur')) { if(MOBILE_CODE ==0 ){ $this->success('目前是演示模式,请输入'.$code); }else{ $this->success('短信验证码已发送到你的手机,请查收'); } } else { $this->error('短信验证码发送失败,请重新点击发送'); } } public function myzr() { if (!userid()) { $this->error('您没有登录请先登录!'); } $moble = M('User')->where(array('id' => userid()))->getField('moble'); if (!$moble) { $this->error('你的手机没有认证'); } $code = rand(111111, 999999); session('myzr_verify', $code); $content = 'CC提币,your code:' . $code; if (SendText($moble, $code, 'cur')) { if(MOBILE_CODE ==0 ){ $this->success('目前是演示模式,请输入'.$code); }else{ $this->success('短信验证码已发送到你的手机,请查收'); } } else { $this->error('短信验证码发送失败,请重新点击发送'); } } } ?> <file_sep><?php namespace Home\Controller; class ArticleController extends HomeController { public function index($id = 19) { if (empty($id)) { redirect(U('Article/detail')); } if (!check($id, 'd')) { redirect(U('Article/detail')); } $this->assign('type', $id == 20?'资讯':'公告'); $Articletype = M('ArticleType')->where(array('id' => $id))->find(); $ArticleTypeList = M('ArticleType')->where(array('status' => 1, 'index' => 1, 'shang' => $Articletype['shang']))->order('sort asc ,id asc')->select(); $Articleaa = M('Article')->where(array('status'=>1,'id' => $ArticleTypeList[0]['id']))->find(); $this->assign('shang', $Articletype); foreach ($ArticleTypeList as $k => $v) { $ArticleTypeLista[$v['name']] = $v; } $this->assign('ArticleTypeList', $ArticleTypeLista); $this->assign('data', $Articleaa); $where = array('type' => $Articletype['name'],'status'=>1); $Model = M('Article'); $count = $Model->where($where)->count(); $Page = new \Think\Page($count, 10); $show = $Page->show(); $list = $Model->where($where)->order('addtime desc')->limit($Page->firstRow . ',' . $Page->listRows)->select(); $hotlist = $Model->where($where)->order('hits desc')->limit(6)->select(); foreach ($list as $k => $v) { $list[$k]['brief'] = mb_substr(preg_replace("/<[^>]+>/is", "", $v['content']), 0, 150); if (empty($v['img'])) $list[$k]['img'] = "app-code.png"; } foreach ($hotlist as $k => $v) { $hotlist[$k]['brief'] = mb_substr(preg_replace("/<[^>]+>/is", "", $v['content']), 0, 150); } $this->assign('list', $list); $this->assign('hotlist', $hotlist); $this->assign('id', $id); $this->assign('page', $show); $this->display(); } public function upgrade(){ $this->display(); } public function detail($id = NULL) { if (empty($id)) { $id = 1; } if (!check($id, 'd')) { $id = 1; } $data = M('Article')->where(array('id' => $id))->find(); $ArticleType = M('ArticleType')->where(array('status' => 1, 'index' => 1))->order('sort asc ,id desc')->select(); foreach ($ArticleType as $k => $v) { $ArticleTypeList[$v['name']] = $v; } $where = array('status'=>1); $Model = M('Article'); $hotlist = $Model->where($where)->order('hits desc')->limit(6)->select(); foreach ($hotlist as $k => $v) { $hotlist[$k]['brief'] = mb_substr(preg_replace("/<[^>]+>/is", "", $v['content']), 0, 150); } $this->assign('hotlist', $hotlist); //保存点击数加一 $rs = M('Article')->where(array('id' => $id))->setInc('hits'); $this->assign('ArticleTypeList', $ArticleTypeList); $this->assign('data', $data); $this->assign('type', $data['type']); $this->display(); } public function mdetail($id = NULL) { if (empty($id)) { $id = 1; } if (!check($id, 'd')) { $id = 1; } $data = M('Article')->where(array('id' => $id))->find(); $ArticleType = M('ArticleType')->where(array('status' => 1, 'index' => 1))->order('sort asc ,id desc')->select(); foreach ($ArticleType as $k => $v) { $ArticleTypeList[$v['name']] = $v; } $this->assign('ArticleTypeList', $ArticleTypeList); $this->assign('data', $data); $this->assign('type', $data['type']); $this->display(); } public function type($id = NULL) { if (empty($id)) { $id = 1; } if (!check($id, 'd')) { $id = 1; } $Article = M('ArticleType')->where(array('id' => $id))->find(); if ($Article['shang']) { $shang = M('ArticleType')->where(array('name' => $Article['shang']))->find(); $ArticleType = M('ArticleType')->where(array('status' => 1, 'shang' => $Article['shang']))->order('sort asc ,id desc')->select(); $Articleaa = $Article; } else { $shang = M('ArticleType')->where(array('id' => $id))->find(); $ArticleType = M('ArticleType')->where(array('status' => 1, 'shang' => $Article['name']))->order('sort asc ,id desc')->select(); $Articleaa = M('ArticleType')->where(array('id' => $ArticleType[0]['id']))->find(); } $this->assign('shang', $shang); foreach ($ArticleType as $k => $v) { $ArticleTypeList[$v['name']] = $v; } $this->assign('ArticleTypeList', $ArticleTypeList); $this->assign('data', $Articleaa); $this->display(); } } ?><file_sep><?php namespace Home\Controller; class FindpwdController extends HomeController { public function check_moble($moble = 0) { if (!check($moble, 'moble')) { $this->error('手机号码格式错误!'); } $moble = $this->_replace_china_mobile($moble); if (M('User')->where(array('moble' => $moble))->find()) { $this->error('手机号码已存在!'); } $this->success(''); } public function check_pwdmoble($moble = 0) { if (!check($moble, 'moble')) { $this->error('手机号码格式错误!'); } if (!M('User')->where(array('moble' => $moble))->find()) { $this->error('手机号码不存在!'); } $this->success(''); } public function real($moble, $verify) { if (!check_verify(strtoupper($verify))) { $this->error('图形验证码错误!'); } if (!check($moble, 'moble')) { $this->error('手机号码格式错误!'); } if (M('User')->where(array('moble' => $moble))->find()) { $this->error('手机号码已存在!'); } $code = rand(111111, 999999); session('real_verify', $code); session('verify#time', time()); $content = 'CC,您正在找回密码,验证码是:' . $code; if (SendText($moble, $code, 'fog')) { if (MOBILE_CODE == 0) { $this->success('目前是演示模式,请输入' . $code); } else { $this->success('验证码已发送'); } } else { $this->error('验证码发送失败,请重发'); } } public function paypassword() { if (!session('reguserId')) { redirect('/Login'); } $this->display(); } public function info() { if (!session('reguserId')) { redirect('/Login'); } $user = M('User')->where(array('id' => session('reguserId')))->find(); if (!$user) { $this->error('请先注册'); } if ($user['regaward'] == 0) { if (C('reg_award') == 1 && C('reg_award_num') > 0) { M('UserCoin')->where(array('id' => session('reguserId')))->setInc(C('reg_award_coin'), C('reg_award_num')); M('User')->where(array('id' => session('reguserId')))->save(array('regaward' => 1)); } } session('userId', $user['id']); session('userName', $user['username']); $this->assign('user', $user); $this->display(); } public function findpwd() { if (!session('userId')) { redirect('/Login'); } if (IS_POST) { $input = I('post.'); //判断参数前校验手机号码是否被篡改 //修改支付密码 $type = $input['type']; $user = M('User')->where(array('id' => userid()))->find(); if (!$user) { $this->error('用户不存在'); } $moble = $user['moble']; $email = $user['email']; $realHash = session('modify_password_validation'); if($type == 'sms'){ $fakeHash = md5($moble); if ($fakeHash != $realHash) $this->error('手机号码错误'); if (!check($moble, 'moble')) { $this->error('手机号码格式错误!'); } if (!check($input['moble_verify'], 'd')) { $this->error('短信验证码格式错误!'); } }else if($type == 'email'){ $fakeHash = md5($email); if ($fakeHash != $realHash) $this->error('邮箱错误!'); if (!check($email, 'email')) { $this->error('邮箱格式错误!'); } if (!check($input['moble_verify'], 'd')) { $this->error('邮箱验证码格式错误!'); } }else{ $this->error('交易方式错误!'); } $this->_verify_count_check($input['moble_verify'],session('findpwd_verify')); if($type == 'sms'){ session("findpaypwdmoble", $moble); }else if($type == 'email'){ session("findpaypwdemail", $email); } session('findpwd_verify',null); $this->success('验证成功'); } else { $this->display(); } } public function findpwdconfirm() { if (empty(session('findpaypwdmoble')) && empty(session('findpaypwdemail'))) { redirect('/'); } $this->display(); } public function password_up($password = "", $repassword = "") { if (empty(session('findpaypwdmoble')) && empty(session('findpaypwdemail'))) { $this->error('请返回第一步重新操作!'); } if (!check($password, 'password')) { $this->error('新交易密码格式错误!'); } if (!check($repassword, 'password')) { $this->error('确认密码格式错误!'); } if ($password != $repassword) { $this->error('确认新密码错误!'); } if(!empty(session('findpaypwdmoble'))){ $moble = $this->_replace_china_mobile(session('findpaypwdmoble')); $user = M('User')->where(array('moble' => $moble))->find(); }else if(!empty(session('findpaypwdemail'))){ $user = M('User')->where(array('email' => session('findpaypwdemail')))->find(); } if (!$user) { $this->error('用户不存在!'); } if ($user['password'] == $password) { $this->error('交易密码不能和登录密码一样'); } $mo = M(); $mo->execute('set autocommit=0'); //$mo->execute('lock tables qq3479015851_user write , qq3479015851_user_log write '); $rs = $mo->table('qq3479015851_user')->where(array('id' => $user['id']))->save(array('paypassword' => $password)); if (!($rs === false)) { $mo->execute('commit'); //$mo->execute('unlock tables'); session('findpaypwdmoble',null); session('findpaypwdemail',null); $this->success('操作成功'); } else { $mo->execute('rollback'); $this->error('操作失败'); } } public function findpwdinfo() { if (empty(session('findpaypwdmoble')) && empty(session('findpaypwdemail'))) { redirect('/'); } session('findpaypwdmoble', ""); session('findpaypwdemail', ""); $this->display(); } public function findpaypwd() { if (IS_POST) { $input = I('post.'); if (!check($input['username'], 'username')) { $this->error('用户名格式错误!'); } $moble = $this->_replace_china_mobile($input['moble']); if (!check($moble, 'moble')) { $this->error('手机号码格式错误!'); } if (!check($input['moble_verify'], 'd')) { $this->error('短信验证码格式错误!'); } $this->_verify_count_check($input['moble_verify'],session('findpaypwd_verify')); $user = M('User')->where(array('username' => $input['username']))->find(); if (!$user) { $this->error('用户名不存在!'); } if ($user['moble'] != $moble) { $this->error('用户名或手机号码错误!'); } if (!check($input['password'], 'password')) { $this->error('新交易密码格式错误!'); } if ($input['password'] != $input['repassword']) { $this->error('确认交易密码错误!'); } $mo = M(); $mo->execute('set autocommit=0'); //$mo->execute('lock tables qq3479015851_user write , qq3479015851_user_log write '); $rs = array(); $rs[] = $mo->table('qq3479015851_user')->where(array('id' => $user['id']))->save(array('paypassword' => $input['password'])); if (check_arr($rs)) { $mo->execute('commit'); //$mo->execute('unlock tables'); session('findpaypwd_verify',null); $this->success('操作成功'); } else { $mo->execute('rollback'); $this->error('操作失败' . $mo->table('qq3479015851_user')->getLastSql()); } } else { $this->display(); } } } ?> <file_sep><?php namespace Org\Util; class EthPayLocal extends EthCommon { function __construct($host, $port = "80", $version, $caiwu) { $this->host = $host; $this->port = $port; $this->version = $version; $this->caiwu = $caiwu; } /** * 获得以太坊账号以太坊的余额 * @author qiuphp2 * @since 2017-9-21 * @return float|int 返回eth数量 10进制 */ function eth_getBalance($account) { //echo 11;exit(); //$account = $_REQUEST['account'];//获得账号公钥 $params = [ $account, "latest" ]; $data = $this->request(__FUNCTION__, $params); if (empty($data['error']) && !empty($data['result'])) { return $this->fromWei($data['result']);//返回eth数量,自己做四舍五入处理 } else { return $data['error']['message']; } } function eth_ercGetBalance($account, $contract) { $data_base = "0x70a08231";//70a08231 $to_data = substr($account, 2); $data_base .= "000000000000000000000000" . $to_data; $dst = array('to' => $contract, 'data' => $data_base); $params = array( $dst, "latest" ); $data = $this->request("eth_call", $params); if (empty($data['error']) && !empty($data['result'])) { return $data['result'];//返回eth数量,自己做四舍五入处理 } else { return $data['error']['message']; } } function eth_ercDoTransaction($zhuan) { $from = $zhuan['fromaddress']; $to = $zhuan['toaddress']; $heyue = $zhuan['token'];//合约地址 $password = COIN_KEY;//解锁密码 //$value = "0x9184e72a"; $value = $this->toWei($zhuan['amount']); if ($zhuan['type'] == "esm" || $zhuan['type'] == "wicc") { $value = $this->toWei3($zhuan['amount']); } if ($zhuan['type'] == "esm1") { $value = '0x'.base_convert($zhuan['amount'], 10, 16); } //$gas = $this->eth_estimateGas($from, $heyue, $value);//16进制 消耗的gas 0x5209 //$gas = base_convert("50000", 10, 16); //$gas = "0x" . $gas; //echo $gas;die(); //$gasPrice = $this->eth_gasPrice();//价格 0x430e23400 $status = $this->personal_unlockAccount($from, $password);//解锁 if (!$status) { return '解锁失败'; } $data_base = "0xa9059cbb";//70a08231 $to_data = substr($to, 2); $data_base .= "000000000000000000000000" . $to_data; $value_data = substr($value, 2); $v = str_pad($value_data, 64, 0, STR_PAD_LEFT); //echo $v; //die(); $data_base .= $v; $params = array( "from" => $from, "to" => $heyue, "data" => $data_base, ); $data = $this->request("eth_sendTransaction", [$params]); return json_encode($data); } function eth_accounts() { $params = []; $data = $this->request(__FUNCTION__, $params); if (empty($data['error']) && !empty($data['result'])) { return $data['result'];//返回eth数量,自己做四舍五入处理 } else { return $data['error']['message']; } } /** * 转账以太坊 coinpay * @author qiuphp2 * @since 2017-9-15 */ function eth_sendTransaction($array) { $from = $array["fromaddress"]; $to = $array["toaddress"]; $value = $this->toWei($array["amount"]); //如果不是16进制 转化为16进制 //$gas = $this->eth_estimateGas($from, $to, $value);//16进制 消耗的gas 0x5209 //$gas = "0xea60";//16进制 消耗的gas 0x5209 //$gasPrice = $this->eth_gasPrice();//价格 0x430e23400 //$password = $data["<PASSWORD>_id"];//解锁密码 $password = COIN_KEY;//解锁密码 $status = $this->personal_unlockAccount($from, $password);//解锁 if (!$status) { //@SaveLog('EthPayLocal', "personal_unlockAccount_解锁失败", _FUNCTION__); //return "personal_unlockAccount_解锁失败"; $data['error']['message'] = "personal_unlockAccount_解锁失败"; return json_encode($data); return false; } $params = array( "from" => $from, "to" => $to, //"gas" => $gas,//$gas,//2100 //"gasPrice " => $gasPrice,//18000000000 "value" => $value,//2441406250 //"data" => "", ); $data = $this->request(__FUNCTION__, [$params]); return json_encode($data); //@SaveLog('EthPayLocal', "eth_sendTransaction_" . json_encode($data), _FUNCTION__); //var_dump($data); if (empty($data['error']) && !empty($data['result'])) { //echo "eth_success_" . $data['result']; // @SaveLog('EthPayLocal', "eth_success_" . $data['result'], _FUNCTION__); // return $data['result'];//转账之后,生成HASH return $data['result']; } else { return json_encode($data); //@SaveLog('EthPayLocal', "eth_error_" . $data['error']['message'], _FUNCTION__); return false; //return $data['error']['message']; } //0x536135ef85aa8015b086e77ab8c47b8d40a3d00a975a5b0cc93b2a6345f538cd } /** * 定时任务查询是否有入账的以太坊 coinpay */ public function EthInCrontab($oldnum = 0) { $ucinsert = $params = array(); $n = $this->request("eth_blockNumber", $params); $number = $n['result']; $nums = base_convert($number, 16, 10); $isk = 1; $ucinsert = array(); $ps = 5; if ($oldnum > 0 && $nums > 0) { $ps = $nums - $oldnum; if ($ps > 6) { $ps = 6; $nums = $oldnum + 5; } else { $ps = 5; } } //$nums = 5353843; for ($i = 1; $i < $ps; $i++) { //echo $nums - $i ."<br>"; $np = '0x' . base_convert($nums - $i, 10, 16); $params = array( $np, true ); $data = $this->request("eth_getBlockByNumber", $params); if (isset($data["result"]) && isset($data["result"]["transactions"])) { foreach ($data["result"]["transactions"] as $k => $t) { $bs = base_convert($t["value"], 16, 10); $b = $this->fromWei2($bs); $ucinsert[$isk]["number"] = $b; $ucinsert[$isk]["hash"] = $t["hash"]; $ucinsert[$isk]["from"] = $t["from"]; $ucinsert[$isk]["to"] = $t["to"]; $ucinsert[$isk]["input"] = $t["input"]; $isk++; } } else { continue; } } $ucinsert[0]["block"] = $nums; $ucinsert[0]["num"] = $ps; return $ucinsert; } public function EthInCrontab_back() { $params = array(); $n = $this->request("eth_blockNumber", $params); $number = $n['result']; for ($i = 1; $i < 11; $i++) { $np = '0x' . base_convert($number - $i, 10, 16); $params = array( $np, true ); // @SaveLog('EthPay', "TotalNumber" . $number - $i, _FUNCTION__); $data = $this->request("eth_getBlockByNumber", $params); if (isset($data["result"]) && isset($data["result"]["transactions"])) { // $config = Config::get('database'); //$this->connection = Db::connect($config['AccessData']); foreach ($data["result"]["transactions"] as $k => $t) { //$uc = $this->connection->table('user_coin')->where('tx', $t["hash"])->find(); echo $t["to"] . "<br>"; if (isset($uc["id"])) { continue; } else { // $tc = $this->connection->table('user_token')->where('token_account', $t["to"])->find(); if (isset($tc["user_id"])) { //@SaveLog('EthPayLocal', "Number" . $number - $i, _FUNCTION__); // @SaveLog('EthPayLocal', "EthInCrontab" . json_encode($data["result"]["transactions"][$k]), _FUNCTION__); $b = base_convert($t["value"], 16, 10); $b = $this->fromWei2($b); //$mod = new \app\model\Common(); //$mod::startTrans(); // try { //$this->connection->table("user_token")->where('id', $tc["id"])->setInc("token_balance", $b); //插入 $ucinsert["user_id"] = $tc["user_id"]; $ucinsert["number"] = $b; $ucinsert["tx"] = $t["hash"]; $ucinsert["token_out"] = $t["from"]; $ucinsert["status"] = 2; $ucinsert["operate_id"] = 1; $ucinsert["income"] = 1; $ucinsert["token_type"] = 2; $ucinsert["time"] = time(); $ucinsert["ip"] = $_SERVER["SERVER_ADDR"]; //$this->connection->table("user_coin")->insert($ucinsert); // } catch (\Exception $e) { // 回滚事务 //$mod::rollback(); // } //echo $this->connection->table("user_token")->getLastSql(); } else { continue; } } } } else { continue; } } return true; } /** * 定时任务查询是否有入账的以太坊 coinpay */ public function EthInCrontabNumber($number) { $np = '0x' . base_convert($number, 10, 16); $params = array( $np, true ); $data = $this->request("eth_getBlockByNumber", $params); if (isset($data["result"]) && isset($data["result"]["transactions"])) { $config = Config::get('database'); $this->connection = Db::connect($config['AccessData']); foreach ($data["result"]["transactions"] as $k => $t) { $uc = $this->connection->table('user_coin')->where('tx', $t["hash"])->find(); if (isset($uc["id"])) { continue; } else { $tc = $this->connection->table('user_token')->where('token_account', $t["to"])->find(); if (isset($tc["user_id"])) { @SaveLog('EthPay', "Number" . $number, _FUNCTION__); @SaveLog('EthPay', "EthInCrontabNumber" . json_encode($data["result"]["transactions"][$k]), _FUNCTION__); $b = base_convert($t["value"], 16, 10); $b = $this->fromWei2($b); $mod = new \app\model\Common(); $mod::startTrans(); try { $this->connection->table("user_token")->where('id', $tc["id"])->setInc("token_balance", $b); //插入 $ucinsert["user_id"] = $tc["user_id"]; $ucinsert["number"] = $b; $ucinsert["tx"] = $t["hash"]; $ucinsert["token_out"] = $t["from"]; $ucinsert["status"] = 2; $ucinsert["operate_id"] = 1; $ucinsert["income"] = 1; $ucinsert["token_type"] = 2; $ucinsert["time"] = time(); $ucinsert["ip"] = $_SERVER["SERVER_ADDR"]; $this->connection->table("user_coin")->insert($ucinsert); // 提交事务 $mod::commit(); } catch (\Exception $e) { // 回滚事务 $mod::rollback(); } //echo $this->connection->table("user_token")->getLastSql(); } else { continue; } } } } return true; } /** * 转账以太坊ERC20代币 coinpay * @author qiuphp2 * @since 2017-9-15 */ function eth_sendContactTransaction($array) { $from = $this->caiwu; //财务账号出账 $heyue = $array["contact"];//合约地址 //$value = "0x9184e72a"; //$value = "0x" . base_convert("5000000000000000000", 10, 16); $value = $this->toWei($array["amount"]); //如果不是16进制 转化为16进制 // if (!ctype_xdigit($value)) { // $value = $this->toWei($value); // } //$gas = $this->eth_estimateGas($from, $heyue, $value);//16进制 消耗的gas 0x5209 $gas = base_convert("50000", 10, 16); $gas = "0x" . $gas; //echo $gas;die(); $gasPrice = $this->eth_gasPrice();//价格 0x430e23400 $password = $array["user_id"];//解锁密码 $status = $this->personal_unlockAccount($from, $password);//解锁 if (!$status) { return '解锁失败'; } //参数组装 //"dd62ed3e": "allowance(address,address)", // "095ea7b3": "approve(address,uint256)", // "cae9ca51": "approveAndCall(address,uint256,bytes)", // "70a08231": "balanceOf(address)", // "42966c68": "burn(uint256)", // "79cc6790": "burnFrom(address,uint256)", // "313ce567": "decimals()", // "06fdde03": "name()", // "95d89b41": "symbol()", // "18160ddd": "totalSupply()", // "a9059cbb": "transfer(address,uint256)", // "23b872dd": "transferFrom(address,address,uint256)" $data_base = "0xa9059cbb";//70a08231 $to = $array["toaddress"];//转出地址 $to_data = substr($to, 2); $data_base .= "000000000000000000000000" . $to_data; $value_data = substr($value, 2); $v = str_pad($value_data, 64, 0, STR_PAD_LEFT); //echo $v; //die(); $data_base .= $v; $params = array( "from" => $from, "to" => $heyue, //"gas" => $gas,//$gas,//2100 //"gasPrice " => $gasPrice,//18000000000 //"value" => $value,//2441406250 "data" => $data_base, ); @SaveLog('EthPayLocal', "eth_sendContactTransaction_" . json_decode($params), _FUNCTION__); $data = $this->request("params", [$params]); if (empty($data['error']) && !empty($data['result'])) { @SaveLog('EthPayLocal', 'Success_' . $data['result'], __FUNCTION__); return $data['result'];//转账之后,生成HASH } else { @SaveLog('EthPayLocal', 'ContactTransaction_' . $data['error']['message'], __FUNCTION__); return false; //return $data['error']['message']; } //0x536135ef85aa8015b086e77ab8c47b8d40a3d00a975a5b0cc93b2a6345f538cd } /** * 转账以太坊ERC20代币 测试代码 * @author qiuphp2 * @since 2017-9-15 */ function eth_ercsendTransaction($zhuan) { $from = $this->caiwu;//转出地址0.000000000000001014 $to = $zhuan['toaddress']; $heyue = $zhuan['token'];//合约地址 $password = COIN_KEY;//解锁密码 //$value = "0x9184e72a"; $value = $this->toWei($zhuan['amount']); if ($zhuan['type'] == "btm" || $zhuan['type'] == "esm" || $zhuan['type'] == "wicc") { $value = $this->toWei3($zhuan['amount']); } //$gas = $this->eth_estimateGas($from, $heyue, $value);//16进制 消耗的gas 0x5209 $gas = base_convert("50000", 10, 16); $gas = "0x" . $gas; //echo $gas;die(); $gasPrice = $this->eth_gasPrice();//价格 0x430e23400 $status = $this->personal_unlockAccount($from, $password);//解锁 if (!$status) { return '解锁失败'; } $data_base = "0xa9059cbb";//70a08231 $to_data = substr($to, 2); $data_base .= "000000000000000000000000" . $to_data; $value_data = substr($value, 2); $v = str_pad($value_data, 64, 0, STR_PAD_LEFT); //echo $v; //die(); $data_base .= $v; $params = array( "from" => $from, "to" => $heyue, //"gas" => $gas,//$gas,//2100 //"gasPrice " => $gasPrice,//18000000000 //"value" => $value,//2441406250 "data" => $data_base, ); $data = $this->request("eth_sendTransaction", [$params]); return json_encode($data); if (empty($data['error']) && !empty($data['result'])) { return $data;//转账之后,生成HASH } else { return $data['error']['message']; } //0x536135ef85aa8015b086e77ab8c47b8d40a3d00a975a5b0cc93b2a6345f538cd } //以太坊合约查询操作 function eth_call() { $from = "0x64fcc62e4d2e7d09907b10ad5ed76c8503363e8a";//转出地址 $to = "0x4c4d11f7ec61d0cff19a80bb513695bf12177398";//合约地址 //参数组装 //"dd62ed3e": "allowance(address,address)", // "095ea7b3": "approve(address,uint256)", // "cae9ca51": "approveAndCall(address,uint256,bytes)", // "70a08231": "balanceOf(address)", // "42966c68": "burn(uint256)", // "79cc6790": "burnFrom(address,uint256)", // "313ce567": "decimals()", // "06fdde03": "name()", // "95d89b41": "symbol()", // "18160ddd": "totalSupply()", // "a9059cbb": "transfer(address,uint256)", // "23b872dd": "transferFrom(address,address,uint256)" $data_base = "0x70a08231";//70a08231 $from_data = substr($from, 2); //echo $from_data;die(); $data_base .= "000000000000000000000000" . $from_data; $params = array( "from" => $from, "to" => $to, "data" => $data_base, ); $data = $this->request("eth_call", [$params, "latest"]); //var_dump($data); if (empty($data['error']) && !empty($data['result'])) { return $data['result'];//转账之后,生成HASH } else { return $data['error']['message']; } } /**根据转账hash获得转账详情 * 转账详细信息 * @author qiuphp2 * @since 2017-9-20 */ function eth_getTransactionReceipt($transactionHash) { //交易hash $params = array( $transactionHash, ); $data = $this->request(__FUNCTION__, $params); if (empty($data['error'])) { if (count($data['result']) == 0) { echo '等待确认'; } else { if ($data['result']['status'] = "0x1") { return $data['result']['blockHash'];//转账成功 } else { return "转账失败"; } //return $data['result'];//转账成功了 } } else { return $data['error']['message']; } } /** 需要 * 新建账号 有点耗时 最好给用户生成的之后,密码保存在数据库里面 * @author qiuphp2 * @since 2017-9-19 */ function personal_newAccount($password) { //$password = "123";//密码 $params = array( $password, ); $data = $this->request(__FUNCTION__, $params); //return json_encode($data); if (empty($data['error']) && !empty($data['result'])) { //@SaveLog('EthPay', "account" . $data['result'], "personal_newAccount"); return $data['result'];//新生成的账号公钥 } else { //@SaveLog('EthPay', "password" . $password, "personal_newAccount"); return false; } } /** * 获得消耗多少GAS * @author qiuphp2 * @since 2017-9-15 */ function eth_estimateGas($from, $to, $value) { $params = array( "from" => $from, "to" => $to, "value" => $value ); //echo "$value".$value;die(); $data = $this->request(__FUNCTION__, [$params]); //var_dump($data);die(); return $data['result']; } /** * 获得当前GAS价格 * @author qiuphp2 * @since 2017-9-15 */ function eth_gasPrice() { $params = array(); $data = $this->request(__FUNCTION__, $params); return $data['result']; } /**需要 * 解锁账号 此函数可能比较耗时 * @author qiuphp2 * @since 2017-9-15 */ function personal_unlockAccount($account, $password) { $params = array( $account, $password, 100, ); $data = $this->request(__FUNCTION__, $params); if (!empty($data['error'])) { return $data['error']['message'];//解锁失败 } else { return $data['result'];//成功返回true } } function eth_getTransactionCount() { $params = array( "0x8d7c0440e01f4840aeafe4a9039b41e00f4157af", "latest" ); $data = $this->request(__FUNCTION__, $params); var_dump($data); die(); if (!empty($data['error'])) { return $data['error']['message'];//解锁失败 } else { return $data['result'];//成功返回true } } function eth_getBlockByNumber() { $number = '0x' . base_convert('4569782', 10, 16); echo $number; $params = array( $number, // 436 true ); $data = $this->request(__FUNCTION__, $params); var_dump($data); var_dump($data["result"]["transactions"]["0"]); die(); if (!empty($data['error'])) { return $data['error']['message'];//解锁失败 } else { return $data['result'];//成功返回true } } } <file_sep><?php return array( 'V_HEADER_LANGUAGE'=>'cn', 'V_HEADER_LANGUAGE_TXT'=>'中文', 'V_ALL_BANK_CARD'=>'银行卡', 'V_ALL_WECHAT'=>'微信', 'V_ALL_ALIPAY'=>'支付宝', 'V_ALL_USERNAME'=>'姓名', 'V_ALL_PASSWORD'=>'密码', 'V_ALL_PASSWORD_PAY'=>'交易密码', 'V_ALL_PASSWORD_FORGET'=>'忘记密码', 'V_ALL_QR_CODE'=>'二维码', 'V_ALL_SAVE'=>'保存', 'V_ALL_COPY'=>'复制', 'V_ALL_MORE'=>'更多..', 'WELCOME'=>'欢迎来到笔加索', 'V_HEADER_SKIN'=>'皮肤', 'V_HEADER_FIRSTPAGE'=>'首页', 'V_HEADER_EXCHANGE'=>'币币交易', 'V_HEADER_C2C'=>'C2C交易', 'V_HEADER_USERCENTER'=>'用户中心', 'V_HEADER_TOKEN_APPLY'=>'上币申请', 'V_HEADER_ARTICLE'=>'资讯中心', 'V_HEADER_EXIT'=>'退出', 'V_HEADER_DISCOUNT'=>'当前交易费折扣:', 'V_HEADER_BALANCE'=>'可用余额:', 'V_HEADER_COMMISSION_FREEZE'=>'委托冻结:', 'V_HEADER_REGISTER'=>'注册', 'V_HEADER_LOGIN'=>'登录', 'V_HEADER_LEVEL'=>'当前等级:', 'V_ARTICLE_UPDATE_TIME'=>'更新时间:', 'V_ARTICLE_READ_COUNT'=>'阅读:', 'V_ARTICLE_HOT'=>'热门文章', 'V_ARTICLE_SHARE'=>'快来分享到:', 'V_SHARE_APP_CENTER'=>'应用中心', 'V_SHARE_SHARE_CENTER'=>'分红中心', 'V_SHARE_TIP'=>'分红中心', 'V_SHARE_WARN'=>'温馨提示', 'V_SHARE_COIN_TYPE'=>'币种', 'V_SHARE_ALL_COIN'=>'全站总额', 'V_SHARE_MY_COIN'=>'我的资产', 'V_SHARE_MY_COIN_PROPORTION'=>'持有比例', 'V_INDEX_CNYT'=>'对CNYT交易区', 'V_INDEX_USDT'=>'对USDT交易区', 'V_INDEX_BTC'=>'对BTC交易区', 'V_INDEX_ETH'=>'对ETH交易区', 'V_INDEX_TIME_LIMIT'=>'限时交易区', 'V_INDEX_USER'=>'对USDT交易区', 'V_INDEX_COIN_STAR'=>'我的自选区', 'V_INDEX_COIN_SEARCH'=>'搜索CNYT交易区', 'V_INDEX_COIN_PAIR'=>'币种对', 'V_INDEX_COIN_PRICE'=>'价格', 'V_INDEX_COIN_24_COUNT'=>'24小时交易量', 'V_INDEX_COIN_24_COIN'=>'24小时交易量', 'V_INDEX_UPSDOWNS'=>'日涨跌', 'V_INDEX_UPSDOWNS_3DAY'=>'价格趋势(3日)', 'V_INDEX_MAIN_AREA'=>'主区', 'V_INDEX_MAIN_AREA_INTRODUCE'=>'主区介绍', 'V_INDEX_TRANSACTION'=>'交易', 'V_INDEX_K_LINE'=>'K线', 'V_INDEX_NEW_AREA'=>'创新区', 'V_INDEX_NEW_AREA_INTRODUCE'=>'创新区介绍', 'V_INDEX_EXPERIMENT_AREA'=>'实验区', 'V_INDEX_EXPERIMENT_AREA_INTRODUCE'=>'实验区介绍', 'V_INDEX_NEW_MESSAGE'=>'最新动态', 'V_INDEX_TEAM_INFO'=>'<ul class="bjs-features-list clearfix"> <li class="feature-1"> <div></div> <h3>全托管</h3> <h4>笔加索为您提供全方位的托管服务<br/>让您省心便捷</h4> <p>-</p> </li> <li class="feature-2"> <div></div> <h3>有保障</h3> <h4>笔加索拥有非常资深的技术实力团队<br/>保障您的各项需求</h4> <p>-</p> </li> <li class="feature-3"> <div></div> <h3>更放心</h3> <h4>您的每一笔交易,都会有笔加索全程护驾<br/>让您交易更放心</h4> <p>-</p> </li> </ul>', 'V_FINANCE_BANK_PAY_SET'=>'支付设置', 'V_FINANCE_BANK_PAY_TYPE'=>'支付方式', 'V_FINANCE_BANK_OPEN'=>'开户银行', 'V_FINANCE_BANK_OPEN_DETAIL'=>'开户支行', 'V_FINANCE_BANK_OPEN_DETAIL_INPUT'=>'输入开户支行', 'V_FINANCE_BANK_BANK_NO'=>'银行卡账号', 'V_FINANCE_BANK_BANK_INPUT'=>'输入银行卡账号', 'V_FINANCE_BANK_PAYPASS_INPUT'=>'输入交易密码', 'V_FINANCE_BANK_BIND'=>'绑定', 'V_FINANCE_BANK_WECHAT_INPUT'=>'输入微信账号', 'V_FINANCE_BANK_WECHAT_PAY'=>'微信支付', 'V_FINANCE_BANK_WECHAT_IMG_PROMPT'=>'请上传您的微信收款二维码图片', 'V_FINANCE_BANK_ALI_INPUT'=>'输入支付宝账号', 'V_FINANCE_BANK_ALI_PAY'=>'支付宝支付', 'V_FINANCE_BANK_ALI_IMG_PROMPT'=>'请上传您的支付宝收款二维码图片', 'V_FINANCE_INTRODUCE_EXPERIMENT_TITLE'=>'试验区-区块链资产交易分区说明', 'V_FINANCE_INTRODUCE_EXPERIMENT_INFO'=>'实验区交易品种属于面世3个月内品种,流动性极小,回报较大同时风险也最大的区块链资产。这类资产属于项目早期阶段,不确定因数较多,上线交易所数量少于5家,风险极大,短期回报也可能较高,适合激进型投资者。每月交易额度低于100万CNYT,则停止交易进入观察阶段。', 'V_FINANCE_INTRODUCE_EXPERIMENT_SUB_TITLE1'=>'交易品种', 'V_FINANCE_INTRODUCE_EXPERIMENT_SUB_INFO1'=>'全球流动性极小', 'V_FINANCE_INTRODUCE_EXPERIMENT_SUB_INFO2'=>'价格波动剧烈,回报较大风险极高的区块链资产。', 'V_FINANCE_INTRODUCE_EXPERIMENT_SUB_TITLE2'=>'计价方式', 'V_FINANCE_INTRODUCE_EXPERIMENT_SUB_INFO3'=>'试验区的交易品种', 'V_FINANCE_INTRODUCE_EXPERIMENT_SUB_INFO4'=>'我们目前会使用CNYT和BTC来计价。', 'V_FINANCE_INTRODUCE_EXPERIMENT_TITLE2'=>'笔加索交易平台试验区风险提示', 'V_FINANCE_INTRODUCE_EXPERIMENT_INFO2'=>'投资于试验区区块链资产的投资者,需要了解笔加索《用户协议》中提示的各类风险,充分认识到试验区数字货币的投资风险,审慎作出投资决策,并自行承担由上述风险而带来的责任和损失。笔加索为保护广大投资者的利益,对区块链资产交易进行了品种始终保持开放而谨慎的态度。不同的区块链资产,会有不同的交易风险,合适不同的交易人群。我们在大量积累的评估数据基础上,会对在笔加索上交易的资产进行分区,以提示投资者不同资产的交易风险和交易性质。', 'V_FINANCE_INTRODUCE_MAIN_TITLE'=>'主区-区块链资产交易分区说明', 'V_FINANCE_INTRODUCE_MAIN_INFO'=>'主区经过市场充分验证和认可,全球流动性较好、风险较小的主流区块链资产。这类资产,一般面世6个月以上,国际国内主流交易平台有不错的表现,交易量大,流通性好,一般长线持有、收益稳定,适合稳健型投资者。', 'V_FINANCE_INTRODUCE_MAIN_SUB_TITLE1'=>'交易品种', 'V_FINANCE_INTRODUCE_MAIN_SUB_INFO1'=>'经过市场充分验证和认可', 'V_FINANCE_INTRODUCE_MAIN_SUB_INFO2'=>'全球流动性较好、风险较小的主流区块链资产。', 'V_FINANCE_INTRODUCE_MAIN_SUB_TITLE2'=>'计价方式', 'V_FINANCE_INTRODUCE_MAIN_SUB_INFO3'=>'主区的交易品种', 'V_FINANCE_INTRODUCE_MAIN_SUB_INFO4'=>'我们目前会使用CNYT和BTC来计价。', 'V_FINANCE_INTRODUCE_MAIN_TITLE2'=>'笔加索交易平台主区风险提示', 'V_FINANCE_INTRODUCE_MAIN_INFO2'=>'投资于主区区块链资产的投资者,需要了解笔加索《用户协议》中提示的各类风险,充分认识到主区数字货币的投资风险,审慎作出投资决策,并自行承担由上述风险而带来的责任和损失。笔加索为保护广大投资者的利益,对区块链资产交易进行了品种始终保持开放而谨慎的态度。不同的区块链资产,会有不同的交易风险,合适不同的交易人群。我们在大量积累的评估数据基础上,会对在笔加索上交易的资产进行分区,以提示投资者不同资产的交易风险和交易性质。', 'V_FINANCE_INTRODUCE_NEW_TITLE'=>'创新区-区块链资产交易分区说明', 'V_FINANCE_INTRODUCE_NEW_INFO'=>'创新区交易品种为新型产品,全球流动性较小,价格波动较大,风险较大的区块链资产。这类资产,一般面世3个月以上,已经上线至少5家有一定实力的交易平台,有一定的升值空间,风险比主区大,适合智慧型投资者。每月交易额度低于150万CNYT,则停止交易进入观察阶段。', 'V_FINANCE_INTRODUCE_NEW_SUB_TITLE1'=>'交易品种', 'V_FINANCE_INTRODUCE_NEW_SUB_INFO1'=>'全球流动性较小', 'V_FINANCE_INTRODUCE_NEW_SUB_INFO2'=>'价格波动较大,风险相对较高的区块链资产。', 'V_FINANCE_INTRODUCE_NEW_SUB_TITLE2'=>'计价方式', 'V_FINANCE_INTRODUCE_NEW_SUB_INFO3'=>'创新区的交易品种', 'V_FINANCE_INTRODUCE_NEW_SUB_INFO4'=>'我们目前会使用CNYT和BTC来计价。', 'V_FINANCE_INTRODUCE_NEW_TITLE2'=>'笔加索交易平台创新区风险提示', 'V_FINANCE_INTRODUCE_NEW_INFO2'=>'投资于创新区区块链资产的投资者,需要了解笔加索《用户协议》中提示的各类风险,充分认识到创新区数字货币的投资风险,审慎作出投资决策,并自行承担由上述风险而带来的责任和损失。笔加索为保护广大投资者的利益,对区块链资产交易进行了品种始终保持开放而谨慎的态度。不同的区块链资产,会有不同的交易风险,合适不同的交易人群。我们在大量积累的评估数据基础上,会对在笔加索上交易的资产进行分区,以提示投资者不同资产的交易风险和交易性质。', 'V_FINANCE_MYCZ_CNYT'=>'CNYT/人民币', 'V_FINANCE_MYCZ_USDT'=>'CNYT/人民币', 'V_FINANCE_MYCZ_BTC'=>'CNYT/人民币', 'V_FINANCE_MYCZ_ETH'=>'CNYT/人民币', 'V_FINANCE_MYCZ_BUY_CNYT'=>'买入CNYT', 'V_FINANCE_MYCZ_BUY_BALANCE'=>'CNYT余额', 'V_FINANCE_MYCZ_BUY_PRICE'=>'买入估价 CNY', 'V_FINANCE_MYCZ_BUY_NUM'=>'买入量CNYT', 'V_FINANCE_MYCZ_BUY_AMOUNT'=>'金额CNY', 'V_FINANCE_MYCZ_BUY_PAY_TYPE'=>'支付方式', 'V_FINANCE_MYCZ_BUY_PAY_SELF'=>'必须本人支付', 'V_FINANCE_MYCZ_BUY_COMMIT'=>'买入(CNY-CNYT)', 'V_FINANCE_MYCZ_SELL_CNY'=>'卖出CNY', 'V_FINANCE_MYCZ_SELL_PRICE'=>'卖出估价 CNY', 'V_FINANCE_MYCZ_SELL_NUM'=>'卖出量CNYT', 'V_FINANCE_MYCZ_SELL_COMMIT'=>'卖出(CNY-CNYT)', 'V_FINANCE_MYCZ_USER_BILL'=>'我的订单', 'V_FINANCE_MYCZ_BILL_ID'=>'订单ID', 'V_FINANCE_MYCZ_BILL_TYPE'=>'类型', 'V_FINANCE_MYCZ_BILL_NUM'=>'数量', 'V_FINANCE_MYCZ_BILL_AMOUNT'=>'转账金额', 'V_FINANCE_MYCZ_BILL_CREATETIME'=>'建立时间', 'V_FINANCE_MYCZ_BILL_STATUS'=>'状态', 'V_FINANCE_MYCZ_BILL_PAY_WAIT'=>'未付款', 'V_FINANCE_MYCZ_BILL_PAY_COMPLETE'=>'我已付款', 'V_FINANCE_MYCZ_BILL_SELLER_WAIT'=>'待卖家确认', 'V_FINANCE_MYCZ_BILL_SELLER_COMPLETE'=>'我已收款', 'V_FINANCE_MYCZ_BILL_PAY_OVER'=>'已付款', 'V_FINANCE_MYCZ_BILL_TRADE_SUCCESS'=>'交易成功', 'V_FINANCE_MYCZ_BILL_TRADE_CHANCEL'=>'交易取消', 'V_FINANCE_MYCZ_BILL_CHANCEL'=>'取消', 'V_FINANCE_MYCZ_BILL_CHOOSE_PAY_TYPE'=>'请选择以下方式给卖家付款', 'V_FINANCE_MYCZ_BILL_SELLERNAME'=>'卖家姓名:', 'V_FINANCE_MYCZ_BILL_ALIACCOUNT'=>'支付宝账号:', 'V_FINANCE_MYCZ_PAY_AMOUNT'=>'付款金额:', 'V_FINANCE_MYCZ_BILL_BANKPAY'=>'银行卡转账:', 'V_FINANCE_MYCZ_BILL_CONTACT'=>'联系方式:', 'V_FINANCE_MYCZ_BILL_ID2'=>'订单ID:', 'V_FINANCE_MYCZ_BILL_WECHATACCOUNT'=>'微信账号:', 'V_FINANCE_MYCZ_BANK_NAME'=>'银行名:', 'V_FINANCE_MYCZ_BANK_NO'=>'银行卡号:', 'V_FINANCE_MYCZ_CHECK_SELLER_INFO'=>'请及时核对卖家信息是否一致', 'V_FINANCE_MYCZ_SELLER_QR'=>'卖家收款码', 'V_FINANCE_MYCZ_REMARK'=>'备注:', 'V_FINANCE_MYCZ_ORDER_CLOSE'=>'此订单已关闭', 'V_FINANCE_MYCZ_ORDER_TIP'=>'切勿再次给卖家付款。当前信息仅供浏览。', 'V_FINANCE_MYCZ_ORDER_WARN'=>'非自动扣款,请本人付款成功后点击“我已付款”,<span class="cb94e50">未付款并点击“我已付款”,经核实,将会暂停账号功能(转账时切勿备注“比特币”,“虚拟币”等信息,否则禁止C2C交易)</span>', 'V_FINANCE_MYCZ_ORDER_I_KNOW'=>'知道了', 'V_FINANCE_REWARD_MY'=>'我的奖励', 'V_FINANCE_REWARD_ACCUMULATION'=>'累计奖励', 'V_FINANCE_REWARD_SUCCESSOR_USER'=>'下家用户名', 'V_FINANCE_REWARD_TYPE'=>'奖励类型', 'V_FINANCE_REWARD_REMARK'=>'奖励说明', 'V_FINANCE_REWARD_OPERATION_TIME'=>'操作时间', 'V_FINANCE_REWARD_OPERATION_COUNT'=>'操作数量', 'V_FINANCE_REWARD_COUNT'=>'奖励数量', 'V_FINANCE_REWARD_STATUS'=>'奖励状态', 'V_FINANCE_REWARD_STATUS_NOT_ARRIVAL'=>'未到账', 'V_FINANCE_REWARD_STATUS_ARRIVAL'=>'已到账', 'V_FINANCE_RECOMMENDATION_MY_DECO'=>'我的推荐', 'V_FINANCE_RECOMMENDATION_SUCCESSOR_TYPE'=>'下家类型', 'V_FINANCE_RECOMMENDATION_SUCCESSOR_NAME'=>'用户名', 'V_FINANCE_RECOMMENDATION_REGISTER_TIME'=>'注册时间', 'V_FINANCE_RECOMMENDATION_IS_CERTIFICATION'=>'是否认证', 'V_FINANCE_RECOMMENDATION_INVITSS'=>'一级下家', 'V_FINANCE_RECOMMENDATION_INVITSS2'=>'二级下家', 'V_FINANCE_RECOMMENDATION_INVITSS3'=>'三级下家', 'V_FINANCE_RECOMMENDATION_AUTH_NO'=>'未认证', 'V_FINANCE_RECOMMENDATION_AUTH_ALREADY'=>'已认证', 'V_FINANCE_COMMISSION_TITLE'=>'我的挂单记录', 'V_FINANCE_COMMISSION_ALL'=>'全部', 'V_FINANCE_COMMISSION_TIME'=>'委托时间', 'V_FINANCE_COMMISSION_BUY'=>'买入', 'V_FINANCE_COMMISSION_SHELL'=>'卖出', 'V_FINANCE_COMMISSION_PRICE'=>'委托价格', 'V_FINANCE_COMMISSION_NUM'=>'委托数量', 'V_FINANCE_COMMISSION_NUM_COMPLETE'=>'已成交量', 'V_FINANCE_COMMISSION_TRAN'=>'交易中', 'V_FINANCE_COMMISSION_COMPLETE'=>'已完成', 'V_FINANCE_COMMISSION_CANCEL'=>'已撤销', 'V_FINANCE_COMMISSION_DO_CANCEL'=>'撤销', 'V_FINANCE_WITHDRAW'=>'提现', 'V_FINANCE_WITHDRAW_ADDRESS'=>'转出地址', 'V_FINANCE_WITHDRAW_ADDRESS_CHOOSE'=>'--选择提现地址--', 'V_FINANCE_WITHDRAW_ADDRESS_ADD'=>'新添加一个提现地址', 'V_FINANCE_WITHDRAW_NUM'=>'转出数量', 'V_FINANCE_CAN_USE_COUNT'=>'可用:', 'V_FINANCE_CAN_USE_QUOTA'=>'限额:200.00000000', 'V_FINANCE_OUT_NUM_FEE1'=>'转出手续费', 'V_FINANCE_OUT_NUM_FEE2'=>'个,最少转出', 'V_FINANCE_OUT_NUM_FEE3'=>'个', 'V_FINANCE_OUT_SMS_1'=>'短信验证码,', 'V_FINANCE_OUT_SMS_2'=>'(接收验证码)', 'V_FINANCE_OUT_SMS_TIP_INPUT'=>'请输入短信验证码', 'V_FINANCE_OUT_SMS_SEND'=>'发送短信验证码', 'V_FINANCE_OUT_PAY_PASSWORD_TIP_INPUT'=>'输入交易密码', 'V_FINANCE_OUT_PAY_PASSWORD_FORGET'=>'<PASSWORD>', 'V_FINANCE_OUT_COIN_OUT'=>'立即转出', 'V_FINANCE_OUT_TIPS_INFO1'=>'最小提币数量为:0.01 ', 'V_FINANCE_OUT_TIPS_INFO2'=>'为保障资金安全,当您账户安全策略变更、密码修改、使用新地址提币,我们会对提币进行人工审核,请耐心等待工作人员电话或邮件联系 ', 'V_FINANCE_OUT_TIPS_INFO3'=>'请务必确认电脑及浏览器安全,防止信息被篡改或泄露。', 'V_FINANCE_OUT_COIN_TITLE'=>'最近提币记录', 'V_FINANCE_OUT_LIST_TITLE1'=>'转出时间', 'V_FINANCE_OUT_LIST_TITLE2'=>'转出币种', 'V_FINANCE_OUT_LIST_TITLE3'=>'转出数量', 'V_FINANCE_OUT_LIST_TITLE4'=>'手续费', 'V_FINANCE_OUT_LIST_TITLE5'=>'到账数量', 'V_FINANCE_OUT_LIST_TITLE6'=>'状态', 'V_FINANCE_OUT_SUCCESS'=>'成功', 'V_FINANCE_OUT_CONFIRM'=>'等待处理,还需要', 'V_FINANCE_OUT_CONFIRM2'=>'个确认', 'V_FINANCE_MYZR_1'=>'转入', 'V_FINANCE_MYZR_2'=>'钱包名称', 'V_FINANCE_MYZR_2_2'=>'输入提币地址', 'V_FINANCE_MYZR_3'=>'钱包地址,转入即赠', 'V_FINANCE_MYZR_4'=>'温馨提示', 'V_FINANCE_MYZR_5'=>'为保障资金安全,当您账户安全策略变更、密码修改、使用新地址提币,我们会对提币进行人工审核,请耐心等待工作人员电话或邮件联系', 'V_FINANCE_MYZR_6'=>'请务必确认电脑及浏览器安全,防止信息被篡改或泄露。', 'V_FINANCE_MYZR_7'=>'最近转入记录', 'V_FINANCE_MYZR_8'=>'转入时间', 'V_FINANCE_MYZR_9'=>'转入币种', 'V_FINANCE_MYZR_10'=>'转入数量', 'V_FINANCE_MYZR_11'=>'转入赠送', 'V_FINANCE_MYZR_12'=>'到账数量', 'V_FINANCE_MYZR_13'=>'状态', 'V_FINANCE_MYZR_14'=>'转入成功', 'V_FINANCE_MYZR_15'=>'等待处理,还需要', 'V_FINANCE_MYZR_16'=>'个确认', 'V_FINANCE_MYZR_LIST_1'=>'最近充币记录', 'V_FINANCE_ZCDB_1'=>'资产对标', 'V_FINANCE_ZCDB_2'=>'锁仓币种:', 'V_FINANCE_ZCDB_3'=>'可用', 'V_FINANCE_ZCDB_4'=>'锁仓时长:', 'V_FINANCE_ZCDB_5'=>'天', 'V_FINANCE_ZCDB_6'=>'锁仓数量:', 'V_FINANCE_ZCDB_7'=>'确定', 'V_FINANCE_ZCDB_8'=>'对标说明', 'V_FINANCE_ZCDB_9'=>'为保障资金安全,当您账户安全策略变更、密码修改、使用新地址提币,我们会对提币进行人工审核,请耐心等待工作人员电话或邮件联系', 'V_FINANCE_ZCDB_10'=>'请务必确认电脑及浏览器安全,防止信息被篡改或泄露。', 'V_FINANCE_ZCDB_11'=>'锁仓记录', 'V_FINANCE_ZCDB_12'=>'对标币种', 'V_FINANCE_ZCDB_13'=>'对标数量', 'V_FINANCE_ZCDB_14'=>'对标时长', 'V_FINANCE_ZCDB_15'=>'对标收益', 'V_FINANCE_ZCDB_16'=>'开始时间', 'V_FINANCE_ZCDB_17'=>'结束时间', 'V_FINANCE_ZCDB_18'=>'状态', 'V_FINANCE_ZCDB_19'=>'操作', 'V_FINANCE_ZCDB_20'=>'申请结算', 'V_FINANCE_ZCDB_21'=>'您当前未开通资产对标,需要先开通才能操作。', 'V_FINANCE_ZCDB_22'=>'开通', 'V_FINDPWD_FINDPWD_1'=>'找回交易密码', 'V_FINDPWD_FINDPWD_2'=>'请选择验证方式', 'V_FINDPWD_FINDPWD_3'=>'请选择', 'V_FINDPWD_FINDPWD_4'=>'邮箱验证', 'V_FINDPWD_FINDPWD_5'=>'短信验证', 'V_FINDPWD_FINDPWD_6'=>'图形验证码', 'V_FINDPWD_FINDPWD_7'=>'换一张', 'V_FINDPWD_FINDPWD_8'=>'获取验证码', 'V_FINDPWD_FINDPWD_9'=>'请输入验证码', 'V_FINDPWD_FINDPWD_10'=>'发送验证码', 'V_FINDPWD_FINDPWD_11'=>'找回交易密码', 'V_FINDPWD_FINDPWDCONFIRM_1'=>'新交易密码', 'V_FINDPWD_FINDPWDCONFIRM_2'=>'请输入新交易密码', 'V_FINDPWD_FINDPWDCONFIRM_3'=>'确认交易密码', 'V_FINDPWD_FINDPWDCONFIRM_4'=>'请输入确认交易密码', 'V_FINDPWD_FINDPWDCONFIRM_5'=>'确认交易密码', 'V_FINDPWD_FINDPWDCONFIRM_6'=>'下一步', 'V_FINDPWD_FINDPWDINFO_1'=>'找回交易密码', 'V_FINDPWD_FINDPWDINFO_2'=>'恭喜您,找回交易密码成功!', 'V_LOGIN_FINDPAYPWD_1'=>'找回交易密码', 'V_LOGIN_FINDPAYPWD_2'=>'手机号码', 'V_LOGIN_FINDPAYPWD_3'=>'请输入手机号码', 'V_LOGIN_FINDPAYPWD_4'=>'图形验证码', 'V_LOGIN_FINDPAYPWD_5'=>'换一张', 'V_LOGIN_FINDPAYPWD_6'=>'发送短信验证码', 'V_LOGIN_FINDPAYPWD_7'=>'手机验证码', 'V_LOGIN_FINDPAYPWD_8'=>'请输入验证码', 'V_LOGIN_FINDPAYPWD_9'=>'获取验证码', 'V_LOGIN_FINDPAYPWD_10'=>'找回登录密码', 'V_LOGIN_FINDPAYPWD_11'=>'修改手机号码之后24小时内禁止提币!', 'V_LOGIN_FINDPWD_1'=>'重置登录密码', 'V_LOGIN_FINDPWD_2'=>'账号', 'V_LOGIN_FINDPWD_3'=>'请输入登录账号', 'V_LOGIN_FINDPWD_4'=>'获取验证码', 'V_LOGIN_FINDPWD_5'=>'换一张', 'V_LOGIN_FINDPWD_6'=>'输入图形验证码', 'V_LOGIN_FINDPWD_7'=>'获取验证码', 'V_LOGIN_FINDPWD_8'=>'验证码', 'V_LOGIN_FINDPWD_9'=>'输入验证码', 'V_LOGIN_FINDPWD_10'=>'提交', 'V_LOGIN_FINDPWD_11'=>'重置登录密码后24小时内禁止提币。', 'V_LOGIN_FINDPWDCONFIRM_1'=>'新密码', 'V_LOGIN_FINDPWDCONFIRM_2'=>'请输入新密码', 'V_LOGIN_FINDPWDCONFIRM_3'=>'确认密码', 'V_LOGIN_FINDPWDCONFIRM_4'=>'请输入确认新密码', 'V_LOGIN_FINDPWDCONFIRM_5'=>'下一步', 'V_LOGIN_FINDPWDCONFIRM_6'=>'重置登录密码后24小时内禁止提币。', 'V_LOGIN_FINDPWDINFO_1'=>'立即登录', 'V_LOGIN_FINDPWDINFO_2'=>'恭喜您,找回登录密码成功!', 'V_LOGIN_INDEX_1'=>'欢迎登录', 'V_LOGIN_INDEX_2'=>'账号', 'V_LOGIN_INDEX_3'=>'请输入登录账号', 'V_LOGIN_INDEX_4'=>'密码', 'V_LOGIN_INDEX_5'=>'请输入登录密码', 'V_LOGIN_INDEX_6'=>'验证码', 'V_LOGIN_INDEX_7'=>'输入验证码', 'V_LOGIN_INDEX_8'=>'换一张', 'V_LOGIN_INDEX_9'=>'登录', 'V_LOGIN_INDEX_10'=>'忘记密码', 'V_LOGIN_INDEX_11'=>'免费注册', 'V_LOGIN_INFO_1'=>'恭喜您,已经注册成功!', 'V_LOGIN_INFO_2'=>'邮箱:', 'V_LOGIN_INFO_3'=>'手机:', 'V_LOGIN_INFO_4'=>'您可以:', 'V_LOGIN_INFO_5'=>'去交易', 'V_LOGIN_INFO_6'=>'或者', 'V_LOGIN_INFO_7'=>'人民币充值', 'V_LOGIN_PAYPASSWORD_1'=>'用户名', 'V_LOGIN_PAYPASSWORD_2'=>'必须字母开头+数字格式', 'V_LOGIN_PAYPASSWORD_3'=>'邮箱', 'V_LOGIN_PAYPASSWORD_4'=>'必须字母开头+数字格式', 'V_LOGIN_PAYPASSWORD_5'=>'设置交易密码', 'V_LOGIN_PAYPASSWORD_6'=>'输入交易密码', 'V_LOGIN_PAYPASSWORD_7'=>'确认交易密码', 'V_LOGIN_PAYPASSWORD_8'=>'确认交易密码', 'V_LOGIN_PAYPASSWORD_9'=>'下一步', 'V_LOGIN_REGISTER_1'=>'欢迎注册', 'V_LOGIN_REGISTER_2'=>'手机注册', 'V_LOGIN_REGISTER_3'=>'邮箱注册', 'V_LOGIN_REGISTER_4'=>'手机号码', 'V_LOGIN_REGISTER_5'=>'请输入手机号码', 'V_LOGIN_REGISTER_6'=>'获取验证码', 'V_LOGIN_REGISTER_7'=>'换一张', 'V_LOGIN_REGISTER_8'=>'输入图形验证码', 'V_LOGIN_REGISTER_9'=>'获取验证码', 'V_LOGIN_REGISTER_10'=>'短信验证码', 'V_LOGIN_REGISTER_11'=>'请输入验证码', 'V_LOGIN_REGISTER_12'=>'登录密码', 'V_LOGIN_REGISTER_13'=>'请输入登录密码', 'V_LOGIN_REGISTER_14'=>'确认密码', 'V_LOGIN_REGISTER_15'=>'再次输入密码', 'V_LOGIN_REGISTER_16'=>'邀请码(选填)', 'V_LOGIN_REGISTER_17'=>'输入邀请码', 'V_LOGIN_REGISTER_18'=>'我已阅读并同意', 'V_LOGIN_REGISTER_19'=>'用户协议', 'V_LOGIN_REGISTER_20'=>'注册', 'V_LOGIN_REGISTER_21'=>'邮箱', 'V_LOGIN_REGISTER_22'=>'输入邮箱', 'V_LOGIN_REGISTER_23'=>'邮箱验证码', 'V_LOGIN_REGISTER_24'=>'国籍信息注册后不可修改,请务必如实选择。 验证邮箱可能会被误判为垃圾邮箱,请注意查收。 <br/> 请妥善保存您的bjs.bi账号已经登录密码。 请勿和其他网站使用相同的登录密码。', 'V_LOGIN_REGISTER2_1'=>'用户注册', 'V_LOGIN_REGISTER2_3'=>'实名认证', 'V_LOGIN_REGISTER2_5'=>'为保障您的资金安全,请设置交易密码,请务必牢记', 'V_LOGIN_REGISTER2_6'=>'交易密码:', 'V_LOGIN_REGISTER2_7'=>'请输入交易密码,不能与登录密码相同', 'V_LOGIN_REGISTER2_8'=>'重复交易密码:', 'V_LOGIN_REGISTER2_9'=>'重复输入交易密码,两次需要一致', 'V_LOGIN_REGISTER2_10'=>'下一步', 'V_LOGIN_REGISTER2_11'=>'<ul class="safety_tips_ul clear"> <li> <div class="safety_img safety_img_1"></div> <h4>系统可靠</h4> <p>银行级用户数据加密、动态身份验证,多级风险识别控制,保障交易安全</p> </li> <li> <div class="safety_img safety_img_2"></div> <h4>资金安全</h4> <p>钱包多层加密,离线存储于银行保险柜,资金第三方托管,确保安全</p> </li> <li> <div class="safety_img safety_img_3"></div> <h4>快捷方便</h4> <p>充值即时、提现迅速,每秒万单的高性能交易引擎,保证一切快捷方便</p> </li> <li> <div class="safety_img safety_img_4"></div> <h4>服务专业</h4> <p>专业的客服团队,400电话和24小时在线QQ,VIP一对一专业服务</p> </li> </ul>', 'V_LOGIN_REGISTER3_5'=>'根据 国家相关规定,请填写您的真实身份信息,完成实名认证', 'V_LOGIN_REGISTER3_6'=>'真实姓名:', 'V_LOGIN_REGISTER3_7'=>'真实姓名设置后不能修改,并且与提现账户名相同', 'V_LOGIN_REGISTER3_8'=>'身份证号:', 'V_LOGIN_REGISTER3_9'=>'真实姓名设置后不能修改,并且与提现账户名相同', 'V_LOGIN_REGISTER3_10'=>'下一步', 'V_LOGIN_REGISTER4_1'=>'恭喜您,已经注册成功!', 'V_LOGIN_REGISTER4_2'=>'用户名:', 'V_LOGIN_REGISTER4_3'=>'认证姓名:', 'V_LOGIN_REGISTER4_4'=>'证件号码:', 'V_LOGIN_REGISTER4_5'=>'去交易', 'V_LOGIN_REGISTER4_6'=>'您还可以:', 'V_LOGIN_REGISTER4_7'=>'绑定手机', 'V_LOGIN_REGISTER4_8'=>'充值', 'V_LOGIN_TRUENAME_1'=>'根据 国家相关规定,请填写您的真实身份信息', 'V_LOGIN_TRUENAME_2'=>'去认证', 'V_TASK_LIST_1'=>'发放类型', 'V_TASK_LIST_3'=>'发放时间', 'V_TASK_LIST_4'=>'来源', 'V_TRADE_INDEX_1'=>'限时', 'V_TRADE_INDEX_2'=>'自选', 'V_TRADE_INDEX_3'=>'当前:', 'V_TRADE_INDEX_4'=>'最高:', 'V_TRADE_INDEX_5'=>'最低:', 'V_TRADE_INDEX_6'=>'日额:', 'V_TRADE_INDEX_7'=>'日量:', 'V_TRADE_INDEX_8'=>'专业版', 'V_TRADE_INDEX_9'=>'介绍', 'V_TRADE_INDEX_10'=>'我的余额', 'V_TRADE_INDEX_11'=>'今日行情', 'V_TRADE_INDEX_12'=>'最大可买', 'V_TRADE_INDEX_13'=>'满仓(全买),设置买入数量为最大值', 'V_TRADE_INDEX_14'=>'最佳买价', 'V_TRADE_INDEX_15'=>'买入价格', 'V_TRADE_INDEX_16'=>'此出价为1个币的价格', 'V_TRADE_INDEX_17'=>'买入量', 'V_TRADE_INDEX_18'=>'买入比例:', 'V_TRADE_INDEX_19'=>'总价', 'V_TRADE_INDEX_20'=>'设置', 'V_TRADE_INDEX_21'=>'成交才收,撤单退回', 'V_TRADE_INDEX_22'=>'CNY计价', 'V_TRADE_INDEX_23'=>'最大可卖', 'V_TRADE_INDEX_24'=>'满仓(全卖),设置买入数量为最大值', 'V_TRADE_INDEX_25'=>'最佳卖价', 'V_TRADE_INDEX_26'=>'卖出价格', 'V_TRADE_INDEX_27'=>'卖出数量', 'V_TRADE_INDEX_28'=>'卖出比例:', 'V_TRADE_INDEX_29'=>'当前委托', 'V_TRADE_INDEX_30'=>'已成交', 'V_TRADE_INDEX_31'=>'我的资金', 'V_TRADE_INDEX_32'=>'隐藏零资金币种', 'V_TRADE_INDEX_33'=>'时间', 'V_TRADE_INDEX_34'=>'买/卖', 'V_TRADE_INDEX_35'=>'总额', 'V_TRADE_INDEX_36'=>'当前无数据!', 'V_TRADE_INDEX_37'=>'以这个价格卖出', 'V_TRADE_INDEX_38'=>'以这个价格买入', 'V_TRADE_INDEX_39'=>'买', 'V_TRADE_INDEX_40'=>'卖', 'V_TRADE_INDEX_41'=>'撤销', 'V_TRADE_INDEX_42'=>'委托量', 'V_TRADE_INDEX_43'=>'成交量', 'V_TRADE_INDEX_44'=>'可用余额', 'V_TRADE_INDEX_45'=>'冻结金额', 'V_TRADE_INDEX_46'=>'总计', 'V_TRADE_INDEX_47'=>'折合(CNYT)', 'V_TRADE_INDEX_48'=>'最新价', 'V_TRADE_INDEX_49'=>'最新成交', 'V_TRADE_INDEX_50'=>'成交价', 'V_TRADE_INDEX_51'=>'每次登录只输入一次交易密码', 'V_TRADE_INDEX_52'=>'每笔交易都输入交易密码', 'V_TRADE_INDEX_53'=>'每次交易都不需要输入交易密码', 'V_TRADE_INDEX_54'=>'请输入交易密码', 'V_TRADE_INFO_1'=>'搜索', 'V_TRADE_INFO_2'=>'排序:', 'V_TRADE_INFO_3'=>'默认', 'V_TRADE_INFO_4'=>'币种缩写', 'V_TRADE_INFO_5'=>'币种价格', 'V_TRADE_INFO_6'=>'币种资料库', 'V_TRADE_INFO_7'=>'中文名', 'V_TRADE_INFO_8'=>'英文名', 'V_TRADE_INFO_9'=>'缩写', 'V_TRADE_INFO_10'=>'去交易', 'V_TRADE_INFO_11'=>'币种简介', 'V_TRADE_INFO_12'=>'币种参数', 'V_TRADE_INFO_13'=>'推出日期', 'V_TRADE_INFO_14'=>'区块奖励', 'V_TRADE_INFO_15'=>'发行总量', 'V_TRADE_INFO_16'=>'研发者', 'V_TRADE_INFO_17'=>'核心算法', 'V_TRADE_INFO_18'=>'难度调整', 'V_TRADE_INFO_19'=>'存<span class="vhide">存量</span>量', 'V_TRADE_INFO_20'=>'区块速度', 'V_TRADE_INFO_21'=>'证明方式', 'V_TRADE_INFO_22'=>'主要特色', 'V_TRADE_INFO_23'=>'不足之处', 'V_TRADE_INFO_24'=>'链 接', 'V_TRADE_INFO_25'=>'钱包下载', 'V_TRADE_INFO_26'=>'源码下载', 'V_TRADE_INFO_27'=>'官方网站', 'V_TRADE_INFO_28'=>'白皮书', 'V_TRADE_PROFESSION_1'=>'币币交易--专业版', 'V_TRADE_PROFESSION_2'=>'普通版', 'V_TRADE_PROFESSION_3'=>'充值/提现', 'V_TRADE_PROFESSION_4'=>'挂单金额', 'V_TRADE_SPECIALTY_1'=>'K线时间段:', 'V_TRADE_SPECIALTY_2'=>'1天', 'V_TRADE_SPECIALTY_3'=>'6小时', 'V_TRADE_SPECIALTY_4'=>'1小时', 'V_TRADE_SPECIALTY_5'=>'30分', 'V_TRADE_SPECIALTY_6'=>'15分', 'V_TRADE_SPECIALTY_7'=>'5分', 'V_TRADE_SPECIALTY_8'=>'页面设置', 'V_TRADE_SPECIALTY_9'=>'均线设置', 'V_TRADE_SPECIALTY_10'=>'关闭均线', 'V_TRADE_SPECIALTY_11'=>'图线样式', 'V_TRADE_SPECIALTY_12'=>'K线-OHLC', 'V_TRADE_SPECIALTY_13'=>'K线-HLC', 'V_TRADE_SPECIALTY_14'=>'OHLC', 'V_TRADE_SPECIALTY_15'=>'单线', 'V_TRADE_SPECIALTY_16'=>'单线-o', 'V_TRADE_SPECIALTY_17'=>'关闭线图', 'V_FOOTER_TITLE'=>'比特币等加密数字货币的交易存在风险,7*24小时交易,没有涨停跌停限制,价格受到新闻事件,<br/>各国政策,市场需求等多种因素影响,浮动很大。我们强烈建议您事先调查了解,<br/>在自身所能承受的风险范围内参与交易。', 'V_FOOTER_BOTTOM'=>'BJS.BI 笔加索 © 2018', );<file_sep><?php namespace Common\Model; class AuthRuleModel extends \Think\Model { const RULE_URL = 1; const RULE_MAIN = 2; } ?><file_sep><?php return array( 'V_HEADER_LANGUAGE'=>'gb', 'V_HEADER_LANGUAGE_TXT'=>'English', 'WELCOME'=>'Welcome to BJS.BI', );<file_sep><?php namespace Home\Controller; class ApiController extends HomeController { // public function marketlist(){ $marketarr = C('market'); //print_r($marketarr); $ik = 0; foreach($marketarr as $k=>$v){ $ren = explode("_",$v['name']); $ret[$v['name']."t"]['name'] = $ren[0]; $ret[$v['name']."t"]['name_cn'] = M('coin')->where(array('name' => $ren[0]))->getField("title");; $ret[$v['name']."t"]['market'] = $v['name']."t"; $ret[$v['name']."t"]['price'] = $v['new_price']; $ret[$v['name']."t"]['buy_price'] = $v['buy_price']; $ret[$v['name']."t"]['sell_price'] = $v['sell_price']; $ret[$v['name']."t"]['change'] = $v['change']; $ret[$v['name']."t"]['max24hr'] = $v['max_price']; $ret[$v['name']."t"]['min24hr'] = $v['min_price']; $ret[$v['name']."t"]['volume'] = $v['volume']; $ik++; } //print_r($ret); echo json_encode($ret); } public function orderlist($market=NULL){ if(!$market) return false; $market = substr($market,0,strlen($market)-1); $trade['buy'] = M()->query("select price,num,addtime from qq3479015851_trade where type=1 and market='".$market."' order by id desc limit 0,30");; $trade['sell'] = M()->query("select price,num,addtime from qq3479015851_trade where type=2 and market='".$market."' order by id desc limit 0,30");; //print_r($ret); $ret[$market."t"] = $trade; echo json_encode($ret); } public function Historylist($market=NULL){ if(!$market) return false; $market = substr($market,0,strlen($market)-1); $trade = M()->query("select id as tradeid,price,num,addtime,type from qq3479015851_trade_log where market='".$market."' order by id desc limit 0,30");; //print_r($ret); foreach($trade as $k=>$v){ $trades[$k] = $v; $trades[$k]['time'] = date("Y-m-d H:i:s",$v['addtime']); $trades[$k]['type'] = ($v['type']==1) ? "buy":"sell"; } $ret[$market."t"] = $trades; echo json_encode($ret); } } ?> <file_sep><?php namespace Home\Controller; class TradeController extends HomeController { public function index($market = NULL) { $showPW = 1; $market = str_replace("cnyt", "cny", $market); $markety = $market; $names = array_column(C('market'), 'name'); if(!in_array($markety,$names)){ $this->error('请选择正确币种'); } if (userid()) { $user = M('User')->where(array('id' => userid()))->find(); if ($user['tpwdsetting'] == 3) { $showPW = 0; } if ($user['tpwdsetting'] == 1) { if (session(userid() . 'tpwdsetting')) { $showPW = 2; } } } //check_server(); if (!$market) { $market = C('market_mr'); } $market_time_qq3479015851 = C('market')[$market]['begintrade'] . "-" . C('market')[$market]['endtrade']; $maktNames = explode('_', $market); $xnb = $maktNames[0]; $rmb = $maktNames[1]; $zr_jz = C('coin')[$xnb]['zr_jz']; $zc_jz = C('coin')[$xnb]['zc_jz']; $this->assign('market_time', $market_time_qq3479015851); $this->assign('showPW', $showPW); $this->assign('market', $market); $this->assign('zr_jz', $zr_jz); $this->assign('zc_jz', $zc_jz); $this->assign('xnb', $xnb); $this->assign('rmb', $rmb); $this->buildHtml('index', './trade/index/market/' . $markety . 't/', '');//生成全静态 $this->display(); } /** * 手机端交易页面 * @param null $market */ public function mindex($market = NULL) { if (!userid()) { } $market = str_replace("cnyt", "cny", $market); check_server(); if (!$market) { $market = C('market_mr'); } $names = array_column(C('market'), 'name'); if(!in_array($market,$names)){ $this->error('请选择正确币种'); } //---x修改--s17/2/72/9/55 //查询全部币种的信息 $dataall = array(); $k = 0; $dq_title = ''; foreach (C('market') as $i => $v) { $zhmoney = 0; //$dataall[$k][0] = $v['title']; $dataall[$k][0] = $v['mname']; $dataall[$k][1] = round($v['new_price'], $v['round']); $dataall[$k][2] = round($v['buy_price'], $v['round']); $dataall[$k][3] = round($v['sell_price'], $v['round']); $dataall[$k][4] = round($v['volume'] * $v['new_price'], 2) * 1; $dataall[$k][5] = ''; $dataall[$k][6] = round($v['volume'], 2) * 1; $dataall[$k][7] = round($v['change'], 2); $dataall[$k][8] = str_replace("cny", "cnyt", $v['name']); $dataall[$k]['main_coin'] = $v['main_coin']; $dataall[$k]['url'] = str_replace("cny", "cnyt", $v['name']); if ($v['name'] == $market) { $dq_title = str_replace("CNY", "CNYT", $v['title']); } $dataall[$k][9] = '/Upload/coin/' . $v['xnbimg']; $dataall[$k][10] = ''; $k++; } $this->assign('dataall', $dataall); $this->assign('dq_title', $dq_title); //----x修改e //----x修改e //----17/2/27添加折合总资产s $CoinList = M('Coin')->where(array('status' => 1))->select(); $UserCoin = M('UserCoin')->where(array('userid' => userid()))->find(); $Market = M('Market')->where(array('status' => 1))->select(); foreach ($Market as $k => $v) { $Market[$v['name']] = $v; } $cny['zj'] = 0; foreach ($CoinList as $k => $v) { if ($v['name'] == 'cny') { $cny['ky'] = round($UserCoin[$v['name']], 2) * 1; $cny['dj'] = round($UserCoin[$v['name'] . 'd'], 2) * 1; $cny['zj'] = $cny['zj'] + $cny['ky'] + $cny['dj']; } else { if ($Market[C('market_type')[$v['name']]]['new_price']) { $jia = $Market[C('market_type')[$v['name']]]['new_price']; } else { $jia = 1; } $coinList[$v['name']] = array('name' => $v['name'], 'img' => $v['img'], 'title' => $v['title'] . '(' . strtoupper($v['name']) . ')', 'xnb' => round($UserCoin[$v['name']], 6) * 1, 'xnbd' => round($UserCoin[$v['name'] . 'd'], 6) * 1, 'xnbz' => round($UserCoin[$v['name']] + $UserCoin[$v['name'] . 'd'], 6), 'jia' => $jia * 1, 'zhehe' => round(($UserCoin[$v['name']] + $UserCoin[$v['name'] . 'd']) * $jia, 2)); $cny['zj'] = round($cny['zj'] + (($UserCoin[$v['name']] + $UserCoin[$v['name'] . 'd']) * $jia), 2) * 1; } } $this->assign('cny', $cny); //----17/2/27添加折合总资产s //----17/2/28交易密码 $rs = M('User')->field('tpwdsetting')->where(array('id' => userid()))->find(); if ($rs['tpwdsetting'] == 3) { $this->assign('tpwdok', $_COOKIE["tpwdsetting_" . userid()]); } $sxxb = explode('_', $market)[0]; foreach ($CoinList as $sk => $sv) { if ($sv['name'] == $sxxb) { $stmp = $sv['js_lt']; } } $tpwdsetting = 0; if(userid()){ $user = M('User')->where(array('id' => userid()))->find(); //每笔交易都需要输入交易密码 if ($user['tpwdsetting'] == 2) { $tpwdsetting = 1; } //每次登录只输入一次交易密码 if ($user['tpwdsetting'] == 1) { if (!session(userid() . 'tpwdsetting')) { $tpwdsetting = 1; } } } $this->assign('tpwdsetting',$tpwdsetting); $this->assign('stmp', $stmp); $this->assign('market', $market); $this->assign('xnb', explode('_', $market)[0]); $this->assign('rmb', explode('_', $market)[1]); $this->display(); } public function ordinary($market = NULL) { if (!$market) { $market = C('market_mr'); } $this->assign('market', $market); $this->display(); } public function profession($market = NULL) { $showPW = 1; $market = str_replace("cnyt", "cny", $market); $markety = $market; if (userid()) { $user = M('User')->where(array('id' => userid()))->find(); if ($user['tpwdsetting'] == 3) { $showPW = 0; } if ($user['tpwdsetting'] == 1) { if (session(userid() . 'tpwdsetting')) { $showPW = 2; } } } //check_server(); if (!$market) { $market = C('market_mr'); } $market_time_qq3479015851 = C('market')[$market]['begintrade'] . "-" . C('market')[$market]['endtrade']; $maktNames = explode('_', $market); $xnb = $maktNames[0]; $rmb = $maktNames[1]; $zr_jz = C('coin')[$xnb]['zr_jz']; $zc_jz = C('coin')[$xnb]['zc_jz']; $this->assign('market_time', $market_time_qq3479015851); $this->assign('showPW', $showPW); $this->assign('market', $market); $this->assign('zr_jz', $zr_jz); $this->assign('zc_jz', $zc_jz); $this->assign('xnb', $xnb); $this->assign('rmb', $rmb); $this->buildHtml('profession', './trade/profession/market/' . $markety . 't/', '');//生成全静态 $this->display(); } public function info($market = NULL) { if (!userid()) { } $market = str_replace("cnyt", "cny", $market); check_server(); if (!$market) { $market = C('market_mr'); } $this->assign('market', $market); $this->assign('xnb', explode('_', $market)[0]); $this->assign('rmb', explode('_', $market)[1]); //$this->buildHtml($market,'./Trade/info/market/','');//生成全静态 $this->display(); } public function specialty($market = NULL) { if (!$market) { $market = C('market_mr'); } $this->assign('market', $market); $this->buildHtml('index', './trade/specialty/market/' . $market . '/', '');//生成全静态 $this->display(); } public function upTrade($paypassword = NULL, $market = NULL, $price, $num, $type) { if (!userid()) { $this->error('请先登录!'); } $userid = userid(); $times = time() - 10; //$isck = M()->query("SELECT * FROM `a_market` where userid = '$userid' and addtime > $times order by addtime desc LIMIT 1"); $isck = M()->table('a_market')->where(array('userid' => $userid, 'addtime' => array('gt', $times)))->order('addtime desc')->limit(1)->select(); if ($isck) $this->error('请不要重复提交订单!'); if (!C('market')[$market]['trade']) { $this->error('当前市场禁止交易,交易时间周一至周六10:00-22:00!'); } if (C('market')[$market]['begintrade']) { $begintrade = C('market')[$market]['begintrade']; } else { $begintrade = "00:00:00"; } if (C('market')[$market]['endtrade']) { $endtrade = C('market')[$market]['endtrade']; } else { $endtrade = "23:59:59"; } $trade_begin_time = strtotime(date("Y-m-d") . " " . $begintrade); $trade_end_time = strtotime(date("Y-m-d") . " " . $endtrade); $cur_time = time(); if ($cur_time < $trade_begin_time || $cur_time > $trade_end_time) { $this->error('当前市场禁止交易,交易时间为每日' . $begintrade . '-' . $endtrade); } if (!check($price, 'double')) { $this->error('交易价格格式错误'); } if (!check($num, 'double')) { $this->error('交易数量格式错误'); } if (($type != 1) && ($type != 2)) { $this->error('交易类型格式错误'); } $user = M('User')->where(array('id' => userid()))->find(); //每笔交易都不会输入交易密码 if ($user['tpwdsetting'] == 3) { } //每笔交易都需要输入交易密码 if ($user['tpwdsetting'] == 2) { if ($paypassword != $user['paypassword']) { $this->error('交易密码错误!'); } } //每次登录只输入一次交易密码 if ($user['tpwdsetting'] == 1) { if (!session(userid() . 'tpwdsetting')) { if ($paypassword != $user['paypassword']) { $this->error('交易密码错误!'); } else { session(userid() . 'tpwdsetting', 1); } } } if (!C('market')[$market]) { $this->error('交易市场错误'); } else { $xnb = explode('_', $market)[0]; $rmb = explode('_', $market)[1]; } // TODO: SEPARATE $price = round(floatval($price), C('market')[$market]['round']); if (!$price) { $this->error('交易价格错误' . $price); } $num = round($num, 9 - C('market')[$market]['round']); if (!check($num, 'double')) { $this->error('交易数量错误'); } //买 if ($type == 1) { $min_price = (C('market')[$market]['buy_min'] ? C('market')[$market]['buy_min'] : 1.0E-8); $max_price = (C('market')[$market]['buy_max'] ? C('market')[$market]['buy_max'] : 10000000); } //卖 else if ($type == 2) { $min_price = (C('market')[$market]['sell_min'] ? C('market')[$market]['sell_min'] : 1.0E-8); $max_price = (C('market')[$market]['sell_max'] ? C('market')[$market]['sell_max'] : 10000000); } else { $this->error('交易类型错误'); } if ($max_price < $price) { $this->error('交易价格超过最大限制!'); } if ($price < $min_price) { $this->error('交易价格超过最小限制!'); } $hou_price = C('market')[$market]['hou_price']; if ($hou_price) { if (C('market')[$market]['zhang']) { // TODO: SEPARATE $zhang_price = round(($hou_price / 100) * (100 + C('market')[$market]['zhang']), C('market')[$market]['round']); if ($zhang_price < $price) { $this->error('交易价格超过今日涨幅限制!'); } } if (C('market')[$market]['die']) { // TODO: SEPARATE $die_price = round(($hou_price / 100) * (100 - C('market')[$market]['die']), C('market')[$market]['round']); if ($price < $die_price) { $this->error('交易价格超过今日跌幅限制!'); } } } $user_coin = M('UserCoin')->where(array('userid' => userid()))->find(); $fee_discounts = M('FeeDiscount')->select(); $fee_discounts = array_column($fee_discounts, 'fee'); if ($type == 1) { $trade_fee = C('market')[$market]['fee_buy']; if($user['backstage_vip'] != 0){ $trade_fee = $trade_fee * (1 - $user['backstage_fee_discount']); }else{ $trade_fee = $trade_fee * (1 - $fee_discounts[$user['vip']]); } if ($trade_fee) { $fee = round((($num * $price) / 100) * $trade_fee, 8); $mum = round((($num * $price) / 100) * (100 + $trade_fee), 8); } else { $fee = 0; $mum = round($num * $price, 8); } if ($user_coin[$rmb] < $mum) { $this->error(C('coin')[$rmb]['title'] . '余额不足!'); } } else if ($type == 2) { $trade_fee = C('market')[$market]['fee_sell']; if($user['backstage_vip'] != 0){ $trade_fee = $trade_fee * (1 - $user['backstage_fee_discount']); }else{ $trade_fee = $trade_fee * (1 - $fee_discounts[$user['vip']]); } if ($trade_fee) { $fee = round((($num * $price) / 100) * $trade_fee, 8); $mum = round((($num * $price) / 100) * (100 - $trade_fee), 8); } else { $fee = 0; $mum = round($num * $price, 8); } if ($user_coin[$xnb] < $num) { $this->error(C('coin')[$xnb]['title'] . '余额不足!'); } } else { $this->error('交易类型错误'); } if (C('coin')[$xnb]['fee_bili']) { if ($type == 2) { // TODO: SEPARATE $bili_user = round($user_coin[$xnb] + $user_coin[$xnb . 'd'], C('market')[$market]['round']); if ($bili_user) { // TODO: SEPARATE $bili_keyi = round(($bili_user / 100) * C('coin')[$xnb]['fee_bili'], C('market')[$market]['round']); if ($bili_keyi) { //$bili_zheng = M()->query('select id,price,sum(num-deal)as nums from qq3479015851_trade where userid=' . userid() . ' and status=0 and type=2 and market like \'%' . $xnb . '%\' ;'); $bili_zheng = M()->table('qq3479015851_trade') ->where(array('userid' => userid(), 'status' => 0, 'type' => 2, 'market' => array('like', '%'.$xnb.'%'))) ->field('id,price,sum(num-deal)as nums')->select(); if (!$bili_zheng[0]['nums']) { $bili_zheng[0]['nums'] = 0; } $bili_kegua = $bili_keyi - $bili_zheng[0]['nums']; if ($bili_kegua < 0) { $bili_kegua = 0; } if ($bili_kegua < $num) { $this->error('您的挂单总数量超过系统限制,您当前持有' . C('coin')[$xnb]['title'] . $bili_user . '个,已经挂单' . $bili_zheng[0]['nums'] . '个,还可以挂单' . $bili_kegua . '个', '', 5); } } else { $this->error('可交易量错误'); } } } } if (C('coin')[$xnb]['fee_meitian']) { if ($type == 2) { $bili_user = round($user_coin[$xnb] + $user_coin[$xnb . 'd'], 8); if ($bili_user < 0) { $this->error('可交易量错误'); } $kemai_bili = ($bili_user / 100) * C('coin')[$xnb]['fee_meitian']; if ($kemai_bili < 0) { $this->error('您今日只能再卖' . C('coin')[$xnb]['title'] . 0 . '个', '', 5); } $kaishi_time = mktime(0, 0, 0, date('m'), date('d'), date('Y')); $jintian_sell = M('Trade')->where(array( 'userid' => userid(), 'addtime' => array('egt', $kaishi_time), 'type' => 2, 'status' => array('neq', 2), 'market' => array('like', '%' . $xnb . '%') ))->sum('num'); if ($jintian_sell) { $kemai = $kemai_bili - $jintian_sell; } else { $kemai = $kemai_bili; } if ($kemai < $num) { if ($kemai < 0) { $kemai = 0; } $this->error('您的挂单总数量超过系统限制,您今日只能再卖' . C('coin')[$xnb]['title'] . $kemai . '个', '', 5); } } } if (C('market')[$market]['trade_min']) { if ($mum < C('market')[$market]['trade_min']) { $this->error('交易总额不能小于' . C('market')[$market]['trade_min']); } } if (C('market')[$market]['trade_max']) { if (C('market')[$market]['trade_max'] < $mum) { $this->error('交易总额不能大于' . C('market')[$market]['trade_max']); } } if (!$rmb) { $this->error('数据错误1'); } if (!$xnb) { $this->error('数据错误2'); } if (!$market) { $this->error('数据错误3'); } if (!$price) { $this->error('数据错误4'); } if (!$num) { $this->error('数据错误5'); } if (!$mum) { $this->error('数据错误6'); } if (!$type) { $this->error('数据错误7'); } if ($type == 1) { $user_coin = M()->table('qq3479015851_user_coin')->where(array('userid' => userid()))->find(); if ($user_coin[$rmb] < $mum) { $this->error(C('coin')[$rmb]['title'] . '余额不足!'); } } else if ($type == 2) { if ($user_coin[$xnb] < $num) { $this->error(C('coin')[$xnb]['title'] . '余额不足2!'); } } else { $this->error('交易类型错误'); } $rs = M()->table('a_market')->add(array('type' => $type, 'addtime' => time(), 'market' => $market, 'num' => $num, 'mum' => $mum, 'pri' => $price, 'fee' => $fee, 'userid' => userid())); $this->success('交易成功!'); } public function chexiao($id) { if (!userid()) { $this->error('请先登录!'); } if (!check($id, 'd')) { $this->error('请选择要撤销的委托!'); } $trade = M('Trade')->where(array('id' => $id))->find(); if (!$trade) { $this->error('撤销委托参数错误!'); } if ($trade['userid'] != userid()) { $this->error('参数非法!'); } //新撤销 $time = time(); $userid = userid(); // $is_c = M()->query("select aid from a_auto where tid='$id' ;"); $is_c = M()->table('a_auto')->field('aid')->where(array('tid' => $id))->select(); if ($is_c) { $this->error('正在撤销中!'); } // $is_t = M()->query("select id from qq3479015851_trade where id='$id' and status = 0 and userid = '$userid' ;"); $is_t = M()->table('qq3479015851_trade')->where(array('id' => $id, 'status' => 0, 'userid' => $userid))->field('id')->select(); if ($is_t) { $rs = M()->table('a_auto')->add(array('type' => 1, 'addtime' => $time, 'tid' => $id, 'uid' => $userid)); } else { $this->error('已经撤销成功!'); } if ($rs) { $this->success("操作成功,已进入撤销流程!"); } else { $this->error('撤销委托错误!'); } } } ?> <file_sep><?php namespace Home\Controller; class IndexController extends HomeController { public function app() { $this->display(); } public function index() { $indexAdver = (APP_DEBUG ? null : S('index_indexAdver')); if (!$indexAdver) { $indexAdver = M('Adver')->where(array('status' => 1))->order('id asc')->select(); S('index_indexAdver', $indexAdver); } $this->assign('indexAdver', $indexAdver);//轮播图 $information=[]; $information[]=['type'=>'官方公告','list'=>(APP_DEBUG ? null : S('notice'))];//公告 $information[]=['type'=>'行业资讯','list'=>(APP_DEBUG ? null : S('notice'))];//资讯 $Model = M('Article');//文章表 foreach ($information as $k => $v){ if(!$v['list']) { $where=['type'=>$v['type'],'status'=>1]; $information[$k]['list'] = $Model->where($where)->page(1, 2)->order('id desc')->select(); foreach ($information[$k]['list'] as $kk => $vv){ $information[$k]['list'][$kk]['brief'] = mb_substr(preg_replace("/<[^>]+>/is", "", $vv['content']), 0, 150); } } } $this->assign('information', $information);//公告和资讯 //设置热门文章 $id = 19; $articletype = M('ArticleType')->where(array('id' => $id))->find(); $where = array('type' => $articletype['name'],'status'=>1); $Model = M('Article'); $hotlist = $Model->where($where)->order('hits desc')->limit(4)->select(); foreach ($hotlist as $k => $v) { $hotlist[$k]['title'] = mb_substr($v['title'],0,14); //$hotlist[$k]['brief'] = mb_substr(preg_replace("/<[^>]+>/is", "", $v['content']), 0, 25); } $this->assign('hotlist', $hotlist); $indexLink = (APP_DEBUG ? null : S('index_indexLink')); if (!$indexLink) { $indexLink = M('Link')->where(array('status' => 1))->order('sort asc ,id desc')->select(); } $is_login = false; if(userid()){ $zj = 0; $CoinList = M('Coin')->where(array('status' => 1))->select(); $UserCoin = M('UserCoin')->where(array('userid' => userid()))->find(); $Market = M('Market')->where(array('status' => 1))->select(); foreach ($Market as $k => $v) { $Market[$v['name']] = $v; } foreach ($CoinList as $k => $v) { if ($v['name'] == 'cny') { $ky = round($UserCoin[$v['name']], 2) * 1;//可用数量 $dj = round($UserCoin[$v['name'] . 'd'], 2) * 1;//冻结数量 $zj = $zj + $ky + $dj;//计算预估总资产 }else { if($Market[C('market_type')[$v['name']]]['status'] != 1){ continue; } if ($Market[C('market_type')[$v['name']]]['new_price']) { $jia = $Market[C('market_type')[$v['name']]]['new_price']; }else { $jia = 1; } $zj = round($zj + (($UserCoin[$v['name']] + $UserCoin[$v['name'] . 'd']) * $jia), 2) * 1;//计算预估总资产 } } $is_login = true; } $marketsy = C('market'); foreach ($marketsy as $key => $val) { $tmp[$key] = $val['id']; } array_multisort($tmp,SORT_ASC,$marketsy); foreach ($marketsy as $k => $v) { $data[$k]['xnb'] = strtoupper(explode('_', $v['name'])[0]); $data[$k]['rmb'] = strtoupper(explode('_', $v['name'])[1]); $data[$k]['url'] = str_replace("cny","cnyt",$v['name']); $data[$k]['title'] = str_replace("CNY","CNYT",$v['title']); $data[$k]['img'] = $v['xnbimg']; $data[$k]['new_price'] = $v['new_price']; $data[$k]['main_coin'] = $v['main_coin']; $data[$k]['volume'] = $v['volume']; $data[$k]['mname'] = $v['mname']; $data[$k]['volumes'] = round($v['volume']*$v['new_price'],2); //$data[$k]['change'] = $v['change']>0 "+".$v['change']:$v['change']; if($v['change']>0){ $data[$k]['change'] = "+".round($v['change'],2); }else{ $data[$k]['change'] = round($v['change'],2); } if($v['change']<0) $data[$k]['class']="red"; } $this->assign('zj',$zj); $this->assign('is_login',$is_login); $this->assign('lists', $data); $this->display(); } public function monesay($monesay = NULL) { } public function install() { } public function fragment() { $ajax = new AjaxController(); $data = $ajax->allcoin(''); $this->assign('data', $data); $this->display('Index/d/fragment'); } public function newPrice() { ini_set('display_errors', 'on'); error_reporting(E_ALL); //var_dump(C('market')); $data = $this->allCoinPrice(); //var_dump($data); // exit; $last_data = S('ajax_all_coin_last'); $_result = array(); if (empty($last_data)) { foreach (C('market') as $k => $v) { $_result[$v['id'] . '-' . strtoupper($v['xnb'])] = $data[$k][1] . '-0.0'; } } else { foreach (C('market') as $k => $v) { $_result[$v['id'] . '-' . strtoupper($v['xnb'])] = $data[$k][1] . '-' . ($data[$k][1] - $last_data[$k][1]); } } S('ajax_all_coin_last', $data); $data = json_encode( array( 'result' => $_result, ) ); exit($data); //exit('{"result":{"25-BTC":"4099.0-0.0","1-LTC":"26.43--0.22650056625141082","26-DZI":"1.72-0.0","6-DOGE":"0.00151-0.0"},"totalPage":5}'); } protected function allCoinPrice() { $data = (APP_DEBUG ? null : S('allcoin')); // 市场交易记录 $marketLogs = array(); foreach (C('market') as $k => $v) { $tradeLog = M('TradeLog')->where(array('status' => 1, 'market' => $k))->order('id desc')->limit(50)->select(); $_data = array(); foreach ($tradeLog as $_k => $v) { $_data['tradelog'][$_k]['addtime'] = date('m-d H:i:s', $v['addtime']); $_data['tradelog'][$_k]['type'] = $v['type']; $_data['tradelog'][$_k]['price'] = $v['price'] * 1; $_data['tradelog'][$_k]['num'] = round($v['num'], 6); $_data['tradelog'][$_k]['mum'] = round($v['mum'], 2); } $marketLogs[$k] = $_data; } $themarketLogs = array(); if ($marketLogs) { $last24 = time() - 86400; $_date = date('m-d H:i:s', $last24); foreach (C('market') as $k => $v) { $tradeLog = isset($marketLogs[$k]['tradelog']) ? $marketLogs[$k]['tradelog'] : null; if ($tradeLog) { $sum = 0; foreach ($tradeLog as $_k => $_v) { if ($_v['addtime'] < $_date) { continue; } $sum += $_v['mum']; } $themarketLogs[$k] = $sum; } } } foreach (C('market') as $k => $v) { $data[$k][0] = $v['title']; $data[$k][1] = round($v['new_price'], $v['round']); $data[$k][2] = round($v['buy_price'], $v['round']); $data[$k][3] = round($v['sell_price'], $v['round']); $data[$k][4] = isset($themarketLogs[$k]) ? $themarketLogs[$k] : 0;//round($v['volume'] * $v['new_price'], 2) * 1; $data[$k][5] = ''; $data[$k][6] = round($v['volume'], 2) * 1; $data[$k][7] = round($v['change'], 2); $data[$k][8] = $v['name']; $data[$k][9] = $v['xnbimg']; $data[$k][10] = ''; } return $data; } } ?> <file_sep>var bjsIndex = (function(){ var bjsIndex = function(){ this.init(); } bjsIndex.prototype.init = function(){ this.localPath = typeof localPath === 'undefined' ? 'https://service.bjs.bi/award/' : localPath; this.indexUrl = { starAdd: 'user/star/add', starRemove: 'user/star/remove', starGet: 'user/star/find' }; //this._fastClick(); this._initFontSize(); this._resizeWindow(); this._initSkin(); this._initInputFocus(); this._initFirstVisit(); if($('.copy-btn')[0]){ this._initClipboard(); } } bjsIndex.prototype.initIndex = function(){ this._initTabs(); this._initSwiper(); this._initFav(); if($.cookies.get('homePageEyes')){ $('.'+$('.assets-eyes').data('class')).toggleClass('hide'); $('.assets-eyes').toggleClass('off'); } $(document).on('click','.assets-eyes',function(event){ event.preventDefault(); $(this).toggleClass('off'); $('.'+$(this).data('class')).toggleClass('hide'); $.cookies.set('homePageEyes',$.cookies.get('homePageEyes') == 1? 0 : 1,360); }); } bjsIndex.prototype.initC2c = function(){ this._initTabs(); $('.input-group').on('focus','.form-control',function(){ $(this).closest('.input-group').addClass('active'); }); $('.input-group').on('blur','.form-control',function(){ $(this).closest('.input-group').removeClass('active'); }); } bjsIndex.prototype.initC2cMerchant = function(){ var _this = this; this.initC2c(); } bjsIndex.prototype.initMarket = function(){ var txt = $('.market-search-input').val().trim(); var _this = this; this._initFav(); $(document).on('input propertychange keyup','.market-search-input',function(){ var _txt = $(this).val().trim(); if(txt !== _txt){ txt = _txt; _this._toSearch(txt); if($('#bi-fav-btn').hasClass('active')){ $('.bi-list-choose-fav').find('.bi-list-tbody-tr:not(".fav-cur")').addClass('hide'); } } }); } bjsIndex.prototype.initMy = function(){ var _this = this; _this.resourcesPath = '/Public/m/'; var state = false; var skin = $.cookies.get('skin'); if(skin !== 'white'){ $('.my-heade-skin').removeClass('sun').addClass('moon'); }else{ $('.my-heade-skin').removeClass('moon').addClass('sun'); } $(document).on('click','.my-heade-skin',function(){ if(state){ return false; } state = true; $(this).toggleClass('moon sun'); var skin = $.cookies.get('skin'); if(skin !== 'white'){ $.cookies.set('skin','white',{expires: 30,path: "/"}); var link = document.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = _this.resourcesPath + 'css/white.css'; link.id = 'style-white'; $('head').append(link); layer.config({ extend: '', //加载您的扩展样式 skin: '' }); }else{ $.cookies.set('skin','black',{expires: 30,path: "/"}); $('#style-white').remove(); layer.config({ extend: 'myskin/style.css', //加载您的扩展样式 skin: 'myskin' }); } setTimeout(function(){ state = false; },600); }); /*$(document).on('click','.my-heade-logout',function(event){ event.preventDefault(); var cookies = document.cookie.split('; '); cookies.forEach(function(item,index){ $.cookies.set(item.split('=')[0],'',0); }); layer.msg('已退出登录',{icon:1,time:800},function(){ window.location.replace('/login'); }); });*/ } bjsIndex.prototype.initMyAsset = function(){ var _this = this; this._initTabs(); this._initBack(); var txt = $('.search-input').val().trim(); var _this = this; $(document).on('input propertychange keyup','.search-input',function(){ var _txt = $(this).val().trim(); if(txt !== _txt){ txt = _txt; _this._toSearch(txt,'.my-asset-list > ul','.my-asset-list-bi-icon'); } }); } bjsIndex.prototype.initUc = function(){ var _this = this; this._initBack(); } bjsIndex.prototype.initSettings = function(){ var _this = this; this._initBack(null,'/Finance/index'); $(document).on('click','.my-links-skin',function(){ $('#skin-box').addClass('right-show'); }); $(document).on('click','.my-links-language',function(){ $('#language-box').addClass('right-show'); }); $(document).on('click','.asset-detail-filter-box-bg',function(){ $('.asset-detail-filter-box.right-show').removeClass('right-show'); }); $(document).on('click','.asset-detail-filter-box-cont a',function(event){ event.preventDefault(); var state = $(this).data('state'); var cookies = $(this).data('cookies'); var callback = $(this).data('callback'); if(state != -1 && $.cookies.get(cookies) != state){ $.cookies.set(cookies,state,30); $('.'+callback).find('em').text($(this).text()); if(cookies == 'skin'){ _this._initSkin(); }else if(cookies == 'think_language'){ window.location.reload(); } } $('.asset-detail-filter-box.right-show').removeClass('right-show'); }); } bjsIndex.prototype.initArticle = function(){ var _this = this; //this._initBack(); this._initTabs(); } bjsIndex.prototype.initAddress = function(){ var _this = this; this._initBack('#tibi-page'); } bjsIndex.prototype.initPayment = function(){ var _this = this; this._initBack('#payment-page'); //添加支付地址 $(document).on('click','#add-payment-btn',function(event){ event.preventDefault(); $('#payment-page').addClass('hide'); $('#payment-address').removeClass('hide'); }); //点击返回按钮 $(document).on('click','#payment-address .search-slide-back',function(event){ event.preventDefault(); $('#payment-page').removeClass('hide'); $('#payment-address').addClass('hide'); }); //点击返回按钮 $(document).on('click','.payment-address-page .search-slide-back',function(event){ event.preventDefault(); $('#payment-address').removeClass('hide'); $(this).closest('.payment-address-page').addClass('hide'); }); //点击添加按钮 $(document).on('click','.bjs-btn-pay-icon',function(){ var id = $(this).data('id'); $('#payment-address').addClass('hide'); $('#'+id).removeClass('hide'); }); //预览图片 $(document).on('click','.preview-btn',function(){ if($(this).closest('.wrap-form-item').find('.upload-payment img')[0]){ layer.load(); var src = $(this).closest('.wrap-form-item').find('.upload-payment img')[0].src; var img = new Image(); img.src = src; img.onload = function(){ layer.closeAll('loading'); layer.open({ title: '图片预览' ,btnAlign: 'c' ,btn: '' ,content: '<img src="'+src+'" style="max-width: 240px; width: 100%;" />' }) } img.onerror = function(){ layer.closeAll('loading'); layer.msg('图片已损坏',{icon:0,time:800}) } }else{ layer.msg('请上传图片',{icon:0,time:1000}); } }); } bjsIndex.prototype.initAssetDetail = function(){ var _this = this; this._initBack(); $(document).on('click','.asset-detail-filter-btn',function(){ $('.asset-detail-filter-box').addClass('right-show'); }); $(document).on('click','.asset-detail-filter-box-bg',function(){ $('.asset-detail-filter-box').removeClass('right-show'); }); $(document).on('click','.asset-detail-filter-box-cont a',function(event){ event.preventDefault(); var state = $(this).data('state'); var text = $(this).text(); if(state == 0){ $('.asset-detail-filter-btn').text(text); $('.asset-detail-list').children().removeClass('hide'); }else if(state > 0){ $('.asset-detail-filter-btn').text(text); $('.asset-detail-list').children().addClass('hide'); $('.asset-detail-list').children('[data-state="'+state+'"]').removeClass('hide'); } $('.asset-detail-filter-box').removeClass('right-show'); }); } bjsIndex.prototype.initDelegation = function(){ var _this = this; this._initBack(); var state = 0; $(document).on('click','.delegation-tab-btn',function(){ var $this = $(this); if($this.hasClass('active')){ return false; } $this.addClass('active').siblings('.active').removeClass('active'); state = $this.data('state'); if(state == 0){ $('.my-asset-list').children().removeClass('hide'); }else{ $('.my-asset-list').children().addClass('hide'); $('.my-asset-list').children('[data-state="'+state+'"]').removeClass('hide'); } if(txt){ _this._toSearch(txt,'.my-asset-list > ul','.bjs-bi-name'); if(state != 0){ $('.my-asset-list').children(':not([data-state="'+state+'"])').addClass('hide'); } } }); var txt = $('.search-input').val().trim(); var _this = this; $(document).on('input propertychange keyup','.search-input',function(){ var _txt = $(this).val().trim(); if(txt !== _txt){ txt = _txt; _this._toSearch(txt,'.my-asset-list > ul','.bjs-bi-name'); if(state != 0){ $('.my-asset-list').children(':not([data-state="'+state+'"])').addClass('hide'); } } }); } bjsIndex.prototype.initPromotion = function(){ var _this = this; this._initBack(); } bjsIndex.prototype.initComplaint = function(){ var _this = this; this._initBack(); } bjsIndex.prototype.initPay = function(){ var _this = this; this._initFav(); this._initTabs(); //this._initProgress(); this._initChooseBi(); $('.form-item').on('focus','.form-input',function(){ $(this).closest('.form-item').addClass('active'); }); $('.form-item').on('blur','.form-input',function(){ $(this).closest('.form-item').removeClass('active'); }); $(document).on('click','.kline-btn',function(event){ event.preventDefault(); $('#trade-page').addClass('hide'); $('#market-page').removeClass('hide'); }); $(document).on('click','#market-page .search-slide-back',function(event){ event.preventDefault(); $('#trade-page').removeClass('hide'); $('#market-page').addClass('hide'); }); } bjsIndex.prototype.initLogin = function(){ var _this = this; //password & text change $(document).on('click','.assets-eyes',function(event){ event.preventDefault(); $(this).toggleClass('off'); var $input = $(this).closest('.wrap-form-item').find('.form-input-password'); var val = $input.val(); $input.val(''); if($input.prop('type') == 'text'){ $input.prop('type','password'); }else{ $input.prop('type','text'); } $input.val(val); }); } bjsIndex.prototype.initRegister = function(){ var _this = this; this._initTabs(); this.initLogin(); } bjsIndex.prototype.initResetPassword = function(){ var _this = this; this._initTabs(); this.initLogin(); } bjsIndex.prototype.initOrder = function(){ var _this = this; //关闭提示 $(document).on('click','.order-detail-warning-close',function(event){ event.preventDefault(); $(this).closest('.order-detail-warning').addClass('hide'); }); //查看订单二维码 $(document).on('click','.order-detail-qrcode',function(){ layer.load(); var src = $(this).data('img'); var img = new Image(); img.src = src; img.onload = function(){ layer.closeAll('loading'); layer.open({ title: '收款二维码' ,btnAlign: 'c' ,btn: '' ,content: '<img src="'+src+'" style="max-width: 240px; width: 100%;" />' }) } img.onerror = function(){ layer.closeAll('loading'); layer.msg('图片已损坏',{icon:0,time:800}) } return false; }); } bjsIndex.prototype.initOrderPayment = function(){ var _this = this; this.initOrder(); } bjsIndex.prototype._initFav = function(){ var _this = this; var userId = userid; var cid = market + 't'; if(userId){ _this._getFav(userId,function(result){ result.data.forEach(function(item,index){ if(item.coin == cid){ $('.fav-btn').addClass('star-cur'); } $('.bi-list-choose-fav').find('[data-name="'+item.coin+'"]').addClass('fav-cur'); }); }); } //切换自选区 $(document).on('click','#bi-fav-btn',function(){ if(!userId){ layer.msg('请登录',{icon:0,time:800}); return false; } $(this).parent().parent().find('.active').removeClass('active'); $(this).addClass('active'); if($('input[name="bi-keywords"]')[0]){ _this._toSearch($('input[name="bi-keywords"]').val()); } $('.bi-list-choose-fav').find('.bi-list-tbody-tr:not(".fav-cur")').addClass('hide'); }); //切换CNYT $(document).on('click','#bi-cnyt-btn',function(){ if(!userId){ return false; } $(this).parent().parent().find('.active').removeClass('active'); $(this).addClass('active'); $('.bi-list-choose-fav .bi-list-tbody-tr').removeClass('hide'); if($('input[name="bi-keywords"]')[0]){ _this._toSearch($('input[name="bi-keywords"]').val()); } }); //收藏、移除 var timer = 0, num = 0; $(document).on('click','.fav-btn',function(event){ event.preventDefault(); if(!userId){ layer.msg('请登录',{icon:0,time:800}); return false; } var $this = $(this); /*num ++; var _timer = new Date().getTime(); if(!timer){ timer = _timer; }else if(_timer - timer < 3000 && num > 3){ layer.msg('操作太快,休息一下吧~',{icon:5}); setTimeout(function(){ num = 0; },3000); return false; }else{ timer = _timer; }*/ if($(this).hasClass('star-cur')){ //执行删除操作 _this._removeFav(userId,cid,function(){ $this.removeClass('star-cur'); $('.bi-list-choose-fav').find('[data-name="'+cid+'"]').removeClass('fav-cur').addClass('hide'); layer.msg('移除收藏成功',{icon:0,time:800}); }); }else{ //执行添加操作 _this._addFav(userId,cid,function(){ $this.addClass('star-cur'); $('.bi-list-choose-fav').find('[data-name="'+cid+'"]').addClass('fav-cur').removeClass('hide'); layer.msg('收藏成功',{icon:1,time:800}); }); } }); } bjsIndex.prototype._getFav = function(userId,callback){ var _this = this; _this._fetch(_this.localPath+_this.indexUrl.starGet,{userId:userId},'post','json',callback); } bjsIndex.prototype._addFav = function(userId,cid,callback){ var _this = this; _this._fetch(_this.localPath+_this.indexUrl.starAdd,{userId:userId,coinType:cid},'post','json',callback); } bjsIndex.prototype._removeFav = function(userId,cid,callback){ var _this = this; _this._fetch(_this.localPath+_this.indexUrl.starRemove,{userId:userId,coinType:cid},'post','json',callback); } bjsIndex.prototype._initBack = function(el,url){ console.log(url) var back = ( el ? el + ' ' : '' ) + '.search-slide-back'; $(document).on('click',back,function(event){ event.preventDefault(); if(url){ window.location.replace(url+'?random='+((Math.random()*100)>>0)); }else{ window.history.back(); } }); } bjsIndex.prototype._initClipboard = function(){ //复制到剪贴板 if(this.clipboard){ this.clipboard.destroy(); } this.clipboard = new ClipboardJS('.copy-btn'); this.clipboard.on('success', function(e){ layer.msg('复制成功',{icon:1,time:800}); }); this.clipboard.on('error', function(e){ layer.msg('浏览器不支持,请手动复制',{icon:2,time:800}); }); } bjsIndex.prototype._initChooseBi = function(){ var _this = this; $(document).on('click','.bjs-bi-choose-name',function(){ $('.bjs-bi-choose-show').slideToggle(200); $('.search-btn-box,.search-slide-box').toggleClass('hide'); }); $(document).on('click','#trade-page .search-slide-back',function(event){ event.preventDefault(); $('.bjs-bi-choose-show').slideToggle(200); $('.search-btn-box,.search-slide-box').toggleClass('hide'); }); var txt = $('.search-input-box input').val().trim(); var _this = this; $(document).on('input propertychange keyup','.search-input-box input',function(){ var _txt = $(this).val().trim(); if(txt !== _txt){ txt = _txt; _this._toSearch(txt); if($('#bi-fav-btn').hasClass('active')){ $('.bi-list-choose-fav').find('.bi-list-tbody-tr:not(".fav-cur")').addClass('hide'); } } }); } bjsIndex.prototype._toSearch = function(txt,list,name){ var _this = this; var list = list || '.bi-list-tbody .bi-list-tbody-tr'; var name = name || '.bi-list-tbody-tr-name'; var $list = $(list); if($list[0]){ $list.each(function(){ var _txt = $(this).find(name).text(); var _txt2 = $(this).data('name'); txt = txt.replace(/\s/g,''); _txt = _txt.replace(/\s/g,''); _txt2 = _txt2.replace(/\s/g,''); var patt1 = new RegExp(txt,'i'); if(patt1.test(_txt) || patt1.test(_txt2)){ $(this).removeClass('hide'); }else{ $(this).addClass('hide'); } }); } } bjsIndex.prototype._initSwiper = function(){ var swiper = new Swiper('.swiper-container', { slidesPerView: 1, spaceBetween: 30, loop: true, pagination: { el: '.swiper-pagination', clickable: true, } }); } bjsIndex.prototype._fastClick = function(){ var u = navigator.userAgent, app = navigator.appVersion; var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端 if (isAndroid) { //console.log('这个是安卓操作系统'); //这个是安卓操作系统 } if (isIOS) { //console.log('这个是ios操作系统'); FastClick.attach(document.body);     //这个是ios操作系统 } } bjsIndex.prototype._initFontSize = function(){ var windowWidth = $('body').width(); var fontSize = windowWidth > 1125 ? 10 : windowWidth*10/1125; $('html').css({ 'fontSize': fontSize*10 + 'px' }); } bjsIndex.prototype._resizeWindow = function(){ var _this = this; $(window).resize(function(){ _this._initFontSize(); }); } bjsIndex.prototype._initTabs = function(){ $(document).on('click','.bjs-tab-btn',function(event){ event.preventDefault(); var $this = $(this); if($this.hasClass('active')){ return false; } var id = $this.data('id'); //console.log(id) $this.closest('.bjs-tab-head').find('.active').removeClass('active').end().end().addClass('active'); $('#'+id).addClass('active').siblings('.active').removeClass('active'); }); } bjsIndex.prototype._initFirstVisit = function(){ var _this = this; if(!$.cookies.get('skin')){ layer.open({ title: '笔加索提示您' ,maxWidth: 280 ,content: '尊敬的游客,您现在访问的是中文站,如果需要设置其他语言,请前往设置。' ,btn: ['设置','不需要'] ,btnAlign: 'c' ,yes: function(index,layero){ window.location.href = '/task/settings'; $.cookies.set('skin','black'); $.cookies.set('think_language','zh-cn'); } ,btn2: function(){ $.cookies.set('skin','black'); $.cookies.set('think_language','zh-cn'); } }); } } bjsIndex.prototype._initSkin = function(){ var _this = this; _this.resourcesPath = '/Public/m/'; var skin = $.cookies.get('skin') || 'black'; if(skin !== 'white'){ $('#style-white').remove(); if(typeof layer != 'undefined'){ layer.config({ extend: 'myskin/style.css', //加载您的扩展样式 skin: 'myskin' }); } }else if(!$('#style-white')[0]){ $.cookies.set('skin','white',{expires: 30,path: "/"}); var link = document.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = _this.resourcesPath + 'css/white.css'; link.id = 'style-white'; $('head').append(link); layer.config({ extend: '', //加载您的扩展样式 skin: '' }); } } bjsIndex.prototype._initInputFocus = function(){ $('input[type="password"],input[type="text"],input[type="number"],input[type="email"],input[type="phone"]').on('focus',function(){ setTimeout(function(){ //this.scrollIntoView(true) this.scrollIntoViewIfNeeded(); }.bind(this),300); }); } bjsIndex.prototype._initNotice = function(title,str,btn,maxWidth,cookie){ var bjsNotice = $.cookies.get(cookie); if(!bjsNotice){ layer.closeAll(); setTimeout(function(){ layer.open({ maxWidth: maxWidth ,title: title ,content: str ,btn: btn ,btnAlign: 'c' ,yes: function(index){ layer.close(index); $.cookies.set(cookie,1,30); } }); },100); } } bjsIndex.prototype._initProgress = function(callback){ if(!$('.bjs-progress')[0]){ return false; } var state = false, click = false; var left = 0, width = 0; var $this; //$(document).on('touchstart','.bjs-progress-btn',start); $('.bjs-progress-up .bjs-progress-btn')[0].addEventListener('touchstart',start, false); $('.bjs-progress-down .bjs-progress-btn')[0].addEventListener('touchstart',start, false); document.addEventListener('touchmove',move, false); document.addEventListener('touchend',end, false); function start(event){ $this = $(event.target); event.preventDefault(); //console.log(event.touches[0]); width = $this.closest('.bjs-progress-top').width(); left = $this.closest('.bjs-progress-top').offset().left; state = true; } function move(event){ if(state){ var x = event.pageX || event.touches[0].pageX; var _left = x - left; _left = _left > width ? width : (_left < 0 ? 0 : _left); var pLeft = (_left / width * 100)>>0; $this.css('left',pLeft+'%'); $this.siblings('.bjs-progress-line').css('width',pLeft+'%'); $this.closest('.bjs-progress').find('.bjs-progress-num').text(pLeft+'%'); $this.siblings('.bjs-progress-points').children().each(function(){ if($(this).data('point') > pLeft){ $(this).removeClass('active'); }else{ $(this).addClass('active'); } }); if(callback){ callback(pLeft,$this.closest('.bjs-progress')[0]); } } } function end(event){ if(state){ state = false; } } $(document).on('click','.bjs-progress-points',function(event){ event.preventDefault(); state = true; $this = $(this).siblings('.bjs-progress-btn'); //console.log(event.touches[0]); width = $this.closest('.bjs-progress-top').width(); left = $this.closest('.bjs-progress-top').offset().left; move(event); }); } bjsIndex.prototype._fetch = function(url,data,type,dataType,success,error){ $.ajax({ url: url, data: data, dataType: dataType, type: type, success: success, error: error }); } return bjsIndex; })(); <file_sep>var bjsIndex = (function(){ var bjsIndex = function(){ this.localPath = typeof localPath === 'undefined' ? 'https://service.bjs.bi/award/' : localPath; this.resourcesPath = typeof resourcesPath === 'undefined' ? '' : resourcesPath; this.indexUrl = { day3: 'market/day3', starAdd: 'user/star/add', starRemove: 'user/star/remove', starGet: 'user/star/find' }; this.fontSize = 10; this.userInfo = this.getUserInfo(); this.init(); } bjsIndex.prototype.init = function(){ this.initSkin(); this.initLanguage(); //全局通用 //$(window).resize(this.initFontSize); //this.initFontSize(); //this.initProgress(callback);//实例化进度条 Array.prototype.insertSort = function(fn){ var array = this; var fn = fn || function(a,b){ return b > a; } for(var i = 1; i < array.length; i++){ var key = array[i]; var j = i - 1; while(j >= 0 && fn(array[j],key)){ array[j + 1] = array[j]; j--; } array[j + 1] = key; } return array; } Object.defineProperty(Array.prototype, 'insertSort', {'enumerable': false}); } bjsIndex.prototype.initIndex = function(){ //初始化首页 var _this = this; this.styleSet = { white : { lineColor: ['rgb(0, 183, 183)' , 'rgb(255, 105, 105)'],//蓝 : 红 topColor: ['rgba(0, 183, 183, 0.4)' , 'rgba(255, 105, 105, 0.4)'], bottomColor: ['rgba(255,255,255,0)' , 'rgba(255,255,255,0)'], }, black : { lineColor: ['rgb(0, 255, 255)' , 'rgb(255, 105, 105)'],//蓝 : 红 topColor: ['rgba(0, 255, 255, 0.4)' , 'rgba(255, 105, 105, 0.4)'], bottomColor: ['rgba(0,0,0,0)' , 'rgba(0,0,0,0)'], } }; this.initSearch(); this.initBanner(); this.getBiInfo(); this.initStar(); this.initIndexSort(); this.initPaomadeng(); this.initAdvertising(); $(document).on('click','.style-white,.style-black',function(){ if(!$(this).hasClass('change')){ return false; } _this.initCanvas(_this.getBiInfoData); }); } bjsIndex.prototype.initAdvertising = function(){ var $box = $('.bjs-news-slide > ul'); var length = $box.children().size(); if(length < 4){ return false; } $box.append($box.html()); var state = true; var index = 0; $(document).on('click','.bjs-news-btn-right',function(){ if(state){ state = false; index --; if(index + length < 0){ $box.css('marginLeft','0%'); index = -1; } $box.stop().animate({ marginLeft: index * 25 + '%' },300,function(){ state = true; }); } }); $(document).on('click','.bjs-news-btn-left',function(){ if(state){ state = false; index ++; if(index > 0){ index = 1 - length; $box.css('marginLeft',- length * 25 + '%'); } $box.stop().animate({ marginLeft: index * 25 + '%' },300,function(){ state = true; }); } }); } bjsIndex.prototype.initPaomadeng = function(){ var width = 0; $('.bjs-notice-list-slide').children().each(function(i,item){ width += $(item).outerWidth(true); }); $('.bjs-notice-list-slide').append($('.bjs-notice-list-slide').html()); var timer = null; var num = 0; function run(){ num ++; if(num >= width){ num = 0; } $('.bjs-notice-list').scrollLeft(num); } timer = setInterval(run,50); $('.bjs-notice-list').hover(function(){ if(timer){ clearInterval(timer); timer = null; } },function(){ timer = setInterval(run,50); }); } bjsIndex.prototype.initIndexSort = function(){ var _this = this; $('.bjs-tab-thead').on('click','.curr-base',function(){ var $this = $(this); var index = $this.parent().index(); var state = $this.data('desc') || false; $this.closest('.bjs-tab-thead').find('.active').removeClass('active'); $this.closest('.bjs-tab-table').find('.bjs-tab-tbody').each(function(){ arr = []; var _html = ''; $(this).find('.bjs-tab-tr').each(function(i,item){ var obj = {}; if(index == 0){ obj.item = item; obj.key = $(this).data('id'); arr.push(obj); }else{ obj.item = item; var text = $(this).children().eq(index).text(); text = text.replace(/(^[^\d\-]*|[^?=\d\.])/g,''); obj.key = parseFloat(text); arr.push(obj); } }); if(state){ arr.insertSort(function(a,b){ return a.key > b.key; }); $this.find('.bjs-sort-down').addClass('active'); $this.find('.bjs-sort-up').removeClass('active'); }else{ arr.insertSort(function(a,b){ return a.key < b.key; }); $this.find('.bjs-sort-up').addClass('active'); $this.find('.bjs-sort-down').removeClass('active'); } var $box = $(this).clone(); $box.empty(); arr.map(function(item,key,ary){ $box.append(item.item); }); $(this).html($box.html()); _this.initCanvas(_this.getBiInfoData); _this.refreshIScroll('page-left-iscroll-wrap'); }); $this.data('desc',!state); }); } bjsIndex.prototype.initRegister = function(){ this.initRegisterSelect(); this.initRegisterSubmit(); //submit 事件 $('.register-form').on('keyup','input',function(e){ if(e.keyCode == 13){ $(this).closest('.register-list').find('.register-form-submit').click(); } }); } bjsIndex.prototype.initRegisterSubmit = function(){ //注册方式切换 $('.register-head').on('click','a',function(event){ event.preventDefault(); if($(this).hasClass('active')){ return false; }else{ $(this).addClass('active').siblings().removeClass('active'); $('#'+this.id+'-form').addClass('active').siblings().removeClass('active'); } }); //是否勾选了用户协议 $('.register-agreement').on('change','input[type="checkbox"]',function(){ var $submit = $(this).closest('.register-list').find('.register-form-submit'); if(this.checked){ $submit.removeClass('disabled-submit-btn'); }else{ $submit.addClass('disabled-submit-btn'); } }); //注册按钮 $('.register-form-submit').on('click',function(){ if($(this).hasClass('disabled-submit-btn')){ return false; } }); } bjsIndex.prototype.initC2c = function(){ var _this = this; //展开订单详情 $('.c2c-order-table').on('click','.open-order-btn',function(){ var $this = $(this); var $detail = $this.closest('tr').next().next(); if(!$detail.hasClass('order-detail-list')){ return false; } if($this.hasClass('close-order-btn')){ $this.removeClass('close-order-btn'); $detail.addClass('hide'); }else{ $this.addClass('close-order-btn'); $detail.removeClass('hide'); } }); //关闭订单过期提示 $('.c2c-order-table').on('click','.order-detail-warning-close',function(){ $(this).closest('.order-detail-warning').addClass('hide'); return false; }); //查看订单二维码 $('.c2c-order-table').on('click','.order-detail-qrcode',function(){ var src = $(this).data('img'); var img = new Image(); img.src = src; img.onload = function(){ layer.open({ title: '收款二维码' ,btnAlign: 'c' ,btn: '' ,content: '<img src="'+src+'" style="max-width: 300px; width: 100%;" />' }) } img.onerror = function(){ layer.msg('图片已损坏',{icon:0}) } return false; }); //订单状态切换 $('.c2c-order-title').on('click','a',function(){ return false; }); //submit 事件 $('.trading-buy').on('keyup','input',function(e){ if(e.keyCode == 13){ $('.trading-buy-btn').click(); } }); $('trading-sell').on('keyup','input',function(e){ if(e.keyCode == 13){ $('.trading-sell-btn').click(); } }); this.initClipboard(); } bjsIndex.prototype.initClipboard = function(){ //复制到剪贴板 var clipboard = new ClipboardJS('.copy-btn'); clipboard.on('success', function(e){ layer.msg('复制成功',{time:800,icon:1}); }); clipboard.on('error', function(e){ layer.msg('复制失败',{time:800,icon:2}); }); } bjsIndex.prototype.initPromotion = function(){ this.initClipboard(); } bjsIndex.prototype.initRecharge = function(){ this.initClipboard(); $('.select4').select2({ minimumResultsForSearch: -1, dropdownAutoWidth: true }); } bjsIndex.prototype.initGoogleAuthenticator = function(){ this.initClipboard(); //submit 事件 $('.form-input').on('keyup',function(e){ if(e.keyCode == 13){ $(this).closest('.default-form').find('.default-form-submit').trigger('click'); } }); } bjsIndex.prototype.initAuthentication = function(){ //submit 事件 $('.form-input').on('keyup',function(e){ if(e.keyCode == 13){ $(this).closest('.default-form').find('.default-form-submit').trigger('click'); } }); $('.select3').select2({ minimumResultsForSearch: -1, dropdownAutoWidth: true }); var $bank_card_pay = $('#bank-card-pay'), $alipay_pay = $('#alipay-pay'), $wechat_pay = $('#wechat-pay'); $('#choose-nationality').change(function(){ var val = this.value; switch(val){ case '01' : break; case '02' : break; case '03' : break; } }); } bjsIndex.prototype.initSetPay = function(){ //submit 事件 $('.form-input').on('keyup',function(e){ if(e.keyCode == 13){ $(this).closest('.default-form').find('.default-form-submit').trigger('click'); } }); $('.select3').select2({ minimumResultsForSearch: -1, dropdownAutoWidth: true }); var $bank_card_pay = $('#bank-card-pay'), $alipay_pay = $('#alipay-pay'), $wechat_pay = $('#wechat-pay'); $('#choose-pay').change(function(){ var val = this.value; switch(val){ case '01' : $bank_card_pay.removeClass('hide'); $alipay_pay.addClass('hide'); $wechat_pay.addClass('hide'); break; case '02' : $bank_card_pay.addClass('hide'); $alipay_pay.addClass('hide'); $wechat_pay.removeClass('hide'); break; case '03' : $bank_card_pay.addClass('hide'); $alipay_pay.removeClass('hide'); $wechat_pay.addClass('hide'); break; } }); //查看订单二维码 $(document).on('click','.order-detail-qrcode',function(){ var src = $(this).data('img'); var img = new Image(); img.src = src; img.onload = function(){ layer.open({ title: '收款二维码' ,btnAlign: 'c' ,btn: '' ,content: '<img src="'+src+'" style="max-width: 300px; width: 100%;" />' }) } img.onerror = function(){ layer.msg('请上传图片',{icon:0}) } return false; }); } bjsIndex.prototype.initArticle = function(){ $('.bjs-aboutUs').addClass('hide'); } bjsIndex.prototype.initVote = function(timer){ $('.vote-list').on('click','.vote-bi-check',function(){ var $this = $(this); if($this.text().trim() == '查看介绍'){ $this.text('收起介绍'); }else{ $this.text('查看介绍'); } $this.closest('li').find('.vote-bi-detail').slideToggle(300); }); var $timer = $('.vote-title-timer'); var time = 0; if(timer && !isNaN(timer)){ runTime(); } function runTime(){ var date = new Date().getTime(); if(date > timer){ return false; } time = timer - date; setInterval(function(){ run(); },1000); } function run(){ time -= 1000; var day = (time / (1000*60*60*24)) >> 0; var hours = ((time - day * (1000*60*60*24)) / (1000*60*60)) >> 0; var minutes = ((time - day * (1000*60*60*24) - hours * (1000*60*60)) / (1000*60)) >> 0; var seconds = ((time - day * (1000*60*60*24) - hours * (1000*60*60) - minutes * (1000*60)) / 1000) >> 0; var _html = '还剩:<em>'+day+'</em>天<em>'+hours+'</em>时<em>'+minutes+'</em>分<em>'+seconds+'</em>秒'; $timer.html(_html); } this.initVoteList(); } bjsIndex.prototype.initVoteList = function(){ this.initClipboard(); } bjsIndex.prototype.initCoins = function(){ var _this = this; _this.keywords = 'default'; //default logogram mvalue _this.$list = $('.coins-item')[0] ? $('.coins-list').clone() : null; $(document).on('click','.coins-search-list a',function(event){ event.preventDefault(); if(!_this.$list){ return false; } $(this).addClass('active').siblings().removeClass('active'); _this.keywords = $(this).data('keywords'); _this._toSortCoins(); }); var $input = _this.$input = $('.coins-search-box input[name="keywords"]'); if(!$input[0]){ return false; } var txt = $input.val().trim(); $input.on('keyup keydown change input',function(event){ var _txt = $(this).val().trim(); if(txt !== _txt){ txt = _txt; _this._toSearchCoins(txt); } }); } bjsIndex.prototype.initCoinsDetail = function(){ this.initIScroll(); var _this = this; _this.keywords = 'default'; //default logogram mvalue _this.$list = []; $(document).on('click','.coins-list-detail-search a',function(event){ event.preventDefault(); if(!_this.$list.length){ $('.bjs-tab-tbody').each(function(){ _this.$list.push($(this).clone()) }); } $('.coins-list-detail-search .active').removeClass('active'); $(this).addClass('active'); _this.keywords = $(this).data('keywords'); _this._toSortCoinsDetail(); }); //搜索 _this.initSearch(); } bjsIndex.prototype._toSortCoinsDetail = function(){ var _this = this; if(_this.keywords == 'default'){ $('.bjs-tab-tbody').each(function(index,item){ $(this).html(_this.$list[index].html()) }); _this.toSearch($('.coins-search-box input[name="keywords"]').val().trim()); return false; } var $list = _this.$list; $('.bjs-tab-tbody').each(function(){ var arr = []; $(this).children().each(function(){ arr.push({ el: this, keywords: $(this).data(_this.keywords) }); }); arr.insertSort(function(a,b){ return a.keywords < b.keywords; }); var $_html = $('<div></div>'); for(var i = 0; i < arr.length; i++){ $_html.append(arr[i].el); } $(this).html($_html.html()); }); } bjsIndex.prototype._toSearchCoins = function(txt){ console.log(txt) var _this = this; var $list = $('.coins-list .coins-item'); if($list[0]){ $list.each(function(){ var _txt = $(this).find('.coins-show').text(); txt = txt.replace(/\s/g,''); _txt = _txt.replace(/\s/g,''); var patt1 = new RegExp(txt,'i'); if(patt1.test(_txt)){ $(this).removeClass('hide'); }else{ $(this).addClass('hide'); } }); } } bjsIndex.prototype._toSortCoins = function(){ var _this = this; if(_this.keywords == 'default'){ $('.coins-list').html(_this.$list.html()); _this._toSearchCoins(_this.$input.val().trim()); return false; } var $list = _this.$list; var arr = []; $('.coins-list').children().each(function(){ arr.push({ el: this, keywords: $(this).data(_this.keywords) }); }); arr.insertSort(function(a,b){ return a.keywords < b.keywords; }); var $_html = $('<div></div>'); for(var i = 0; i < arr.length; i++){ $_html.append(arr[i].el); } $('.coins-list').html($_html.html()); } bjsIndex.prototype.initTrade = function(){ var _this = this; $('body').addClass('w1280'); $('.bjs-aboutUs').addClass('hide'); $('.header .window-wrap').removeClass('w1500'); $('.my-tab-head').on('click','a',function(event){ event.preventDefault(); var $this = $(this); if($this.hasClass('active')){ return false; } var index = $this.index(); var $unit = $this.closest('.my-tab-box').find('.my-tab-unit').eq(index); $this.addClass('active').siblings('.active').removeClass('active'); $unit.addClass('active').siblings('.active').removeClass('active'); var id = $unit.find('.my-tab-scroll-cont')[0].id; _this.refreshIScroll(id); }); this.initIScroll(); this.initSearch(); this.initStar(); this.initIndexSort(); //submit 事件 $('.trading-buy').on('keyup','input',function(e){ if(e.keyCode == 13){ $('.trading-buy-btn').click(); } }); $('trading-sell').on('keyup','input',function(e){ if(e.keyCode == 13){ $('.trading-sell-btn').click(); } }); } bjsIndex.prototype.initTradingView = function(){ /*TradingView.onready(function(){ var widget = window.tvWidget = new TradingView.widget({ // debug: true, // uncomment this line to see Library errors and warnings in the console //fullscreen: true, symbol: 'AAPL', interval: 'D', height:'100%', width: '100%', container_id: "tv_chart_container", // BEWARE: no trailing slash is expected in feed URL datafeed: new Datafeeds.UDFCompatibleDatafeed("https://demo_feed.tradingview.com"), library_path: "tradingview/charting_library/", locale: "zh", // Regression Trend-related functionality is not implemented yet, so it's hidden for a while drawings_access: { type: 'black', tools: [ { name: "Regression Trend" } ] }, disabled_features: [ "use_localstorage_for_settings", "left_toolbar", "header_widget_dom_node", "header_symbol_search", "header_resolutions", "header_chart_type", "header_undo_redo", "header_indicators", "header_settings", "header_fullscreen_button", "header_compare", "header_saveload", "header_screenshot" ], enabled_features: ["study_templates"], charts_storage_url: 'https://saveload.tradingview.com', charts_storage_api_version: "1.1", client_id: 'tradingview.com', user_id: 'public_user_id' }); });*/ } bjsIndex.prototype.initTradeProfession = function(){ this._initResizeWindow(); this.initTrade(); } bjsIndex.prototype._initResizeWindow = function(){ var _this = this; $(window).resize(resizeWindow); var $profession_page_left = $('.profession-page-left');//左栏 var $profession_page_right = $('.profession-page-right');//右栏 function resizeWindow(){ var height = $(window).height(); $profession_page_left.height(height); $profession_page_right.height(height); for(var i in _this.iscroll){ _this.refreshIScroll(i); } } resizeWindow(); } bjsIndex.prototype.refreshIScroll = function(id){ try{ this.iscroll[id].refresh(); }catch(e){ console.log(id+' is not iscroller !'); } } bjsIndex.prototype.initIScroll = function(){ this.iscroll = {}; var options = { mouseWheel: true, click: true, scrollX: false, mouseWheelSpeed: 10, scrollbars: 'custom',bounce: false ,disableTouch: true/*, disablePointer: true, disableMouse: true*/, preventDefault: false}; var _iscroll = [ 'article-wrap-iscroll', 'page-left-iscroll-wrap', 'my-tab-scroll-box-0', 'my-tab-scroll-box-1', 'my-tab-scroll-box-2', 'my-tab-scroll-box-3', 'my-tab-scroll-box-4', 'my-tab-scroll-box-6', 'my-tab-scroll-box-a', 'my-tab-scroll-box-b', 'my-tab-scroll-box-c', 'my-tab-scroll-box-d', 'my-tab-scroll-box-e', 'my-tab-scroll-box-f' ]; for(var i = 0; i < _iscroll.length; i++){ var $iscroll = $('#'+_iscroll[i]); if($iscroll[0]){ this.iscroll[_iscroll[i]] = new IScroll('#'+_iscroll[i], options); } } } bjsIndex.prototype.initRegisterSelect = function(){ function formatState(state){ var baseUrl = ""; var $state = $( '<span><img src="images/language.png" class="img-flag" /> ' + state.text + '</span>' ); return $state; } $(".select2").select2({ minimumResultsForSearch: -1, dropdownAutoWidth: true, templateResult: formatState }); $(".select3").select2({ minimumResultsForSearch: -1, dropdownAutoWidth: true, }); } bjsIndex.prototype.resetStar = function(){ var _this = this; $('.bjs-tab-tbody').find('.bjs-star').removeClass('star-cur'); for(var i in _this.fav){ if(_this.fav[i]){ $('.bjs-tab-tbody').find('[data-id="'+i+'"]').find('.bjs-star').addClass('star-cur'); } } } bjsIndex.prototype.initTradeStar = function(){ var _this = this; $('.bjs-tab-tbody').find('.bjs-star').removeClass('star-cur'); if(_this.userInfo.userId != ''){ _this.getStar(function(e){ if(e.code == '10000' && e.data.length){ _this.fav = {}; for(var i = 0; i < e.data.length; i++){ _this.fav[e.data[i].coin] = 1; $('.bjs-tab-tbody').find('[data-id="'+e.data[i].coin+'"]').find('.bjs-star').addClass('star-cur'); } } }); } } bjsIndex.prototype.initStar = function(){ var _this = this; _this.fav = {}; $('.bjs-tab-tbody').find('.bjs-star').removeClass('star-cur'); if(_this.userInfo.userId != ''){ _this.getStar(function(e){ if(e.code == '10000' && e.data.length){ for(var i = 0; i < e.data.length; i++){ _this.fav[e.data[i].coin] = 1; $('.bjs-tab-tbody').find('[data-id="'+e.data[i].coin+'"]').find('.bjs-star').addClass('star-cur'); } } }); } //收藏、移除 $('.bjs-tab-tbody').on('click','.bjs-star',function(){ if(_this.userInfo.userId == ''){ layer.msg('请登录',{icon:0}); return false; } var $this = $(this); var cid = $this.closest('.bjs-tab-tr').data('id'); if($(this).hasClass('star-cur')){ //执行删除操作 _this.removeStar(cid,function(){ _this.fav[cid] = 0; $this.removeClass('star-cur'); if($('.localStorage-star').hasClass('active')){ $this.closest('.bjs-tab-tr').addClass('hide'); } }); }else{ //执行添加操作 _this.addStar(cid,function(){ _this.fav[cid] = 1; $this.addClass('star-cur'); }); } }); //自选区 $('.bjs-tab-head').on('click','.localStorage-star',function(){ if(_this.userInfo.userId == ''){ layer.msg('请登录',{icon:0}); return false; } $('.bjs-tab-tbody .bjs-tab-tr').addClass('hide'); $(this).closest('ul').find('.active').removeClass('active').end().end().addClass('active'); for(var i in _this.fav){ if(_this.fav[i]){ $('.bjs-tab-tbody').find('[data-id="'+i+'"]').removeClass('hide'); } } }); //对CNYT交易区 $('.bjs-tab-head').on('click','a',function(){ if(!$(this).hasClass('active') && $(this).parent().index() == 0){ $('.bjs-tab-tbody .bjs-tab-tr').removeClass('hide'); $(this).closest('ul').find('.active').removeClass('active').end().end().addClass('active'); } }); } bjsIndex.prototype.getStar = function(callback){ var _this = this; _this.fetch(_this.localPath+_this.indexUrl.starGet,{userId:_this.userInfo.userId},'post','json',callback); } bjsIndex.prototype.addStar = function(cid,callback){ var _this = this; //_this.fav[cid] = 1; //localStorage.fav = JSON.stringify(_this.fav); //callback(); _this.fetch(_this.localPath+_this.indexUrl.starAdd,{userId:_this.userInfo.userId,coinType:cid},'post','json',callback); } bjsIndex.prototype.removeStar = function(cid,callback){ var _this = this; //_this.fav[cid] = 0; //localStorage.fav = JSON.stringify(_this.fav); //callback(); _this.fetch(_this.localPath+_this.indexUrl.starRemove,{userId:_this.userInfo.userId,coinType:cid},'post','json',callback); } bjsIndex.prototype.getBiInfo = function(){ var _this = this; _this.fetch(_this.localPath+_this.indexUrl.day3,{coinType:123},'post','json',function(e){ if(e.data && e.data.length){ _this.getBiInfoData = e.data; _this.initCanvas(_this.getBiInfoData); }else{ console.log(e.msg); } }); } bjsIndex.prototype.initFontSize = function(){ var windowWidth = $('body').width(); this.fontSize = windowWidth > 1500 ? 10 : (windowWidth < 1200 ? 12000/1500 : windowWidth*10/1500); $('html').css({ 'fontSize': this.fontSize*10 + 'px' }); } bjsIndex.prototype.initSearch = function(){ var $input = $('.bjs-search-box input'); if(!$input[0]){ return false; } var txt = $input.val().trim(); var _this = this; $input.on('keyup keydown change input',function(){ var _txt = $(this).val().trim(); if(txt !== _txt){ txt = _txt; _this.toSearch(txt); } }); } bjsIndex.prototype.toSearch = function(txt){ var _this = this; var $list = $('.bjs-tab-tbody .bjs-tab-tr'); if($list[0]){ $list.each(function(){ var _txt = $(this).find('.bjs-bi-icon').text(); txt = txt.replace(/\s/g,''); _txt = _txt.replace(/\s/g,''); var patt1 = new RegExp(txt,'i'); if(patt1.test(_txt)){ $(this).removeClass('hide'); }else{ $(this).addClass('hide'); } _this.refreshIScroll('page-left-iscroll-wrap'); }); } } bjsIndex.prototype.initBanner = function(){ if(!$('.slider6')[0]){ return false; } $('.slider6').bxSlider({ mode: 'fade', slideMargin: 0, captions: true,//自动控制 auto: true, controls: false//隐藏左右按钮 }); } bjsIndex.prototype.initCanvas = function(data){ var _this = this; $('.bjs-tab-tbody canvas').each(function(index,obj){ var id = $(obj).closest('.bjs-tab-tr').data('id'); for(var i = 0; i < data.length; i++){ if(data[i].coin === id){ _this.drawCnvas(obj,data[i].marketData); } } }); } bjsIndex.prototype.drawCnvas = function(obj,strData){ var _this = this; var skin = $.cookies.get('skin') || 'black'; //strData = "[1,2,3]";//字符串转化为数组 var data = strData.replace(/[\[\]\s]/g,''); var arr = data.split(','); var status = arr[0] - arr[arr.length - 1]; var canvas2 = Charts({ el: obj, data:arr, styleSet:{ lineColor: status < 0 ? _this.styleSet[skin].lineColor[0] : _this.styleSet[skin].lineColor[1],//蓝 : 红 topColor: status < 0 ? _this.styleSet[skin].topColor[0] : _this.styleSet[skin].topColor[1], bottomColor: status < 0 ? _this.styleSet[skin].bottomColor[0] : _this.styleSet[skin].bottomColor[1], } }); } bjsIndex.prototype.getUserInfo = function(){ var info = { userId: '' }; $.ajax({ url: "/login/getuid/t/"+Math.ceil(Math.random()*1000000000000), data: {}, dataType: 'json', type: 'get', async: false, success: function(result){ if(result.userid){ info.userId = result.userid; } } }); console.log(info) return info; } bjsIndex.prototype.initSkin = function(){ var _this = this; var skin = $.cookies.get('skin') || 'black'; if(skin == 'white'){ $('.style-box').find('.style-white').addClass('active'); }else{ $('.style-box').find('.style-black').addClass('active'); $('#style-white').remove(); if(typeof layer != 'undefined'){ layer.config({ extend: 'myskin/style.css', //加载您的扩展样式 skin: 'myskin' }); } } $(document).on('click','.style-white,.style-black',function(){ if($(this).hasClass('active')){ $(this).removeClass('change'); return false; } $(this).addClass('active').siblings('.active').removeClass('active'); $(this).addClass('change').siblings('.change').removeClass('change'); if($(this).hasClass('style-white')){ $.cookies.set('skin','white',{expires: 30,path: "/"}); var link = document.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = _this.resourcesPath + 'css/white.css'; link.id = 'style-white'; $('head').append(link); layer.config({ extend: '', //加载您的扩展样式 skin: '' }); }else{ $.cookies.set('skin','black',{expires: 30,path: "/"}); $('#style-white').remove(); layer.config({ extend: 'myskin/style.css', //加载您的扩展样式 skin: 'myskin' }); } }); } bjsIndex.prototype.initLanguage = function(){ $(document).on('click','.lang-option a',function(){ var language = $(this).data('language'); if($.cookies.get('think_language') == language){ return false; } $.cookies.set('think_language',language,30); window.location.reload(); }); } bjsIndex.prototype.initNotice = function(title,str,btn,maxWidth,cookie){ var bjsNotice = $.cookies.get(cookie); if(!bjsNotice){ layer.closeAll(); setTimeout(function(){ layer.open({ maxWidth: maxWidth ,title: title ,content: str ,btn: btn ,btnAlign: 'c' ,yes: function(index){ layer.close(index); $.cookies.set(cookie,1,30); } }); },100); } } bjsIndex.prototype.initProgress = function(callback){ if(!$('.bjs-progress')[0]){ return false; } var state = false, click = false; var left = 0, width = 0; var $this; $('.bjs-progress').on('mousedown','.progress-box',function(event){ event.preventDefault(); $this = $(this); state = false; click = false; width = $(this).width(); left = $(this).offset().left; if(event.target.className == 'progress-btn'){ state = true; }else{ click = true; } }); $('.bjs-progress').on('mouseup','.progress-box',function(event){ event.preventDefault(); if(click){ //点击选择 var _left = event.pageX; var x = _left - left; // move s var _width = x / width * 100; _width = _width < 0 ? 0 : (_width > 100 ? 100 : _width>>0); $this.find('.progress-left').css('width',_width+'%'); $this.find('.progress-btn').css('left',_width+'%'); $this.siblings('.progress-num').html(_width+'%'); $this.siblings('.progress-num-input').val(_width); callback($this); } }); $(document).on('mousemove',function(event){ if(state){ event.preventDefault(); //触发拖拽 var _left = event.pageX; var x = _left - left; var _width = x / width * 100; _width = _width < 0 ? 0 : (_width > 100 ? 100 : _width>>0); $this.find('.progress-left').css('width',_width+'%'); $this.find('.progress-btn').css('left',_width+'%'); $this.siblings('.progress-num').html(_width+'%'); $this.siblings('.progress-num-input').val(_width); callback($this); } }); $(document).on('mouseup',function(event){ state = false; click = false; }); } bjsIndex.prototype.fetch = function(url,data,type,dataType,success,error){ $.ajax({ url: url, data: data, dataType: dataType, type: type, success: success, error: error }); } return bjsIndex; })();<file_sep><?php /** * Created by PhpStorm. * User: BBB * Date: 2018/8/4 * Time: 9:46 */ namespace Home\Controller; class MarketController extends HomeController { public function index(){ $marketsy = C('market'); foreach ($marketsy as $key => $val) { $tmp[$key] = $val['id']; } array_multisort($tmp,SORT_ASC,$marketsy); foreach ($marketsy as $k => $v) { $data[$k]['xnb'] = strtoupper(explode('_', $v['name'])[0]); $data[$k]['rmb'] = strtoupper(explode('_', $v['name'])[1]); $data[$k]['url'] = str_replace("cny","cnyt",$v['name']); $data[$k]['title'] = str_replace("CNY","CNYT",$v['title']); $data[$k]['img'] = $v['xnbimg']; $data[$k]['new_price'] = $v['new_price']; $data[$k]['main_coin'] = $v['main_coin']; $data[$k]['volume'] = $v['volume']; $data[$k]['mname'] = $v['mname']; $data[$k]['name'] = $v['name']; $data[$k]['volumes'] = round($v['volume']*$v['new_price'],2); //$data[$k]['change'] = $v['change']>0 "+".$v['change']:$v['change']; if($v['change']>0){ $data[$k]['change'] = "+".round($v['change'],2); }else{ $data[$k]['change'] = round($v['change'],2); } if($v['change']<0) $data[$k]['class']="red"; } $this->assign('lists', $data); $this->display(); } }<file_sep><?php namespace Common\Model; class MoneyModel extends \Think\Model { protected $keyS = 'Money'; } ?>
690e8d3d7b07a10e7958e186ae82b62169dd36fb
[ "JavaScript", "HTML", "PHP" ]
29
PHP
huangli0277/chibi
86985fd855a61049788c5ab154d89af87f465d10
03ab1a912d3354440911118cdc60b2094aadaf8d
refs/heads/main
<repo_name>bobbymahaffey/web_development_labs<file_sep>/Weeks/Week7/Controllers/StudentController.cs using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using Database; namespace webapi.Controllers { [Route("api/[controller]")] [ApiController] public class StudentController : ControllerBase { private readonly SchoolContext _dbContext; public StudentController(SchoolContext dbContext) { _dbContext = dbContext; } [HttpGet] public ActionResult<List<Product>> GetAllProducts() { var result = _dbContext.Product.ToList(); return Ok(result); } [HttpGet("{studentId}")] public ActionResult<Student> GetStudent(int studentId) { var student = _dbContext.Student .SingleOrDefault(p => p.StudentId == studentId); if (student != null) { return student; } else { return NotFound(); } } [HttpPost] public ActionResult<Student> AddStudent(Student student) { _dbContext.Student.Add(student); _dbContext.SaveChanges(); // return CreatedAtAction(nameof(GetProduct), new { id = product.ProductId }, product); return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status201Created); } [HttpDelete("{studentId}")] public ActionResult DeleteStudent(int studentId) { var student = new Student { StudentId = studentId }; _dbContext.Student.Attach(student); _dbContext.Student.Remove(student); _dbContext.SaveChanges(); return Ok(); } [HttpPut("{studentId}")] public ActionResult UpdateStudent(int studentId, Student studentUpdate) { var student = _dbContext.Student .SingleOrDefault(p => p.StudentId == studentId); if (student != null) { student.Name = studentUpdate.Name; student.Price = studentUpdate.Price; student.Count = studentUpdate.Count; _dbContext.Update(student); _dbContext.SaveChanges(); } return NoContent(); } } }
addcd7297c5527f7191cae31b972da4cefe39504
[ "C#" ]
1
C#
bobbymahaffey/web_development_labs
0c9f4f46d09928e7afefaabf8f7344e2e6807b44
7fe98414f89bf6f32cfda6ac828ca125310b76dc
refs/heads/master
<file_sep>module.exports = { 'url': 'mongodb://localhost/node-passport' }<file_sep>// expose our config directly to our application using module.exports module.exports = { //https://developers.facebook.com/ 'facebookAuth': { 'clientID': '1675914896001421', 'clientSecret': '7fe0217711792f908161a1efb4711842', 'callbackURL': 'http://localhost:8080/auth/facebook/callback' }, //https://dev.twitter.com/ 'twitterAuth': { 'consumerKey': '<KEY>', 'consumerSecret': '<KEY>', 'callbackURL': 'http://localhost:8080/auth/twitter/callback' }, //console.developer.google.com or https://console.cloud.google.com 'googleAuth': { 'clientID': '87668141240-tiqv5uie7i0oe8nq2tlrr10qu6jkd1pa.apps.googleusercontent.com', 'clientSecret': '<KEY>', 'callbackURL': 'http://localhost:8080/auth/google/callback' } };
b8cbf25afd18d739c571cc33757f61e9e230c297
[ "JavaScript" ]
2
JavaScript
xilenomg/node-passportjs
c6bbac4c4fb65973573a4f2473727765cecdd5b4
97aecd7418d607b811dd7590d085336a1f756f1c
refs/heads/master
<file_sep># gorm-postgresql-sample Connects AWS RDS PostgreSQL with Gorm <file_sep>package main import ( "database/sql" "fmt" "log" "time" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" _ "github.com/lib/pq" ) type artist struct { gorm.Model id int name string description string image_url string rating float64 } /* func initDBGorm() { var err error db, err := gorm.Open("postgres", "host=grandline.clclpmbitplj.ap-southeast-1.rds.amazonaws.com user=kaidou dbname=grandline_app sslmode=disable password=<PASSWORD>$ connect_timeout=5") if err != nil { panic(err) } //db.LogMode(true) log.Printf("Connected") defer db.Close() db.AutoMigrate(&artist{}) var art artist rows := db.First(&art, 1) //fmt.Fprintln(rows) log.Printf("DB ok!") //handleRows(rows, err) } */ func initDB() { var err error now := time.Now() defer func() { log.Printf("Exited after %v", time.Since(now)) }() log.Printf("Opening...") db, err := sql.Open("postgres", "host=grandline.clclpmbitplj.ap-southeast-1.rds.amazonaws.com user=kaidou dbname=grandline_app sslmode=disable password=<PASSWORD>line connect_timeout=5") defer db.Close() if err != nil { log.Print(err) return } log.Printf("Opened, pinging...") err = db.Ping() if err != nil { log.Print(err) return } log.Printf("Ping ok!") rows, err := db.Query("select * from artist where rating > $1", 4) handleRows(rows, err) } func handleRows(rows *sql.Rows, err error) { if err != nil { log.Fatal(err) } defer rows.Close() artists := []artist{} for rows.Next() { a := artist{} err := rows.Scan(&a.id, &a.name, &a.description, &a.image_url, &a.rating) if err != nil { log.Println(err) continue } artists = append(artists, a) } if err := rows.Err(); err != nil { log.Fatal(err) } fmt.Println(artists) } func main() { //db, err := sql.Open("postgres", "postgres://kaidou:Seizetheday24$@grandline.cl<EMAIL>.ap-southeast-1.rds.amazonaws.com:5432/grandline_app?sslmode=verify-full") initDB() //initDBGorm() /* http.HandleFunc("/",func(w http.ResponseWriter, r *http.Request){ fmt.Fprintf(w, "Hello Web Development!") }) fmt.Println(http.ListenAndServe(":8000",nil)) */ }
ba78a39b0d13b9706a3c920e3178bf086ed7ae27
[ "Markdown", "Go" ]
2
Markdown
RahadianArthapati/gorm-postgresql-sample
13d9b8c71a06ada5568f76694f51e4f9c7e34cac
60cf9f12f1bfdaa3aca397c6e69533b4e5a87fd5
refs/heads/master
<repo_name>s-owl/ssslackbot<file_sep>/plugins/geo.py from slackbot.bot import listen_to from slackbot.bot import respond_to import requests @respond_to('위치 (.*)') @listen_to('!위치 (.*)') def geo(message, address): r = requests.get('https://maps.googleapis.com/maps/api/geocode/json', {'address': address}) loc = r.json()['results'][0]['geometry']['location'] message.send(str(loc)) <file_sep>/requirements.txt slackbot>=0.4.1 python-forecastio>=1.3.5 yandex.translate>=0.3.5 <file_sep>/slackbot_settings.py # Need ENV : SLACKBOT_API_TOKEN, DARKSKY_API, AQICN_API import os DEFAULT_REPLY = "몰라" ERROR_TO = 'junsu' PLUGINS = [ 'plugins.example', 'plugins.weather', 'plugins.reactions', 'plugins.geo', 'plugins.dust', 'plugins.filter', ] try: DARKSKY_API = os.environ['DARKSKY_API'] AQICN_API = os.environ['AQICN_API'] YANDEX_TRANSLATE_API = os.environ['YANDEX_TRANSLATE_API'] except KeyError: pass <file_sep>/plugins/example.py from slackbot.bot import respond_to from slackbot.bot import listen_to @respond_to('안녕') def hi(message): message.reply('안녕') message.react('+1') @respond_to('test') @respond_to('테스트') def bot(message): message.send('나 불렀니?') <file_sep>/plugins/weather.py from slackbot.bot import respond_to from slackbot.bot import listen_to from slackbot_settings import DARKSKY_API import requests import forecastio @respond_to('weather (.*)') @listen_to('!weather (.*)') @respond_to('날씨 (.*)') @listen_to('!날씨 (.*)') @respond_to('天气 (.*)') @listen_to('!天气 (.*)') def weather(message, address): r = requests.get('https://maps.googleapis.com/maps/api/geocode/json', {'address': address}) loc = r.json()['results'][0]['geometry']['location'] forecast = forecastio.load_forecast( DARKSKY_API, loc['lat'], loc['lng'], ) data = forecast.currently() string = f"현재 `{address}`의 날씨입니다.\n" \ f"{forecast.hourly().summary}\n" \ f"\n온도: `{str(data.temperature)}℃`\n" \ f"\n기상: `{data.summary}`\n" \ f"\n풍속: `{str(round(data.windSpeed, 1))}m/s`" message.send(string) <file_sep>/plugins/filter.py from slackbot.bot import listen_to from yandex_translate import YandexTranslate from slackbot_settings import YANDEX_TRANSLATE_API translate = YandexTranslate(YANDEX_TRANSLATE_API) @listen_to('^(?!!)(.*[\u4e00-\u9fff]+.*)') def chinese(message, *arg): string = translate.translate(arg[0],'zh-ko') message.send(string['text'][0]) <file_sep>/README.md # ssslackbot 성공회대학교 소모임 sss의 slack에서 사용하는 채팅봇입니다. ## Requirements - git - python3.6 - environment variable - SLACKBOT_API_TOKEN (slack에서 bot을 추가하고 해당 token을 저장합니다.) - DARKSKY_API (날씨 plugin을 위해서 darksky에서 api를 받습니다.) - AQICN_API (공기 plugin을 위해서 aqicn에에서 api를 받습니다.) ## Usage ```bash git clone https://github.com/vaporize93/ssslackbot cd ssslackbot pip install -r requirements.txt python3 run.py ``` ## Deploy ```bash docker build -t ssslackbot . docker run --name user/ssslackbot \ --env="SLACKBOT_API_TOKEN=<your_token>" \ --env="DARKSKY_API=<your_token>" \ --env="AQICN_API=<your_token>" \ -d ssslackbot ``` ## Contribution Plugin을 작성해서 PR을 넣어주세요. Plugin은 [slackbot](https://github.com/lins05/slackbot)에서 많은 부분을 참고할 수 있습니다. <file_sep>/plugins/dust.py from slackbot.bot import listen_to from slackbot.bot import respond_to from slackbot_settings import AQICN_API import requests @respond_to('air (.*)') @listen_to('!air (.*)') @respond_to('공기 (.*)') @listen_to('!공기 (.*)') @respond_to('空气 (.*)') @listen_to('!空气 (.*)') def dust(message, address): r = requests.get('https://maps.googleapis.com/maps/api/geocode/json', {'address': address}) loc = r.json()['results'][0]['geometry']['location'] url = 'https://api.waqi.info/feed/geo:' + str(loc['lat']) + ';' + str(loc['lng']) + '/' d = requests.get(url, {'token': AQICN_API}) aqi = d.json()['data']['aqi'] if aqi <= 50: grade = "좋음(대기오염 관련 질환자군에서도 영향이 유발되지 않을 수준)" elif 50 < aqi <= 100: grade = "보통(환자군에게 만성 노출시 경미한 영향이 유발될 수 있는 수준)" elif 100 < aqi <= 150: grade = "민감군 영향(환자군 및 민감군에게 유해한 영향이 유발될 수 있는 수준)" elif 150 < aqi <= 200: grade = "나쁨(환자군 및 민감군[어린이, 노약자 등]에게 유해한 영향 유발, 일반인도 건강산 불쾌감을 경험할 수 있는 수준)" elif 200 < aqi <= 300: grade = "매우 나쁨(환자군 및 민감군에게 급성 노출시 심각한 영향 유발, 일반인도 약한 영향이 유발될 수 있는 수준)" elif aqi >= 300: grade = "위험(환자군 및 민감군에게 응급 조치가 발생되거나, 일반인에게 유해한 영향이 유발될 수 있는 수준)" message.send(f'현재 `{address}`의 대기 품질 지수(AQI)는 `{aqi}`이며 현재 대기상황 `{grade}`입니다.') <file_sep>/Dockerfile FROM python:latest MAINTAINER <NAME> <<EMAIL>> ENV DEBIAN_FRONTEND=noninteractive RUN apt-get update && apt-get upgrade -y # Timezone ENV TZ=Asia/Seoul RUN echo $TZ | tee /etc/timezone RUN dpkg-reconfigure --frontend noninteractive tzdata ADD requirements.txt /src/ WORKDIR /src RUN pip install -r requirements.txt ADD run.py slackbot_settings.py /src/ ADD plugins /src/plugins CMD ["python", "./run.py"] <file_sep>/plugins/reactions.py from slackbot.bot import listen_to from slackbot.bot import respond_to @respond_to('(ㅋ*)$') @listen_to('(ㅋ*)$') def laugh(message, arg): k = arg.count('ㅋ') if k > 5: message.send('ㅋ'*(k+2)) @respond_to(':parrot:') @listen_to(':parrot:') def parrot(message): message.send(':parrot:')
96d470d2c92120a7a9568ba015501ff1723ac0f6
[ "Markdown", "Python", "Text", "Dockerfile" ]
10
Python
s-owl/ssslackbot
d3c393d4e8a99c52004b4b138a25dc4c3ee2e70b
7149522baa0ad15fbde6592935e58a7a54a17a63
refs/heads/main
<repo_name>qq995931576/JavaWeb<file_sep>/README.md # JavaWeb JavaWeb学习 <br> https://www.bilibili.com/video/BV1Y7411K7zz?p=1 <file_sep>/book--Version.JavaEE/src/main/java/com/achang/dao/impl/UserDaoImpl.java package com.achang.dao.impl; import com.achang.bean.User; import com.achang.dao.UserDao; /****** @author 阿昌 @create 2020-11-25 23:30 ******* */ public class UserDaoImpl extends BaseDao implements UserDao { @Override public User queryUserByUsername(String username) { String sql = "select id,username,password,email from t_user where username = ?"; return (User) queryForOne(User.class,sql,username); } @Override public int saveUser(User user) { String sql = "insert into t_user(username,password,email)values(?,?,?)"; return update(sql,user.getUsername(),user.getPassword(),user.getEmail()); } @Override public User queryUserByUsernameAndPassword(String username, String password) { String sql = "select id,username,password,email from t_user where username = ? And password = ?"; return (User) queryForOne(User.class,sql,username,password); } } <file_sep>/book--Version.JavaEE/src/main/java/jdbc.properties username=root password=<PASSWORD> url=jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf8 driverClassName=com.mysql.jdbc.Driver initialSize=5 maxActive=10<file_sep>/book--Version.JavaEE/src/main/java/com/achang/dao/impl/OrderDaoImpl.java package com.achang.dao.impl; import com.achang.bean.Order; import com.achang.dao.OrderDao; /****** @author 阿昌 @create 2020-12-02 12:00 ******* */ public class OrderDaoImpl extends BaseDao implements OrderDao { @Override public int saveOrder(Order order) { String sql ="insert into t_order(order_id,create_time,price,status,user_id) value(?,?,?,?,?)"; return update(sql,order.getOrderId(),order.getCreateTime(),order.getPrice(),order.getStatus(),order.getUserId()); } } <file_sep>/book--Version.JavaEE/src/main/java/com/achang/web/UserServlet.java package com.achang.web; import com.achang.bean.User; import com.achang.service.impl.UserServiceImpl; import com.achang.utils.WebUtils; import com.google.gson.Gson; import org.apache.commons.beanutils.BeanUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Hashtable; import java.util.Map; import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY; /****** @author 阿昌 @create 2020-11-28 13:40 ******* */ public class UserServlet extends BaseServlet { private UserServiceImpl userService = new UserServiceImpl(); //登录处理 protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1.获取请求参数 String username = req.getParameter("username"); String password = req.getParameter("<PASSWORD>"); //2.调用 userService.Login()登录处理业务 User loginUser = userService.login(new User(0, username, password, null)); //3.根据login()方法返回结果判断登录是否成功 if (loginUser ==null){ //4.如果等于null,登入失败 //把错误信息,和回显的表单项信息,保存到Request域中 req.setAttribute("msg","用户名或密码错误!"); req.setAttribute("username",username); //5.转跳login登入页面 req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp); }else { System.out.println("登录成功"); //保存用户登录的信息到Session域中 req.getSession().setAttribute("user",loginUser); //6.不为null,登入成功,跳转login_success页面 req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp); } } //注册处理 protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1.获取请求的参数 String username = req.getParameter("username"); String password = req.getParameter("<PASSWORD>"); String email = req.getParameter("email"); // 获取 Session 中的验证码 String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY); // 删除 Session 中的验证码 req.getSession().removeAttribute(KAPTCHA_SESSION_KEY); String code = req.getParameter("code"); User user = WebUtils.copyParamToBean(req.getParameterMap(), new User()); //2.检查验证码是否正确,先写死,要求,验证码为:abcde if ( (token.equalsIgnoreCase(code)) && (token != null) ){ //检查用户名是否可用 if (userService.existsUsername(username)){ //把错误信息,和回显的表单项信息,保存到Request域中 req.setAttribute("errorMsg","用户名已存在"); req.setAttribute("username",username); req.setAttribute("email",email); //跳转到注册页面 req.getRequestDispatcher("pages/user/regist.jsp").forward(req,resp); }else { //调用Service保存到数据库 userService.registUser(new User(0,username,password,email)); //跳转到注册成功页面 req.getRequestDispatcher("pages/user/regist_success.jsp").forward(req,resp); } }else { //把回显信息,保存到Request域中 req.setAttribute("errorMsg","验证码错误!!!"); req.setAttribute("username",username); req.setAttribute("email",email); //跳转到注册页面 System.out.println("验证码 ["+code+"] 错误"); req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp); } } //注销处理 protected void logOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1、销毁Seesion中用户登录的信息(或销毁Session) req.getSession().invalidate(); // 2、重定向到首页或登录页面。 resp.sendRedirect(req.getContextPath()); } protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1、获取请求参数username String username = req.getParameter("username"); //2、调用userService.existUsername(); boolean existsUsername = userService.existsUsername(username); //把返回的结果封装成Map对象 Map<String,Object> map = new Hashtable<>(); map.put("existsUsername",existsUsername); Gson gson = new Gson(); String mapJson = gson.toJson(map); resp.getWriter().write(mapJson); } } <file_sep>/json_ajax_i18n-12/src/main/resources/i18n_zh_CN.properties username=\u7528\u6237\u540D password=\<PASSWORD> sex=\u6027\u522B age=\u5E74\u9F84 regist=\u6CE8\u518C boy=\u7537 girl=\u5973 email=\u90AE\u7BB1 reset=\u91CD\u7F6E submit=\u63D0\u4EA4<file_sep>/book--Version.JavaEE/src/main/java/com/achang/test/JDBCUtilsTest.java package com.achang.test; import com.achang.utils.JDBCUtils; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; /****** @author 阿昌 @create 2020-11-25 17:06 ******* */ public class JDBCUtilsTest { // @Test // public void testGetConnection() throws SQLException { // for (int i=0;i<100;i++){ // Connection conn = JDBCUtils.getConnection(); // System.out.println(conn);//com.mysql.jdbc.JDBC4Connection@9f70c54 // JDBCUtils.closeConnection(conn); // // } // // // } } <file_sep>/servlet-7/src/main/java/com/achang/servlet/RequestAPIServlet.java package com.achang.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author 阿昌 * @create 2020-11-04 22:27 */ public class RequestAPIServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ①getRequestURI() 获取请求的URI资源路径地址 System.out.println("URI => " + request.getRequestURI()); ///servlet_7/requestAPIServlet // ②getRequstURL() 获取请求的统一资源定位符(绝对路径) System.out.println("UIL => " + request.getRequestURL()); //http://localhost:8080/servlet_7/requestAPIServlet // ③getRemoteHost() 获取客户端的ip地址 /* 在IDEA中,使用 localhost 访问时,得到的客户端ip地址是 --->>> 127.0.0.1 <br/> 在IDEA中,使用 127.0.0.1 访问时,得到的客户端ip地址是 --->>> 127.0.0.1 <br/> 在IDEA中,使用 真实ip 访问时,得到的客户端ip地址是 --->>> 真实的ip地址 */ System.out.println("客户端ip地址 => " + request.getRemoteHost());//127.0.0.1 // ④getHeader() 获取请求头 System.out.println("请求头User-Agent =>>> " + request.getHeader("User-Agent")); // ⑤getMethod() 获取请求的方式GET或POST System.out.println("请求的方式 ->>> " + request.getMethod()); } } <file_sep>/book--Version.JavaEE/src/main/java/com/achang/service/impl/BookServiceImpl.java package com.achang.service.impl; import com.achang.bean.Book; import com.achang.bean.Page; import com.achang.dao.BookDao; import com.achang.dao.impl.BookDaoImpl; import com.achang.service.BookService; import java.util.List; /****** @author 阿昌 @create 2020-11-28 20:37 ******* */ public class BookServiceImpl implements BookService { private BookDao bookDao = new BookDaoImpl(); @Override public Page<Book> page(int pageNo, int pageSize) { Page<Book> page = new Page<>(); //设置每页显示数量 page.setPageSize(pageSize); //求总记录数 Integer pageToalCount = bookDao.queryForPageTotalCount(); //设置总记录数 page.setPageTotalCount(pageToalCount); //求总页码 int pageTotal = pageToalCount/pageSize; if (pageToalCount % pageSize > 0 ){ pageTotal+=1; } //设置总页码 page.setPageTotal(pageTotal); //设置当前页码 page.setPageNo(pageNo); //求当前页数据的开始索引 int begin = (page.getPageNo()-1) * pageSize; //求当前页数据 List<Book> items = bookDao.queryForItems(begin,pageSize); //设置当前页数据 page.setItems(items); return page; } @Override public void addBook(Book book) { bookDao.addBook(book); } @Override public void deleteBookById(int id) { bookDao.deleteBook(id); } @Override public void updateBook(Book book) { bookDao.updateBook(book); } @Override public Book queryBookById(int id) { return bookDao.queryBookById(id); } @Override public List<Book> queryBooks() { return bookDao.queryBooks(); } @Override public Page<Book> pageByPrice(int pageNo, int pageSize, int min, int max) { Page<Book> page = new Page<>(); //设置每页显示数量 page.setPageSize(pageSize); //求总记录数 Integer pageToalCount = bookDao.queryForPageTotalCountByPrice(min,max); //设置总记录数 page.setPageTotalCount(pageToalCount); //求总页码 int pageTotal = pageToalCount/pageSize; if (pageToalCount % pageSize > 0 ){ pageTotal+=1; } //设置总页码 page.setPageTotal(pageTotal); //设置当前页码 page.setPageNo(pageNo); //求当前页数据的开始索引 int begin = (page.getPageNo()-1) * pageSize; //求当前页数据 List<Book> items = bookDao.queryForItemsByPrice(begin,pageSize,min,max); //设置当前页数据 page.setItems(items); return page; } } <file_sep>/book--Version.JavaEE/src/main/java/com/achang/test/UserDaoTest.java package com.achang.test; import com.achang.bean.User; import com.achang.dao.impl.UserDaoImpl; import org.junit.Test; import static org.junit.Assert.*; /****** @author 阿昌 @create 2020-11-25 23:48 ******* */ public class UserDaoTest { UserDaoImpl userDao = new UserDaoImpl(); @Test public void queryUserByUsername() { if (userDao.queryUserByUsername("admin")==null){ System.out.println("用户名可用"); }else { System.out.println("用户名已存在"); } } @Test public void saveUser() { System.out.println(userDao.saveUser(new User(1,"achang999","915456","<EMAIL>"))); } @Test public void queryUserByUsernameAndPassword() { if (userDao.queryUserByUsernameAndPassword("admin","admin")==null){ System.out.println("用户名或密码错误,登入失败"); }else { System.out.println("登入成功"); } } }<file_sep>/book--Version.JavaEE/src/main/java/com/achang/dao/OrderItemDao.java package com.achang.dao; import com.achang.bean.Order; import com.achang.bean.OrderItem; /****** @author 阿昌 @create 2020-12-02 11:59 ******* */ public interface OrderItemDao { public int saveOrderItem(OrderItem orderItem); } <file_sep>/json_ajax_i18n-12/src/main/java/com/achang/json/PersonListType.java package com.achang.json; import com.achang.bean.Person; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.List; /****** @author 阿昌 @create 2020-12-03 17:10 ******* */ public class PersonListType extends TypeToken<List<Person>> { } <file_sep>/book--Version.JavaEE/src/main/java/com/achang/dao/BookDao.java package com.achang.dao; import com.achang.bean.Book; import java.util.List; /****** @author 阿昌 @create 2020-11-28 19:50 ******* */ public interface BookDao { public int addBook(Book book); public int deleteBook(Integer id); public int updateBook(Book book); public Book queryBookById(Integer id); public List<Book> queryBooks(); public Integer queryForPageTotalCount(); public List<Book> queryForItems(int begin, int pageSize); Integer queryForPageTotalCountByPrice(int min, int max); List<Book> queryForItemsByPrice(int begin, int pageSize, int min, int max); } <file_sep>/book--Version.JavaEE/src/main/java/com/achang/web/ClientBookServlet.java package com.achang.web; import com.achang.bean.Book; import com.achang.bean.Page; import com.achang.service.BookService; import com.achang.service.impl.BookServiceImpl; import com.achang.utils.WebUtils; import org.omg.CORBA.PUBLIC_MEMBER; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /****** @author 阿昌 @create 2020-11-30 15:50 ******* */ public class ClientBookServlet extends BaseServlet{ private BookService bookService = new BookServiceImpl(); public void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1、获取请求的参数 pageNo和pageSize int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1); int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE); //2、调用BookService.page(pageNo,pageSize) --->page对象 Page<Book> page = bookService.page(pageNo, pageSize); //设置客户端分页条地址 page.setUrl("client/bookServlet?action=page"); //3、保存到Request域中 req.setAttribute("page",page); //4、请求转发到/pages/manager/book_manager.jsp页面 req.getRequestDispatcher("/pages/client/index.jsp").forward(req,resp); } public void pageByPrice(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1、获取请求的参数 pageNo和pageSize int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1); int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE); int min = WebUtils.parseInt(req.getParameter("min"),0); int max = WebUtils.parseInt(req.getParameter("max"),Integer.MAX_VALUE); //2、调用BookService.page(pageNo,pageSize) --->page对象 Page<Book> page = bookService.pageByPrice(pageNo, pageSize,min,max); StringBuilder sb = new StringBuilder("client/bookServlet?action=pageByPrice&"); //如果有最小价格的参数,追加到分页条的地中参数中 if (req.getParameter(("min"))!=null){ sb.append("&min=").append(req.getParameter("min")); } //如果有最大价格的参数,追加到分页条的地中参数中 if (req.getParameter(("max"))!=null){ sb.append("&max=").append(req.getParameter("max")); } //设置客户端分页条地址 page.setUrl(sb.toString()); //3、保存到Request域中 req.setAttribute("page",page); //4、请求转发到/pages/manager/book_manager.jsp页面 req.getRequestDispatcher("/pages/client/index.jsp").forward(req,resp); } } <file_sep>/servlet-7/src/main/java/com/achang/servlet2/Servlet2.java package com.achang.servlet2; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author 阿昌 * @create 2020-11-05 19:34 */ public class Servlet2 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取请求的参数(办事的资料) 查看 String username = req.getParameter("username"); System.out.println("在Servlet2(柜台2)中查看参数(材料)+ " + username); //查看 柜台1 是否有盖章 Object key = req.getAttribute("key"); System.out.println("柜台1是否有盖章 " + key); //处理自己的业务 System.out.println("Servlet2处理自己的业务"); } } <file_sep>/book--Version.JavaEE/src/main/java/com/achang/test/OrderDaoImplTest.java package com.achang.test; import com.achang.bean.Order; import com.achang.dao.OrderDao; import com.achang.dao.impl.OrderDaoImpl; import org.junit.Test; import java.math.BigDecimal; import java.util.Date; import static org.junit.Assert.*; /****** @author 阿昌 @create 2020-12-02 12:20 ******* */ public class OrderDaoImplTest { private OrderDao orderDao = new OrderDaoImpl(); @Test public void saveOrder() { orderDao.saveOrder(new Order("1234567890",new Date(),new BigDecimal(100),0,1)); } }<file_sep>/json_ajax_i18n-12/src/main/java/com/achang/i18n/i18nTest.java package com.achang.i18n; import org.junit.Test; import java.util.Locale; import java.util.ResourceBundle; /****** @author 阿昌 @create 2020-12-04 11:45 ******* */ public class i18nTest { @Test public void testLocale() { //getDefault():获取你系统默认的语言、国家信息 Locale locale = Locale.getDefault(); System.out.println(locale);// zh_CN //getAvailableLocales():获取支持的语音、国家信息 //遍历 for (Locale availableLocale : Locale.getAvailableLocales()) { System.out.println(availableLocale); } //获取中文,中文的常量的Locale对象 System.out.println(Locale.CANADA);// zh_CN //获取英文,美国的常量的Locale对象 System.out.println(Locale.US);// en_US } @Test public void testI18n() { //得到需要的local对象 Locale locale = Locale.CHINA; //通过指定的baseName和Locale对象,来读取相应的配置文件 ResourceBundle bundle = ResourceBundle.getBundle("i18n", locale); System.out.println(bundle.getString("username")); System.out.println(bundle.getString("password")); System.out.println(bundle.getString("sex")); System.out.println(bundle.getString("age")); } } <file_sep>/json_ajax_i18n-12/src/main/java/com/achang/servlet/BaseServlet.java package com.achang.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; /****** @author 阿昌 @create 2020-11-28 15:01 ******* */ public abstract class BaseServlet extends HttpServlet { //子类模块继承此类,不重写doPost()方法,因此调用的是父类BaseServlet的doPost()方法, //然后通过下面的方法反射出子类this的方法名,并且调用方法。完成业务请求。 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException { //解决post请求中文乱码问题 req.setCharacterEncoding("UTF-8"); //解决响应中文乱码问题 resp.setContentType("text/html;charset=UTF-8"); String action = req.getParameter("action"); //处理登录请求 try { //获取action业务,鉴别字符串,获取相应的业务方法,反射对象 Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class); //调用目标业务方法 method.invoke(this, req, resp); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); //把异常抛给Filter过滤器 } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } } <file_sep>/servlet-7/src/main/java/com/achang/servlet/HelloServlet3.java package com.achang.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author 阿昌 * @create 2020-11-03 20:00 */ public class HelloServlet3 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("helloservlet3的doPost方法"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("helloservlet3的doGET方法"); } } <file_sep>/servlet-7/src/main/java/com/achang/servlet/Context1Servlet.java package com.achang.servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author 阿昌 * @create 2020-11-03 23:29 */ public class Context1Servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取ServletContext对象 ServletContext context = getServletContext(); System.out.println(context);//org.apache.catalina.core.ApplicationContextFacade@11f32f19 System.out.println("保存之前: context中获取数据key1的value值是: " + context.getAttribute("key1"));//null context.setAttribute("key1", "value1"); System.out.println("Context1Servlet中获取数据key1的value值是: " + context.getAttribute("key1"));//key1 } } <file_sep>/servlet-7/src/main/java/com/achang/servlet/Context2Servlet.java package com.achang.servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author 阿昌 * @create 2020-11-03 23:42 */ public class Context2Servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取ServletContext对象 ServletContext context = getServletContext(); System.out.println(context);//org.apache.catalina.core.ApplicationContextFacade@11f32f19 System.out.println("Context2Servlet中获取数据key1的value值是: " + context.getAttribute("key1"));//key1 } } <file_sep>/book--Version.JavaEE/src/main/java/com/achang/web/LoginServlet.java package com.achang.web; import com.achang.bean.User; import com.achang.dao.UserDao; import com.achang.service.UserService; import com.achang.service.impl.UserServiceImpl; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /****** @author 阿昌 @create 2020-11-26 14:00 ******* */ public class LoginServlet extends HttpServlet { private UserServiceImpl userService = new UserServiceImpl(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1.获取请求参数 String username = req.getParameter("username"); String password = req.getParameter("password"); //2.调用 userService.Login()登录处理业务 User loginUser = userService.login(new User(0, username, password, null)); //3.根据login()方法返回结果判断登录是否成功 if (loginUser ==null){ //4.如果等于null,登入失败 //把错误信息,和回显的表单项信息,保存到Request域中 req.setAttribute("msg","用户名或密码错误!"); req.setAttribute("username",username); //5.转跳login登入页面 req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp); }else { System.out.println("登录成功"); //6.不为null,登入成功,跳转login_success页面 req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp); } } }
1e46258926dd042e40f1eebaab447586068d548a
[ "Markdown", "Java", "INI" ]
22
Markdown
qq995931576/JavaWeb
f7f508dd4280e510bb74e8c2730382a55aeb9e5c
3b84be8cab832b3b648983cff3a1a296a5ccad3d
refs/heads/master
<file_sep># Univoice A web app that picks a random choice from a list of choices, using random atmospheric data. Each choice is assigned a random number, and a fact about the picked choice's number is also displayed. ## URL [univoice.azurewebsites.net](http://univoice.azurewebsites.net/) ## Built With * [Visual Studio Code](https://code.visualstudio.com/) - A cross platform open-source code editor developed by Microsoft. * [npm](https://www.npmjs.com/) - A NodeJS package manager. * [Bower](https://bower.io/) - A package manager that focuses on front-end components. * [Yeoman](http://yeoman.io/) - A scaffolding tool that generates the basic files and structures for simple client-side applications. * [generator-webapp](https://github.com/yeoman/generator-webapp) - A Yeoman generator for simple web apps. * [TypeScript](https://www.typescriptlang.org/) - A superset of JavaScript which enforces a type system, and allows you to use ES6 features. * [Bootstrap](http://getbootstrap.com/) - A CSS Framework. * [SASS](http://sass-lang.com/) - A CSS preprocessor that makes it easier and more fun to add styles. * [jQuery](https://jquery.com/) - A JavaScript library. * [Browsersync](https://www.browsersync.io/) - Provides a small and easy-to-use web server with live reloading. * [Gulp](http://gulpjs.com/) - A task runner that automates tedious tasks you usually have to do manually. * [Git](https://git-scm.com/) - A popular distributed version control system. * [Git](http://github.com/) and [BitBucket](http://bitbucket.org/) - Online services that allow you to host your git repositories online. * [Azure Web Apps](https://azure.microsoft.com/en-us/services/app-service/web/) - Hosts your website. I used continous deployment so the latest version on the master branch is always used by my web app. If you're a student, you too can sign up for a [DreamSpark account](https://www.dreamspark.com/) for an Azure DreamSpark subscription. * [Visual Studio Application Insights](https://azure.microsoft.com/en-us/documentation/articles/app-insights-get-started/) - Tracks and shows data about your users' interactions with your web app. * [Facebook Social Plugins](https://developers.facebook.com/docs/plugins) - Allows you to add like and share buttons, as well as a Facebook comments section, on your web app. * [Sweet Alert Plugin](http://t4t5.github.io/sweetalert/) - A prettier version of an alert. * [Spin Plugin](http://ksylvest.github.io/jquery-spin/) - Shows an animated loading indicator. * [Alertify Library](http://fabien-d.github.io/alertify.js/) - Allows you to use aesthetically pleasing notifications. ## APIs used 1. [RANDOM.ORG](https://api.random.org/json-rpc/1/) - Generates random numbers from random atmospheric data. 2. [NUMBERSAPI](http://numbersapi.com) - Shows facts about numbers. ## Authors * **<NAME>** - [jpdc-developer](https://github.com/jpdc-developer) ## License This project is open-source and was made for educational purposes.<file_sep>/// <reference path="typings/index.d.ts" /> declare function swal(title: any): void; declare function swal(title: string, body: string): void; declare var alertify: any; declare function success(message: string): void; var choices: string[] = []; var addChoice = $('#add-choice'); var choose = $('#choose'); var choiceField = $('#choice-field'); var choiceListContainer = $('#choice-list-container'); var spin = $('.spin'); var chooseText = $('.choose-text'); $( document ).ready( function(): void { spin.hide(); } ); addChoice.click( function (e: any): void { add(e); }); choose.click( function (e: any): void { decide(e); }); choiceField.keyup(function (e: any): void { if (e.keyCode == 13) { add(e); } }); function add(e: any): void { e.preventDefault(); let choice: any = choiceField; let messageLength: number = choice.val().replace(/ /g, '').length; if (messageLength > 0) { choices.push(choice.val()) updatePage(choice); var width: number = $(window).width(); if (width>768) { alertify.success('Choice Added!'); } } else { choiceField.blur(); retryInput(); } } function retryInput(): void { swal({ title: "Your choice is blank ...", text: "Please type in a choice.", showConfirmButton: false, showCancelButton: true, cancelButtonText: "OK" }); } function updatePage(choice: any): void { $('#choice-list-container').append('<p id=\'list-preview' + choices.length + '\' class=\'btn btn-info\' >' + choice.val() + '</p>'); $('#list-preview' + choices.length).hide(); $('#list-preview' + choices.length).fadeIn(500); $('#list-preview' + choices.length).css('visibility', 'visible'); choice.val(''); } function decide(e: any): void { e.preventDefault(); choiceField.blur(); chooseText.hide(); spin.show(); if (choices.length <= 1) { swal({ title: "You don't have enough choices ...", text: "Please add more choices.", showConfirmButton: false, showCancelButton: true, cancelButtonText: "OK" }); } else { addChoice[0].style.pointerEvents = 'none'; choose[0].style.pointerEvents = 'none'; getRandomNumberFromAPI(choices.length, function (number: number): void { let choiceIndex: number = number - 1; getNumberTriviaFromAPI(number, function (fact: any): void { // Present the data let chosenNumber: string = 'Choice #' + number + ' has been chosen:\t'; let chosenChoice: string = choices[choiceIndex]; let chosenFact: string = fact.text; choiceField.blur(); showChoiceAndFact(chosenNumber, chosenChoice, chosenFact); cleanUp(); addChoice[0].style.pointerEvents = 'auto'; choose[0].style.pointerEvents = 'auto'; }); }); } } function showChoiceAndFact(chosenNumber: string, chosenChoice: string, chosenFact: string): void { swal({ title: chosenNumber + chosenChoice, text: 'Fun Fact:\t' + chosenFact, showConfirmButton: false, showCancelButton: true, cancelButtonText: "OK" }); } function cleanUp(): void { choices = []; choiceListContainer.html(''); choiceField.val(''); chooseText.show(); spin.hide(); } function getRandomNumberFromAPI(numberOfChoices: number, callback: any): void { $.ajax({ url: 'https://api.random.org/json-rpc/1/invoke', beforeSend: function (xhrObj: JQueryXHR): void { // Request headers xhrObj.setRequestHeader('Content-Type', 'application/json-rpc'); }, type: 'POST', dataType: 'json', data: JSON.stringify( { 'jsonrpc': '2.0', 'method': 'generateIntegers', 'params': { 'apiKey': '<KEY>', 'n': 1, 'min': 1, 'max': numberOfChoices, 'replacement': true }, 'id': 1 } ) }) .done(function (data: any): void { try { callback(data.result.random.data[0]); } catch (error) { let errorMessage: string = error.message; swal('An error has occured :( Here is the error message:\n' + errorMessage); console.log(errorMessage) cleanUp(); } }) .fail(function (error: any): void { let errorMessage: string = error.message; swal('An error has occured :( Here is the error message:\n' + errorMessage); console.log(error.getAllResponseHeaders()); console.log(errorMessage); }); } function getNumberTriviaFromAPI(number: number, callback: any): void { var url = 'http://numbersapi.com/' + number + '/?json'; $.ajax({ url: url, type: 'GET', }) .done(function (data: any): void { callback(data); }) .fail(function (error: any) { let errorMessage: string = error.message; swal('An error has occured :( Here is the error message:\n' + errorMessage); console.log(error.getAllResponseHeaders()); console.log(errorMessage); }); }
0078cd7dff5ab55664031c18f7100a77bf01bce5
[ "Markdown", "TypeScript" ]
2
Markdown
jpdc-developer/univoice
3d39d65a2f8cc6bfe35bcebd5e1c73e175f8f759
ac2a8313c9a96e3334ce26f6a434a27427a57560
refs/heads/master
<repo_name>VilsonJuniorIlegra/selenium-config<file_sep>/selenium-utils-browser/src/main/java/br/com/selenium/browser/BrowserFactory.java package br.com.selenium.browser; import org.openqa.selenium.WebDriver; /** * Created by Vilson on 31/07/2015. */ public class BrowserFactory { public static WebDriver create(String browser){ if (browser.equals("Chrome")){ return new ChromeConfig().config(); } else if (browser.equals("Firefox")){ return new FirefoxConfig().config(); } else if (browser.equals("Safari")){ return new SafariConfig().config(); } return null; } } <file_sep>/selenium-utils-browser/src/test/java/br/com/selenium/browser/test/SelectBrowserTest.java package br.com.selenium.browser.test; import br.com.selenium.browser.BrowserFactory; import org.junit.Test; import org.openqa.selenium.WebDriver; /** * Created by Vilson on 31/07/2015. */ public class SelectBrowserTest { private WebDriver driver; @Test public void selectChromeBrowserTest(){ driver = BrowserFactory.create("Chrome"); } @Test public void selectFirefoxBrowserTest(){ driver = BrowserFactory.create("Firefox"); } @Test public void selectSafariBrowserTest(){ driver = BrowserFactory.create("Safari"); } } <file_sep>/selenium-utils-browser/src/main/java/br/com/selenium/browser/SafariConfig.java package br.com.selenium.browser; import org.openqa.selenium.WebDriver; import org.openqa.selenium.safari.SafariDriver; import java.util.concurrent.TimeUnit; /** * Created by Vilson on 31/07/2015. */ public class SafariConfig implements BrowserConfig { public WebDriver config() { System.setProperty("webdriver.safari.noinstall", "true"); WebDriver driver = new SafariDriver(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); return driver; } } <file_sep>/README.md # selenium-config Basic factory browser, Chrome, Firefox, Safari to Selenium WD
3e994d33ebc7a1a567b3a8cb37b9814b9774377b
[ "Markdown", "Java" ]
4
Java
VilsonJuniorIlegra/selenium-config
8ea5dd7309fafb67f3cc56fc68b692e1b526607e
cd197bb896ae32a7c3108cd31889138b60a427d7
refs/heads/master
<file_sep>#ifndef GAME_BOARD_H #define GAME_BOARD_H #include <iostream> #include <stdlib.h> #include <time.h> #include "game_board.h" #define GAME_BOARD_SIZE_X 10 #define GAME_BOARD_SIZE_Y 20 #define NUM_BLOCKS 4 class GameBoard; // A piece of the active piece struct Square { int x; int y; }; typedef Square Square; // The current piece which is falling // Square 0 will be the axis of rotation struct Active_Piece { Square squares[NUM_BLOCKS]; }; typedef Active_Piece Active_Piece; class Game_Board { friend class Game_Board_Tester; private: // Tracks the number of filled squares in a row int row_descriptor[GAME_BOARD_SIZE_Y]; // creates a new piece which becomes the active piece void new_piece(int piece_type); // removes squares in rows which have become full void clear_rows(); // rotates the coordinates left void rotate_left(); // checks if the square is intersecting another square bool check_drop_intersect(); // checks if the active piece is able to more horizontally // @param delta the direction the piece will move bool check_horz_intersect(int delta); // Checks it the coordinates passed in are out of bounds or intersect anything bool check_intersect(int x, int y); // Checks if the piece is able to be rotated anticlockwise bool check_anticlock_rot_intersect(); // Checks if the piece is able to be rotated clockwise bool check_clock_rot_intersect(); //drops the piece as far as it is able to go void quick_drop(); // Adds the active piece to the game board void add_piece(); // Assigns the specified coordinates to corresdoning square in ap void assign_coords(int one_x, int one_y, int two_x, int two_y, int three_x, int three_y); // produces a random number for piece creation int random_num(int max); public: // a struct containing 4 squares which represents the actively falling piece Active_Piece ap; // a 2d bool array to represent spots taken up by a square bool board[GAME_BOARD_SIZE_X][GAME_BOARD_SIZE_Y]; static void begin_game(); void rotate_right(); void drop(); bool isPiece(int i, int j); void printBoard(); Game_Board(); void on_left_arrow(); void on_right_arrow(); void on_up_arrow(); void on_space_bar(); void on_down_arrow(); }; #endif<file_sep>#include "dialog.h" #include "ui_dialog.h" #include "game_board.h" #include <QtDebug> #include <QKeyEvent> #include <QMessageBox> extern Game_Board mainBoard; Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); } Dialog::~Dialog(){ delete ui; } //used to interperet key presses from keyboard void Dialog::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_D) { //std::cout<<"KEY D\n"; mainBoard.on_right_arrow(); } else if (event->key() == Qt::Key_A) { mainBoard.on_left_arrow(); } else if (event->key() == Qt::Key_W) { //qDebug()<<"Shift Pressed"; mainBoard.rotate_right(); } else if (event->key() == Qt::Key_S) { //qDebug()<<"Shift Pressed"; mainBoard.rotate_right(); } else if (event->key() == Qt::Key_Space) { mainBoard.on_space_bar(); } } void Dialog::check_loss() { for (int i = 0; i < GAME_BOARD_SIZE_X; ++i) { if (mainBoard.board[i][GAME_BOARD_SIZE_Y - 1]) { quitGame(); } } } //Main funtion that draws everything to the screen void Dialog::paintEvent(QPaintEvent *e) { QPainter painter(this); //draws all the pieces on the board for (int i = 0; i < GAME_BOARD_SIZE_X; ++i) { for (int j = 0; j < GAME_BOARD_SIZE_Y; ++j) { if (mainBoard.board[i][j]) { QRect square(i * 20, 380 - j * 20, 20, 20); painter.fillRect(square, Qt::red); painter.drawRect(square); } } } //draws the active piece for (int i = 0; i < NUM_BLOCKS; i++) { QRect active(mainBoard.ap.squares[i].x * 20, 380 - mainBoard.ap.squares[i].y * 20, 20, 20); painter.fillRect(active, Qt::red); painter.drawRect(active); } mainBoard.drop(); check_loss(); QThread::msleep(200); update(); } //creates dialog on game loss void Dialog::quitGame() { QMessageBox msgBox; msgBox.setText("Game Over."); msgBox.setInformativeText("Would you like to play again?"); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); if (ret == QMessageBox::Yes) { //clears board to start a new game for (int i = 0; i < GAME_BOARD_SIZE_X; ++i) { for (int j = 0; j < GAME_BOARD_SIZE_Y; ++j) { mainBoard.board[i][j] = false; } } Game_Board::begin_game(); return; } close(); }<file_sep>#include "dialog.h" #include "ui_dialog.h" #include "game_board.h" Game_Board mainBoard; Game_Board::Game_Board() { for (int i = 0; i < GAME_BOARD_SIZE_X; ++i) { for (int j = 0; j < GAME_BOARD_SIZE_Y; ++j) { mainBoard.board[i][j] = false; } } srand(time(NULL)); } void Game_Board::begin_game() { mainBoard.new_piece(mainBoard.random_num(6)); } //Used to initialize a new peice based on the perameter piece type (0-5) void Game_Board::new_piece(int piece_type) { ap.squares[0].x = GAME_BOARD_SIZE_X / 2; ap.squares[0].y = GAME_BOARD_SIZE_Y - 2; switch (piece_type) { case 0: // add left l assign_coords(ap.squares[0].x - 1, ap.squares[0].y, ap.squares[0].x + 1, ap.squares[0].y, ap.squares[0].x + 1, ap.squares[0].y + 1); break; case 1: // add right l assign_coords(ap.squares[0].x + 1, ap.squares[0].y, ap.squares[0].x - 1, ap.squares[0].y, ap.squares[0].x - 1, ap.squares[0].y + 1); break; case 2: // add left zig assign_coords(ap.squares[0].x + 1, ap.squares[0].y, ap.squares[0].x, ap.squares[0].y + 1, ap.squares[0].x - 1, ap.squares[0].y + 1); break; case 3: // add right zig assign_coords(ap.squares[0].x - 1, ap.squares[0].y, ap.squares[0].x, ap.squares[0].y + 1, ap.squares[0].x + 1, ap.squares[0].y + 1); break; case 4: // add square assign_coords(ap.squares[0].x + 1, ap.squares[0].y, ap.squares[0].x + 1, ap.squares[0].y + 1, ap.squares[0].x, ap.squares[0].y + 1); break; case 5: // add t assign_coords(ap.squares[0].x + 1, ap.squares[0].y, ap.squares[0].x - 1, ap.squares[0].y, ap.squares[0].x, ap.squares[0].y + 1); break; default: // add straight //qDebug() << "Straight"; assign_coords(ap.squares[0].x - 1, ap.squares[0].y, ap.squares[0].x + 1, ap.squares[0].y, ap.squares[0].x - 2, ap.squares[0].y); break; } } //Sets up the quardinates for the active peice void Game_Board::assign_coords(int one_x, int one_y, int two_x, int two_y, int three_x, int three_y) { ap.squares[1].x = one_x; ap.squares[1].y = one_y; ap.squares[2].x = two_x; ap.squares[2].y = two_y; ap.squares[3].x = three_x; ap.squares[3].y = three_y; } //checks for a full row using the values in row_descriptor void Game_Board::clear_rows() { for (int j = 0; j < GAME_BOARD_SIZE_Y; ++j) { if (row_descriptor[j] >= GAME_BOARD_SIZE_X) { for (int i = j + 1; i < GAME_BOARD_SIZE_Y; ++i) { for (int x = 0; x < GAME_BOARD_SIZE_X; ++x) { board[x][i - 1] = board[x][i]; } row_descriptor[i - 1] = row_descriptor[i]; } } } } //moves the piece down everytime the screan is redrawn //it also checks for intersection, if intersection exists, //it adds the peice to the board. void Game_Board::drop() { if (check_drop_intersect()) { for (int i = 0; i < 4; ++i) { row_descriptor[ap.squares[i].y]++; } add_piece(); new_piece(random_num(6)); return; } for (int i = 0; i < 4; ++i) { ap.squares[i].y--; } } //rotates the active peice right void Game_Board::rotate_right() { if (!check_anticlock_rot_intersect()) { for (int i = 0; i < 4; ++i) { int relx = ap.squares[i].x - ap.squares[0].x; int rely = ap.squares[i].y - ap.squares[0].y; ap.squares[i].x = -rely + ap.squares[0].x; ap.squares[i].y = relx + ap.squares[0].y; } } } //rotates the active peice LEFT void Game_Board::rotate_left() { if (!check_clock_rot_intersect()) { for (int i = 0; i < 4; ++i) { ap.squares[i].x = (ap.squares[i].y - ap.squares[0].y) + ap.squares[0].x; ap.squares[i].y = -(ap.squares[i].x - ap.squares[0].x) + ap.squares[0].y; } } } //funtion to check if the active piece intersects with any peices below it bool Game_Board::check_drop_intersect() { for (int i = 0; i < 4; ++i) { if (check_intersect(ap.squares[i].x, ap.squares[i].y - 1)) { return true; } } return false; } //funtion to ensure that a player can't move a piece horizontally into another bool Game_Board::check_horz_intersect(int delta) { for (int i = 0; i < 4; ++i) { if (check_intersect(ap.squares[i].x + delta, ap.squares[i].y)) { return true; } } return false; } //intersection checker relied on by check_horz_intersect and check_drop_intersect bool Game_Board::check_intersect(int x, int y) { if (x <= -1 || x == GAME_BOARD_SIZE_X || y <= -1 || y == GAME_BOARD_SIZE_Y || board[x][y]) { return true; } return false; } //ensures the piece doesnt hit anything when rotating clockwise bool Game_Board::check_clock_rot_intersect() { for (int i = 0; i < 4; ++i) { int rot_x = -(ap.squares[i].y - ap.squares[0].y) + ap.squares[0].x; int rot_y = (ap.squares[i].x - ap.squares[0].x) + ap.squares[0].y; if (check_intersect(rot_x, rot_y)) { return true; } } return false; } //ensures the piece doesnt hit anything when rotating counter-clockwise bool Game_Board::check_anticlock_rot_intersect() { for (int i = 0; i < 4; ++i) { int rot_x = (ap.squares[i].y - ap.squares[0].y) + ap.squares[0].x; int rot_y = -(ap.squares[i].x - ap.squares[0].x) + ap.squares[0].y; if (check_intersect(rot_x, rot_y)) { return true; } } return false; } void Game_Board::quick_drop() { while (!check_drop_intersect()) { drop(); } add_piece(); for (int i = 0; i < 4; ++i) { row_descriptor[ap.squares[i].y]++; } new_piece(random_num(6)); } void Game_Board::add_piece() { for (int i = 0; i < 4; ++i) { board[ap.squares[i].x][ap.squares[i].y] = true; } clear_rows(); } //returns a random number mod max int Game_Board::random_num(int max) { return rand() % (max + 1); } //moves piece left void Game_Board::on_left_arrow() { if (!check_horz_intersect(-1)) { for (int i = 0; i < 4; ++i) { ap.squares[i].x--; } } } //moves piece right void Game_Board::on_right_arrow() { if (!check_horz_intersect(1)) { for (int i = 0; i < 4; ++i) { ap.squares[i].x++; } } } //rotates piece left void Game_Board::on_up_arrow() { rotate_left(); } //drops piece with the press of the space bar void Game_Board::on_space_bar() { quick_drop(); } //rotates piece right void Game_Board::on_down_arrow() { rotate_right(); } //HELPER FUNCTION //Funtion used to print the board for debugging void Game_Board::printBoard() { for (int i = 0; i < GAME_BOARD_SIZE_Y; i++) { std::cout << row_descriptor[i] << " "; } std::cout << std::endl; for (int i = 0; i < GAME_BOARD_SIZE_Y; ++i) { for (int j = 0; j < GAME_BOARD_SIZE_X; ++j) { if (board[j][i] || isPiece(j, i)) { std::cout << 1; } else { std::cout << 0; } } std::cout << std::endl; } for (int x = 0; x < 4; x++) { std::cout << "X: " << ap.squares[x].x << " Y: " << ap.squares[x].y << ", "; } std::cout << "\n\n\n\n\n"; } //used for printing board when debugging to show the active //piece that isn't on the board bool Game_Board::isPiece(int i, int j) { for (int x = 0; x < 4; x++) { if (ap.squares[x].x == i && ap.squares[x].y == j) { return true; } } return false; }<file_sep>#ifndef DIALOG_H #define DIALOG_H #include <QDialog> #include <QtGui> #include <QtCore> #include <QtDebug> #include "game_board.h" #include <QMessageBox> namespace Ui { class Dialog; } class Dialog : public QDialog { Q_OBJECT public: explicit Dialog(QWidget *parent = 0); ~Dialog(); void quitGame(); private: Ui::Dialog *ui; void keyPressEvent(QKeyEvent *event); void check_loss(); protected: void paintEvent(QPaintEvent *e); }; #endif // DIALOG_H<file_sep>This project of Tetris was built by <NAME>, <NAME>, and <NAME>. The code for this project is written in C++, and we have utilized Qt to develop the GUI. To run the project, simply open the Painter.pro file in QT Creator and Click run. A new window will open and the game is immediately playable. Because the app utilizes QT Creator, it can be played on any system with QT Creator installed although it was exclusively designed and tested on Mac OSX. The project is an emulation of Tetris, offering the player more control over various aspects of the game. For example, the speed of the blocks is customizable, as is the dimensions of the board, and so on. ![tet1](https://user-images.githubusercontent.com/19563337/29514770-573c58b8-8687-11e7-9d1b-55f1d5307338.png) ![tet2](https://user-images.githubusercontent.com/19563337/29514796-6f239158-8687-11e7-97b7-4a8035169ab5.png)
6daf9f55822e6a9d5f9d48ec6d3732e9f0ec6d55
[ "Markdown", "C++" ]
5
C++
SVirat/Customizable-Tetris-Emulation
ebde2f0152351692d6da26736f2025922e0ab1fd
3d4988eecf35458016cd8fe57a1600faef5b58d1
refs/heads/master
<file_sep>#include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <vector> #include <sys/shm.h> #include <string.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <iostream> #include <algorithm> // Source: Dr. Rincon's code from BlackBoard using namespace std; int main(int argc, char *argv[]) { int sockfd, portno, n,numProcess, empty = 0, process; struct sockaddr_in serv_addr; struct hostent *server; int pipefd[numProcess+ 1][2]; int pid; int i; int token; char buffer[256]; if (argc < 3) { cout << "usage hostname port" << argv[0] << endl; exit(0); } portno = atoi(argv[2]); sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) cout << "ERROR opening socket"; server = gethostbyname(argv[1]); if (server == NULL) { cout << "ERROR, no such host\n"; exit(0); } bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) cout << "ERROR connecting"; n = write(sockfd,&empty,sizeof(empty)); if (n < 0) cout << "ERROR writing to socket"; n = read(sockfd,&numProcess,sizeof(numProcess)); if (n < 0) cout << "ERROR reading from socket"; close(sockfd); numProcess -= 1; for (i = 0; i <= numProcess; i++){ if (pipe(pipefd[i]) < 0) { cout << "ERROR: Pipe Creation failed\n"; exit(1); } } for (i = 0; i < numProcess ; i++){ if ((pid=fork())==0) { while(true){ read(pipefd[i][0], &token, sizeof(token) ); if (token == -1) { token = -1; write(pipefd[i+1][1],&token,sizeof(token)); _exit(0); } sockfd = socket(AF_INET, SOCK_STREAM, 0); if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) cout << "ERROR connecting"; n = write(sockfd,&empty,sizeof(int)); if (n < 0) cout << "ERROR writing to socket"; n = read(sockfd,&process,sizeof(int)); close(sockfd); if (n < 0) cout << "ERROR reading from socket"; if (token >= 0 && process == 1){ cout << "Process " << i + 1 << " is using the network" << endl; } if (process == -1) { token = -1; write(pipefd[i+1][1],&token,sizeof(token)); _exit(0); } token = <PASSWORD> + 1; write(pipefd[i+1][1],&token,sizeof(token)); } } close (pipefd[i][0]); close(pipefd[i + 1][1]); } token = 0; while(true) { sockfd = socket(AF_INET, SOCK_STREAM, 0); if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) cout << "ERROR connecting"; n = write(sockfd,&empty,sizeof(int)); if (n < 0) cout << "ERROR writing to socket"; n = read(sockfd,&process,sizeof(int)); close(sockfd); if (n < 0) cout << "ERROR reading from socket"; if (process == 1){ cout << "Process 0 is using the network" << endl; } if (process==-1) { token = -1; write(pipefd[0][1],&token,sizeof(token)); break; } token += 1; write(pipefd[0][1],&token, sizeof(int)); read(pipefd[numProcess][0], &token, sizeof(int)); if (token == -1) { token = -1; write(pipefd[0][1],&token, sizeof(int)); break; } } for(i=0; i < numProcess; i++) wait(NULL); } <file_sep>#include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <vector> #include <sys/shm.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <iostream> #include <algorithm> //Source: Dr. Rincon's code from BlackBoard. using namespace std; int main(int argc, char *argv[]) { int sockfd, newsockfd, portno, clilen; char buffer[256]; struct sockaddr_in serv_addr, cli_addr; int n, numOfProcess, contents, empty; int counter = 0; vector<int> mainVec; cin >> numOfProcess; while(cin >> contents) { mainVec.push_back(contents); } if (argc < 2) { cout << "ERROR, no port provided\n"; exit(1); } sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) cout << "ERROR opening socket"; bzero((char *) &serv_addr, sizeof(serv_addr)); portno = atoi(argv[1]); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(portno); if ((::bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr))) < 0) cout << "ERROR on binding"; listen(sockfd,5); clilen = sizeof(cli_addr); newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, (socklen_t *)&clilen); if (newsockfd < 0) cout << "ERROR on accept"; n = read(newsockfd,&empty,sizeof(int)); if (n < 0) cout<< "ERROR reading from socket"; n = write(newsockfd, &numOfProcess, sizeof(numOfProcess)); if (n < 0) cout << "ERROR writing to socket"; close(newsockfd); while(true) { newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, (socklen_t *)&clilen); if (newsockfd < 0) cout << "ERROR on accept"; bzero(buffer,256); n = read(newsockfd,&empty,sizeof(int)); if (n < 0) cout << "ERROR reading from socket"; n = write(newsockfd, &mainVec[counter], sizeof(int)); close(newsockfd); if (mainVec[counter] == -1){ break; } counter++; } close(sockfd); return 0; }
5e5b69d5e55008daa1d508f91ae53b49c4725621
[ "C++" ]
2
C++
RenzoM157/Interprocess-Communication
6f08ee43627d569e68b8f0b5dfef742d8858cce3
35c74a93cae548e51738eb0cdd2a5450d68b2b71
refs/heads/master
<repo_name>kitchmas/The-Recipe-App<file_sep>/models/recipe.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const IngredientsSchema = new Schema({ ingredient:String }); const RecipeShcema = new Schema({ name:String, method:String, ingredients:[IngredientsSchema] }); const Recipe = mongoose.model('recipe',RecipeShcema); module.exports = Recipe; <file_sep>/public/js/recipe.js var recipeHandler = require('./recipe-handler.js'); var saveModal = require('./save-modal.js'); var viewModal = require('./view-modal.js'); var $ = require('jquery'); function loadRecipes(recipes) { recipes.forEach(function(recipe) { console.log(recipe); var recipeItem = '<div class="recipe-item" recipe-id="' + recipe._id + '">' + '<h3 class="recipe-item-heading">' + recipe.name + '</h3>' + '<div class="recipe-item-body">' + '<h4 class="recipe-method-heading">Method</h4>' + '<div class="recipe-method-body">' + recipe.method + '</div>' + '</div>' + '</div>'; $(".recipe-viewer").append(recipeItem); }); }; $(function() { recipeHandler.getRecipes(loadRecipes) // Save Modal Events $('.rec-btn-add').on('click', saveModal.openSaveModal); $('#save-recipe-modal .close').on('click', function() { saveModal.closeSaveModal(); }); $('.rec-btn-add-ingredient').click(function() { saveModal.addIngredient(); }); $('#save-recipe-modal').on('click', '.rec-btn-save', function() { saveModal.saveRecipe(); }); $('#save-recipe-modal').on("click", '.rec-btn-update', function(e) { var url = "/recipe/recipeAPI/" + e.currentTarget.closest('#save-recipe-modal').attributes['recipe-id'].value; saveModal.updateRecipe(url); }); // View Modal Events $('.recipe-viewer').on("click", '.recipe-item', function(e) { debugger; var url = "/recipe/recipeAPI/" + e.currentTarget.attributes['recipe-id'].value; recipeHandler.getRecipeById(url, viewModal.showRecipe); }); $('#view-recipe-modal .rec-edit').on('click', function(e) { debugger; var url = "/recipe/recipeAPI/" + e.currentTarget.closest('.recipe-view').attributes['recipe-id'].value; viewModal.closeViewModal(); viewModal.setUpdateModal(); saveModal.openSaveModal(); recipeHandler.getRecipeById(url, saveModal.showRecipe); }); // size related functions $('.hamburger-btn').on("click", function() { $('.collapse-nav').toggle(); }); $(window).resize(function() { if ($(window).width() >= 768) { // if larger or equal $('.collapse-nav').show(); } else { // if smaller $('.collapse-nav').hide(); } }).resize(); // This will simulate a resize to trigger the initial run. });<file_sep>/app.js const express = require('express'); const recipeController = require('./controllers/recipeController'); const homeController = require('./controllers/homeController'); //middlware const bodyParser = require('body-parser'); const mongoose = require('mongoose'); const app = express(); //ES6 Promises mongoose.Promise = global.Promise; //connect to mongodb mongoose.connect('mongodb://localhost/recipe'); mongoose.connection.on('connected', function() { console.log('Mongoose default connection open to the database'); }); //set up template engine app.set('view engine', 'ejs'); //middlware //static files app.use(express.static('public')); app.use(express.static('dist')); app.use(express.static('views')); //use body-parser must come before routes app.use(bodyParser.urlencoded()); app.use(bodyParser.json()); //handes the routes app.use(require('./controllers')) //listen to port app.listen(2000); console.log('You are listeing to port 2000'); <file_sep>/controllers/index.js var express = require('express') , router = express.Router() router.use('/home',require('./homeController')) router.use('/recipe',require('./recipeController')) module.exports = router <file_sep>/webpack.config.js module.exports = { //define entry point entry:'./public/js/recipe.js', //define output point output:{ path: __dirname + "/dist", filename:'bundle.js' } };<file_sep>/controllers/recipeController.js var express = require('express'), router = express.Router(); const Recipe = require('../models/recipe'); //Serve the recipe page router.get('/', function(req, res) { res.render('recipe'); }); //Get all recipes router.get('/recipeAPI', function(req, res) { Recipe.find({}, function(err, recipes) { if (err) res.status(500).send(err); else console.log(recipes); res.send(recipes); }); }); // add a recipe to the db router.post('/recipeAPI', function(req, res, next) { //using body parser to access the body var recipe = new Recipe(req.body); recipe.save(); res.json(req.body); }); //Middleware that gets the recipe and addis it otthe req router.use('/recipeAPI/:recipeId', function(req, res, next) { //get by ID Recipe.findById(req.params.recipeId, function(err, recipe) { if (err) res.status(500).send(err); else if (recipe) { req.recipe = recipe; next(); } else { res.status(404).send('No recipe found'); } }); }); router.route('/recipeAPI/:recipeId') .get(function(req, res) { debugger; //Getting from middleware res.send(req.recipe); }) .put(function(req, res) { //getting from req using middleware req.recipe.name = req.body.name; req.recipe.method = req.body.method; req.recipe.ingredients = req.body.ingredients; req.recipe.save(function(err){ if(err) res.status(500).send(err); else{ res.json(req.recipe); } }); }); module.exports = router; <file_sep>/public/js/save-modal.js var saveModal = function() { var $ = require('jquery'); function clearSaveModal() { $('#save-recipe-modal #recipe-name').val(""); $('#save-recipe-modal #recipe-steps').val(""); $('#save-recipe-modal').attr("recipe-id", ""); $('#save-recipe-modal #ingredients-list').empty(); $('#save-recipe-modal #recipe-ingredient').val(""); }; function closeSaveModal() { clearSaveModal(); $('#save-recipe-modal').css("display", "none"); }; function openSaveModal() { debugger; $('#save-recipe-modal').css("display", "block"); }; function addIngredient() { ingredient = $('input[name=ingredient]'); $('<li>').text(ingredient.val()).prependTo('#ingredients-list'); ingredient.val(""); }; function getIngredients() { var ingredients = []; $("#ingredients-list li").each(function(index) { ingredients.push({ ingredient: $(this).text() }); }); return ingredients; }; function getRecipe() { var name = $('input[name=name]').val(), method = $('textarea[name=recipe-method]').val(), ingredients = getIngredients(); return { name: name, method: method, ingredients: ingredients }; }; function setSaveModal() { //Change buttons $(".rec-btn-update").toggleClass("rec-btn-update rec-btn-save").html('Update'); }; function saveRecipe() { debugger; var recipe = getRecipe(); recipeHandler.addRecipe(recipe); clearSaveModal(); closeSaveModal(); }; function updateRecipe(url) { var recipe = getRecipe(); recipeHandler.updateRecipe(url,recipe); clearSaveModal(); closeSaveModal(); }; function showRecipe(recipe) { debugger; $('#save-recipe-modal #recipe-name').val(recipe.name); $('#save-recipe-modal #recipe-steps').val(recipe.method); $('#save-recipe-modal').attr("recipe-id", recipe._id); recipe.ingredients.forEach(function(ingredient) { $('#save-recipe-modal #ingredients-list').append('<li>' + ingredient.ingredient + '</li>'); }); }; return { saveRecipe: saveRecipe, addIngredient: addIngredient, openSaveModal: openSaveModal, closeSaveModal: closeSaveModal, clearSaveModal: clearSaveModal, showRecipe:showRecipe, updateRecipe:updateRecipe } } module.exports = saveModal();
201604ec3af9fa1bfe74266f51f9e81dc9666714
[ "JavaScript" ]
7
JavaScript
kitchmas/The-Recipe-App
2f5aa11bd5d99a87dc6e98abb97818f9a7f98020
6d38a24cf703130d546aa40570f4b520a43b2dc8
refs/heads/master
<repo_name>zedsh/bitrix<file_sep>/DbLockHelper.php <?php namespace App\Helpers; use Bitrix\Main\Application; use Bitrix\Main\Entity\Base; class DbLockHelper { const CONNECTION = 'default'; const TIMEOUT = 5; public static function lock($lockName) { $connection = Application::getInstance()->getConnectionPool()->getConnection(static::CONNECTION); if ($connection instanceof \Bitrix\Main\DB\MysqlCommonConnection) { $lock = $connection->queryScalar( sprintf('SELECT GET_LOCK("%s", %d)', $lockName, static::TIMEOUT) ); return ($lock != '0'); } else { throw new \Exception('Unsupported db'); } } public static function unlock($lockName) { $connection = Application::getInstance()->getConnectionPool()->getConnection(static::CONNECTION); if ($connection instanceof \Bitrix\Main\DB\MysqlCommonConnection) { $connection->queryExecute( sprintf('DO RELEASE_LOCK("%s")', $lockName) ); return true; } else { throw new \Exception('Unsupported db'); } } }
0943ee90cfe25877c806de22442a86dd890e95f5
[ "PHP" ]
1
PHP
zedsh/bitrix
bc037f957dd2cc5012d044d3f2c07a61e5d0ee3f
d3f83746b42194992fb96b717665961721ec2ed0
refs/heads/master
<file_sep>package sample import javafx.collections.FXCollections import javafx.geometry.Insets import javafx.scene.Scene import javafx.scene.control.* import javafx.scene.layout.GridPane import javafx.stage.Stage import sample.Main.Companion.FRESH_AF_PLAYLIST_NAME class EditPlaylistWindow { companion object { fun spawnEditPlaylistWindow(playlist: Playlist) { val grid = GridPane() val scene = Scene(grid) val stage = Stage() stage.scene = scene stage.title = "Edit ${playlist.playlistName}" stage.setOnCloseRequest { val confirmationResult = Alert(Alert.AlertType.CONFIRMATION, "Are you sure you want to close without saving?").showAndWait() if (confirmationResult.get() == ButtonType.OK) { val dbConn = DBConn() dbConn.linesFromQuery("DELETE FROM Playlist WHERE playlistName = '$FRESH_AF_PLAYLIST_NAME';") dbConn.close() stage.close() } } grid.padding = Insets(10.0, 10.0, 10.0, 10.0) grid.vgap = 5.0 grid.hgap = 5.0 // add name text box val playlistNameBox = TextField() playlistNameBox.promptText = "New playlist name..." GridPane.setConstraints(playlistNameBox, 0, 0, 90, 1) grid.children.add(playlistNameBox) // add explanatory header val hintHeader = TextField("Click a song to move it to the opposite playlist.") hintHeader.isEditable = false GridPane.setConstraints(hintHeader, 0, 1, 80, 1) grid.children.add(hintHeader) // add All Songs header val allSongsHeader = TextField("All Songs") allSongsHeader.isEditable = false GridPane.setConstraints(allSongsHeader, 0, 2, 80, 1) grid.children.add(allSongsHeader) // add Current Playlist header val currentPlaylistHeader = TextField(playlist.playlistName) currentPlaylistHeader.isEditable = false GridPane.setConstraints(currentPlaylistHeader, 81, 2, 80, 1) grid.children.add(currentPlaylistHeader) // add All Songs table val allSongs = MP3Player.songsInPlaylist(MP3Player.playlistFromName("All Songs")) val allSongNames = FXCollections.observableArrayList<String>(MP3Player.songTitlesInPlaylist(MP3Player.playlistFromName("All Songs"))) val currentSongs = ArrayList<Song>(MP3Player.songsInPlaylist(playlist)) val currentSongNames = FXCollections.observableArrayList<String>(MP3Player.songTitlesInPlaylist(MP3Player.playlistFromName(playlist.playlistName))) val allSongsLV = ListView(allSongNames) allSongsLV.setCellFactory { _ -> DelCell("->", PlaylistType.ALL_SONGS, allSongs, currentSongs, currentSongNames) } allSongsLV.cellFactoryProperty() GridPane.setConstraints(allSongsLV, 0, 3, 80, 10) grid.children.add(allSongsLV) // add Current Playlist table val currentSongsLV = ListView(currentSongNames) currentSongsLV.setCellFactory { _ -> DelCell("<-", PlaylistType.NOT_ALL_SONGS, allSongs, currentSongs, currentSongNames) } GridPane.setConstraints(currentSongsLV, 81, 3, 80, 10) grid.children.add(currentSongsLV) // add publish button val publishButton = Button("Publish!") publishButton.setOnMouseClicked { if (playlist.playlistName == FRESH_AF_PLAYLIST_NAME && (playlistNameBox.text.isBlank() || playlistNameBox.text == FRESH_AF_PLAYLIST_NAME)) { Alert(Alert.AlertType.ERROR, "Please give your new playlist a name").showAndWait() } else { val dbConn = DBConn() val oldPlaylistName = playlist.playlistName val newPlaylistName = if (playlistNameBox.text.isNotBlank()) playlistNameBox.text.trim() else playlist.playlistName if (newPlaylistName != oldPlaylistName) { dbConn.linesFromQuery("SET FOREIGN_KEY_CHECKS = 0;") dbConn.linesFromQuery("UPDATE Playlist SET playlistName = '$newPlaylistName' WHERE playlistName = '$oldPlaylistName';") dbConn.linesFromQuery("UPDATE PlaylistSong SET playlistName = '$newPlaylistName' WHERE playlistName = '$oldPlaylistName';") dbConn.linesFromQuery("SET FOREIGN_KEY_CHECKS = 1;") } else { dbConn.linesFromQuery("DELETE FROM PlaylistSong WHERE playlistName = '$oldPlaylistName'") } for (song in currentSongs) { dbConn.linesFromQuery("INSERT IGNORE INTO PlaylistSong VALUES ('$newPlaylistName', ${song.songID});") } dbConn.close() stage.close() } } GridPane.setConstraints(publishButton, 0, 13) grid.children.add(publishButton) stage.show() } } }<file_sep>package sample import javafx.collections.ObservableList import javafx.scene.control.Button import javafx.scene.control.Label import javafx.scene.control.ListCell import javafx.scene.layout.Priority import javafx.scene.layout.HBox import javafx.scene.layout.Pane enum class PlaylistType { ALL_SONGS, NOT_ALL_SONGS } internal class DelCell(delText: String, type: PlaylistType, allSongs: ArrayList<Song>, currentSongs: ArrayList<Song>, currentSongNames: ObservableList<String>) : ListCell<String>() { private var hbox = HBox() private var label = Label() private var pane = Pane() private var button = Button(delText) init { hbox.children.addAll(button, label, pane) HBox.setHgrow(pane, Priority.ALWAYS) button.setOnAction { if (type == PlaylistType.ALL_SONGS) { val songToAdd = allSongs[this.index] if (songToAdd !in currentSongs) { currentSongs.add(songToAdd) currentSongNames.add(songToAdd.title) } } else { currentSongs.removeAt(this.index) listView.items.remove(item) } } } override fun updateItem(item: String?, empty: Boolean) { super.updateItem(item, empty) text = null graphic = null if (item != null && !empty) { label.text = item graphic = hbox } } } <file_sep># MusicManager2 A GUI-based music manager that hosts and streams music from an online server. ## Streaming features Play, pause, skip and seek through your favourite songs. ## Server features Upload, delete and rename songs from your library. <file_sep>package sample import javafx.collections.FXCollections.observableArrayList import javafx.geometry.Insets import javafx.scene.Scene import javafx.scene.control.* import javafx.scene.layout.GridPane import javafx.stage.Stage import sample.MP3Player.Companion.allPlaylists import sample.MP3Player.Companion.playlistFromName import sample.MP3Player.Companion.songsInPlaylist import java.lang.reflect.Type enum class DeleteType { PLAYLIST, SONG } class DeleteWindow { companion object { fun spawnDeleteWindow(deleteType: DeleteType, type: Type) { val grid = GridPane() val scene = Scene(grid) val stage = Stage() stage.scene = scene val deletingSongs = deleteType == DeleteType.SONG val typeName = if (type is Song) "Song" else "Playlist" stage.title = "Delete ${typeName}s." stage.setOnCloseRequest { val confirmationResult = Alert(Alert.AlertType.CONFIRMATION, "Are you sure you want to close without saving?").showAndWait() if (confirmationResult.get() == ButtonType.OK) { stage.close() } } grid.padding = Insets(10.0, 10.0, 10.0, 10.0) grid.vgap = 5.0 grid.hgap = 5.0 // add explanatory header val hintHeader = TextField("Click a $typeName to move it to the opposite category.") hintHeader.isEditable = false GridPane.setConstraints(hintHeader, 0, 0, 80, 1) grid.children.add(hintHeader) // add All Songs/Playlists header val allSongsOrPlaylistsHeader = TextField("All ${typeName}s") allSongsOrPlaylistsHeader.isEditable = false GridPane.setConstraints(allSongsOrPlaylistsHeader, 0, 2, 80, 1) grid.children.add(allSongsOrPlaylistsHeader) // add All Songs ListView val allSongsOrPlaylists = if (deletingSongs) songsInPlaylist(playlistFromName("All Songs")) else allPlaylists() val allNames = observableArrayList<String>( if (deletingSongs) MP3Player.titlesInPlaylist(playlistFromName("All Songs")) else MP3Player.allPlaylistNames() ) val songsOrPlaylistsToBin = if (deletingSongs) ArrayList<Song>() else ArrayList<Playlist>() val songOrPlaylistNamesToBin = observableArrayList<String>() val allSongsLV = ListView(allNames) allSongsLV.setCellFactory { _ -> DelCell("->", PlaylistGroupType.ALL_PLAYLISTS, ) } allSongsLV.cellFactoryProperty() GridPane.setConstraints(allSongsLV, 0, 3, 80, 10) grid.children.add(allSongsLV) // add Bin header val binHeader = TextField("Bin :(") binHeader.isEditable = false GridPane.setConstraints(binHeader, 81, 2, 80, 1) grid.children.add(binHeader) // add Bin ListView val songNamesToBinLV = ListView(songOrPlaylistNamesToBin) songNamesToBinLV.setCellFactory { _ -> DelCell("<-", PlaylistType.REGULAR_PLAYLIST, allSongsOrPlaylists, songsOrPlaylistsToBin, songOrPlaylistNamesToBin) } GridPane.setConstraints(songNamesToBinLV, 81, 3, 80, 10) grid.children.add(songNamesToBinLV) // add publish button val publishButton = Button("Publish!") publishButton.setOnMouseClicked { stage.close() } GridPane.setConstraints(publishButton, 0, 13) grid.children.add(publishButton) stage.show() } } }<file_sep>package sample import javafx.collections.FXCollections import javafx.geometry.Insets import javafx.geometry.Orientation import javafx.scene.Scene import javafx.scene.control.* import javafx.scene.layout.GridPane import javafx.stage.FileChooser import javafx.stage.Stage import org.apache.tika.metadata.Metadata import org.apache.tika.parser.ParseContext import org.apache.tika.parser.mp3.Mp3Parser import org.xml.sax.helpers.DefaultHandler import java.io.FileInputStream class MainWindow { companion object { private val mp3Player = MP3Player() fun show(currentUser: User) { var currentPlaylist = Playlist("All Songs", currentUser.username, false) // initialising stage val stage = Stage() val grid = GridPane() val scene = Scene(grid) stage.scene = scene stage.title = "Music Manager" stage.setOnCloseRequest { System.exit(0) } grid.padding = Insets(10.0, 10.0, 10.0, 10.0) grid.vgap = 5.0 grid.hgap = 5.0 val functComboBox = ComboBox<String>(FXCollections.observableArrayList(arrayListOf("Function...", "Add", "Edit", "Delete"))) val runActionOnComboBox = ComboBox<String>(FXCollections.observableArrayList(arrayListOf("To...", "Playlist", "Song"))) fun editingSongs() = functComboBox.value == "Edit" && runActionOnComboBox.value == "Song" fun deletingSongs() = functComboBox.value == "Delete" && runActionOnComboBox.value == "Song" fun deletingPlaylist() = functComboBox.value == "Delete" && runActionOnComboBox.value == "Playlist" // adding user login button val loginButton = Button("Login") loginButton.setOnAction { login() } GridPane.setConstraints(loginButton, 0, 0) grid.children.add(loginButton) // add seek slider val seekSlider = Slider() seekSlider.valueProperty().addListener { _, _, newValue -> if (seekSlider.isPressed) { mp3Player.seekTo(newValue.toDouble()) } } GridPane.setConstraints(seekSlider, 1, 3, 94, 1) grid.children.add(seekSlider) // add song table val listView = ListView(FXCollections.observableList(arrayListOf(""))) listView.selectionModel.selectedItemProperty().addListener { _, _, _ -> val index = listView.selectionModel.selectedIndex if (index >= 0 && index < listView.items.size) // if the user pressed on a row with a song on it, not just a blank row { when { editingSongs() -> { val oldSongName = MP3Player.songTitlesInPlaylist(currentPlaylist)[index] val dialog = TextInputDialog() // showing a "rename this song to __ " dialog dialog.title = "Rename Song" dialog.headerText = "Rename $oldSongName:" dialog.showAndWait().ifPresent { // if the user inputted a new name val dbConn = DBConn() dbConn.runQuery("UPDATE Song SET title = '$it' WHERE songID = ${index + 1}") // SQL uses 1-based indexes. `it` is a kotlin-made variable that stores the song name dbConn.close() } } deletingSongs() -> { val songNameToDelete = MP3Player.songTitlesInPlaylist(currentPlaylist)[index] val confirmation = Alert(Alert.AlertType.CONFIRMATION) confirmation.title = "Delete $songNameToDelete" confirmation.headerText = "Are you sure you want to delete $songNameToDelete from ${currentPlaylist.playlistName}?" if (confirmation.showAndWait().get() == ButtonType.OK) // if the user said yes to deleting the song { val dbConn = DBConn() val songID = MP3Player.nthSongInPlaylist(currentPlaylist, index).songID dbConn.runQuery("DELETE FROM PlaylistSong WHERE songID = $songID") // will delete the song entirely -- from all playlists dbConn.runQuery("DELETE FROM Song WHERE songID = $songID") dbConn.close() } } else -> // pressing a song without any special mode selected. just playing the song normally { mp3Player.reload(MP3Player.songsInPlaylist(currentPlaylist)) mp3Player.skipTo(index) seekSlider.value = 0.0 // starting from beginning } } } } listView.orientation = Orientation.VERTICAL GridPane.setConstraints(listView, 0, 2, 98, 1) grid.children.add(listView) // adding search box val searchBox = TextField() val songTitlesCached = FXCollections.observableArrayList(MP3Player.songTitlesInPlaylist(currentPlaylist)) searchBox.textProperty().addListener { _, _, searchText -> val searchTrimmed = searchText.trim().toLowerCase() if (searchTrimmed.isNotBlank()) { listView.items.clear() songTitlesCached.forEach { if (it.toLowerCase().contains(searchTrimmed)) listView.items.add(it) } } else { listView.items = songTitlesCached } } searchBox.promptText = "Search the current playlist..." GridPane.setConstraints(searchBox, 1, 0, 97, 1) grid.children.add(searchBox) // add playlist combo box val playlistMenu = ComboBox<String>(FXCollections.observableList<String>(MP3Player.allPlaylistNames())) playlistMenu.valueProperty().addListener { _, _, newPlaylistName -> currentPlaylist = MP3Player.playlistFromName(newPlaylistName) listView.items.clear() listView.items.addAll(MP3Player.songTitlesInPlaylist(currentPlaylist)) } playlistMenu.selectionModel.select("All Songs") GridPane.setConstraints(playlistMenu, 0 ,1, 5, 1) grid.children.add(playlistMenu) // add play playlist button val playPlaylistButton = Button("Play playlist") playPlaylistButton.setOnAction { mp3Player.stop() mp3Player.reload(MP3Player.songsInPlaylist(currentPlaylist)) mp3Player.play() } GridPane.setConstraints(playPlaylistButton,6, 1) grid.children.add(playPlaylistButton) // add play/pause button val playPauseButton = Button("| | ▶") playPauseButton.setOnAction { mp3Player.togglePlayPause() } GridPane.setConstraints(playPauseButton, 0, 3) grid.children.add(playPauseButton) // add skip backwards button val skipBackwardsButton = Button("◀") skipBackwardsButton.setOnMouseClicked { mp3Player.skipBackward() } GridPane.setConstraints(skipBackwardsButton, 95, 3) grid.children.add(skipBackwardsButton) // add skip forwards button val skipForwardsButton = Button("▶") skipForwardsButton.setOnMouseClicked { mp3Player.skipForward() } GridPane.setConstraints(skipForwardsButton, 97, 3) grid.children.add(skipForwardsButton) // add Add options functComboBox.selectionModel.selectFirst() GridPane.setConstraints(functComboBox, 70, 1, 10, 1) grid.children.add(functComboBox) // add Rename options runActionOnComboBox.selectionModel.selectFirst() GridPane.setConstraints(runActionOnComboBox, 80, 1, 10, 1) grid.children.add(runActionOnComboBox) // add Execute button val executeButton = Button("Go!") executeButton.setOnMouseClicked { if (functComboBox.value == "Add") { if (runActionOnComboBox.value == "Playlist") { val dbConn = DBConn() dbConn.runQuery("INSERT INTO Playlist VALUES ('${Main.FRESH_AF_PLAYLIST_NAME}', '${currentUser.username}', TRUE);") dbConn.close() EditPlaylistWindow.spawnEditPlaylistWindow(MP3Player.playlistFromName(Main.FRESH_AF_PLAYLIST_NAME)) } else if (runActionOnComboBox.value == "Song") { val songFile = FileChooser().showOpenDialog(stage) if (songFile != null) { val input = FileInputStream(songFile) val metadata = Metadata() Mp3Parser().parse(input, DefaultHandler(), metadata, ParseContext()) input.close() val newSongIndex = MP3Player.songsInPlaylist(MP3Player.playlistFromName("All Songs")).last().songID + 1 val newTitle = if (metadata.get("title") != null) { metadata.get("title") } else songFile.name.substringBefore(".").trim() val newArtist = if (metadata.get("xmpDM:artist") != null) { metadata.get("artist") } else "" val newAlbum = if (metadata.get("xmpDM:album") != null) { metadata.get("album") } else "" val newSongPath = songFile.absolutePath.replace("\\", "@@") val dbConn = DBConn() println("INSERT INTO Song (songID, title, artist, album, filepath) VALUES ($newSongIndex, '$newTitle', '$newArtist', '$newAlbum', '$newSongPath');") dbConn.runQuery("INSERT INTO Song (songID, title, artist, album, filepath) VALUES ($newSongIndex, '$newTitle', '$newArtist', '$newAlbum', '$newSongPath');") dbConn.runQuery("INSERT INTO PlaylistSong VALUES ('All Songs', $newSongIndex);") println("INSERT INTO PlaylistSong VALUES ('All Songs', $newSongIndex);") dbConn.close() } } } else if (functComboBox.value == "Edit") { if (runActionOnComboBox.value == "Playlist") { if (currentPlaylist.isUserEditable) { EditPlaylistWindow.spawnEditPlaylistWindow(currentPlaylist) } else { Alert(Alert.AlertType.ERROR, "Cannot edit \"${currentPlaylist.playlistName}\".").showAndWait() } } else if (runActionOnComboBox.value == "Song") { } } else if (functComboBox.value == "Delete" && runActionOnComboBox.value == "Playlist") { if (currentPlaylist.isUserEditable) { val confirmation = Alert(Alert.AlertType.CONFIRMATION, "Are you sure you want to delete ${currentPlaylist.playlistName}?").showAndWait() if (confirmation.get() == ButtonType.OK) { val dbConn = DBConn() dbConn.runQuery("DELETE FROM PlaylistSong WHERE playlistName = '${currentPlaylist.playlistName}';") dbConn.runQuery("DELETE FROM Playlist WHERE playlistName = '${currentPlaylist.playlistName}';") dbConn.close() } } } } GridPane.setConstraints(executeButton, 97, 1) grid.children.add(executeButton) mp3Player.reload(MP3Player.songsInPlaylist(MP3Player.playlistFromName("All Songs"))) stage.show() val incrementSliderThread = Thread(Runnable { var unixTime = System.currentTimeMillis() while (true) { if (System.currentTimeMillis() - unixTime >= 100 && mp3Player.playing) { val tick = mp3Player.currentSongLength() / 10000000 seekSlider.value += tick unixTime = System.currentTimeMillis() } if (mp3Player.newSong) { seekSlider.adjustValue(0.0) mp3Player.newSong = false } } }) incrementSliderThread.start() } private fun login() = showNotImplemented() private fun showNotImplemented() = Alert(Alert.AlertType.WARNING, "Not implemented yet... But watch this space!").showAndWait() } }<file_sep>package sample import javafx.scene.media.Media import javafx.scene.media.MediaPlayer import java.io.File class MP3Player { private val queue = ArrayList<MediaPlayer>() var playing = false; private set @Volatile var newSong = false private var songIndex = 0 companion object { fun songsInPlaylist(playlist: Playlist): ArrayList<Song> { val dbConn = DBConn() val query = "SELECT Song.* FROM Song JOIN PlaylistSong ON Song.songID = PlaylistSong.songID WHERE PlaylistSong.playlistName = '${playlist.playlistName}';" val resultLines = dbConn.linesFromQuery(query) val songsInPlaylist = ArrayList<Song>() resultLines.forEach { val columns = it.split("\t") songsInPlaylist.add(Song( columns[0].trim().toInt(), columns[1].trim(), columns[2].trim(), columns[3].trim(), columns[4].trim().replace("@@", "\\") ))} dbConn.close() return songsInPlaylist } fun allPlaylists(): ArrayList<Playlist> { val dbConn = DBConn() val query = "SELECT Playlist.* FROM Playlist;" val resultLines = dbConn.linesFromQuery(query) val playlists = ArrayList<Playlist>() resultLines.forEach { val columns = it.split("\t") println("|${columns[2]}|") playlists.add(Playlist( columns[0].trim(), columns[1].trim(), columns[2].trim() != "0" ))} dbConn.close() return playlists } fun allPlaylistNames(): ArrayList<String> { val allNames = ArrayList<String>() allPlaylists().forEach { allNames.add(it.playlistName) } return allNames } fun playlistFromName(name: String): Playlist = allPlaylists().filter { it.playlistName == name }[0] fun songTitlesInPlaylist(playlist: Playlist): ArrayList<String> { val allSongNames = ArrayList<String>() songsInPlaylist(playlist).forEach { allSongNames.add(it.title) } return allSongNames } fun nthSongInPlaylist(playlist: Playlist, n: Int): Song { val dbConn = DBConn() val songID = dbConn.linesFromQuery("SELECT * FROM PlaylistSong WHERE playlistName = '${playlist.playlistName}' ORDER BY songID LIMIT $n, 1")[0].substringAfter("\t").trim().toInt() val songData = dbConn.linesFromQuery("SELECT * FROM Song WHERE songID = $songID;")[0].split("\t") return Song( songData[0].trim().toInt(), songData[1].trim(), songData[2].trim(), songData[3].trim(), songData[4].trim().replace("@@", "\\") ) } } fun play() { if (!playing) { queue[songIndex].play() playing = true } } fun pause() { if (playing) { queue[songIndex].pause() playing = false } } fun togglePlayPause() = if (playing) pause() else play() private fun mediaPlayerFromSong(song: Song): MediaPlayer { val uri = File(song.filepath).toURI() val media = Media(uri.toString()) val player = MediaPlayer(media) player.onEndOfMedia = Runnable { skipForward() } return player } fun push(song: Song) = queue.add(mediaPlayerFromSong(song)) fun push(vararg songs: Song) = songs.forEach { push(it) } fun push(songs: ArrayList<Song>) = songs.forEach { push(it) } fun clear() { queue.clear() songIndex = 0 } fun reload(songs: ArrayList<Song>) { stop() clear() push(songs) play() } fun startFromBeginning() { if (queue.isEmpty()) { println("Can't play an empty queue :(") } else { songIndex = 0 play() } } fun stop() { if (playing) { queue[songIndex].stop() playing = false } } fun seekTo(percentage: Double) { if (percentage > 100.0 || percentage < 0.0) { println("Cannot seek to $percentage, which is not in the interval [0, 100]") } else { queue[songIndex].seek(queue[songIndex].totalDuration.multiply(percentage / 100.0)) queue[songIndex].play() } } fun skipTo(newIndex: Int) { if (newIndex >= queue.size) { println("newIndex is $newIndex, which is out of range of the queue, which has ${queue.size} elements.") } else if (newIndex < 0) { println("newIndex is $newIndex, which is less than 0. ") } else { stop() songIndex = newIndex play() } } fun skipForward() { stop() if (songIndex + 1 < queue.size) { songIndex++ } else { songIndex = 0 } newSong = true play() } fun skipBackward() { stop() songIndex = Math.max(songIndex - 1, 0) play() } fun currentSongLength(): Double { if (queue.isNotEmpty() && songIndex < queue.size && songIndex >= 0) { return queue[songIndex].totalDuration.toMillis() } throw Exception("songIndex is $songIndex, whereas queue has ${queue.size} elements.") } }<file_sep>package sample class Song(url: String) { }<file_sep>package sample import com.jcraft.jsch.ChannelExec import com.jcraft.jsch.JSch import java.io.BufferedReader import java.io.InputStreamReader import java.util.* class DBConn(private val hostUser: String = "pi", private val hostPassword: String = "<PASSWORD>", private val hostURL: String = "www.musicmanager.duckdns.org", private val dbUser: String = "root", private val dbPassword: String = "<PASSWORD>", private val dbName: String = "MusicLibrary") { private var connected = false private val session = JSch().getSession(hostUser, hostURL, 22) private val config = Properties() fun connect() { if (!connected) { session.setPassword(hostPassword) config.put("StrictHostKeyChecking", "no") session.setConfig(config) session.connect() } connected = true } private fun outputFromCommand(command: String): String { if (!connected) { connect() } val channel = session.openChannel("exec") val instream = BufferedReader(InputStreamReader(channel.inputStream)) (channel as ChannelExec).setCommand(command) channel.connect() var output: String? var totalOutput = "" do { output = instream.readLine() totalOutput += if (output != null) { output } else { "" } } while (output != null) channel.disconnect() return totalOutput } fun linesFromQuery(query: String): Array<String> { val resultsAsLines = outputFromCommand("mysql --user=$dbUser --password=$dbPassword -D $dbName -e \"$query\" > foo.txt && perl -pi -e 's/\n/#/g' foo.txt && cat foo.txt").split("#") return if (resultsAsLines.isNotEmpty()) resultsAsLines.subList(1, resultsAsLines.size).filter { it.isNotBlank() }.toTypedArray() // first element is the column headings else resultsAsLines.toTypedArray() // which is empty } fun runQuery(query: String) { outputFromCommand("mysql --user=$dbUser --password=$db<PASSWORD> -D $dbName -e \"$query\"") } fun userExists(username: String, password: String) = linesFromQuery("SELECT * FROM User WHERE username = '$username' and password = <PASSWORD>';").isNotEmpty() fun makeNewUser(username: String, password: String) { runQuery("INSERT INTO User VALUES ('$username', '$password');") runQuery("INSERT INTO Playlist VALUES ('All Songs', '$username', 0);") } fun close() = session.disconnect() }<file_sep>package sample data class Song (val songID: Int, val title: String, val artist: String?, val album: String?, val filepath: String) data class Playlist (val playlistName: String, val username: String, val isUserEditable: Boolean) data class User (val username: String, val password: String)<file_sep>package sample import javafx.application.Application import javafx.geometry.Insets import javafx.scene.Scene import javafx.scene.control.Alert import javafx.scene.control.Button import javafx.scene.control.TextField import javafx.scene.layout.GridPane import javafx.stage.Stage class Main : Application() { override fun start(stage: Stage) // show login window { val grid = GridPane() val scene = Scene(grid) stage.scene = scene stage.title = "Log In" stage.setOnCloseRequest { System.exit(0) } grid.padding = Insets(10.0, 10.0, 10.0, 10.0) grid.vgap = 5.0 grid.hgap = 5.0 // login textbox val usernameBox = TextField() usernameBox.promptText = "<NAME>" GridPane.setConstraints(usernameBox, 0, 0, 30, 1) grid.children.add(usernameBox) // password textbox val passwordBox = TextField() passwordBox.promptText = "<PASSWORD>" GridPane.setConstraints(passwordBox, 0, 1, 30, 1) grid.children.add(passwordBox) // login button val loginButton = Button("Log in!") loginButton.setOnAction { val dbConn = DBConn() println("u|${usernameBox.text}|, p|${passwordBox.text}|") if (dbConn.userExists(usernameBox.text, passwordBox.text)) { MainWindow.show(User(usernameBox.text, passwordBox.text)) stage.close() } else { Alert(Alert.AlertType.ERROR, "This user does not exist. Dobule-check you typed the details in correctly, or try creating a new user instead.").showAndWait() } } GridPane.setConstraints(loginButton, 0, 2) grid.children.add(loginButton) val newUserButton = Button("Make a new user!") newUserButton.setOnAction { val dbConn = DBConn() dbConn.connect() val username = usernameBox.text val password = <PASSWORD>Box.text if (!dbConn.userExists(username, password)) { dbConn.makeNewUser(username, password) MainWindow.show(User(username, password)) } else { Alert(Alert.AlertType.ERROR, "This user alredy exists. Try logging in instead.").showAndWait() } dbConn.close() } GridPane.setConstraints(newUserButton, 5, 2) grid.children.add(newUserButton) stage.show() } private fun login(username: String, password: String) = MainWindow.show(User(username, password)) companion object { val FRESH_AF_PLAYLIST_NAME = "<New Playlist>" @JvmStatic fun main(args: Array<String>) { launch(Main::class.java) } } }
9ac946f20f081e154d441d64a18c38bb86111fd4
[ "Markdown", "Kotlin" ]
10
Kotlin
nikolaimerritt/MusicManager2
9b70e889cde7a001a2eb7798b6d647030c1c6fbf
2a5b9fbbf422d17a3af92b1b8eb20c22de2c34d1
refs/heads/master
<file_sep>from django.db import models class DataItem(models.Model): id = models.AutoField(primary_key = True) title = models.CharField(max_length = 30) def __str__(self): return str(self.file_name) + ' ' + str(self.file_name) <file_sep>from django.shortcuts import render from data.models import * from django.http import HttpResponse import os from django.views.decorators.csrf import csrf_exempt def home(request): return render(request, 'index.html', {'title': 'Home'}) def upload(request): title = request.POST['title'] text_content = request.POST['text_content'] data_item = DataItem(title = title) data_item.save() file_name = str(data_item.id) + '.txt' f = open('./data/static/' + file_name, 'a+') f.write(text_content) f.close() # error_msg = 'An error occured :/' return render(request, 'index.html', {'title': 'Home', 'success_msg': 'success'}); def file_list(request): data_items_list = os.listdir('./data/static') return render(request, 'file-list.html', {'data_items': data_items_list}) @csrf_exempt def file_download(request): file_name = './data/static/' + request.GET['file_name'] f = open(file_name, 'r') file_content = f.read() f.close() print('tesjfs' + file_content) return HttpResponse(file_content) <file_sep>from django.urls import path from .views import * urlpatterns = [ path('', home, name='home'), path('upload', upload, name='upload'), path('filelist', file_list, name='file_list'), path('file', file_download, name='file'), ] <file_sep>from django.contrib import admin from .models import DataItem admin.site.register(DataItem)
0ffa81124ee68c26ecbcf9e2cd154d39850e94be
[ "Python" ]
4
Python
i-64/xchange-hsbc
ef464a800b5030e0cc6e024e57eda3faf2d8ed00
0960beeed0336fc51c34daf8f6f1598cadad7926
refs/heads/master
<repo_name>Ayagaki-muti/Music<file_sep>/app/src/main/java/com/example/music/utils/ToastUtils.java package com.example.music.utils; import android.content.Context; import android.widget.Toast; public class ToastUtils { public static void Short(Context context,String message){ Toast.makeText(context.getApplicationContext(), message, Toast.LENGTH_SHORT).show(); } public static void Long(Context context,String message){ Toast.makeText(context.getApplicationContext(), message, Toast.LENGTH_LONG).show(); } } <file_sep>/app/src/main/java/com/example/music/ScrollingActivity.java package com.example.music; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.media.MediaPlayer; import android.os.Bundle; import com.example.music.beans.Music; import com.example.music.utils.SearchFile; import com.google.android.material.floatingactionbutton.FloatingActionButton; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.GridLayout; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.util.ArrayList; public class ScrollingActivity extends AppCompatActivity { private GridLayout v1; private TextView textView_basic; private ArrayList<Music> music; private LayoutInflater inflater; private TextView textView_music_id; private TextView textView_music_name; private TextView textView_music_singer; private View itemView; private int JiShuQi; private MediaPlayer mediaPlayer; private FloatingActionButton bt_add; private int[] likes; private int SZJSQ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scrolling); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); likes = new int[10]; v1 = (GridLayout)findViewById(R.id.MainForm); inflater =LayoutInflater.from(this); if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1); } else { bt_add = (FloatingActionButton)findViewById(R.id.addin); bt_add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //转到喜欢列表 Intent intent_add = new Intent(ScrollingActivity.this,activity_like.class); intent_add.putParcelableArrayListExtra("MUSIC",music); intent_add.putExtra("Likes",likes); startActivity(intent_add); } }); //View itemView = inflater.inflate(R.layout.list_items_layout, null, false); textView_music_id = new TextView(this); textView_music_name = new TextView(this); textView_music_singer = new TextView(this); //music返回歌曲列表 SZJSQ = 0; music = SearchFile.searchLocaltion(this); //对item界面进行添加元素 for(int i = 0;i<music.size();i++) { JiShuQi = i+1; itemView = new View(this); itemView = inflater.inflate(R.layout.list_items_layout, null, false); textView_music_id = new TextView(this); textView_music_name = new TextView(this); textView_music_singer = new TextView(this); textView_music_id = (TextView) itemView.findViewById(R.id.item_numbers); textView_music_id.setText(String.valueOf(i+1)); textView_music_name = itemView.findViewById(R.id.item_songs); textView_music_name.setText(music.get(i).getMusic_name()); textView_music_singer= (TextView)itemView.findViewById(R.id.item_singer); textView_music_singer.setText(music.get(i).getMusic_singer()); v1.addView(itemView); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TextView textView_find = new TextView(ScrollingActivity.this); textView_find = (TextView)view.findViewById(R.id.item_numbers); int a = Integer.valueOf(textView_find.getText().toString()); Intent intent = new Intent(ScrollingActivity.this,activity_play.class); intent.putParcelableArrayListExtra("MUSIC",music); intent.putExtra("JSQ",a-1); startActivity(intent); } }); itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { TextView textView_find = new TextView(ScrollingActivity.this); textView_find = (TextView)view.findViewById(R.id.item_numbers); int a = Integer.valueOf(textView_find.getText().toString()); System.out.println("当前的为:"+a); likes[SZJSQ] = a - 1; SZJSQ++; Toast.makeText(ScrollingActivity.this,"已经添加到我的喜欢",Toast.LENGTH_LONG).show(); return false; } }); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_scrolling, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
cd8c727c58f4f37a5a7cc39785ef6c255f90565f
[ "Java" ]
2
Java
Ayagaki-muti/Music
f82b5a21ececb3ffcbcbb638eaaf6864f4fc9ab5
654a5fd273d4ad28e6f3c94d798a6e285e779dcd
refs/heads/master
<repo_name>sravan7/Rainfall-rate-and-Onion-production<file_sep>/README.md # Rainfall rate and Onion production <file_sep>/onion2.py ''' Created on 09-Nov-2017 @author: srava ''' #http://pbpython.com/excel-pandas-comp-2.html import pandas as pd import matplotlib.pyplot as plt import numpy as np #from numpy import ma df = pd.read_csv('rainfall_filtered.csv'); print(df.head(5)) maha = df[df["State"] == "MADHYA MAHARASHTRA"] guj = df[df["State"] == "GUJARAT REGION"] mad = df[df["State"] == "EAST MADHYA PRADESH"] kar = df[df["State"] == "NORTH INTERIOR KARNATAKA"] print(maha.head(), guj.head(),mad.head(), kar.head()) #mh = maha #mh = maha[[str("Year"),"q1" , "q2", "q3","q4"]] #mp = mad[[ str("Year"),"q1" , "q2", "q3","q4"]] #gj = guj[[ str("Year"),"q1" , "q2", "q3","q4"]] #ka = kar[[ str("Year"),"q1" , "q2", "q3","q4"]] #print(mh) plt.figure(1) maha.plot(x="Year") plt.title("maharastra rain fall rate quarterly ") plt.xlabel("year") plt.ylabel("Rain fall rate ") plt.show() plt.figure(2) mad.plot(x="Year") plt.title("Madhya Pradesh rain fall rate quarterly ") plt.xlabel("year") plt.ylabel("Rain fall rate ") plt.show() plt.figure(3) guj.plot(x="Year") plt.title("Gujarat rain fall rate quarterly ") plt.xlabel("year") plt.ylabel("Rain fall rate ") plt.show() plt.figure(4) kar.plot(x="Year") plt.title("Kanataka rain fall rate quarterly ") plt.xlabel("year") plt.ylabel("Rain fall rate ") plt.show() <file_sep>/onion.py ''' Created on 08-Nov-2017 @author: srava ''' #http://pbpython.com/excel-pandas-comp-2.html #http://pbpython.com/excel-pandas-comp.html import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('onion.csv') print( df.tail(5)) hyd = df[df["Centre_Name"]=="HYDERABAD"] #chn = df[df["Centre_Name"]=="CHENNAI"] hyd["Date"] = pd.to_datetime(hyd["Date"] ) #chn["Date"] = pd.to_datetime(chn["Date"]) #print("dth 2000", hyd[hyd['Date'] >= '01-01-2000'].head() ) hyd = hyd[(hyd["Date"] >= "01-01-1998") & (hyd["Date"] <= "12-31-2015")] #chn = chn[(chn["Date"] >= "01-01-2000") & (chn["Date"] <= "03-30-2015")] #print("hyderabd", hyd) k = 1997 yearNo = [] q1 = [] q2 = [] q3 = [] q4 = [] for i in range(0,17) : k =k+1 yearNo.append(k) temp = (str(k)+"-"+"01"+"-"+"01" , str(k)+"-"+"03"+"-"+"30") q1.append(temp) q2.append(( str(k)+"-"+"04"+"-"+"01" , str(k)+"-"+"06"+"-"+"30" ) ) q3.append( (str(k)+"-"+"07"+"-"+"01" , str(k)+"-"+"09"+"-"+"30" ) ) q4.append(( str(k)+"-"+"10"+"-"+"01" , str(k)+"-"+"12"+"-"+"30" )) print(yearNo) q1m = [] q2m = [] q3m = [] q4m = [] print(q1) g = hyd[(hyd["Date"] >= "1998-01-01") & (hyd["Date"] <= "1998-03-30")]["Price"] print(hyd.head(5)) q = hyd[(hyd["Date"] >= "1998-04-01") & (hyd["Date"] <= "1998-06-30")]["Price"] print(hyd.head(5)) #print(g.head(5)) print("g count", g.count()) print("q count", q.count()) print("2nd quarterv mean",g.max(), g.min(), g.mode() , g.count(), g.mean() ) print("q s", q.max(), q.min(), q.mode() , q.count(), q.mean()) for year in range(0,17) : #print(q1[year]) #c = hyd[(hyd["Date"] >= q1[year][0] ) | (hyd["Date"] <= q1[year][1]) ] print(q1[year][0]) print(q1[year][1]) q1m.append(int( hyd[(hyd["Date"] >= q1[year][0] ) & (hyd["Date"] <= q1[year][1]) ]["Price"].mean() ) ) #print("inside looop", hyd[(hyd["Date"] >= q1[year][0] ) | (hyd["Date"] <= q1[year][1]) ]["Price"].mean() ) q2m.append( int( hyd[(hyd["Date"] >= q2[year][0] ) & (hyd["Date"] <= q2[year][1]) ]["Price"].mean()) ) q3m.append( int( hyd[(hyd["Date"] >= q3[year][0] ) & (hyd["Date"] <= q3[year][1]) ]["Price"].mean() )) q4m.append(int( hyd[(hyd["Date"] >= q4[year][0] ) & (hyd["Date"] <= q4[year][1]) ]["Price"].mean() )) #print(c) print(q1m) print(q2m) print(q3m) print(q4m) file = open("mean.csv", "w") file.write("year"+"," + "quarter1"+","+"quarter2"+","+"quarter3"+","+"quarter4"+ '\n') for i in range(0,17) : #print(yearNo[i]) #print(q1m[i]) file.write( str(yearNo[i]) +","+str(q1m[i]) + ","+str(q2m[i]) + ","+str(q3m[i]) + ","+str(q4m[i]) + "," +'\n') file.close() data = pd.read_csv("mean.csv") data.plot() plt.title("quarterly price of Onions from 1998 - 2014") plt.xlabel("year") plt.ylabel("Price ") plt.show()
e8aabe36d0e7e624ad3a0c9e577082c516a5a974
[ "Markdown", "Python" ]
3
Markdown
sravan7/Rainfall-rate-and-Onion-production
a90eae6abf089062ace7fc82c93dc3f428cb3a93
e010126367a0789e3094f6ff66788fe748c11b07
refs/heads/master
<repo_name>lucascbarbosa/Linear-Array-Processing-Python<file_sep>/convertItkToPlot.py def CreateParametricImage(bModeName, parametricName, colormap = 'jet', show = False, outFileName = None, maxParametricValue = None): '''Input: bModeName: parametricName: colormap: show: outFileName If show is true, display the parametric image immediately. If outFileName is true, save a PNG image of the output. ''' #read in B-mode image/parametric image import SimpleITK as sitk reader = sitk.ImageFileReader() reader.SetFileName(bModeName) bModeItk = reader.Execute() bMode = sitk.GetArrayFromImage(bModeItk).T bModeSpacing = bModeItk.GetSpacing() bModeOrigin = bModeItk.GetOrigin() reader.SetFileName(parametricName) paramImItk = reader.Execute() paramImage = sitk.GetArrayFromImage(paramImItk).T paramSpacing = paramImItk.GetSpacing() paramOrigin = paramImItk.GetOrigin() if maxParametricValue: paramImage[paramImage > maxParametricValue] = maxParametricValue print "Mean value in parametric image is: " + str(paramImage.mean() ) spacing = [ int( round(paramSpacing[0]/bModeSpacing[0]) ), int( round(paramSpacing[1]/bModeSpacing[1]) ) ] origin = [int( round(paramOrigin[0]/bModeSpacing[0]) ),int( round(paramOrigin[1]/bModeSpacing[1]) ) ] points,lines = bMode.shape #work out size of region in B-mode image bModeSizeY = spacing[0]*(paramImage.shape[0] - 1) + 1 bModeSizeX = spacing[1]*(paramImage.shape[1] - 1) + 1 from numpy import arange,zeros from scipy import interpolate paramImageUpInY = zeros( (bModeSizeY, paramImage.shape[1] ) ) paramImageUp = zeros( (bModeSizeY, bModeSizeX) ) #Upsample strain image to same spacing as B-mode image. paramRfYIndexes = arange(origin[0], origin[0] + spacing[0]*paramImage.shape[0], spacing[0] ) paramRfYIndexesNew = arange(origin[0], origin[0] + spacing[0]*(paramImage.shape[0]-1) + 1 ) paramRfXIndexes = arange(origin[1], origin[1] + spacing[1]*paramImage.shape[1], spacing[1] ) paramRfXIndexesNew = arange(origin[1], origin[1] + spacing[1]*(paramImage.shape[1]-1) + 1 ) #use old image to interpolate for x in range(paramImage.shape[1]): interp = interpolate.interp1d(paramRfYIndexes, paramImage[:,x], kind = 'nearest' ) paramImageUpInY[:, x] = interp(paramRfYIndexesNew ) for y in range(paramImageUp.shape[0]): interp = interpolate.interp1d(paramRfXIndexes, paramImageUpInY[y,:] ) paramImageUp[y, :] = interp( paramRfXIndexesNew ) '''Convert array containing param values to RGBALpha array''' from matplotlib import cm from matplotlib import pyplot palette = cm.ScalarMappable() palette.set_cmap(colormap) tempIm = palette.to_rgba(paramImageUp) palette = cm.ScalarMappable() palette.set_cmap('gray') bMode = palette.to_rgba(bMode) bMode[origin[0]:origin[0] + tempIm.shape[0],origin[1]:origin[1] + tempIm.shape[1], :] = tempIm if show: fig =pyplot.figure() ax = fig.add_subplot(111) cax = ax.imshow( bMode, extent = [0, bModeSpacing[1]*lines, bModeSpacing[0]*points, 0] , vmin = paramImage.min(), vmax = paramImage.max() ) cbar = fig.colorbar(cax) pyplot.show() if __name__ == '__main__': import sys if len(sys.argv) <4: CreateParametricImage(sys.argv[1], sys.argv[2], show = True) else: CreateParametricImage(sys.argv[1], sys.argv[2], show = True, maxParametricValue = float(sys.argv[3]) ) <file_sep>/chirpz.py """Chirp z-Transform. As described in <NAME>., <NAME> and <NAME>. The Chirp z-Transform Algorithm. IEEE Transactions on Audio and Electroacoustics, AU-17(2):86--92, 1969 """ import numpy as np def chirpz(x,A,W,M): """Compute the chirp z-transform. The discrete z-transform, X(z) = \sum_{n=0}^{N-1} x_n z^{-n} is calculated at M points, z_k = AW^-k, k = 0,1,...,M-1 for A and W complex, which gives X(z_k) = \sum_{n=0}^{N-1} x_n z_k^{-n} """ A = np.complex(A) W = np.complex(W) if np.issubdtype(np.complex,x.dtype) or np.issubdtype(np.float,x.dtype): dtype = x.dtype else: dtype = float x = np.asarray(x,dtype=np.complex) N = x.size L = int(2**np.ceil(np.log2(M+N-1))) n = np.arange(N,dtype=float) y = np.power(A,-n) * np.power(W,n**2 / 2.) * x Y = np.fft.fft(y,L) v = np.zeros(L,dtype=np.complex) v[:M] = np.power(W,-n[:M]**2/2.) v[L-N+1:] = np.power(W,-n[N-1:0:-1]**2/2.) V = np.fft.fft(v) g = np.fft.ifft(V*Y)[:M] k = np.arange(M) g *= np.power(W,k**2 / 2.) return g <file_sep>/generalizedSpectrum.py from rfData import rfClass class collapsedAverageImage(rfClass): def __init__(self, fname, ftype, freqLowMHz = 0.0, freqHighMHz = 15.0, windowYmm = 8, windowXmm = 8, overlapY = .75, overlapX = .75): '''At each block this function will compute a power spectrum. It will then fit that power spectrum to a Gaussian, and set the bounds on the chirpz transform to run from mu -sigma to mu + sigma. Input parameters: freqLowMHz: A low cut-off for the chirpz transform of the power spectrum calculation. freqHighMHz: The high cut-off for the chirpz transform of the power spectrum calcuation. windowYmm: Block size in axial direction in mm windowXmm: Block size in lateral direction in mm overlapY: Axial overlap between blocks as a percentage. overlapX: Lateral overlap between blocks as a percentage. ''' import numpy #Set up RF data object super(collapsedAverageImage, self).__init__(fname, ftype) #figure out how many 6 mm by 4 mm windows fit into image self.gsWindowYmm = windowYmm self.gsWindowXmm = windowXmm self.windowY =int( windowYmm/self.deltaY) self.windowX =int( windowXmm/self.deltaX) #make the windows odd numbers if not self.windowY%2: self.windowY +=1 if not self.windowX%2: self.windowX +=1 self.halfY = (self.windowY -1)/2 self.halfX = (self.windowX -1)/2 #overlap the windows axially and laterally stepY = int( (1-overlapY)*self.windowY ) startY = self.halfY stopY = self.points - self.halfY - 1 self.winCenterY = range(startY, stopY, stepY) self.numY = len(self.winCenterY) stepX = int( (1-overlapX)*self.windowX ) startX = self.halfX stopX = self.lines - self.halfX - 1 self.winCenterX = range(startX, stopX, stepX) self.numX = len(self.winCenterX) self.caStepX = stepX self.caStepY = stepY #Work out parameters for chirpz transform self.freqHigh = freqHighMHz self.freqLow = freqLowMHz #figure out block size in points self.psdPoints = 2*self.halfY self.psdPoints -= self.psdPoints%4 self.gsPoints = self.psdPoints self.psdPoints /= 2 freqStep = (freqHighMHz - freqLowMHz)/self.psdPoints self.psdFreq = numpy.arange(0,self.psdPoints)*freqStep + freqLowMHz fracUnitCircle = (freqHighMHz - freqLowMHz)/(self.fs/10**6) self.cztW = numpy.exp(1j* (-2*numpy.pi*fracUnitCircle)/self.psdPoints ) self.cztA = numpy.exp(1j* (2*numpy.pi*freqLowMHz/(self.fs/10**6) ) ) def ComputeCollapsedAverageImage(self, vMax = None, itkFileName = None): import numpy self.ReadFrame() self.CaAvgImage =numpy.zeros( (self.numY, self.numX,7) ) self.CaSlopeImage = numpy.zeros( (self.numY, self.numX,7) ) self.centerFrequency= numpy.zeros( (self.numY, self.numX) ) self.sigmaImage= numpy.zeros( (self.numY, self.numX) ) startY = self.halfY startX = self.halfX #work out time to compute a point, then spit out time to calculate image from time import time y = x = 0 t1 = time() tempRegion = self.data[self.winCenterY[y] - self.halfY:self.winCenterY[y] + self.halfY + 1, self.winCenterX[x] - self.halfX:self.winCenterX[x] + self.halfX + 1] self.CalculateGeneralizedSpectrum(region = tempRegion) t2 = time() print "Elapsed time was: " + str(t2-t1) + "seconds" print "Estimate time to compute an entire image is: " + str( (t2-t1)*self.numY*self.numX/3600. ) + " hours" counter = 0 #Compute whole image for y in range(self.numY): for x in range(self.numX): tempRegion = self.data[self.winCenterY[y] - self.halfY:self.winCenterY[y] + self.halfY + 1, self.winCenterX[x] - self.halfX:self.winCenterX[x] + self.halfX + 1] caBinned,caSlope, sigma, mu = self.CalculateGeneralizedSpectrum(region = tempRegion) self.CaAvgImage[y,x, :] = caBinned self.CaSlopeImage[y,x] =caSlope self.centerFrequency[y,x] = sigma self.sigmaImage[y,x] = mu counter += 1 print str(counter) + " completed of " + str(self.numY*self.numX) if vMax: self.caImage[self.caImage > vMax] = vMax #Write image to itk format if itkFileName: import itk p = itk.Point.F2() itkIm = itk.Image.F2.New() itkIm.SetRegions(self.sigmaImage.shape) itkIm.Allocate() itkIm.SetSpacing( [self.deltaY*self.caStepY, self.deltaX*self.caStepX] ) itkIm.SetOrigin( [startY*self.deltaY, startX*self.deltaX] ) writer = itk.ImageFileWriter.IF2.New() for freqBin in range(7): for countY in range(self.numY): for countX in range(self.numX): itkIm.SetPixel( [countY, countX], self.CaAvgImage[countY, countX, freqBin]) writer.SetInput(itkIm) writer.SetFileName(itkFileName + 'caBin' + str(freqBin) + '.mhd') writer.Update() for freqBin in range(7): for countY in range(self.numY): for countX in range(self.numX): itkIm.SetPixel( [countY, countX], self.CaSlopeImage[countY, countX, freqBin]) writer.SetInput(itkIm) writer.SetFileName(itkFileName + 'CaSlope' + str(freqBin) + '.mhd') writer.Update() for countY in range(self.numY): for countX in range(self.numX): itkIm.SetPixel( [countY, countX], self.centerFrequency[countY, countX]) writer.SetInput(itkIm) writer.SetFileName(itkFileName + 'centerFreq.mhd') writer.Update() for countY in range(self.numY): for countX in range(self.numX): itkIm.SetPixel( [countY, countX], self.sigmaImage[countY, countX]) writer.SetInput(itkIm) writer.SetFileName(itkFileName + 'sigma.mhd') writer.Update() def ComputeCollapsedAverageInRegion(self, fname): '''Create a windowY by windowX region, then compute the collapsed average in that region. Save a collapsed average image.''' import numpy self.SetRoiFixedSize(self.gsWindowXmm, self.gsWindowYmm) self.ReadFrame() dataBlock = self.data[self.roiY[0]:self.roiY[1], self.roiX[0]:self.roiX[1]] out1, out2, mu,sigma = self.CalculateGeneralizedSpectrum(dataBlock) from matplotlib import pyplot pyplot.plot(self.CAaxis, self.CA, 'k') pyplot.ylabel('Magnitude') pyplot.xlabel('Frequency difference (MHz)') pyplot.savefig(fname + 'collapsedAverage.pdf') pyplot.close() from matplotlib import pyplot import pdb pdb.set_trace() fig = pyplot.figure() axes = fig.add_subplot(111) spacingAxis = 1540./(2*self.CAaxis*10**6)*10**3 axes.plot(self.CAaxis, self.CA, 'k') step = len(self.CAaxis)//5 print "step is " + str(step) xticks = self.CAaxis[0::step] axes.set_xticks(xticks) xticklabelsFloats = spacingAxis[0::step] xtickLabels = [ '{:.2f}'.format(j) for j in xticklabelsFloats ] axes.set_xticklabels(xtickLabels ) axes.set_ylabel('Magnitude') axes.set_xlabel('Scatterer Spacing (mm)') pyplot.savefig(fname + 'collapsedAveragePlotBySpacing.png') pyplot.close() #color different regions from by each sigma '''fig = pyplot.figure() axes = fig.add_subplot(111) spacingAxis = 1540./(2*self.CAaxis*10**6)*10**3 axes.plot(self.CAaxis, self.CA, 'k') step = len(self.CAaxis)//5 print "step is " + str(step) xticks = self.CAaxis[0::step] axes.set_xticks(xticks) xticklabelsFloats = spacingAxis[0::step] xtickLabels = [ '{:.2f}'.format(j) for j in xticklabelsFloats ] axes.set_xticklabels(xtickLabels ) axes.set_ylabel('Magnitude') axes.set_xlabel('Scatterer Spacing (mm)') for i in range(3): axes.axvspan(sigma*(2*i), sigma*(2*i+1), alpha = .5) ''' pyplot.savefig(fname + 'collapsedAveragePlotBySpacingColored.png') pyplot.close() pyplot.imshow( numpy.flipud(abs(self.GS)), extent= [self.gsFreq.min(), self.gsFreq.max(), self.gsFreq.min(), self.gsFreq.max()] ) pyplot.xlabel('Frequency (MHz)') pyplot.ylabel('Frequency (MHz)') pyplot.colorbar() pyplot.savefig(fname + 'generalizedSpectrum.png') pyplot.close() def CalculateGeneralizedSpectrum(self, region): '''Use 3 50% overlapping windows axially to compute PSD. Calculate Power spectrum first. Normalize it to have a max value of 1. Fit this to a Gaussian. f(x) = exp[ -(x - mu)**2 / 2 (sigma**2)] A Gaussian falls to -6 dB (1/4 of max value) at a little more than one sigma. Use full window length to compute axial signal.''' from scipy.signal import hann,convolve from scipy import optimize, interpolate import numpy from chirpz import chirpz maxDataWindow = region[0:self.gsPoints, :] windowFuncPsd = hann(self.psdPoints+2)[1:-1].reshape(self.psdPoints,1) powerSpectrum = numpy.zeros( self.psdPoints ) #first compute the power spectrum, normalize it to maximum value for r in range(3): dataWindow = maxDataWindow[self.psdPoints/2*r:self.psdPoints/2*r + self.psdPoints, :]*windowFuncPsd fourierData = numpy.zeros( dataWindow.shape ) for l in range(maxDataWindow.shape[1]): fourierData[:,l] = abs(chirpz(dataWindow[:,l], self.cztA, self.cztW, self.psdPoints)) powerSpectrum += fourierData.mean(axis = 1) powerSpectrum /= powerSpectrum.max() #now fit the spectrum to a gaussian errfunc = lambda param,x,y: y - numpy.exp(- (x - param[0])**2/(2*param[1]**2) ) param0 = (5., 1.0) args = (self.psdFreq,powerSpectrum) param, message = optimize.leastsq(errfunc, param0, args) mu = param[0] sigma = param[1] if sigma < .75: sigma = .75 #set low and high frequency cutoffs based on output mu, sigma #3 Sigmas is 1% intensity on PSD is -20 dB lowCut = mu - 3*sigma if lowCut < 0: lowCut = 0 highCut = mu + 3*sigma if highCut > self.fs/10**6: highCut = self.fs/10**6 freqStep = (highCut - lowCut)/self.psdPoints spectrumFreq = numpy.arange(0,self.psdPoints)*freqStep + lowCut fracUnitCircle = (highCut - lowCut)/(self.fs/10**6) cztW = numpy.exp(1j* (-2*numpy.pi*fracUnitCircle)/self.psdPoints ) cztA = numpy.exp(1j* (2*numpy.pi*lowCut/(self.fs/10**6) ) ) self.gsFreq = spectrumFreq ########################### ###Time averaged GS######## ########################### GS = numpy.zeros( (self.psdPoints, self.psdPoints,3 ) , numpy.complex128) for r in range(3): dataWindow = maxDataWindow[self.psdPoints/2*r:self.psdPoints/2*r + self.psdPoints, :] maxPointDelay = dataWindow.argmax(axis = 0 )/self.fs dataWindow*=windowFuncPsd tempPoints = dataWindow.shape[0] tempLines = dataWindow.shape[1] fourierData = numpy.zeros( dataWindow.shape, numpy.complex128 ) for l in range(tempLines): fourierData[:,l] = chirpz(dataWindow[:,l], cztA, cztW, self.psdPoints) #get point delay in seconds delta = numpy.outer(spectrumFreq*10**6,maxPointDelay) phase = numpy.exp(1j*2*numpy.pi*delta) for l in range(tempLines): outerProd = numpy.outer(fourierData[:,l]*phase[:,l], fourierData[:,l].conjugate()*phase[:,l].conjugate() ) GS[:,:,r] += outerProd/abs(outerProd) numSegs = tempLines*3 GS = GS.sum(axis = 2)/numSegs ############################################## ########COMPUTE COLLAPSED AVERAGE############# ############################################## #Along diagonal lines the scatterer spacing/frequency difference is the same #exclude all the entries that have a larger scatter spacing/lower frequency difference #than 1.5 mm: .51 MHz #Exclude all sizes less than .5 mm, which is 1.54 MHz numFreq = len(spectrumFreq) self.CA = numpy.zeros(numFreq) counts = numpy.zeros(numFreq) for f1 in range(numFreq): for f2 in range(numFreq): d = abs(f1-f2) self.CA[d] += abs(GS[f1,f2]) counts[d] += 1 self.CA /= counts self.CAaxis = numpy.arange(numFreq)*freqStep self.GS = GS ####################################### ########COMPUTE THE AVERAGE OF THE##### ########COLLAPSED AVERAGE############## ###########AND THE SLOPE############### ###CA avg. bins: ###0.0-1.0 sigma ###1.0-2.0 sigma ###2.0-3.0 sigma ###3.0-4.0 sigma ###4.0-5.0 sigma ###5.0-6.0 sigma ###0.0-6.0 sigma ####################################### ###Work out leakage location from PSD####### self.psdLimit = (1540./(2*self.gsWindowYmm*10**-3/2 ))/10**6 secondDeriv = self.CA[0:-2] - 2*self.CA[1:-1] + self.CA[2:] psdInd = int(self.psdLimit/freqStep) psdInd = secondDeriv[0:psdInd+10].argmax() + 1 print "The PSD leakage stops at: " + str(secondDeriv[0:psdInd+10].argmax() +1 ) CAbinned = numpy.zeros(7) CAcounts = numpy.zeros(7) CAslope = numpy.zeros(7) for f, val in enumerate(self.CA): if f*freqStep > self.psdLimit and f*freqStep < 1.0*sigma: CAbinned[0] += val CAcounts[0] += 1 elif f*freqStep > 1.0*sigma and f*freqStep < 2.0*sigma: CAbinned[1] += val CAcounts[1] += 1 elif f*freqStep > 2.0*sigma and f*freqStep < 3.0*sigma: CAbinned[2] += val CAcounts[2] += 1 elif f*freqStep > 3.0*sigma and f*freqStep < 4.0*sigma: CAbinned[3] += val CAcounts[3] += 1 elif f*freqStep > 4.0*sigma and f*freqStep < 5.0*sigma: CAbinned[4] += val CAcounts[4] += 1 elif f*freqStep > 5.0*sigma and f*freqStep < 6.0*sigma: CAbinned[5] += val CAcounts[5] += 1 if f*freqStep > self.psdLimit: CAbinned[6] += val CAcounts[6] += 1 for ind,count in enumerate(CAcounts): if val > 0: CAbinned[ind] /= count ##compute slope of Collapsed Average for ind in range(7): if ind == 0 or ind == 6: lowCut = int(self.psdLimit/freqStep) else: lowCut = int(sigma*ind/freqStep) highCut = int(sigma*(ind+1)/freqStep) CAslope[ind] = self.ComputeSlope( self.CA[lowCut:highCut], self.CAaxis[lowCut:highCut]) return CAbinned, CAslope, mu, sigma def ComputeSlope(self, yData, xData): from numpy import zeros, ones, array from numpy.linalg import lstsq #want to solve equation y = mx + b for m #[x1 1 [m = [y1 # x2 1 b ] y2 # x3 1] y3] # #strain image will be smaller than displacement image A = ones( (len(xData),2) ) A[:,0] = xData b = yData out = lstsq(A, b) xVec = out[0] return xVec[0] <file_sep>/blockMatch.py #first define the class unique priority queue from Queue import PriorityQueue import heapq from rfData import rfClass import cv import numpy as np from matplotlib import pyplot as plt from scipy.signal import hilbert class UniquePriorityQueue(PriorityQueue): def _init(self, maxsize): '''This is meant to take in tuples of (-quality, locInd, iniDpY, iniDpX, region)''' PriorityQueue._init(self, maxsize) self.locations = [] self.itemsInQueue = [] def _put(self, item, heappush=heapq.heappush): #unique items added to list without checks if item[1] not in self.locations: self.locations.append(item[1]) self.itemsInQueue.append(item) PriorityQueue._put(self, item, heappush) #if already in list, then only insert if #quality is higher than what is already in list elif item[1] in self.locations: if abs(item[0]) < abs( self.itemsInQueue[ self.locations.index(item[1]) ][0] ): pass #no insertion, correlation is lower than what is already in list else: tmpItem = self.itemsInQueue.pop( self.locations.index(item[1]) ) self.queue.remove( tmpItem ) self.locations.remove(item[1]) self.locations.append(item[1]) self.itemsInQueue.append(item) PriorityQueue._put(self, item, heappush) def _get(self, heappop=heapq.heappop): item = PriorityQueue._get(self, heappop) self.itemsInQueue.pop( self.locations.index(item[1]) ) self.locations.remove(item[1]) return item class blockMatchClass(rfClass): def __init__(self, fname, dataType, postFile = None, selectRoi = False,windowYmm = 1.0, windowXmm = 4.0, rangeYmm = 1.0, rangeXmm = .6, overlap = .65, strainKernelmm = 6.0): '''Input: fname: (string) Either a file containing a sequence of frames with motion, or a pre-compression file. dataType: (string) The filetype of the input files, see rfClass for allowed types postFile: (string) A file of post compression data, the same type and dimensions as the input file windowYmm: (float) the axial window size of the block match window in mm windowXmm: (float) The lateral window size of the block match window in mm rangeYmm: (float) The axial search range for the block match window in mm rangeXmm: (float) The lateral search range for the block match window in mm overlap: (float) [0-1]. The axial overlap between block matching windows. strainKernelmm: (float) The size of the least squares strain estimation kernel in mm. ''' super(blockMatchClass, self).__init__(fname, dataType) if postFile: self.postRf = rfClass(postFile, dataType) else: self.postRf = None self.windowYmm = windowYmm self.windowXmm = windowXmm self.rangeYmm = rangeYmm self.rangeXmm = rangeXmm #axial block size self.windowY = int(self.windowYmm/self.deltaY) if not self.windowY%2: self.windowY += 1 self.halfY = self.windowY//2 #lateral block size if self.imageType == 'la': self.windowX = int(self.windowXmm/self.deltaX) else: self.windowX = 21 if not self.windowX%2: self.windowX +=1 self.halfX = self.windowX//2 #search range if self.imageType == 'la': self.rangeX = int(self.rangeXmm/self.deltaX) else: self.rangeX = 10 self.rangeY = int(self.rangeYmm/self.deltaY) self.smallRangeY = 3 self.smallRangeX = 2 #overlap and step self.overlap = overlap self.stepY =int( (1 - self.overlap)*self.windowY ) ####work out tracking boundaries self.startY = 0 + self.rangeY + self.smallRangeY + self.halfY self.stopY = self.points - self.halfY - self.smallRangeY - self.rangeY #last pixel that can fit a window self.startX = 0 + self.halfX + self.rangeX + self.smallRangeX self.stopX = self.lines - self.halfX - self.smallRangeX - self.rangeX ###Allow for selection of an ROI#### if self.imageType == 'la' and selectRoi: self.SetRoiBoxSelect() if self.roiX[0] > self.startX: self.startX = self.roiX[0] if self.roiX[1] < self.stopX: self.stopX = self.roiX[1] if self.roiY[0] > self.startY: self.startY = self.roiY[0] if self.roiY[1] < self.stopY: self.stopY = self.roiY[1] ###Re-adjust roiX, roiY for display self.roiY = [self.startY, self.stopY] self.roiX = [self.startX, self.stopX] if selectRoi and self.imageType == 'la': self.ShowRoiImage() ###create arrays containing window centers in rf data coordinates self.windowCenterY = range(self.startY,self.stopY, self.stepY) self.numY = len(self.windowCenterY) self.windowCenterX = range(self.startX,self.stopX) self.numX = len(self.windowCenterX) #work out strainwindow in rf pixels, divide by step to convert to displacement pixels #make odd number self.strainWindow = int(strainKernelmm/(self.deltaY*self.stepY) ) if not self.strainWindow%2: self.strainWindow += 1 self.halfLsq = self.strainWindow//2 self.strainwindowmm = self.strainWindow*self.deltaY*self.stepY if self.numY - 1 < self.strainWindow or self.numX < 1: print "ROI is too small" import sys sys.exit() def WriteParameterFile(self, fname): 'Write the block matching parameters to file' f = open(fname, 'w') f.write('Axial window length: ' + str(self.windowYmm) + ' mm. \n') f.write('Lateral window length: ' + str(self.windowXmm) + ' mm. \n') f.write('Axial search range: ' + str(self.rangeYmm) + ' mm. \n') f.write('Lateral search range: ' + str(self.rangeXmm) + ' mm. \n') f.write('Ovlerlap: ' + str(self.overlap) + '\n' ) def InitializeArrays(self): '''Called to clear out displacement and quality arrays if I'm looking at a sequence of strain images.''' ######allocate numpy arrays to store quality, dpy, dpx self.dpY = np.zeros( (self.numY, self.numX) ) self.dpX = np.zeros( (self.numY, self.numX) ) self.quality = np.zeros( (self.numY, self.numX) ) self.processed = np.zeros( (self.numY, self.numX) ) self.regionImage = np.zeros( (self.numY, self.numX) ) ####seed is tuple containing (quality, ptidx, region) self.seedList = UniquePriorityQueue() #work out number of seed points, and index into dp arrays seedsY = int(.05*self.numY) if seedsY == 0: seedsY = 1 seedsX = int(.05*self.numX) if seedsX == 0: seedsX = 1 strideY = self.numY/seedsY strideX = self.numX/seedsX self.seedsY = range(0,self.numY, strideY) self.seedsX = range(0,self.numX, strideX) #regionarray to determine how many points grown from a particular seed self.numRegions = len(self.seedsY)*len(self.seedsX) self.regionArray = np.ones( self.numRegions ) #for determining bad seeds self.threshold = round( (self.numY/10)*(self.numX/10) ) def CreateStrainImage(self, preFrame = 0, skipFrame = 0, vMax = None, pngFileName = None, itkFileName = None): '''With the given parameters, pre, and post RF data create a strain image.''' #get pre and post frame self.ReadFrame(preFrame) self.pre = self.data.copy() if self.postRf: self.postRf.ReadFrame(preFrame) self.post = self.postRf.data.copy() else: self.ReadFrame(preFrame + 1 + skipFrame) self.post = self.data.copy() self.InitializeArrays() #Perform tracking self.TrackSeeds() self.TrackNonSeeds() #self.DropOutCorrection() self.DisplacementToStrain() if vMax: self.strain[self.strain> vMax] = vMax #take the strain image and create a scan-converted strain image. startY =self.windowCenterY[self.halfLsq] startYdp = self.windowCenterY[0] startX =self.windowCenterX[0] stepY =self.stepY stepX =1 #Write image to itk format if itkFileName: import SimpleITK as sitk #First strain itkIm = sitk.GetImageFromArray(self.strain) halfWind = int( (self.strainWindow-1)/2 ) itkIm.SetSpacing( [self.deltaY*stepY, self.deltaX*stepX] ) itkIm.SetOrigin( [(startY + halfWind)*self.deltaY, startX*self.deltaX] ) writer = sitk.ImageFileWriter() if itkFileName[-4:] != '.mhd': itkFileName += '.mhd' writer.SetFileName(itkFileName) writer.Execute(itkIm) #dpY itkIm = sitk.GetImageFromArray(self.dpY) itkIm.SetSpacing( [self.deltaY*stepY, self.deltaX*stepX] ) itkIm.SetOrigin( [startY*self.deltaY, startX*self.deltaX] ) writer.SetFileName(itkFileName[:-4] + 'dispY.mhd') writer.Execute(itkIm) #dpX itkIm = sitk.GetImageFromArray(self.dpX) itkIm.SetSpacing( [self.deltaY*stepY, self.deltaX*stepX] ) itkIm.SetOrigin( [startY*self.deltaY, startX*self.deltaX] ) writer.SetFileName(itkFileName[:-4] + 'dispX.mhd') writer.Execute(itkIm) ##Write image to PNG self.strainRGB = self.CreateParametricImage(self.strain,[startY, startX], [stepY, stepX], colormap = 'gray' ) self.dpYRGB = self.CreateParametricImage(self.dpY,[startYdp, startX], [stepY, stepX] ) self.dpXRGB = self.CreateParametricImage(self.dpX,[startYdp, startX], [stepY, stepX]) self.qualityRGB = self.CreateParametricImage(self.quality,[startYdp, startX], [stepY, stepX] ) if pngFileName: if pngFileName[-4:] != '.png': pngFileName += '.png' from matplotlib import pyplot pyplot.imshow(self.strainRGB, extent = [0, self.fovX, self.fovY, 0], vmax = self.strain.max(), vmin = 0, cmap = 'gray') pyplot.colorbar() pyplot.savefig(pngFileName) pyplot.close() def RescaleRgbStrainImage(self, vMax): """This function rescales my scan-converted RGB strain image""" if self.strain is None: print 'Error, no strain image has been calculated yet.' return startY =self.windowCenterY[self.halfLsq] startYdp = self.windowCenterY[0] startX =self.windowCenterX[0] stepY =self.stepY stepX =1 tmpStrain = self.strain.copy() locs = tmpStrain > vMax tmpStrain[locs] = vMax self.strainRGB = self.CreateParametricImage(tmpStrain,[startY, startX], [stepY, stepX], colormap = 'gray' ) def DisplayScanConvertedStrainImage(self, vMax = .02): bmode = np.log10(abs(hilbert(self.data) ) ) bmode -= bmode.max() if self.imageType == 'la': fig = plt.figure() fig.canvas.set_window_title("B-mode image " ) ax = fig.add_subplot(1,1,1) ax.imshow(self.strainRGB, extent = [0, self.fovX, self.fovY, 0] ) ax.show() if self.imageType == 'ps': plt.pcolormesh(self.X,self.Y, bmode,hold = True, vmin = -3, vmax = 0, cmap = 'gray') tmpX = np.zeros(self.strain.shape) tmpY = np.zeros(self.strain.shape) strainYrf = self.windowCenterY[self.halfLsq:-self.halfLsq] for i in range(tmpX.shape[0]): for j in range(tmpY.shape[1]): tmpX[i,j] = self.X[strainYrf[i], self.windowCenterX[j] ] tmpY[i,j] = self.Y[strainYrf[i], self.windowCenterX[j] ] print tmpX.shape print tmpY.shape plt.pcolormesh(tmpX,tmpY, self.strain, vmin = 0, vmax = vMax, cmap = 'gray') plt.gca().set_axis_bgcolor("k") plt.ylim(plt.ylim()[::-1]) plt.show() def SubSampleFit(self,f): """This function takes a 3 by 1 array assumes a quadratic function and finds the maximum as if the function were continuous. The assumption is that f(x) = ax^2 + bx + c""" c = f[1] a = (f[0] + f[2] )/2. - c b = -(f[0] - f[2] )/2. delta = -b/(2*a) if abs(delta) > 1: delta = 0 return delta def AddToSeedList(self,maxCC, y,x, intDpY,intDpX, region ): """Add up to four neighbors to a point to the seed list. Perform bounds checking to make sure the neighbors aren't located out of the image. Notice that the Normalized cross-correlation goes in as the quality metric, and that the sign will be reversed inside the function as necessary. """ Sub2ind = lambda shape, row, col : shape[1]*row + col #add point above if y > 0 and not self.processed[y-1,x]: self.seedList.put( (-maxCC, Sub2ind(self.dpY.shape, y-1, x), intDpY,intDpX, region)) #add point below if y < self.numY - 1 and not self.processed[y+1,x]: self.seedList.put((-maxCC, Sub2ind(self.dpY.shape, y+1, x), intDpY,intDpX,region) ) #add point to left if x > 0 and not self.processed[y,x-1]: self.seedList.put( (-maxCC, Sub2ind(self.dpY.shape, y, x-1),intDpY,intDpX,region) ) #add point to right if x < self.numX - 1 and not self.processed[y, x+1]: self.seedList.put( (-maxCC, Sub2ind(self.dpY.shape, y, x+1),intDpY,intDpX,region) ) def TrackSeeds(self): """Perform block-matching only on the seed points """ #allocate array to hold results of cross correlation resultNp = np.float32( np.zeros( (2*self.rangeY + 1, 2*self.rangeX + 1) ) ) resultCv = cv.fromarray(resultNp) region = 0 #perform tracking on seed points for y in self.seedsY: for x in self.seedsX: self.processed[y,x] = True self.regionImage[y,x] = region #GRAB SLICE OF DATA FOR CC CONVERT TO CV FRIENDLY FORMAT startBlockY = self.windowCenterY[y] - self.halfY stopBlockY = self.windowCenterY[y] + self.halfY + 1 startBlockX = self.windowCenterX[x] - self.halfX stopBlockX = self.windowCenterX[x] + self.halfX + 1 template = cv.fromarray( np.float32(self.pre[startBlockY:stopBlockY, startBlockX:stopBlockX ] ) ) startBlockY = self.windowCenterY[y] - self.halfY - self.rangeY stopBlockY = self.windowCenterY[y] + self.halfY + 1 + self.rangeY startBlockX = self.windowCenterX[x] - self.halfX - self.rangeX stopBlockX = self.windowCenterX[x] + self.halfX + 1 + self.rangeX image = cv.fromarray( np.float32( self.post[startBlockY:stopBlockY, startBlockX:stopBlockX] ) ) cv.MatchTemplate(template, image, resultCv, cv.CV_TM_CCORR_NORMED ) resultNp = np.asarray(resultCv) #FIND MAXIMUM, PERFORM SUB-SAMPLE FITTING maxInd = resultNp.argmax() maxCC = resultNp.max() maxY, maxX = np.unravel_index(maxInd, resultNp.shape) self.quality[y,x] = maxCC #perform sub-sample fit if maxY > 0 and maxY < 2*self.rangeY - 1: deltaY = self.SubSampleFit(resultNp[maxY-1:maxY+2, maxX]) else: deltaY = 0.0 if maxX > 0 and maxX < 2*self.rangeX - 1: deltaX = self.SubSampleFit(resultNp[maxY, maxX-1:maxX + 2] ) else: deltaX = 0.0 self.dpY[y,x] = maxY - self.rangeY + deltaY self.dpX[y,x] = maxX - self.rangeX + deltaX intDpY = int(round(self.dpY[y,x])) intDpX = int(round(self.dpX[y,x])) #PUT ITEM IN SEED LIST self.AddToSeedList(maxCC, y,x, intDpY,intDpX, region) region +=1 def TrackNonSeeds(self): """Perform block-matching on all the non-seed points, using a very small search range. """ #re-allocate array to hold results of cross correlation resultNp = np.float32( np.zeros( (2*self.smallRangeY + 1, 2*self.smallRangeX + 1) ) ) resultCv = cv.fromarray(resultNp) #perform tracking on other points while self.seedList.qsize() > 0: (tempQuality, pointInd, iniDpY, iniDpX, region) = self.seedList.get() self.regionArray[region] += 1 (y,x) = np.unravel_index(pointInd, self.dpY.shape) self.processed[y,x] = True self.regionImage[y,x] = region #GRAB SLICE OF DATA FOR CC CONVERT TO CV FRIENDLY FORMAT startBlockY = self.windowCenterY[y] - self.halfY stopBlockY = self.windowCenterY[y] + self.halfY + 1 startBlockX = self.windowCenterX[x] - self.halfX stopBlockX = self.windowCenterX[x] + self.halfX + 1 template = cv.fromarray( np.float32(self.pre[startBlockY:stopBlockY, startBlockX:stopBlockX ] ) ) startBlockY = self.windowCenterY[y] - self.halfY - self.smallRangeY + iniDpY stopBlockY = self.windowCenterY[y] + self.halfY + self.smallRangeY + 1 + iniDpY startBlockX = self.windowCenterX[x] - self.halfX - self.smallRangeX + iniDpX stopBlockX = self.windowCenterX[x] + self.halfX + self.smallRangeX + 1 + iniDpX image = cv.fromarray( np.float32( self.post[startBlockY:stopBlockY, startBlockX:stopBlockX] ) ) cv.MatchTemplate(template, image, resultCv, cv.CV_TM_CCORR_NORMED ) resultNp = np.asarray(resultCv) #FIND MAXIMUM, PERFORM SUB-SAMPLE FITTING maxInd = resultNp.argmax() maxCC = resultNp.max() maxY, maxX = np.unravel_index(maxInd, resultNp.shape) self.quality[y,x] = maxCC #perform sub-sample fit #fit to f(x) = ax^2 + bx + c in both directions if maxY > 0 and maxY < 2*self.smallRangeY - 1: deltaY = self.SubSampleFit(resultNp[maxY-1:maxY+2, maxX]) else: deltaY = 0.0 if maxX > 0 and maxX < 2*self.smallRangeX - 1: deltaX = self.SubSampleFit(resultNp[maxY, maxX-1:maxX + 2] ) else: deltaX = 0.0 #Add in y displacement, keep within allowed range self.dpY[y,x] = maxY - self.smallRangeY + deltaY + iniDpY if self.dpY[y,x] > self.rangeY: self.dpY[y,x] = self.rangeY if self.dpY[y,x] < -self.rangeY: self.dpY[y,x] = -self.rangeY #add in x displacement, keep in range self.dpX[y,x] = maxX - self.smallRangeX + deltaX + iniDpX if self.dpX[y,x] > self.rangeX: self.dpX[y,x] = self.rangeX if self.dpX[y,x] < -self.rangeX: self.dpX[y,x] = -self.rangeX intDpY = int(round(self.dpY[y,x])) intDpX = int(round(self.dpX[y,x])) #PUT ITEM IN SEED LIST self.AddToSeedList(maxCC, y, x, intDpY,intDpX, region) def DropOutCorrection(self): """Re-run the algorithm, but replace the displacements in all the regions not grown from good seeds""" self.processed[:] = 0 #determine bad regions goodSeeds = np.zeros( self.numRegions ) goodSeeds[self.regionArray > self.threshold ] = 1 region = 0 #rerun good seed points for y in self.seedsY: for x in self.seedsX: if goodSeeds[region]: self.processed[y,x] = 1 intDpY = int(round(self.dpY[y,x])) intDpX = int(round(self.dpX[y,x])) #PUT ITEM IN SEED LIST self.AddToSeedList(self.quality[y,x], y,x, intDpY,intDpX, region) region += 1 #re-allocate array to hold results of cross correlation resultNp = np.float32( np.zeros( (2*self.smallRangeY + 1, 2*self.smallRangeX + 1) ) ) resultCv = cv.fromarray(resultNp) #rerun algorithm, if point was grown from good seed maintain it while self.seedList.qsize() > 0: (tempQuality, pointInd, iniDpY, iniDpX, region) = self.seedList.get() (y,x) = np.unravel_index(pointInd, self.dpY.shape) self.processed[y,x] = 1 #Re-process if not originally from a good seed if not goodSeeds[ self.regionImage[y,x] ]: self.regionImage[y,x] = region #GRAB SLICE OF DATA FOR CC CONVERT TO CV FRIENDLY FORMAT startBlockY = self.windowCenterY[y] - self.halfY stopBlockY = self.windowCenterY[y] + self.halfY + 1 startBlockX = self.windowCenterX[x] - self.halfX stopBlockX = self.windowCenterX[x] + self.halfX + 1 template = cv.fromarray( np.float32(self.pre[startBlockY:stopBlockY, startBlockX:stopBlockX ] ) ) startBlockY = self.windowCenterY[y] - self.halfY - self.smallRangeY + iniDpY stopBlockY = self.windowCenterY[y] + self.halfY + self.smallRangeY + 1 + iniDpY startBlockX = self.windowCenterX[x] - self.halfX - self.smallRangeX + iniDpX stopBlockX = self.windowCenterX[x] + self.halfX + self.smallRangeX + 1 + iniDpX image = cv.fromarray( np.float32( self.post[startBlockY:stopBlockY, startBlockX:stopBlockX] ) ) cv.MatchTemplate(template, image, resultCv, cv.CV_TM_CCORR_NORMED ) resultNp = np.asarray(resultCv) #FIND MAXIMUM, PERFORM SUB-SAMPLE FITTING maxInd = resultNp.argmax() maxCC = resultNp.max() maxY, maxX = np.unravel_index(maxInd, resultNp.shape) self.quality[y,x] = maxCC #perform sub-sample fit #fit to f(x) = ax^2 + bx + c in both directions if maxY > 0 and maxY < 2*self.smallRangeY - 1: deltaY = self.SubSampleFit(resultNp[maxY-1:maxY+2, maxX]) else: deltaY = 0.0 if maxX > 0 and maxX < 2*self.smallRangeX - 1: deltaX = self.SubSampleFit(resultNp[maxY, maxX-1:maxX + 2] ) else: deltaX = 0.0 self.dpY[y,x] = maxY - self.smallRangeY + deltaY + iniDpY if self.dpY[y,x] > self.rangeY: self.dpY[y,x] = self.rangeY if self.dpY[y,x] < -self.rangeY: self.dpY[y,x] = -self.rangeY self.dpX[y,x] = maxX - self.smallRangeX + deltaX + iniDpX if self.dpX[y,x] > self.rangeX: self.dpX[y,x] = self.rangeX if self.dpX[y,x] < -self.rangeX: self.dpX[y,x] = -self.rangeX intDpY = int(round(self.dpY[y,x])) intDpX = int(round(self.dpX[y,x])) #PUT ITEM IN SEED LIST self.AddToSeedList(maxCC, y,x, intDpY,intDpX, region) else: intDpY = int(round(self.dpY[y,x])) intDpX = int(round(self.dpY[y,x])) #PUT ITEM IN SEED LIST self.AddToSeedList(self.quality[y, x], y,x, intDpY,intDpX, region) def DisplacementToStrain(self): from numpy import zeros, ones, array from numpy.linalg import lstsq #want to solve equation y = mx + b for m #[x1 1 [m = [y1 # x2 1 b ] y2 # x3 1] y3] # #strain image will be smaller than displacement image self.strain = zeros( (self.numY - self.strainWindow + 1, self.numX) ) A = ones( (self.strainWindow,2) ) colOne = array( range(0, self.strainWindow) ) A[:,0] = colOne halfWindow = (self.strainWindow-1)/2 self.startYstrain = self.startY + self.stepY*halfWindow self.stopYstrain = self.stopY - self.stepY*halfWindow for y in range( halfWindow,self.numY - halfWindow): for x in range(self.numX): b = self.dpY[y - halfWindow: y + halfWindow + 1, x] out = lstsq(A, b) xVec = out[0] self.strain[y - halfWindow,x] = xVec[0] self.strain = self.strain/self.stepY self.strain = abs(self.strain) <file_sep>/interp2NoSplines.py def interp2(x,y,z, xi, yi): '''This function implements cubic interpolation without splines as described in: Cubic convolution interpolation for digital image processing. <NAME>. IEEE transactions on acoustics, speech, and signal processing. Vol. 29. No. 6. 1981. Input: x: A 1-D array containing the known values' x-location y: A 1-D array containing the known values' y-location z: A 2-D array containing the known values xi: 1-D or 2-D array of x-coordinates to be interpolated to yi: 1-D or 2-D array of y-coordinates to be interpolated to Output: F: 1-D or 2-D array of interpolated values ''' ##TODO change from matlab indexing## import numpy as np rows, cols = z.shape if len(x) != cols or len(y) != rows: print 'length of x and y arrays must match z shape' import sys sys.exit() xiOrig = xi.copy() xi = xi.flatten() yi = yi.flatten() if len(xi) != len(yi): print 'Length of xi and yi should match' import sys sys.exit() #Normalize the units on the requested positions to the given positions s = 1 + (xi - x[0])/(x[-1] - x[0])*(cols - 1) t = 1 + (yi - y[0])/(y[-1] - y[0])*(rows - 1) #2-D array element indexing, adjusted for boundary padding ndx = (t).astype('int') + (s - 1).astype('int')*(rows + 2) # Check for out of range values of s and set coordinate to 1 # + with logical arrays is like or s[(s<1) + (s>cols)] = 1 # Check for out of range values of t and set coordinate to 1 s[(t<1) + (t>rows)] = 1 #check for boundary values d = s==cols s = s - s.astype('int') s[d] = s[d] + 1. ndx[d] = ndx[d] - rows - 2 #check for boundary values d = t==rows t = t - t.astype('int') t[d] = t[d] + 1. ndx[d] = ndx[d] - rows - 1 #Expand z so interpolation is valid at the boundaries. zz = np.zeros( (z.shape[0]+2, z.shape[0]+2) ) zz[1:rows+1,1:cols+1] = z; zz[0,1:cols+1] = 3*z[0,:]-3*z[1,:]+z[2,:]; zz[rows+1,1:cols+1] = 3*z[rows-1,:]-3*z[rows-2,:]+z[rows-3,:]; zz[:,0] = 3*zz[:,1]-3*zz[:,2]+zz[:,3]; zz[:,cols+1] = 3*zz[:,cols]-3*zz[:,cols-1]+zz[:,cols-2]; rows += 2 # Now interpolate using computationally efficient algorithm. t0 = -t**3 + 2*t**2 -t t1 = 3*t**3 - 5*t**2 +2 t2 = -3*t**3 + 4*t**2 +t t = t**3-t**2 #Changes for compatability with numpy flatZZ = zz.T.flatten() ndx -= 1 F= ( flatZZ[ndx]*t0 + flatZZ[ndx+1]*t1 + flatZZ[ndx+2]*t2 + flatZZ[ndx+3]*t )* (-s**3 + 2*s**2 - s) ndx += rows; F += ( flatZZ[ndx]*t0 + flatZZ[ndx+1]*t1 + flatZZ[ndx+2]*t2 + flatZZ[ndx+3]*t ) * (3*s**3 - 5*s**2 + 2) ndx += rows; F += ( flatZZ[ndx]*t0 + flatZZ[ndx+1]*t1 + flatZZ[ndx+2]*t2 + flatZZ[ndx+3]*t ) * (-3*s**3 + 4*s**2 + s) ndx += rows; F += ( flatZZ[ndx]*t0 + flatZZ[ndx+1]*t1 + flatZZ[ndx+2]*t2 + flatZZ[ndx+3]*t ) * (s**3 - s**2) F /= 4; return F.reshape(xiOrig.shape) <file_sep>/rfData.py import numpy as np from matplotlib import pyplot as plt from scipy.signal import hilbert class rfClass(object): def __init__(self, filename, dataType, centerFreqSimulation = 5.0, sigmaSimulation = 1.0, fsSimulation = 40.0): '''Input: filename: The name of the file or directory the data is from dataType: A lowercase string indicating the type of the data, choices are: ei, elasticity imaging on the Seimens S2000 rfd, research mode on the Seimens S2000 rf, research mode with clinical software on Ultrasonix SonixTouch sim, file format for simulated data with linear array transducers, one frame only multiSim, file format for simulated data with linear array transducers, multiple frames ''' if not( dataType == 'ei' or dataType == 'rfd' or dataType == 'rf' or dataType =='sim' or dataType == 'multiSim' or dataType == 'multiFocus', 'wobbler2D'): print 'Error. Datatype must be ei,rfd,rf, sim, multiSim, or multiFocus ' return self.fname = filename self.dataType = dataType self.soundSpeed = 1540. #m/s self.data = None if dataType == 'ei': import os startdir = os.getcwd() os.chdir(self.fname) self.imageType == 'la' metaData = open('metaData.txt', 'r') metaList = [0,0,0,0] for i in range(4): metaList[i] = int(metaData.readline() ) metaData.close() nFrames = len( [name for name in os.listdir('.') if os.path.isfile(name)]) nFrames -= 1 #because of metaData.txt points = len( range( metaList[3]/2, metaList[2] + metaList[3]/2 ) ) aLines = metaList[1] self.nFrames = nFrames self.soundSpeed = 1540. #m/s self.fs = 40.*10**6 #Hz self.deltaX = 40./aLines #assume a 40 mm FOV self.deltaY = self.soundSpeed/(2*self.fs)*10**3 self.fovX = self.deltaX*(aLines-1) self.fovY = self.deltaY*(points -1 ) os.chdir(startdir) self.points = points self.lines = aLines if dataType == 'rfd': import readrfd hInfo = readrfd.headerInfo(filename) self.fs = hInfo[1] if hInfo[4] == 'phased sector': self.imageType = 'ps' self.deltaX = hInfo[5] self.aLineSpacing = hInfo[6] else: self.imageType = 'la' self.deltaX = (1./hInfo[2])*10. #read a frame to find out number of points and A lines tempFrame = readrfd.readrfd(filename, 1) self.nFrames = readrfd.rfdframes(filename) self.deltaY = self.soundSpeed/(2*self.fs)*10**3 self.fovX = self.deltaX*(tempFrame.shape[1] - 1) self.fovY = self.deltaY*(tempFrame.shape[0] -1 ) self.points = tempFrame.shape[0] self.lines = tempFrame.shape[1] if dataType == 'rf': #The header is 19 32-bit integers self.imageType = 'la' dataFile = open(self.fname, 'r') header = np.fromfile(dataFile, np.int32, 19) self.header = header self.fs = header[15] self.deltaY = self.soundSpeed/(2*self.fs)*10**3 self.points = header[3] self.lines = header[2] self.deltaX = 40./self.lines #parameter in header is broken, so assume a 40 mm FOV self.fovX = self.lines*self.deltaX self.fovY = self.points*self.deltaY self.nFrames = header[1] if dataType == 'wobbler2D': #The header is 19 32-bit integers self.imageType = 'wobbler' dataFile = open(self.fname, 'r') header = np.fromfile(dataFile, np.int32, 19) self.header = header self.fs = header[15] self.deltaY = self.soundSpeed/(2*self.fs)*10**3 self.points = header[3] self.lines = header[2] self.deltaX = 40./self.lines #parameter in header is broken, so assume a 40 mm FOV self.fovX = self.lines*self.deltaX self.fovY = self.points*self.deltaY self.nFrames = header[1] self.deltaTheta = np.pi/180*.410 self.R1 = 39.5 if dataType == 'sim': f = open(filename, 'rb') self.imageType == 'la' #in Hz self.freqstep =float( np.fromfile(f, np.double,1) ) self.points = int( np.fromfile(f, np.int32,1) ) self.lines = int( np.fromfile(f, np.int32,1) ) tempReal = np.fromfile(f,np.double, self.points*self.lines ) tempImag = np.fromfile(f, np.double, self.points*self.lines ) f.close() self.simFs = fsSimulation self.sigma = sigmaSimulation self.centerFreq = centerFreqSimulation self.deltaX = .2 #beamspacing in mm self.fovX = self.lines*self.deltaX if dataType == 'multiSim': f = open(filename, 'rb') self.imageType == 'la' #in Hz self.freqstep =float( np.fromfile(f, np.double,1) ) self.points = int( np.fromfile(f, np.int32,1) ) self.lines = int( np.fromfile(f, np.int32,1) ) self.nFrames = int(np.fromfile(f, np.int32,1) ) tempReal = np.fromfile(f,np.double, self.points*self.lines ) tempImag = np.fromfile(f, np.double, self.points*self.lines ) f.close() self.simFs = fsSimulation self.sigma = sigmaSimulation self.centerFreq = centerFreqSimulation self.deltaX = .2 #beamspacing in mm self.fovX = self.lines*self.deltaX if dataType == 'multiFocus': self.imageType == 'la' self.fs = 40.0E6 #self.deltaX = 0.09 self.deltaX = 0.15 #read a frame to find out number of points and A lines import os self.nFrames = len( os.listdir(filename) ) tempFrame = np.load(filename + '/001.npy') self.deltaY = self.soundSpeed/(2*self.fs)*10**3 self.fovX = self.deltaX*(tempFrame.shape[1] - 1) self.fovY = self.deltaY*(tempFrame.shape[0] -1 ) self.points = tempFrame.shape[0] self.lines = tempFrame.shape[1] if self.imageType == 'ps': rPos = self.deltaY*np.arange(self.points) thetaPos = self.deltaX*np.arange(-self.lines//2,-self.lines//2 + self.lines) THETA, R = np.meshgrid(thetaPos, rPos) ##for plotting self.X = R*np.sin(THETA) + self.aLineSpacing*np.arange(-self.lines//2,-self.lines//2 + self.lines) self.Y = R*np.cos(THETA) if self.imageType == 'wobbler': thetaPos = -self.lines/2*self.deltaTheta + np.arange(self.lines)*self.deltaTheta rPos = self.R1 + np.arange(self.points)*self.deltaY THETA, R = np.meshgrid(thetaPos, rPos) self.X = R*np.sin(THETA) self.Y = R*np.cos(THETA) self.roiX = [0, self.lines-1] self.roiY = [0, self.points - 1] def __iter__(self): self.iterIndex = 0 return self def next(self): if self.index == self.nFrames: raise StopIteration self.ReadFrame(self.iterIndex) self.iterIndex += 1 return self.data.copy() def ReadFrame(self, frameNo = 0): '''Read a single frame from the input file, the method varies depending on the file type that was read in. This can handle linear array data from the Seimens S2000 recorded in either mode or the Ultrasonix scanner recorded using the clinical software. For a simulated data file, the 2nd and 3rd parameters matter, not for real data. Input:: frameNo. The RF data frame from a file obtained off a real ultrasound scanner. CenterFreq: (Hz) The center frequency of the transmitted pulse for simulated ultrasound data. Sigma. (Hz) The standard deviation of the Gaussian shaped transmit pulse for simulated data. samplingFrequency. (Hz) The simulated sampling frequency for a simulated data set. Higher sampling frequencies are achieved through zero-padding.''' import os,numpy as np if self.dataType == 'ei': startdir = os.getcwd() os.chdir(self.fname) metaData = open('metaData.txt', 'r') metaList = [0,0,0,0] for i in range(4): metaList[i] = int(metaData.readline() ) metaData.close() points = len( range( metaList[3]/2, metaList[2] + metaList[3]/2 ) ) aLines = metaList[1] self.data = np.zeros( (points, aLines) ) readThisMany = (metaList[2]+ metaList[3]/2)*metaList[1] tempIn = open(str(frameNo), 'r') frame = fromfile(tempIn, np.int16, readThisMany) frame = frame.reshape( ( metaList[2]+ metaList[3]/2, metaList[1] ) , order = 'F' ) self.data[:,:] = frame[metaList[3]/2:metaList[3]/2 + metaList[2], :].copy('C') os.chdir(startdir) if self.dataType == 'rfd': import readrfd self.data = readrfd.readrfd(self.fname, frameNo + 1) if self.dataType == 'rf' or self.dataType == 'wobbler2D': #Read in the header, then read in up to one less frame than necessary dataFile = open(self.fname, 'r') header = np.fromfile(dataFile, np.int32, 19) if frameNo == 0: temp = np.fromfile( dataFile, np.int16, self.points*self.lines) self.data = temp.reshape( (self.points, self.lines),order='F') else: dataFile.seek( 2*self.points*self.lines*(frameNo-1), 1) temp = np.fromfile( dataFile, np.int16, self.points*self.lines) self.data = temp.reshape( (self.points, self.lines), order='F') if self.dataType == 'sim': ####To get the actual sampling frequency we will zero-pad up to the ###desired sampling frequency f = open(self.fname, 'rb') #in Hz self.freqstep =float( np.fromfile(f, np.double,1) ) tmpPoints = int( np.fromfile(f, np.int32,1) ) self.lines = int( np.fromfile(f, np.int32,1) ) tempReal = np.fromfile(f,np.double, tmpPoints*self.lines ) tempImag = np.fromfile(f, np.double, tmpPoints*self.lines ) f.close() pointsToDesiredFs = int(self.simFs*10**6/self.freqstep) self.fs = pointsToDesiredFs*self.freqstep self.freqData = (tempReal - 1j*tempImag).reshape( (tmpPoints, self.lines), order = 'F' ) import math f = np.arange(0,tmpPoints*self.freqstep, self.freqstep) self.pulseSpectrum = np.exp(-(f - self.centerFreq*10**6)*(f - self.centerFreq*10**6)/(2*(self.sigma*10**6)**2) ) temp = self.freqData*self.pulseSpectrum.reshape( (tmpPoints, 1) ) zeroPadded = np.zeros( (pointsToDesiredFs, self.lines) ) + 1j*np.zeros( (pointsToDesiredFs, self.lines) ) zeroPadded[0:tmpPoints, :] = temp self.data = np.fft.ifft(zeroPadded,axis=0 ).real self.points = pointsToDesiredFs self.fs = self.freqstep*self.points self.deltaY = 1540. / (2*self.fs)*10**3 self.fovY = self.deltaY*self.points if self.dataType == 'multiSim': ####To get the actual sampling frequency we will zero-pad up to the ###desired sampling frequency f = open(self.fname, 'rb') #in Hz self.freqstep =float( np.fromfile(f, np.double,1) ) tmpPoints = int( np.fromfile(f, np.int32,1) ) self.lines = int( np.fromfile(f, np.int32,1) ) self.nFrames = int(np.fromfile(f, np.int32, 1) ) #now jump ahead by as many frames as necessary #assume 64 bit, 8 byte doubles f.seek(8*2*tmpPoints*self.lines*frameNo, 1) #read in desired frame tempReal = np.fromfile(f,np.double, tmpPoints*self.lines ) tempImag = np.fromfile(f, np.double, tmpPoints*self.lines ) f.close() pointsToDesiredFs = int(self.simFs*10**6/self.freqstep) self.fs = pointsToDesiredFs*self.freqstep self.freqData = (tempReal - 1j*tempImag).reshape( (tmpPoints, self.lines), order = 'F' ) import math f = np.arange(0,tmpPoints*self.freqstep, self.freqstep) self.pulseSpectrum = np.exp(-(f - self.centerFreq*10**6)*(f - self.centerFreq*10**6)/(2*(self.sigma*10**6)**2) ) temp = self.freqData*self.pulseSpectrum.reshape( (tmpPoints, 1) ) zeroPadded = np.zeros( (pointsToDesiredFs, self.lines) ) + 1j*np.zeros( (pointsToDesiredFs, self.lines) ) zeroPadded[0:tmpPoints, :] = temp self.data = np.fft.ifft(zeroPadded,axis=0 ).real self.points = pointsToDesiredFs self.fs = self.freqstep*self.points self.deltaY = 1540. / (2*self.fs)*10**3 self.fovY = self.deltaY*self.points if self.dataType == 'multiFocus': self.data = np.load(self.fname + '/' + str(frameNo + 1).zfill(3) + '.npy') def SaveBModeImage(self, fname, image = 0, itkFileName = None, noPng = False): """Create a B-mode image, display it, and save it as a Png. The data can also be saved in Itk format.""" import matplotlib.cm as cm self.ReadFrame(image) bMode = np.log10(abs(hilbert(self.data, axis = 0))) bMode = bMode - bMode.max() bMode[ bMode < -3] = -3 #import matplotlib and create plot if not noPng: fig = plt.figure() ax = fig.add_subplot(1,1,1) if self.imageType == 'la': ax.imshow(bMode, cmap = cm.gray, vmin = -3, vmax = 0, extent = [0, self.fovX, self.fovY, 0]) ax.set_xlabel('Width (mm) ' ) ax.set_ylabel('Depth (mm) ' ) ax.set_xticks( np.arange(0, self.fovX, 10) ) ax.set_yticks( np.arange(0, self.fovY, 10) ) plt.savefig(fname + '.png') plt.close() if self.imageType == 'ps' or self.imageType == 'wobbler': ax.pcolormesh(self.X,self.Y, bMode, vmin = -3, vmax = 0, cmap = cm.gray) ax.set_axis_bgcolor("k") plt.ylim(plt.ylim()[::-1]) plt.savefig(fname + '.png') plt.close() if itkFileName: import SimpleITK as sitk itkIm = sitk.GetImageFromArray(bMode) itkIm.SetSpacing( [self.deltaY, self.deltaX] ) itkIm.SetOrigin( [0., 0.] ) writer = sitk.ImageFileWriter() if itkFileName[-4:] != '.mhd': itkFileName += '.mhd' writer.SetFileName(itkFileName) writer.Execute(itkIm) def DisplayBmodeImage(self, frameNo = 0): """Create a B-mode image and immediately display it. This is useful for interactive viewing of particular frames from a data set.""" self.ReadFrame(frameNo) temp = self.data #import signal processing modules and generate Numpy array bMode = np.log10(abs(hilbert(temp, axis = 0))) bMode = bMode - bMode.max() #import matplotlib and create plot import matplotlib.cm as cm fig = plt.figure() fig.canvas.set_window_title("B-mode image " ) ax = fig.add_subplot(1,1,1) if self.imageType == 'la': ax.imshow(bMode, cmap = cm.gray, vmin = -3, vmax = 0, extent = [0, self.fovX, self.fovY, 0]) if self.imageType == 'ps' or self.imageType == 'wobbler': ax.pcolormesh(self.X,self.Y, bMode, vmin = -3, vmax = 0, cmap = cm.gray) ax.set_axis_bgcolor("k") plt.ylim(plt.ylim()[::-1]) plt.show() def ParametricImageResolutionToBmodeResolution(self, paramImage, origin, spacing, inPixels = True, vmin= None, vmax = None): import numpy as np from scipy import interpolate if not inPixels: origin = np.array(origin); spacing = np.array(spacing) origin[0] /= self.deltaY spacing[0] /= self.deltaY origin[1] /= self.deltaX spacing[1] /= self.deltaX origin = origin.round().astype('int') spacing = spacing.round().astype('int') if vmin: paramImage[paramImage < vmin] = vmin if vmax: paramImage[paramImage > vmax] = vmax self.paramValMax = paramImage.max() self.paramValMin = paramImage.min() #work out size of region in B-mode image bModeSizeY = spacing[0]*(paramImage.shape[0] - 1) + 1 bModeSizeX = spacing[1]*(paramImage.shape[1] - 1) + 1 paramImageUpInY = np.zeros( (bModeSizeY, paramImage.shape[1] ) ) paramImageUp = np.zeros( (bModeSizeY, bModeSizeX) ) #Upsample strain image to same spacing as B-mode image. paramRfYIndexes = np.arange(origin[0], origin[0] + spacing[0]*paramImage.shape[0], spacing[0] ) paramRfYIndexesNew = np.arange(origin[0], origin[0] + spacing[0]*(paramImage.shape[0]-1) + 1 ) paramRfXIndexes = np.arange(origin[1], origin[1] + spacing[1]*paramImage.shape[1], spacing[1] ) paramRfXIndexesNew = np.arange(origin[1], origin[1] + spacing[1]*(paramImage.shape[1]-1) + 1 ) #use old image to interpolate for x in range(paramImage.shape[1]): interp = interpolate.interp1d(paramRfYIndexes, paramImage[:,x] ) paramImageUpInY[:, x] = interp(paramRfYIndexesNew ) for y in range(paramImageUp.shape[0]): interp = interpolate.interp1d(paramRfXIndexes, paramImageUpInY[y,:] ) paramImageUp[y, :] = interp( paramRfXIndexesNew ) return paramImageUp def CreateParametricImage(self, paramImage, origin, spacing, inPixels = True, colormap = 'jet',frameNo = 0, vmin = None, vmax = None): '''Input: paramImage: The image to place within the B-mode image origin: The B-mode pixel at which the upper left hand corner of the parametric image is located. [row, column] spacing: The number of B-mode pixels separating paramImage's pixels [rows, columns] colormap: The colormap of the parametric image''' paramImageUp = self.ParametricImageResolutionToBmodeResolution(paramImage, origin, spacing, inPixels, vmin, vmax) if not inPixels: origin = np.array(origin); spacing = np.array(spacing) origin[0] /= self.deltaY spacing[0] /= self.deltaY origin[1] /= self.deltaX spacing[1] /= self.deltaX origin = origin.round().astype('int') spacing = spacing.round().astype('int') #Convert array containing param values to RGBALpha array from matplotlib import cm palette = cm.ScalarMappable() palette.set_cmap(colormap) tempIm = palette.to_rgba(paramImageUp) #Create B-mode image self.ReadFrame(frameNo) from scipy.signal import hilbert from numpy import log10 bMode = log10(abs(hilbert(self.data, axis = 0))) bMode = bMode - bMode.max() bMode[bMode < -3] = -3 palette = cm.ScalarMappable() palette.set_cmap('gray') bMode = palette.to_rgba(bMode) bMode[origin[0]:origin[0] + tempIm.shape[0],origin[1]:origin[1] + tempIm.shape[1], :] = tempIm return bMode def SetRoiFixedSize(self, windowX = 4, windowY = 4, parametricImage = None, origin = None, spacing = None): #The Roi size here is given in mm. For a phased array probe windowX is the #number of A-lines in an ROI. self.ReadFrame() yExtent = self.deltaY*self.points xExtent = self.deltaX*self.lines bmode = np.log10(abs(hilbert(self.data, axis=0) ) ) bmode = bmode - bmode.max() #Compute the center of the bounding box and its size in pixels if self.imageType == 'la': if parametricImage == None: plt.imshow(bmode, extent = [0,xExtent,yExtent,0], cmap = 'gray', vmin = -3, vmax = 0 ) else: bMode = self.CreateParametricImage(paramImage, origin, spacing) plt.imshow(bmode, extent = [0,xExtent,yExtent,0], cmap = 'gray', vmin = -3, vmax = 0 ) x= plt.ginput() plt.close() boxX = int( x[0][0]/self.deltaX ) boxY = int( x[0][1]/self.deltaY ) windowY = int(windowY/self.deltaY) windowX = int(windowX/self.deltaX) xLow = boxX - windowX/2 if xLow < 0: xLow = 0 xHigh = xLow + windowX if xHigh > self.lines: xHigh = self.lines xLow = xHigh - windowX yLow = boxY - windowY/2 if yLow < 0: yLow = 0 yHigh = yLow + windowY if yHigh > self.points+1: yHigh = self.points+1 yLow = yHigh - windowY #Compute center of bounding box and its size, phased array probe if self.imageType == 'ps': fig = plt.figure() ax = fig.add_subplot(1,1,1) if parametricImage == None: ax.pcolormesh(self.X, self.Y, bmode, cmap = 'gray', vmin = -3, vmax = 0) else: ax.pcolormesh(self.X, self.Y, bmode, cmap = 'gray', vmin = -3, vmax = 0, hold = True) paramUp = self.ParametricImageResolutionToBmodeResolution(paramImage, origin, spacing) xx = self.X[origin[0]:origin[0] + paramUp.shape[0], origin[1]:origin[1] + paramUp.shape[1]] yy = self.Y[origin[0]:origin[0] + paramUp.shape[0], origin[1]:origin[1] + paramUp.shape[1]] ax.pcolormesh(xx,yy,paramUp) ax.set_axis_bgcolor("k") plt.ylim(plt.ylim()[::-1]) x = plt.ginput() plt.close() #pain in the ass #Find X-coordinates of beamlines at depth Y xPos = x[0][0] depth = x[0][1] angles = self.deltaX*np.arange(-self.lines//2,-self.lines//2 + self.lines) startX = self.aLineSpacing*np.arange(-self.lines//2,-self.lines//2 + self.lines) beamLineXPos = startX + np.sin(angles)*depth closestLine = abs(beamLineXPos - xPos).argmin() closestPoint = abs(np.cos(angles[closestLine])*np.arange(self.points)*self.deltaY - depth).argmin() extentRPixels = int(windowY/self.deltaY) xLow = closestLine - windowX//2 if xLow < 0: xLow = 0 xHigh = closestLine + windowX//2 if xHigh > self.lines: xHigh = self.lines xLow = xHigh - windowX yLow = closestPoint - extentRPixels//2 if yLow < 0: yLow = 0 yHigh = yLow + extentRPixels if yHigh > self.points: yHigh = self.points yLow = yHigh - extentRPixels if self.imageType == 'wobbler': fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.pcolormesh(self.X, self.Y, bmode, cmap = 'gray', vmin = -3, vmax = 0) ax.set_axis_bgcolor("k") plt.ylim(plt.ylim()[::-1]) x = plt.ginput() plt.close() #pain in the ass #Find X-coordinates of beamlines at depth Y xPos = x[0][0] depth = x[0][1] rPos = np.sqrt(xPos**2 + depth**2) thetaPos = np.arctan(xPos/depth) closestLine = int(thetaPos/self.deltaTheta + (self.lines/2) ) closestPoint = int( (rPos - self.R1)/self.deltaY ) extentRPixels = int(windowY/self.deltaY) xLow = closestLine - windowX//2 if xLow < 0: xLow = 0 xHigh = closestLine + windowX//2 if xHigh > self.lines: xHigh = self.lines xLow = xHigh - windowX yLow = closestPoint - extentRPixels//2 if yLow < 0: yLow = 0 yHigh = yLow + extentRPixels if yHigh > self.points: yHigh = self.points yLow = yHigh - extentRPixels self.roiX = [xLow, xHigh] self.roiY = [yLow, yHigh] #Draw Analysis Window import matplotlib.cm as cm palette = cm.gray palette.set_bad('r') from numpy import ma, zeros bmode = ma.array(bmode) bmode.mask = zeros(bmode.shape) bmode.mask[yLow:yHigh, xLow] = True bmode.mask[yLow:yHigh, xHigh] = True #since the pixels are so much thinner in the axial direction we use ten of them to #draw the ROI lineThickY = 10 if yLow < lineThickY: yLow = lineThickY bmode.mask[yLow-lineThickY:yLow, xLow:xHigh] = True if yHigh > bmode.mask.shape[0] - lineThickY: yHigh = bmode.mask.shape[0] - lineThickY bmode.mask[yHigh-lineThickY:yHigh, xLow:xHigh] = True fig = plt.figure() ax = fig.add_subplot(1,1,1) if self.imageType == 'la': plt.imshow(bmode, cmap = palette, extent = [0, xExtent, yExtent, 0 ],vmin = -3, vmax = 0) plt.xticks( np.arange(0,self.fovX, 10) ) plt.yticks( np.arange(0,self.fovY, 10) ) plt.xlabel('Width (mm)') plt.ylabel('Depth (mm)') plt.show() if self.imageType == 'ps' or self.imageType == 'wobbler': ax.pcolormesh(self.X, self.Y,bmode, cmap = palette, vmin = -3, vmax = 0) ax.set_axis_bgcolor("k") #plt.xticks( np.arange(0,self.fovX, 10) ) #plt.yticks( np.arange(0,self.fovY, 10) ) plt.xlabel('Width (mm)') plt.ylabel('Depth (mm)') plt.ylim(plt.ylim()[::-1]) plt.show() def SetRoiBoxSelect(self): """ Do a mouseclick somewhere, move the mouse to some destination, release the button. This class gives click- and release-events and also draws a line or a box from the click-point to the actual mouseposition (within the same axes) until the button is released. Within the method 'self.ignore()' it is checked wether the button from eventpress and eventrelease are the same. """ #Check that a Data set has been loaded if self.fname == None: return if self.imageType != 'la': print 'Function only valid for linear array probes. ' return from matplotlib.widgets import RectangleSelector current_ax = plt.subplot(111) # make a new plotingrangej def on_select(eclick, erelease): self.roiX = [0,0] self.roiY = [0,0] self.roiX[0] = int(erelease.xdata/self.deltaX) self.roiX[1] = int(eclick.xdata/self.deltaX) self.roiX.sort() self.roiY[0] = int(eclick.ydata/self.deltaY) self.roiY[1] = int(erelease.ydata/self.deltaY) self.roiY.sort() # drawtype is 'box' or 'line' or 'none' rectprops = dict(facecolor='red', edgecolor = 'red', alpha=0.5, fill=False) rs = RectangleSelector(current_ax, on_select, drawtype='box', useblit=True, button=[1,3], # don't use middle button minspanx=0, minspany=0, spancoords='data', rectprops = rectprops) #could be image sequence or just a 2-D image import types if type(self.data) == types.NoneType: self.ReadFrame(0) temp = self.data from scipy.signal import hilbert from numpy import log10 bMode = log10(abs(hilbert(temp, axis = 0))) bMode = bMode - bMode.max() bMode[bMode < -3] = -3 #import matplotlib and create plot import matplotlib.cm as cm plt.imshow(bMode, cmap = cm.gray, extent = [0, self.fovX, self.fovY, 0]) plt.show() def ReturnRoiData(self): return self.data[self.roiY[0]:self.roiY[1], self.roiX[0]:self.roiX[1]] def CreateRoiArray(self): #Check that a Data set has been loaded #could be image sequence or just a 2-D image if self.data == None: self.ReadFrame(0) temp = self.data #Create masked array with B-mode data, mask entries for box from scipy.signal import hilbert from numpy import log10 bMode = log10(abs(hilbert(temp, axis = 0))) bMode = bMode - bMode.max() bMode[bMode < -3] = -3 from numpy import ma, zeros bMode = ma.array(bMode) bMode.mask = zeros(bMode.shape) #replace some B-mode data with sentinels xLow = min(self.roiX); xHigh = max(self.roiX) yLow = min(self.roiY); yHigh = max(self.roiY) bMode.mask[yLow:yHigh, xLow] = True bMode.mask[yLow:yHigh, xHigh] = True #since the pixels are so much thinner in the axial direction we use ten of them to #draw the ROI lineThickY = 10 if yLow < lineThickY: yLow = lineThickY bMode.mask[yLow-lineThickY:yLow, xLow:xHigh] = True if yHigh > bMode.mask.shape[0] - lineThickY: yHigh = bMode.mask.shape[0] - lineThickY bMode.mask[yHigh-lineThickY:yHigh, xLow:xHigh] = True return bMode def ShowRoiImage(self): bMode = self.CreateRoiArray() #import matplotlib and create plot import matplotlib.cm as cm palette = cm.gray palette.set_bad('r') fig = plt.figure() ax = fig.add_subplot(1,1,1) if self.imageType == 'ps' or self.imageType == 'wobbler': ax.pcolormesh(self.X, self.Y,bMode, cmap = palette, vmin = -3, vmax = 0) ax.set_axis_bgcolor("k") #plt.xticks( np.arange(0,self.fovX, 10) ) #plt.yticks( np.arange(0,self.fovY, 10) ) plt.xlabel('Width (mm)') plt.ylabel('Depth (mm)') plt.ylim(plt.ylim()[::-1]) else: im = plt.imshow(bMode, cmap = palette, extent = [0, self.fovX, self.fovY, 0]) plt.show() def SaveRoiImage(self, fname): bMode = self.CreateRoiArray() #import matplotlib and create plot import matplotlib.cm as cm palette = cm.gray palette.set_bad('r') fig = plt.figure() ax = fig.add_subplot(1,1,1) if self.imageType == 'ps' or self.imageType == 'wobbler': ax.pcolormesh(self.X, self.Y,bMode, cmap = palette, vmin = -3, vmax = 0) ax.set_axis_bgcolor("k") #plt.xticks( np.arange(0,self.fovX, 10) ) #plt.yticks( np.arange(0,self.fovY, 10) ) plt.xlabel('Width (mm)') plt.ylabel('Depth (mm)') plt.ylim(plt.ylim()[::-1]) if self.imageType == 'wobbler': from matplotlib.ticker import MaxNLocator plt.gca().yaxis.set_major_locator(MaxNLocator(prune='lower')) else: im = plt.imshow(bMode, cmap = palette, extent = [0, self.fovX, self.fovY, 0]) plt.savefig(fname) plt.close() <file_sep>/rayleighImage.py from rfData import rfClass import numpy as np from scipy.signal import hilbert class rayleighClass(rfClass): def __init__(self, fname, ftype,windowYmm = 8, windowXmm = 8, overlapY = .75, overlapX = .75): #Set up RF data object super(rayleighClass, self).__init__(fname, ftype) #figure out how many windows fit into image self.windowYmm = windowYmm self.windowXmm = windowXmm self.windowY =int( windowYmm/self.deltaY) self.windowX =int( windowXmm/self.deltaX) #make the windows odd numbers if not self.windowY%2: self.windowY +=1 if not self.windowX%2: self.windowX +=1 self.halfY = (self.windowY -1)/2 self.halfX = (self.windowX -1)/2 #overlap the windows axially and laterally stepY = int( (1-overlapY)*self.windowY ) startY = self.halfY stopY = self.points - self.halfY - 1 self.winCenterY = range(startY, stopY, stepY) self.numY = len(self.winCenterY) stepX = int( (1-overlapX)*self.windowX ) startX = self.halfX stopX = self.lines - self.halfX - 1 self.winCenterX = range(startX, stopX, stepX) self.numX = len(self.winCenterX) self.stepX = stepX self.stepY = stepY def ComputeRayleighImage(self, vMax = None, itkFileName = None): self.ReadFrame() self.rayleighImage =np.zeros( (self.numY, self.numX) ) #Compute whole image counter = 0 for y, centerY in enumerate(self.winCenterY): for x, centerX in enumerate(self.winCenterX): tempRegion = self.data[centerY - self.halfY:centerY + self.halfY + 1, centerX - self.halfX:centerX + self.halfX + 1] envelope = abs(hilbert(tempRegion, axis = 0)) SNR = envelope.mean()/envelope.std() self.rayleighImage[y,x] = abs(SNR - 1.91) counter += 1 print str(counter) + " completed of " + str(self.numY*self.numX) startY = self.winCenterY[0] startX = self.winCenterY[1] self.rayleighRGB = self.CreateParametricImage(self.rayleighImage,[startY, startX], [self.stepY, self.stepX], colormap = 'jet' ) <file_sep>/faranScattering.py class faranBsc(object): def writeBackScatterFile(self,fname,d, deltaFreq = .01,maxFreq = 20, lowCutoff = .1, sosm = 1540.,soss = 5570.,sosshear = 3374.7,rhom = 1020.,rhos = 2540.,maxang = 180,maxn = 25): '''This is used to write a backscatter file to be read by the ultrasound simulation program. The parameters are identical to CalculateBSC(), except for the filename. Input: fname = the name of the output file to be written. d = the diameter of the scatterer in microns deltaFreq: (MHz) The frequency spacing of the calculation. maxFreq: (MHz) The maximum frequency for which the BSC is calculated. lowCutoff: (MHz) The low frequency for which the BSC is calculated. If this threshold is too low calculations may blow up and give NaN. The program assumes all BSC below lowCutoff are equal to zero.''' import numpy freq = numpy.arange(0, maxFreq, deltaFreq) #make all backscatter coefficients less than .1 MHz equal to 0 ind_lowCutoff = int(lowCutoff/deltaFreq) + 1 bscCurve = self.calculateBSC(freq[ind_lowCutoff:], d, sosm = 1540.,soss = 5570.,sosshear = 3374.7,rhom = 1020.,rhos = 2540.,maxang = 180,maxn = 25) #Add back in low frequency points by zero padding bscCurvePadded = numpy.zeros(len(freq)) bscCurvePadded[ind_lowCutoff:] = bscCurve #Add freq step and number of freq points to backscatter array bscCurveExtraInfo = numpy.zeros( len(bscCurvePadded) + 2) bscCurveExtraInfo[0] = deltaFreq bscCurveExtraInfo[1] = len(freq) bscCurveExtraInfo[2:] = bscCurvePadded bscCurveExtraInfo.tofile(fname) def calculateBSC(self, freq, d, sosm = 1540.,soss = 5570.,sosshear = 3374.7,rhom = 1020.,rhos = 2540.,maxang = 180,maxn = 25): '''a function to calculate normalized BSC curve from Tony's Faran code. Assume Tony's %code only calculates 180 degree k3absscatlength values. % %Input: %freq: The frequency over which I would like backscatter coefficients calculated in MHz %d: scatterer size, diameter, not radius (in unit of micro meter) % %output: BSCCurve: the BSC curve, in unit of 1/m/Sr % %<NAME>, 05/15/2006 ''' import numpy freq = freq*1.E6 #Work out ka values for frequency range and scatterer diameter sos=1540. #%speed of sound in surrounding media k=2*numpy.pi*freq/sos ka=k*d/2.*1e-6 #get scattering length and convert to backscatter coefficient kabsscatlength = self.sphere(ka,sosm,soss,sosshear,rhom,rhos,maxang,maxn) BSCCurve=(kabsscatlength/k)**2 return BSCCurve def sphere(self,ka,sosm,soss,sosshear,rhom,rhos,maxang,maxn): '''a function which calculates scattering cross sections for spheres according to Faran's theory; the output is a size of x3 vector giving the scattering length at 180 degrees and entries correspond to different values of ka (step size and max value of ka can be changed by manipulating the initialization of x3); note that the output is the absolute value of the scattering length (i.e. square root of the differential scattering cross section) times the wavenumber in the host medium (output is therefore unitless) ka = an array containing the (wavenumber)*(scatter radius) values over which scattering length will be calculated. sosm = speed of sound in host medium (fluid) soss = speed of sound in sphere sosshear = speed of sound for shear waves in sphere (if poisson's ratio (sigma)is available, sosshear=soss*sqrt((1-2*sigma)/2/(1-sigma))) rhom = host medium density rhos = sphere density maxang = maximum angle (in degrees) for which to calculate a cross section maxn = number of terms to include in the summation (higher number = greater accuracy but more computation time) %UNITS ARE OF NO CONSEQUENCE AS LONG AS THEY ARE CONSISTENT, I.E. %SPEEDS OF SOUND MUST HAVE THE SAME UNITS AND DENSITIES MUST HAVE THE SAME %UNITS %9/20/04 <NAME> %<NAME> added comments: % for glass beads we used in lab, Poisson's ratio sigma=0.21, %sosm=1540m/s %soss=5570m/s %so sosshear=3374.7m/s %rhom=1020 kg/m^3 %rhos=2540 kg/m^3 % %so an example to run this code is: % k3absscatlength = sphere(1540,5570,3374.7,1020,2540,180,100); ''' import numpy from scipy.special import lpmn #initialization theta= 180 x3=ka x2=x3*sosm/sosshear #ka value for shear waves in sphere x1=x3*sosm/soss #ka value for compressional waves in sphere #main loop over order n coeff = numpy.zeros((maxn + 1, len(x3)) ) + 1j*numpy.zeros((maxn + 1, len(x3))) for n in range(0,maxn + 1): #spherical bessel functions jx1=self.sphbess(n,x1) jx2=self.sphbess(n,x2) jx3=self.sphbess(n,x3) #spherical neumann functions nx3=self.sphneumm(n,x3) #derivatives of spherical bessel and neumann functions jpx3=n/(2*n+1.)*self.sphbess(n-1,x3)-(n+1)/(2*n+1.)*self.sphbess(n+1,x3) npx3=n/(2*n+1.)*self.sphneumm(n-1,x3)-(n+1)/(2*n+1.)*self.sphneumm(n+1,x3) jpx1=n/(2*n+1.)*self.sphbess(n-1,x1)-(n+1)/(2*n+1.)*self.sphbess(n+1,x1) jpx2=n/(2*n+1.)*self.sphbess(n-1,x2)-(n+1)/(2*n+1.)*self.sphbess(n+1,x2) #calculation of tandelta, tanalpha, tanbeta tandeltax3=-jx3/nx3 tanalphax3=-x3*jpx3/jx3 tanbetax3=-x3*npx3/nx3 tanalphax1=-x1*jpx1/jx1 tanalphax2=-x2*jpx2/jx2 #calculation of tanxsi [eq. 30] term1=tanalphax1/(tanalphax1+1) term2=(n**2+n)/(n**2+n-1-0.5*x2**2+tanalphax2) term3=(n**2+n-0.5*x2**2+2*tanalphax1)/(tanalphax1+1) term4=((n**2+n)*(tanalphax2+1))/(n**2+n-1-0.5*x2**2+tanalphax2) tanxsi=-x2**2/2*(term1-term2)/(term3-term4) #calculation of tanphi [eq. 29] tanPhi = -rhom/rhos*tanxsi #calculation of coefficient (2n+1)*sin(eta)*cos(eta) part of [eqn. 31] taneta=tandeltax3*(tanPhi+tanalphax3)/(tanPhi+tanbetax3) coeff[n,:]=(2*n+1)*taneta/(1+taneta**2)+1j*(2*n+1)*taneta**2/(1+taneta**2) #legendre polynomials temp, deriv=lpmn(n,n,numpy.cos(numpy.pi/180*theta)) #taking the first row is effectively taking m = 0 legend=temp[0,:].reshape((1,maxn + 1)) #matrix mult completes summation over n [eqn. 31] k3absscatlength=abs(numpy.dot(legend,coeff)) output = k3absscatlength.reshape( len(x3) ) output[numpy.isnan(output)] = 0 return output def sphneumm(self,order,vect): #calculates the spherical neumann function of order 'order' for the passed #vector import numpy from scipy.special import yv sphneumm=numpy.sqrt(numpy.pi/2./vect)*yv(order+0.5,vect) return sphneumm def sphbess(self,order,vect): '''calculates the spherical bessel function of order 'order' for the passed vector''' import numpy from scipy.special import jv sphbess=numpy.sqrt(numpy.pi/2./vect)*jv(order+0.5,vect) return sphbess <file_sep>/attenuation.py from rfData import rfClass class attenuation(rfClass): def __init__(self, sampleName, refName, dataType, numRefFrames = 0, refAttenuation = .5, freqLow = 2., freqHigh = 8., attenuationKernelSizeYmm = 12, blockYmm = 8, blockXmm = 8, overlapY = .85, overlapX = .85, bscFitRadius = 1.0, centerFreqSimulation = 5.0, sigmaSimulation = 1.0 ): '''Description: This class implements the reference phantom method of Yao et al. It inherits from the RF data class defined for working with simulations and Seimens rfd files. Input: sampleName: Filename of sample RF data refName: Filename of reference RF data dataType: The file type of the sample and reference RFdata. Must be the same. numRefFrames: The number of frames to use in the reference data set to calculate the reference spectrum. A value of 0 will use all the frames in the data set. refAttenuation: Assuming a linear dependence of attenuation on frequency, the attenuation slope in dB/(cm MHz) freqLow: The low frequency for the CZT in MHz freqHigh: The high frequency for the CZT in MHz attenuationKernelSizeMM: The size of the data segment used to do the least squares fitting to find center frequency shift with depth. blockSize[Y,X]mm: overlap[Y,X]: frequencySmoothingKernel: (MHz) Throughout the code I'll call the 1-D segment where a single FFT is performed a window A block will refer to a 2-D region spanning multiple windows axially and several A-lines where a power spectrum is calculated by averaging FFTs ''' import numpy super(attenuation, self).__init__(sampleName, dataType, centerFreqSimulation, sigmaSimulation) #For data from clinical scanners the reference and sample data will be the same file #type. For simulations I will be using a different file type if dataType == 'sim': self.refRf = rfClass(refName, 'multiSim', centerFreqSimulation, sigmaSimulation) else: self.refRf = rfClass(refName, dataType) #Work out which reference frames to use. First make sure that I haven't selected too many #to use if numRefFrames >= 1 and numRefFrames < self.refRf.nFrames: self.numRefFrames = numRefFrames else: self.numRefFrames = self.refRf.nFrames #Next, instead of picking adjacent reference frames, use reference frames that are evenly spaced #throughout the data set, to get beamlines as uncorrelated as possible self.refFrameStep = self.refRf.nFrames//numRefFrames self.refFrames = numpy.arange(0,numRefFrames)*self.refFrameStep #read in frames self.refRf.ReadFrame() self.ReadFrame() #Check to see that reference data and sample data contain #the same number of points if self.points != self.refRf.points or self.lines != self.refRf.lines: print "Error. Sample and reference images must be the same size. \n\ " return #Attenuation estimation parameters self.betaRef = refAttenuation #get window sizes and overlap self.blockYmm = blockYmm self.blockXmm = blockXmm self.overlapY = overlapY self.overlapX = overlapX self.blockX =int( self.blockXmm/self.deltaX) self.blockY =int( self.blockYmm/self.deltaY) #make the block sizes in pixels odd numbers for the sake of calculating their centers if not self.blockY%2: self.blockY +=1 if not self.blockX%2: self.blockX +=1 self.halfY = self.blockY//2 self.halfX = self.blockX//2 #overlap the blocks axially by self.overlapY% stepY = int( (1-self.overlapY)*self.blockY ) startY = self.halfY stopY = self.points - self.halfY - 1 self.blockCenterY = range(startY, stopY, stepY) #Set the attenuation kernel size in mm #Work it out in points #Make kernel size an odd number of poitns #Work out kernel size in mm self.attenuationKernelSizeYmm = attenuationKernelSizeYmm #attenuation estimation size used in least squares fit self.lsqFitPoints = int(self.attenuationKernelSizeYmm/(stepY*self.deltaY) ) #make this number odd if not self.lsqFitPoints%2: self.lsqFitPoints += 1 self.halfLsq = self.lsqFitPoints//2 self.attenuationKernelSizeYmm = self.lsqFitPoints*stepY*self.deltaY #cutoff some more points because of least squares fitting, cross correlation self.attenCenterY= self.blockCenterY[self.halfLsq + 1:-(self.halfLsq + 1)] stepX = int( (1-self.overlapX)*self.blockX ) if stepX < 1: stepX = 1 startX =self.halfX stopX = self.lines - self.halfX self.blockCenterX = range(startX, stopX, stepX) ##Within each block a Welch-Bartlett style spectrum will be estimated ##Figure out the number of points used in an individual FFT based on ##a 50% overlap and rounding the block size to be divisible by 4 self.blockY -= self.blockY%4 self.bartlettY = self.blockY//2 self.spectrumFreqStep = (freqHigh - freqLow)/self.bartlettY self.radiusInPoints = int( bscFitRadius/self.spectrumFreqStep) self.spectrumFreq = numpy.arange(0, self.bartlettY)*self.spectrumFreqStep + freqLow #set-up parameters for the chirpZ transform fracUnitCircle = (freqHigh - freqLow)/(self.fs/10**6) self.cztW = numpy.exp(1j* (-2*numpy.pi*fracUnitCircle)/self.bartlettY ) self.cztA = numpy.exp(1j* (2*numpy.pi*freqLow/(self.fs/10**6) ) ) def CalculateAttenuationImage(self, itkFileName = None): '''Estimate the center frequency by fitting to a Gaussian''' '''Loop through the image and calculate the spectral shift at each depth. Perform the operation 1 A-line at a time to avoid repeating calculations. Input: convertToRgb: A switch to make the output an RGB image that I can plot directly, but I'll lose the attenuation slope values. ''' import numpy import types if type(self.data) == types.NoneType: self.ReadFrame() self.refRf.ReadFrame() numY = len(self.attenCenterY) numX = len(self.blockCenterX) self.attenuationImage = numpy.zeros( (numY, numX) ) startY = self.attenCenterY[0] startX = self.blockCenterX[0] stepY = self.blockCenterY[1] - self.blockCenterY[0] stepX = self.blockCenterX[1] - self.blockCenterX[0] #first compute the power spectrum at each depth for the reference phantom and #average over all the blocks print "Computing reference spectrum" self.ComputeReferenceSpectrum() print "Computing sample spectrum" self.ComputeSampleSpectrum() #compute the log ratio #fit the log ratio at each depth to a line #to get derivative with respect to frequency #only look between within a 1 MHz radius of the #PSD peak print "Computing log ratios" dFreqLogRatio = numpy.zeros( ( self.refSpectrum.shape[1], numX) ) for countY in range(self.refSpectrum.shape[1]): for countX in range(numX): middleInd = self.refSpectrum[:,countY].argmax() lowInd = middleInd - self.radiusInPoints if lowInd < 0: lowInd = 0 highInd = middleInd + self.radiusInPoints if highInd > self.refSpectrum.shape[0]: highInd = self.refSpectrum.shape[0] logRatio = numpy.log( self.sampleSpectrum[lowInd:highInd,countY,countX]/self.refSpectrum[lowInd:highInd,countY] ) dFreqLogRatio[countY, countX] = self.lsqFit(logRatio, self.spectrumFreqStep) print "Performing linear fitting" attenKernelCm = self.attenuationKernelSizeYmm/10. #now compute the derivative with respect to depth for countY in range(numY): for countX in range(numX): self.attenuationImage[countY, countX] = self.lsqFit(dFreqLogRatio[countY:countY+self.lsqFitPoints, countX], attenKernelCm/self.lsqFitPoints ) #convert slope value to attenuation value self.attenuationImage *= -8.686/4. self.attenuationImage += self.betaRef print "Mean attenuation value of: " + str( self.attenuationImage.mean() ) self.attenuationImageRGB = self.CreateParametricImage(self.attenuationImage,[startY, startX], [stepY, stepX] ) #Write image to itk format if itkFileName: if 'mhd' not in itkFileName: itkFilename += '.mhd' import itk itkIm = itk.Image.F2.New() itkIm.SetRegions(self.attenuationImage.shape) itkIm.Allocate() for countY in range(numY): for countX in range(numX): itkIm.SetPixel( [countY, countX], self.attenuationImage[countY, countX]) itkIm.SetSpacing( [self.deltaY*stepY, self.deltaX*stepX] ) itkIm.SetOrigin( [startY*self.deltaY, startX*self.deltaX] ) writer = itk.ImageFileWriter[itk.Image.F2] writer.SetInput(itkIm) writer.SetFileName(itkFileName) writer.Update() def ComputeReferenceSpectrum(self): '''Calculate the spectrum of the reference region over every beamline at every depth, average over all the beamlines ''' import numpy self.refSpectrum = numpy.zeros((self.bartlettY, len(self.blockCenterY) )) for im in self.refFrames: self.refRf.ReadFrame(im) for countY,y in enumerate(self.blockCenterY): maxDataWindow = self.refRf.data[y - self.halfY:y + self.halfY+1, :] fftRef = self.CalculateSpectrumBlock(maxDataWindow) self.refSpectrum[:,countY] += fftRef #normalize for y in range(self.refSpectrum.shape[1]): self.refSpectrum[:,y] /= self.refSpectrum[:,y].max() def ComputeSampleSpectrum(self): '''Calculate the spectra for the sample. ''' import numpy self.sampleSpectrum = numpy.zeros( (self.bartlettY, len(self.blockCenterY), len(self.blockCenterX)) ) for countX, x in enumerate(self.blockCenterX): for countY,y in enumerate(self.blockCenterY): maxDataWindow = self.data[y - self.halfY:y + self.halfY+1, x - self.halfX: x + self.halfX + 1] fftSample = self.CalculateSpectrumBlock(maxDataWindow) self.sampleSpectrum[:,countY,countX] = fftSample.copy() self.sampleSpectrum[:, countY, countX]/=self.sampleSpectrum[:, countY, countX].max() def lsqFit(self, inputArray, spacing): ''' Input: inputArray: An array containing frequency shifts over depth. The units are MHz Output: slope: A scalar. The value of the slope of the least squares line fit. slope is in units of Mhz/cm #perform linear least squares fit to line #want to solve equation y = mx + b for m #[x1 1 [m = [y1 # x2 1 b ] y2 # x3 1] y3] # ''' import numpy A = numpy.ones( (len(inputArray),2) ) A[:,0] = numpy.arange(0, len(inputArray))*spacing b = inputArray out = numpy.linalg.lstsq(A, b) return out[0][0] def CalculateSpectrumBlock(self, region): '''Return the power spectrum of a region based on a Welch-Bartlett method. The block used in each FFT is half the length of the total window. The step size is half the size of the FFT window. Average over A-lines. This function assumes the size of the region is divisible by 4. It uses a zoomed in FFT to compute the power spectrum. The zoomed in FFT is given by the chirpz transform. ''' from scipy.signal import hann,convolve import numpy from chirpz import chirpz points = region.shape[0] points -= points%4 points /= 2 #######SAMPLE REGION############# maxDataWindow = region[0:2*points, :] #compute 3 fourier transforms and average them #Cutting off the zero-value end points of the hann window #so it matches Matlab's definition of the function windowFunc = hann(points+2)[1:-1].reshape(points,1) fftSample = numpy.zeros(points) for f in range(3): dataWindow = maxDataWindow[(points/2)*f:(points/2)*f + points, :]*windowFunc for l in range(dataWindow.shape[1]): fftSample += abs(chirpz(dataWindow[:,l], self.cztA, self.cztW, points))**2 return fftSample
0f159fc553febd1b100cc6c85b0b29b33fdfadb6
[ "Python" ]
9
Python
lucascbarbosa/Linear-Array-Processing-Python
7e98d4a29d8660804d22940e8ddf8843824d4b67
054287bb7285376ad450a7bcbb4b3a55413e7adf
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { DataService } from 'src/app/data.service'; import { ToastController, NavController } from '@ionic/angular'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) export class HomePage implements OnInit { public products: any[]; public contacts: any[]; public showList = true; constructor( private service: DataService, private toastCtrl: ToastController, private navCtrl: NavController, ) { } ngOnInit() { this.service.getContacts().subscribe( (res: any) => { this.contacts = res; } ); } async showMessage(message) { const toast = await this.toastCtrl.create({ message: message, closeButtonText: "Fechar", duration: 3000, showCloseButton: true }); toast.present(); } newCustomer() { this.navCtrl.navigateRoot('/new-contact'); } toggleView() { this.showList = !this.showList; } } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { environment } from 'src/environments/environment.prod'; @Injectable({ providedIn: 'root' }) export class DataService { constructor( private http: HttpClient ) { } createCustomer(data: any) { return this.http.post('http://localhost:8000/customer/create', data); } auth(data: any) { return this.http.post('http://localhost:8000/customer/authenticate', data); } resetPasswordCustomer(data: any) { return this.http.post('http://localhost:8000/customer/reset-password', data); } createContact(data: any) { return this.http.post('http://localhost:8000/contact/create', data); } getContacts() { return this.http.get('http://localhost:8000/contacts'); } } <file_sep># curso-angular8-final-project Projeto final desenvolvido para o curso de Angular 8 do instrutor <NAME>. <file_sep>import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { LoadingController, AlertController, ToastController, NavController } from '@ionic/angular'; import { DataService } from 'src/app/data.service'; @Component({ selector: 'app-reset-password', templateUrl: './reset-password.page.html', styleUrls: ['./reset-password.page.scss'], }) export class ResetPasswordPage implements OnInit { public form: FormGroup; constructor( private fb: FormBuilder, private service: DataService, private loadingCtrl: LoadingController, private alertCtrl: AlertController, private toastCtrl: ToastController, private navCtrl: NavController, ) { this.form = this.fb.group({ email: ['', Validators.compose([ Validators.required, Validators.minLength(5), Validators.maxLength(50), ])], newPassword: ['', Validators.compose([ Validators.required, Validators.minLength(6), Validators.maxLength(20), ])], }); } ngOnInit() { } async submit() { const loading = await this.loadingCtrl.create({ message: "Atualizando..." }); loading.present(); this.service.resetPasswordCustomer(this.form.value).subscribe( (res: any) => { this.showSuccess(res); loading.dismiss(); }, (err: any) => { this.showError("Falha ao redefinir a senha!"); loading.dismiss(); } ); } async showSuccess(data) { const alert = await this.alertCtrl.create({ message: "Senha redefinida com sucesso!", buttons: [ { text: "Continuar", handler: () => { this.navCtrl.navigateRoot('/login'); } } ] }); alert.present(); } async showError(message) { const toast = await this.toastCtrl.create({ message: message, duration: 3000, showCloseButton: true, closeButtonText: "Fechar" }); toast.present(); } }
d184bd38b447f4afaf49c1370e2bdfff5c4d9a96
[ "Markdown", "TypeScript" ]
4
TypeScript
lviesi/curso-angular8-final-project
2784e4bf495a12bf25495fafa2702306941d8247
4ac9d16847931ff61cce54101217675c27851bb0
refs/heads/master
<file_sep>if [[ ! -a ~/.oh-my-zsh ]] then sh -c "$(wget https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh -O -)" fi <file_sep>alias reload!='. ~/.zshrc' alias subl="sublime" alias pulls="hub browse -- pulls" alias mypulls="open https://github.com/pulls" alias pi="pod install" alias ddd='rm -rfd ~/Library/Developer/Xcode/DerivedData/*' alias gsu='git submodule update' alias gog="go get" alias opn="open -a" alias ipadd="ifconfig | grep inet" alias act="source venv/bin/activate" <file_sep># GRC colorizes nifty unix tools all over the place if (( $+commands[grc] )) && (( $+commands[brew] )) then # Instead of souricng this, it is copied from the following file so changes # be made to it: # source `brew --prefix`/etc/grc.bashrc GRC=`which grc` if [ "$TERM" != dumb ] && [ -n "$GRC" ] then alias colourify="$GRC -es --colour=auto" # alias colourifyconfigure='colourify -c `brew --prefix`/etc/configure' alias diff='colourify diff' # alias make='colourify make' alias gcc='colourify gcc' alias g++='colourify g++' alias as='colourify as' alias gas='colourify gas' alias ld='colourify ld' alias netstat='colourify netstat' alias ping='colourify ping' alias traceroute='colourify /usr/sbin/traceroute' alias head='colourify head' alias tail='colourify tail' alias dig='colourify dig' alias mount='colourify mount' alias ps='colourify ps' alias mtr='colourify mtr' alias df='colourify df' fi fi <file_sep>cask_args appdir: '/Applications' tap 'homebrew/bundle' cask 'atom' cask 'iterm2' brew 'git' brew 'ack' brew 'coreutils' brew 'go' brew 'dep' brew 'grc' brew 'hub' brew 'imagemagick' brew 'jp2a' brew 'libgit2' brew 'openssl' brew 'node' brew 'nave' brew 'readline' brew 'postgresql' brew 'shellcheck' brew 'spaceman-diff' brew 'spark' brew 'unrar' brew 'wget' brew 'terminal-notifier' brew 'fzf' cask 'firefox' cask 'google-chrome' cask 'vlc' cask 'jumpcut' ## not right now # # window management # cask 'spectacle' # brew 'ruby-build' # brew 'rbenv'
b182b89c0b6c4e1da352754892e64d812338bb2d
[ "Ruby", "Shell" ]
4
Shell
ianmdawson/dotfiles
44b3a44e7a1ce89e9e6622b696bce20085d8ec5a
2a241224978b3021135ce3ef01be6a754799b02a
refs/heads/master
<file_sep>#!/bin/bash scriptLoc="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" templateArchiveName="Gold-21iMac.zip" templateDirName=${templateArchiveName/.zip} remotefileURL="http://192.168.20.19/Avid_Settings/$templateArchiveName" zipDownload="${scriptLoc}/download/" zipLocal="${scriptLoc}/template" me=$(whoami) profilePath="/Users/Shared/AvidMediaComposer/Avid Users/$me" # Attempt download of archive from server to temporary location echo "Attempting to download AVID template from $remotefileURL" curl -f -# "$remotefileURL" > "$zipDownload/$templateArchiveName" # Check archive downloaded if [ -f "$zipDownload/$templateArchiveName" ] && [ -s "$zipDownload/$templateArchiveName" ] then # Remove old local archive rm -f "$zipLocal/$templateArchiveName" # Move to permanent storage location mv -vf "$zipDownload/$templateArchiveName" "$zipLocal/$templateArchiveName" else echo "Unable to download remote archive. Will continue copying locally-saved archive" # Remove 0k file rm -f "$zipDownload/$templateArchiveName" fi # Check archive exists at permanent storage location if [ -f "$zipLocal/$templateArchiveName" ] && [ -s "$zipLocal/$templateArchiveName" ] then # Make AVID profile dir if not present mkdir -p "$profilePath" # Remove existing AVID template dir rm -fr "$profilePath/$templateDirName" # Change owner profile dir chown -R $me "profilePath" # Unzip archive to AVID profile location (over-writes) unzip -o -d "$profilePath" "$zipLocal/$templateArchiveName" # Remove annoying extraneous directory rm -rf "$profilePath/__MACOSX"; # Make AVID profile dir world-writable chmod -R 777 "$profilePath/$templateDirName" else echo "Local template archive not found. Exiting" exit 1 fi exit 0
32541934c90afca887580053a06215ecdb2cec81
[ "Shell" ]
1
Shell
gsmc-alx/avid-profile-update
ac10c99fc4dd7966ced6a8a5419af60f51e246a6
977b76396c8325ed683ceb387c46d09a045c6515
refs/heads/master
<repo_name>bi0phaze/instaWrong<file_sep>/main.js var $ = require('jquery'); var _ = require('underscore'); var ItemCollection = require('./itemCollection'); var ItemModel = require('./itemModel'); $(document).ready(function () { page.init(); }); var page = { init: function() { page.initStyling(); page.initEvents(); }, initEvents: function (){ $('button').on('click','.submit', function(event){ event.preventDefault(); var newPic = new ItemModel ({ image: $('.urlinput').val(), caption: $('.titleinput').val(), }); newPic.save(); });
ea0f5e177d1dd22864ad228d77528bc594e5c2ed
[ "JavaScript" ]
1
JavaScript
bi0phaze/instaWrong
c0c9901609b2234c4634342d52cd4ef305f12a54
425c2f442d5e24c92e322ee17ab7f77ffa8b37c6
refs/heads/main
<repo_name>MrEyelet/IFX<file_sep>/src/main.js //Styles import "./scss/style.scss"
95ecfe63ba2deca7ac7a577eac457e40e481bca7
[ "JavaScript" ]
1
JavaScript
MrEyelet/IFX
5863b13736b2c12debffdcd952e55af4c52c2cb2
135df3097f163c3d7c7d71c071f9dd2ef1237632
refs/heads/master
<file_sep>#include <iostream> #include <fstream> #include <string> #include "cards.h" //#include "cards.cpp" using namespace std; void startGame(CardList& Player1, CardList& Player2, int count); int main(int argv, char** argc){ if(argv != 3){ cout << "Please provide 2 file names" << endl; return 1; } ifstream cardFile1 (argc[1]); ifstream cardFile2 (argc[2]); string line; if (cardFile1.fail()){ cout << "Could not open file " << argc[1]; return 1; } if (cardFile2.fail()){ cout << "Could not open file " << argc[2]; return 1; } // Create two objects of the class you defined // to contain two sets of cards in two input files CardList Player1("Alice"); CardList Player2("Bob"); // Read each file and store cards while (getline (cardFile1, line) && (line.length() > 0)){ // store line in each node of LinkedList // insert function here, insert into LL Player1.insertCard(line); } cardFile1.close(); while (getline (cardFile2, line) && (line.length() > 0)){ // store line in each node of LinkedList // insert function here, insert into LL Player2.insertCard(line); } cardFile2.close(); // Start the game int count(0); startGame(Player1,Player2, count); return 0; } void startGame(CardList& Player1, CardList& Player2, int count) { if(Player1.searchMatch(Player1, Player2)) { count++; return startGame(Player2, Player1, count); } else{ if(count % 2 == 0) { cout << Player1; cout << Player2; } else { cout << Player2; cout << Player1; } } }<file_sep>// cards.cpp // Authors: <NAME> | <NAME> | 5/8/21 // Implementation of the classes defined in cards.h #include "cards.h" #include <iostream> #include <string> using namespace std; CardList::CardList() { name = "No Name"; head = NULL; } CardList::CardList(string value) { name = value; head = NULL; } CardList::~CardList() { Card* n = head; Card* temp; while (n) { temp = n -> next; delete n; n = temp; } } void CardList::insertCard(string value) { if (!head) { head = new Card; head -> data = value; head -> next = NULL; } else { Card* n = head; while (n -> next) { n = n -> next; } n -> next = new Card; n -> next -> data = value; n -> next -> next = NULL; } } bool CardList::searchMatch(CardList& value1, CardList& value2) const{ Card* n1 = value1.head; Card* n2 = value2.head; if (!(n1) || !(n2)) { return false; } while (n1) { while (n2) { if (n1->data == n2->data) { cout << value1.name << " picked matching card " << n1->data << endl; value1.deleteCard(n1 -> data); value2.deleteCard(n2 -> data); return true; } n2 = n2 -> next; } n2 = value2.head; n1 = n1 -> next; } return false; } void CardList::deleteCard(string value) { Card* current = this -> head; Card* pred; if(current -> data == value) { this -> head = current -> next; delete current; } else { while (current) { if (current -> next -> data == value) { pred = current; break; } current = current -> next; } deleteCardHelper(pred, value); } } void CardList::deleteCardHelper(Card* pred, string value) { Card* temp; temp = pred -> next; pred -> next = temp -> next; delete temp; } bool CardList::operator==(const CardList& rhs) const { return (head -> data == rhs.head -> data); } // - return certain functions we want to call for the game to complete /* StartGame - Already Declared: Alice's name and hand & Bob's name and hand - Alice is going first - She search's for a card that matches with a card in Bob's hand - if there is a match -> delete card -> do Bob's turn - if there is not a match -> do Bob's turn - Bob is going after Alice - He search's for a card that matches with a card in Alice's hand - if there is a match -> delete card -> do Alice's turn - if there is not a match -> do Bob's turn - Repeat this process until both people don't have any matching cards left - Print Alice's hand, then print Bob's */<file_sep>// testcards.h //Authors: <NAME> | <NAME> | 5/8/21 //All test declarations go here // This is not exhaustive list of tests. You can remove / edit tests if it doesn't suit your design but you should definitelty add more // You should test all possible cornere cases of your public functions #ifndef TESTCARDS_H #define TESTCARDS_H #include "cards.h" #include <iostream> using namespace std; void test_constructor(); void test_insertCard(); void test_deleteCard(); void test_os_operator(); void test_double_equals_operator(); void START_TEST(string testname){ cout<<"Start "<<testname<<endl; } void END_TEST(string testname) { cout<<"End "<<testname<<endl<<endl; } /* void runAll(); void test_equal(); void test_card();] void test_destructor(); void test_remove(); void test_search(); */ /* void test_append_empty_list(); // A test case for append void test_append_single_element_list(); // Tests cases should be independent, // small, fast, orthogonal void test_equal_empty_list(); void test_card_operator_double_equal(); */ /* void assertEquals(string expected, string actual, string testDescription){ if (expected == actual) { cout<<"PASSED " << endl; } else { cout<< " FAILED: "<< testDescription << endl <<" Expected: "<< expected << " Actual: " << actual << endl; } } void assertEquals(int expected, int actual, string testDescription){ if (expected == actual) { cout<<"PASSED " << endl; } else { cout<< " FAILED: "<< testDescription << endl <<" Expected: "<< expected << " Actual: " << actual << endl; } } */ // You should add more assertEquals function for your classes. For example, Node/Card class /* void assertEquals(Node *expected, Node *actual, string testDescription){ if (expected == actual) { cout<<"PASSED " << endl; } else { cout<< " FAILED: "<< testDescription << endl <<" Expected: "<< expected << " Actual: " << actual << endl; } } */ #endif<file_sep>//cards.h //Authors: <NAME> | <NAME> | 5/6/21 //All class declarations go here #ifndef CARDS_H #define CARDS_H #include <iostream> using namespace std; struct Card { string data; Card* next; }; class CardList { public: // default constructor CardList(); // constructor --> initialize head to NULL and initialize name CardList(string value); // destructor ~CardList(); // insert void insertCard(string value); // search bool searchMatch(CardList& value1, CardList& value2) const; // delete void deleteCard(string value); void deleteCardHelper(Card* temp, string value); // operator << friend std::ostream& operator<<(std::ostream& os, const CardList& input) { Card* n = input.head; os << endl << input.name << "'s cards: " << endl; while (n) { os << n -> data; if (n -> next) { os << endl; } n = n -> next; } os << endl; return os; } // operator == bool operator==(const CardList& rhs) const; private: string name; Card* head; //void clear(Card* n); }; #endif // Use this file to define all your classes and public functions // You should design your program with OOP principles using classes // An example of class design would be having Card, CardList and Player as Classes. // Card represent Node in your LinkedList which has some data in it // CardList can be your LinkedList Class which has operations such as append, remove etc // Player class represents your game player // Think about the public functions that should be part of each class. (All public function need to be tested in unit testing) // One of the important functions is search / find which is essential for players to find cars in their opponent's "hand" // Make sure you overload the desired operators // This is not the fixed design. We are not expecting exactly 3 classes. You can do with less or more. // Important thing to consider is abstraction. /* OUTLINE OF WHAT WE NEED TO DO To-do's: - How many classes would we need? --> possibly 2 - Card class and CardList - Card struct/class (LinkedList) --> this is the NODE - first card --> head of the linkedlist - last card --> tail of the LL - next pointer to traverse through the list - a Node struct inside the class that consists of "int data" and "Node* next" - functions (public) - constructor - destructor - Two overloaded operators - << and == - CardList Class - within this class, there is the struct called Card - insert function - search function - delete function - Player Class? Questions - Is our approach appropriate (2 classes, 1 struct inside a class) - What's the point of the overload operator, elaborate on this please, both << and == - How are we supposed to store each card into a node, since each card is either (1) number/number or (2) number/letter - Could we possibly treat each card as a string, regardless of the integer value? - Is Card a class - Our design would be 2 classes: Cardlist and Player (Card struct within Cardlist) - How would the two classes interact? - Possibility: Have an overall class: Player. And inside the Cardlist - Clarify on what they mean when they say to have multiple classes --> how would they interact? */ /* player class - would use the interface created for it to play the game - use the container of cards to play the game - represents the deck of cards in your hands - user/player -> container of the cards - class that would use cardlist and card to play the game - Player that owns the hand of cards */<file_sep>// This file should contain unit tests for all the // public interfaces of the classes that you implement //#include "cards.h" //#include "cards.cpp" #include "testcards.h" #include <iostream> #include <string> #include <vector> using namespace std; int main(){ string divider = "--------------------------------------------------"; cout << endl; test_constructor(); cout << divider << endl << endl; test_insertCard(); cout << divider << endl << endl; test_deleteCard(); cout << divider << endl << endl; test_os_operator(); cout << divider << endl << endl; test_double_equals_operator(); return 0; } void test_constructor() { CardList NoName; CardList WithName("Yes Name"); START_TEST("Test Default Constructor and Parametrized Constructor"); cout << "Player WITHOUT initililized name VS. Player WITH initialized name" << endl; cout << endl << "ACTUAL OUTPUT -->"; cout << NoName; cout << WithName << endl; cout << "EXPECTED OUTPUT -->" << endl; cout << "No Name's Cards:\n"; cout << endl; cout << endl; cout << "Yes Name's cards:\n" << endl << endl; END_TEST("Default Constructor and Parametrized Constructor"); } void test_insertCard() { START_TEST("Test insertCard"); cout << endl; cout << "ACTUAL OUTPUT -->" << endl; CardList l1("Player 1"); cout << "Empty List:"; cout << l1; cout << "Appending an element to the empty list: "; l1.insertCard("h 4"); cout << l1 << endl; cout << "Appending an element to a one-element list: "; l1.insertCard("b 5"); cout << l1 << endl; cout << "EXPECTED OUTPUT -->" << endl; cout << "Empty List:\nPlayer 1's cards:" << endl << endl; cout << "Appending an element to the empty list:\nPlayer 1's cards:\nh 4" << endl << endl; cout << "Appending an element to a one-element list:\nPlayer 1's cards:\nh4\nb5\n" << endl << endl; END_TEST("insertCard"); } void test_deleteCard() { START_TEST("Test deleteCard"); cout << endl; cout <<"ACTUAL OUTPUT -->" << endl; CardList l1("Player 1"); l1.insertCard("f 9"); l1.insertCard("c 7"); l1.insertCard("q 3"); l1.insertCard("a 1"); cout << "Before deleting any cards:"; cout << l1 << endl; cout << "After deleting the first card:"; l1.deleteCard("f 9"); cout << l1 << endl; cout << "After deleting the card in the middle card: "; l1.deleteCard("q 3"); cout << l1 << endl; cout << "After deleting the last card"; l1.deleteCard("a 1"); cout << l1 << endl; cout << "EXPECTED OUTPUT -->" << endl; cout << "Before deleting any cards:\nPlayer 1's cards:\nf 9\nc 7\nq 3\na 1\n" << endl; cout << "After deleting the first card\nPlayer 1's cards:\nc 7\nq 3\na 1\n" << endl; cout << "After deleting the card in the middle:\nPlayer 1's cards:\nc 7\na 1\n" << endl; cout << "After deleting the last card\nPlayer 1's cards:\nc 7\n" << endl; END_TEST("deleteCard");; } void test_os_operator() { CardList l1("Player 1"); l1.insertCard("a 1"); l1.insertCard("b 2"); l1.insertCard("c 3"); l1.insertCard("d 4"); START_TEST("TEST OS operator"); cout << endl; cout << "Using the overloaded os operator to print out user cards:" << endl << endl; cout << "ACTUAL OUTPUT-->"; cout << l1; cout << "\nEXPECTED OUTPUT-->" << endl; cout << "Player 1's cards:\na 1\nb 2\nc 3\nd 4\n" << endl; END_TEST("OS operator"); } void test_double_equals_operator() { CardList l1("Player 1"); CardList l2("Player 2"); l1.insertCard("h 3"); l2.insertCard("h 3"); CardList l3("Player 1"); CardList l4("Player 2"); l3.insertCard("a 5"); l4.insertCard("n 3"); START_TEST(" Test Double equals operator"); cout << endl; cout << "Using the == operator to determine if cards \"h 3\" and \"h 3\" are the same: " << endl; cout<< "ACTUAL OUTPUT--> "; if(l1 == l2) { cout << "TRUE" << endl; } else { cout << "FALSE" << endl; } cout << "EXPECTED OUTPUT--> "; cout << "TRUE" << endl << endl; cout << "Using the == operator to determine if cards \"a 5\" and \"n 3\" are the same: " << endl; cout << "ACTUAL OUTPUT--> "; if(l3 == l4) { cout << "TRUE" << endl; } else { cout << "FALSE" << endl; } cout << "EXPECTED OUTPUT--> "; cout << "FALSE" << endl << endl; END_TEST("Double equals operator"); } /* void test_constructor() { CardList c1; CardList c2("Billy"); //assertEquals() } void runAll(){ test_insertCard(); test_deleteCard(); //test_equal(); //test_card(); } void test_equal(){ START_TEST("test_equal"); test_equal_empty_list(); //test_equal_single_element_list(); END_TEST("test_equal"); } void test_card(){ START_TEST("test_card"); test_card_operator_double_equal(); //test_equal_single_element_list(); END_TEST("test_card"); } void test_append_empty_list(){ // A test case for append single card node to LinkedList } void test_append_single_element_list(){ // Tests cases should be independent, // small, fast, orthogonal (test for different cases) } void test_equal_empty_list(){ string testname = "Case 0: [], []"; CardList l1; CardList l2; //assertEquals(l1, l2, testname); } void test_card_operator_double_equal(){ // Test to check if == is overloaded for card } */
46f5ab64d36aacfd4fd22d74707818ebc0f35203
[ "C++" ]
5
C++
svregala12/pa01_gutierrez_regala
862d4c707d02b10ad298275814dcf2fb9561e3d8
d18af4005c639f14078ceaeb40c9313dd808f54b
refs/heads/master
<file_sep>package gq.cader.realfakestoreapp.entity import android.content.Context import android.widget.TextView import gq.cader.realfakestoreapp.R import com.beust.klaxon.Klaxon import okhttp3.OkHttpClient import okhttp3.Request data class Product ( var productId: Int, var name: String, var price: Double, var description: String, var imgPath: String, var numInInventory: Int, var upc: String, var category: String) class ProductDAO(private val context: Context, val listView: TextView){ var thread = Thread(backgroundRequester()) lateinit var productList: List<Product> fun getAllProducts(){ thread.start() } private fun request() { val requestUrl = context.resources.getString(R.string.server_address) .plus("/api/products/") val client = OkHttpClient() val request = Request.Builder().url(requestUrl).get().build() val response = client.newCall(request).execute().body?.string().toString() productList = Klaxon().parseArray(response)!! } fun draw() { while (thread.isAlive){ Thread.sleep(100) } listView.text = productList?.get(0)?.toString() } inner class backgroundRequester : Runnable{ override fun run() { request() } } } enum class ProductCategory { BOOKS, CLOTHING, COSMETICS, HOME, OUTDOORS, TECHNOLOGY, TOYS } <file_sep>include ':app' rootProject.name='Real Fake Store App' <file_sep>package gq.cader.realfakestoreapp.ui.products import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ListView import android.widget.TextView import androidx.fragment.app.Fragment import gq.cader.realfakestoreapp.R import gq.cader.realfakestoreapp.entity.ProductDAO class ProductFragment : Fragment() { private lateinit var productViewModel: ProductViewModel private lateinit var listView: ListView private lateinit var productDAO: ProductDAO override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val root = inflater.inflate(R.layout.fragment_products, container, false) val textView: TextView = root.findViewById(R.id.textView2) //val recycleListView = root.findViewById<RecyclerView>(R.id.product_list) productDAO = ProductDAO(this.requireContext(), textView) productDAO.getAllProducts() return root } override fun onStart() { super.onStart() Thread.sleep(2000) productDAO.draw() } }<file_sep># RealFakeStoreApp Remember Real Fake Store? He's Back! ...in app form. Currently this project does very little. Check back soon <3!
018f47e6f6633bf681c139caed4c2e7900b812c4
[ "Markdown", "Kotlin", "Gradle" ]
4
Kotlin
CaderHancock/RealFakeStoreApp
ebb31054a3a9ad07b98b74fd543e748736247c37
f28cf4773bcb6279f4a0f783e9f2c4c4b629ddcc
refs/heads/master
<file_sep># 1.Query the existence of 1 course select * from course where name = 'Language'; # 2.Query the presence of both 1 and 2 courses select * from course where name = 'Language' or name = 'Math'; # 3.Query the student number and student name and average score of students whose average score is 60 or higher. select studentid,student.name,studentavg from student right join (select studentid,AVG(score) as studentavg from student_course group by studentid having studentavg>=60) as c on student.id =c.studentid; # 4.Query the SQL statement of student information that does not have grades in the student_course table select * from student left join student_course on student.id=student_course.studentid where student_course.score is null; # 5.Query all SQL with grades select * from student left join student_course on student.id=student_course.studentid where student_course.score is not null; # 6.Inquire about the information of classmates who have numbered 1 and also studied the course numbered 2 select * from student left join student_course on student.id=student_course.studentid where student.id = 1 and student_course.courseid = 2; # 7.Retrieve 1 student score with less than 60 scores in descending order select b.score from (select * from (select * from student_course order by score asc)as a where courseid = 2) as b where b.score < 60; # 8.Query the average grade of each course. The results are ranked in descending order of average grade. When the average grades are the same, they are sorted in ascending order by course number. select courseid ,AVG(score) as courseavg from student_course group by courseid order by courseavg asc,courseid desc; # 9.Query the name and score of a student whose course name is "Math" and whose score is less than 60 select student.name,a.score from student left join (select * from student_course left join course on student_course.courseid = course.id where course.name ='Math') as a on a.studentid = student.id where a.score <60;
c0d74120bb8c8f919db53d5db9d654ad0e59622b
[ "SQL" ]
1
SQL
Vicki7777777/multi-table-query-english-2019-10-12-6-42-26-537
f7b550018dde06f1b90d5f73e0a95b836c5b146e
b3ec0718a5f3335baa9a49b88d5a8803920f8397
refs/heads/master
<file_sep>var stores_table; var cookies_table; /** var monster = new Monster(); function Monster() { this.cookies_ = {}; this.reset = function () { this.cookies_ = {}; } } **/ chrome.browserAction.onClicked.addListener(function (tab) { var manager_url = chrome.extension.getURL("background.html"); focusOrCreateTab(manager_url); }); function focusOrCreateTab(url) { chrome.windows.getAll({ "populate": true }, function (windows) { var existing_tab = null; for (var i in windows) { var tabs = windows[i].tabs; for (var j in tabs) { var tab = tabs[j]; if (tab.url == url) { existing_tab = tab; break; } } } if (existing_tab) { chrome.tabs.update(existing_tab.id, { "selected": true }); } else { chrome.tabs.create({ "url": url, "selected": true }); } }); } document.addEventListener('DOMContentLoaded', on_load); function on_load() { chrome.cookies.getAllCookieStores(processCookieStores); stores_table = document.getElementById('stores_table'); cookies_table = document.getElementById('cookies_table'); setTimeout(function () { location.reload(true) }, 60000); document.getElementById("refresh").onclick = function () { location.reload(true); }; document.getElementById("clear").onclick = function () { chrome.browsingData.remove({ "since": 0 }, { "cookies": true }, overlay('Cookies cleared.', 1000)); location.reload(true); }; } function processCookieStores(cookiestores) { var tbody = stores_table.getElementsByTagName("tbody")[0]; for (var cookiestore in cookiestores) { var row = document.createElement("tr"); row.innerHTML += "<td>" + cookiestores[cookiestore].id + "</td>"; row.innerHTML += "<td>" + cookiestores[cookiestore].tabIds + "</td>"; tbody.appendChild(row); chrome.cookies.getAll({ "storeId": cookiestore.id }, processCookies); } stores_table.appendChild(tbody); } function processCookies(cookies) { var tbody = cookies_table.getElementsByTagName("tbody")[0]; cookies_table.appendChild(tbody); for (var cookie in cookies) { var row = document.createElement("tr"); tbody.appendChild(row); var button = document.createElement("input"); button.setAttribute("type", "button"); button.setAttribute("class", "delete"); var buttonid = "button" + cookies[cookie].storeId + cookie; button.setAttribute("id", buttonid); button.value = "X"; var col = document.createElement("td"); col.appendChild(button); row.appendChild(col); row.innerHTML += "<td>" + processDomain(cookies[cookie].domain) + "</td>"; row.innerHTML += "<td>" + cookies[cookie].domain + "</td>"; row.innerHTML += "<td>" + cookies[cookie].name + "</td>"; row.innerHTML += "<td>" + cookies[cookie].path + "</td>"; row.innerHTML += "<td>" + cookies[cookie].session + "</td>"; row.innerHTML += "<td>" + cookies[cookie].secure + "</td>"; row.innerHTML += "<td>" + cookies[cookie].httpOnly + "</td>"; row.innerHTML += "<td>" + cookies[cookie].hostOnly + "</td>"; row.innerHTML += "<td>" + cookies[cookie].storeId + "</td>"; row.innerHTML += "<td>" + cookies[cookie].expirationDate + "</td>"; row.innerHTML += "<td class=\"value\">" + cookies[cookie].value + "</td>"; var secure = cookies[cookie].secure + ""; var name = cookies[cookie].name + ""; var path = cookies[cookie].path + ""; var domain = cookies[cookie].domain + ""; var storeId = cookies[cookie].storeId + ""; document.getElementById(buttonid).onclick = (function (a, b, c, d, e) { return function () { removeCookie(a, b, c, d, e); }; })(secure, name, path, domain, storeId); } } function processDomain(domain) { var pattern = new RegExp("[a-zA-Z]*\.[a-zA-Z]*"); var result = pattern.exec(reverse(domain)); /** if(domain.charAt(0) == '.'){ return domain.substring(1,domain.length); } if(domain.substr(1,4) == 'www.'){ return domain.substring(4,domain.length); } **/ return reverse(result[0]); } function reverse(s) { return s.split("").reverse().join(""); } function removeCookie(secure, name, path, domain, storeId) { var url = "http" + (secure ? "s" : "") + "://" + domain + path; chrome.cookies.remove({ "url": url, "name": name, "storeId": storeId }, null); location.reload(true); } function overlay(message, time) { var success = document.createElement('div'); success.classList.add('overlay'); success.setAttribute('id', 'success'); success.setAttribute('role', 'alert'); success.textContent = message; document.body.appendChild(success); setTimeout(function () { success.classList.add('visible'); }, 10); setTimeout(function () { success.classList.remove('visible'); }, time); } /** var cookie_cache = new CookieCache(); var tab_cache = new TabCache(); var cookie_reload_scheduled = false; var tab_reload_scheduled = false; var reload = 250; var enabled = false; chrome.browserAction.onClicked.addListener(function(tab) { var manager_url = chrome.extension.getURL("background.html"); focusOrCreateTab(manager_url); }); function focusOrCreateTab(url) { chrome.windows.getAll({"populate":true}, function(windows) { var existing_tab = null; for (var i in windows) { var tabs = windows[i].tabs; for (var j in tabs) { var tab = tabs[j]; if (tab.url == url) { existing_tab = tab; break; } } } if (existing_tab) { chrome.tabs.update(existing_tab.id, {"selected":true}); } else { chrome.tabs.create({"url":url, "selected":true}); } }); } document.addEventListener('DOMContentLoaded', function() { onload(); select("#enabled").checked = enabled; select("#enabled").addEventListener('click',options); select('#cookies_remove_button').addEventListener('click', removeAllCookies); select('#run_cookie_check').addEventListener('click', checkCookiesEnabled); }); function onload() { startListening(); chrome.cookies.getAll({}, function(cookies) { for (var i in cookies) { cookie_cache.add(cookies[i]); } reloadCookieTable(); }); chrome.tabs.query({}, function(tabs) { for (var i in tabs) { tab_cache.add(tabs[i]); } reloadTabTable(); }); } function options() { if(select("#enabled").checked){ enabled = true; }else{ enabled = false; } checkCookies(); } function checkCookiesEnabled() { var temp = enabled; enabled = true; checkCookies(); enabled = temp; } function checkCookies() { var urls = tab_cache.getAllTabUrls(); cookie_cache.getDomains().forEach(function(domain){ var tmp = domain; if(domain.charAt(0) == '.'){ tmp = domain.substr(1); } else { if (domain.indexOf("www.") == 0) { tmp = domain.substr(4); } else{ if(domain.indexOf(".") != domain.lastIndexOf(".")){ tmp = domain.substr(domain.indexOf(".")+1); } } } var found = 0; urls.forEach(function(url){ if (url.indexOf(tmp) != -1){ found = 1; } }); if(found == 0){ cookie_cache.getCookies(domain).forEach(function(cookie){ if(enabled){ cookie_cache.remove(domain); removeCookie(cookie); } }); } }); } function scheduleReloadCookieTable() { if (!cookie_reload_scheduled) { cookie_reload_scheduled = true; setTimeout(reloadCookieTable, reload); } } function scheduleReloadTabTable() { if (!tab_reload_scheduled) { tab_reload_scheduled = true; setTimeout(reloadTabTable, reload); } } function reloadCookieTable() { cookie_reload_scheduled = false; var domains = cookie_cache.getDomains(); debugger; select("#cookies_total_count").innerText = domains.length; resetCookieTable(); var table = select("#cookies"); domains.forEach(function(domain) { var cookies = cookie_cache.getCookies(domain); var row = table.insertRow(-1); row.insertCell(-1).innerText = domain; var cell = row.insertCell(-1); cell.innerText = cookies.length; cell.setAttribute("class", "cookie_count"); var button = document.createElement("button"); button.innerText = "delete"; button.onclick = (function(dom){ return function() { removeCookiesForDomain(dom); }; }(domain)); var cell = row.insertCell(-1); cell.appendChild(button); cell.setAttribute("class", "button"); }); } function reloadTabTable() { tab_reload_scheduled = false; var ids = tab_cache.getIds(); select("#tabs_total_count").innerText = ids.length; resetTabTable(); var table = select("#tabs"); ids.forEach(function(id) { var tabs = tab_cache.getTabs(id); var row = table.insertRow(-1); row.insertCell(-1).innerText = id; var cell = row.insertCell(-1); cell.innerText = tabs[0].url; cell.setAttribute("class", "tab_count"); }); } function resetCookieTable() { var table = select("#cookies"); while (table.rows.length > 1) { table.deleteRow(table.rows.length - 1); } } function resetTabTable() { var table = select("#tabs"); while (table.rows.length > 1) { table.deleteRow(table.rows.length - 1); } } function removeAllCookies() { var all_cookies = []; cookie_cache.getDomains().forEach(function(domain) { cookie_cache.getCookies(domain).forEach(function(cookie) { all_cookies.push(cookie); }); }); cookie_cache.reset(); var count = all_cookies.length; for (var i = 0; i < count; i++) { removeCookie(all_cookies[i]); } chrome.cookies.getAll({}, function(cookies) { for (var i in cookies) { cookie_cache.add(cookies[i]); removeCookie(cookies[i]); } }); } function removeCookiesForDomain(domain) { cookie_cache.getCookies(domain).forEach(function(cookie) { removeCookie(cookie); }); } function removeCookie(cookie) { var url = "http" + (cookie.secure ? "s" : "") + "://" + cookie.domain + cookie.path; chrome.cookies.remove({"url": url, "name": cookie.name}); } function startListening() { chrome.tabs.onUpdated.addListener(listenerTabUpdated); chrome.tabs.onRemoved.addListener(listenerTabRemoved); chrome.cookies.onChanged.addListener(listenerCookieChanged); } function listenerTabUpdated(tabId, info, tab) { tab_cache.remove(tabId); tab_cache.add(tab); checkCookies(); scheduleReloadTabTable(); } function listenerTabRemoved(tabId, info) { tab_cache.remove(tabId); checkCookies(); scheduleReloadTabTable(); } function listenerCookieChanged(info) { cookie_cache.remove(info.cookie); if (!info.removed) { cookie_cache.add(info.cookie); } checkCookies(); scheduleReloadCookieTable(); } function CookieCache() { this.cookies_ = {}; this.reset = function() { this.cookies_ = {}; } this.add = function(cookie) { var domain = cookie.domain; if (!this.cookies_[domain]) { this.cookies_[domain] = []; } this.cookies_[domain].push(cookie); }; this.remove = function(cookie) { var domain = cookie.domain; if (this.cookies_[domain]) { var i = 0; while (i < this.cookies_[domain].length) { if (cookieMatch(this.cookies_[domain][i], cookie)) { this.cookies_[domain].splice(i, 1); } else { i++; } } if (this.cookies_[domain].length == 0) { delete this.cookies_[domain]; } } }; this.getDomains = function() { return sortedKeys(this.cookies_); } this.getCookies = function(domain) { return this.cookies_[domain]; }; } function cookieMatch(c1, c2) { return (c1.name == c2.name) && (c1.domain == c2.domain) && (c1.hostOnly == c2.hostOnly) && (c1.path == c2.path) && (c1.secure == c2.secure) && (c1.httpOnly == c2.httpOnly) && (c1.session == c2.session) && (c1.storeId == c2.storeId); } function TabCache() { this.tabs_ = {}; this.reset = function() { this.tabs_ = {}; } this.add = function(tab) { var id = tab.id; if (!this.tabs_[id]) { this.tabs_[id] = []; } this.tabs_[id].push(tab); }; this.remove = function(id) { if (this.tabs_[id]) { delete this.tabs_[id]; } }; this.getIds = function() { var result = []; sortedKeys(this.tabs_).forEach(function(id) { result.push(id); }); return result; } this.getAllTabUrls = function() { var urls = []; for (var id in this.tabs_){ urls.push(this.tabs_[id][0].url); } return urls; }; this.getTabs = function(id) { return this.tabs_[id]; }; } function select(selector) { return document.querySelector(selector); } function sortedKeys(array) { var keys = []; for (var i in array) { keys.push(i); } keys.sort(); return keys; } **/
83139f9b7f8fef91ed8e3870b96740c5559d8ea5
[ "JavaScript" ]
1
JavaScript
damacode/GoogleChromeCookieMonsterExtension
23bf4438197a3aed82fa861b2b6a165945957df5
a447a217c1407936d8798169c0797e6d74061cb9
refs/heads/master
<file_sep>class ChangeSongsSongIdToGenreId < ActiveRecord::Migration def change rename_column :songs, :song_id, :genre_id end end
ff9f3037c5bb0e3db86143e236f19794504d4e7f
[ "Ruby" ]
1
Ruby
mkruszewski89/rails-cru-form_for-lab-v-000
3da7c0429ead8c57bb84f3b221c93f16ad4c7041
bf6094479589fd1f2d2016967b8f78c4da2c46cf
refs/heads/staging
<repo_name>IfeanyiOsuji/Learning-Management-System<file_sep>/src/main/java/com/ileiwe/security/config/SecurityConstants.java //package com.ileiwe.security.config; // ///** // * @author oluwatobi // * @version 1.0 // * @date on 29/10/2021 // * inside the package - com.ileiwe.security.config // */ //public class SecurityConstants { // // public static final String SECRET = "SecretKeyToGenJWTs"; // public static final long EXPIRATION_TIME = 864_000_000; //10days // public static final String TOKEN_PREFIX = "Bearer "; // public static final String HEADER_STRING = "Authorization"; //} <file_sep>/src/test/java/com/ileiwe/data/repository/LearningPartyRepositoryTest.java package com.ileiwe.data.repository; import com.ileiwe.data.model.Authority; import com.ileiwe.data.model.LearningParty; import com.ileiwe.data.model.Role; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.jdbc.Sql; import org.springframework.transaction.annotation.Transactional; import javax.validation.ConstraintViolationException; import javax.validation.Valid; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; /** * @author oluwatobi * @version 1.0 * @date on 28/10/2021 * inside the package - com.ileiwe.data.repository */ @SpringBootTest @Slf4j @Sql(scripts = {"/db/insert.sql"}) class LearningPartyRepositoryTest { @Autowired LearningPartyRepository learningPartyRepository; @BeforeEach void setUp() { } @Test @Transactional @Rollback(value = false) void createLearningPartyWithStudentRoleTest(){ LearningParty learningUser = new LearningParty("<EMAIL>", "Yomi123", new Authority(Role.ROLE_STUDENT)); log.info("Before saving --> {}", learningUser); learningPartyRepository.save(learningUser); assertThat(learningUser.getId()).isNotNull(); assertThat(learningUser.getEmail()).isEqualTo("<EMAIL>"); assertThat(learningUser.getAuthorities() .get(0).getAuthority()).isEqualTo(Role.ROLE_STUDENT); assertThat(learningUser.getAuthorities() .get(0).getId()).isNotNull(); log.info("After saving --> {}", learningUser); } @Test void createLearningPartyUniqueEmailsTest(){ //create a learning party LearningParty user1 = new LearningParty("<EMAIL>", "Yomi123", new Authority(Role.ROLE_STUDENT)); //save to db learningPartyRepository.save(user1); assertThat(user1.getEmail()).isEqualTo("<EMAIL>"); assertThat(user1.getId()).isNotNull(); //create another learning party with same email LearningParty user2 = new LearningParty("<EMAIL>", "Yomi123", new Authority(Role.ROLE_STUDENT)); //save and catch exception assertThrows(DataIntegrityViolationException.class, () -> learningPartyRepository.save(user2)); } @Test void learningPartyWithNullValuesTest(){ //create a learning party with null values LearningParty user2 = new LearningParty(null, null, new Authority(Role.ROLE_STUDENT)); //save and catch exception assertThrows(ConstraintViolationException.class, () -> learningPartyRepository.save(user2)); } @Test void learningPartyWithEmptyStringValuesTest(){ //create a learning party with null values LearningParty user = new LearningParty(" ", "", new Authority(Role.ROLE_STUDENT)); assertThrows(ConstraintViolationException.class, ()-> learningPartyRepository.save(user)); } @Test void findByUserNameTest(){ LearningParty learningParty = learningPartyRepository.findByEmail("<EMAIL>"); assertThat(learningParty).isNotNull(); assertThat(learningParty.getEmail()).isEqualTo("<EMAIL>"); log.info("Learning party object --> {}", learningParty); } @AfterEach void tearDown() { } }<file_sep>/src/main/java/com/ileiwe/service/studentService/StudentService.java package com.ileiwe.service.studentService;public interface StudentService { } <file_sep>/target/generated-sources/annotations/com/ileiwe/service/mapper/CourseMapperImpl.java package com.ileiwe.service.mapper; import com.ileiwe.data.dto.CourseDto; import com.ileiwe.data.model.Course; import javax.annotation.processing.Generated; import org.springframework.stereotype.Component; @Generated( value = "org.mapstruct.ap.MappingProcessor", date = "2021-11-05T11:54:03+0100", comments = "version: 1.4.2.Final, compiler: javac, environment: Java 16.0.2 (Oracle Corporation)" ) @Component public class CourseMapperImpl implements CourseMapper { @Override public void mapToCourse(CourseDto courseDto, Course course) { if ( courseDto == null ) { return; } if ( courseDto.getTitle() != null ) { course.setTitle( courseDto.getTitle() ); } if ( courseDto.getDescription() != null ) { course.setDescription( courseDto.getDescription() ); } if ( courseDto.getDuration() != null ) { course.setDuration( courseDto.getDuration() ); } if ( courseDto.getLanguage() != null ) { course.setLanguage( courseDto.getLanguage() ); } if ( courseDto.getDatePublished() != null ) { course.setDatePublished( courseDto.getDatePublished() ); } course.setPublished( courseDto.isPublished() ); if ( courseDto.getInstructor() != null ) { course.setInstructor( courseDto.getInstructor() ); } } } <file_sep>/src/main/java/com/ileiwe/web/controller/Controllable.java package com.ileiwe.web.controller; import com.ileiwe.data.dto.CourseDto; import com.ileiwe.data.dto.InstructorPartyDto; import com.ileiwe.data.model.Course; import com.ileiwe.data.model.Instructor; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public interface Controllable { Instructor save(InstructorPartyDto dto); Course createCourse(@PathVariable Long id, @RequestBody Course course); Course updateCourse(@PathVariable Long id, Long courseId, @RequestBody CourseDto courseDto); Course publishCourse(@PathVariable Long instructorId, Long courseId); void deleteCourseById(@PathVariable Long InstructorId, Long courseId); List<Course>viewCourses(@PathVariable Long id); List<Course> viewPublishedCourses(@PathVariable Long instructorId); Course viewCourseById(@PathVariable Long id, Long courseId); Course viewCourseByTitle(@PathVariable Long instructorId, String title); } <file_sep>/src/main/java/com/ileiwe/controller/CourseController.java package com.ileiwe.controller; import com.ileiwe.data.dto.CourseDto; import com.ileiwe.data.model.Course; import com.ileiwe.service.courseService.CourseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/course") public class CourseController { @Autowired CourseService courseService; @PostMapping("/{id}") public ResponseEntity<?> createCourse(@RequestBody Course course) { return ResponseEntity.ok().body(courseService.createCourse(course)); } @GetMapping("/course/{id}") public Course createCourse(@PathVariable Long id) { return null; // return courseService.viewCourse(id); } @PutMapping("/update/{id}/{num}") public void update(@RequestBody CourseDto courseDto,@PathVariable Long id) { courseService.update(id, courseDto); } } <file_sep>/src/test/java/com/ileiwe/service/courseService/InstructorServiceImplTest.java package com.ileiwe.service.courseService; import com.ileiwe.data.dto.CourseDto; import com.ileiwe.data.model.Course; import com.ileiwe.data.model.Instructor; import com.ileiwe.data.repository.InstructorRepository; import com.ileiwe.service.instructorService.InstructorServiceImpl; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.Rollback; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; @SpringBootTest @Slf4j class InstructorServiceImplTest { @Autowired InstructorServiceImpl instructorServiceImpl; @Autowired CourseServiceImpl courseServiceImpl; @Autowired InstructorRepository instructorRepository; @BeforeEach void setUp() { } @AfterEach void tearDown() { } @Test @Transactional @Rollback(value = false) void createCurse() { Optional<Instructor> instructor = instructorRepository.findById(2L); Course course = new Course(); course.setTitle("CSS"); course.setDescription("Demystifying programming using CSS"); course.setDuration("2 hours"); course.setLanguage("French"); log.info("Course before saving {}", course); course.setInstructor(instructor.get()); instructorServiceImpl.CreateCurse(instructor.get().getId(), course); log.info("course after saving {}", course); } @Test void updateCourse(){ CourseDto courseDto = new CourseDto(); courseDto.setLanguage("Portuguese"); courseDto.setDuration("3 hours"); courseDto.setTitle("Java Collections For Beginners"); Course course = courseServiceImpl.findById(1L); log.info("Before updating course {}", course.getTitle()); Course updated =instructorServiceImpl.updateCourse(1L, course.getId(), courseDto); assertThat(courseDto.getTitle()).isEqualTo(updated.getTitle()); log.info("After updating course {}", updated.getTitle()); } @Test void publishCourse(){ Course unpublishedCourse = courseServiceImpl.findById(2L); log.info("Course published date before publishing {}", unpublishedCourse.getDatePublished()); log.info("Course published status before publishing {}", unpublishedCourse.isPublished()); Course course = instructorServiceImpl.publishCourse( 1l,unpublishedCourse.getId()); assertThat(course.isPublished()).isEqualTo(true); assertThat(course.getDatePublished()).isNotNull(); log.info("Course published date after publishing {}", course.getDatePublished()); log.info("Course published status after publishing {}", course.isPublished()); } @Test void deleteCourseById(){ Course unpublishedCourse = courseServiceImpl.findById(5L); int size = instructorServiceImpl.viewCourses(1L).size(); log.info("List of courses before deleting {}", size); instructorServiceImpl.deleteCourseById(2L,unpublishedCourse.getId()); assertThat(instructorServiceImpl.viewCourses(2L).size()).isEqualTo(size - 1); log.info("List of courses after deleting {}", instructorServiceImpl.viewCourses(2L).size()); } @Test @Transactional @Rollback(value = false) void viewCourses(){ List<Course> courses = instructorServiceImpl.viewCourses(2L); log.info("Courses in the list {}", courses.toString()); } @Test @Transactional @Rollback(value = false) void viewPublishedCourses(){ List<Course> courses = instructorServiceImpl.viewPublishedCourses(2L); log.info("Courses in the list {}", courses.toString()); } @Test @Transactional @Rollback(value = false) void getCourseById(){ Course course = instructorServiceImpl.viewCourseById(2L, 1L); log.info("Course with id "+course.getId() +" is "+course); } @Test @Transactional @Rollback(value = false) void getCourseByTitle(){ Course course = instructorServiceImpl.viewCourseByTitle(2L, "CSS"); log.info("Course with title "+course.getTitle() +" is "+course); } }<file_sep>/src/main/java/com/ileiwe/data/repository/InstructorRepository.java package com.ileiwe.data.repository; import com.ileiwe.data.model.Instructor; import org.springframework.data.jpa.repository.JpaRepository; /** * @author oluwatobi * @version 1.0 * @date on 28/10/2021 * inside the package - com.ileiwe.data.repository */ public interface InstructorRepository extends JpaRepository<Instructor, Long> { } <file_sep>/target/classes/application.properties spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/iwedb spring.datasource.username=ile-dev spring.datasource.password=<PASSWORD> spring.jpa.hibernate.ddl-auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect server.port=8085<file_sep>/src/main/java/com/ileiwe/security/user/LearningPartyServiceImpl.java //package com.ileiwe.security.user; // //import com.ileiwe.data.model.Authority; //import com.ileiwe.data.model.LearningParty; //import com.ileiwe.data.repository.LearningPartyRepository; //import lombok.extern.slf4j.Slf4j; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.security.core.authority.SimpleGrantedAuthority; //import org.springframework.security.core.userdetails.User; //import org.springframework.security.core.userdetails.UserDetails; //import org.springframework.security.core.userdetails.UserDetailsService; //import org.springframework.security.core.userdetails.UsernameNotFoundException; //import org.springframework.stereotype.Service; //import org.springframework.transaction.annotation.Transactional; // //import java.util.Collection; //import java.util.Collections; //import java.util.List; //import java.util.stream.Collectors; // ///** // * @author oluwatobi // * @version 1.0 // * @date on 29/10/2021 // * inside the package - com.ileiwe.security.user // */ // //@Service //@Slf4j //@Transactional //public class LearningPartyServiceImpl // implements UserDetailsService { // // @Autowired // private LearningPartyRepository learningPartyRepository; // // // @Override // public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { // // log.info("Username request --> {}", email); // LearningParty user = // learningPartyRepository.findByEmail(email); // // if(user == null){ // throw new UsernameNotFoundException // ("User with email does not exists"); // } // return new User(user.getEmail(), user.getPassword(), // getAuthorities(user.getAuthorities())); // } // // private List<SimpleGrantedAuthority> getAuthorities // (List<Authority> authorities){ // return authorities // .stream() // .map(authority -> { // return new SimpleGrantedAuthority // (authority.getAuthority().name()); // }).collect(Collectors.toList()); // } //} <file_sep>/src/main/java/com/ileiwe/data/repository/LearningPartyRepository.java package com.ileiwe.data.repository; import com.ileiwe.data.model.LearningParty; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; /** * @author oluwatobi * @version 1.0 * @date on 28/10/2021 * inside the package - com.ileiwe.data.repository */ public interface LearningPartyRepository extends JpaRepository<LearningParty, Long> { LearningParty findByEmail(String email); // @Query("select '*' from LearningParty" + // " as L where L.email =:email") // LearningParty findUserByEmail(String email); } <file_sep>/src/main/java/com/ileiwe/security/config/HttpAuthenticationEntryPoint.java //package com.ileiwe.security.config; // //import lombok.extern.slf4j.Slf4j; //import org.springframework.security.core.AuthenticationException; //import org.springframework.security.web.AuthenticationEntryPoint; //import org.springframework.stereotype.Component; // //import javax.servlet.ServletException; //import javax.servlet.http.HttpServletRequest; //import javax.servlet.http.HttpServletResponse; //import java.io.IOException; // ///** // * @author oluwatobi // * @version 1.0 // * @date on 29/10/2021 // * inside the package - com.ileiwe.security.config // */ // //@Component //@Slf4j //public class HttpAuthenticationEntryPoint implements AuthenticationEntryPoint { // @Override // public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { // log.info("Pre-authenticated entry point called. Rejecting access"); // httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied"); // } //} <file_sep>/src/main/java/com/ileiwe/data/model/Student.java package com.ileiwe.data.model; import lombok.Data; import javax.persistence.*; import java.time.LocalDate; import java.util.List; /** * @author oluwatobi * @version 1.0 * @date on 27/10/2021 * inside the package - com.ileiwe.data.model */ @Entity @Data public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String firstname; private String lastname; private LocalDate dob; @Enumerated(EnumType.STRING) private Gender gender; @OneToOne private LearningParty learningParty; @ManyToMany private List<Course> enrolledCourses; } <file_sep>/src/main/java/com/ileiwe/controller/RegistrationController.java package com.ileiwe.controller; import com.ileiwe.data.dto.InstructorPartyDto; import com.ileiwe.service.instructorService.InstructorServiceImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author oluwatobi * @version 1.0 * @date on 29/10/2021 * inside the package - com.ileiwe.controller */ @RestController @RequestMapping("/api") @Slf4j public class RegistrationController { @Autowired InstructorServiceImpl instructorService; @PostMapping("/instructor") public ResponseEntity<?> registerAsInstructor(@RequestBody InstructorPartyDto instructorPartyDto){ log.info("instructor object --> {}", instructorPartyDto); return ResponseEntity.ok() .body(instructorService.save(instructorPartyDto)); } } <file_sep>/src/main/java/com/ileiwe/data/repository/CourseRepository.java package com.ileiwe.data.repository; import com.ileiwe.data.model.Course; import org.springframework.data.jpa.repository.JpaRepository; import javax.persistence.Id; /** * @author oluwatobi * @version 1.0 * @date on 28/10/2021 * inside the package - com.ileiwe.data.repository */ public interface CourseRepository extends JpaRepository<Course, Long> { Course findCourseByTitle(String title); } <file_sep>/src/main/resources/db/setup.sql create database if not exists iwedb; create user if not exists 'ile-dev'@'localhost' identified by 'IleIwe123'; grant all privileges on iwedb.* to 'ile-dev'@'localhost'; flush privileges;<file_sep>/src/main/java/com/ileiwe/service/instructorService/InstructorService.java package com.ileiwe.service.instructorService; import com.ileiwe.data.dto.CourseDto; import com.ileiwe.data.dto.InstructorPartyDto; import com.ileiwe.data.model.Course; import com.ileiwe.data.model.Instructor; import org.springframework.stereotype.Service; import java.util.List; @Service public interface InstructorService { Instructor save(InstructorPartyDto dto); Course CreateCurse(Long id, Course course); Course updateCourse(Long id, Long courseId, CourseDto courseDto); Course publishCourse(Long instructorId, Long courseId); void deleteCourseById(Long InstructorId, Long courseId); List<Course>viewCourses(Long id); List<Course> viewPublishedCourses(Long instructorId); Course viewCourseById(Long id, Long courseId); Course viewCourseByTitle(Long instructorId, String title); } <file_sep>/src/test/java/com/ileiwe/data/repository/InstructorRepositoryTest.java package com.ileiwe.data.repository; import com.ileiwe.data.model.*; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.jdbc.Sql; import org.springframework.transaction.annotation.Transactional; import javax.validation.ConstraintViolationException; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; /** * @author oluwatobi * @version 1.0 * @date on 28/10/2021 * inside the package - com.ileiwe.data.repository */ @SpringBootTest @Slf4j @Sql(scripts=("/db/insert.sql")) class InstructorRepositoryTest { @Autowired InstructorRepository instructorRepository; @BeforeEach void setUp() { } @Test @Transactional @Rollback(value = false) void saveInstructorAsLearningPartyTest(){ //create a learning party LearningParty user = new LearningParty("<EMAIL>", "1234pass", new Authority(Role.ROLE_INSTRUCTOR)); //create instructor Instructor instructor = Instructor.builder() .firstname("John") .lastname("Alao") .learningParty(user).build(); //save instructor log.info("Instructor before saving --> {}", instructor); instructorRepository.save(instructor); assertThat(instructor.getId()).isNotNull(); assertThat(instructor.getLearningParty().getId()).isNotNull(); log.info("Instructor after saving --> {}", instructor); //create a learning party LearningParty user2 = new LearningParty("<EMAIL>", "333pass", new Authority(Role.ROLE_INSTRUCTOR)); //create instructor Instructor instructor2 = Instructor.builder() .firstname("Mark") .lastname("Houstine") .learningParty(user2).build(); //save instructor log.info("Instructor before saving --> {}", instructor2); instructorRepository.save(instructor2); assertThat(instructor.getId()).isNotNull(); assertThat(instructor2.getLearningParty().getId()).isNotNull(); log.info("Instructor after saving --> {}", instructor2); } @Test @Transactional @Rollback(value = false) void updateInstructorTableAfterCreate(){ //create a learning party LearningParty user = new LearningParty("<EMAIL>", "<PASSWORD>", new Authority(Role.ROLE_INSTRUCTOR)); //create instructor Instructor instructor = Instructor.builder() .firstname("John") .lastname("Alao") .learningParty(user).build(); //save instructor log.info("Instructor before saving --> {}", instructor); instructorRepository.save(instructor); assertThat(instructor.getId()).isNotNull(); assertThat(instructor.getLearningParty().getId()).isNotNull(); log.info("Instructor after saving --> {}", instructor); Instructor savedInstructor = instructorRepository.findById(instructor.getId()).orElse(null); log.info("Saved Instructor --> {}", savedInstructor); assertThat(savedInstructor).isNotNull(); assertThat(savedInstructor.getBio()).isNull(); assertThat(savedInstructor.getGender()).isNull(); savedInstructor.setBio("I am java instructor"); savedInstructor.setGender(Gender.MALE); instructorRepository.save(savedInstructor); assertThat(savedInstructor.getBio()).isNotNull(); assertThat(savedInstructor.getGender()).isNotNull(); } @Test void createInstructorWithNullValuesTest(){ //create a learning party LearningParty user = new LearningParty("<EMAIL>", "<PASSWORD>", new Authority(Role.ROLE_INSTRUCTOR)); Instructor instructor = Instructor.builder() .firstname(null) .lastname(null) .learningParty(user).build(); assertThrows(ConstraintViolationException.class ,() -> instructorRepository.save(instructor)); } @Test void createInstructorWithEmptyValuesTest(){ //create a learning party LearningParty user = new LearningParty("<EMAIL>", "<PASSWORD>", new Authority(Role.ROLE_INSTRUCTOR)); Instructor instructor = Instructor.builder() .firstname("") .lastname(" ") .learningParty(user).build(); assertThrows(ConstraintViolationException.class ,() -> instructorRepository.save(instructor)); } }<file_sep>/src/main/java/com/ileiwe/service/courseService/CourseService.java package com.ileiwe.service.courseService; import com.ileiwe.data.dto.CourseDto; import com.ileiwe.data.model.Course; import java.util.List; public interface CourseService{ Course createCourse(Course course); Course update(Long id, CourseDto courseDto); void delete(Long id); List<Course> viewCourses(); Course publishCourse(Long courseId); Course findCourseByTitle(String title); Course findById(Long id); List<Course>showPublishedCourses(); } <file_sep>/src/main/resources/db/insert.sql set foreign_key_checks = 0; truncate table learning_party; truncate table authority; truncate table instructor; insert into learning_party(`id`, `email`,`password`, `enabled`) values(123, '<EMAIL>', '<PASSWORD>', false), (124, '<EMAIL>', '<PASSWORD>', false), (125, '<EMAIL>', '<PASSWORD>', false), (126, '<EMAIL>', '<PASSWORD>', false), (127, '<EMAIL>', '<PASSWORD>', false); set foreign_key_checks = 1; <file_sep>/src/main/java/com/ileiwe/web/exceptions/CourseAlreadyExistException.java package com.ileiwe.web.exceptions; public class CourseAlreadyExistException extends RuntimeException { public CourseAlreadyExistException(String s) { super(s); } } <file_sep>/src/main/java/com/ileiwe/data/dto/CourseDto.java package com.ileiwe.data.dto; import com.ileiwe.data.model.Instructor; import lombok.Data; import org.springframework.context.annotation.Bean; import java.time.LocalDateTime; import java.util.List; @Data public class CourseDto { private String title; private String description; private String duration; private String language; private List<String> imgUrl; private Instructor instructor; private LocalDateTime datePublished; private boolean isPublished; } <file_sep>/src/main/java/com/ileiwe/security/config/WebSecurityConfig.java //package com.ileiwe.security.config; // //import com.ileiwe.security.user.LearningPartyServiceImpl; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.context.annotation.Bean; //import org.springframework.http.HttpMethod; //import org.springframework.security.authentication.AuthenticationManager; //import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; //import org.springframework.security.config.annotation.web.builders.HttpSecurity; //import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; //import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; //import org.springframework.security.config.http.SessionCreationPolicy; //import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; // ///** // * @author oluwatobi // * @version 1.0 // * @date on 29/10/2021 // * inside the package - com.ileiwe.security.user // */ // //@EnableWebSecurity //public class WebSecurityConfig // extends WebSecurityConfigurerAdapter { // // private final LearningPartyServiceImpl userDetails; // // @Autowired // public WebSecurityConfig(LearningPartyServiceImpl learningPartyService){ // this.userDetails = learningPartyService; // } // // @Override // protected void configure(HttpSecurity http) throws Exception { // http // .csrf().disable() // .authorizeRequests() // .antMatchers(HttpMethod.POST, "/api/instructor").permitAll() // .anyRequest() // .authenticated() // .and() // .addFilter(new JWTAuthenticationFilter(authenticationManager())) // .addFilter(new JWTAuthorizationFilter(authenticationManager())) // .exceptionHandling() // .and() // .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // } // // @Override // protected void configure(AuthenticationManagerBuilder auth) throws Exception { // auth.userDetailsService(userDetails) // .passwordEncoder(bCryptPasswordEncoder()); // } // // // @Bean // public BCryptPasswordEncoder bCryptPasswordEncoder(){ // return new BCryptPasswordEncoder(); // } // //} <file_sep>/src/test/java/com/ileiwe/service/courseService/CourseServiceImpleMockTest.java package com.ileiwe.service.courseService; import com.ileiwe.data.dto.CourseDto; import com.ileiwe.data.model.Course; import com.ileiwe.data.repository.CourseRepository; import com.ileiwe.service.mapper.CourseMapper; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import static org.mockito.Mockito.*; @Slf4j public class CourseServiceImpleMockTest { @Mock CourseRepository courseRepository; @InjectMocks CourseServiceImpl courseServiceImpl; @Autowired CourseMapper mapper; @BeforeEach void setUp() { courseServiceImpl = new CourseServiceImpl(); MockitoAnnotations.openMocks(this); } @Test void updateCourse(){ // CourseDto courseDto = new CourseDto(); // courseDto.setLanguage("Portuguese"); // courseDto.setDuration("3 hours"); // courseDto.setTitle("Java Collections"); // Course courseToUpdate = courseRepository.findCourseByTitle("Java"); // log.info("Before updating course {}", courseToUpdate); // when(courseServiceImpl.update(courseToUpdate.getId(), courseDto)).thenReturn(courseToUpdate.getId()); // courseServiceImpl.update(courseToUpdate.getId(), courseDto); // verify(courseRepository, times(1)); } }
f7bdb9ad2350f72cbc8067c0b4d888e9acbe370d
[ "Java", "SQL", "INI" ]
24
Java
IfeanyiOsuji/Learning-Management-System
ec7203c9b2a9b13dc74c56fb619735f845657f6f
8f2125f41e44cc0bdfb40d8d208c4528b5932877
refs/heads/master
<repo_name>Buzdygan/ai-arena<file_sep>/documentation/index.rst .. Ai Arena documentation master file, created by sphinx-quickstart on Sat Jan 7 17:32:01 2012. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to Ai Arena's documentation! ==================================== Contents: .. toctree:: :maxdepth: 2 Modules =================================== .. toctree:: :maxdepth: 2 modules/nadzorca.rst modules/gearman_worker_lib.rst modules/model.rst modules/forms.rst modules/compilation.rst modules/game_launcher.rst modules/utils.rst modules/views.rst modules/game_views.rst modules/bot_views.rst modules/match_views.rst modules/contest_views.rst modules/user_views.rst modules/comment_views.rst modules/may_contest_views.rst modules/may_contest_helper_functions.rst Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` <file_sep>/ai_arena/templates/gaming/show_source.html {% extends 'base.html' %} {% block css %} <link rel="stylesheet" href="{{ MEDIA_URL }}source_code.css" /> {% endblock %} {% block content %} <div id="source_code"> {% for line in source %} <span class='line_number'>{{ forloop.counter }}</span> {% for token in line %} <span class='{{ token.class }}'>{{ token.value }}</span> {% endfor %} <br> {% endfor %} </div> {% endblock %} <file_sep>/ai_arena/media/may_contest/bot.cpp #include <iostream> #include <time.h> #define CONFIRM cout << "0\n" #define WAIT cin >> trash using namespace std; int firstBet(int card){ int bet = 10; if(card > 1) bet = 100; if(card == 4) bet = 200; return bet; } int secondBet(int my1bet, int op1bet, int card){ if(card == 4) return 200; if(card > 1) return 120; if(op1bet > my1bet) return 10; return 50; } int decision(int myBet, int opBet, int card){ if(card < 2) return 0; if((card == 2)&&(2*myBet > opBet)) return 1; if(card > 2) return 1; return 0; } int main(){ int card, my1bet, op1bet, bet1, my2bet, op2bet, decision1, decision2, opCard; int trash; while(true){ cin >> card; //cerr << "CARD " << card << "\n"; my1bet = firstBet(card); cout << my1bet << "\n"; cin >> op1bet; //cerr << "op1bet " << op1bet << "\n"; if(op1bet > my1bet){ decision1 = decision(my1bet, op1bet, card); //cerr << "making decision " << decision1 << "\n"; cout << decision1 << "\n"; if(decision1 == 0) continue; } if(my1bet > op1bet){ CONFIRM; cin >> decision1; //cerr << "op made decision " << decision1 << "\n"; CONFIRM; if(decision1 == 0){ continue; } } if(my1bet == op1bet){ CONFIRM; //cerr << "equal 1bet\n"; } //SECOND BET cin >> bet1; //cerr << "1bet for " << bet1 << "\n"; my2bet = secondBet(my1bet, op1bet, card); cout << my2bet << "\n"; cin >> op2bet; if(op2bet > my2bet){ decision2 = decision(my1bet+my2bet, op1bet+op2bet, card); cout << decision2 << "\n"; if(decision2 == 0) continue; } if(my2bet > op2bet){ CONFIRM; cin >> decision2; CONFIRM; if(decision2 == 0) continue; } if(my2bet == op2bet){ CONFIRM; //cerr << "equal 2bet\n"; } cin >> opCard; CONFIRM; } return 0; } <file_sep>/ai_arena/templates/registration/registration_form.html {% extends 'base.html' %} {% block content %} <form action="/accounts/register/" method="POST">{% csrf_token %} {{ form.as_p }} <p><label for="submit"></label><input id="submit" type="submit" value="Submit" /></p> </form> {% endblock %} <file_sep>/ai_arena/nadzorca/testing/pok2/Makefile CC=gcc all: pok_judge pok_bot cpp_pok_bot c_pok_bot timeout_judge: pok_judge.cpp g++ pok_judge.cpp -O0 -o pok_judge timeout_bot: bot_logs_bot.cpp g++ pok_bot.cpp -O0 -o pok_bot clean: rm pok_judge pok_bot cpp_pok_bot c_pok_bot <file_sep>/ai_arena/nadzorca/testing/timeout/Makefile all: timeout_judge timeout_bot timeout_judge: timeout_judge.cpp g++ timeout_judge.cpp -O0 -o timeout_judge timeout_bot: timeout_bot.cpp g++ timeout_bot.cpp -O0 -o timeout_bot clean: rm timeout_judge timeout_bot <file_sep>/ai_arena/nadzorca/testing/parse_messages/Makefile all: parse_messages_judge parse_messages_bot timeout_judge: parse_messages_judge.cpp g++ parse_messages_judge.cpp -O0 -o parse_messages_judge timeout_bot: parse_messages_bot.cpp g++ parse_messages_bot.cpp -O0 -o parse_messages_bot clean: rm parse_messages_judge parse_messages_bot <file_sep>/files/testing/kk/dummy_bot.cpp #include <iostream> #define N 3 #define M 3 #define K 3 #define DEBUG using namespace std; void printBoard(void); int endGame(void); char board[N][M]; bool ruch; void makeMove(void); int main(){ string com; bool end = false; for(int i = 0; i < N; ++i) for(int j = 0; j < M; ++j) board[i][j] = '.'; while(!end){ cin>>com; int X, Y; if(com == "MOVE"){ cin >>X>>Y>>com; board[X][Y] = 'O'; if(endGame() == 0){ ruch = true; makeMove(); } } if(com == "START"){ board[0][0] = 'X'; cout << "MOVE 0 0 <<<\n"; } if(com == "END"){ cin >> com; end = true; } } return 0; } int ocenStan(){ int endG = endGame(); if(endG == 0) return 0; if(endG == 1) return 1; if(endG == 2) return -1; if(endG == 3) return 0; return 0; } int minimax(int depth){ int ocena = ocenStan(); if(depth == 0 || ocena != 0){ return ocena; } int min = 2, max = -2, temp, X, Y; for(int i = 0; i < N; ++i) for(int j = 0; j < M; ++j){ if(board[i][j] == '.'){ if(ruch) board[i][j] = 'X'; else board[i][j] = 'O'; ruch = !ruch; temp = minimax(depth-1); ruch = !ruch; board[i][j] = '.'; if(ruch && temp > max){ if(temp == 1){ if(depth == 9){ cout<<"MOVE "<<i<<" "<<j<<" <<<\n"; board[i][j] = 'X'; } return 1; } max = temp; X = i; Y = j; } else if(!ruch && temp < min){ if(temp == -1){ return -1; } min = temp; X = i; Y = j; } } } if(min == 2) min = 0; if(max == -2) max = 0; if(depth == 9){ cout<<"MOVE "<<X<<" "<<Y<<" <<<\n"; board[X][Y] = 'X'; } return (ruch)?max:min; } void makeMove(){ int depth = 9; for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) if(board[i][j] == '.') { board[i][j] = 'X'; cout<<"MOVE "<<i<<" "<<j<<" <<<\n"; return; } } int endGame(){ bool x[8], y[8]; for(int i = 0; i < 8; ++i){ x[i] = true; y[i] = true; } for(int i = 0; i < N; ++i) for(int j = 0; j < N; ++j) if(board[i][j] == '.'){ x[i] = false; y[i] = false; x[j+N] = false; y[j+N] = false; if(i == j){ x[2*N] = false; y[2*N] = false; } if(i+j == N-1){ x[2*N+1] = false; y[2*N+1] = false; } } else if(board[i][j] == 'X'){ y[i] = false; y[j+N] = false; if(i == j) y[2*N] = false; if(i+j == N-1) y[2*N+1] = false; } else{ x[i] = false; x[j+N] = false; if(i == j) x[2*N] = false; if(i+j == N-1) x[2*N+1] = false; } for(int i = 0; i < 8; ++i){ if(x[i]) return 1; if(y[i]) return 2; } for(int i = 0; i < N; ++i) for(int j = 0; j < M; ++j) if(board[i][j] == '.') return 0; return 3; } void printBoard(){ for(int i = 0; i < N; ++i){ for(int j = 0; j < M; ++j) cout << board[i][j]; cout<<endl; } } <file_sep>/documentation/modules/game_views.rst game_views ================================= .. automodule:: ai_arena.contests.game_views :members: <file_sep>/ai_arena/media/game_judges_sources/paper_soccer_game/paper_soccer_judge.py #!/usr/bin/env python import sys def log(mes): sys.stderr.write(mes) sys.stderr.flush() def send(mes): sys.stdout.write(mes) sys.stdout.flush() def recv_mes(): try: m = sys.stdin.readline() mr = map(lambda x: int(x), m.split(',')) return mr except: return [] LEN = 11 WID = 9 visited = set() unused_edges = set() def init(): global visited global unused_edges visited = set((4,5)) visited.update([(a,b) for a in [0,8] for b in range(0,11)]) visited.update([(a,b) for a in range(1,8) for b in [0,10]]) visited.remove((4,0)) visited.remove((4,10)) current = (4,5) unused_edges = set([(a,b,c) for a in range(1,8) for b in range(1,10) for c in range(0,8)]) unused_edges.update(set([(0,b,c) for b in range(1,10) for c in [1,2,3]])) unused_edges.update(set([(8,b,c) for b in range(1,10) for c in [5,6,7]])) unused_edges.update(set([(a,0,c) for a in range(1,8) for c in [7,0,1]])) unused_edges.update(set([(a,10,c) for a in range(1,8) for c in [3,4,5]])) unused_edges.add((0,0,1)) unused_edges.add((8,0,7)) unused_edges.add((0,10,3)) unused_edges.add((8,10,5)) unused_edges.add((3,0,3)) unused_edges.update([(4,0,c) for c in [3,4,5]]) unused_edges.add((5,0,5)) unused_edges.add((3,10,1)) unused_edges.update([(4,10,c) for c in [7,0,1]]) unused_edges.add((5,10,7)) def main(): global visited global unused_edges points_1 = 0; points_2 = 0; log('log1\n') for game_num in range(4): init() send("[0] INIT\n") ok = recv_mes() if (ok != "OK\n"): points_2 += 1 continue ok = recv_mes() if (ok != "OK\n"): points_1 += 1 continue send("[{0}] UP\n".format(1 + (game_num % 2))) ok = recv_mes() if (ok != "OK\n"): points_1 += (game_num % 2) points_2 += 1 - (game_num % 2) continue send("[{0}] DOWN\n".format(2 - (game_num % 2))) ok = recv_mes() if (ok != "OK\n"): points_1 += 1 - (game_num % 2) points_2 += (game_num % 2) moving = 1 + (game_num % 2) while(True): send("[{0}] MOVE []\n".format(moving)) move = recv_mes() move_copy = move end_game = True bad_move = True who_won = 0 while (move != []): n = move[0] del move[0] if ((current[0], current[1], n) in unused_edges): newx = current[0] newy = current[1] if (n in [7,0,1]): newy += 1 if (n in [1,2,3]): newx += 1 if (n in [3,4,5]): newy -= 1 if (n in [5,6,7]): newx -= 1 current = (newx, newy) else: break if (current == (4,0) or current == (4, 10)): bad_move = False break if (current in visited) and (move == []): break elif (current not in visited) and (move != []): break elif (current in visited) and (move != []): continue elif (current not in visited) and (move == []): end_game = False bad_move = False break if (end_game): if (bad_move): points_1 += (moving-1) points_2 += (2-moving) else: s = int((current == (4,0)) ^ ((game_num % 2) == 0)) points_1 += s points_2 += (1 - s) break else: moving = 3 - moving send("[{0}] MOVE {1}\n".format(moving, move_copy)) send("[0] END\n") send("[{0}, {1}]\n".format(points_1, points_2)) main() <file_sep>/files/testing/paper_soccer/random_bot.py #!/usr/bin/env python import sys import random def log(log): sys.stderr.write(log) sys.stderr.flush() def send(mes): sys.stdout.write(mes) sys.stdout.flush() def recv_mes(): try: m = sys.stdin.readline() return m except: return [] LEN = 11 WID = 9 visited = set() unused_edges = set() direction = 0 current = (0,0) def init(): global visited global unused_edges global current visited = set((4,5)) visited.update([(a,b) for a in [0,8] for b in range(0,11)]) visited.update([(a,b) for a in range(1,8) for b in [0,10]]) visited.remove((4,0)) visited.remove((4,10)) current = (4,5) unused_edges = set([(a,b,c) for a in range(1,8) for b in range(1,10) for c in range(0,8)]) unused_edges.update(set([(0,b,c) for b in range(1,10) for c in [1,2,3]])) unused_edges.update(set([(8,b,c) for b in range(1,10) for c in [5,6,7]])) unused_edges.update(set([(a,0,c) for a in range(1,8) for c in [7,0,1]])) unused_edges.update(set([(a,10,c) for a in range(1,8) for c in [3,4,5]])) unused_edges.add((0,0,1)) unused_edges.add((8,0,7)) unused_edges.add((0,10,3)) unused_edges.add((8,10,5)) unused_edges.add((3,0,3)) unused_edges.update([(4,0,c) for c in [3,4,5]]) unused_edges.add((5,0,5)) unused_edges.add((3,10,1)) unused_edges.update([(4,10,c) for c in [7,0,1]]) unused_edges.add((5,10,7)) unused_edges.update([(4,11,a) for a in [3,4,5]]) unused_edges.add((3,11,3)) unused_edges.add((5,11,5)) unused_edges.update([(4,-1,a) for a in [7,0,1]]) unused_edges.add((3,-1,1)) unused_edges.add((5,-1,7)) def simulate(ml): global current global unused_edges global visited while(ml != []): d = ml[0] del ml[0] unused_edges.remove((current[0], current[1], d)) newx = current[0] newy = current[1] if (d in [7,0,1]): newy += 1 if (d in [1,2,3]): newx += 1 if (d in [3,4,5]): newy -= 1 if (d in [5,6,7]): newx -= 1 current = (newx,newy) unused_edges.remove((current[0], current[1], ((d+4)%8))) visited.add(current) #log("Simulated {0}".format(current)) def move(): ms = [] global current global unused_edges global visited while(True): d = -1 untried = set(range(-1,8,1)) while ((current[0], current[1], d) not in unused_edges): untried.remove(d) if (list(untried) == []): d = -1 break else: d = random.choice(list(untried)) ms.append(d) if (d == -1): log("Blocked :( \n") break unused_edges.remove((current[0], current[1], d)) newx = current[0] newy = current[1] if (d in [7,0,1]): newy += 1 if (d in [1,2,3]): newx += 1 if (d in [3,4,5]): newy -= 1 if (d in [5,6,7]): newx -= 1 current = (newx,newy) unused_edges.remove((current[0], current[1], ((d+4)%8))) if (current not in visited): visited.add(current) break send("{0}\n".format(ms)) def main(): global visited global unused_edges global direction while(True): mes = recv_mes() if (mes[0:4] == "INIT"): #log("Got init!\n") init() send("OK\n") #log("Sent OK\n") mes_dir = recv_mes() if mes_dir == "UP\n": direction = 'UP' else: direction = 'DOWN' send("OK\n") elif (mes == "\n"): pass elif (mes[0:4] == "MOVE"): ms = mes.split() if (ms[1] == "[]"): move() else: ml = map(int, (ms[1][1:-1]).split(',')) simulate(ml) move() main() <file_sep>/ai_arena/nadzorca/testing/timeout/timeout_bot.cpp #include <iostream> #include <time.h> using namespace std; int main(){ long long int a = 0; int move = 1; string s; while(true){ //sleep(10); getline(cin, s); if(move == 3) while(a < 1000000000){ a++; } cout << move << " <<<\n"; if(move < 10) move++; } return 0; } <file_sep>/ai_arena/nadzorca/testing/timeout/run.py import os current_dir = os.path.dirname(os.path.abspath(__file__)) grand_dir = os.path.dirname(os.path.dirname(current_dir)) os.sys.path.insert(0, grand_dir) import nadzorca print 'TEST timeout' judge_path = current_dir + "/timeout_judge" bot_path = current_dir + "/timeout_bot" results = nadzorca.play(judge_file=judge_path, judge_lang='CPP', players=[(bot_path, 'CPP'), (bot_path, 'CPP')], time_limit=1, memory_limit=100000) passed = True judge_info = '' for item in results['logs']['judge']: judge_info = judge_info + item if judge_info != '1122DEAD_BOT': passed = False print "judge info: " + judge_info + " instead of 1122DEAD_BOT" if results['exit_status'] != 0: passed = False print "exit status: " + str(results['exit_status']) + " instead of 0" if passed: print "PASS" else: print "FAIL" <file_sep>/ai_arena/contests/may_contest_views.py from datetime import datetime from os import system from django.core.files import File from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from django.template import RequestContext from django.http import HttpResponseRedirect from contests.forms import MayContestSendBotForTest, OnlineBotCreationForm from ai_arena.contests.models import Bot, Game, Match from ai_arena import settings from ai_arena.contests.compilation import compile from ai_arena.contests.bot_views import create_bot_from_request, send_bot_without_name from ai_arena.contests.game_launcher import launch_single_match from ai_arena.contests.may_contest_helper_functions import * @login_required def my_results(request): """ Selects from database results of all matches against a User's Bot.\n Contains both ranked and test matches. """ matches = []#Match.objects.all() #[] for match in Match.objects.all(): for mbr in match.players_results.all(): if (mbr.bot.owner == request.user) & (match not in matches): matches.append(match) ranked_matches = [] test_matches = [] for match in matches: if match.ranked_match: ranked_matches.append(match) else: test_matches.append(match) return render_to_response('may_contest/results.html', { 'ranked_matches': ranked_matches, 'test_matches': test_matches, }, context_instance=RequestContext(request)) @login_required def match_details(request, match_id): """ Displays details of a Match object with given match_id. """ match = Match.objects.get(id=match_id) return render_to_response('may_contest/match_details.html', { 'match': match, 'user': request.user, # 'player1': match.objects.all()[0], # 'player2': match.objects.all()[1], }, context_instance=RequestContext(request)) def show_ladder(request): """ Generates, refreshes and displays current ranking of may Contest. """ ranking = generate_ranking() if ranking: ladder = sorted(ranking.botranking_set.all(), key=lambda botranking: botranking.position) else: ladder = [] return render_to_response('may_contest/show_ranking.html', { 'ranking': ranking, 'ladder': ladder, }, context_instance=RequestContext(request)) @login_required def may_contest_send_bot(request): """ This view is used when user wants to send bot from game details view. It is different from simple send bot view, because game is known, so there is no need to pick it form list. """ game_id = get_may_game().id may_contest = get_default_may_contest() if may_contest.ranking: may_contest.ranking.updated = False may_contest.ranking.save() return send_bot_without_name(request, game_id) @login_required def testing(request): """ View responsible for displaying form to upload Bots to test.\n Using provided form User can upload one or two Bot's source codes. In case of uploading two source codes system performs a Match between these two Bots. If User uploads only one source code, then system performs Match against default Bot. """ if request.method == 'POST': form = MayContestSendBotForTest(request.POST, request.FILES) if not form.is_valid(): return render_to_response('may_contest/testing.html', { 'form': form, }, context_instance=RequestContext(request)) else: # Handle a bot (exit_status, logs, bot) = create_bot_from_request(request, get_may_game(), testing=True) if exit_status != 0: return render_to_response('error.html', { 'error_details': logs, }, context_instance = RequestContext(request)) # Check is user uploaded also an opponent # If so - handle it if 'opponent_source' in request.FILES: (exit_status, logs, opp) = create_bot_from_request(request, get_may_game(), bot_field='opponent_source', testing=True) if exit_status != 0: # error occured return render_to_response('error.html', { 'error_details': logs, }, context_instance = RequestContext(request)) # otherwise - use default bot as an opponent else: opp = get_default_may_contest_bot() launch_single_match(get_may_game(), [bot, opp]) return HttpResponseRedirect('/testing/uploaded/') else: form = MayContestSendBotForTest() return render_to_response('may_contest/testing.html', { 'form': form, 'judge_path': settings.MAY_CONTEST_EXAMPLE_JUDGE_PATH, 'bot_path': settings.MAY_CONTEST_EXAMPLE_BOT_PATH, 'judge_manual_path': settings.MAY_CONTEST_JUDGE_MANUAL_PATH, }, context_instance=RequestContext(request)) def uploaded_for_tests(request): return render_to_response('may_contest/uploaded_for_testing.html', context_instance=RequestContext(request)) def online_bot_uploaded(request, bot_name): return render_to_response('may_contest/online_bot_uploaded.html', { 'bot_name': bot_name, }, context_instance=RequestContext(request)) @login_required def online_bot_creation(request): """ Page where everyone can prepare bot online and submit it to contest. """ default_bot_codes = get_default_bot_codes() code_names = settings.PICNIC_DEFAULT_BOTS_NAMES user = request.user may_contest = get_default_may_contest() if may_contest.ranking: may_contest.ranking.updated = False may_contest.ranking.save() if request.method == 'POST': form = OnlineBotCreationForm(request.POST, initial=default_bot_codes) if not form.is_valid(): return render_to_response('may_contest/online_bot_creation.html', { 'form': form, 'code_names': code_names, }, context_instance=RequestContext(request)) else: source_code = request.POST['code'] error_log = create_bot_and_add_to_contest(source_code=source_code, owner=user, contest=may_contest, bot_language=settings.PICNIC_DEFAULT_LANGUAGE) if error_log: return render_to_response('error.html', { 'error_details': error_log, }, context_instance = RequestContext(request)) return HttpResponseRedirect('/ladder/') else: form = OnlineBotCreationForm(initial=default_bot_codes) return render_to_response('may_contest/online_bot_creation.html', { 'form': form, 'code_names': code_names, }, context_instance=RequestContext(request)) <file_sep>/files/testing/kk/Makefile all: g++ -Wall -g kk_judge.cpp -o judge g++ -Wall -g kk_bot.cpp -o bot clean: rm -rf judge bot <file_sep>/ai_arena/nadzorca/testing/pok/Makefile all: pok_judge pok_bot timeout_judge: pok_judge.cpp g++ pok_judge.cpp -O0 -o pok_judge timeout_bot: bot_logs_bot.cpp g++ pok_bot.cpp -O0 -o pok_bot clean: rm pok_judge pok_bot <file_sep>/files/universal makefile/cpp.mk # uniwersalny makefile dla języka C++ CC = g++ CFLAGS = -Wall -g OBJ = $(SRC:.cpp=.o) all : $(TARGET) $(TARGET) : $(OBJ) $(CC) $(CFLAGS) -o $(TARGET) $(OBJ) .cpp.o: $(CC) $(CFLAGS) -c $< -o $@ <file_sep>/documentation/modules/user_views.rst user_views ================================= .. automodule:: ai_arena.contests.user_views :members: <file_sep>/makefile/makefile.py from os import system def compile(src, target, lang): print('make SRC=' + src + " TARGET=" + target + " LANG=" + lang) system('make SRC=' + src + " TARGET=" + target + " LANG=" + lang) <file_sep>/ai_arena/nadzorca/testing/memory_limit/Makefile all: memory_limit_judge memory_limit_bot timeout_judge: memory_limit_judge.cpp g++ memory_limit_judge.cpp -O0 -o memory_limit_judge timeout_bot: memory_limit_bot.cpp g++ memory_limit_bot.cpp -O0 -o memory_limit_bot clean: rm memory_limit_judge memory_limit_bot <file_sep>/ai_arena/contests/contest_views.py from django.shortcuts import render_to_response, redirect from django.template import RequestContext from ai_arena.contests.models import Contest, BotRanking, ContestComment from ai_arena.contests.forms import BotsSelectForm def contests_list(request): """ Displays list of all available contests. """ contests = Contest.objects.all() return render_to_response('contests/contests_list.html', { 'contests': contests, }, context_instance=RequestContext(request), ) def show_contest(request, contest_id, error_msg=None): """ Displays info about the contest, with it's current rank list, and comments underneath. """ contest = Contest.objects.get(id=contest_id) if not contest.ranking: contest.generate_group_ranking() contest.save() ranking_list = BotRanking.objects.filter(ranking=contest.ranking) ranking_list = sorted(ranking_list, key=lambda x: x.position) comments = ContestComment.objects.filter(contest=contest) moderators = contest.moderators.all() return render_to_response('contests/display_contest.html', { 'contest': contest, 'object_id': contest.id, 'ranking_list': ranking_list, 'comments': comments, 'moderators': moderators, 'template_type': 'contests', 'error_msg': error_msg, }, context_instance=RequestContext(request), ) def add_contestant(request, contest_id): """ Returns a view to render that allows to select a bot to add to given contests. """ contest = Contest.objects.get(id=contest_id) contestants = contest.contestants.all().values_list('id', flat=True) game = contest.game bot_form = None if request.method == 'POST': if 'bot_form' in request.POST: number_of_bots = 1 bot_form = BotsSelectForm(request.POST, game=game, number_of_bots=number_of_bots, prefix='bot') if bot_form.is_valid(): for i in range(number_of_bots): bot = bot_form.cleaned_data['bot_field%d' % (i+1)] if bot.id not in contestants: contest.contestants.add(bot) contestants.append(bot.id) return redirect('/') if not bot_form: bot_form = BotsSelectForm(game=game, number_of_bots=1, prefix='bot') return render_to_response('contests/add_contestant.html', { 'bot_form': bot_form, 'contest_id': contest.id, }, context_instance=RequestContext(request) ) <file_sep>/ai_arena/templates/send/results.html {% extends "send/base_send.html" %} {% block title %} Results {% endblock %} {% block content %} <h1> Results </h1> {% if lang1 %} <h2> Language1: {{ lang1 }} </h2> {% endif %} {% if prog1 %} <h3> Prog1: {{ prog1 }} </h3> {% endif %} {% if lang2 %} <h2> Language2: {{ lang2 }} </h2> {% endif %} {% if prog2 %} <h3> Prog2: {{ prog2 }} </h3> {% endif %} {% if i %} {{ i }} {% endif %} {% endblock %} <file_sep>/documentation/modules/utils.rst utils ====================== .. automodule:: ai_arena.utils :members: <file_sep>/ai_arena/nadzorca/testing/pok2/pok_judge.cpp #include <iostream> #include <sstream> #include <time.h> #include <stdlib.h> #define MIN_BET 10 #define MAX_BET 200 #define CARD_COUNT 5 #define ROUNDS_COUNT 2 #define CALL 1 #define FOLD 0 using namespace std; string toSend[3]; int receivedMes[3]; bool communicate = true; int actualBet = 0; void error(int pl, string info){ if(communicate){ cerr << "ERRRORR: player " << pl << " " << info << "\n"; cerr << "wys " << "[" << pl << "]KILL\n"; cout << "[" << pl << "]KILL\n"; cout << "[0]END\n"; if(pl == 1) cout << "[0, 2]\n"; else cout << "[2, 0]\n"; } communicate = false; } void buffer(int pl, int mes){ stringstream ss; ss << mes; if(toSend[pl] != "") toSend[pl] += " "; toSend[pl] += ss.str(); } void send(int pl){ string mes, received; mes = toSend[pl]; toSend[pl] = ""; if(communicate){ cerr << "wys " << "[" << pl << "]" << mes << "\n"; cout << "[" << pl << "]" << mes << "\n"; getline(cin, received); cerr << "dost " << received << "\n"; } if(received == "_DEAD_") error(pl, "dead"); else{ istringstream ss(received); int num; if((ss >> num).fail()) error(pl, "NaN"); else receivedMes[pl] = num; } } void readMes(int pl, int& mes, int min, int max, bool maybe0){ int num = receivedMes[pl]; if(((num >= min) && (num <= max)) || (maybe0 && (num == 0))){ mes = num; receivedMes[pl] = -1; }else error(pl, "mes out of range"); } int decisionMaker(int * bets){ if(bets[1] < bets[2]) return 1; if(bets[2] < bets[1]) return 2; return 0; } int opponent(int player){ return 3 - player; } bool readBets(int * bets, bool firstRound){ for(int pl=1; pl <= 2; pl++) if(bets[pl] == 0) readMes(pl, bets[pl], MIN_BET, MAX_BET, false); for(int pl=1; pl <= 2; pl++) buffer(opponent(pl), bets[pl]); int dm = decisionMaker(bets); if(dm){ int op = opponent(dm); send(dm); int response; if(firstRound) readMes(dm, response, MIN_BET, MAX_BET, true); else readMes(dm, response, 0, 1, true); if(response > 0){ buffer(op, CALL); if(firstRound){ send(op); bets[dm] = response; } actualBet += bets[op]; bets[op] = 0; bets[0] = 0; }else{ actualBet += bets[dm]; buffer(op, FOLD); bets[0] = op; } }else{ actualBet += bets[1]; bets[0] = 0; for(int pl=1; pl <= 2; pl++) bets[pl] = 0; if(firstRound) for(int pl=1; pl <= 2; pl++) send(pl); } return true; } int main(){ for(int i=0; i < 3; i++){ toSend[i] = ""; receivedMes[i] = -1; } int bets[3]; int scores[3]; int pl1card=0, pl2card=0; int decision=0; int winner=0; int sum1=0, sum2=0; scores[0] = scores[1] = scores[2] = 0; srand(getpid() + time(NULL)); for(int i=0; i<ROUNDS_COUNT; i++){ pl1card = rand() % CARD_COUNT; pl2card = rand() % CARD_COUNT; for(int i=0; i < 3; i++) bets[i] = 0; buffer(1, pl1card); buffer(2, pl2card); cerr << "sending CARDS " << pl1card << " " << pl2card << "\n"; send(1); send(2); sum1 += pl1card; sum2 += pl2card; winner = 0; actualBet = 0; if(pl1card > pl2card) winner = 1; if(pl2card > pl1card) winner = 2; readBets(bets, true); if(bets[0]) winner = bets[0]; else{ cerr << "second BET\n"; readBets(bets, false); if(bets[0]) winner = bets[0]; else{ buffer(1, pl2card); buffer(2, pl1card); } } cerr << "winner " << winner << " actBet " << actualBet << "\n"; if(winner) scores[winner] += actualBet; } cerr << "sum of cards " << sum1 << " " << sum2 << "\n"; cerr << "scores " << scores[1] << " " << scores[2] << "\n"; cout << "[0]END\n"; if(scores[1] > scores[2]) cout << "[2, 0]\n"; if(scores[2] > scores[1]) cout << "[0, 2]\n"; if(scores[1] == scores[2]) cout << "[1, 1]\n"; return 0; } <file_sep>/ai_arena/contests/may_contest_helper_functions.py import os from django.conf import settings from django.core.files import File from django.core.exceptions import ObjectDoesNotExist from ai_arena.utils import get_current_date_time from ai_arena.contests.models import User, Game, Bot, Contest, Ranking """ This module contains views needed to perform may contest.\n The fact that GUI of may contest was slightly different from the final one explains why separate views were needed.\n\n WARNING: These views shoud not be used after closing may contest! """ def create_may_game(): """ Function creating instance of may Game. """ try: game = Game() game.name = settings.MAY_CONTEST_GAME_NAME game.min_players = settings.MAY_CONTEST_PLAYERS_NUMBER game.max_players = settings.MAY_CONTEST_PLAYERS_NUMBER game.judge_lang = settings.MAY_CONTEST_GAME_JUDGE_LANG game.judge_source_file.save(game.name + settings.SOURCE_FORMATS[game.judge_lang], File(open(settings.MAY_CONTEST_GAME_JUDGE_PATH))) game.rules_file.save(game.name, File(open(settings.MAY_CONTEST_GAME_RULES_PATH))) game.save() moderator = User.objects.get(username=settings.MAY_MODERATOR_NAME) game.moderators.add(moderator) game.compile_judge() return game except Exception as e: # If something went wrong, delete the game Game.objects.filter(name=settings.MAY_CONTEST_GAME_NAME).delete() raise e def create_may_default_bot(): """ Function creating instance of may default Bot, against which other Bots could be tested. """ try: bot = Bot() bot.name = settings.MAY_CONTEST_DEFAULT_BOT_NAME bot.owner = User.objects.get(username=settings.TEST_USER_NAME) bot.game = get_may_game() bot.bot_lang = settings.MAY_CONTEST_DEFAULT_BOT_LANG bot.bot_source_file.save(bot.name + settings.SOURCE_FORMATS[bot.bot_lang], File(open(settings.MAY_CONTEST_DEFAULT_BOT_PATH))) bot.ranked = False bot.save() bot.compile_bot() return bot except Exception as e: # If something went wrong, delete the bot Bot.objects.filter(name=settings.MAY_CONTEST_DEFAULT_BOT_NAME).delete() raise e def create_may_contest(): """ Creates an instance of may Contest. """ try: contest = Contest() contest.name = settings.MAY_CONTEST_NAME contest.game = get_may_game() contest.begin_date = settings.MAY_CONTEST_BEGIN_DATE contest.end_date = settings.MAY_CONTEST_END_DATE contest.regulations_file.save(contest.name, File(open(settings.MAY_CONTEST_REGULATIONS_PATH))) contest.memory_limit = settings.MAY_CONTEST_MEMORY_LIMIT contest.time_limit = settings.MAY_CONTEST_TIME_LIMIT ranking = Ranking(type=Ranking.TYPE_GROUP) ranking.date_updated = get_current_date_time() ranking.save() contest.ranking = ranking contest.save() moderator = User.objects.get(username=settings.MAY_MODERATOR_NAME) contest.moderators.add(moderator) contest.save() return contest except Exception as e: # If something went wrong, delete the contest Contest.objects.filter(name=settings.MAY_CONTEST_NAME).delete() raise e def get_may_game(): """ Helper function to access instance of may Game. If no such object exist this function creates a new one. """ try: return Game.objects.get(name=settings.MAY_CONTEST_GAME_NAME) except ObjectDoesNotExist: return create_may_game() def get_default_may_contest_bot(): """ Helper function to access instance of default Bot. If no such object exist this function creates a new one. """ try: return Bot.objects.get(name=settings.MAY_CONTEST_DEFAULT_BOT_NAME) except ObjectDoesNotExist: return create_may_default_bot() def get_default_may_contest(): """ Helper function to access instance of may Contest. If no such object exist this function creates a new one. """ try: return Contest.objects.get(name=settings.MAY_CONTEST_NAME) except ObjectDoesNotExist: return create_may_contest() def get_picnic_user(): return User.objects.get(username=settings.MAY_CONTEST_PICNIC_USERNAME) def get_default_may_ranking(): """ Helper function to access instance of Ranking. """ contest = get_default_may_contest() if not contest: raise Exception("There is no may contest") return contest.ranking def generate_ranking(): """ Function used to generate Ranking object to may Contest. """ contest = get_default_may_contest() if not contest: raise Exception("There is no may contest") """ if contest.ranking: if contest.ranking.updated: return contest.ranking """ contest.contestants.clear() game = get_may_game() game_bots = Bot.objects.filter(game=game, invalid=False, ranked=True) for bot in game_bots: contest.contestants.add(bot) contest.generate_group_ranking() return contest.ranking def find_new_name_for_bot(bot_name, owner): if not Bot.objects.filter(owner=owner, name=bot_name).count(): return bot_name suffix = 2 while Bot.objects.filter(owner=owner, name=bot_name + str(suffix)).count(): suffix += 1 return bot_name + str(suffix) def create_bot_and_add_to_contest(source_code, owner, contest, bot_language): """ Creates new bot with owner from source code, adds suffix to name if needed Returns new name and error_log if something went wrong. """ bot_name = owner.username + '_bot' bots_to_delete = Bot.objects.filter(owner=owner, name=bot_name) bot_path = settings.PICNIC_BOTS_PATH + bot_name + settings.SOURCE_FORMATS[bot_language] bot_file = open(bot_path, 'w') bot_file.write(source_code) bot_file.close() new_bot = Bot(name=bot_name, owner=owner, game=contest.game, bot_lang=bot_language) new_bot.bot_source_file.save(new_bot.name + settings.SOURCE_FORMATS[new_bot.bot_lang], File(open(bot_path))) new_bot.save() exit_status, logs = new_bot.compile_bot() print('logs', logs) if exit_status != 0: new_bot.delete() return logs else: for bot in bots_to_delete: if bot.id != new_bot.id: bot.delete_bot_matches() bot.delete() contest.contestants.add(new_bot) return None def read_code_from_file(filename): file = open(filename, 'r') code = file.read() file.close() return code def get_default_bot_codes(): """ Helper function returning templates of bots for may Contest. """ bot_codes = dict() bot_codes['bot_code1'] = read_code_from_file(settings.PICNIC_BOT_CODES_FILES['bot_code1']) bot_codes['bot_code2'] = read_code_from_file(settings.PICNIC_BOT_CODES_FILES['bot_code2']) bot_codes['bot_code3'] = read_code_from_file(settings.PICNIC_BOT_CODES_FILES['bot_code3']) bot_codes['bot_code4'] = read_code_from_file(settings.PICNIC_BOT_CODES_FILES['bot_code4']) return bot_codes <file_sep>/ai_arena/nadzorca/testing/timeout/timeout_judge.cpp #include <iostream> #include <sstream> #include <time.h> using namespace std; int main(){ bool end = false; bool firstMoves = true; int move = 0; string response; while(!end){ cout << (firstMoves ? "[1] " : "[2] ") << "MOVE <<<\n"; getline(cin, response); if(response == "_DEAD_<<<"){ cerr << "DEAD_BOT"; usleep(10); cout << "[0]END<<<\n"; cout << "[0, 0]<<<\n"; end = true; } else{ stringstream(response) >> move; cerr << move; } if((move == 5)&&(!end)){ end = true; cout << "[0]END<<<\n"; if(firstMoves) cout << "[1, 0]<<<\n"; else cout << "[0, 1]<<<\n"; } firstMoves = !firstMoves; } return 0; } <file_sep>/ai_arena/contests/game_views.py from os import system from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponseRedirect from django.core.files import File from django.contrib.auth.decorators import login_required from ai_arena import settings from ai_arena.contests.forms import NewGameForm, EditGameForm from ai_arena.contests.models import Game, GameComment from ai_arena.contests.compilation import compile import shutil @login_required def create_new_game(request): """ Prepares a form to render for creating new game. Later it checks results, and if everything is OK it saves new Game object to database """ if request.method == 'POST': form = NewGameForm(request.POST, request.FILES) if form.is_valid(): # Save known fields game = Game() game.name = request.POST['game_name'] # Check if there exist another game wuth that name games = Game.objects.filter(name=game.name) if len(games) > 0: error_msg = 'There already exists a game with that name!' return render_to_response('gaming/new_game.html', { 'form': form, 'error_msg': error_msg, }, context_instance=RequestContext(request)) game.rules_file = request.FILES['game_rules'] game.judge_source_file = request.FILES['game_judge'] game.max_players = request.POST['max_players'] game.judge_lang = request.POST['judge_language'] game.save() game.moderators.add(request.user) game.compile_judge() return HttpResponseRedirect('/game_details/' + str(game.id) + '/') else: form = NewGameForm() return render_to_response('gaming/new_game.html', { 'form': form, }, context_instance=RequestContext(request)) def game_list(request): """ Displays list of available games """ games = Game.objects.all() return render_to_response('gaming/game_list.html', { 'games': games, }, context_instance=RequestContext(request)) def parse_game_details(game): """ Helper function preparing subobjects of game object to display. """ rules = game.rules_file line = rules.readline() game_details = [] while line: game_details.append(line) line = rules.readline() return game_details def game_details(request, game_id, error_msg=None): """ Displays detailed information about game with id equal to game_id If game_id is not given or there is no Game object with id equal to game_id then Exception is thrown """ if not game_id: raise Exception("In game_details: No game_id given") game = Game.objects.get(id=game_id) if game is None: raise Exception("In game_details: Wrong game_id given") comments = GameComment.objects.filter(game=game) return render_to_response('gaming/game_details.html', { 'game': game, 'object_id': game.id, 'game_details': parse_game_details(game), 'comments': comments, 'moderators': game.moderators.all(), 'template_type': 'game_details', 'error_msg': error_msg, }, context_instance=RequestContext(request)) def parse_line(line, lang): """ Parses line of source code returning list of pairs (class, value), where class is to be used in html code to apply correct css """ parsed = [] #this is to display correctly beginning white characters while len(line) > 0 and (line[0] == ' ' or line[0] == '\t'): if line[0] == ' ': parsed.append( {'class':'space', 'value':''} ) else: parsed.append( {'class':'tab', 'value':''} ) line = line[1:] #then follow the rest of the line if lang == settings.C_LANGUAGE: keywords = settings.C_KEYWORDS types = settings.C_TYPES elif lang == settings.CPP_LANGUAGE: keywords = settings.CPP_KEYWORDS types = settings.CPP_TYPES elif lang == settings.JAVA_LANGUAGE: keywords = settings.JAVA_KEYWORDS types = settings.JAVA_TYPES elif lang == settings.PYTHON_LANGUAGE: keywords = settings.PYTHON_KEYWORDS types = settings.PYTHON_TYPES splited = line.split() for s in splited: if s in keywords: parsed.append( {'class':'keyword', 'value':s} ) elif s in types: parsed.append( {'class':'types', 'value':s} ) elif (lang == 'CPP' or lang == 'C') and s.startswith('#'): parsed.append( {'class':'special', 'value':s} ) elif (lang == 'CPP' or lang == 'C') and s.startswith('<') and s.endswith('>'): parsed.append( {'class':'special', 'value':s} ) else: parsed.append( {'class':'normal', 'value':s} ) return parsed def show_source(request, game_id): """ Displays source code of the judge connected with game with id=game_id """ #get the game object game = Game.objects.get(id=game_id) if game is None: raise Exception("In show_source: Wrong game_id given") #get the language lang = game.judge_lang #get the source code of judge judge = game.judge_source_file line = judge.readline() source = [] while line: line = line[:-1] #get rid of \n char parsed_line = parse_line(line, lang) source.append(parsed_line) line = judge.readline() #parse code according to language rules #find key words #find comments #find strings #find procedure names return render_to_response('gaming/show_source.html', { 'source':source, }, context_instance=RequestContext(request)) @login_required def edit_game(request, game_id): """ Allows user to edit game description and other details. Takes one extra argument - game_id - describing id of a game to edit. The view takes care of safety issues - it checks if a user calling this view has apprioprate privillages (is a moderator of the game or staff member) """ game = Game.objects.get(id=game_id) user = request.user if not user.is_staff and user not in game.moderators.all(): return HttpResponseRedirect('/') if request.method == 'POST': # If user changes a gamename we have to do several things: # change name in objects, change all paths and make sure that no other # game with this name exists if 'name' in request.POST and request.POST['name'] != game.name: games = Game.objects.filter(name=request.POST['name']) if len(games) > 0: form = EditGameForm(initial={ 'name': game.name, 'description': game.rules_file.read(), 'judge_language': game.judge_lang, }) error_msg = 'There exist other game with that name!' return render_to_response('gaming/edit_game.html', { 'form': form, 'game': game, 'error_msg': error_msg, }, context_instance=RequestContext(request)) # When we made sure that game name is unique we can make necessairy changes oldname = game.name game.name = request.POST['name'] game.save() def move(source, file): filename = file.name.split('/').pop() file.save(filename, file) system('rm -rf ' + source) move(settings.GAME_RULES_PATH + oldname + '/', game.rules_file) move(settings.GAME_JUDGE_SOURCES_PATH + oldname + '/', game.judge_source_file) move(settings.GAME_JUDGE_BINARIES_PATH + oldname + '/', game.judge_bin_file) # When somebody updated decsription it's easier to create new file # instead of diff with previous one. if 'description' in request.POST: # create new file path = settings.GAME_RULES_PATH + game.name + '/' filename = game.rules_file.name.split('/').pop() game.rules_file.delete() f = open(path + 'tempfile', 'w') f.write(request.POST['description']) f = open(path + 'tempfile', 'rw') # save changes file_to_save = File(f) game.rules_file.save(filename, file_to_save) # remove temp file system('rm ' + path + 'tempfile') # if user updated just rules file we've got an easy job :P if 'game_rules' in request.FILES: game.rules_file.delete() game.rules_file = request.FILES['game_rules'] # if judge file has changed bigger changes are necessairy game.judge_lang = request.POST['judge_language'] if 'game_judge' in request.FILES: # delete old (no longer needed files game.judge_source_file.delete() game.judge_bin_file.delete() #save new instead game.judge_source_file = request.FILES['game_judge'] game.save() # Recompile source file to directory with source file src = settings.MEDIA_ROOT + game.judge_source_file.name target = settings.MEDIA_ROOT + game.judge_source_file.name + '.bin' lang = game.judge_lang compile(src, target, lang) # Use compiled file in object game f = File(open(target)) game.judge_bin_file.save(game.name, f) # Save changes made to game object game.save() # Remove compiled file from directory with source system('rm ' + target) return HttpResponseRedirect('/game_details/' + game_id + '/') game.save() return HttpResponseRedirect('/game_details/' + game_id + '/') else: form = EditGameForm(initial={ 'name': game.name, 'description': game.rules_file.read(), 'judge_language': game.judge_lang, }) return render_to_response('gaming/edit_game.html', { 'form': form, 'game': game, }, context_instance=RequestContext(request)) @login_required def delete_game(request, game_id): """ Deletes game which id is equal to game_id. The view performs a safety check - it makes sure that user has apprioprate previllages (is either a moderator of this game or admin). """ user = request.user game = Game.objects.get(id=game_id) if not user.is_staff and not user in game.moderators.all(): return HttpResponseRedirect('/game_details/' + game_id + '/') # Not only we have to delete object from database, but also all files related to it gamename = game.name path = settings.MEDIA_ROOT game.delete() system('rm -rf ' + path + settings.JUDGES_SOURCES_DIR + '/' + gamename + '/') system('rm -rf ' + path + settings.JUDGES_BINARIES_DIR + '/' + gamename + '/') system('rm -rf ' + path + settings.RULES_DIR + '/' + gamename + '/') return HttpResponseRedirect('/') <file_sep>/ai_arena/contests/views.py from django.shortcuts import render_to_response from django.template import RequestContext def index(request): """ Returns main template to render. """ return render_to_response('index.html', context_instance=RequestContext(request)) def error(request): """ Shows standard error page when an error occurs (e.g. during compilation) """ return render_to_response('error.html', context_instance=RequestContext(request)) def contact(request): """ Shows template with contact informations. """ return render_to_response('contact.html', context_instance=RequestContext(request)) <file_sep>/ai_arena/settings_defaults.py # Django settings for ai_arena project. import os BASE_DIR = os.path.abspath(os.path.dirname(__file__)) def ABS_DIR(rel): return os.path.join(BASE_DIR, rel.replace('/',os.path.sep)) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('<NAME>', '<EMAIL>'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'ai_arena', # Or path to database file if using sqlite3. 'USER': 'ai_arena', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale USE_L10N = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = ABS_DIR('media/') # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '/media/' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = ABS_DIR('static/') # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # URL prefix for admin static files -- CSS, JavaScript and images. # Make sure to use a trailing slash. # Examples: "http://foo.com/static/admin/", "/static/admin/". ADMIN_MEDIA_PREFIX = '/static/admin/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = '<KEY>' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'ai_arena.urls' TEMPLATE_DIRS = ( ABS_DIR("templates"), # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'ai_arena.contests', 'ai_arena.nadzorca', 'ai_arena.registration2', 'captcha', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', ) RECAPTCHA_PUBLIC_KEY = '<KEY>' RECAPTCHA_PRIVATE_KEY = '<KEY>' AUTH_PROFILE_MODULE = 'contests.UserProfile' # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } "Constants section" ACCOUNT_ACTIVATION_DAYS = 7 REGISTRATION_OPEN = True DEFAULT_FROM_EMAIL = '<EMAIL>' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST='localhost' EMAIL_PORT='1025' LANGUAGES = ( ('C', 'C'), ('CPP', 'C++'), ('PYTHON', 'Python'), ) MAKEFILE_DIR = ABS_DIR('../makefile/') MAKEFILE_PATH = MAKEFILE_DIR + 'Makefile' # contests/models.py NAME_LENGTH = 255 LANG_LENGTH = 10 GAME_MIN_PLAYERS_DEFAULT = 1 GAME_MAX_PLAYERS_DEFAULT = 6 COMPILATION_TEMP_DIR = 'compilation_temp' RULES_DIR = 'game_rules' JUDGES_BINARIES_DIR = 'game_judges_binaries' JUDGES_SOURCES_DIR = 'game_judges_sources' BOTS_BINARIES_DIR = 'game_bots_binaries' BOTS_SOURCES_DIR = 'game_bots_sources' CONTEST_REGULATIONS_DIR = 'contests_regulations' PHOTOS_DIR = 'profiles/photos' SCORE_DIGITS = 15 SCORE_DECIMAL_PLACES = 6 # in MB DEFAULT_GAME_MEMORY_LIMIT = 32 # in miliseconds DEFAULT_GAME_TIME_LIMIT = 5000 DEFAULT_CONTEST_MEMORY_LIMIT = DEFAULT_GAME_MEMORY_LIMIT DEFAULT_CONTEST_TIME_LIMIT = DEFAULT_GAME_TIME_LIMIT # /contests/game_views.py GAME_RULES_PATH = MEDIA_ROOT + RULES_DIR + '/' GAME_JUDGE_SOURCES_PATH = MEDIA_ROOT + JUDGES_SOURCES_DIR + '/' GAME_JUDGE_BINARIES_PATH = MEDIA_ROOT + JUDGES_BINARIES_DIR + '/' COMPILATION_TEMP_PATH = MEDIA_ROOT + COMPILATION_TEMP_DIR + '/' # bot create page BOT_CREATE_FIELD_COLUMNS = 200 BOT_CREATE_FIELD_ROWS = 20 C_LANGUAGE = 'C' C_KEYWORDS = ['auto', 'break', 'case', 'const', 'continue', 'default', 'do', 'else', 'enum', 'extern', 'for', 'goto', 'if', 'register', 'return', 'signed', 'sizeof', 'static', 'struct', 'switch', 'typedef', 'union', 'unsigned', 'volatile', 'while'] C_TYPES = ['char', 'double', 'float', 'int', 'long', 'short', 'void'] CPP_LANGUAGE = 'CPP' CPP_KEYWORDS = ['and', 'and_eq', 'alignas', 'alignof', 'asm', 'auto', 'bitand', 'bitor', 'break', 'case', 'catch', 'class', 'compl', 'const', 'constexpr', 'const_cast', 'continue', 'decltype', 'default', 'delete', 'do', 'dynamic_cast', 'else', 'enum', 'explicit', 'export', 'extern', 'false', 'for', 'friend', 'goto', 'if', 'inline', 'long', 'mutuable', 'namespace', 'new', 'noexcept', 'not', 'not_eq', 'nullptr', 'operator', 'or', 'or_eq', 'private', 'protected', 'public', 'register', 'reinterpret_cast', 'return', 'signed', 'sizeof', 'static', 'static_assert', 'static_cast', 'struct', 'switch', 'template', 'this', 'thread_local', 'throw', 'true', 'try', 'typedef', 'typeid', 'typename', 'union', 'unsigned', 'using', 'virtual', 'volatile', 'wchar_t', 'while', 'xor', 'xor_eq', 'override', 'final'] CPP_TYPES = ['bool', 'char', 'char16_t', 'char32_t', 'double', 'float', 'int', 'long', 'short', 'void'] JAVA_LANGUAGE = 'JAVA' JAVA_KEYWORDS = ['abstract', 'assert', 'break', 'case', 'catch', 'class', 'const', 'continue', 'default', 'do', 'else', 'enum', 'extends', 'final', 'finally', 'for', 'goto', 'if', 'implements', 'import', 'instanceof', 'interface', 'native', 'new', 'package', 'private', 'protected', 'public', 'return', 'static', 'staticfp', 'super', 'switch', 'synchronized', 'this', 'throw', 'throws', 'transient', 'try', 'volatile', 'while'] JAVA_TYPES = ['boolean', 'byte', 'char', 'double', 'float', 'int', 'long', 'short', 'void'] PYTHON_LANGUAGE = 'PYTHON' PYTHON_KEYWORDS = ['and', 'as', 'assert', 'break', 'class', 'contiune', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield'] PYTHON_TYPES = [] SOURCE_FORMATS = { C_LANGUAGE: '.c', CPP_LANGUAGE: '.cpp', JAVA_LANGUAGE: '.java', PYTHON_LANGUAGE: '.py', } # contests/game_launcher.py GEARMAN_HOST = 'localhost:4730' TEST_USER_NAME = 'test_user' # May Contest constants MAY_MODERATOR_NAME = "may_master" MAY_CONTEST_NAME = "May Contest" MAY_CONTEST_BEGIN_DATE = '2012-05-12 00:00' MAY_CONTEST_END_DATE = '2012-05-16 23:59' MAY_CONTEST_REGULATIONS_PATH = ABS_DIR("../files/may_game/contest_regulations.txt") # in MB MAY_CONTEST_MEMORY_LIMIT = 64 # in miliseconds MAY_CONTEST_TIME_LIMIT = 5000 MAY_CONTEST_GAME_NAME = "POK" MAY_CONTEST_GAME_JUDGE_LANG = CPP_LANGUAGE MAY_CONTEST_GAME_JUDGE_PATH = ABS_DIR("../files/may_game/pok_judge.cpp") MAY_CONTEST_JUDGE_MANUAL_PATH = ABS_DIR("../files/may_game/pok_judge_manual.txt") MAY_CONTEST_BOT_PATH = ABS_DIR("../files/may_game/pok_bot.cpp") MAY_CONTEST_GAME_RULES_PATH = ABS_DIR("../files/may_game/pok_rules.txt") MAY_CONTEST_PLAYERS_NUMBER = 2 MAY_CONTEST_EXAMPLE_JUDGE_PATH = MEDIA_URL + "may_contest/judge.cpp" MAY_CONTEST_EXAMPLE_BOT_PATH = MEDIA_URL + "may_contest/bot.cpp" MAY_CONTEST_JUDGE_MANUAL_PATH = MEDIA_URL + "may_contest/README.txt" MAY_CONTEST_DEFAULT_BOT_PATH = ABS_DIR("../files/may_game/pok_bot.cpp") MAY_CONTEST_DEFAULT_BOT_NAME = "POK_default_bot" MAY_CONTEST_DEFAULT_BOT_LANG = CPP_LANGUAGE MAY_CONTEST_PICNIC_USERNAME = "picnic_user" PICNIC_DEFAULT_LANGUAGE = PYTHON_LANGUAGE PICNIC_BOTS_PATH = ABS_DIR("media/picnic_bots/") PICNIC_DEFAULT_BOTS_NAMES = { 'bot_code1' : 'Bot Template', 'bot_code2' : 'Weak Bot', 'bot_code3' : 'Medium Bot', 'bot_code4' : 'Strong Bot', } PICNIC_BOT_CODES_FILES = { 'bot_code1' : ABS_DIR("../files/may_game/default_bots/template_bot.py"), 'bot_code2' : ABS_DIR("../files/may_game/default_bots/weak_bot.py"), 'bot_code3' : ABS_DIR("../files/may_game/default_bots/medium_bot.py"), 'bot_code4' : ABS_DIR("../files/may_game/default_bots/strong_bot.py"), } TEST_BOT_PREFIX = "test_from_" OPPONENT_TEST_BOT_PREFIX = "opponent_from_" MAX_BOTS_PER_USER = 10 # Running programs from nadzorca C_RUN_COMMAND = "" CPP_RUN_COMMAND = "" JAVA_RUN_COMMAND = "java " PYTHON_RUN_COMMAND = "python " <file_sep>/documentation/modules/forms.rst forms ====================== .. automodule:: ai_arena.contests.forms :members: <file_sep>/documentation/modules/may_contest_helper_functions.rst may_contest_helper_functions ============================= .. automodule:: ai_arena.contests.may_contest_helper_functions :members: <file_sep>/files/testing/statki/statki_bot.py import sys from itertools import product received = [] def read_int(): global received if received: return received.pop(0) m = sys.stdin.readline() received = map(lambda x: int(x), m.split(' ')) print(received) return received.pop(0) def send_int(a): sys.stdout.write('%d ' % a) sys.stdout.flush() def play_round(): n = read_int() ships_number = read_int() ship_types = [] for i in range(ships_number): stype = read_int() ship_types.append(stype) x = 4 y = 2 for stype in ship_types: send_int(stype) send_int(x) send_int(y) x += 4 if x > n: x = 4 y += 4 all_fields = product(range(1, n+1), range(1, n+1)) for x, y in all_fields: send_int(x) send_int(y) target = read_int() if target < 0: if target == -1: return 1 if target == -2: return -1 if target == -3: return 0 dead = read_int() return 0 def play(): score = 0 while True: score += play_round() play() <file_sep>/files/testing/statki/statki_judge.py import random from itertools import product from collections import defaultdict from sys import stdin, stdout, stderr CLASHES_NUMBER = 50 MAX_ROUNDS_NUMBER = 1000 MAX_SHIP_SIZE = 2 MIN_N = 12 MAX_N = 20 EMPTY = 0 OUT = -1 MISS = 0 WINNER_RESULT = -1 LOSER_RESULT = -2 DRAW_RESULT = -3 DRAW = 3 AVAILABLE_TYPES = range(1, 12) neighbours = [(-1,0), (1,0), (0,-1), (0,1)] ships_types = dict() ship_types_by_size = defaultdict(list) def prepare_ships(): # horizontal lines ships_types[1] = [(-1,0), (0,0)] ships_types[2] = [(-2, 0), (-1,0), (0,0)] ships_types[3] = [(-3, 0), (-2, 0), (-1,0), (0,0)] ships_types[4] = [(-4, 0), (-3, 0), (-2, 0), (-1,0), (0,0)] # vertical lines for i in range(1, 5): ships_types[i + 4] = [(y, x) for x,y in ships_types[i]] # cross ships_types[9] = [(0,0), (-1, 0), (-2, 0), (-1, -1), (-1, 1)] # boat ships_types[10] = [(0,0), (0, -1), (-1, -1), (-2, -1), (-2, 0)] # reversed boat ships_types[11] = [(0,0), (0, -1), (-1, 0), (-2, -1), (-2, 0)] for stype, ship_fields in ships_types.items(): ship_types_by_size[len(ship_fields)].append(stype) class GameException(Exception): pass class Ship: def __init__(self, number, stype, x, y): self.number = number self.stype = stype self.alive = True self.hp = len(ships_types[stype]) self.x = x self.y = y class Board: def __init__(self, n, ships_number): r = range(-MAX_SHIP_SIZE, n + MAX_SHIP_SIZE) self.brd = dict([(pair, OUT) for pair in product(r,r)]) for pair in product(range(1,n+1), range(1,n+1)): self.brd[pair] = EMPTY self.n = n self.ships_number = ships_number self.alive_number = ships_number self.ships = dict() def put(self, x, y, v): if self.brd[(x,y)] != EMPTY: raise GameException("Field (%d,%d) is not empty!" % (x,y)) for xn, yn in neighbours: if self.brd[(x+xn,y+yn)] > 0 and self.brd[(x+xn, y+yn)] != v: raise GameException("Neighbour of field (%d,%d) is ocuppied!" % (x,y)) self.brd[(x,y)] = v def add_ship(self, ship): if ship.number > self.ships_number: raise GameException("Too many ships") self.ships[ship.number] = ship x = ship.x y = ship.y for dx, dy in ships_types[ship.stype]: self.put(x+dx, y+dy, ship.number) def shoot(self, x, y): if (x < 1) or (x > self.n) or (y < 1) or (y > self.n): raise GameException("Shot out of bounds!") if self.brd[(x,y)] > 0: number = self.brd[(x,y)] self.brd[(x,y)] = 0 self.ships[number].hp -= 1 if self.ships[number].hp == 0: self.ships[number].alive = False self.alive_number -= 1 return number, int(not self.ships[number].alive) return MISS, 0 class Game: def __init__(self): self.n = random.choice(range(MIN_N, MAX_N+1)) self.stypes = self.choose_ships() self.boards = [None, Board(self.n, len(self.stypes)), Board(self.n, len(self.stypes))] self.ships_nums = [0, 0, 0] self.players_ships = [[], [], []] def choose_ships(self): stypes = list() for i in range(2, MAX_SHIP_SIZE+1): for j in range(MAX_SHIP_SIZE - i + 1): stypes.append(random.choice(ship_types_by_size[i])) return stypes def place_ship(self, player, stype, x, y): try: if stype not in AVAILABLE_TYPES: raise GameException("Wrong ship type") self.ships_nums[player] += 1 ship = Ship(self.ships_nums[player], stype, x, y) self.players_ships[player].append(ship) self.boards[player].add_ship(ship) if len(self.players_ships[player]) == len(self.stypes): player_ships_types = set([ship.stype for ship in self.players_ships[player]]) if set(self.stypes) != player_ships_types: raise GameException("Wrong set of ships given") except GameException as e: raise GameException(e.args[0], player) def shoot(self, player, x, y): try: number, dead = self.boards[player].shoot(x, y) if dead: self.ships_nums[player] -= 1 if number == MISS: return MISS, dead else: return self.players_ships[player][number-1].stype, dead except GameException as e: raise GameException(e.args[0], player) def game_over(self): if self.ships_nums[1] <= 0: return 2 if self.ships_nums[2] <= 0: return 1 return -1 def opponent(x): return 3 - x ################ Communication ################### received_ints = [[], [], []] ints_to_send = [[], [], []] def to_send(player_number, i): global ints_to_send ints_to_send[player_number].append(i) def send(player_number): global received_ints global ints_to_send mes = "" for index, i in enumerate(ints_to_send[player_number]): mes += str(i) if index + 1 < len(ints_to_send[player_number]): mes += " " ints_to_send[player_number] = [] stdout.write("[" + str(player_number) + "]" + mes + "\n") stdout.flush() response = map(int, raw_input().split()) received_ints[player_number].extend(response) def read(player_number): global received_ints return received_ints[player_number].pop(0) ################ Communication END ################### def send_int(player_number, a, flush=True): to_send(player_number, a) if flush: send(player_number) def send_int_list(player_number, intlist): """ At beggining we should send number of ints to be sent """ to_send(player_number, len(intlist)) for i in intlist: to_send(player_number, i) send(player_number) def read_ship_position(player): """ Returns ship_type, x, y """ ship_type = read(player) x = read(player) y = read(player) return ship_type, x, y #return 0,0,0 def read_shot(player): """ Returns x, y of player's shot """ x = read(player) y = read(player) return x, y #return 0,0 def end_game(scores): """ scores[i] - number of clashes won by i scores[2] - number of draws """ pass def end_error(error_player, error_message): """ error_player did error with error_message """ stderr.write('player %d looses' % error_player) stderr.write(error_message) def send_ships_types(player, stypes): send_int_list(player, stypes) def read_ships_positions(player, game): ships_number = len(game.stypes) for i in range(ships_number): stype, x, y = read_ship_position(player) print(stype, x, y) game.place_ship(player, stype, x, y) def play_one(start_player): global ints_to_send game = Game() for player in [1,2]: send_int(player, game.n, flush=False) send_ships_types(player, game.stypes) read_ships_positions(player, game) n = game.n player = start_player for i in range(MAX_ROUNDS_NUMBER): # player 0 shoots x, y = read_shot(player) stype, dead = game.shoot(opponent(player), x, y) game_res = game.game_over() if game_res != -1: # returns winner return game_res send_int(player, stype, flush=False) send_int(player, dead) player = opponent(player) return DRAW def play(): global received_ints global ints_to_send prepare_ships() try: scores = [0, 0, 0, 0] start_player = 1 for i in range(CLASHES_NUMBER): winner = play_one(start_player) scores[winner] += 1 received_ints = [[], [], []] ints_to_send = [[], [], []] if winner == DRAW: send_int(0, DRAW_RESULT, flush=False) send_int(1, DRAW_RESULT, flush=False) else: send_int(winner, WINNER_RESULT, flush=False) send_int(opponent(winner), LOSER_RESULT, flush=False) start_player = opponent(start_player) end_game(scores) except GameException as e: error_message = e.args[0] error_player = e.args[1] end_error(error_player, error_message) play() <file_sep>/ai_arena/nadzorca/syscall_trace.c #include <sys/reg.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/wait.h> #include <sys/syscall.h> #include <sys/ptrace.h> #include <sys/time.h> #include <errno.h> #if __WORDSIZE == 64 #define bits_num 8 #define syscall_place ORIG_RAX #else #define bits_num 4 #define syscall_place ORIG_EAX #endif #define fsn 22 int main(int argc, char **argv) { int exec_status; int naughty_child; pid_t child; int status, syscall_nr, i; int forbidden_syscalls_number = fsn; int forbidden_syscalls[fsn] = { //multiprocess kernel/process.c 4 __NR_fork, __NR_clone, __NR_vfork, __NR_wait4, //open, directories fs/open.c 10 __NR_creat, __NR_link, __NR_unlink, __NR_chdir, __NR_mknod, __NR_chmod, __NR_lchown, __NR_rmdir, __NR_rename, __NR_chroot, //system misc 9 //__NR_mount, __NR_umount2,__NR_setuid, __NR_ptrace, __NR_sysinfo, __NR_getuid, __NR_setuid, __NR_getppid, __NR_reboot, //__NR_getuid, //pipes 6 __NR_pipe, __NR_pipe2, __NR_dup, __NR_dup2, __NR_dup3, __NR_fcntl, //time 1 __NR_utime, //net 12 //__NR_shutdown, __NR_socket, __NR_socketpair, __NR_bind, __NR_listen, __NR_accept, __NR_connect, __NR_getsockname, __NR_getpeername, __NR_recvfrom, //__NR_sendmsg, __NR_recvmsg, //signals 1 __NR_kill, //limits 1 //__NR_setrlimit, //__NR_getrlimit, }; int max_fsn = -1; for (i=0; i<fsn; ++i) if (forbidden_syscalls[i] > max_fsn) max_fsn = forbidden_syscalls[i]; short illegal_syscall[max_fsn+1]; for (i=0; i<= max_fsn; ++i) illegal_syscall[i] = 0; for (i=0; i<fsn; ++i) illegal_syscall[forbidden_syscalls[i]] = 1; child = fork(); if (child == 0) { /* In child. */ printf("%d\n", getpid()); fflush(stdout); ptrace(PTRACE_TRACEME, 0, NULL, NULL); if (strcmp(argv[2], "PYTHON") == 0) { exec_status = execl("/usr/bin/python2.7", "/usr/bin/python2.7", "-u", argv[1], NULL); } else if (strcmp(argv[2], "C") == 0 || strcmp(argv[2], "CPP") == 0) { exec_status = execl(argv[1], argv[1], NULL); } if (exec_status == -1) fprintf(stderr, "Exec failure %d\n", errno); } else if (child < 0) { printf("%d\n", child); fflush(stdout); exit(EXIT_FAILURE); } else { /* In parent. */ naughty_child = 0; ptrace(PTRACE_SYSCALL, child, NULL, NULL); while (1) { wait(&status); /* Abort loop if child has exited. */ if (WIFEXITED(status) || WIFSIGNALED(status)) break; /* Obtain syscall number from the child's process context. */ syscall_nr = ptrace(PTRACE_PEEKUSER, child, bits_num * syscall_place, NULL); if (illegal_syscall[syscall_nr]) { fprintf(stderr ,"Program tried to use forbiden system call %d. Terminating program.\n", syscall_nr); ptrace(PTRACE_KILL, child, NULL, NULL); } else { ptrace(PTRACE_SYSCALL, child, NULL, NULL); } } exit(EXIT_SUCCESS); } } <file_sep>/ai_arena/contests/game_launcher.py from decimal import Decimal from ai_arena.contests.models import Match, MatchBotResult from ai_arena import settings from ai_arena.nadzorca.exit_status import * import gearman import pickle class PickleDataEncoder(gearman.DataEncoder): @classmethod def encode(cls, encodable_object): return pickle.dumps(encodable_object) @classmethod def decode(cls, decodable_string): return pickle.loads(decodable_string) class PickleClient(gearman.GearmanClient): data_encoder = PickleDataEncoder def launch_single_match(game, bots): """ Launches single match of given game with given list of bots """ match = Match(ranked_match=False, game=game, contest=None, time_limit=game.time_limit, memory_limit=game.memory_limit, status=MATCH_NOT_PLAYED) match.save() bot_results = dict() for bot in bots: bot_result = MatchBotResult(score=0, bot=bot, time_used=0, memory_used=0) bot_result.save() match.players_results.add(bot_result) bot_results[bot] = bot_result arguments = {'game': game, 'bots': bots, 'match': match, 'bot_results': bot_results} gearman_client = PickleClient([settings.GEARMAN_HOST]) gearman_client.submit_job('single_match', arguments, background=True) def launch_contest_match(game, bots, contest): """ Launches contest match of given game with given list of bots and contest """ match = Match(ranked_match=True, game=game, contest=contest, time_limit=contest.time_limit, memory_limit=contest.memory_limit, status=MATCH_NOT_PLAYED) match.save() bot_results = dict() for bot in bots: bot_result = MatchBotResult(score=0, bot=bot, time_used=0, memory_used=0) bot_result.save() match.players_results.add(bot_result) bot_results[bot] = bot_result arguments = {'game': game, 'bots': bots, 'match': match, 'bot_results': bot_results} gearman_client = PickleClient([settings.GEARMAN_HOST]) gearman_client.submit_job('single_match', arguments, background=True) <file_sep>/ai_arena/contests/comment_views.py from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.auth.decorators import login_required from ai_arena.contests.models import Game, GameComment, Contest, ContestComment from ai_arena.contests.forms import AddCommentForm, EditCommentForm from ai_arena.contests.game_views import game_details from ai_arena.contests.contest_views import show_contest @login_required def add_comment(request, comment_type, object_id): """ This view allows adding comments under game description or contest details. It takes following arguments: comment_type is either 'game_details' or 'contests' and it defines type of comment object_id is number of the object to be commented (either game or contest). The view redirects user to a form, where one can fill comment details. After confirming new comment is created and saved in a database. Note that game comments and contest comments are enumerated independently. """ if comment_type not in ['game_details', 'contests']: return HttpResponseRedirect('/') if request.method == 'POST': form = AddCommentForm(request.POST) if form.is_valid(): user = request.user content = request.POST['comment'] if comment_type == 'game_details': game = Game.objects.get(id=object_id) comment = GameComment(user=user, game=game, content=content) comment.save() return HttpResponseRedirect('/game_details/' + object_id + '/') else: contest = Contest.objects.get(id=object_id) comment = ContestComment(user=user, contest=contest, content=content) comment.save() return HttpResponseRedirect('/contests/show_contest/' + object_id + '/') else: form = AddCommentForm() return render_to_response('gaming/add_comment.html', { 'form': form, 'object_id': object_id, 'comment_type': comment_type, }, context_instance=RequestContext(request)) @login_required def del_comment(request, comment_type, object_id, comment_id): """ This view is to delete a comment. It takes 3 arguments apart from request: comment_type - equal either 'game_details' or 'contests' indicates type of comment and object, object_id - describes internal object's (in meaning either game or contest) identification number, and comment_id - points out which comment is to be deleted. The view performs check for the integrity - it assures that: user calling this view has proper previlleges (it particulary checks if user is an author of a comment, staff member or admin), there exists a comment of particular type with given comment_id, the given comment is linked with object (game or contest) with provided object_id. """ if comment_type not in ['game_details', 'contests']: HttpResponseRedirect('/') if comment_type == 'game_details': object = Game.objects.get(id=object_id) comment = GameComment.objects.get(id=comment_id) else: object = Contest.objects.get(id=object_id) comment = ContestComment.objects.get(id=comment_id) user = request.user moderators = object.moderators.all() if not user.is_staff and not user in moderators and user != comment.user: if comment_type == 'game_details': return game_details(request, object_id, error_msg='You cannot delete this comment!') else: return show_contest(request, object_id, error_msg='You cannot delete this comment!') comment.delete() if comment_type == 'game_details': return HttpResponseRedirect('/game_details/' + object_id) else: return HttpResponseRedirect('/contests/show_contest/' + object_id) @login_required def edit_comment(request, comment_type, object_id, comment_id): """ This view is to edit existing comment. It takes 3 arguments apart from request: comment_type - equal either 'game_details' or 'contests' indicates type of comment and object, object_id - describes internal object's (in meaning either game or contest) identification number, and comment_id - points out which comment is to be deleted. The view performs check for the integrity - it assures that: user calling this view has proper previlleges (it particulary checks if user is an author of a comment, staff member or admin), there exists a comment of particular type with given comment_id, the given comment is linked with object (game or contest) with provided object_id. """ if comment_type not in ['game_details', 'contests']: return HttpResponseRedirect('/') if comment_type == 'game_details': object = Game.objects.get(id=object_id) comment = GameComment.objects.get(id=comment_id) else: object = Contest.objects.get(id=object_id) comment = ContestComment.objects.get(id=comment_id) user = request.user moderators = object.moderators.all() if not user.is_staff and not user in moderators and user != comment.user: if comment_type == 'game_details': return game_details(request, object_id, error_msg='You cannot edit this comment!') else: return show_contest(request, object_id, error_msg='You cannot edit this comment!') if request.method == 'POST': comment.content = request.POST['comment'] comment.save() if comment_type == 'game_details': return HttpResponseRedirect('/game_details/' + object_id + '/') else: return HttpResponseRedirect('/contests/show_contest/' + object_id + '/') else: form = EditCommentForm(initial={ 'comment': comment.content, }) return render_to_response('gaming/edit_comment.html', { 'form': form, 'comment_type': comment_type, 'object_id': object_id, 'comment_id': comment_id, }, context_instance=RequestContext(request)) @login_required def quick_comment_edit(request, comment_type, object_id, comment_id, new_content): """ This view is to edit existing comment. Comparing to comment edit view it hides most of options returning other template. User can edit the text of comment, but he is unable to modify e.g. font weight, font collor or other text properties. It takes 3 arguments apart from request: comment_type - equal either 'game_details' or 'contests' indicates type of comment and object, object_id - describes internal object's (in meaning either game or contest) identification number, and comment_id - points out which comment is to be deleted. The view performs check for the integrity - it assures that: user calling this view has proper previlleges (it particulary checks if user is an author of a comment, staff member or admin), there exists a comment of particular type with given comment_id, the given comment is linked with object (game or contest) with provided object_id. """ if not comment_type in ['game_details', 'contests']: return HttpResponseRedirect('/') if comment_type == 'game_details': object = Game.objects.get(id=object_id) comment = GameComments.objects.get(id=comment_id) else: object = Contest.objects.get(id=object_id) comment = ContestComment.objects.get(id=comment_id) user = request.user moderators = object.moderators.all() if not user.is_staff and not user in moderators and user != comment.user: if comment_type == 'game_details': return game_details(request, object_id, error_msg="You cannot edit this comment!") else: return show_contest(request, object_id, error_msg="You cannot edit this comment!") comment.content = new_content; comment.save() if comment_type == 'game_details': return HttpResponseRedirect('/game_details/' + object_id + '/') else: return HttpResponseRedirect('/contests/show_contest/' + object_id + '/') <file_sep>/documentation/modules/game_launcher.rst game_launcher ================================= .. automodule:: ai_arena.contests.game_launcher :members: <file_sep>/ai_arena/nadzorca/testing/pok/run.py import os current_dir = os.path.dirname(os.path.abspath(__file__)) grand_dir = os.path.dirname(os.path.dirname(current_dir)) os.sys.path.insert(0, grand_dir) import nadzorca print 'TEST pok' judge_path = current_dir + "/pok_judge" bot_path = current_dir + "/pok_bot" results = nadzorca.play(judge_file=judge_path, judge_lang='CPP', players=[(bot_path, 'CPP'), (bot_path, 'CPP')], time_limit=100, memory_limit=64) print results passed = True judge_info = '' for item in results['logs']['judge']: judge_info = judge_info + item bot1_info = '' for item in results['logs'][0]: bot1_info = bot1_info + item bot2_info = '' for item in results['logs'][1]: bot2_info = bot2_info + item print "judge info:\n" + judge_info #print "bot1 info:\n" + bot1_info #print "bot2 info:\n" + bot2_info if results['exit_status'] != 0: passed = False print "exit status: " + str(results['exit_status']) + " instead of 0" print "results: " + str(results['results']) if passed: print "PASS" else: print "FAIL" <file_sep>/ai_arena/contests/tests.py from django.test import TestCase from django.test.client import Client from ai_arena.contests.models import * #from StringIO import StringIO #import Image class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.assertEqual(1 + 1, 2) class WebPageTest(TestCase): fixtures = ['test_fixture.json'] def test_main(self): """ Tests displaying of a main page. """ client = Client() response = client.get('/') self.assertContains(response, 'Home', status_code=200) def test_login(self): """ Tests logging into the page. """ self.client.login(username='test_user', password='<PASSWORD>') response = self.client.get('/') self.assertContains(response, 'Logged as <a href="/profile/">test_user</a>.', status_code=200) def test_register(self): """ Tests registering. """ response = self.client.post('/accounts/register/', {'username': 'fred', 'password1': '<PASSWORD>', 'password2': '<PASSWORD>'}, follow=True) self.assertContains(response, 'My profile', status_code=200) self.assertRedirects(response, '/profile/') def test_show_profile(self): """ Tests showing profile. """ self.client.login(username='test_user', password='<PASSWORD>') response = self.client.get('/profile/') self.assertContains(response, 'My profile', status_code=200) def test_show_profile_of_user(self): """ Tests showing profile for specified user. """ self.client.login(username='test_user', password='<PASSWORD>') response = self.client.get('/profile/test_user/') self.assertContains(response, 'My profile', status_code=200) def test_show_contests_of_user(self): """ Tests showing contests of specified user. """ self.client.login(username='test_user', password='<PASSWORD>') response = self.client.get('/profile/test_user/contests/') self.assertContains(response, 'Contests:', status_code=200) self.assertContains(response, 'test_contest', status_code=200) #TODO zrobic bardziej konkretny test dla bazy zawierajacej newsy def test_show_news_of_user(self): """ Tests showing news of specified user. """ self.client.login(username='test_user', password='<PASSWORD>') response = self.client.get('/profile/test_user/news/') self.assertContains(response, 'My profile', status_code=200) def test_edit_profile(self): """ Tests profile edition. """ self.client.login(username='test_user', password='<PASSWORD>') response = self.client.get('/profile_edit/') self.assertContains(response, 'Photo:', status_code=200) photo_file = open('media/profiles/photos/default_avatar.jpg', "rb").read() """ file = StringIO() image = Image.new("RGBA", size=(50,50), color=(256,0,0)) image.save(file, 'png') file.name = 'test.png' file.seek(0) """ post_data = { 'city': 'Africa', 'country': 'Poland', 'interests': None, 'about': None, 'university': None, 'photo': photo_file } response = self.client.post('/profile_edit/', post_data, follow=True) photo_file.close() self.assertContains(response, 'Country:', status_code=200) self.assertContains(response, 'Africa', status_code=200) self.assertContains(response, 'News:', status_code=200) def test_create_game(self): """ Tests creating new Game. """ self.client.login(username='test_user', password='<PASSWORD>') rules_file = open('../files/testing/kk/kk_desc.txt') judge_file = open('../files/testing/kk/kk_judge.cpp') post_data = { 'game_name': 'new_game', 'game_rules': rules_file, 'game_judge': judge_file, 'judge_language': 'CPP' } response = self.client.post('/new_game/', post_data, follow=True) rules_file.close() judge_file.close() self.assertContains(response, 'new_game', status_code=200) self.assertContains(response, 'gra w kolko i krzyzyk', status_code=200) self.assertContains(response, 'Delete this game', status_code=200) def test_game_list(self): """ Tests displaying of Game List page. """ client = Client() response = client.get('/game_list/') self.assertContains(response, 'test_game', status_code=200) def test_game_details(self): """ Tests displaying of Game details page. """ response = self.client.get('/game_details/13/') self.assertContains(response, 'test_game_kk', status_code=200) def test_game_source(self): """ Tests displaying of Game source. """ response = self.client.get('/game_details/13/source/') self.assertContains(response, '#include', status_code=200) def test_game_edit(self): """ Tests displaying of Game edition page. """ self.client.login(username='test_user', password='<PASSWORD>') response = self.client.get('/game_details/14/edit/') self.assertContains(response, 'KOMUNIKACJA Z SEDZIA', status_code=200) #TODO test_delete_game def test_add_comment(self): """ Tests adding comments to Game. """ self.client.login(username='test_user', password='<PASSWORD>') response = self.client.post('/game_details/add_comment/13/', {'comment': 'test_comment'}, follow=True) self.assertContains(response, 'test_comment', status_code=200) self.assertContains(response, 'test_game_kk', status_code=200) self.assertContains(response, 'test_user', status_code=200) def test_delete_comment(self): """ Tests deleting comments to Game. """ self.client.login(username='test_user', password='<PASSWORD>') response = self.client.post('/game_details/add_comment/13/', {'comment': 'test_comment'}, follow=True) response = self.client.post('/game_details/del_comment/13/1/', follow=True) self.assertNotContains(response, 'test_comment', status_code=200) def test_edit_comment(self): """ Tests editing comments to Game. """ self.client.login(username='test_user', password='<PASSWORD>') response = self.client.post('/game_details/add_comment/13/', {'comment': 'test_comment'}, follow=True) response = self.client.post('/game_details/edit_comment/13/1/', {'comment': 'edited_test_comment'}, follow=True) self.assertContains(response, 'edited_test_comment', status_code=200) self.assertContains(response, 'test_game_kk', status_code=200) self.assertContains(response, 'test_user', status_code=200) def test_send_bot(self): """ Tests sending bot. """ self.client.login(username='test_user', password='<PASSWORD>') bot_file = open('../files/testing/kk/kk_bot.cpp') post_data = { 'game': '13', 'bot_name': 'test_bot', 'bot_source': bot_file, 'bot_language': 'CPP' } response = self.client.post('/send_bot/', post_data, follow=True) bot_file.close() self.assertContains(response, 'this is index content block', status_code=200) def test_send_game_bot(self): """ Tests sending bot for specified game. """ self.client.login(username='test_user', password='<PASSWORD>') bot_file = open('../files/testing/kk/kk_bot.cpp') post_data = { 'bot_name': 'test_bot', 'bot_source': bot_file, 'bot_language': 'CPP' } response = self.client.post('/send_bot/13/', post_data, follow=True) bot_file.close() self.assertContains(response, 'this is index content block', status_code=200) def test_match_results_list(self): """ Tests displaying of Match Results List page. """ client = Client() response = client.get('/results/match_results_list/') self.assertContains(response, 'Match Results', status_code=200) self.assertContains(response, 'test_game_kk', status_code=200) def test_match_result(self): """ Tests displaying of particular Match Result. """ response = self.client.get('/results/show_match_result/50/') self.assertContains(response, 'Match log:', status_code=200) self.assertContains(response, 'dummy', status_code=200) self.assertContains(response, 'test_game_kk', status_code=200) #TODO czy testowac odpalanie meczu? def test_launch_match(self): """ Tests displaying of Launch Match page. """ client = Client() response = client.get('/launch_match/') self.assertContains(response, 'Game field', status_code=200) def test_contests_list(self): """ Tests displaying Contests List. """ response = self.client.get('/contests/contests_list/') self.assertContains(response, 'Contest name', status_code=200) self.assertContains(response, 'test_contest', status_code=200) self.assertContains(response, 'test_game_kk', status_code=200) def test_show_contest(self): """ Tests displaying Contests details. """ response = self.client.get('/contests/show_contest/3/') self.assertContains(response, 'Owner', status_code=200) self.assertContains(response, 'test_contest', status_code=200) self.assertContains(response, 'test_bot_kk1', status_code=200) def test_add_contestant(self): """ Tests displaying Add Contestant page. """ response = self.client.get('/contests/add_contestant/3/') self.assertContains(response, 'Bot field', status_code=200) def test_new_game(self): """ Tests displaying of Create New Game page. """ client = Client() response = client.get('/new_game/') # should redirect to login page self.assertRedirects(response, '/accounts/login/?next=/new_game/') client.login(username='test_user', password='<PASSWORD>') response = client.get('/new_game/', follow=True) self.assertContains(response, 'Game name', status_code=200) def test_send_bot_page(self): """ Tests displaying of Send Bot page. """ client = Client() response = client.get('/send_bot/') # should redirect to login page self.assertRedirects(response, '/accounts/login/?next=/send_bot/') client.login(username='test_user', password='<PASSWORD>') response = client.get('/send_bot/', follow=True) self.assertContains(response, 'Bot name', status_code=200) class ModelsTest(TestCase): def test_game_path(self): """ Tests path method of Game model. """ b = Bot(name='bot') print b <file_sep>/ai_arena/nadzorca/nadzorca.py #!/usr/bin/python # Filename: nadzorca.py import subprocess import os import tempfile import sys import threading import Queue import time import select import threading import resource import exit_status import multiprocessing as mp import signal current_dir = os.path.dirname(os.path.abspath(__file__)) grand_dir = os.path.dirname(current_dir) os.sys.path.insert(0, current_dir) def read_logs(judge_process, bots_process_list, log_map, run_thread): """ Function that runs in a separate thread It polls stderrs of judge and bots, reads them and remembers the outputs in a map that is shared with the main thread (log_map argument) Later stderrs are returned as a form of logs """ pipes = [judge_process.stderr] stderr_to_proc_num = {} stderr_to_proc_num[judge_process.stderr] = 'judge' logs = {} logs[judge_process.stderr] = [] for i in range(len(bots_process_list)): pipes.append(bots_process_list[i].stderr) stderr_to_proc_num[bots_process_list[i].stderr] = i logs[bots_process_list[i].stderr] = [] while (run_thread['val']): (rlist, wlist, xlist) = select.select(pipes, [], [], 1) for pipe in rlist: readp = read_whole_pipe(pipe) if readp != '': log(logs[pipe], readp) (rlist, wlist, xlist) = select.select(pipes, [], [], 1) for pipe in rlist: readp = read_whole_pipe(pipe) if readp != '': log(logs[pipe], readp) for pipe in logs.keys(): log_map[stderr_to_proc_num[pipe]] = logs[pipe] def read_whole_pipe(pipe): """ Reads the pipe untill it's empty Used for reading stderrs """ res = '' while True: (rl, wl, xl) = select.select([pipe],[],[], 0) if rl != []: read_letter = pipe.read(1) if read_letter != '': res += read_letter else: break else: break return res # Exception thrown when timeout while waiting for output is reached class TimeoutException(Exception): pass # Exception thrown when EOF is found before proper end of message ('<<<\n') class EOFException(Exception): pass def parse_message(to_send): """ This function parses a message from judge returning list of players as a first of pair and an actual message as a second of pair Every message coming here must contain a list of players in brackets like these: '[' and ']'. It can contain multiple of any of them, in this case the first pair is treated as a list of players. """ l = to_send.split(']') players = map(lambda x:int(x), l[0][1:].split(',')) mes = '' for k in l[1:]: mes = mes + k + ']' return (players,mes[:-1]) def readout(pipe, timeout): """ This function reads communicates. The assumption is that every communicate ends with char '\\n' In addition every '\\n' is considered to be end of a communicate """ mes = '' while mes[len(mes)-1:] != '\n': (rl, wl, xl) = select.select([pipe], [], [], timeout) if (rl != []): letter = pipe.read(1) if (letter == ''): raise EOFException() else: mes = mes + letter else: raise TimeoutException() return mes[:-1] def log(log_list, log_message): """ A convenience function for readability purposes """ log_list.append(log_message) def set_limits(time_limit, memory_limit): """ A function that is run in forked processes before exec (see subprocess.Popen constructor preexec_fn argument) Previously used for setting limits of time and memory consumption for the process. Currently not in use. """ mem_limit = memory_limit * 1024 * 1024 resource.setrlimit(resource.RLIMIT_CPU, (time_limit + 1, time_limit + 1)) resource.setrlimit(resource.RLIMIT_AS, (mem_limit* 2, mem_limit*2)) def get_stats(pid): """ Reads informaton about time and memory consumption of the process with given pid from the proc folder. """ try: proc_stats = open('/proc/{0}/stat'.format(str(pid))) line = proc_stats.readline().split() return (float(line[13]) + float(line[14]), int(line[22])) except: return (None, None) def limiter(pids_list, stop_indicator, proc_info, max_time, max_memory, time_limit, memory_limit): """ Function executed in separate process, that measures memory and time consumption of processes with pids in pids_list. Reads information from proc folder about all relevant processes, every 0.1 seconds. """ sc_clk_tck_id = os.sysconf_names['SC_CLK_TCK'] ticks_per_second = os.sysconf(sc_clk_tck_id) mem_lmt = memory_limit * 1024 * 1024 time_lmt = time_limit * ticks_per_second while(True): judge_pid = pids_list[0] if os.path.exists("/proc/{0}/stat".format(judge_pid)): time_elapsed, memory = get_stats(judge_pid) if time_elapsed > 10*time_lmt: judge_proc.kill() proc_info[0] = exit_status.BOT_TLE elif memory > 10*mem_lmt: judge_proc.kill() proc_info[0] = exit_status.BOT_MLE max_memory[0] = max(max_memory[0], memory) for pid_num in range(1,len(pids_list)): bot_pid = pids_list[pid_num] if os.path.exists("/proc/{0}/stat".format(bot_pid)): time_elapsed, memory = get_stats(bot_pid) if time_elapsed > time_lmt: os.kill(bot_pid, signal.SIGKILL) proc_info[pid_num] = exit_status.BOT_TLE elif memory > mem_lmt: os.kill(bot_pid, signal.SIGKILL) proc_info[pid_num] = exit_status.BOT_MLE max_memory[pid_num] = max(max_memory[pid_num], memory) max_time[pid_num] = max(max_time[pid_num], float(time_elapsed)/ticks_per_second) time.sleep(0.1) if stop_indicator[0]: break; C_LANGUAGE = 'C' CPP_LANGUAGE = 'CPP' JAVA_LANGUAGE = 'JAVA' PYTHON_LANGUAGE = 'PYTHON' def get_run_command(program_name, program_lang): return [current_dir + "/syscall_trace" , program_name , program_lang] #if program_lang == C_LANGUAGE: # command = C_RUN_COMMAND + program_name #if program_lang == CPP_LANGUAGE: # command = CPP_RUN_COMMAND + program_name #if program_lang == JAVA_LANGUAGE: # command = JAVA_RUN_COMMAND + program_name #if program_lang == PYTHON_LANGUAGE: # command = PYTHON_RUN_COMMAND + program_name return command def play(judge_file, judge_lang, players, time_limit, memory_limit): """ judge_file - file containing judge program\n players - list of bots binaries\n memory_limit (in MB) - maximum memory for one bot\n time_limit (in sec) - maximum time limit for one bot\n """ players_num = len(players) supervisor_log = [] to_execute = get_run_command(judge_file, judge_lang) judge_process = subprocess.Popen( to_execute, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, close_fds = True, #preexec_fn = lambda : set_limits(10*time_limit, 10*memory_limit), ) judge_pid = int(judge_process.stdout.readline()) log(supervisor_log, "Started judge succesfully\n") bots_process_list = [] bots_pids = [] for (bot_program, bot_lang) in players: arg_to_execute = get_run_command(bot_program, bot_lang) bot_process = subprocess.Popen( arg_to_execute, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, close_fds = True, #preexec_fn = lambda : set_limits(time_limit, memory_limit), ) bots_process_list.append(bot_process) bots_pids.append(int(bot_process.stdout.readline())) log(supervisor_log, "Started all bots succesfully\n") log_map = {} run_thread = dict([('val', True)]) log_thread = threading.Thread(None, read_logs, None, (judge_process, bots_process_list, log_map, run_thread), {}) log_thread.start() manager = mp.Manager() pids_list = manager.list() pids_list.append(judge_pid) pids_list.extend(bots_pids) max_memory = manager.list([0.0 for x in range(players_num+1)]) max_time = manager.list([0.0 for x in range(players_num+1)]) stop_indicator = manager.dict([(0, False)]) proc_info = manager.list([exit_status.BOT_OK for x in range(players_num+1)]) limiter_proc = mp.Process(target=limiter, args=(pids_list, stop_indicator, proc_info, max_time, max_memory, time_limit, memory_limit)) limiter_proc.start() bots = [] message = '' results = {'exit_status' : exit_status.SUPERVISOR_OK, 'time' : {}, 'memory' : {}, 'supervisor_log' : supervisor_log, 'bots_exit' : {}, } game_in_progress = True while (game_in_progress): try: judge_mes = readout(judge_process.stdout, time_limit*10) except TimeoutException: results['exit_status'] = exit_status.JUDGE_TIMEOUT os.kill(judge_pid, signal.SIGKILL) log(supervisor_log, "Timeout reached while waiting for judge message.") break except EOFException: results['exit_status'] = exit_status.JUDGE_EOF try: os.kill(judge_pid, signal.SIGKILL) except: pass log(supervisor_log, "EOF reached while reading message from judge.") break try: (bots, message) = parse_message(judge_mes) except: results['exit_status'] = exit_status.JUDGE_WRONG_MESSAGE log(supervisor_log, "Wrong message format from judge.") os.kill(judge_pid, signal.SIGKILL) break if bots == [0]: bots = range(1,players_num + 1) if message == 'END': try: res = readout(judge_process.stdout, time_limit * 10) except TimeoutException: results['exit_status'] = exit_status.JUDGE_SCORES_TIMEOUT log(supervisor_log, "Timeout reached while waiting for scores from judge.") break except EOFException: results['exit_status'] = exit_status.JUDGE_SCORES_EOF log(supervisor_log, "EOF reached while waiting for scores from judge.") break try: (scores, empty_mes) = parse_message(res) results['results'] = dict(enumerate(scores)) except: results['exit_status'] = exit_status.JUDGE_WRONG_SCORES log(supervisor_log, "Wrong scores message from judge.") break elif message == 'KILL': for bnum in bots: if bnum > 0 and bnum <= players_num: try: os.kill(bots_pids[bnum-1], signal.SIGKILL) #bots_process_list[bnum-1].kill() proc_info[bnum] = exit_status.BOT_KILLED except: pass else: results['exit_status'] = exit_status.NOT_EXISTING_KILL log(supervisor_log, "Tried to kill an unexsisting bot.") game_in_progress = False break else: for bnum in bots: if bnum > 0 and bnum <= players_num: bot_process = bots_process_list[bnum-1] message = message + '\n' try: bot_process.stdin.write(message) response = readout(bot_process.stdout, time_limit) + '\n' except TimeoutException: response = '_DEAD_\n' try: os.kill(bot_pids[bnum-1], signal.SIGKILL) except: pass except EOFException: response = '_DEAD_\n' try: os.kill(bot_pids[bnum-1], signal.SIGKILL) except: pass except: response = '_DEAD_\n' finally: try: judge_process.stdin.write(response) except: results['exit_status'] = exit_status.JUDGE_WRITE log(supervisor_log, "Failed to send message to judge") break else: results['exit_status'] = exit_status.NOT_EXISTING_MESSAGE log(supervisor_log, "Tried to send a message to an unexsiting bot.") game_in_progress = False break # Stop the log thred run_thread['val'] = False # Kill all the processes try: os.kill(judge_pid, signal.SIGKILL) judge_process.kill() except: pass for bot_num in range(len(bots_pids)): try: os.kill(bots_pids[bot_num], signal.SIGKILL) except Exception as inst: pass log_thread.join() # Stop the limiter stop_indicator[0] = True limiter_proc.join() final_times = {} final_memory = {} for i in range(len(bots_process_list)): bot_process = bots_process_list[i] #wait_info = os.wait4(bot_process.pid, 0) final_times[i] = float(max_time[i+1]) final_memory[i] = float(max_memory[i+1])/(1024*1024) results['bots_exit'][i] = proc_info[i+1] #judge_wait_info = os.wait4(judge_process.pid, 0) final_times['judge'] = float(max_time[0]) final_memory['judge'] = float(max_memory[0])/(1024*1024) results['judge_exit'] = proc_info[0] results['time'] = final_times results['memory'] = final_memory results['logs'] = log_map results['supervisor_log'] = supervisor_log return results <file_sep>/files/Makefile all: python -mcompileall . clean: rm *.pyc *.py~ <file_sep>/ai_arena/templates/registration/register.html {% extends 'base.html' %} {% block title %} Register {% endblock %} {% block content %} {% if error_message %} <p><strong> {{ error_message }} </strong></p> {% endif %} <form action="/register_user/" method="POST"> {%csrf_token %} <div> Username: <input type="text" name="username" size="15" /> </div> <!-- <div> e-mail: <input type="text" name="email" size="15" /> </div> --> <div> Password: <input type="<PASSWORD>" name="password" size="15" /> </div> <div> Retype password: <input type="<PASSWORD>" name="<PASSWORD>" size="15" /> </div> <div><input type="submit" value="Send" /> </div> </form> {% endblock %} <file_sep>/documentation/modules/views.rst views ====================== .. automodule:: ai_arena.contests.views :members: <file_sep>/files/testing/paper_soccer/paper_soccer_judge.py #!/usr/bin/env python import sys import copy def log(mes): sys.stderr.write(mes) sys.stderr.flush() def send(mes): sys.stdout.write(mes) sys.stdout.flush() def recv_mes(): try: m = sys.stdin.readline() if (m == "OK\n"): return m mr = map(lambda x: int(x), m[1:-2].split(',')) return mr except: return [] LEN = 11 WID = 9 visited = set() unused_edges = set() current = (0,0) def init(): global visited global unused_edges global current visited = set((4,5)) visited.update([(a,b) for a in [0,8] for b in range(0,11)]) visited.update([(a,b) for a in range(1,8) for b in [0,10]]) visited.remove((4,0)) visited.remove((4,10)) current = (4,5) unused_edges = set([(a,b,c) for a in range(1,8) for b in range(1,10) for c in range(0,8)]) unused_edges.update(set([(0,b,c) for b in range(1,10) for c in [1,2,3]])) unused_edges.update(set([(8,b,c) for b in range(1,10) for c in [5,6,7]])) unused_edges.update(set([(a,0,c) for a in range(1,8) for c in [7,0,1]])) unused_edges.update(set([(a,10,c) for a in range(1,8) for c in [3,4,5]])) unused_edges.add((0,0,1)) unused_edges.add((8,0,7)) unused_edges.add((0,10,3)) unused_edges.add((8,10,5)) unused_edges.add((3,0,3)) unused_edges.update([(4,0,c) for c in [3,4,5]]) unused_edges.add((5,0,5)) unused_edges.add((3,10,1)) unused_edges.update([(4,10,c) for c in [7,0,1]]) unused_edges.add((5,10,7)) unused_edges.update([(4,11,a) for a in [3,4,5]]) unused_edges.add((3,11,3)) unused_edges.add((5,11,5)) unused_edges.update([(4,-1,a) for a in [7,0,1]]) unused_edges.add((3,-1,1)) unused_edges.add((5,-1,7)) def main(): global visited global unused_edges global current points_1 = 0; points_2 = 0; for game_num in range(4): log("INIT") init() bad_1 = False bad_2 = False send("[1,2]INIT\n") ok = recv_mes() if (ok != "OK\n"): bad_1 = True #log("Not OK 1\n") else: pass #log("OK 1\n") ok = recv_mes() if (ok != "OK\n"): bad_2 = True #log("Not OK 2\n") else: pass #log("OK 2\n") if (bad_1 and bad_2): continue elif (bad_1): points_2 += 1 continue elif (bad_2): points_1 += 1 continue send("[{0}]UP\n".format(1 + (game_num % 2))) ok = recv_mes() if (ok != "OK\n"): points_1 += (game_num % 2) points_2 += 1 - (game_num % 2) continue send("[{0}]DOWN\n".format(2 - (game_num % 2))) ok = recv_mes() if (ok != "OK\n"): points_1 += 1 - (game_num % 2) points_2 += (game_num % 2) moving = 1 + (game_num % 2) send("[{0}]MOVE []\n".format(moving)) while(True): move = recv_mes() move_copy = copy.deepcopy(move) log("{0}\n".format(len(move))) end_game = True bad_move = True who_won = 0 while (move != []): n = move[0] del move[0] if ((current[0], current[1], n) in unused_edges): unused_edges.remove((current[0], current[1], n)) newx = current[0] newy = current[1] if (n in [7,0,1]): newy += 1 if (n in [1,2,3]): newx += 1 if (n in [3,4,5]): newy -= 1 if (n in [5,6,7]): newx -= 1 current = (newx, newy) unused_edges.remove((current[0], current[1], ((n+4)%8))) else: log("Tried to use used edge {0} , {1}\n".format(current, n)) log break if (current in set([(a,b) for a in [3,4,5] for b in [-1,11]])): log("Goal!\n") bad_move = False break if (current in visited) and (move == []): log("Shouldn't stop\n") break elif (current not in visited) and (move != []): log("Should have stopped\n") break elif (current in visited) and (move != []): continue elif (current not in visited) and (move == []): visited.add(current) end_game = False bad_move = False break if (end_game): log("End game\n") if (bad_move): log("Bad move\n") points_1 += (moving-1) points_2 += (2-moving) else: log("Goal!\n") s = int((current == (4,0)) ^ ((game_num % 2) == 0)) points_1 += s points_2 += (1 - s) break else: moving = 3 - moving send("[{0}]MOVE {1}\n".format(moving, move_copy)) #log("Sent [{0}]MOVE {1}\n".format(moving, move_copy)) #log("{0}".format(current)) send("[0]END\n") send("[{0}, {1}]\n".format(points_1, points_2)) main() <file_sep>/ai_arena/nadzorca/testing/parse_messages/parse_messages_bot.cpp #include <iostream> #include <time.h> using namespace std; int main(){ int move = 1; while(move < 1000000000){ cerr << move; cout << move << " <<<\n"; move++; } return 0; } <file_sep>/ai_arena/gearman_worker_lib.py import gearman import pickle from nadzorca import nadzorca from nadzorca.exit_status import * from decimal import Decimal from django.conf import settings from ai_arena.contests.models import Match, MatchBotResult def single_match(gearman_worker, gearman_job): """ Gearman worker main function.\n It's responsible for getting argunemts from Gearman server, parsing them and finally calling Nadzorca's play function (which performs Match between given Bots).\n Then it stores results in match object (received from Gearman server) and saves changes to database. """ print "lets play single match\n" arguments = gearman_job.data game = arguments['game'] match = arguments['match'] bots = arguments['bots'] bot_results = arguments['bot_results'] memory_limit = match.memory_limit # convert miliseconds to seconds time_limit = match.time_limit / 1000.0 judge_program = game.judge_bin_file.path judge_lang = game.judge_lang bots_programs = [(bot.bot_bin_file.path, bot.bot_lang) for bot in bots] results = nadzorca.play(judge_file=judge_program, judge_lang=judge_lang, players=bots_programs, memory_limit=memory_limit, time_limit=time_limit) scores = results['results'] time_used = results['time'] memory_used = results['memory'] bots_exit = results['bots_exit'] bot_logs = results['logs'] if len(scores) < len(bots) or len(time_used) < len(bots) + 1: return log = ''.join(results['supervisor_log']) print(results) match.status = results['exit_status'] for (i, bot) in enumerate(bots): bot_result = bot_results[bot] bot_result.score = scores[i] # convert from seconds to miliseconds bot_result.time_used = int(1000.0 * time_used[i]) bot_result.memory_used = memory_used[i] bot_result.status = bots_exit[i] if (bot_result.status != BOT_OK) & (match.status == SUPERVISOR_OK): match.status = MATCH_WALKOVER bot_result.logs = ''.join(bot_logs[i]) bot_result.save() match.log = log match.save() <file_sep>/ai_arena/nadzorca/testing/memory_limit/memory_limit_bot.cpp #include <iostream> #include <time.h> #include <stdlib.h> using namespace std; int main(){ int move = 1; string message; while(move < 10){ if(move == 3){ char array[8000000]; //void * p = malloc(800000000000); } cin >> message; cerr << move; cout << move << " <<<\n"; move++; } return 0; } <file_sep>/documentation/modules/contest_views.rst contest_views ================================= .. automodule:: ai_arena.contests.contest_views :members: <file_sep>/ai_arena/contests/admin.py from contests.models import * from django.contrib import admin admin.site.register(Game) admin.site.register(Bot) admin.site.register(Contest) admin.site.register(MatchBotResult) admin.site.register(Match) admin.site.register(UserProfile) admin.site.register(UserNews) admin.site.register(GameComment) admin.site.register(ContestComment) admin.site.register(Ranking) admin.site.register(BotRanking) <file_sep>/ai_arena/contests/compilation.py from os import system from ai_arena import settings def compile(src, target, lang, log_target=None): """ Executes makefile with params LANG, SRC and TARGET. It takes 3 arguments: lang is one of the following: 'C', 'CPP', 'JAVA', 'PYTHON' - and indicates language of a source code to compile. src points a location of source code on a hard drive. target is a location where compiled program should be placed to. The command also creates a log file capturing all logs output'd to command line and stores it to file named <target>.log in the same directory as source file. """ command = 'make -f ' + settings.MAKEFILE_PATH + ' LANG=' + lang + ' SRC=' + src + ' TARGET=' + target if log_target: command += ' 2> ' + log_target return system(command) <file_sep>/ai_arena/utils.py import datetime def get_current_date_time(): """ Returns current date and time in formated way (YYYY-MM-DD HH:MM). """ now = datetime.datetime.now() tt = datetime.datetime.timetuple(now) return "%d-%d-%d %d:%d" % (tt.tm_year, tt.tm_mon, tt.tm_mday, tt.tm_hour, tt.tm_min) def parse_logs(logs): """ Helper function to prepare logs to display. If we would pass logs simply without parsing they would be unreadable, e.g. new line chars would be ignored """ return logs.split('\n') <file_sep>/documentation/modules/model.rst models ================================= .. automodule:: ai_arena.contests.models :members: <file_sep>/ai_arena/nadzorca/Makefile syscall_trace : syscall_trace.c gcc syscall_trace.c -o syscall_trace <file_sep>/ai_arena/nadzorca/exit_status.py #!/usr/bin/env python # Supervisor SUPERVISOR_OK = 10 JUDGE_TIMEOUT = 14 JUDGE_EOF = 15 JUDGE_WRONG_MESSAGE = 11 JUDGE_SCORES_TIMEOUT = 16 JUDGE_SCORES_EOF = 17 JUDGE_WRONG_SCORES = 12 NOT_EXISTING_KILL = 18 NOT_EXISTING_MESSAGE = 13 JUDGE_WRITE = 104 # Bots BOT_OK = 0 BOT_TLE = 1 # Time limit exceeded BOT_MLE = 2 # Memory limit exceeded BOT_KILLED = 3 # Bot killed by judge # Match statuses MATCH_NOT_PLAYED = 1 MATCH_WALKOVER = 2 #MATCH_PLAYED = 2 <file_sep>/ai_arena/contests/match_views.py from django.shortcuts import render_to_response, redirect from django.template import RequestContext from ai_arena.contests.forms import GameSelectForm, BotsSelectForm from django.contrib.auth.decorators import login_required from ai_arena.contests.models import Game, Match from ai_arena.contests.game_launcher import launch_single_match def match_results_list(request): """ Displays list of recent matches """ matches = Match.objects.all() return render_to_response('results/match_results_list.html', { 'matches':matches, }, context_instance=RequestContext(request), ) def show_match_result(request, match_id): """ Displays page with results of the given match. Shows logs from the match. """ if not match_id: raise Exception("In show_match_result: Noe match_id given") match = Match.objects.get(id=match_id) players_results = sorted( [player_result for player_result in match.players_results.all()], key=lambda x: -x.score) return render_to_response('results/match_result.html', { 'match':match, 'game':match.game, 'players_results':players_results, }, context_instance=RequestContext(request), ) @login_required def match_details(request, match_id): """ Displays details of a Match object with given match_id. """ match = Match.objects.get(id=match_id) return render_to_response('results/match_details.html', { 'match': match, 'user': request.user, }, context_instance=RequestContext(request)) def launch_match(request, game_id=None, number_of_bots=None): """ Launches match for the selected game, with selected bots. """ if not game_id: game = None else: game = Game.objects.get(id=game_id) if number_of_bots: number_of_bots = int(number_of_bots) bot_form = None game_form = None bot = None if request.method == 'POST': # handle game selection form if 'game_form' in request.POST: game_form = GameSelectForm(request.POST, prefix='game') if game_form.is_valid(): game = game_form.cleaned_data['game_field'] number_of_bots=int(game_form.cleaned_data['number_of_bots']) bot_form = BotsSelectForm(game=game, number_of_bots=number_of_bots, prefix='bot') # handle bot selection form if 'bot_form' in request.POST: bot_form = BotsSelectForm(request.POST, game=game, number_of_bots=number_of_bots, prefix='bot') if bot_form.is_valid(): bots = [] for i in range(number_of_bots): bots.append(bot_form.cleaned_data['bot_field%d' % (i+1)]) launch_single_match(game, bots) return redirect('/') if not game_form: game_form = GameSelectForm(prefix='game') if game and not bot_form: bot_form = BotsSelectForm(game=game, number_of_bots=number_of_bots, prefix='bot') if game: game_id = game.id return render_to_response('gaming/launch_match.html', { 'game_form':game_form, 'bot_form':bot_form, 'game_id':game_id, 'number_of_bots':number_of_bots, }, context_instance=RequestContext(request) ) <file_sep>/ai_arena/nadzorca/testing/pok2/py_pok_bot.py from sys import stdin, stdout, stderr def firstBet(card): bet = 10 if card > 1: bet = 100 if card == 4: bet = 200 return bet def secondBet(my1bet, op1bet, card): if card == 4: return 200 if card > 1: return 100 if op1bet > my1bet: return 10 return 50 def decision(myBet, opBet, card): if card < 2: return 0 if (card == 2) and (2*myBet > opBet): return 1 if card > 2: return 1 return 0 receivedInts = [] def takeInt(): global receivedInts if len(receivedInts) == 0: receivedInts = map(int, raw_input().split()) return receivedInts.pop(0) while True: card = takeInt() stderr.write("CARD " + str(card) + "\n") my1bet = firstBet(card) stdout.write("" + str(my1bet) + "\n") stdout.flush() op1bet = takeInt() stderr.write("op1bet " + str(op1bet) + "\n") if op1bet > my1bet: decision1 = decision(my1bet, op1bet, card) stderr.write("making decision " + str(decision1) + "\n") if decision1 == 0: stdout.write(str(decision1) + "\n") stdout.flush() continue if my1bet > op1bet: decision1 = takeInt() stderr.write("op made decision " + str(decision1) + "\n") if decision1 == 0: continue if my1bet == op1bet: stderr.write("equal 1bet\n") # Second bet stderr.write("Second round \n") my2bet = secondBet(my1bet, op1bet, card) stdout.write(str(my2bet) + "\n") stdout.flush() op2bet = takeInt() stderr.write("op2bet " + str(op2bet) + "\n") if op2bet > my2bet: decision2 = decision(my1bet+my2bet, op1bet + op2bet, card) stderr.write("making decision " + str(decision2) + "\n") stdout.write(str(decision2) + "\n") stdout.flush() if decision2 == 0: continue if my2bet > op2bet: decision2 = takeInt() stderr.write("op made decision " + str(decision2) + "\n") if decision2 == 0: continue if my2bet == op2bet: stderr.write("equal 2bet\n") opCard = takeInt() <file_sep>/ai_arena/nadzorca/testing/bot_logs/Makefile all: bot_logs_judge bot_logs_bot timeout_judge: bot_logs_judge.cpp g++ bot_logs_judge.cpp -O0 -o bot_logs_judge timeout_bot: bot_logs_bot.cpp g++ bot_logs_bot.cpp -O0 -o bot_logs_bot clean: rm bot_logs_judge bot_logs_bot <file_sep>/ai_arena/contests/models.py from os import system from django.db import models from django.contrib.auth.models import User from itertools import combinations from decimal import Decimal from ai_arena import settings from ai_arena.nadzorca.exit_status import * from utils import parse_logs class Game(models.Model): """ Game consists of Judge and Rules. It may be used in different Contests. """ def __unicode__(self): return self.name # method generating path for uploaded files path = lambda dirname: lambda instance, filename: \ '/'.join([dirname, instance.name, filename]) name = models.CharField(max_length=settings.NAME_LENGTH) min_players = models.IntegerField(default=settings.GAME_MIN_PLAYERS_DEFAULT) max_players = models.IntegerField() # in MB memory_limit = models.IntegerField(default=settings.DEFAULT_GAME_MEMORY_LIMIT) # in Miliseconds time_limit = models.IntegerField(default=settings.DEFAULT_GAME_TIME_LIMIT) # File with rules of the Game rules_file = models.FileField(upload_to=path(settings.RULES_DIR)) # Executable with judge judge_bin_file = models.FileField(upload_to=path(settings.JUDGES_BINARIES_DIR)) judge_source_file = models.FileField(upload_to=path(settings.JUDGES_SOURCES_DIR)) judge_lang = models.CharField(max_length=settings.LANG_LENGTH, choices=settings.LANGUAGES) moderators = models.ManyToManyField(User, related_name='game_moderators', null=True, blank=True) def compile_judge(self): """ Compile source file to directory with source file """ from ai_arena.contests.compilation import compile from django.core.files import File src = settings.MEDIA_ROOT + self.judge_source_file.name log_target = settings.COMPILATION_TEMP_PATH + self.name + '.log' target = settings.COMPILATION_TEMP_PATH + self.name + '.bin' lang = self.judge_lang exit_status = compile(src, target, lang, log_target) if exit_status != 0: log_file = open(log_target, 'r') logs = parse_logs(log_file.read()) return (exit_status, logs) else: # Use compiled file in object bot self.judge_bin_file.save(self.name, File(open(target))) # Save changes made to bot object self.save() # Remove compiled file from directory with source system('rm ' + target) return (exit_status, "") class Bot(models.Model): """ Stores info about single Bot. Bot is owned by User and connected with Game. Bot has its own BotContestRanking where the info about Bot's matches is accumulated. """ def __unicode__(self): return self.name # method generating path for uploaded files path = lambda dirname: lambda instance, filename: \ '/'.join([dirname, instance.game.name, instance.owner.username, instance.name, filename]) name = models.CharField(max_length=settings.NAME_LENGTH) owner = models.ForeignKey(User) game = models.ForeignKey(Game) # Executable with Bot program bot_bin_file = models.FileField(upload_to=path(settings.BOTS_BINARIES_DIR)) bot_source_file = models.FileField(upload_to=path(settings.BOTS_SOURCES_DIR)) bot_lang = models.CharField(max_length=settings.LANG_LENGTH, choices=settings.LANGUAGES) invalid = models.BooleanField(default=False) # whether to include in rankings ranked = models.BooleanField(default=True) def delete_bot_matches(self): for match in Match.objects.filter(game=self.game): if self.id in set([bot_res.bot.id for bot_res in match.players_results.all()]): match.delete() def compile_bot(self): """ Compile source file to directory with source file """ from ai_arena.contests.compilation import compile from django.core.files import File src = settings.MEDIA_ROOT + self.bot_source_file.name log_target = settings.COMPILATION_TEMP_PATH + self.name + '.log' target = settings.COMPILATION_TEMP_PATH + self.name + '.bin' lang = self.bot_lang exit_status = compile(src, target, lang, log_target) if exit_status != 0: log_file = open(log_target, 'r') logs = parse_logs(log_file.read()) return (exit_status, logs) else: # Use compiled file in object bot self.bot_bin_file.save(self.name, File(open(target))) # Save changes made to bot object self.save() # Remove compiled file from directory with source system('rm ' + target) return (exit_status, "") class Ranking(models.Model): """ Ranking can be created for a given contest. There are different types of rankings. Basic type is TYPE_GROUP where every players plays against each other. """ date_updated = models.DateTimeField(null=True, blank=True) TYPE_GROUP = 1 RANKING_TYPES = ( (TYPE_GROUP, 'Type group'), ) type = models.IntegerField(choices=RANKING_TYPES) updated = models.BooleanField(default = False) class BotRanking(models.Model): """ Stores position and overall score of bot in a given ranking """ ranking = models.ForeignKey(Ranking) bot = models.ForeignKey(Bot) overall_score = models.DecimalField(max_digits=settings.SCORE_DIGITS, decimal_places=settings.SCORE_DECIMAL_PLACES, default=Decimal('0.0')) position = models.IntegerField(null=True, blank=True) matches_played = models.IntegerField(null=True, blank=True, default=0) class Contest(models.Model): """ There are Matches played within the Contest and they results sum up to the ContestRanking. """ # method generating path for uploaded files path = lambda dirname: lambda instance, filename: \ '/'.join([dirname, instance.name, filename]) name = models.CharField(max_length=settings.NAME_LENGTH) # Game related to the Contest game = models.ForeignKey(Game) # List of Bots participating in the Contest # in MB memory_limit = models.IntegerField(default=settings.DEFAULT_CONTEST_MEMORY_LIMIT) # in Miliseconds time_limit = models.IntegerField(default=settings.DEFAULT_CONTEST_TIME_LIMIT) contestants = models.ManyToManyField(Bot, related_name="contestants", null=True, blank=True) # Contest regulations regulations_file = models.FileField(upload_to=path(settings.CONTEST_REGULATIONS_DIR)) # Begin and End dates of the contest. Can be null, when # the contest has no deadlines. begin_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) ranking = models.ForeignKey(Ranking, null=True, blank=True, on_delete=models.SET_NULL) moderators = models.ManyToManyField(User, related_name='contest_moderators', null=True, blank=True) def generate_group_ranking(self): """ Method that generates rank list for the contest. It checks whether all matches have been played. If not, it launches the missing ones by gearman. """ from contests.game_launcher import launch_contest_match updated = True # if ranking does not exist yet if not self.ranking: self.ranking = Ranking(type=Ranking.TYPE_GROUP) self.ranking.save() BotRanking.objects.filter(ranking=self.ranking).delete() # how many players required for the match match_size = self.game.min_players matches = Match.objects.filter(ranked_match=True, contest=self, game=self.game) played_matches = matches.exclude(status=MATCH_NOT_PLAYED) matches_set = [sorted(match.players_results.all().values_list('bot__id', flat=True)) for match in matches] contestants = sorted(self.contestants.all(), key=lambda x: x.id) contestants_ranks = dict([(bot, BotRanking(ranking=self.ranking, bot=bot)) for bot in contestants]) # order execution of missing matches matches_to_play = combinations([c.id for c in contestants], match_size) for match in matches_to_play: if list(match) not in matches_set: bots = [Bot.objects.get(id=bot_id) for bot_id in match] launch_contest_match(self.game, bots, self) # Ranking still needs some matches to be played updated = False # collect results from played matches for match in played_matches: for res in match.players_results.all(): rank = contestants_ranks[res.bot] rank.overall_score += res.score rank.matches_played += 1 prev_score = Decimal('-1.0') pos = 0 pos_cnt = 1 for rank in sorted(contestants_ranks.values(), key = lambda x: x.overall_score, reverse=True): if rank.overall_score != prev_score: prev_score = rank.overall_score pos += pos_cnt pos_cnt = 1 else: pos_cnt += 1 rank.position = pos rank.save() self.ranking.updated = updated self.ranking.save() class MatchBotResult(models.Model): """ Stores single result of Bot in the given match. Appart from point score, it keeps info about time and memory usage or some errors during the execution. """ def __unicode__(self): return self.bot.name + ' results' score = models.DecimalField(max_digits=settings.SCORE_DIGITS, decimal_places=settings.SCORE_DECIMAL_PLACES) # in miliseconds time_used = models.IntegerField(null=True, blank=True) # in MB memory_used = models.IntegerField(null=True, blank=True) # status of bot behaviour during match status = models.IntegerField(null=True, blank=True) # logs logs = models.TextField(null=True) bot = models.ForeignKey(Bot) # String representing status def string_status(self): return { BOT_OK: "OK", BOT_TLE: "TIME LIMIT EXCEEDED", BOT_MLE: "MEMORY LIMIT EXCEEDED", BOT_KILLED: "DIDN'T FOLLOW PROTOCOL OR RULES", }.get(self.status, "UNKNOWN") class Match(models.Model): """ Contains info about single Match. """ def __unicode__(self): return self.game.name # Is the match connected with any ranking ranked_match = models.BooleanField() # If match is not ranked, then contest=Null contest = models.ForeignKey(Contest, null=True) # Connected game game = models.ForeignKey(Game) # List of players results players_results = models.ManyToManyField(MatchBotResult, related_name="players_results", null=True, blank=True) match_log = models.TextField() # Max time (in miliseconds) for one player time_limit = models.IntegerField(null=True, blank=True) # Max memory (in MB) for one player memory_limit = models.IntegerField(null=True, blank=True) # Status of the match (described in settings) status = models.IntegerField(null=True, blank=True) # String representing status def string_status(self): return { MATCH_NOT_PLAYED: "NOT PLAYED YET", MATCH_WALKOVER: "WALKOVER", SUPERVISOR_OK: "OK", JUDGE_TIMEOUT: "JUDGETIMEOUT", JUDGE_EOF: "JUDGE EOF", JUDGE_WRONG_MESSAGE: "JUDGE WRONG MESSAGE", JUDGE_SCORES_TIMEOUT: "JUDGE SCORES TIMEOUT", JUDGE_SCORES_EOF: "JUDGE SCORES EOF", JUDGE_WRONG_SCORES: "JUDGE WRONG SCORES", NOT_EXISTING_KILL: "NOT EXISTING KILL", NOT_EXISTING_MESSAGE: "NOT EXISTING MESSAGE", JUDGE_WRITE: "JUDGE WRITE???", #MATCH_PLAYED: "OK, PLAYED", }.get(self.status, "UNKNOWN") class UserProfile(models.Model): # method generating path for uploaded files path = lambda dirname: lambda instance, filename: \ '/'.join([dirname, instance.user.username, filename]) user = models.ForeignKey(User, unique=True) photo = models.ImageField(upload_to=path(settings.PHOTOS_DIR)) about = models.TextField(null=True) country = models.CharField(max_length = settings.NAME_LENGTH, null=True) city = models.CharField(max_length = settings.NAME_LENGTH, null=True) university = models.CharField(max_length = settings.NAME_LENGTH, null=True) birthsday = models.DateField(null=True) last_login = models.DateField(auto_now=True) interests = models.TextField(null=True) def __unicode__(self): return self.user.username class UserNews(models.Model): user = models.ForeignKey(User) date_set = models.DateField(auto_now_add=True) content = models.TextField() def __unicode__(self): return self.content class GameComment(models.Model): user = models.ForeignKey(User) game = models.ForeignKey(Game) date_set = models.DateTimeField(auto_now_add=True) content = models.TextField() def __unicode__(self): return self.content class ContestComment(models.Model): user = models.ForeignKey(User) contest = models.ForeignKey(Contest) date_set = models.DateTimeField(auto_now_add=True) content = models.TextField() def __unicode__(self): return self.content <file_sep>/ai_arena/contests/user_views.py from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.auth.decorators import login_required from ai_arena.contests.models import UserProfile, UserNews, Contest from django.http import HttpResponseRedirect from ai_arena.contests.forms import UpdateUserProfileForm @login_required def show_profile(request, login=None): """ Displays user's profile. If user calls this function for the first time (or user profile doesn't exist of any reason) it also creates new profile with default settings (which can be customized later). """ user_profile = None error_message = None news = None if login is None: user_profile_list = UserProfile.objects.filter(user=request.user) news = UserNews.objects.filter(user=request.user) else: user_profile_list = [] news = [] for up in UserProfile.objects.all(): if up.user.username == login: user_profile_list.append(up) for n in UserNews.objects.all(): if n.user.username == login: news.append(n) if len(user_profile_list) > 0: user_profile = user_profile_list[0] else: if login is None: # create new profile with default values user_profile = getDefaultUserProfile(request.user) else: error_message = 'User ' + login + ' is not registered' return render_to_response('profile/show_profile.html', { 'user_profile':user_profile, 'error_message':error_message, 'news':news }, context_instance=RequestContext(request)) @login_required def show_contests(request, login): """ displays list of contests in which user is participating. """ user_profile_list = [] for up in UserProfile.objects.all(): if up.user.username == login: user_profile_list.append(up) if len(user_profile_list) > 0: user_profile = user_profile_list[0] else: user_profile = None contests = [] for c in Contest.objects.all(): for bot in c.contestants.all(): if login == bot.owner.username: contests.append(c) break return render_to_response('profile/show_contests.html', { 'user_profile':user_profile, 'contests':contests, }, context_instance=RequestContext(request)) @login_required def show_news(request, login): """ Displays a list of news linked with the user. News are created in variety of situations: when creating a new game, sending a bot for a game, editing a profile and so on. """ user_profile_list = [] for up in UserProfile.objects.all(): if up.user.username == login: user_profile_list.append(up) if len(user_profile_list) > 0: user_profile = user_profile_list[0] else: user_profile = None news = [] for n in UserNews.objects.all(): if n.user.username == login: news.append(n) return render_to_response('profile/show_news.html', { 'user_profile':user_profile, 'news':news, }, context_instance=RequestContext(request)) @login_required def edit_profile(request): """ Called when user wants to edit his profile page. Note that none of the fields in returned form is required. """ user_profiles = UserProfile.objects.filter(user=request.user) if len(user_profiles) > 0: user_profile = user_profiles[0] else: user_profile = getDefaultUserProfile(request.user) if request.method == 'POST': form = UpdateUserProfileForm(request.POST, request.FILES) if request.POST['interests'] is not None: if len(request.POST['interests']) > 0: user_profile.interests = request.POST['interests'] if request.POST['about'] is not None: if len(request.POST['about']) > 0: user_profile.about = request.POST['about'] if request.POST['country'] is not None: if len(request.POST['country']) > 0: user_profile.country = request.POST['country'] if request.POST['city'] is not None: if len(request.POST['city']) > 0: user_profile.city = request.POST['city'] if request.POST['university'] is not None: if len(request.POST['university']) > 0: user_profile.university = request.POST['university'] if request.POST['photo'] is not None: if len(request.POST['photo']) > 0: user_profile.photo = request.FILES['photo'] news = UserNews(user=request.user, content='Profile was updated') news.save() user_profile.save() return HttpResponseRedirect('/profile/') else: form = UpdateUserProfileForm() return render_to_response('profile/edit_profile.html', { 'user_profile':user_profile, 'form':form, }, context_instance=RequestContext(request)) def getDefaultUserProfile(user): """ Helper function that creates and saves default user profile. Used when user doesn't have his profile yet. """ user_profile = UserProfile(user=user) user_profile.save() return user_profile <file_sep>/ai_arena/media/may_contest/judge.cpp #include <iostream> #include <sstream> #include <time.h> #include <stdlib.h> #define MIN_BET 10 #define MAX_BET 200 #define CARD_COUNT 5 #define ROUNDS_COUNT 200 using namespace std; bool readBet(int player, int message, int * bet){ string line; //cerr << "sending " << "[" << player << "] " << message << "\n"; cout << "[" << player << "] " << message << "\n"; getline(cin, line); //cerr << "received " << line << "\n"; return (stringstream(line) >> *bet); } int decisionMaker(int * bets){ if(bets[1] < bets[2]) return 1; if(bets[2] < bets[1]) return 2; return 0; } int opponent(int player){ return 3 - player; } bool readBets(int mes1, int mes2, int * bets, bool secondRound){ readBet(1, mes1, bets+1); readBet(2, mes2, bets+2); //cerr << "BETS1 " << bets[1] << " " << bets[2] << "\n"; int dm = decisionMaker(bets); int trash; if(dm){ int op = opponent(dm); readBet(dm, bets[op], bets); if(bets[0]){ readBet(op, bets[dm], &trash); readBet(op, 1, &trash); bets[dm] = bets[op]; bets[0] = 0; }else{ readBet(op, bets[dm], &trash); readBet(op, 0, &trash); bets[0] = op; } }else{ bets[0] = 0; readBet(1, bets[2], &trash); readBet(2, bets[1], &trash); } return true; } int main(){ int bets[3]; int scores[3]; int actualBet=0, pl1card=0, pl2card=0; int decision=0; int trash=0; int winner=0; int sum1=0, sum2=0; bets[0] = bets[1] = bets[2] = 0; scores[0] = scores[1] = scores[2] = 0; for(int i=0; i<ROUNDS_COUNT; i++){ pl1card = rand() % CARD_COUNT; pl2card = rand() % CARD_COUNT; sum1 += pl1card; sum2 += pl2card; //cerr << "CARDS " << pl1card << " " << pl2card << "\n"; winner = 0; actualBet = 0; if(pl1card > pl2card) winner = 1; if(pl2card > pl1card) winner = 2; //cerr << "first BET\n"; readBets(pl1card, pl2card, bets, false); actualBet = min(bets[1], bets[2]); if(bets[0]) winner = bets[0]; else{ //cerr << "second BET\n"; readBets(bets[2], bets[1], bets, true); actualBet += min(bets[1], bets[2]); if(bets[0]) winner = bets[0]; else{ readBet(1, pl2card, bets); readBet(2, pl1card, bets); } } if(winner) scores[winner] += actualBet; } cerr << "sum of cards " << sum1 << " " << sum2 << "\n"; cerr << "scores " << scores[1] << " " << scores[2] << "\n"; cout << "[0]END\n"; if(scores[1] > scores[2]) cout << "[2, 0]\n"; if(scores[2] > scores[1]) cout << "[0, 2]\n"; if(scores[1] == scores[2]) cout << "[1, 1]\n"; return 0; } <file_sep>/files/nadzorca.py #!/usr/bin/python # Filename: nadzorca.py import subprocess import os import tempfile import sys import threading import Queue import time class Game: memory_limit = 50 # Memory limit in MB time_limit = 600 # Time limit in seconds judge_path = None # The binary file of the judge def __init__(self, j_path=None, mem_limit=None, t_limit=None): if mem_limit: self.memory_limit = mem_limit if t_limit: self.time_limit = t_limit if j_path: self.judge_path = j_path def set_limits(self, mem_limit=None, t_limit=None): if mem_limit: self.memory_limit = mem_limit if t_limit: self.time_limit = t_limit def set_judge(self, j): self.judge_path = j class Bot: filepath = None def __init__(self, fpath=None): if fpath: self.filepath = fpath def set_filepath(self, fpath): self.filepath = fpath def parse_response(response, player): return "[" + str(player) + "]" + response """ This function parses a message from judge returning list of players as a first of pair and an actual message as a second of pair Every message coming here must comtain a list of players in brackets like these: '[' and ']'. It can contain multiple of any of them, in this case the first pair is treated as a list of players. """ def parse_message(to_send): l = to_send.split(']') players = map(lambda x:int(x), l[0][1:].split(',')) mes = l[1] for t in l[2:]: mes += ']' + t return (players,mes) """ This function reads communicates. The assumption is that every communicate ends with chars 'END\n' not case-sensitive In addition every 'END\n' frase is considered to be end of a communicate """ # TODO: Add timeout! def readout(pipe, timeout=0): mes = '' while mes[len(mes)-3:].upper() != 'END': mes = mes + pipe.read(1) pipe.read(1) return mes[:len(mes)-3] """ ListOfBots is a list of objects of class Bot. Bots are meant to know where is theirs executable file is located. Game, according to the description above knows its limits and the judge, which is an executable file """ def play(list_of_bots, game): jp = subprocess.Popen( game.judge_path, stdout=subprocess.PIPE, stdin=subprocess.PIPE, # stderr=subprocess.PIPE, shell=True, ) bots_process_list = [] for bot in list_of_bots: arg_to_execute = "ulimit -v %d; ulimit -t %d ; ./%s" % (game.memory_limit * 1024, game.time_limit, bot.filepath) bot_process = subprocess.Popen( arg_to_execute, stdin = subprocess.PIPE, stdout = subprocess.PIPE, # stderr = subprocess.PIPE, shell=True, ) bots_process_list.append(bot_process) for bot in bots_process_list: print bot.pid end_game = False; while not end_game: to_send = readout(jp.stdout) (players, message) = parse_message(to_send) if message == ' ': print 'Ending game' end_game = True break for player in players: message = message + '\n' bots_process_list[player-1].stdin.write(message) response = readout(bots_process_list[player-1].stdout) + '\n' jp.stdin.write(response) def costam(): return 5 <file_sep>/ai_arena/contests/bot_views.py from os import system from datetime import datetime from django.core.files import File from django.contrib.auth.decorators import login_required from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponseRedirect from ai_arena import settings from ai_arena.contests.compilation import compile from ai_arena.contests.forms import SendBotForm, SendBotWithoutNameForm, SendBotWithGameForm from ai_arena.contests.models import Game, Bot, Contest from ai_arena.contests.may_contest_helper_functions import generate_ranking @login_required def create_bot_from_request(request, game, testing=False, bot_field='bot_source'): """ Helper function used to create bot object after receiving POST data from html form. It tries to compile uploaded source file, creates object and places apriopriate files in theirs final destination. In case of compilation failure bot object is not created. Function returns 3-tuple: (exit_status, logs, bot) in case of compilation failure, where exit_status != 0 and logs is a string representation of error or log = "" if compilation succedes, where exit_status == 0 and bot is created bot object. """ # Save known fields new_bot = Bot() new_bot.name = request.user.username + '_bot' if 'bot_name' in request.POST and len(request.POST['bot_name']) > 0: new_bot.name = request.POST['bot_name'] if testing: new_bot.ranked = False if 'test_name' in request.POST and len(request.POST['test_name']) > 0: new_bot.name = request.POST['test_name'] else: new_bot.name = 'test_bot' # bot.name = settings.TEST_BOT_PREFIX + datetime.now().isoformat().replace(':', '-').replace('.', '-') new_bot.bot_lang = request.POST['bot_language'] if bot_field=='opponent_source': # bot.name = settings.OPPONENT_TEST_BOT_PREFIX + datetime.now().isoformat().replace(':', '-').replace('.', '-') new_bot.name = 'test_opponent' new_bot.bot_lang = request.POST['opponent_language'] bots_to_delete = Bot.objects.filter(owner=request.user, name=new_bot.name) new_bot.bot_source_file = request.FILES[bot_field] new_bot.game = game # Add owner info new_bot.owner = request.user new_bot.save() # Compile source file to directory with source file exit_status, logs = new_bot.compile_bot() if exit_status != 0: new_bot.delete() return (exit_status, logs, None) else: for bot in bots_to_delete: if bot.id != new_bot.id: bot.delete_bot_matches() bot.delete() return (exit_status, "", new_bot) @login_required def send_bot(request, game_id): """ Displays form to send bot for a game with id equal to game_id. If game_id is not given or there is no Game object with id equal to game_id then Exception is thrown If contest_id is given, the bot is added to this contest as a contestant """ if not game_id: raise Exception("In game_details: No game_id given") game = Game.objects.get(id=game_id) if game is None: raise Exception("In game_details: Wrong game_id given") if request.method == 'POST': form = SendBotForm(request.POST, request.FILES) if form.is_valid(): (exit_status, logs, bot) = create_bot_from_request(request, game) if exit_status != 0: # error occured return render_to_response('error.html', { 'error_details': logs, }, context_instance=RequestContext(request)) else: return HttpResponseRedirect('/') else: form = SendBotForm() return render_to_response('gaming/send_bot.html', { 'form': form, 'game_id': game_id, }, context_instance=RequestContext(request)) @login_required def send_bot_without_name(request, game_id): """ Displays form to send bot for a game with id equal to game_id. If game_id is not given or there is no Game object with id equal to game_id then Exception is thrown If contest_id is given, the bot is added to this contest as a contestant """ if not game_id: raise Exception("In game_details: No game_id given") game = Game.objects.get(id=game_id) if game is None: raise Exception("In game_details: Wrong game_id given") if request.method == 'POST': form = SendBotWithoutNameForm(request.POST, request.FILES) if form.is_valid(): (exit_status, logs, bot) = create_bot_from_request(request, game) if exit_status != 0: # error occured return render_to_response('error.html', { 'error_details': logs, }, context_instance=RequestContext(request)) else: generate_ranking() return HttpResponseRedirect('/') else: form = SendBotWithoutNameForm() return render_to_response('gaming/send_bot_without_name.html', { 'form': form, 'game_id': game_id, }, context_instance=RequestContext(request)) @login_required def send_bot_with_game(request): """ This view is used when user wants to send bot from game details view. It is different from simple send bot view, because game is known, so there is no need to pick it form list. """ if request.method == 'POST': form = SendBotWithGameForm(request.POST, request.FILES) if form.is_valid(): game = Game.objects.get(id = request.POST['game']) if game is None: raise Exception("In send_bot_with_game: Wrong game_id given") (exit_status, logs, bot) = create_bot_from_request(request, game) if exit_status != 0: # error occured return render_to_response('error.html', { 'error_details': logs, }, context_instance=RequestContext(request)) return HttpResponseRedirect('/') else: form = SendBotWithGameForm() return render_to_response('gaming/send_bot.html', { 'form': form, }, context_instance=RequestContext(request)) <file_sep>/files/may_game/default_bots/strong_bot.py from sys import stdin, stdout, stderr def firstBet(myCard): bet = 10 if myCard > 1: bet = 100 if myCard == 4: bet = 200 return bet def secondBet(my1bet, op1bet, card): if card == 4: return 200 if card > 1: return 100 if op1bet > my1bet: return 10 return 50 def firstDecision(myBet, opBet, card): if card < 2: return 0 if (card == 2) and (2*myBet > opBet): return 1 if card > 2: return 1 return 0 def secondDecision(myBet, opBet, card): if card < 2: return 0 if (card == 2) and (2*myBet > opBet): return 1 if card > 2: return 1 return 0 receivedInts = [] total_score = 0 def takeInt(): global receivedInts if len(receivedInts) == 0: receivedInts = map(int, raw_input().split()) return receivedInts.pop(0) def log(message): stderr.write(message) def won(stake): global total_score total_score += stake log("Won %d " % stake) log("Total score: %d " % total_score) def lost(stake): global total_score total_score -= stake log("Lost %d " % stake) log("Total score: %d " % total_score) def send(decision): stdout.write(str(decision) + "\n") stdout.flush() while True: """ First Round """ # Draw card card = takeInt() # Make first bet my1bet = firstBet(card) send(my1bet) # Learn opponent bet op1bet = takeInt() # If my bet was lower if op1bet > my1bet: decision1 = firstDecision(my1bet, op1bet, card) # Pass if decision1 == 0: send(decision1) lost(my1bet) continue # If my bet was higher if my1bet > op1bet: decision1 = takeInt() # Opponent passed if decision1 == 0: won(op1bet) continue stake1 = max(my1bet, op1bet) """ Second Round """ # Make second bet my2bet = secondBet(my1bet, op1bet, card) send(my2bet) # Learn opponent bet op2bet = takeInt() # If my bet was lower if op2bet > my2bet: decision2 = secondDecision(my1bet+my2bet, op1bet + op2bet, card) send(decision2) # Pass if decision2 == 0: lost(stake1 + my2bet) continue # If my bet was higher if my2bet > op2bet: decision2 = takeInt() # Opponent passed if decision2 == 0: won(stake1 + op2bet) continue stake2 = max(my2bet, op2bet) final_stake = stake1 + stake2 # learn opponent card opCard = takeInt() if opCard == card: log('Draw ') if opCard > card: lost(final_stake) if opCard < card: won(final_stake) <file_sep>/makefile/python.mk # uniwersalny makefile dla języka PYTHON all : $(SRC) python -m py_compile $(SRC) cp $(SRC) $(TARGET) <file_sep>/documentation/modules/nadzorca.rst nadzorca ====================== .. automodule:: ai_arena.nadzorca.nadzorca :members: <file_sep>/ai_arena/templates/index.html {% extends "base.html" %} {% block css %} <link rel='stylesheet' href="{{ MEDIA_URL }}index.css" /> {% endblock %} {% block content %} <div id='welcome_news'> <div id='logo'> <img src="{{ MEDIA_URL }}img/logo.png" /> </div> <h1> Welcome to AI-Arena! </h1> <p class='p_news'> AI-arena is a place where you can learn and try all the tricks from artificial intelligence in practice. You can help us to improve the service by <a href="{% url contact_us %}" > sharing your suggestions with us </a>. </p> </div> {% endblock %} <file_sep>/ai_arena/templates/gaming/launch_match.html {% extends "base.html" %} {% block content %} {% if game_form %} <form action="{% url launch_match %}" method="post"> {% csrf_token %} {{ game_form.as_p }} <input name="game_form" class="btn primary" type="submit" value="Submit" /> </form> {% endif %} {% if game_id and bot_form %} <form action="{% url launch_game_match game_id number_of_bots %}" method="post"> {% csrf_token %} {{ bot_form.as_p }} <input name="bot_form" class="btn primary" type="submit" value="Launch match" /> </form> {% endif %} {% endblock %} <file_sep>/ai_arena/nadzorca/testing/pok2/run.py import os current_dir = os.path.dirname(os.path.abspath(__file__)) grand_dir = os.path.dirname(os.path.dirname(current_dir)) os.sys.path.insert(0, grand_dir) import nadzorca print 'TEST pok' judge_path = current_dir + "/pok_judge" bot_path = current_dir + "/pok_bot" bot_lang = 'CPP' bot2_path = current_dir + "/py_pok_bot.py" bot2_lang = 'PYTHON' results = nadzorca.play(judge_file=judge_path, judge_lang='CPP', players=[(bot_path, bot_lang), (bot2_path, bot2_lang)], time_limit=10, memory_limit=1000000) print results passed = True judge_info = '' for item in results['logs']['judge']: judge_info = judge_info + item bot1_info = '' for item in results['logs'][0]: bot1_info = bot1_info + item bot2_info = '' for item in results['logs'][1]: bot2_info = bot2_info + item #print "judge info:\n" + judge_info #print "bot1 info:\n" + bot1_info #print "bot2 info:\n" + bot2_info if results['exit_status'] != 10: passed = False print "exit status: " + str(results['exit_status']) + " instead of 10" print "results: " + str(results['results']) if passed: print "PASS" else: print "FAIL" <file_sep>/ai_arena/media/game_judges_sources/test_game_kk/kk_judge.cpp #include <iostream> #define N 3 #define M 3 #define K 3 #define DEBUG using namespace std; int endGame(void); void makeMove(int, int); void printBoard(void); char board[N][M]; bool ruch; string TAG = "Sedzia: "; int main(){ string com; bool end = false; int X, Y; for(int i = 0; i < N; ++i) for(int j = 0; j < N; ++j) board[i][j] = '.'; ruch = true; cout << "[1] START <<<\n"; cerr << TAG << "[1] START <<<\n"; while(!end){ cin >> com; if(com == "MOVE"){ cin >> X >> Y >> com; makeMove(X, Y); if(endGame() == 0){ (ruch)?cout<<"[2] ":cout<<"[1] "; cout<<"MOVE " << X << " " << Y << " <<<\n"; cerr << TAG << ((ruch)?"[2] ":"[1] ") << "MOVE "<<X<<" "<<Y<<" <<<\n"; } } int endg = endGame(); if(endg != 0){//end game cout << "[0]END<<<\n"; cerr << TAG <<"[0]END<<<\n"; if(endg == 3){ cout << "[0, 0] <<<\n"; cerr<<TAG << "[0, 0] <<<\n"; } if(endg == 2){ cout << "[0, 1] <<<\n"; cerr << TAG << "[0, 1] <<<\n"; } if(endg == 1){ cout << "[1, 0] <<<\n"; cerr << TAG << "[1, 0] <<<\n"; } end = true; } ruch = !ruch; // printBoard(); } return 0; } void makeMove(int i, int j){ if(ruch){ board[i][j] = 'X'; }else{ board[i][j] = 'O'; } } int endGame(){ bool x[8], y[8]; for(int i = 0; i < 8; ++i){ x[i] = true; y[i] = true; } for(int i = 0; i < N; ++i) for(int j = 0; j < N; ++j) if(board[i][j] == '.'){ x[i] = false; y[i] = false; x[j+N] = false; y[j+N] = false; if(i == j){ x[2*N] = false; y[2*N] = false; } if(i+j == N-1){ x[2*N+1] = false; y[2*N+1] = false; } } else if(board[i][j] == 'X'){ y[i] = false; y[j+N] = false; if(i == j) y[2*N] = false; if(i+j == N-1) y[2*N+1] = false; } else{ x[i] = false; x[j+N] = false; if(i == j) x[2*N] = false; if(i+j == N-1) x[2*N+1] = false; } for(int i = 0; i < 8; ++i){ if(x[i]) return 1; if(y[i]) return 2; } for(int i = 0; i < N; ++i) for(int j = 0; j < M; ++j) if(board[i][j] == '.') return 0; return 3; } void printBoard(){ for(int i = 0; i < N; ++i){ for(int j = 0; j < M; ++j) cout << board[i][j]; cout << endl; } } <file_sep>/ai_arena/nadzorca/testing/memory_limit/run.py import os current_dir = os.path.dirname(os.path.abspath(__file__)) grand_dir = os.path.dirname(os.path.dirname(current_dir)) os.sys.path.insert(0, grand_dir) import nadzorca print 'TEST memory_limit' judge_path = current_dir + "/memory_limit_judge" bot_path = current_dir + "/memory_limit_bot" results = nadzorca.play(judge_file=judge_path, judge_lang='CPP', players=[(bot_path, 'CPP'), (bot_path, 'CPP')], time_limit=100, memory_limit=10000) #print results passed = True if results['results'] != [0, 0]: passed = False print "results: " + str(results['results']) + " instead of [1, 0]" if passed: print "PASS" else: print "FAIL" <file_sep>/documentation/modules/match_views.rst match_views ================================= .. automodule:: ai_arena.contests.match_views :members: <file_sep>/documentation/modules/bot_views.rst bot_views ================================= .. automodule:: ai_arena.contests.bot_views :members: <file_sep>/makefile/java.mk # uniwersalny makefile dla języka C++ JC = gcc JFLAGS = -g all : $(TARGET) $(TARGET) : $(SRC) $(JC) $(CFLAGS) $(SRC) <file_sep>/ai_arena/contests/forms.py from django import forms from django.core.files.uploadedfile import SimpleUploadedFile from ai_arena.contests.models import Game, Bot from ai_arena import settings from django.contrib.admin.widgets import AdminDateWidget class vModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return "%s" % obj.name class GameSelectForm(forms.Form): """ Form that allows to link particular Bot with Game object """ games = Game.objects game_field = vModelChoiceField(queryset=games) number_of_bots = forms.IntegerField(min_value=settings.GAME_MIN_PLAYERS_DEFAULT, max_value=settings.GAME_MAX_PLAYERS_DEFAULT) class BotsSelectForm(forms.Form): """ Form used to select bots to match """ def __init__(self, *args, **kwargs): game = kwargs['game'] number_of_bots = kwargs['number_of_bots'] kwargs.pop('game') kwargs.pop('number_of_bots') super(BotsSelectForm, self).__init__(*args, **kwargs) bots = Bot.objects.filter(game=game) for i in range(number_of_bots): self.fields['bot_field%d' % (i+1)] = vModelChoiceField(queryset=bots) class NewGameForm(forms.Form): """ Form allowing creating new game with selected number of players (between 1 and 6) """ game_name = forms.CharField(max_length=settings.NAME_LENGTH) game_rules = forms.FileField() game_judge = forms.FileField() max_players = forms.IntegerField(min_value=settings.GAME_MIN_PLAYERS_DEFAULT, max_value=settings.GAME_MAX_PLAYERS_DEFAULT) judge_language = forms.ChoiceField(choices= settings.LANGUAGES) class SendBotForm(forms.Form): """ Form used to upload Bot source code to a server. It's similar to SendBotWithoutNameForm, but it allows to choose bot name. """ bot_name = forms.CharField(max_length=settings.NAME_LENGTH) bot_source = forms.FileField() bot_language = forms.ChoiceField(choices = settings.LANGUAGES) class SendBotWithoutNameForm(forms.Form): """ Form used to upload Bot source code to a server. It's similar to SendBotForm, but it doesn't allow for choosing bot name. """ bot_source = forms.FileField() bot_language = forms.ChoiceField(choices = settings.LANGUAGES) class SendBotWithGameForm(forms.Form): """ Form used to send Bot source code and link it against a Game object at the same time. """ games = Game.objects game = vModelChoiceField(queryset=games) bot_name = forms.CharField(max_length=settings.NAME_LENGTH) bot_source = forms.FileField() bot_language = forms.ChoiceField(choices = settings.LANGUAGES) class MayContestSendBotForTest(forms.Form): """ Form used to perform single match against two uploaded Bots (or against default Bot). It was used to simplify testing Bots for may contest. """ test_name = forms.CharField(required=False, max_length=settings.NAME_LENGTH) bot_source = forms.FileField() bot_language = forms.ChoiceField(choices = settings.LANGUAGES) opponent_source = forms.FileField(required=False) opponent_language = forms.ChoiceField(required=False, choices = settings.LANGUAGES) class UpdateUserProfileForm(forms.Form): """ Form used to update User Profile. """ photo = forms.ImageField() about = forms.CharField(widget=forms.widgets.Textarea(attrs={'cols':100, 'rows':6})) interests = forms.CharField(widget=forms.widgets.Textarea(attrs={'cols':100, 'rows':6})) country = forms.CharField(max_length=settings.NAME_LENGTH) city = forms.CharField(max_length=settings.NAME_LENGTH) university = forms.CharField(max_length=settings.NAME_LENGTH) birthsday = forms.DateField(widget=AdminDateWidget()) class AddCommentForm(forms.Form): """ Form used to add comments under game or contest """ comment = forms.CharField(widget=forms.widgets.Textarea(attrs={'cols':100, 'rows':6})) class EditCommentForm(forms.Form): """ Form used to edit comments under game or contest """ comment = forms.CharField(widget=forms.widgets.Textarea(attrs={'cols':100, 'rows':6})) class EditGameForm(forms.Form): """ Form used to edit game details after its creation. """ name = forms.CharField(max_length=settings.NAME_LENGTH) description = forms.CharField(widget=forms.widgets.Textarea(attrs={'cols':100, 'rows':15}), required=False) game_rules = forms.FileField(required=False) game_judge = forms.FileField(required=False) judge_language = forms.ChoiceField(choices = settings.LANGUAGES, required=False) class OnlineBotCreationForm(forms.Form): """ Form simplifying creating new bots for may contest. It contains 4 hard-coded templates, which users can use and modify before sending for the contest. """ code = forms.CharField ( widget=forms.widgets.Textarea( attrs={'cols':settings.BOT_CREATE_FIELD_COLUMNS, 'rows':settings.BOT_CREATE_FIELD_ROWS}) ) bot_code1 = forms.CharField ( widget=forms.widgets.HiddenInput()) bot_code2 = forms.CharField ( widget=forms.widgets.HiddenInput()) bot_code3 = forms.CharField ( widget=forms.widgets.HiddenInput()) bot_code4 = forms.CharField ( widget=forms.widgets.HiddenInput()) <file_sep>/ai_arena/templates/profile/show_profile.html {% extends 'base.html' %} {% block css %} <link rel='stylesheet' href='{{ MEDIA_URL }}profile.css' /> {% endblock %} {% block content %} {% if error_message %} <h1>{{ error_message }}</h1> {% endif %} {% if user_profile %} {% block side_panel %} <div id='side_panel'> {% if user_profile.photo %} <div><img src='{{ MEDIA_URL }}/{{ user_profile.photo }}' alt='avatar' id='avatar'></div> {% else %} <div><img src='{{ MEDIA_URL }}/profiles/photos/default_avatar.jpg' alt='avatar' id='avatar' /></div> {% endif %} <div><a href='/profile/{{ user_profile.user.username }}/'>My profile</a></div> <div><a href='/profile/{{ user_profile.user.username }}/contests/'>My contests</a></div> <div><a href='/profile/{{ user_profile.user.username }}/news/'>News</a></div> <div><a href='/profile_edit/'>Edit profile</a></div> </div> {% endblock %} {% block main_panel %} <div id='main_panel'> <div id='personalities'> <table> {% if user_profile.about %} <tr> <td class='first_column'> About me: </td> <td class='second_column'>{{ user_profile.about }}</td> </tr> {% endif %} {% if user_profile.birthsday %} <tr> <td class='first_column'> Birthsday: </td> <td class='second_column'>{{ user_profile.birthsday }} </td> </tr> {% endif %} {% if user_profile.country %} <tr> <td class='first_column'> Country: </td> <td class='second_column'>{{ user_profile.country }}</td> </tr> {% endif %} {% if user_profile.city %} <tr> <td class='first_column'> City: </td> <td class='second_column'>{{ user_profile.city }}</td> </tr> {% endif %} {% if user_profile.university %} <tr> <td class='first_column'> University: </td> <td class='second_column'>{{ user_profile.university }}</td> </tr> {% endif %} {% if user_profile.interests %} <tr> <td class='first_column'> Interests: </td> <td class='second_column'>{{ user_profile.interests }}</td> </tr> {% endif %} {% if news %} <tr> <td class='first_column'> News: </td> <td class='second_column'> <table id='news_table'> {% for n in news %} <tr class='news_row'> <td class='news_cont'>{{ n.content }}</td> <td class='news_date_set'>{{ n.date_set }}</td> </tr> {% endfor %} <table> </td> </tr> {% endif %} </table> </div> {% endblock %} {% endif %} {% endblock %} <file_sep>/ai_arena/nadzorca/testing/bot_logs/run.py import os current_dir = os.path.dirname(os.path.abspath(__file__)) grand_dir = os.path.dirname(os.path.dirname(current_dir)) os.sys.path.insert(0, grand_dir) import nadzorca print 'TEST bot_logs' judge_path = current_dir + "/bot_logs_judge" bot_path = current_dir + "/bot_logs_bot" results = nadzorca.play(judge_file=judge_path, judge_lang='CPP', players=[(bot_path, 'CPP'), (bot_path, 'CPP')], time_limit=1, memory_limit=100000) passed = True bot1_info = '' for item in results['logs'][0]: bot1_info = bot1_info + item bot2_info = '' for item in results['logs'][1]: bot2_info = bot2_info + item if bot1_info != '1122334455': passed = False print "bot1 info: " + bot1_info + " instead of 1122334455" if bot2_info != '11223344': passed = False print "bot2 info: " + bot2_info + " instead of 11223344" if results['exit_status'] != 0: passed = False print "exit status: " + str(results['exit_status']) + " instead of 0" if results['results'] != [1, 0]: passed = False print "results: " + str(results['results']) + " instead of [1, 0]" if passed: print "PASS" else: print "FAIL" <file_sep>/ai_arena/nadzorca/testing/pok2/c_pok_bot.c #include <stdio.h> #include <time.h> #define false 0 #define true 1 #define CONFIRM printf("0\n");fflush(stdout) #define WAIT scanf("%d", &trash) int firstBet(int card){ int bet = 10; if(card > 1) bet = 100; if(card == 4) bet = 200; return bet; } int secondBet(int my1bet, int op1bet, int card){ if(card == 4) return 200; if(card > 1) return 120; if(op1bet > my1bet) return 10; return 50; } int decision(int myBet, int opBet, int card){ if(card < 2) return 0; if((card == 2)&&(2*myBet > opBet)) return 1; if(card > 2) return 1; return 0; } int main(){ int card, my1bet, op1bet, bet1, my2bet, op2bet, decision1, decision2, opCard; int trash; while(true){ scanf("%d", &card); fprintf(stderr, "CARD %d\n", card); my1bet = firstBet(card); printf("%d\n",my1bet); fflush(stdout); scanf("%d",&op1bet); fprintf(stderr,"op1bet %d\n", op1bet); if(op1bet > my1bet){ decision1 = decision(my1bet, op1bet, card); fprintf(stderr, "making decision %d\n", decision1); if(decision1 == 0){ printf("%d\n", decision1); fflush(stdout); continue; } } if(my1bet > op1bet){ scanf("%d", &decision1); fprintf(stderr, "op made decision %d\n", decision1); if(decision1 == 0){ continue; } } if(my1bet == op1bet){ fprintf(stderr,"equal 1bet\n"); } //SECOND BET fprintf(stderr, "second round\n"); my2bet = secondBet(my1bet, op1bet, card); printf("%d\n", my2bet); fflush(stdout); scanf("%d", &op2bet); fprintf(stderr, "op2bet %d\n", op2bet); if(op2bet > my2bet){ decision2 = decision(my1bet+my2bet, op1bet+op2bet, card); fprintf(stderr, "making decision %d\n", decision2); printf("%d\n", decision2); fflush(stdout); if(decision2 == 0) continue; } if(my2bet > op2bet){ scanf("%d", &decision2); fprintf(stderr, "op made decision %d\n", decision2); if(decision2 == 0) continue; } if(my2bet == op2bet){ fprintf(stderr, "equal 2bet\n"); } scanf("%d", &opCard); } return 0; } <file_sep>/files/may_game/default_bots/medium_bot.py from sys import stdin, stdout, stderr from random import * def firstBet(myCard): stake1 = 0 if myCard == 0: if randint (0,100) < 15: # blef stake1 = 120 + randint(0,20) else: stake1 = 20 + randint(0,5) elif myCard == 1: stake1 = 45 + randint(0,10) elif myCard == 2: stake1 = 60 + randint(0,20) elif myCard == 3: stake1 = 80 + randint (0,25) elif myCard == 4: stake1 = 100 + randint (0,30) else: assert False stake1 = min(stake1, 200) return stake1 def secondBet(stake1, minStake2, myCard): if myCard == 0: stake2 = min(stake1 + randint(0,12), 200) if myCard == 1: stake2 = min(stake1 + randint(0,25), 200) if myCard == 2: stake2 = min(stake1 + randint(0,50), 200) if myCard == 3: stake2 = min(stake1 + randint(0,100), 200) if myCard == 4: stake2 = 200 - randint(0,20) stake2 = min(200, stake2) stake2 = max(minStake2, stake2) return stake2 def firstDecision(stake1, otherStake1, myCard): stake1 = max(stake1, otherStake1) if otherStake1 <= stake1: return 1 if myCard == 0: return int(otherStake1 <= stake1 + 10) if myCard == 1: return int(otherStake1 <= stake1 + 20) if myCard == 2: return int(otherStake1 <= stake1 + 40) if myCard == 3: return int(otherStake1 <= stake1 + 80) if myCard == 4: return 1 assert False def secondDecision(stake1, otherStake2, myCard): if myCard == 0: return int(otherStake2 <= stake1 * 1.2) if myCard == 1: return int(otherStake2 <= stake1 * 1.3) if myCard == 2: return int(otherStake2 <= stake1 * 1.5) if myCard == 3: return int(otherStake2 <= stake1 * 2) if myCard == 4: return 1 assert False receivedInts = [] total_score = 0 def takeInt(): global receivedInts if len(receivedInts) == 0: receivedInts = map(int, raw_input().split()) return receivedInts.pop(0) def log(message): stderr.write(message) def won(stake): global total_score total_score += stake log("Won %d " % stake) log("Total score: %d " % total_score) def lost(stake): global total_score total_score -= stake log("Lost %d " % stake) log("Total score: %d " % total_score) def send(decision): stdout.write(str(decision) + "\n") stdout.flush() while True: """ First Round """ # Draw card card = takeInt() # Make first bet my1bet = firstBet(card) send(my1bet) # Learn opponent bet op1bet = takeInt() # If my bet was lower if op1bet > my1bet: decision1 = firstDecision(my1bet, op1bet, card) # Pass if decision1 == 0: send(decision1) lost(my1bet) continue # If my bet was higher if my1bet > op1bet: decision1 = takeInt() # Opponent passed if decision1 == 0: won(op1bet) continue stake1 = max(my1bet, op1bet) """ Second Round """ # Make second bet my2bet = secondBet(my1bet, op1bet, card) send(my2bet) # Learn opponent bet op2bet = takeInt() # If my bet was lower if op2bet > my2bet: decision2 = secondDecision(my1bet+my2bet, op1bet + op2bet, card) send(decision2) # Pass if decision2 == 0: lost(stake1 + my2bet) continue # If my bet was higher if my2bet > op2bet: decision2 = takeInt() # Opponent passed if decision2 == 0: won(stake1 + op2bet) continue stake2 = max(my2bet, op2bet) final_stake = stake1 + stake2 # learn opponent card opCard = takeInt() if opCard == card: log('Draw ') if opCard > card: lost(final_stake) if opCard < card: won(final_stake) <file_sep>/files/universal makefile/Makefile ifeq ($(LANG), CPP) include cpp.mk else ifeq ($(LANG), C) include c.mk else ifeq($(LANG), JAVA) include java.mk endif <file_sep>/makefile/Makefile TOP := $(dir $(lastword $(MAKEFILE_LIST))) ifeq ($(LANG), CPP) include $(TOP)/cpp.mk else ifeq ($(LANG), C) include $(TOP)/c.mk else ifeq ($(LANG), JAVA) print settings.MAKEFILE_DIR include $(TOP)/java.mk else ifeq ($(LANG), PYTHON) include $(TOP)/python.mk endif <file_sep>/documentation/modules/gearman_worker_lib.rst gearman_worker ====================== .. automodule:: ai_arena.gearman_worker_lib :members: <file_sep>/ai_arena/templates/gaming/edit_game.html {% extends 'base.html' %} {% block css %} <link rel="stylesheet" href="{{ MEDIA_URL }}game_edit.css" /> {% endblock %} {% block content %} <div id='additional_info'> Here you can update game details. Remember that if you upload game rules file, your changes id description will be automaticly discarded! </div> <form action='/game_details/{{ game.id }}/edit/' method='POST' enctype='multipart/form-data'> {% csrf_token %} {{ form.as_p }} <p><input type='submit' value='Accept changes' /></p> </form> {% endblock %} <file_sep>/documentation/modules/compilation.rst compilation ================================= .. automodule:: ai_arena.contests.compilation :members: <file_sep>/ai_arena/urls.py from django.conf.urls.defaults import patterns, include, url from django.conf import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'ai_arena.views.home', name='home'), # url(r'^ai_arena/', include('ai_arena.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), url(r'^admin/jsi18n', 'django.views.i18n.javascript_catalog'), url(r'^$', 'contests.views.index'), url(r'^error/$', 'contests.views.error'), url(r'^accounts/', include('registration2.backends.simple.urls')), url(r'^accounts/login/$', 'django.contrib.auth.views.login'), url(r'^profile/$', 'contests.user_views.show_profile'), url(r'^profile/(?P<login>\w+)/$','contests.user_views.show_profile'), url(r'^profile/(?P<login>\w+)/contests/$', 'contests.user_views.show_contests'), url(r'^profile/(?P<login>\w+)/news/$', 'contests.user_views.show_news'), url(r'^profile_edit/$', 'contests.user_views.edit_profile'), url(r'^new_game/$', 'contests.game_views.create_new_game', name='create_new_game'), url(r'^game_list/$', 'contests.game_views.game_list', name='game_list'), url(r'^game_details/(?P<game_id>\d+)/$', 'contests.game_views.game_details', name='game_details'), url(r'^game_details/(?P<game_id>\d+)/source/$', 'contests.game_views.show_source'), url(r'^game_details/(?P<game_id>\d+)/edit/$', 'contests.game_views.edit_game'), url(r'^game_details/(?P<game_id>\d+)/delete/$', 'contests.game_views.delete_game'), url(r'^(?P<comment_type>\w+)/add_comment/(?P<object_id>\d+)/$', 'contests.comment_views.add_comment'), url(r'^(?P<comment_type>\w+)/del_comment/(?P<object_id>\d+)/(?P<comment_id>\d+)/$', 'contests.comment_views.del_comment'), url(r'^(?P<comment_type>\w+)/edit_comment/(?P<object_id>\d+)/(?P<comment_id>\d+)/$', 'contests.comment_views.edit_comment'), url(r'^send_bot/$', 'contests.bot_views.send_bot_with_game', name='send_bot_with_game'), url(r'^send_bot/(?P<game_id>\d+)/$', 'contests.bot_views.send_bot'), url(r'^send_bot_without_name/(?P<game_id>\d+)/$', 'contests.bot_views.send_bot_without_name'), url(r'^results/match_results_list/$', 'contests.match_views.match_results_list', name='match_results_list'), url(r'^results/show_match_result/(?P<match_id>\d+)/$', 'contests.match_views.match_details', name='show_match_result'), url(r'^launch_match/$', 'contests.match_views.launch_match', name='launch_match'), url(r'^launch_match/(?P<game_id>\d+)/(?P<number_of_bots>\d+)/$', 'contests.match_views.launch_match', name='launch_game_match'), url(r'^contests/contests_list/$', 'contests.contest_views.contests_list', name='contests_list'), url(r'^contests/show_contest/(?P<contest_id>\d+)/$', 'contests.contest_views.show_contest', name='show_contest'), url(r'^contests/add_contestant/(?P<contest_id>\d+)/$', 'contests.contest_views.add_contestant', name='add_contestant'), url(r'^contact_us/$', 'contests.views.contact', name='contact_us'), #url(r'^ladder/$', 'contests.may_contest_views.show_ladder', name='may_contest_ladder'), #url(r'^my_results/$', 'contests.may_contest_views.my_results', name='may_contest_my_results'), #url(r'^my_results/details/(?P<match_id>\d+)/$', 'contests.may_contest_views.match_details'), #url(r'^downloads/$', 'contests.may_contest_views.downloads'), #url(r'^send_bot_may_contest/$', 'contests.may_contest_views.may_contest_send_bot', name='may_contest_send_bot'), #url(r'^online_bot_creation/$', 'contests.may_contest_views.online_bot_creation', name='may_contest_online_bot_creation'), #url(r'^online_bot_creation/uploaded/(?P<bot_name>\w+)/$', 'contests.may_contest_views.online_bot_uploaded', name='may_contest_online_bot_uploaded'), #url(r'^testing/$', 'contests.may_contest_views.testing', name='may_contest_testing'), #url(r'^testing/uploaded/$', 'contests.may_contest_views.uploaded_for_tests'), ) if settings.DEBUG: urlpatterns += patterns('', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT,}), )
111f12cf3bf6f7ded201b67eaed40dbce9aa69a9
[ "HTML", "reStructuredText", "Makefile", "Python", "C", "C++" ]
84
reStructuredText
Buzdygan/ai-arena
319fcff6e4734355e566f7dc353d135a70fd1e36
072a826499388a4fa8b295c0df17f5bbec2fd3cb
refs/heads/master
<file_sep># Algorithms Problems Misc algorithm problems written in [Rust](https://www.rust-lang.org/). <file_sep>// Problem statement: // A hiker is going on a trail and tracks when they are going up or down hill. // They always start and end at sealevel (SL). A path s can look like the following: // s = DDUUUUDD. // A mountain is a sequence of consecutive steps above SL, starting with // a step up from SL and ending with a step down to SL. // A valley is vice versa. // Given a path s, calculate the number of valleys traversed. // n: number of steps // s: path // Approach: // We can track their distance from SL by mapping U -> 1 and D -> -1. // The hiker is entering a valley when their first step is D and they are at // sealevel. fn main() { let n = 8; let s = String::from("UDDDUDUU"); // Initialize counters for distance from sealevel // and number of valleys let mut dist_sl = 0; let mut n_valleys = 0; // Only looping through path once so O(n) for i in 1..n { // Condition to determine if hiker is entering valley if dist_sl == 0 && &s[i-1..i] == "D" { n_valleys = n_valleys + 1; } if &s[i-1..i] == "U" { dist_sl = dist_sl + 1; } else if &s[i-1..i] == "D" { dist_sl = dist_sl - 1; } } println!("{}", n_valleys); } <file_sep>// Problem statement: // Given a string s and an integer n, print the number of a's in the repeated string. // e.g. s = 'aba', n = 10, repeated_string = 'abaabaabaa' and n_a = 4. // Approach: // The repeated string is constructed via the following formula: // remainder = n mod(length(s)) // s * (n // lenght_s) + s[remainder:] // We need to find the number of a's in the two substrings s and s[remainder:]. Given // a function count_as(), the number of a's is: // n_a = count_as(s) * (n // length_s) + count_as(s[remainder:]). // If the length of s is a perfect divisor of n, simply count the a's and multiply by that factor. // Count number of a's in a string s fn count_as(s: String) -> usize { let mut count = 0; for i in 1..s.len() + 1 { if &s[i-1..i] == "a" { count = count + 1; } } count } fn main() { let s = String::from("aba"); let n = 10; // Find length of string let len_s = s.len(); // Determine if there is a trailing piece of the string let tail = n % len_s; // Initialize counter for a's let count: usize; if tail != 0 { let s_tail = &s[0..tail]; let tail_count = count_as(s_tail.to_string()); count = count_as(s) * (n / len_s) + tail_count; } else { count = count_as(s) * (n / len_s); } println!("{}", count); } <file_sep>// Problem statement: // // Given an array of clouds numbered 0 if safe or 1 if they must be avoided, // find the minimum number of jumps to get to the end. You can only jump // 1 or 2 steps ahead and you can always win the game. // // c: clouds // // e.g. c = [0, 1, 0, 0, 0, 1, 0] // The shortest path is c[0] -> c[2] -> c[4] -> c[6] and the minimum // number of steps is 3. // // Approach: // // You can always win the game, therefore we can assume the last cloud // will always be 0. We can be greedy with our paths as well. If the // second cloud from us is 0, then we take it. // // Iterate through every cloud except for the last two. Check if the second one // is 0, else the first one is 0. If we end up on the second last cloud, just move ahead.x fn main() { // let c = [0, 0, 1, 0, 0, 1, 0]; // output is 4 let c = [0, 0, 0, 1, 0, 0]; // output is 3 // Find out how many clouds there are let n = c.len(); // Initialize counting variable let mut count = 0; // Initialize iteration counter let mut i = 0; // Iterate through each cloud except for the last two; O(n) while i < (n - 2) { if c[i + 2] == 0 { i = i + 2; count = count + 1; } else if c[i + 1] == 0 { i = i + 1; count = count + 1; } } if i == (n - 2) { count = count + 1; } println!("{}", count); } <file_sep>// Problem statement: // // Given an array of integers representing the color of each sock, determine // how many pairs of socks with matching colors are there. // // n: number of socks // ar: array of socks // // Find the number of pairs of socks. // // Approach: // // Create auxillary array where the index corresponds to the color of the sock. // Count each sock, divide by two and count the number of pairs. fn main() { let n = 7; // number of socks let ar = [1, 2, 1, 2, 1, 3, 2]; // socks // Find max value in order to create auxillary array; O(n) let mut n_colors = ar[0]; for i in 1..ar.len() { if ar[i] > n_colors { n_colors = ar[i]; } } // Create auxillary array to hold counts of pairs // Arrays cannot be dynamic, therefore we need to use vector let mut c = vec![0; n_colors]; // Count each sock; O(n) for i in 0..n { let key = ar[i]; c[key - 1] = c[key - 1] + 1; } // Divide each pair by 2 to get the count; O(n) for i in 0..n_colors { c[i] = c[i] / 2; } // Add all the pairs; O(n) let mut n_pairs = 0; for i in 0..n_colors { n_pairs = n_pairs + c[i]; } println!("{}", n_pairs); }
e6d976783c6a22b467756af282818b995b002dd5
[ "Markdown", "Rust" ]
5
Markdown
dtcrout/algo-problems
6e0478fbcdaa614bc0608eebb390672335d25103
d02a9fd159abbcd0ef4b0eec7eda2f36bf82bd69
refs/heads/master
<repo_name>loveAndroidAndroid/RxUpload<file_sep>/RxUpload/rxupload/src/main/java/com/wen/rxupload/uploadfile/task/UploadSingleItem.java package com.wen.rxupload.uploadfile.task; import java.io.File; import java.io.Serializable; import java.util.List; import java.util.Map; /** * Created by zhangxiaowen on 2018/11/1. * 上传操作所需构造的bean类 */ public class UploadSingleItem implements Serializable { private static final long serialVersionUID = 2876093702446386602L; private Class zClass;//retrofit 所需的接口对象 private String stringMethod;//上传文件的方法 private String stringKey;//上传文件所需的key 字符串 private Map<String, String> paramMap;//上传文件所需的其他参数的字符串 private File file;//单张文件只传file private List<File> files;//多张文件传files集合 private List<String> stringKeys;//多张文件传key集合 public List<File> getFiles() { return files; } public void setFiles(List<File> files) { this.files = files; } public List<String> getStringKeys() { return stringKeys; } public void setStringKeys(List<String> stringKeys) { this.stringKeys = stringKeys; } public Class getzClass() { return zClass; } public void setzClass(Class zClass) { this.zClass = zClass; } public String getStringMethod() { return stringMethod; } public void setStringMethod(String stringMethod) { this.stringMethod = stringMethod; } public String getStringKey() { return stringKey; } public void setStringKey(String stringKey) { this.stringKey = stringKey; } public Map<String, String> getParamMap() { return paramMap; } public void setParamMap(Map<String, String> paramMap) { this.paramMap = paramMap; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } } <file_sep>/RxUpload/base-lib-network/src/main/java/com/wen/network/http/RetrofitUtil.java package com.wen.network.http; import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import java.util.concurrent.TimeUnit; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import retrofit2.Retrofit; /** * ResponseInfoAPI工具类 */ public class RetrofitUtil { private static volatile RetrofitUtil instance = null; private Retrofit retrofit; private RetrofitUtil() { } /** * 静态内部类 */ public static RetrofitUtil getInstance() { if (instance == null) { synchronized (RetrofitUtil.class) { if (instance == null) { instance = new RetrofitUtil(); } } } return instance; } public void init(String baseURL, long readTime, long writeTime, long connectTime, Interceptor... interceptor) { retrofit = new Retrofit.Builder() .baseUrl(baseURL) .client(genericClient(readTime, writeTime, connectTime, interceptor)) //2.自定义ConverterFactory处理异常情况 .addConverterFactory(JsonArrayConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); } public OkHttpClient genericClient(long readTime, long writeTime, long connectTime, Interceptor... interceptors) { OkHttpClient.Builder builder = new OkHttpClient.Builder() .readTimeout(readTime, TimeUnit.SECONDS) .writeTimeout(writeTime, TimeUnit.SECONDS) .connectTimeout(connectTime, TimeUnit.SECONDS); if (interceptors != null && interceptors.length > 0) { for (int i = 0; i < interceptors.length; i++) { builder.addInterceptor(interceptors[i]); } } return builder.build(); } /** * 得到Retrofit的对象 * * @return */ public Retrofit getRetrofit() { return retrofit; } } <file_sep>/RxUpload/rxupload/src/main/java/com/wen/rxupload/uploadfile/task/UploadEvent.java package com.wen.rxupload.uploadfile.task; import java.io.Serializable; /** * Created by zhangxiaowen on 2018/11/1. * 上传回调的事件 */ public class UploadEvent implements Serializable { private static final long serialVersionUID = 3398585473606266145L; private int flag = UploadFlag.START; private UploadStatus uploadStatus = new UploadStatus(); private Throwable mError; public int getFlag() { return flag; } public void setFlag(int flag) { this.flag = flag; } public UploadStatus getUploadStatus() { return uploadStatus; } public void setUploadStatus(UploadStatus uploadStatus) { this.uploadStatus = uploadStatus; } public Throwable getError() { return mError; } public void setError(Throwable error) { mError = error; } } <file_sep>/RxUpload/rxupload/src/main/java/com/wen/rxupload/uploadfile/task/UploadTask.java package com.wen.rxupload.uploadfile.task; import com.wen.rxupload.uploadfile.manger.UploadMutiProcessManger; import java.util.Map; import java.util.concurrent.Semaphore; import io.reactivex.disposables.Disposable; import io.reactivex.processors.BehaviorProcessor; import io.reactivex.processors.FlowableProcessor; /** * Created by zhangxiaowen on 2018/10/31. * task抽象封装类 */ public abstract class UploadTask { private UploadMutiProcessManger mUploadMutiProcessManger; public UploadMutiItem uploadItem; public UploadTask(UploadMutiProcessManger uploadMutiProcessManger, UploadMutiItem uploadItem) { this.mUploadMutiProcessManger = uploadMutiProcessManger; this.uploadItem = uploadItem; } //再单个任务中注入taskMap和processorMap public abstract boolean init(Map<String, UploadTask> taskMap, Map<String, FlowableProcessor<UploadEvent>> processorMap); //开始任务 传入Semaphore线程控制 public abstract void startUploadFile(final Semaphore semaphore); //取消网络请求 public abstract void cancel(); /** * 得到对应的processor * * @param processorMap * @param urlFile * @return */ protected FlowableProcessor<UploadEvent> getProcessor(Map<String, FlowableProcessor<UploadEvent>> processorMap, String urlFile) { if (processorMap.get(urlFile) == null) { FlowableProcessor<UploadEvent> processor = BehaviorProcessor.<UploadEvent>create().toSerialized(); processorMap.put(urlFile, processor); } return processorMap.get(urlFile); } /** * 任务开始上传的方法 * * @param semaphore * @param callback * @return */ public Disposable startUploadFile(final Semaphore semaphore, final UploadTaskCallback callback) { Disposable disposable = mUploadMutiProcessManger.startUploadFileManger(uploadItem, semaphore, callback); return disposable; } /** * 取消此次操作 * * @param disposable */ public void dispose(Disposable disposable) { if (disposable != null && !disposable.isDisposed()) { disposable.dispose(); } } } <file_sep>/RxUpload/base-lib-network/src/main/java/com/wen/network/bean/ErrResponse.java package com.wen.network.bean; import java.io.Serializable; /** * Created by wen on 2018/5/14. * code不为1 解析msg错误字段 */ public class ErrResponse implements Serializable { private static final long serialVersionUID = -5180361253882702933L; private String code; private String msg; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } } <file_sep>/RxUpload/rxupload/src/main/java/com/wen/rxupload/uploadfile/manger/UploadSingleProcessManger.java package com.wen.rxupload.uploadfile.manger; import android.text.TextUtils; import com.wen.network.bean.TopResponse; import com.wen.network.http.RetrofitUtil; import com.wen.rxupload.uploadfile.netHelper.UploadSubscriberCallBack; import com.wen.rxupload.uploadfile.requestBoy.UploadFileRequestBody; import com.wen.rxupload.uploadfile.task.UploadSingleItem; import org.reactivestreams.Publisher; import java.io.File; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import java.util.Set; import io.reactivex.Flowable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; import okhttp3.MultipartBody; /** * Created by zhangxiaowen on 2018/10/31. * 单多文件单进度上传管理者 */ public class UploadSingleProcessManger<T> { /** * 同步方法 单上传文件的封装 * * @param file 需要上传的文件 * @param fileUploadObserver 上传回调 */ public Disposable syncUpLoadFile(UploadSingleItem uploadSingleItem, UploadSubscriberCallBack<T> uploadSubscriberCallBack) { return baseUploadFiles(false, uploadSingleItem, uploadSubscriberCallBack); } /** * 单上传文件的封装 * * @param file 需要上传的文件 * @param fileUploadObserver 上传回调 */ public Disposable upLoadFile(UploadSingleItem uploadSingleItem, UploadSubscriberCallBack<T> uploadSubscriberCallBack) { return baseUploadFiles(true, uploadSingleItem, uploadSubscriberCallBack); } private Disposable baseUploadFiles(boolean isAsync, UploadSingleItem uploadSingleItem, UploadSubscriberCallBack<T> uploadSubscriberCallBack) { MultipartBody multipartBody = fileToMultipartBody(uploadSingleItem.getStringKey(), uploadSingleItem.getParamMap(), uploadSingleItem.getFile(), uploadSubscriberCallBack); Object o = RetrofitUtil .getInstance() .getRetrofit() .create(uploadSingleItem.getzClass()); Disposable disposable = null; try { Method declaredMethod = o.getClass().getDeclaredMethod(uploadSingleItem.getStringMethod(), MultipartBody.class); Flowable<TopResponse<T>> invoke = (Flowable<TopResponse<T>>) declaredMethod.invoke(o, multipartBody); Flowable<TopResponse<T>> tmpInvoke = null; if (isAsync) { tmpInvoke = invoke .subscribeOn(Schedulers.io()); } else { tmpInvoke = invoke; } disposable = tmpInvoke .observeOn(AndroidSchedulers.mainThread()) .onBackpressureBuffer() .flatMap(new Function<TopResponse<T>, Publisher<T>>() { @Override public Publisher<T> apply(TopResponse<T> tTopResponse) throws Exception { if (tTopResponse.getCode().equals("1")) { return Flowable.just(tTopResponse.getData()); } else { return Flowable.error(new Throwable(tTopResponse.getInfo())); } } }) .subscribeWith(uploadSubscriberCallBack); } catch (Exception e) { e.printStackTrace(); } return disposable; } /** * 多上传文件的封装 * * @param files 需要上传的多个文件 * @param fileUploadObserver 上传回调 */ public Disposable upLoadFiles(UploadSingleItem uploadSingleItem, UploadSubscriberCallBack<T> uploadSubscriberCallBack) { MultipartBody multipartBody = filesToMultipartBody(uploadSingleItem.getStringKeys(), uploadSingleItem.getParamMap(), uploadSingleItem.getFiles(), uploadSubscriberCallBack); Object o = RetrofitUtil .getInstance() .getRetrofit() .create(uploadSingleItem.getzClass()); Disposable disposable = null; try { Method declaredMethod = o.getClass().getDeclaredMethod(uploadSingleItem.getStringMethod(), MultipartBody.class); Flowable<TopResponse<T>> invoke = (Flowable<TopResponse<T>>) declaredMethod.invoke(o, multipartBody); disposable = invoke.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .flatMap(new Function<TopResponse<T>, Publisher<T>>() { @Override public Publisher<T> apply(TopResponse<T> tTopResponse) throws Exception { if (tTopResponse.getCode().equals("1")) { return Flowable.just(tTopResponse.getData()); } else { return Flowable.error(new Throwable(tTopResponse.getInfo())); } } }) .subscribeWith(uploadSubscriberCallBack); } catch (Exception e) { e.printStackTrace(); } return disposable; } /** * 得到单文件上传的MultipartBody * * @param file * @param uploadSubscriberCallBack * * @return */ public MultipartBody fileToMultipartBody(String name, Map<String, String> paramsMap, File file, UploadSubscriberCallBack<T> uploadSubscriberCallBack) { MultipartBody.Builder builder = new MultipartBody.Builder(); if (file == null) { return builder.build(); } UploadFileRequestBody uploadFileRequestBody = new UploadFileRequestBody<T>(file, uploadSubscriberCallBack); builder.addFormDataPart(name, file.getName(), uploadFileRequestBody); if (paramsMap != null) { Set<String> params = paramsMap.keySet(); for (String paramKey : params) { if (paramKey != null) { String paramValue = paramsMap.get(paramKey); if (!TextUtils.isEmpty(paramValue)) { builder.addFormDataPart(paramKey, paramValue); } } } } builder.setType(MultipartBody.FORM); return builder.build(); } /** * 得到多文件上传的MultipartBody * * @param files * @param uploadSubscriberCallBack * * @return */ public MultipartBody filesToMultipartBody(List<String> name, Map<String, String> paramsMap, List<File> files, UploadSubscriberCallBack<T> uploadSubscriberCallBack) { MultipartBody.Builder builder = new MultipartBody.Builder(); if (files == null || files.size() == 0) { return builder.build(); } long content = 0; for (File file : files) { content += file.length(); } for (int i = 0; i < files.size(); i++) { UploadFileRequestBody uploadFileRequestBody = new UploadFileRequestBody<T>(content, files.get(i), uploadSubscriberCallBack); builder.addFormDataPart(name.get(i), files.get(i).getName(), uploadFileRequestBody); } if (paramsMap != null) { Set<String> params = paramsMap.keySet(); for (String paramKey : params) { if (paramKey != null) { String paramValue = paramsMap.get(paramKey); builder.addFormDataPart(paramKey, paramValue); } } } builder.setType(MultipartBody.FORM); return builder.build(); } } <file_sep>/RxUpload/rxupload/src/main/java/com/wen/rxupload/uploadfile/task/UploadFlag.java package com.wen.rxupload.uploadfile.task; /** * Created by zhangxiaowen on 2018/11/1. * UploadFlag参数集合 */ public class UploadFlag { public static final int START = 9990; //开始上传 public static final int STARTED = 9991; //上传中 public static final int FAIL = 9992; //失败 public static final int COMPLETE = 9993; //完成 } <file_sep>/RxUpload/rxupload/src/main/java/com/wen/rxupload/uploadfile/task/UploadMutiItem.java package com.wen.rxupload.uploadfile.task; import java.io.Serializable; import java.util.Map; import io.reactivex.disposables.Disposable; /** * Created by zhangxiaowen on 2018/11/1. * 上传操作所需构造的bean类 */ public class UploadMutiItem implements Serializable { private static final long serialVersionUID = 6594398131889838048L; private Class zClass;//retrofit 所需的接口对象 private String stringMethod;//上传文件的方法 private String stringKey;//上传文件所需的key 字符串 private Map<String, String> paramMap;//上传文件所需的其他参数的字符串 private Disposable disposable;//监听文件上传进度的Disposable private String urlFile;//上传文件的url public int progress = 0;//上传文件的进度记录 用于列表更新进度 public Class getzClass() { return zClass; } public void setzClass(Class zClass) { this.zClass = zClass; } public String getStringMethod() { return stringMethod; } public void setStringMethod(String stringMethod) { this.stringMethod = stringMethod; } public String getStringKey() { return stringKey; } public void setStringKey(String stringKey) { this.stringKey = stringKey; } public Map<String, String> getParamMap() { return paramMap; } public void setParamMap(Map<String, String> paramMap) { this.paramMap = paramMap; } public Disposable getDisposable() { return disposable; } public void setDisposable(Disposable disposable) { this.disposable = disposable; } public String getUrlFile() { return urlFile; } public void setUrlFile(String urlFile) { this.urlFile = urlFile; } } <file_sep>/RxUpload/settings.gradle include ':app', ':rxupload', ':base-lib-network' <file_sep>/RxUpload/rxupload/src/main/java/com/wen/rxupload/uploadfile/task/UploadController.java package com.wen.rxupload.uploadfile.task; /** * UploadController 上传回调的Controller */ public class UploadController { private Callback callback; public void handleClick(Callback callback) { this.callback = callback; } public interface Callback { void startUpload(); void startNowUpload(); void failUpload(); void Complete(UploadEvent event); } public void setEvent(UploadEvent event) { int flag = event.getFlag(); switch (flag) { case UploadFlag.START: callback.startUpload(); break; case UploadFlag.STARTED: callback.startNowUpload(); break; case UploadFlag.FAIL: callback.failUpload(); break; case UploadFlag.COMPLETE: callback.Complete(event); break; } } } <file_sep>/RxUpload/rxupload/src/main/java/com/wen/rxupload/uploadfile/task/UploadEventFactory.java package com.wen.rxupload.uploadfile.task; import static com.wen.rxupload.uploadfile.task.UploadFlag.COMPLETE; import static com.wen.rxupload.uploadfile.task.UploadFlag.FAIL; import static com.wen.rxupload.uploadfile.task.UploadFlag.START; import static com.wen.rxupload.uploadfile.task.UploadFlag.STARTED; /** * Created by zhangxiaowen on 2018/11/2. * 采用简单工厂设计模式提供UploadEvent事件实体类 */ public class UploadEventFactory { public static UploadEvent start(UploadStatus status) { return createEvent(START, status); } public static UploadEvent started(UploadStatus status) { return createEvent(STARTED, status); } public static UploadEvent failed(UploadStatus status, Throwable throwable) { return createEvent(FAIL, status, throwable); } public static UploadEvent completed(UploadStatus status) { return createEvent(COMPLETE, status); } private static UploadEvent createEvent(int flag, UploadStatus status, Throwable throwable) { UploadEvent event = createEvent(flag, status); event.setError(throwable); return event; } public static UploadEvent createEvent(int flag, UploadStatus status) { UploadEvent event = new UploadEvent(); event.setUploadStatus(status == null ? new UploadStatus() : status); event.setFlag(flag); return event; } } <file_sep>/RxUpload/base-lib-network/src/main/java/com/wen/network/bean/ResultException.java package com.wen.network.bean; import java.io.Serializable; /** * Created by wen on 2018/5/14. * 自定义错误返回 */ public class ResultException extends RuntimeException implements Serializable { private static final long serialVersionUID = 1441864083681083935L; private String errCode = ""; public ResultException(String errCode, String msg) { super(msg); this.errCode = errCode; } public String getErrCode() { return errCode; } } <file_sep>/RxUpload/rxupload/src/main/java/com/wen/rxupload/uploadfile/service/UploadFileService.java package com.wen.rxupload.uploadfile.service; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; import com.wen.rxupload.uploadfile.task.UploadEvent; import com.wen.rxupload.uploadfile.task.UploadTask; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.Semaphore; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; import io.reactivex.processors.BehaviorProcessor; import io.reactivex.processors.FlowableProcessor; import io.reactivex.schedulers.Schedulers; /** * Created by zhangxiaowen on 2018/11/1. * startService开启服务 * bindService 用户访问service中的方法等 */ public class UploadFileService extends Service { //用于传递最大并发线程参数 public static final String INTENT_KEY = "max_upload_number"; //自定义UploadBinder 返回service实例 private UploadBinder mBinder; //此Map用于返回进度的消息 用urlFile为唯一指定key private Map<String, FlowableProcessor<UploadEvent>> processorMap; //用于存储任务执行的队列 默认大小无限制 private BlockingQueue<UploadTask> uploadQueue; //java并发包下的类 用于控制线程执行的个数 private Semaphore semaphore; //上传task的列表 用urlFile为唯一指定key private Map<String, UploadTask> taskMap; private Disposable disposable; @Override public void onCreate() { super.onCreate(); //执行初始化操作 mBinder = new UploadBinder(); uploadQueue = new LinkedBlockingQueue<>(); processorMap = new ConcurrentHashMap<>(); taskMap = new ConcurrentHashMap<>(); } /** * 返回内部类binder对象 * * @param intent * @return */ @Nullable @Override public IBinder onBind(Intent intent) { //启动队列 startDispatch(); return mBinder; } /** * 在onStartCommand中初始化最大并发线程数 * * @param intent * @param flags * @param startId * @return */ @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null) { int maxUploadNumber = intent.getIntExtra(INTENT_KEY, 3); semaphore = new Semaphore(maxUploadNumber); } return super.onStartCommand(intent, flags, startId); } /** * 在队列里添加任务 * * @param uploadTask * @throws InterruptedException */ public void addUploadTask(UploadTask uploadTask) throws InterruptedException { //如果此任务已经在taskMap中存在 则不添加到队列中 boolean init = uploadTask.init(taskMap, processorMap); if (init) { uploadQueue.put(uploadTask); } } /** * 开始任务的调度 * ObservableEmitter 类似发射器的东西 用于发射事件 * Consumer 最小粒度的观察者 */ private void startDispatch() { disposable = Observable .create(new ObservableOnSubscribe<UploadTask>() { @Override public void subscribe(ObservableEmitter<UploadTask> emitter) throws Exception { UploadTask uploadTask; while (!emitter.isDisposed()) { try { uploadTask = uploadQueue.take(); } catch (InterruptedException e) { continue; } emitter.onNext(uploadTask); } emitter.onComplete(); } }) .subscribeOn(Schedulers.newThread()) .subscribe(new Consumer<UploadTask>() { @Override public void accept(UploadTask uploadTask) throws Exception { uploadTask.startUploadFile(semaphore); } }); } /** * FlowableProcessor 系统级别的处理器 线程安全 * 用来处理进度相应的消息 * Processor和Subject的作用是相同的。 * 关于Subject部分,RxJava1.x与RxJava2.x在用法上没有显著区别。其中Processor是RxJava2.x新增的,继承自Flowable * 所以其本身就是一个被观察者 * * @return * @aram url * <p> * 此方法用于创建urlFile对应的FlowableProcessor */ public FlowableProcessor<UploadEvent> receiveUploadEvent(String urlFile) { FlowableProcessor<UploadEvent> processor = createProcessor(urlFile); return processor; } private FlowableProcessor<UploadEvent> createProcessor(String urlFile) { if (processorMap.get(urlFile) == null) { FlowableProcessor<UploadEvent> processor = BehaviorProcessor.<UploadEvent>create().toSerialized(); processorMap.put(urlFile, processor); } return processorMap.get(urlFile); } /** * 再退出时 执行清空操作 */ public void clearAll() { uploadQueue.clear(); taskMap.clear(); processorMap.clear(); } /** * 退出请求 */ public void cancelUpload(String urlFile) { UploadTask uploadTask = taskMap.get(urlFile); if (uploadTask != null) { uploadTask.cancel(); } } /** * 用于对外暴露UploadFileService实例 * Binder extent Ibinder */ public class UploadBinder extends Binder { public UploadFileService getService() { return UploadFileService.this; } } } <file_sep>/RxUpload/rxupload/src/main/java/com/wen/rxupload/uploadfile/netHelper/UploadSubscriberCallBack.java package com.wen.rxupload.uploadfile.netHelper; import com.jakewharton.retrofit2.adapter.rxjava2.HttpException; import com.wen.network.bean.ResultException; import java.net.ConnectException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.concurrent.TimeoutException; import io.reactivex.subscribers.DisposableSubscriber; /** * Created by wen on 2018/5/14. * 自定义DisposableSubscriber(业务相关) * 采用适配器模式,去除不必要的接口方法 * 关于文件上传单独写UploadSubscriberCallBack回调和统一处理区别并去除耦合 */ public abstract class UploadSubscriberCallBack<T> extends DisposableSubscriber<T> { //w网络库 public static final String NET_ERROR = "网络不好,请确认网络重新连接"; public static final String NOT_KNOW_ERROR = "未知错误,请重新开启APP"; private long bytesWrittenTotal = 0; @Override public void onNext(T t) { onSuccess(t); } @Override public void onError(Throwable e) { e.printStackTrace(); //在这里做全局的错误处理 if (e instanceof HttpException || e instanceof ConnectException || e instanceof SocketTimeoutException || e instanceof TimeoutException || e instanceof UnknownHostException) { //网络错误 onFailure(new Throwable(NET_ERROR)); } else if (e instanceof ResultException) { onFailure(e); } else { //其他错误 onFailure(new Throwable(NOT_KNOW_ERROR)); } } //监听文件进度的改变 public void onProgressChange(long bytesWritten, long contentLength) { bytesWrittenTotal += bytesWritten; onProgress((int) (bytesWrittenTotal * 100 / contentLength)); } //上传进度回调 public abstract void onProgress(int progress); @Override public void onComplete() { } public abstract void onSuccess(T t); public abstract void onFailure(Throwable t); }
c47dd62033cf967ca4f3f073b21acda498c7b05c
[ "Java", "Gradle" ]
14
Java
loveAndroidAndroid/RxUpload
8dff1fe6df18f99adb483f3e133d53cc13e051f3
b1b3d95785a82fd1f25f2b5e15ef74e42d7d4d42
refs/heads/master
<repo_name>HoTaeWang/Earthquake<file_sep>/src/main/java/EarthQuake/App.java /* * This Java source file was generated by the Gradle 'init' task. */ package EarthQuake; public class App { public static void main(String[] args) { EarthQuakeClient client = new EarthQuakeClient(); System.out.println("========================= bigQuakes > 5.0 ==================================="); client.bigQuakes(); System.out.println("============================================================================="); System.out.println(" Near me "); client.closeToMe(); System.out.println("============================================================================="); System.out.println(" Depth "); client.quakeOfDepth(); System.out.println("============================================================================="); System.out.println("Filtering by Phrase in Title"); System.out.println("California at end"); client.quakeByPhrase(); } } <file_sep>/src/test/java/EarthQuake/EarthQuakeClientTest.java package EarthQuake; import org.junit.Test; import static org.junit.Assert.*; public class EarthQuakeClientTest { @Test public void testCreateCSV() { EarthQuakeClient client = new EarthQuakeClient(); //client.createCSV(); //assertError("app should have a list of earthquake", client.createCSV()); // App classUnderTest = new App(); // assertNotNull("app should have a greeting", classUnderTest.getGreeting()); } } <file_sep>/README.md # Earthquake Earthquake Location filtering sabioguru <EMAIL>
37a099dfe2f94dbb3e994c1ad2fe714f3a8d9e15
[ "Markdown", "Java" ]
3
Java
HoTaeWang/Earthquake
133cd182c82b38aac4067f7911f9933cd1102471
725f2eb91531017c0220a6388fcb7ec40b674dbe
refs/heads/master
<file_sep>package bwei.com.zhou3_demo; import android.animation.ObjectAnimator; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.nostra13.universalimageloader.core.ImageLoader; import java.util.List; import bwei.com.zhou3_demo.myapp.MyApp; public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private List<MainBean.DataBeanX.DataBean> list; private static final int ONE=0; private static final int TWO=1; private OnItemClickListener onItemClickListener; public MyAdapter(List<MainBean.DataBeanX.DataBean> list) { this.list = list; } @Override public int getItemViewType(int position) { if (list.get(position).getPics().size()==3){ return ONE; }else{ return TWO; } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType==ONE){ Log.d("11111","aaaa"); View view1 = LayoutInflater.from(parent.getContext()).inflate(R.layout.itme_two, parent, false); return new myViewHolder1(view1); }else{ View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.itme_layout, parent, false); return new myViewHolder(itemView); } } @Override public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) { if (holder instanceof myViewHolder){ final myViewHolder holder1= (myViewHolder) holder; holder1.tv.setText(list.get(position).getTitle()); holder1.tv2.setText(list.get(position).getTitle()); ImageLoader.getInstance().displayImage("http://365jia.cn/uploads/"+list.get(position).getPics().get(0),holder1.image,MyApp.getOptions()); holder1.image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("一张","posin++++++++"+position); ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(holder1.image, "alpha", 1f,0f,1f); objectAnimator.setDuration(5000); objectAnimator.start(); } }); holder1.mitemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (onItemClickListener!=null){ onItemClickListener.onItemClick(v,position); } return true; } }); }else{ final myViewHolder1 holder2 = (myViewHolder1) holder; ImageLoader.getInstance().displayImage("http://365jia.cn/uploads/"+list.get(position).getPics().get(0),holder2.imag1, MyApp.getOptions()); ImageLoader.getInstance().displayImage("http://365jia.cn/uploads/"+list.get(position).getPics().get(1),holder2.imag2, MyApp.getOptions()); ImageLoader.getInstance().displayImage("http://365jia.cn/uploads/"+list.get(position).getPics().get(2),holder2.imag3, MyApp.getOptions()); holder2.imag1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("第二张","posin++++++++"+position); ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(holder2.imag1, "alpha", 1f,0f,1f); objectAnimator.setDuration(5000); objectAnimator.start(); } }); holder2.imag2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("第三张","posin++++++++"+position); ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(holder2.imag2, "alpha", 1f,0f,1f); objectAnimator.setDuration(5000); objectAnimator.start(); } }); holder2.imag3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("第四张","posin++++++++"+position); ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(holder2.imag3, "alpha", 1f,0f,1f); objectAnimator.setDuration(5000); objectAnimator.start(); } }); } holder.itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (onItemClickListener!=null){ onItemClickListener.onItemClick(v,position); } return false; } }); } @Override public int getItemCount() { return list==null ? 0 :list.size(); } public class myViewHolder extends RecyclerView.ViewHolder { private final TextView tv,tv2; private final ImageView image; private View mitemView; public myViewHolder(final View itemView) { super(itemView); mitemView = itemView; tv = itemView.findViewById(R.id.itme_tv); tv2 = itemView.findViewById(R.id.itme_tv2); image = itemView.findViewById(R.id.itme_image); } } private class myViewHolder1 extends RecyclerView.ViewHolder { private ImageView imag1,imag2,imag3; public myViewHolder1(View view1) { super(view1); imag1 = view1.findViewById(R.id.itme_image0); imag2 = view1.findViewById(R.id.itme_image2); imag3 = view1.findViewById(R.id.itme_image3); } } public interface OnItemClickListener{ void onItemClick(View view,int position); } public void setOnItemClickListtener(OnItemClickListener onItemClickListener){ this.onItemClickListener=onItemClickListener; } } <file_sep>package bwei.com.zhou3_demo; import okhttp3.OkHttpClient; public class Model { private HttpUtils httputils; private String myurl="http://365jia.cn/news/api3/365jia/news/headline?page=1"; public void login(final getModelHttpIntence getModelHttpIntence){ httputils = HttpUtils.getIntence(); httputils.doGet(myurl, new HttpUtils.OkHttpIntence() { @Override public void getsuccceed(String json) { getModelHttpIntence.getsuccceed(json); } @Override public void geteeror(Exception error) { } }); } public interface getModelHttpIntence{ void getsuccceed(String json); void geteeror(Exception error); } }
519d5a418d7b6d9322fe588bfb3b73399e6dda16
[ "Java" ]
2
Java
yankuokuo/douju_demo
feb3fa7ebcef87203be60b95995a4f8de6687c52
81817389f167c9139c8bf097d9e1d7ce28f5eba2
refs/heads/master
<repo_name>iMega/compile-nasm<file_sep>/Dockerfile FROM alpine RUN apk add --update nasm binutils WORKDIR /data CMD ./run.sh<file_sep>/Makefile default: build @docker run --rm -v `pwd`:/data imega/nasm build: @docker build -t imega/nasm . <file_sep>/run.sh #!/usr/bin/env sh nasm -f elf64 hello.asm ld -s -o hello hello.o ./hello exit 0
86ba1b92c18ede8e1c00dd7710e97265056ba3d6
[ "Makefile", "Dockerfile", "Shell" ]
3
Dockerfile
iMega/compile-nasm
2b44c93070af9e014e6599deba25af0496962af4
00323634f9dc346378b0ffee89cdc68dff1940a8
refs/heads/master
<repo_name>latviancoder/3m5landing<file_sep>/index.html <!DOCTYPE html> <html lang="de"> <head> <meta charset="UTF-8"> <title>3m5 Landing Page</title> <link rel='stylesheet' href='//fonts.googleapis.com/css?family=Oswald:300,400,700' data-noprefix> <link rel="stylesheet" href="css/main.css" data-noprefix> <script src="js/jquery-1.11.2.min.js"></script> <script src="js/jquery.keyframes.js"></script> <script src="js/wow.min.js"></script> <script src="js/main.js"></script> <script src="http://127.0.0.1:12346/livereload.js?snipver=1"></script> </head> <body> <header> <div class="container"> <div class="header-logo"></div> <div class="header-contacts"> <div class="header-phone">+49(89) - 741 185 368</div> <div class="header-mail"><EMAIL></div> </div> </div> </header> <section class="promo-teaser"> <div class="container"> <h1 class="promo-heading">Ihr Spezialist für erfolgreiche <span>Typo3 Projekte</span></h1> <div class="promo-text-block"> <div class="heading">Suchen sie einen <br> Typo3 Experten?</div> <div class="list-container"> <div class="subheading">WARUM 3m5.?</div> <ul class="list"> <li>Einer der führenden TYPO3 Solution Partner in der DACH-Region</li> <li>TYPO3 Gold Member mit 12 Jahren Erfahrung</li> <li>Spezialist für globale eCMS-Projekte</li> <li>Scrum Master als Projektleiter</li> <li>Zertifizierter TYPO3 Solution Partner</li> </ul> </div> </div> <div class="promo-imac"> <div class="screen"> <div class="screen-animation-container"> <!--Slide deck must be duplicated to make it appear infinite with javascript--> <img class="screen-animation-slide" src="img/screen_slides/schunk.jpg"> <img class="screen-animation-slide" src="img/screen_slides/schunk2.jpg"> <img class="screen-animation-slide" src="img/screen_slides/schunk.jpg"> <img class="screen-animation-slide" src="img/screen_slides/schunk2.jpg"> </div> </div> </div> <img class="promo-typo3-gold" src="img/typo3_gold.png" alt="Typo3 Gold Member"> </div> </section> <section class="small-references"> <img class="reference-icon" src="img/references/ZDF.png"> <img class="reference-icon" src="img/references/Gardena.png"> <img class="reference-icon" src="img/references/kulmbacher.jpg"> <img class="reference-icon" src="img/references/ARD.png"> <img class="reference-icon" src="img/references/Goethe.png"> <img class="reference-icon" src="img/references/Schunk.png"> <img class="reference-icon" src="img/references/winterhalter.png"> <img class="reference-icon" src="img/references/wanzl.png"> <img class="reference-icon" src="img/references/UIM.png"> </section> <section class="contact"> <div class="container"> <div class="contact-text"> <h2>Kontakt zu einem unserer Scrum Master</h2> <p>Wir haben Ihr Interesse geweckt? Dann rufen Sie mich an. Ich freue mich von Ihnen zu hören.</p> </div> <div class="contact-by-email"> <p><NAME></p> <a href="mailto:<EMAIL>" class="email"><EMAIL></a> </div> <div class="contact-by-phone"> <p>oder telefonisch unter</p> <div class="phone">+49(89) - 741 185 368</div> </div> <div class="contact-photo"></div> </div> </section> <section class="typo3-projects"> <div class="typo3-projects-heading"> <div class="container">Unsere Typo3 Referenzen</div> </div> <div class="animated-projects-list"> <!--Gardena--> <div class="animated-project animated-project--gardena"> <div class="container"> <div class="heading">Weltweiter Rollout eCMS</div> <div class="description">29 Sprachen, 37 Ländern. Über eine eCMS werden hier pro Land 5 Portale verwaltet. Mehr als 130 Redakteure weltweit pflegen wöchentlich neue Inhalte in das Redaktionssystem. Die Einbíndung des kompletten Produktkataloges und ein Ersatzonlineshop lassen das Herz des Hobbygärtners höher schlagen. </div> <img class="logo" src="img/typo3_projects/gardena/logo.png"> <img class="all wow" data-wow-offset="200" src="img/typo3_projects/gardena/all.png"> </div> </div> <!--ZDF--> <div class="animated-project animated-project--zdf"> <div class="container"> <div class="heading">Heute Journal – hochskalierbares CMS für On-Air-Sendung</div> <div class="description">Das Flaggschiff des Zweiten Deutschen Fernsehens erschließt sich mit Relaunch und neuem eCMS jüngere Zielgruppen. Das System organisiert die Inhalte des Live-Web-TV-Formats, das parallel zur klassischen On-Air-Nachrichtensendung läuft. Da die Qualität eines eCMS maßgeblich von der Nutzerfreundlichkeit bei der Dateneingabe abhängt, wurde in diesem Projekt auf intuitive Tools, die den Online-Redakteuren ihre tägliche Arbeit erleichtern, Wert gelegt. </div> <img class="logo" src="img/typo3_projects/zdf/logo.png"> <img class="all wow" data-wow-offset="200" src="img/typo3_projects/zdf/all.png"> </div> </div> <!--Kulmbacher--> <div class="animated-project animated-project--kulmbacher"> <div class="container"> <div class="heading">Weltweiter eCMS Relaunch</div> <div class="description">Wie bei den meisten internationalen eCMS-Projekten zählten auch hier die sprach- und standortunabhängige Speicherung und Ausgabe der Inhalte zu den wichtigsten Herausforderungen. Daneben lag ein besonderes Augenmerk auf der flexiblen Verwaltung der mehrsprachigen Websites, was eine nahtlose Integration von Übersetzungsprozessen für die Lokalisierung der einzelnen Länderseiten erforderte. </div> <img class="logo" src="img/typo3_projects/kulmbacher/logo.png"> <img class="all wow" data-wow-offset="200" src="img/typo3_projects/kulmbacher/all.png"> </div> </div> <!--ARD--> <div class="animated-project animated-project--ard"> <div class="container"> <div class="heading">Hochperformantes eCMS <br/> für Sportberichterstattung in der ARD</div> <div class="description">Für die ARD-Sendergruppe realisierte 3m5. eine extrem leistungsfähige Live-Voting- Applikation, die während der Übertragungen von Spielen der Fußball-Bundesliga und der deutschen Nationalelf zum Einsatz kommt. Die maßgebliche Anforderung bei der Implementierung dieses CMS war Performance, denn die Verbindung mit den hochpopulären Fernsehübertragungen bringt außerordentlich hohe Leistungsanforderungen an das System mit sich, besonders in Fragen der Konzeption und des Anwendungsdesigns. </div> <img class="logo" src="img/typo3_projects/ard/logo.png"> <img class="all wow" data-wow-offset="200" src="img/typo3_projects/ard/all.png"> </div> </div> <!--UIM--> <div class="animated-project animated-project--uim"> <div class="container"> <div class="heading">eCMS Lead Agentur der United Internet Gruppe</div> <div class="description">Realisierung aller Websites für den Werbekundenbereich. Ein intuitiv zu bedienter Konfigurator zu allen Werbeformen der UIM Gruppe ermöglicht dem Mediakunde eine einfache und schnelle Buchung der benötigen Formate in allen erdenklichen Grössen und Formen. SO macht Media-buying Spass. </div> <img class="logo" src="img/typo3_projects/uim/logo.png"> <img class="all wow" data-wow-offset="200" src="img/typo3_projects/uim/all.png"> </div> </div> <!--GOETHE--> <div class="animated-project animated-project--goethe"> <div class="container"> <div class="heading">Online Dictionairy <br/>9 Sprachen, 280.000 Begriffe</div> <div class="description">Die Konzeption und Umsetzung dieser multilingualen CMS-Lösung stellte in mehrfacher Hinsicht hohe Anforderungen an die Entwickler. Es galt, die regionalen Nutzungsgewohnheiten zu beachten und technische Anforderungen wie die arabische Leserichtung „rechts-links“ zu realisieren, daneben war zudem ein sehr fein abgestuftes Rechte-Management zu implementieren. Neben der technischen Umsetzung begleitete 3m5. in diesem Projekt auch den Einführungsprozess samt Changemanagement. In diesem Rahmen fanden unter anderem Workshops und Schulungen für verschiedene Gruppen von Online-Redakteuren im Schulungszentrum von Rabat in Marokko statt. </div> <img class="logo" src="img/typo3_projects/goethe/logo.png"> <img class="all wow" data-wow-offset="200" src="img/typo3_projects/goethe/all.png"> </div> </div> <!--WANZL--> <div class="animated-project animated-project--wanzl"> <div class="container"> <div class="heading">Wanzl Headline</div> <div class="description">Wie bei den meisten internationalen eCMS-Projekten zählten auch hier die sprach- und standortunabhängige Speicherung und Ausgabe der Inhalte zu den wichtigsten Herausforderungen. Daneben lag ein besonderes Augenmerk auf der flexiblen Verwaltung der mehrsprachigen Websites, was eine nahtlose Integration von Übersetzungsprozessen für die Lokalisierung der einzelnen Länderseiten erforderte. </div> <img class="logo" src="img/typo3_projects/wanzl/logo.png"> <img class="all wow" data-wow-offset="200" src="img/typo3_projects/wanzl/all.png"> </div> </div> <!--SCHUNK--> <div class="animated-project animated-project--schunk"> <div class="container"> <div class="heading">Globaler eCMS-Rollout für Weltmarktführer</div> <div class="description">Neben dem Aufbau eines weltweiten eCMS moderierte 3m5. für das Unternehmen die Evaluierung einer passgenauen Content-Management-Software. Deren Kernstück ist ein vollständig integriertes Produktinformationsmanagement (PIM), in dem sämtliche Produktdetails einschließlich CAD-Zeichnungen für alle Produktvarianten online abrufbar und über eine intelligente Suchfunktion mit wenigen Klicks zu finden sind. </div> <img class="logo" src="img/typo3_projects/schunk/logo.png"> <img class="all wow" data-wow-offset="200" src="img/typo3_projects/schunk/all.png"> </div> </div> <!--Winterhalter--> <div class="animated-project animated-project--winterhalter"> <div class="container"> <div class="heading">Weltweites eCMS des Weltmarktführers <br/> für gewerbliche Spülsysteme <br/> 35 Sprachen, 25 Länder </div> <div class="description">Für den Weltmarktführer im Bereich gewerblicher Spülsysteme brachte 3m5. erfolgreich ein globales eCMS an den Start. Neben der Anbindung von Backoffice- und Drittsystemen lag ein besonderes Augenmerk auf der Konzeption eines Online-Produktkonfigurators. Das wichtigste Ziel dabei: Der komplette Katalog mit Hunderttausenden Artikelvarianten sollte so nutzerfreundlich wie möglich gestaltet werden und die Ingenieure der Partnerunternehmen mit drei Klicks zum gewünschten Produkt führen. </div> <img class="logo" src="img/typo3_projects/winterhalter/logo.png"> <img class="all wow" data-wow-offset="200" src="img/typo3_projects/winterhalter/all.png"> </div> </div> </div> </section> <footer>Copyright 2015 by 3m5.</footer> </body> </html><file_sep>/js/main.js new WOW().init(); $(function() { // Go left by width of one slide var step = $('.screen-animation-slide').width(); var slide_count = $('.screen-animation-slide').length / 2; // Slider animation function function animatePromoScreen(index) { $('.screen-animation-container').addClass('animated'); $('.screen-animation-container').css('left', -(index*step)); setTimeout(function() { if (index == slide_count) { // If we are at the last slide - return slider to the beginning without any animation // This is done to make slider appear infinite $('.screen-animation-container').removeClass('animated'); $('.screen-animation-container').css('left', '0px'); // Wait 10ms for changes in DOM, then animate setTimeout(animatePromoScreen.bind(null, 1), 10); } else { // Otherwise just animate one step further animatePromoScreen(index + 1); } }, 4000) } // Start animation from the first slide animatePromoScreen(1); });
039eef17a34de85560c11ef744f70d7aa6c71bae
[ "JavaScript", "HTML" ]
2
HTML
latviancoder/3m5landing
43b34e28ddeaaa1be554f16e788987366073494e
b57415f706e677df490277d7fc3c9e2472b78dca
refs/heads/master
<file_sep>#include <bits/stdc++.h> using namespace std; #define X first #define Y second int dx[4] = { 1, 0, -1, 0 }; int dy[4] = { 0, 1, 0, -1 }; int main(void) { ios::sync_with_stdio(0), cin.tie(0); int F; cin >> F; for (int i = 0; i < F; i++) { int board[50][50] = { 0, }; bool vis[50][50] = { 0, }; int M, N, K; cin >> M >> N >> K; for (int i = 0; i < K; i++) { int x, y; cin >> x >> y; board[x][y] = 1; } int bug = 0; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { if (board[i][j] == 0 || vis[i][j]) continue; bug++; queue<pair<int, int>> q; vis[i][j] = 1; q.push({ i, j }); while (!q.empty()) { pair<int, int> cur = q.front(); q.pop(); for (int dir = 0; dir < 4; dir++) { int nx = dx[dir] + cur.X; int ny = dy[dir] + cur.Y; if (nx < 0 || nx >= M || ny < 0 || ny >= N) continue; if (board[nx][ny] != 1 || vis[nx][ny]) continue; vis[nx][ny] = 1; q.push({ nx, ny }); } } } } cout << bug << '\n'; } }<file_sep>#include <bits/stdc++.h> using namespace std; int main(void) { ios::sync_with_stdio(0), cin.tie(0); int N, M; map<int, string> col; map<string, int> col2; string pokemon, ans; cin >> N >> M; for (int i = 1; i <= N; i++) { cin >> pokemon; col.insert(make_pair(i, pokemon)); col2.insert(make_pair(pokemon, i)); } for (int i = 1; i <= M; i++) { cin >> pokemon; if (atoi(pokemon.c_str()) == 0) { cout << col2[pokemon] << "\n"; } else { cout << col[atoi(pokemon.c_str())] << "\n"; } } }<file_sep>#include <bits/stdc++.h> using namespace std; #define MAX 68 string screen[MAX]; string ans; bool check(int row, int col, int num) { bool isSame = true; char start = screen[row][col]; for (int i = row; i < row + num; i++) { for (int j = col; j < col + num; j++) if (screen[i][j] != start) return false; } if (isSame) ans += start; return true; } void div(int row, int col, int num) { if (num == 0) return; bool isSame = check(row, col, num); if(!isSame) { num /= 2; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++){ if (i == 0 && j == 0) ans += "("; div(row + (num * i), col + (num * j), num); if (i == 1 && j == 1) ans += ")"; } } } } int main(void) { ios::sync_with_stdio(0), cin.tie(0); int N; cin >> N; for (int i = 0; i < N; i++) cin >> screen[i]; div(0, 0, N); cout << ans; } <file_sep>#include <bits/stdc++.h> using namespace std; int arr[500002]; stack<pair<int, int>> st; int main(void) { ios::sync_with_stdio(0), cin.tie(0); int n, height; cin >> n; cin >> height; st.push({ 0, height }); for (int i = 1; i < n; i++) { cin >> height; if (st.top().second < height) { while (!st.empty() && st.top().second < height) st.pop(); if (st.empty()) { arr[i] = 0; } else { arr[i] = st.top().first + 1; if (st.top().second == height) st.pop(); } } else { arr[i] = st.top().first + 1; } st.push({ i, height }); } for (int i = 0; i < n; i++) { cout << arr[i] << ' '; } }<file_sep>#include <bits/stdc++.h> using namespace std; #define X first #define Y second int box[1002][1002]; int dist[1002][1002]; int n, m; int dx[4] = { 1, 0, -1, 0 }; int dy[4] = { 0, 1, 0, -1 }; int main(void) { ios::sync_with_stdio(0), cin.tie(0); queue<pair<int, int>>Q; cin >> m >> n; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { cin >> box[i][j]; if (box[i][j] == 1) { Q.push({ i, j }); } if (box[i][j] == 0) dist[i][j] = -1; } while (!Q.empty()) { auto cur = Q.front(); Q.pop(); for (int dir = 0; dir < 4; dir++) { int nx = cur.X + dx[dir]; int ny = cur.Y + dy[dir]; if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue; if (dist[nx][ny] >= 0) continue; dist[nx][ny] = dist[cur.X][cur.Y] + 1; Q.push({ nx, ny }); } } int ans = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (dist[i][j] == -1) { cout << -1; return 0; } ans = max(ans, dist[i][j]); } } cout << ans; }
f7fe19a26aa9a0f084882f6790ed4e738db8234b
[ "C++" ]
5
C++
thisfetch/Study_ProblemSolving
79e7bc732255af1a737577c50ed6e19fd360fc46
6cb3172f36c1c787f31f870e38b446cb3a186d82
refs/heads/master
<repo_name>ViniciusFloriano/Notepad<file_sep>/BlocoDeNotas/MainWindow.xaml.cs using Microsoft.Win32; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace BlocoDeNotas { /// <summary> /// Interação lógica para MainWindow.xam /// </summary> public partial class MainWindow : Window { public ICommand AbrirArquivo { get; private set; } public MainWindow() { InitializeComponent(); this.DataContext = MainText; } string FileName = ""; private void SalvarArquivo() { if (FileName != "") { File.WriteAllText(FileName, MainText.Text); } else { SaveFileDialog saveFileDialog = new SaveFileDialog(); if (saveFileDialog.ShowDialog() == true) { FileName = saveFileDialog.FileName; File.WriteAllText(saveFileDialog.FileName, MainText.Text); } } } private void SalvarComo_Click(object sender, RoutedEventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); if (saveFileDialog.ShowDialog() == true) { FileName = saveFileDialog.FileName; File.WriteAllText(saveFileDialog.FileName, MainText.Text); } } private void Salvar_Click(object sender, RoutedEventArgs e) { if(FileName != "") { File.WriteAllText(FileName, MainText.Text); } else { SaveFileDialog saveFileDialog = new SaveFileDialog(); if (saveFileDialog.ShowDialog() == true) { FileName = saveFileDialog.FileName; File.WriteAllText(saveFileDialog.FileName, MainText.Text); } } } private void Abrir_Click(object sender, RoutedEventArgs e) { OpenFileDialog op = new OpenFileDialog(); if (op.ShowDialog() == true) { MainText.Text = File.ReadAllText(op.FileName); FileName = op.FileName; } } } } <file_sep>/README.md # Notepad Windows notepad in C# WPF
72dfab03cc435ea8703444c684e8a2d497d2f7ff
[ "Markdown", "C#" ]
2
C#
ViniciusFloriano/Notepad
e8006c49e0e3460141291dea2cdb5c6b3219043b
d02dc12c3dc689bdf08d70d0d56ad93e0e99456f
refs/heads/master
<repo_name>divyaswormakai/QRApp<file_sep>/backend/models/IndoorForm.js const mongoose = require('mongoose'); const { Schema } = mongoose; const IndoorFormSchema = new Schema({ vendorID: { type: Schema.Types.ObjectId, ref: 'Vendor', required: true, }, email: { type: String, required: true, }, fullName: { type: String, required: true, }, dateOfVisit: { type: Date, required: true, default: Date.now, }, timeOfVisit: { type: String, required: true, }, }); IndoorFormSchema.set('toJSON', { transform: (document, returnedObject) => { returnedObject.id = returnedObject._id.toString(); delete returnedObject._id; delete returnedObject.__v; }, }); module.exports = mongoose.model('IndoorForm', IndoorFormSchema); <file_sep>/backend/models/Form.js const mongoose = require('mongoose'); const { Schema } = mongoose; const FormSchema = new Schema({ vendorID: { type: Schema.Types.ObjectId, ref: 'Vendor', required: true, }, email: { type: String, required: true, }, fullName: { type: String, required: true, }, phoneNumber: { type: String, required: true, }, dateOfVisit: { type: Date, required: true, default: Date.now, }, timeOfVisit: { type: String, required: true, }, noOfPeopleInGroup: { type: Number, }, comments: { type: String, }, }); FormSchema.set('toJSON', { transform: (document, returnedObject) => { returnedObject.id = returnedObject._id.toString(); delete returnedObject._id; delete returnedObject.__v; }, }); module.exports = mongoose.model('Form', FormSchema); <file_sep>/backend/middleware/schoolAuth.js const { request, response } = require('express'); const jwt = require('jsonwebtoken'); const { secret } = require('../config/keys'); const School = require('../models/School'); const Admin = require('../models/Admin'); module.exports = async (request, response, next) => { try { const token = request.header('x-auth-token'); if (!token) { throw new Error('You are not authorized. Use a admin account.'); } const decodedToken = jwt.verify(token, secret); const school = await School.findById(decodedToken.id); if (!school) { const admin = await Admin.findById(decodedToken.id); if (!admin) { throw new Error('You are not authorized. Use an admin account.'); } } request.school = school; next(); } catch (err) { return response.status(401).send({ error: err.message }); } }; <file_sep>/backend/controller/awsS3.js const AWS = require('aws-sdk'); const bucketName = 'contacttracingbucket'; const fs = require('fs'); const async = require('async'); AWS.config.loadFromPath('./aws.json'); AWS.config.getCredentials(function (err) { if (err) { console.log(err.stack); exit(0); } }); AWS.config.update({ region: 'eu-west-1' }); const s3 = new AWS.S3({ region: 'eu-west-1' }); const createMainBucket = (callback) => { // Create the parameters for calling createBucket const bucketParams = { Bucket: bucketName, }; s3.headBucket(bucketParams, function (err, data) { if (err) { console.log('ErrorHeadBucket', err); s3.createBucket(bucketParams, function (err, data) { if (err) { console.log('Error', err); callback(err, null); } else { callback(null, data); } }); } else { callback(null, data); } }); }; const createItemObject = (callback) => { const params = { Bucket: bucketName, Key: `${imageName}`, ACL: 'public-read', Body: image, }; s3.putObject(params, function (err, data) { if (err) { console.log('Error uploading image: ', err); callback(err, null); } else { console.log('Successfully uploaded image on S3', data); callback(null, data); } }); }; exports.upload = (req, res, next) => { console.log(req.files); var tmp_path = req.files[0].path; // console.log("item", req.files.file) image = fs.createReadStream(tmp_path); imageName = req.files[0].filename; console.log(imageName); async.series([createMainBucket, createItemObject], (err, result) => { if (err) { console.log(err); throw new Error('Could not upload file.'); // return res.status(400).json({ error: 'Error in async' }); } else { console.log(result); next(); } }); }; <file_sep>/backend/controller/awsSES.js const AWS = require('aws-sdk'); const nodemailer = require('nodemailer'); const fs = require('fs'); const Form = require('../models/Form'); const Vendor = require('../models/Vendor'); const School = require('../models/School'); const SchoolForm = require('../models/SchoolForm'); const moment = require('moment'); // AWS configuration AWS.config.loadFromPath('./aws.json'); AWS.config.getCredentials(function (err) { if (err) { console.log(err.stack); exit(0); } }); AWS.config.update({ region: 'us-west-2' }); const ses = new AWS.SES({ apiVersion: '2010-12-01' }); exports.emailViaAWS_SES = function async(savedForm) { const params = { Destination: { ToAddresses: [savedForm.email], // Email address/addresses that you want to send your email }, Message: { Body: { Html: { // HTML Format of the email Charset: 'UTF-8', Data: `<html> <body> <h3>Dear ${savedForm.fullName},</h3> <p> <b>Data Protection Notice:</b> Your personal data is being collected on this form in order to help prevent the spread of COVID-19 in <b><i>"${ savedForm.vendorID.vendorName }"</i></b> and to protect our staff and our customers. Your personal data is being processed in accordance with Article 9(2)(i) of the General Data Protection Regulation, and Section 53 of the Data Protection Act 2018. The information you provide on this form will not be used for any other purpose, and will be strictly confidential. The form will be accessible only to administrator of e-society and the vendor for whom you have filled the form. The Health Act 1947 (Section 31A - Temporary Restrictions) (Covid-19) (No. 2) Regulations 2021 (SI 217 of 2021) provide that a specified person shall retain and make available records made under paragraph (2) for the purposes of inspection by a member of the <NAME> acting in the course of his or her duties under these Regulations, or by a person appointed by the Health Service Executive for the purposes of the programme commonly known as the Covid-19 Contact Management Programme, for a period of 28 days after the records have been made. Should a confirmed case arise, the Contact Management Programme will take the necessary action to contact those who need to be contacted. </p> <p>Thank you for filling out the contact tracing form for ${ savedForm.vendorID.vendorName }. The following table shows the information that was collected.</p> <table> <tr> <td><b>Full Name</b></td> <td>${savedForm.fullName}</td> </tr> <tr> <td><b>Email</b></td> <td>${savedForm.email}</td> </tr> <tr> <td><b>Date Of Visit</b></td> <td>${moment(savedForm.dateOfVisit).format('DD-MM-YYYY')}</td> </tr> <tr> <td><b>Time Of visit</b></td> <td>${savedForm.timeOfVisit}</td> </tr> <tr> <td><b>How many people are there in your group/table?</b></td> <td>${savedForm.noOfPeopleInGroup || ''}</td> </tr> <tr> <td><b>Comment</b></td> <td>${savedForm.comments || ''}</td> </tr> </table> <br/> <i>If you have any queries, please feel free to contact the venue.</i> <br/> <p>Thank you.</p> <div style="background:#e7e9eb;"> <b>Powered by:</b><br/> <a href="https://e-society.ie"><b>E-Society.ie</b></a> </div> </body> </html>`, }, Text: { Charset: 'UTF-8', Data: 'Thanks for reaching out. This is a test mail.', }, }, Subject: { Charset: 'UTF-8', Data: 'Thanks for filling out the contact form', }, }, Source: '<EMAIL>', }; const sendEmailReceiver = ses.sendEmail(params).promise(); sendEmailReceiver .then((data) => { console.log('email submitted to SES', data); }) .catch((error) => { console.log(error); res.status(404).send({ message: 'Failed to send !', }); }); }; exports.vendorEmailAWS_SES = async () => { const now = new Date(); const yesterday = new Date(); yesterday.setDate(now.getDate() - 1); // Yesterday to get data from yesterday const today = new Date( yesterday.getFullYear(), yesterday.getMonth(), yesterday.getDate() ); const todayString = `${today.getFullYear()}/${ today.getMonth() + 1 }/${now.getDate()}`; const forms = await Form.find({ dateOfVisit: { $gt: today } }).populate( 'vendorID' ); const vendors = await Vendor.find({ active: true }).select([ 'vendorName', 'vendorEmail', ]); const emailBodyForVendors = {}; vendors.forEach((vendor) => { emailBodyForVendors[vendor.vendorName] = { email: vendor.vendorEmail, body: '', }; }); const activeVendorList = Object.keys(emailBodyForVendors); forms.forEach((form) => { if ( form.vendorID && form.vendorID.vendorName && activeVendorList.includes(form.vendorID.vendorName) ) { if (emailBodyForVendors[form.vendorID.vendorName].body.length <= 0) { emailBodyForVendors[form.vendorID.vendorName].body = ` <html> <head> <style> table, th, td { border: 1px solid black; } </style> </head> <body> <h2>Hello ${form.vendorID.vendorName},</h2> <p>The forms that heve been filled on the date ${todayString} is as follows:</p> <table> <thead> <tr> <th>Full Name</th> <th>Email</th> <th>Date Of Visit</th> <th>Time Of Visit</th> <th>Contact Number</th> <th>How many people were there in your table/group?</th> <th>Comments</th> </tr> </thead> <tbody> <tr> <td>${form.fullName}</td> <td>${form.email}</td> <td>${moment(form.dateOfVisit).format('DD-MM-YYYY')}</td> <td>${form.timeOfVisit}</td> <td>${form.phoneNumber || ''}</td> <td>${form.noOfPeopleInGroup}</td> <td>${form.comments || ''}</td> </tr> `; } else { emailBodyForVendors[form.vendorID.vendorName].body += ` <tr> <td>${form.fullName}</td> <td>${form.email}</td> <td>${moment(form.dateOfVisit).format('DD-MM-YYYY')}</td> <td>${form.timeOfVisit}</td> <td>${form.phoneNumber || ''}</td> <td>${form.noOfPeopleInGroup}</td> <td>${form.comments || ''}</td> </tr> `; } } }); activeVendorList.forEach((vendorName) => { if (emailBodyForVendors[vendorName].body.length > 0) { emailBodyForVendors[vendorName].body += ` </tbody> </table> <p>You can get the entire list by visiting our portal built for you or by contacting our adminstrator.</p> <i>Regards,</i><br/> <a href="https://e-society.ie"><b>E-Society.ie</b></a> </body> <footer> </footer> </html> `; const params = { Destination: { ToAddresses: [emailBodyForVendors[vendorName].email], }, Message: { Body: { Html: { // HTML Format of the email Charset: 'UTF-8', Data: emailBodyForVendors[vendorName].body, }, Text: { Charset: 'UTF-8', Data: `List of forms for the day - ${todayString}`, }, }, Subject: { Charset: 'UTF-8', Data: `List of forms for the day - ${todayString}`, }, }, Source: '<EMAIL>', }; const sendEmailReceiver = ses.sendEmail(params).promise(); sendEmailReceiver .then((data) => { console.log('email submitted to SES', data); }) .catch((error) => { console.log(error); res.status(404).send({ message: 'Failed to send !', }); }); } }); }; exports.indorEmailviaAWS_SES = async (formContent, res) => { let transporter = nodemailer.createTransport({ SES: ses, }); let attachments = []; let vendorAttachments = []; if (formContent.certificate) { attachments.push({ filename: formContent.fullName.split(' ')[0] + '-' + formContent.certificate.filename, content: fs.createReadStream(formContent.certificate.path), }); vendorAttachments.push({ filename: formContent.fullName.split(' ')[0] + '-' + formContent.certificate.filename, content: fs.createReadStream(formContent.certificate.path), }); } if (formContent.identity) { attachments.push({ filename: formContent.fullName.split(' ')[0] + '-' + formContent.identity.filename, content: fs.createReadStream(formContent.identity.path), }); vendorAttachments.push({ filename: formContent.fullName.split(' ')[0] + '-' + formContent.identity.filename, content: fs.createReadStream(formContent.identity.path), }); } // send mail with defined transport object await transporter.sendMail({ from: '<EMAIL>', to: formContent.email, subject: `Ref: ${ formContent.refNo || '' }. Thanks for Uploading Verification Documents`, // Subject line html: `<html> <body> <h3>Dear ${formContent.fullName},</h3> <p> <b>Data Protection Notice:</b> <br/> Personal data contained in a proof of immunity shall be processed only for the purpose of accessing and verifying the information included in such proof of immunity in connection with the admittance of permitted persons to relevant indoor premises. </p> <p>Thank you for filling out the verification form for ${ formContent.vendor.vendorName }. The following table shows the information that is checked.</p> <table> <tr> <td><b>Full Name</b></td> <td>${formContent.fullName}</td> </tr> <tr> <td><b>Email</b></td> <td>${formContent.email}</td> </tr> <tr> <td><b>Date Of Visit</b></td> <td>${moment(formContent.dateOfVisit).format('DD-MM-YYYY')}</td> </tr> <tr> <td><b>Time Of visit</b></td> <td>${formContent.timeOfVisit}</td> </tr> <tr> <td><b>Reference Number</b></td> <td>${formContent.refNo}</td> </tr> </table> <br/> <i>If you have any queries, please feel free to contact the venue.</i> <br/> <p>Thank you.</p> <div style="background:#e7e9eb;"> <b>Powered by:</b><br/> <a href="https://e-society.ie"><b>E-Society.ie</b></a> </div> </body> </html>`, // html version attachments: [...attachments], }); await transporter.sendMail({ from: '<EMAIL>', to: formContent.vendor.vendorEmail, subject: `Ref: ${formContent.refNo || ''}. Details of ${ formContent.fullName } for entry at ${formContent.dateOfVisit},${formContent.timeOfVisit}`, // Subject line html: `<html> <body> <h3>Dear ${formContent.vendor.vendorName},</h3> <p> <b>Data Protection Notice:</b> <br/> Personal data contained in a proof of immunity shall be processed only for the purpose of accessing and verifying the information included in such proof of immunity in connection with the admittance of permitted persons to relevant indoor premises. </p> <p>Following are the details of ${formContent.fullName}.</p> <table> <tr> <td><b>Full Name</b></td> <td>${formContent.fullName}</td> </tr> <tr> <td><b>Email</b></td> <td>${formContent.email}</td> </tr> <tr> <td><b>Date Of Visit</b></td> <td>${moment(formContent.dateOfVisit).format('DD-MM-YYYY')}</td> </tr> <tr> <td><b>Time Of visit</b></td> <td>${formContent.timeOfVisit}</td> </tr> <tr> <td><b>Reference Number</b></td> <td>${formContent.refNo}</td> </tr> </table> <br/> <i>If you have any queries, please feel free to contact the venue.</i> <br/> <p>Thank you.</p> <div style="background:#e7e9eb;"> <b>Powered by:</b><br/> <a href="https://e-society.ie"><b>E-Society.ie</b></a> </div> </body> </html>`, // html version attachments: [...vendorAttachments], }); // console.log('Message sent: %s', info.messageId); // console.log('To vendor', toVendor.messageId); }; exports.schoolFormEmail_SES = async (savedForm) => { const params = { Destination: { ToAddresses: [savedForm.email], // Email address/addresses that you want to send your email }, Message: { Body: { Html: { // HTML Format of the email Charset: 'UTF-8', Data: `<html> <body> <h3>Dear ${savedForm.fullName},</h3> <p> <b> Data Protection Notice:</b> Your personal data is being collected for Covid-19 contact tracing. The information you provide on this form will not be used for any other purpose. Your information will be kept for 28 days in accordance with: The Health Act 1947 (Section 31A - Temporary Restrictions) (Covid-19) (No. 2) Regulations 2021 (SI 217 of 2021). <br/> </p> </p> <p>Thank you for filling out the contact tracing form for ${ savedForm.schoolID.schoolName }. The following table shows the information that was collected.</p> <table> <tr> <td><b>Full Name</b></td> <td>${savedForm.fullName}</td> </tr> <tr> <td><b>Email</b></td> <td>${savedForm.email}</td> </tr> <tr> <td><b>Student ID</b></td> <td>${savedForm.studentID || ''}</td> </tr> <tr> <td><b>Contact</b></td> <td>${savedForm.phoneNumber}</td> </tr> <tr> <td><b>Date Of Visit</b></td> <td>${moment(savedForm.dateOfVisit).format('DD-MM-YYYY')}</td> </tr> <tr> <td><b>Time Of visit</b></td> <td>${savedForm.timeOfVisit}</td> </tr> <tr> <td><b>Room Number</b></td> <td>${savedForm.roomNumber}</td> </tr> </table> <br/> <p>Thank you.</p> <div style="background:#e7e9eb;"> <b>Powered by:</b><br/> <a href="https://e-society.ie"><b>E-Society.ie</b></a> </div> </body> </html>`, }, Text: { Charset: 'UTF-8', Data: 'Thanks for reaching out. This is a test mail.', }, }, Subject: { Charset: 'UTF-8', Data: 'Thanks for filling out the contact form.', }, }, Source: '<EMAIL>', }; const sendEmailReceiver = ses.sendEmail(params).promise(); sendEmailReceiver .then((data) => { console.log('email submitted to SES', data); }) .catch((error) => { console.log(error); res.status(404).send({ message: 'Failed to send !', }); }); }; exports.schoolFormsForSchool_SES = async () => { try { let transporter = nodemailer.createTransport({ SES: ses, }); const schools = await School.find(); await schools.forEach(async (school) => { school = school.toJSON(); // Yesterday to get data from yesterday const today = moment().subtract(1, 'day').toISOString(); const forms = await SchoolForm.find({ schoolID: school.id, dateOfVisit: { $gt: today }, }).populate('schoolID'); // Make groups classified by the room number let groupedForms = {}; await forms.forEach((form) => { if (groupedForms[form.roomNumber]) { groupedForms[form.roomNumber].push(form); } else { groupedForms[form.roomNumber] = [form]; } }); await Object.keys(groupedForms).forEach(async (group) => { let bodyTableText = ''; groupedForms[group].forEach((form) => { bodyTableText += ` <tr> <td>${form.fullName}</td> <td>${form.email}</td> <td>${form.phoneNumber}</td> <td>${moment(form.dateOfVisit).format('DD-MM-YYYY')}</td> <td>${form.timeOfVisit}</td> <td>${form.studentID}</td> <td>${form.roomNumber}</td> </tr> `; }); await transporter.sendMail({ from: '<EMAIL>', to: school.schoolEmail, subject: `Room:${group} for ${moment().format('DD-MM-YYYY')}`, html: ` <html> <head> <style> table, th, td { border: 1px solid black; } </style> </head> <body> <h2>Hello ${school.schoolName},</h2> <p>The forms that heve been filled on the date ${moment().format( 'DD-MM-YYYY' )} for ${group} is as follows:</p> <table> <thead> <tr> <th>Full Name</th> <th>Email</th> <th>Contact Number</th> <th>Date Of Visit</th> <th>Time Of Visit</th> <th>Student Number</th> <th>Room Number</th> </tr> </thead> <tbody> ${bodyTableText} </tbody> </table> </body> </html> `, }); }); }); } catch (error) { console.log(error); } }; <file_sep>/backend/routes/LoginRoute.js const express = require('express'); const router = express.Router(); const bcrypt = require('bcryptjs'); const Vendor = require('../models/Vendor'); const Admin = require('../models/Admin'); const School = require('../models/School'); const { secret } = require('../config/keys'); const jwt = require('jsonwebtoken'); // @Route POST api/login/vendor // @desc Login for vendor // @access Public router.post('/vendor', async (req, res) => { try { const { vendorEmail, password } = req.body; const vendor = await Vendor.findOne({ vendorEmail, }); if (!vendor) { throw new Error('Could not find user'); } const isPasswordMatch = await bcrypt.compare(password, vendor.password); if (!isPasswordMatch) { throw new Error('Password do not match'); } if (!vendor.active) { return res.status(201).json({ message: 'You have been inactive, please contact the admin to reactivate the account.', }); } const tokenDetails = { email: vendor.vendorEmail, id: vendor._id, name: vendor.vendorName, }; const token = jwt.sign(tokenDetails, secret); return res.status(200).send({ token, vendor: vendor.toJSON() }); } catch (err) { return res.status(400).json({ error: 'Could not load the vendor data.' }); } }); // @Route POST api/login/admin // @desc Login for admin // @access Public router.post('/admin', async (req, res) => { try { const { username, password } = req.body; const admin = await Admin.findOne({ username, }); if (!admin) { throw new Error('Could not find admin with that username.'); } const isPasswordMatch = await bcrypt.compare(password, admin.password); if (!isPasswordMatch) { throw new Error('Password do not match.'); } const adminDetails = { username: admin.username, id: admin._id, }; const token = jwt.sign(adminDetails, secret); return res.status(200).send({ token }); } catch (err) { return res.status(400).json({ error: err.message }); } }); // @Route POST api/login/school // @desc Login for school // @access Public router.post('/school', async (req, res) => { try { const { schoolEmail, password } = req.body; const school = await School.findOne({ schoolEmail, }); if (!school) { throw new Error('Could not find user'); } const isPasswordMatch = await bcrypt.compare(password, school.password); if (!isPasswordMatch) { throw new Error('Password do not match'); } const tokenDetails = { email: school.vendorEmail, id: school._id, name: school.vendorName, }; const token = jwt.sign(tokenDetails, secret); return res.status(200).send({ token, school: school.toJSON() }); } catch (err) { return res.status(400).json({ error: 'Could not load the vendor data.' }); } }); module.exports = router; <file_sep>/frontend/nuxt.config.js export default { // Global page headers: https://go.nuxtjs.dev/config-head head: { title: 'Contact Form', htmlAttrs: { lang: 'en', }, meta: [ { charset: 'utf-8' }, { name: 'viewport', content: 'width=device-width, initial-scale=1' }, { hid: 'description', name: 'description', content: 'COVID Contact Tracing form', }, { hid: 'description', name: 'description', content: 'Powered by E-Society', }, ], link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }], }, // Global CSS: https://go.nuxtjs.dev/config-css css: ['ant-design-vue/dist/antd.css'], // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins plugins: ['@/plugins/antd-ui', '@/plugins/axios'], // Auto import components: https://go.nuxtjs.dev/config-components components: true, // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules buildModules: [], // Modules: https://go.nuxtjs.dev/config-modules modules: [ // https://go.nuxtjs.dev/axios '@nuxtjs/axios', ['cookie-universal-nuxt', { alias: 'cookies' }], ], //axios axios: { baseURL: process.env.BASEURL || 'https://form.e-society.ie/api/', }, // Build Configuration: https://go.nuxtjs.dev/config-build build: {}, middleware: ['auth', 'adminAuth', 'vendorAuth','schoolAuth'], } <file_sep>/backend/routes/VendorRoute.js const express = require('express'); const router = express.Router(); const Vendor = require('../models/Vendor'); // @Route POST api/vendor/:id // @desc Get individual vendor // @access Public router.post('/:id', async (req, res) => { try { const id = req.params.id; const vendor = await Vendor.findById(id); if (!vendor) { return res .status(400) .json({ error: 'Could not find vendor data for id:' + id }); } return res.status(200).json(vendor.toJSON()); } catch (err) { return res.status(400).json({ error: 'Could not load the vendor data.' }); } }); module.exports = router; <file_sep>/frontend/middleware/auth.js import { LOCAL_STORAGE_ROLE_TYPE, LOCAL_STORAGE_VENDOR_ID, } from '../utils/constants' export default function ({ app, redirect }) { if (app.context.app.$cookies.get(LOCAL_STORAGE_ROLE_TYPE) === 'vendor') { redirect(`/vendor/${app.context.app.$cookies.get(LOCAL_STORAGE_VENDOR_ID)}`) } else if ( app.context.app.$cookies.get(LOCAL_STORAGE_ROLE_TYPE) === 'admin' ) { redirect(`/vendor`) } } <file_sep>/backend/server.js // Import the packages const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const cors = require('cors'); const path = require('path'); const morgan = require('morgan'); const multer = require('multer'); require('dotenv').config(); // Cron job import const cron = require('node-cron'); // Create an instance for express const app = express(); // Importing the routes const VendorRoute = require('./routes/VendorRoute'); const FormRoute = require('./routes/FormRoute'); const AdminRoute = require('./routes/AdminRoute'); const LoginRoute = require('./routes/LoginRoute'); const ErrorRoute = require('./routes/ErrorRoute'); const SchoolRoute = require('./routes/SchoolRoute'); // Middlewares const adminAuth = require('./middleware/adminAuth'); // AWS Service const awsSES = require('./controller/awsSES'); // purgeData servce const purgeData = require('./controller/purgeData'); app.use( morgan(':method :url :status :res[content-length] - :response-time ms') ); // Apply the bodyParser middleware, to get json data from requests (Body) app.use(bodyParser.json()); app.use(cors()); app.use(express.json()); app.set('view engine', 'jade'); app.use(express.urlencoded({ extended: false })); app.use(express.static(path.join(__dirname, 'build'))); // Apply the routes app.use('/api/uploads', express.static(path.join(`${__dirname}/uploads`))); app.use('/api/logos', express.static(path.join(`${__dirname}/logos`))); app.use('/api/form', FormRoute); app.use('/api/login', LoginRoute); app.use('/api/vendor', VendorRoute); app.use('/api/school', SchoolRoute); app.use('/api/admin', adminAuth, AdminRoute); app.use('/api/*', ErrorRoute); app.use('*', (req, res) => res.sendFile(path.join(`${__dirname}/build`, 'index.html')) ); // Get the mongoURI for database const db = require('./config/keys').mongoURI; const { exit } = require('process'); // Connecting with database mongoose .connect(db, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, }) // If all run ok, console log the message .then(() => console.log('MongoDB connected')) // For console log any error .catch((err) => console.log(err)); // Port declaration const port = process.env.PORT || 3001; // Init the express.js server app.listen(port, () => console.log(`Server running on ${port}`)); // Schedule cron job cron.schedule('0 23 * * *', () => { // SEND MAIL TO ALL ACTIVE VENDORS WITH LIST OF FORMS THAT THEY HAVE BEEN SUBMITTED awsSES.vendorEmailAWS_SES(); // SEND MAIL TO SCHOOLS awsSES.schoolFormsForSchool_SES(); // PURGE OLD DATA purgeData.purgeOldData(); }); <file_sep>/frontend/utils/constants.js export const VENDOR_COLUMNS = [ { dataIndex: 'vendorName', key: 'vendorName', title: 'Vendor Name', scopedSlots: { customRender: 'vendorName' }, width: 200, }, { dataIndex: 'vendorLocation', key: 'vendorLocation', title: 'Vendor Location', width: 200, }, { dataIndex: 'vendorEmail', key: 'vendorEmail', title: 'Vendor Email', width: 200, }, { dataIndex: 'vendorContact', key: 'vendorContact', title: 'Vendor Contact', width: 200, }, { dataIndex: 'vendorSecondaryContact', key: 'vendorSecondaryContact', title: 'Vendor Secondary Contact', width: 200, }, { title: 'Action', key: 'action', scopedSlots: { customRender: 'action' }, width: 200, }, ] export const SCHOOL_COLUMNS = [ { dataIndex: 'logoURL', key:'logoURL', title:"Logo", scopedSlots: {customRender: 'logo'}, width: 200 }, { dataIndex: 'schoolName', key: 'schoolName', title: 'School Name', scopedSlots: { customRender: 'schoolName' }, width: 200, }, { dataIndex: 'schoolLocation', key: 'schoolLocation', title: 'School Location', width: 200, }, { dataIndex: 'schoolEmail', key: 'schoolEmail', title: 'School Email', width: 200, }, { dataIndex: 'schoolContact', key: 'schoolContact', title: 'School Contact', width: 200, }, { title: 'Action', key: 'action', scopedSlots: { customRender: 'action' }, width: 200, }, ] export const FORMS_ADMIN_COLUMNS = [ { dataIndex: 'id', key: 'id', title: 'ID', scopedSlots: { customRender: 'formID' }, width: 200, }, { dataIndex: 'fullName', key: 'fullName', title: '<NAME>', scopedSlots: { customRender: 'fullName' }, width: 200, }, { dataIndex: 'phoneNumber', key: 'phoneNumber', title: 'Phone Number', width: 200, }, { dataIndex: 'email', key: 'email', title: 'Email', width: 200, }, { dataIndex: 'vendorName', key: 'vendorName', title: 'Vendor Name', scopedSlots: { customRender: 'vendorName' }, width: 200, }, { dataIndex: 'dateOfVisit', key: 'dateOfVisit', title: 'Date of Visit', scopedSlots: { customRender: 'dateOfVisit' }, width: 200, }, { dataIndex: 'timeOfVisit', key: 'timeOfVisit', title: 'Time of Visit', width: 200, }, ] export const SCHOOL_FORMS_ADMIN_COLUMNS = [ { dataIndex: 'id', key: 'id', title: 'ID', scopedSlots: { customRender: 'formID' }, width: 50, }, { dataIndex: 'fullName', key: 'fullName', title: 'Full Name', scopedSlots: { customRender: 'fullName' }, width: 200, }, { dataIndex: 'phoneNumber', key: 'phoneNumber', title: 'Phone Number', width: 200, }, { dataIndex: 'email', key: 'email', title: 'Email', width: 200, }, { dataIndex: 'studentID', key: 'studentID', title: 'Student ID', width: 200, }, { dataIndex: 'roomNumber', key: 'roomNumber', title: 'Room Number', width: 200, }, { dataIndex: 'dateOfVisit', key: 'dateOfVisit', title: 'Date of Visit', scopedSlots: { customRender: 'dateOfVisit' }, width: 200, }, { dataIndex: 'timeOfVisit', key: 'timeOfVisit', title: 'Time of Visit', width: 200, }, ] export const LOCAL_STORAGE_TOKEN = 'scanMeToken' export const LOCAL_STORAGE_ROLE_TYPE = 'scanMeRole' export const LOCAL_STORAGE_VENDOR_ID = 'tescanMeVendorID' export const BASE_URL = 'https://form.e-society.ie/api/' <file_sep>/backend/models/Vendor.js const mongoose = require('mongoose'); const { Schema } = mongoose; // const uniqueValidator = require('mongoose-unique-validator'); const VendorSchema = new Schema({ vendorName: { type: String, required: true, }, vendorLocation: { type: String, required: true, }, vendorContact: { type: String, required: true, }, password: { type: String, required: true, }, vendorSecondaryContact: { type: String, }, vendorEmail: { type: String, required: true, }, active: { type: Boolean, required: true, default: true, }, }); VendorSchema.set('toJSON', { transform: (document, returnedObject) => { returnedObject.id = returnedObject._id.toString(); delete returnedObject.password; // delete returnedObject.active; delete returnedObject._id; delete returnedObject.__v; }, }); // VendorSchema.plugin(uniqueValidator); module.exports = mongoose.model('Vendor', VendorSchema); <file_sep>/backend/routes/SchoolRoute.js const express = require('express'); const router = express.Router(); const School = require('../models/School'); // @Route POST api/school/:id // @desc Get individual school // @access Public router.post('/:id', async (req, res) => { try { const id = req.params.id; const school = await School.findById(id); if (!school) { throw new Error('Could not find data'); } return res.status(200).json(school.toJSON()); } catch (err) { return res.status(400).json({ error: 'Could not find school data.' }); } }); module.exports = router; <file_sep>/backend/models/SchoolForm.js const mongoose = require('mongoose'); const { Schema } = mongoose; // const uniqueValidator = require('mongoose-unique-validator'); const SchoolFormSchema = new Schema({ schoolID: { type: Schema.Types.ObjectId, ref: 'School', required: true, }, email: { type: String, required: true, }, fullName: { type: String, required: true, }, phoneNumber: { type: String, required: true, }, dateOfVisit: { type: Date, required: true, default: Date.now, }, timeOfVisit: { type: String, required: true, }, studentID: { type: String, default: '', }, roomNumber: { type: String, required: true, }, }); SchoolFormSchema.set('toJSON', { transform: (document, returnedObject) => { returnedObject.id = returnedObject._id.toString(); // delete returnedObject.active; delete returnedObject._id; delete returnedObject.__v; }, }); // SchoolFormSchema.plugin(uniqueValidator); module.exports = mongoose.model('SchoolForm', SchoolFormSchema); <file_sep>/backend/config/keys.js require('dotenv').config(); module.exports = { mongoURI: process.env.MONGO_URI, saltRound: 10 || process.env.SALTROUND, secret: process.env.SECRET, adminSaltRound: 13, aws_access_key_id: process.env.AWS_SECRET_KEY_ID, aws_secret_access_key: process.env.AWS_SECRET_ACCESS_KEY, }; <file_sep>/backend/controller/purgeData.js const moment = require('moment'); const SchoolForm = require('../models/SchoolForm'); const Form = require('../models/Form'); exports.purgeOldData = async () => { try { const oldDate = moment().subtract('28', 'days'); console.log(oldDate); console.log('Purging old data'); await Form.deleteMany({ dateOfVisit: { $lte: oldDate.toISOString() }, }); await SchoolForm.deleteMany({ dateOfVisit: { $lte: oldDate.toISOString() }, }); } catch (err) { console.log(err); } };
f14be186ba3e50fc22e216d02eb0bb6649fd4f3e
[ "JavaScript" ]
16
JavaScript
divyaswormakai/QRApp
3e6574dba2dd1ed52c090370801e209ccb089a5d
27184c91ff5a2ef26eed8c167df2490b90475ade
refs/heads/master
<repo_name>rivyuz/zuul-ms<file_sep>/src/main/resources/static/js/index/confirmRegistration.js function getUrlVars() { var plainText; var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for(var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); plainText = decryptQs(hash[0]); } return plainText; } function checkIfConfirmation() { var qs = getUrlVars(); if(qs != "" && qs.startsWith("job=confirm")) { var splitArray = qs.split("&"); var jobArray = splitArray[0].split("="); var job = jobArray[1]; var codeArray = splitArray[1].split("="); var code = codeArray[1]; var emailArray = splitArray[2].split("="); var email = emailArray[1]; if(job == "confirm") { var splitEmail = email.split("XXXXXxxxxXXXX"); var replyEmail = splitEmail[0] + "@" + splitEmail[1]; addConfirmationMask("Please wait", true); var url = $("#dto-form-zu").val(); var uri = "/users-ms/user/confirmRegistration"; var api = url + uri; //ajax call $.ajax( { url: api, type: 'POST', data: { code: code }, success: function(result, status, xhr) { $("#dto-form-j").val(xhr.getResponseHeader("j")); var registrationConfirmed = result.response; if(registrationConfirmed == "true") { actionPerformingAlert.render('Registration', 'Confirmed', 'confirmationSuccess'); } if(registrationConfirmed == "false") { actionPerformingAlert.render('We are sorry', 'There seems to be a problem', 'confirmationError'); } }, //success callback ends error: function(result, status, xhr) { console.log(result.status + " " + result.statusText); } //error callback ends } //ajax method ends ); //ajax ends } } } /*confirmReg() ends*/<file_sep>/src/main/resources/static/js/index/resetPassword.js function resetPassword() { var emailId = $(".reset-password-email").val(); var oneTimePassword = $(".reset-password-one-time-password").val(); var newPassword = $(".reset-password-new-password").val(); var validationResult = validateFieldsInResetPasswordDialog(oneTimePassword, newPassword); if (validationResult == true) { } else { return; } //addHardMask("Please wait", true); emailId = encryptQs(emailId); oneTimePassword = encryptQs(oneTimePassword); newPassword = encryptQs(newPassword); var url = $("#dto-form-zu").val(); var uri = "/users-ms/user/resetpassword"; var api = url + uri; //ajax call $.ajax( { url: api, type: 'POST', data: { forward: emailId, reverse: oneTimePassword, idle: newPassword }, success: function(result, status, xhr) { $("#dto-form-j").val(xhr.getResponseHeader("j")); var resetPasswordResult = result.response; if(resetPasswordResult == "reset error") { $('.progress-indicator').hide(); actionPerformingAlert.render('We are sorry', 'Your one-time password expired', 'reset error'); } if(resetPasswordResult == "invalid temp password") { $('.progress-indicator').hide(); actionPerformingAlert.render('We are sorry', 'Invalid one-time password', 'invalid temp password'); } if(resetPasswordResult == "reset successful") { $(".reset-password-dialog").hide(); actionPerformingAlert.render('Reset successful', 'Have a great time', 'reset successful'); } }, //success callback ends error: function(result, status, xhr) { console.log(result.status + " " + result.statusText); } //error callback ends } //ajax method ends ); //ajax ends } /*resetPassword() ends*/<file_sep>/src/main/resources/static/js/index/getReviewsByEntity.js function getReviewsByEntity() { var url = $("#dto-form-zu").val(); var uri = "/reviews-ms/reviews"; var api = url + uri; $("#dto-form-entity-id").val($(this).attr("id")); $("#dto-form-entity-name").val($(this).find("span").attr("id")); $(".dto-form").attr('method', 'post'); $(".dto-form").attr('action', api); $(".dto-form").submit(); } function getOtherReviewsByEntity(category, entityId, entityName) { //var url = $("#dto-form-review-url").val(); var url = $("#dto-form-zu").val(); var uri = "/reviews-ms/reviews"; var api = url + uri; $("#dto-form-category").val(category); $("#dto-form-entity-id").val(entityId); $("#dto-form-entity-name").val(entityName); $(".dto-form").attr('method', 'post'); $(".dto-form").attr('action', api); $(".dto-form").submit(); }<file_sep>/src/main/resources/static/js/index/getEntityDetails.js $('.entity').click(function (event) { $(this).parent().parent().hide(); var catg = $(this).parent().attr('class'); var splitArray = catg.split("_list"); var category = splitArray[0]; var entityId = $(this).attr("id"); var entity = $(this).text(); if(category == "Cats" || category == "OnlineStore" || category == "PackersAndMovers") { getOtherReviewsByEntity(category, entityId, entity); return; } var url = $("#dto-form-zu").val(); var uri = "/entities-ms/entities/list/" + category + "/" + entity; var api = url + uri; //ajax call $.ajax( { url: api, type: 'GET', data: {}, success: function(result,status,xhr) { $('.right-side').detach(); var commentsContainerDiv = document.createElement('div'); $(commentsContainerDiv).addClass("right-side"); for (var i = 0; i < result.length; i++) { $("#dto-form-category").val(result[i].indxCatg); //..................................................................create div tag - "box-comment text-left box-comment-boxed" var divTag_one = document.createElement('div'); $(divTag_one).addClass("box-comment"); $(divTag_one).addClass("text-left"); $(divTag_one).addClass("box-comment-boxed"); $(divTag_one).attr("id", result[i].id); //..................................................................create div tag - "media" var divTag_two = document.createElement('div'); $(divTag_two).addClass("media"); //..................................................................create div tag - "media-left" var divTag_three = document.createElement('div'); $(divTag_three).addClass("media-left"); //..................................................................create div tag - "image" var divTag_four = document.createElement('div'); $(divTag_four).addClass(result[i].spriteName); $(divTag_four).addClass(result[i].spriteImage); $(divTag_four).addClass("entity-image"); //..................................................................create div tag - "media-body" var divTag_five = document.createElement('div'); $(divTag_five).addClass("media-body"); //..................................................................create header tag var header_tag = document.createElement('header'); $(header_tag).addClass("box-comment-header"); $(header_tag).addClass("unit"); $(header_tag).addClass("unit-vertical"); $(header_tag).addClass("unit-spacing-xxs"); $(header_tag).addClass("unit-md"); $(header_tag).addClass("unit-md-horizontal"); $(header_tag).addClass("unit-md-inverse"); $(header_tag).addClass("unit-md-middle"); $(header_tag).addClass("unit-md-align-right"); //..................................................................create div tag - "unit-body" var divTag_six = document.createElement('div'); $(divTag_six).addClass("unit-body"); if(category == "camera") { if(i == 0) { //..................................................................create pTag - brand var pTag = document.createElement('p'); $(pTag).addClass("entity_name"); $(pTag).addClass("format-class"); var content = result[i].brand; $(pTag).text(content); $(commentsContainerDiv).append(pTag); } //..................................................................create spanTag_2 - name var spanTag_2 = document.createElement('span'); $(spanTag_2).addClass("entity_name"); var content = result[i].name; $(spanTag_2).attr("id", content); $(spanTag_2).text(content); //..................................................................create brTag_2 var brTag_2 = document.createElement('br'); $(spanTag_2).append(brTag_2); //..................................................................create spanTag_3 - category var spanTag_3 = document.createElement('span'); $(spanTag_3).addClass("entity_name"); var content = result[i].category; if(content == "digital_cameras") { content = "Digital Camera" } else if (content == "digital_slr") { content = "Digital SLR" } $(spanTag_3).text(content); //..................................................................create brTag_2 var brTag_3 = document.createElement('br'); $(spanTag_3).append(brTag_3); //..................................................................create spanTag_4 - specification var spanTag_4 = document.createElement('span'); $(spanTag_4).addClass("entity_name"); var content = result[i].specification; $(spanTag_4).text(content); //..................................................................create brTag_4 var brTag_4 = document.createElement('br'); $(spanTag_4).append(brTag_4); $(divTag_six).append(spanTag_1); $(divTag_six).append(spanTag_2); $(divTag_six).append(spanTag_3); $(divTag_six).append(spanTag_4); } if(category == "car") { if(i == 0) { //..................................................................create pTag - brand var pTag = document.createElement('p'); $(pTag).addClass("entity_name"); $(pTag).addClass("format-class"); var content = result[i].mfgName; $(pTag).text(content); $(commentsContainerDiv).append(pTag); } //..................................................................create spanTag_2 var spanTag_2 = document.createElement('span'); $(spanTag_2).addClass("entity_name"); var content = result[i].name; $(spanTag_2).attr("id", content); $(spanTag_2).text(content); //..................................................................create brTag_2 var brTag_2 = document.createElement('br'); $(spanTag_2).append(brTag_2); //..................................................................create spanTag_3 var spanTag_3 = document.createElement('span'); $(spanTag_3).addClass("entity_name"); var content = result[i].category; $(spanTag_3).text(content); //..................................................................create brTag_3 var brTag_3 = document.createElement('br'); $(spanTag_3).append(brTag_3); //..................................................................create spanTag_4 var spanTag_4 = document.createElement('span'); $(spanTag_4).addClass("entity_name"); var content = result[i].fuelType; $(spanTag_4).text(content); //..................................................................create brTag_4 var brTag_4 = document.createElement('br'); $(spanTag_4).append(brTag_4); $(divTag_six).append(spanTag_1); $(divTag_six).append(spanTag_2); $(divTag_six).append(spanTag_3); $(divTag_six).append(spanTag_4); } if(category == "dog") { if(i == 0) { //..................................................................create pTag - brand var pTag = document.createElement('p'); $(pTag).addClass("entity_name"); $(pTag).addClass("format-class"); var content = result[i].category; $(pTag).text(content); $(commentsContainerDiv).append(pTag); } //..................................................................create spanTag_1 - name var spanTag_1 = document.createElement('span'); $(spanTag_1).addClass("entity_name"); var content = result[i].name; $(spanTag_1).attr("id", content); $(spanTag_1).text(content); //..................................................................create brTag_1 var brTag_1 = document.createElement('br'); $(spanTag_1).append(brTag_1); //..................................................................create spanTag_3 var spanTag_3 = document.createElement('span'); $(spanTag_3).addClass("entity_name"); var content = result[i].family; $(spanTag_3).text("Family: " + content); //..................................................................create brTag_3 var brTag_3 = document.createElement('br'); $(spanTag_3).append(brTag_3); //..................................................................create spanTag_4 var spanTag_4 = document.createElement('span'); $(spanTag_4).addClass("entity_name"); var content = result[i].areaOfOrigin; $(spanTag_4).text("Area of Origin: " + content); //..................................................................create brTag_4 var brTag_4 = document.createElement('br'); $(spanTag_4).append(brTag_4); $(divTag_six).append(spanTag_1); $(divTag_six).append(spanTag_2); $(divTag_six).append(spanTag_3); $(divTag_six).append(spanTag_4); } if(category == "fitness_center" || category == "night_life" || category == "restaurant" || category == "spa_center" || category == "tattoo_parlor") { var title; if(category == "fitness_center") { title = "Fitness Centers in "; } else if(category == "night_life") { title = "Night Life in "; } else if(category == "restaurant") { title = "Restaurants in "; } else if(category == "spa_center") { title = "Spa Centers in "; } else if(category == "tattoo_parlor") { title = "Tattoo Parlors in "; } if(i == 0) { //..................................................................create pTag - brand var pTag = document.createElement('p'); $(pTag).addClass("entity_name"); $(pTag).addClass("format-class"); var content = result[i].cityName; $(pTag).text(title + content); $(commentsContainerDiv).append(pTag); } //..................................................................create spanTag_1 var spanTag_1 = document.createElement('span'); $(spanTag_1).addClass("entity_name"); var content = result[i].name; $(spanTag_1).attr("id", content); $(spanTag_1).text(content); //..................................................................create brTag_1 var brTag_1 = document.createElement('br'); $(spanTag_1).append(brTag_1); //..................................................................create spanTag_2 var spanTag_2 = document.createElement('span'); $(spanTag_2).addClass("entity_name"); var content = result[i].address1; $(spanTag_2).text(content); //..................................................................create brTag_2 var brTag_2 = document.createElement('br'); $(spanTag_2).append(brTag_2); if(result[i].address2 != "") { //..................................................................create spanTag_3 var spanTag_3 = document.createElement('span'); $(spanTag_3).addClass("entity_name"); var content = result[i].address2; $(spanTag_3).text(content); //..................................................................create brTag_3 var brTag_3 = document.createElement('br'); $(spanTag_3).append(brTag_3); } //..................................................................create spanTag_4 var spanTag_4 = document.createElement('span'); $(spanTag_4).addClass("entity_name"); var content = result[i].cityName; $(spanTag_4).text(content); //..................................................................create spanTag_5 var spanTag_5 = document.createElement('span'); $(spanTag_5).addClass("entity_name"); var content = result[i].pinCode; $(spanTag_5).text(content); //..................................................................create brTag_5 var brTag_5 = document.createElement('br'); $(spanTag_5).append(brTag_5); $(divTag_six).append(spanTag_1); $(divTag_six).append(spanTag_2); $(divTag_six).append(spanTag_3); $(divTag_six).append(spanTag_4); $(divTag_six).append(spanTag_5); } if(category == "fragrance") { //..................................................................create spanTag_1 - brand var spanTag_1 = document.createElement('span'); $(spanTag_1).addClass("entity_name"); var content = result[i].brand; $(spanTag_1).attr("id", result[i].name); $(spanTag_1).text(content); //..................................................................create brTag_1 var brTag_1 = document.createElement('br'); $(spanTag_1).append(brTag_1); //..................................................................create spanTag_2 - name var spanTag_2 = document.createElement('span'); $(spanTag_2).addClass("entity_name"); var content = result[i].name; $(spanTag_2).text(content); //..................................................................create brTag_2 var brTag_2 = document.createElement('br'); $(spanTag_2).append(brTag_2); if(result[i].edition != "") { //..................................................................create spanTag_3 - edition var spanTag_3 = document.createElement('span'); $(spanTag_3).addClass("entity_name"); var content = result[i].edition; $(spanTag_3).text(content); //..................................................................create brTag_3 var brTag_3 = document.createElement('br'); $(spanTag_3).append(brTag_3); } //..................................................................create spanTag_4 - type var spanTag_4 = document.createElement('span'); $(spanTag_4).addClass("entity_name"); var content = result[i].type; $(spanTag_4).text(content); //..................................................................create brTag_4 var brTag_4 = document.createElement('br'); $(spanTag_4).append(brTag_4); //..................................................................create spanTag_6 - category var spanTag_6 = document.createElement('span'); $(spanTag_6).addClass("entity_name"); var content = result[i].category; $(spanTag_6).text(content); //..................................................................create brTag_6 var brTag_6 = document.createElement('br'); $(spanTag_6).append(brTag_6); $(divTag_six).append(spanTag_1); $(divTag_six).append(spanTag_2); $(divTag_six).append(spanTag_3); $(divTag_six).append(spanTag_4); $(divTag_six).append(spanTag_6); } if(category == "motor_cycle" || category == "scooter") { if(i == 0) { //..................................................................create pTag - brand var pTag = document.createElement('p'); $(pTag).addClass("entity_name"); $(pTag).addClass("format-class"); var content = result[i].mfgName; $(pTag).text(content); $(commentsContainerDiv).append(pTag); } //..................................................................create spanTag_1 var spanTag_1 = document.createElement('span'); $(spanTag_1).addClass("entity_name"); var content = result[i].name; $(spanTag_1).attr("id", content); $(spanTag_1).text(content); //..................................................................create brTag_1 var brTag_1 = document.createElement('br'); $(spanTag_1).append(brTag_1); $(divTag_six).append(spanTag_1); //--------hidden variable for comment id----------------------// var idAttr = "entityId_" + result[i].id; var hiddenInputTag_commentId = document.createElement('input'); hiddenInputTag_commentId.setAttribute("type", "hidden"); hiddenInputTag_commentId.setAttribute("id", idAttr); hiddenInputTag_commentId.setAttribute("name", idAttr); hiddenInputTag_commentId.setAttribute("value", result[i].id); $(divTag_one).append(hiddenInputTag_commentId); } if(category == "movie") { if(i == 0) { //..................................................................create pTag - brand var pTag = document.createElement('p'); $(pTag).addClass("entity_name"); $(pTag).addClass("format-class"); var content = result[i].language; if(content == "Chinese" || content == "Japanese" || content == "Korean") { content = "Other Language"; } $(pTag).text(content + " Movies"); $(commentsContainerDiv).append(pTag); } //..................................................................create spanTag_1 - movieName var spanTag_1 = document.createElement('span'); $(spanTag_1).addClass("entity_name"); var content = result[i].movieName; $(spanTag_1).attr("id", content); $(spanTag_1).text(content); //..................................................................create brTag_1 var brTag_1 = document.createElement('br'); $(spanTag_1).append(brTag_1); //..................................................................create spanTag_2 - director var spanTag_2 = document.createElement('span'); $(spanTag_2).addClass("entity_name"); var content = result[i].director; $(spanTag_2).text("Director: " + content); //..................................................................create brTag_2 var brTag_2 = document.createElement('br'); $(spanTag_2).append(brTag_2); //..................................................................create spanTag_3 - cast var spanTag_3 = document.createElement('span'); $(spanTag_3).addClass("entity_name"); var content = result[i].cast; $(spanTag_3).text("Cast: " + content); //..................................................................create brTag_3 var brTag_3 = document.createElement('br'); $(spanTag_3).append(brTag_3); if(result[i].genre != "") { //..................................................................create spanTag_4 - genre var spanTag_4 = document.createElement('span'); $(spanTag_4).addClass("entity_name"); var content = result[i].genre; $(spanTag_4).text(content); //..................................................................create brTag_4 var brTag_4 = document.createElement('br'); $(spanTag_4).append(brTag_4); } if(result[i].language == "Chinese" || result[i].language == "Japanese" || result[i].language == "Korean") { //..................................................................create spanTag_5 - language var spanTag_5 = document.createElement('span'); $(spanTag_5).addClass("entity_name"); var content = result[i].language; $(spanTag_5).text(content); //..................................................................create brTag_5 var brTag_5 = document.createElement('br'); $(spanTag_5).append(brTag_5); } //..................................................................create spanTag_6 - year var spanTag_6 = document.createElement('span'); $(spanTag_6).addClass("entity_name"); var content = result[i].year; $(spanTag_6).text("Year: " + content); //..................................................................create brTag_6 var brTag_6 = document.createElement('br'); $(spanTag_6).append(brTag_6); $(divTag_six).append(spanTag_1); $(divTag_six).append(spanTag_2); $(divTag_six).append(spanTag_3); $(divTag_six).append(spanTag_4); if(result[i].language == "Chinese" || result[i].language == "Japanese" || result[i].language == "Korean") { $(divTag_six).append(spanTag_5); } $(divTag_six).append(spanTag_6); } if(category == "salon") { if(i == 0) { //..................................................................create pTag - brand var pTag = document.createElement('p'); $(pTag).addClass("entity_name"); $(pTag).addClass("format-class"); var content = result[i].cityName; $(pTag).text("Salons in " + content); $(commentsContainerDiv).append(pTag); } //..................................................................create spanTag_1 var spanTag_1 = document.createElement('span'); $(spanTag_1).addClass("entity_name"); var content = result[i].name; $(spanTag_1).attr("id", content); $(spanTag_1).text(content); //..................................................................create brTag_1 var brTag_1 = document.createElement('br'); $(spanTag_1).append(brTag_1); //..................................................................create spanTag_2 var spanTag_2 = document.createElement('span'); $(spanTag_2).addClass("entity_name"); var content = result[i].address1; $(spanTag_2).text(content); //..................................................................create brTag_2 var brTag_2 = document.createElement('br'); $(spanTag_2).append(brTag_2); //..................................................................create spanTag_3 var spanTag_3 = document.createElement('span'); $(spanTag_3).addClass("entity_name"); var content = result[i].address2; $(spanTag_3).text(content); //..................................................................create brTag_3 var brTag_3 = document.createElement('br'); $(spanTag_3).append(brTag_3); //..................................................................create spanTag_4 var spanTag_4 = document.createElement('span'); $(spanTag_4).addClass("entity_name"); var content = result[i].cityName; $(spanTag_4).text(content); //..................................................................create spanTag_5 var spanTag_5 = document.createElement('span'); $(spanTag_5).addClass("entity_name"); var content = result[i].pinCode; $(spanTag_5).text(content); //..................................................................create brTag_5 var brTag_5 = document.createElement('br'); $(spanTag_5).append(brTag_5); //..................................................................create spanTag_6 var spanTag_6 = document.createElement('span'); $(spanTag_6).addClass("entity_name"); var content = result[i].brand; $(spanTag_6).text(content); //..................................................................create brTag_6 var brTag_6 = document.createElement('br'); $(spanTag_6).append(brTag_6); //..................................................................create spanTag_7 var spanTag_7 = document.createElement('span'); $(spanTag_7).addClass("entity_name"); var content = result[i].type; $(spanTag_7).text(content); //..................................................................create brTag_7 var brTag_7 = document.createElement('br'); $(spanTag_7).append(brTag_7); if(result[i].category != "NULL") { //..................................................................create spanTag_8 var spanTag_8 = document.createElement('span'); $(spanTag_8).addClass("entity_name"); var content = result[i].category; $(spanTag_8).text(content); //..................................................................create brTag_8 var brTag_8 = document.createElement('br'); $(spanTag_8).append(brTag_8); } $(divTag_six).append(spanTag_1); $(divTag_six).append(spanTag_2); $(divTag_six).append(spanTag_3); $(divTag_six).append(spanTag_4); $(divTag_six).append(spanTag_5); $(divTag_six).append(spanTag_6); $(divTag_six).append(spanTag_7); $(divTag_six).append(spanTag_8); } //..................................................................create span tag - "spanTag_badge" var spanTag_badge = document.createElement('span'); $(spanTag_badge).addClass("revBadge"); var content = result[i].counter; $(spanTag_badge).text(content); $(divTag_six).append(spanTag_badge); $(header_tag).append(divTag_six); $(divTag_five).append(header_tag); $(divTag_three).append(divTag_four); $(divTag_two).append(divTag_three); $(divTag_two).append(divTag_five); $(divTag_one).append(divTag_two); $( divTag_one ).on( "click", getReviewsByEntity );//.................................................................bind getReviewsByEntity() method $(commentsContainerDiv).append(divTag_one); //..................................................................create brTag_10 var brTag = document.createElement('br'); $(commentsContainerDiv).append(brTag); console.log(result[i].brand); } $(".page-article").append(commentsContainerDiv); }, //success callback ends error: function(xhr,status,error) { console.log(xhr.status + " " + xhr.statusText); } //error callback ends } //ajax method ends ); //ajax ends removeMasks(); }); /*$('.entity').click ends*/
bf09568bafd7eb22580658a7b22d038d883e3fe3
[ "JavaScript" ]
4
JavaScript
rivyuz/zuul-ms
cd7714c3978a587a29a7a82eddb97147f7a194fd
aff6bbf3a0c6e4fa56c37088140e770098d58fee
refs/heads/master
<repo_name>Tonycrosss/8_vk_friends_online<file_sep>/README.md # Watcher of Friends Online This module is connecting to vk.com and show u friends online # Variables APP_ID - to get app_id u must register your app at https://vk.com/dev # How to Install Python 3 should be already installed. Then use pip (or pip3 if there is a conflict with old Python 2 setup) to install dependencies: ```bash pip install -r requirements.txt # alternatively try pip3 ``` Remember, it is recommended to use [virtualenv/venv](https://devman.org/encyclopedia/pip/pip_virtualenv/) for better isolation. # Usage Example ```bash $ python3 vk_friends_online.py Введите свой логин: *****<EMAIL> Введите свой пароль: *********** Сейчас в онлайне след. пользователи: <NAME> <NAME> <NAME> <NAME> <NAME> <NAME> <NAME> ``` # Project Goals The code is written for educational purposes. Training course for web-developers - [DEVMAN.org](https://devman.org) <file_sep>/vk_friends_online.py import vk import getpass APP_ID = 6238089 def get_user_login(): user_login = input('Введите свой логин:\n') return user_login def get_user_password(): user_password = getpass.getpass(prompt='Введите свой пароль:\n') return user_password def create_vk_session(login, password): session = vk.AuthSession( app_id=APP_ID, user_login=login, user_password=<PASSWORD>, scope='friends', ) api = vk.API(session) return api def get_online_friends_ids(vk_session): friends_online_ids = vk_session.friends.getOnline() return friends_online_ids def get_users_info(users_ids, vk_session): users_info = vk_session.users.get(user_ids=users_ids) return users_info def output_friends_to_console(users_info): print('Сейчас в онлайне след. пользователи:\n') for user in users_info: print('{} {}'.format(user['first_name'], user['last_name'])) if __name__ == '__main__': login = get_user_login() password = <PASSWORD>() vk_session = create_vk_session(login, password) friends_online_ids = get_online_friends_ids(vk_session) users_info = get_users_info(friends_online_ids, vk_session) output_friends_to_console(users_info)
d11c38dcc7d14c897b3e2ef4fdf0685d47fb1801
[ "Markdown", "Python" ]
2
Markdown
Tonycrosss/8_vk_friends_online
fa2d65937d50c5b93d7ec982aac1580e5fca71ff
7fcbfb55360920789956748928c187232dc8f6fe
refs/heads/master
<file_sep>import json import os import datetime import sys import time import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties import argparse parser = argparse.ArgumentParser() parser.add_argument("path", help="Path to your messenger 'inbox' folder.") parser.add_argument("--recipient", help="The person to graph.", default="<NAME>") parser.add_argument("--name", help="Your name so script can remove it as a participant. Default: none") parser.add_argument("--messages", help="Minimum number of messages to display. Default: 250", default=50, type=int) parser.add_argument("--maxgroup", help="Maximum group size. Large group chats tend to have a lot of messages.", default=10, type=int) args = parser.parse_args() # So it removes me NAME = args.name # Min messages to show up MIN_MSG = args.messages # Max number of group members (large groups have more messages). MAX_GROUP_SIZE = args.maxgroup # Path to messenger inbox folder. directory = args.path # So it removes me RECIPIENT = args.recipient participant_messages_time_dict = dict() participant_lists = dict() total_messages_time_dict = dict() def toTimestamp(date): return (date - datetime.date(1970, 1, 1)).days * 24 * 60 * 60 # This creates a count for the number of days def countDays(message_time_list): days_dict = dict() num_per_day = [] days = [] min_day = datetime.date.today() max_day = datetime.date(1970, 1, 1) for time in message_time_list: day = datetime.date.fromtimestamp(time/1000) if day < min_day: min_day = day if day > max_day: max_day = day if day in days_dict: days_dict[day] += 1 else: days_dict[day] = 1 min_day = min_day - datetime.timedelta(days=30) max_day = max_day + datetime.timedelta(days=30) if max_day > datetime.date.today(): max_day = datetime.date.today() for time_ms in range(toTimestamp(min_day), toTimestamp(max_day), 24 * 60 * 60): day = datetime.date.fromtimestamp(time_ms) days.append(day) if day in days_dict: num_per_day.append(days_dict[day]) else: num_per_day.append(0) return days, num_per_day # Expects to be run like `python process_time.py ~/Downloads/facebook/messages/inbox/` for chat_folder in os.listdir(directory): chat_folder_path = os.path.join(directory, chat_folder) if os.path.isdir(chat_folder_path): for chat_file in os.listdir(chat_folder_path): if ".json" in chat_file: chat_file_path = os.path.join(chat_folder_path, chat_file) with open(chat_file_path, 'r') as f: messages_dict = json.load(f) if len(messages_dict["messages"]) > MIN_MSG: participant = [p["name"] for p in messages_dict["participants"]] if NAME in participant: participant.remove(NAME) if len(participant) <= MAX_GROUP_SIZE: participant_names = set() participant_message_times = dict() total_messages_time_list = [] print(participant) for message in messages_dict["messages"]: participant_name = message["sender_name"] participant_names.add(participant_name) # divide into days total_messages_time_list.append(message["timestamp_ms"]) if participant_name not in participant_message_times: participant_message_times[participant_name] = [] participant_message_times[participant_name].append(message["timestamp_ms"]) participant_key = ', '.join(participant) total_messages_time_dict[participant_key] = countDays(total_messages_time_list) participant_lists[participant_key] = participant_names participant_messages_time_dict[participant_key] = dict() for participant_name in participant_names: participant_messages_time_dict[participant_key][participant_name] = countDays(participant_message_times[participant_name]) messages_dates, num_messages = total_messages_time_dict[RECIPIENT] line, = plt.plot(messages_dates, num_messages, label="Total", linewidth=1) for participant_name in participant_lists[RECIPIENT]: participant_messages_dates, participant_num_messages = participant_messages_time_dict[RECIPIENT][participant_name] line, = plt.plot(participant_messages_dates, participant_num_messages, label=participant_name, linewidth=1, linestyle="dotted") fontP = FontProperties() fontP.set_size('small') legend = plt.legend() plt.show()<file_sep># Facebook-Data-Visualization This repo contains script(s) to run on your downloaded data from facebook. It aims to offer fun data visualizations from your past messenger messages, posts, and whatever else. See The following link to download your data. https://www.facebook.com/help/1701730696756992?helpref=hc_global_nav To use, download and install Python 3 [here](https://www.python.org/downloads/). Then, run the following command in the command line to install matplotlib: ``` pip3 install matplotlib ``` ### Plot Messenger Messages See who you talk to over time. Takes a path to your messages inbox folder. Takes in your name, the recipient's name, maximum group text size, and minimum number of messages in order to display. ``` python3 plot_messages.py ~/Downloads/facebook/messages/inbox/ --recipient 'Other Name' --name '<NAME>' --messages 50 --maxgroup 10 ```
8ded266ac13ad113682a5db9634ddbcaab86b1a8
[ "Markdown", "Python" ]
2
Python
PhastPhood/Facebook-Data-Visualization
631d0b31c6002164c3423d79d0a8347f87c43ead
464e6460719309bce837334edf599e60db4dfaaa
refs/heads/master
<file_sep>package org.archive.util.iterator; import java.io.IOException; import java.util.Iterator; public interface CloseableIterator<E> extends Iterator<E> { public void close() throws IOException; }
ed33c5ddad79c39775ec4e8d4dd2dd7cdf15a6d0
[ "Java" ]
1
Java
nlevitt/archive-commons
5eb732e39dae3d1bbde36c8da31b0ce4936c2841
4eaa4159ae4a204da600e78cc07596f248f1308c
refs/heads/master
<file_sep>import locale import random import sys import time from datetime import timedelta locale.setlocale(locale.LC_ALL, '') length = 0 if (len(sys.argv) > 1): length = int(sys.argv[1]) else: print("W: No length given. 8 taken as default") length = 8 print("Length: ", length) l = [] l.extend(range(1, length + 1)) sorted_l = l.copy() random.shuffle(l) start = time.time() print("---- Start \"Sorting\" at " + time.ctime() + " ----") cnt = 0 while (not l == sorted_l): print(str(l) + " tries = {:n}".format(cnt + 1), end="\r") random.shuffle(l) cnt += 1 end = time.time() print(l) print("---- Done found at " + time.ctime() + " ----") print("The {:n} tries took {} seconds".format(cnt, timedelta(seconds=end - start))) <file_sep> # FunSort
64cd3c9d2971fc3c7166fdf1fac52969939c0741
[ "Markdown", "Python" ]
2
Python
DerWario/FunSort
d4070183f288a9ddccaf515c7026569a7d9a6c42
4ebb4c65474d902a1a0f6232c4fcdef80108751f
refs/heads/master
<repo_name>poppinlr/ifquestion<file_sep>/src/main/java/hello/SampleService.java package hello; import entity.Category; import lombok.extern.java.Log; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; /** * Created by poppinlr on 2017/6/4. */ @Service @Log public class SampleService { @Autowired private SampleRepository repository; public Double getPriceOfStr(String str) throws Exception{ Category category = repository.findByStr(str); if(category == null){ //cant find the category in db throw new Exception(); }else if(category.getPrice() == null){ //find price close to str return repository.findCloseToStr(category); }else{ return category.getPrice(); } } }
726feb01637891e0dc8f4ef2d238939f411643f6
[ "Java" ]
1
Java
poppinlr/ifquestion
aeb48aeb4eb08167aa4e8ff8d077cdb645ec5f26
a4e5a392169730c00d78194444278bbc43acf050
refs/heads/master
<repo_name>Alieddin/intro-to-SDC<file_sep>/kalman1d.py # Write a program to update your mean and variance when given the mean and variance of belief and those of measurement. # This program will update the parameters of your belief function. def update(mean1, var1, mean2, var2): new_mean = float((var2 * mean1) + (var1 * mean2)) / (var1 + var2) new_var =1./((1./var2)+(1./var1)) return [new_mean, new_var] # Write a program that will predict your new mean and variance given the mean and variance of your # prior belief and the mean and variance of your motion. def predict(mean1, var1, mean2, var2): new_mean = mean1+mean2 new_var =var1+var2 return [new_mean, new_var] # Write a program that will iteratively update and predict based on the location measurements # and inferred motions shown below. measurements = [5., 6., 7., 9., 10.] measurement_sig = 4. motion = [1., 1., 2., 1., 1.] motion_sig = 2. mu = 0. sig = 10000. for i in range(len(measurements)): mu,sig = update(mu,sig,measurements[i],measurement_sig) print ("update: {} ,{}".format(float(mu), float(sig))) mu, sig = predict(mu, sig, motion[i], motion_sig) print ("predict: {} ,{}".format(mu, sig))
9687f25c765243881eb40c0cf366b58565950a3b
[ "Python" ]
1
Python
Alieddin/intro-to-SDC
9cf456490196d3e2cf6fc2cdeecc879b1c2df85b
86f3db764711fecdb83ae45697759af54ac45724
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package BaiTap2; /** * * @author <NAME> */ public class BaiTap2Main { public static void main(String[] args) { GioHang giohang1 = new GioHang(); giohang1.sethinhThucTT(new ThanhToanOnline()); giohang1.them(new HangHoa("Bánh Cosy", 100000, "bánh tròn")); giohang1.them(new HangHoa("Bánh Gạo", 20000, "bánh dài")); giohang1.them(new HangHoa("Cocacola", 160000, "lon")); giohang1.them(new HangHoa("Kẹo Chip Chip", 50000, "hình con vật ngộ nghĩnh")); giohang1.them(new HangHoa("Kẹo Singum", 20000, "viên")); giohang1.inDS(); System.out.println("Tổng tiền phải thanh toán: " + giohang1.thanhToan()); GioHang giohang2 = new GioHang(); giohang2 .sethinhThucTT(new ThanhToanCOD()); giohang2.them(new HangHoa("Kẹo Socola", 200000, "viên tròn")); giohang2.them(new HangHoa("Kẹo dưa hấu", 70000, "hủ")); giohang2.them(new HangHoa("Bánh ngu cốc", 90000, "bịch")); giohang2.them(new HangHoa("Pepsi", 180000, "lon")); giohang2.them(new HangHoa("Bánh Snack", 6000, "bánh vị khoai tây")); giohang2.inDS(); System.out.println("Tổng tiền phải thanh toán: " + giohang2.thanhToan()); } } <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 BaiTap2; /** * * @author <NAME> */ public class ThanhToanCOD implements IThanhToan { @Override public double thanhToan(int tienHang) { double Tien=0; if(tienHang>200000) return (tienHang-(tienHang*2/100)); else Tien=tienHang; return Tien; } } <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 BaiTap3; import java.util.ArrayList; /** * * @author <NAME> */ public class QLSV { ArrayList<SinhVien> dsSV; ISoSanh soSanh; public QLSV(ArrayList<SinhVien> dsSV) { this.dsSV = dsSV; } public void setSoSanh(ISoSanh soSanh) { this.soSanh = soSanh; } public void sapXep() { dsSV.sort((sv1, sv2) -> soSanh.soSanh(sv1, sv2)); } public void inDS() { for (int i = 0; i < dsSV.size(); i++) { System.out.println(dsSV.get(i).toString()); } } } <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 BaiTap3; import java.util.ArrayList; /** * * @author <NAME> */ public class BaiTap3Main { public static void main(String[] args) { ArrayList<SinhVien> ds = new ArrayList<>(); ds.add(new SinhVien("<NAME>", "1/1/1999", (float) 8.5)); ds.add(new SinhVien("<NAME>", "2/2/1999", (float) 8.0)); ds.add(new SinhVien("<NAME>", "5/7/1999", (float) 7.9)); QLSV ql = new QLSV(ds); ql.setSoSanh(new SoSanhTheoTen()); ql.sapXep(); ql.inDS(); ql.setSoSanh(new SoSanhTheoDiem()); ql.sapXep(); ql.inDS(); } }
96e1a3cee2c98301d590453e2a3fccfa8acec51b
[ "Java" ]
4
Java
chaucamly/ChauCamLy_59131356_-Stratery-Pattern-
8e030b88a8f2e1803b7e87193cfa65e3797084e5
b6f80ed7a6d4717962d69541bbcb9e85dae2d435
refs/heads/master
<file_sep>#!/usr/bin/env python3 from datetime import datetime from urllib.parse import unquote import geolocator as locator from settings import debug from db import Session from db import Location def loc2csv(loc): return "%.2f,%.2f" % (getattr(loc, "latitude"), getattr(loc, "longitude")) def to_csv(model): """ Returns a CSV representation of an SQLAlchemy-backed object. """ if not model: return "" if isinstance(model, list): return "\n".join([next.name + ", " + loc2csv(next) for next in model]) else: return loc2csv(model) def query_location(name=None, latitude=None, longitude=None): location = None session = Session(expire_on_commit=False) if name is not None and len(name) > 0: name = unquote(name) location = session.query(Location).filter(Location.name.like(name)).first() if ( latitude is not None and len(latitude) > 0 and longitude is not None and len(longitude) > 0 ): if location is None: # print('create') location = Location( name=name.upper(), latitude=latitude, longitude=longitude ) session.add(location) else: # print('update') location.latitude = latitude location.longitude = longitude location.lastseen = datetime.now() session.commit() else: # not on our database if location is None: # print('import') rloc = locator.geocode(name) location = Location( name=name.upper(), latitude=rloc.latitude, longitude=rloc.longitude ) session.add(location) session.commit() else: location = session.query(Location).order_by(Location.name.asc()).all() session.close() return to_csv(location) if __name__ == "__main__": pass <file_sep>import hashlib import re import numpy as np # The geolocators in geopy that do not expect api_key from geopy.geocoders import GeocodeFarm, Yandex, ArcGIS from db import Session from db import Query locators = [GeocodeFarm(), ArcGIS()] def _query(session, hashcode, provider): return ( session.query(Query) .filter(Query.hashcode == hashcode, Query.provider == provider) .first() ) def cached_query(address, provider): address = re.sub(r"\s+", " ", address.upper()) session = Session(expire_on_commit=False) provider_name = provider.__class__.__name__ hashcode = hashlib.md5(bytes(address, encoding="utf-8")).hexdigest() cached = _query(session, hashcode, provider_name) if not cached: try: response = provider.geocode(address) except Exception as e: print(e) response = None if response: cached = Query( hashcode=hashcode, address=address, latitude=response.latitude, longitude=response.longitude, provider=provider_name, ) session.add(cached) session.commit() # session.expunge(cached) # session.expunge_all() session.close() return cached class Coordinates: def __init__(self, latitude, longitude): self.latitude = latitude self.longitude = longitude def __repr__(self): return "%s, %s" % (self.latitude, self.longitude) def reject_outliers(data, alpha=90): mask = (data.lat < np.percentile(data.lat, alpha)) & ( data.long < np.percentile(data.long, alpha) ) return data[mask] def geocode(address): # candidates = np.array([], dtype=[('long',float),('lat', float)]) candidates = [] for locator in locators: rloc = cached_query(address, locator) if rloc: # print(rloc.raw) candidates.append((rloc.latitude, rloc.longitude)) # coords = np.core.records.fromrecords([x.values() for x in candidates], names=candidates[0].keys()) # candidates.append(rloc) # a = np.array([(1, 2.0), (1, 2.0)], dtype=[('x', int), ('y', float)]) if not candidates: return None coords = np.core.records.fromrecords(candidates, names="lat,long") if len(coords) > 2: coords = reject_outliers(coords) # return {"latitude": np.average(coords.lat), "longitude": np.average(coords.long)} return Coordinates(np.average(coords.lat), np.average(coords.long)) if __name__ == "__main__": result = geocode("VIA DELLA CASETTA MATTEI 205") print(result) <file_sep># whereami - A web service for GAZE BEYOND In memory of <NAME> (1987-2017). On 21 January 2019 I have decided that the [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/) license better serves the memory of Liana. It would still allow people to reuse this code, but would also make sure that they mention this site as a source and thus would keep her memory alive. For obvious legal reasons, the code up to the [tag:gaze_beyond](https://github.com/mapto/whereami/releases/tag/gaze_beyond) is also available under the [GNU Lesser General Public License v3.0](https://www.gnu.org/licenses/lgpl-3.0.en.html) as previously. This is a test service for her prototype for http://cargocollective.com/lialessa/GAZE-BEYOND, probably the best use of geolocation I've encountered in my life. Please do check out the idea and - if inspired - do try to take it forward, with or without me. ## Requirements - Python3 (https://www.python.org) - bottle (http://bottlepy.org) - SQLAlchemy (http://www.sqlalchemy.org) using SQLite (https://sqlite.org) - GeoPy (https://github.com/geopy) using GeocodeFarm (https://geocode.farm) and ArcGIS (https://www.arcgis.com) - NumPy (https://numpy.org/) ## Executables - To test web services, run "python test.py". - To create a blank database run "python db.py". - To start the API locally, run "python main.py" and open http://localhost:8000 from your browser. All major browsers are supported. - Use 'pyinstaller main.spec' to build a standalone executable (requries [pyinstaller](https://www.pyinstaller.org/)). This [requires](https://github.com/mapto/whereami/blob/master/main.spec) a database file. ## API GET endpoints * **/at** - get all locations<br/> * **/at?name=sofia** - get locations like name<br/> * **/at?name=sofia&latitude=42.7&longitude=23** - set location of name to the given coordinates<br/> * **/where** - same as **/at**<br/> * **/where/sofia** - same as **/at?name=sofia**<br/> * **/where/sofia/42.7/23** - same as **/at?name=sofia&latitude=42.7&longitude=23**<br/> The service has a web interface, but was intended to be accessed from Arduino. Thus, it serves GET endpoints also for PUT operations. For the same reason it also delivers CSV, and not JSON. To see the web interface, visit http://whereami.unriddle.it. <file_sep>#!/usr/bin/env python3 from bottle import Bottle from bottle import template, static_file from bottle import response, request, redirect, abort from settings import debug from settings import static_path, host, port import service app = Bottle(__name__) @app.error(405) def mistake405(code): return "The given call is not allowed by the application." @app.error(404) def mistake404(code): return "Sorry, this page does not exist." @app.get("/at") # ?name=:name&latitude=:latitude&longitude=:longitude def query_location_get(): name = request.query.get("name") if name is not None and type(name) is str and len(name) > 0: latitude = request.query.get("latitude") longitude = request.query.get("longitude") if ( latitude is not None and len(latitude) > 0 and longitude is not None and len(longitude) > 0 ): return service.query_location(name, latitude, longitude) else: return service.query_location(name) else: return service.query_location() @app.get("/where") # @app.get('/where/') @app.get("/where/:name") @app.get("/where/:name/") @app.route( "/where/:name/:latitude/:longitude", method=["GET", "POST", "PUT"] ) # ?name=:name&latitude=:latitude&longitude=:longitude def query_location(name=None, latitude=None, longitude=None): if name is not None and type(name) is str and len(name) > 0: if ( latitude is not None and len(latitude) > 0 and longitude is not None and len(longitude) > 0 ): return service.query_location(name, latitude, longitude) else: return service.query_location(name) else: return service.query_location() """ @route('/delete/:name') def delete_location(name=None): session = Session() if name is not None and len(name) > 0: location = session.query(Locations).filter(Locations.name.like(name)).first() if location is not None: session.delete(location) session.commit() return "Successfully deleted: " + name return "Nothing to delete" """ @app.get("/<filename:re:.*\.js>") def javascripts(filename): return static_file(filename, root=static_path + "/js") @app.get("/<filename:re:.*\.css>") def stylesheets(filename): return static_file(filename, root=static_path + "/css") @app.get("/<filename:re:.*\.(jpg|png|gif|ico)>") def images(filename): return static_file(filename, root=static_path + "/img") @app.get("/<filename:re:.*\.(eot|ttf|woff|svg)>") def fonts(filename): return static_file(filename, root=static_path + "/fonts") @app.get("/") def root(): return static_file("index.html", root=static_path) def start_server(): import os from settings import curdir, db_url from db import reset_db print("Starting in %s" % curdir) if os.path.exists(db_url): print("With database %s" % db_url) else: reset_db(blank=True) app.run(host=host, port=port, debug=debug) if __name__ == "__main__": start_server() <file_sep>#!/usr/bin/env python3 """Run standalone to reset DB for test purposes. Timestamped backup of previous version will be created if it exists""" import os from datetime import datetime from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, Float, String, DateTime, func from settings import db_path, db_url, dateformat_log from settings import debug """ Declare Tables """ Base = declarative_base() engine = create_engine(db_url, echo=debug) class Query(Base): __tablename__ = "query" id = Column(Integer, primary_key=True) hashcode = Column(String) address = Column(String, default=None) latitude = Column(Float) longitude = Column(Float) provider = Column(String, default=None) date = Column(DateTime, default=func.current_timestamp()) class Location(Base): __tablename__ = "location" id = Column(Integer, primary_key=True) name = Column(String, unique=True) address = Column(String, default=None) latitude = Column(Float) longitude = Column(Float) lastseen = Column(DateTime, default=func.current_timestamp()) Session = sessionmaker(bind=engine) session = Session() def reset_db(blank=False, backup=True): timestamp = None if backup and os.path.exists(db_path): timestamp = datetime.now().strftime(dateformat_log) backup = "%s.%s.%s" % (db_path[:-3], timestamp, db_path[-2:]) print("Backup previous database at: %s" % backup) os.rename(db_path, backup) print("Create new database: %s" % db_url) Base.metadata.create_all(engine) print("Populate with dummy data: %s" % ("True" if not blank else "False")) if not blank: mecca = Location(name="MECCA", latitude=21.389082, longitude=39.857912) berlin = Location(name="BERLIN", latitude=52.520007, longitude=13.404954) london = Location(name="LONDON", latitude=51.507351, longitude=-0.127758) milano = Location(name="MILANO", latitude=45.465422, longitude=9.185924) sofia = Location(name="SOFIA", latitude=42.697708, longitude=23.321868) brasilia = Location(name="BRASILIA", latitude=-14.235004, longitude=-51.92528) session.add_all([mecca, berlin, london, milano, sofia, brasilia]) session.commit() return timestamp def restore_db(timestamp): engine.dispose() path = "%s.%s.%s" % (db_path[:-3], timestamp, db_path[-2:]) if timestamp else "" if os.path.exists(path): timestamp = datetime.now().strftime(dateformat_log) os.remove(db_path) print("Restoring previous database from: %s" % path) os.rename(path, db_path) if __name__ == "__main__": reset_db(blank=True) <file_sep>from os import path date_format = "%d/%m/%Y" dateformat_log = "%Y%m%d%H%M%S" # host = '172.16.58.3' host = "localhost" port = 8000 curdir = path.dirname(path.realpath(__file__)) # no trailing slash path.curdir = curdir db_path = curdir + "/locations.db" db_url = "sqlite:///" + db_path + "?check_same_thread=False" static_path = curdir + "/static" debug = False <file_sep>#!/usr/bin/env python """This is very quick and dirty service testing. It makes a copy of the database and wipes it. Also, server remains running at the end and user has to stop it.""" import os import requests from threading import Thread from time import sleep from bottle import WSGIRefServer, run from settings import host, port from db import reset_db, restore_db from main import start_server timeout = 3 root_url = "http://%s:%d" % (host, port) def test_service(url, expected=None): response = requests.get(url) assert response.status_code == 200 if not expected: if response.text: print(response.text) else: if not response.text == expected: print(response.text) print(expected) assert response.text == expected return response.text from threading import Thread import time class TestWSGIServer(WSGIRefServer): """A mimic of WSGIRefServer with changes allowing the server to be shutdown wih a dedicated call. Taken from https://stackoverflow.com/a/19749945/1827854""" def run(self, app): # pragma: no cover from wsgiref.simple_server import WSGIRequestHandler, WSGIServer from wsgiref.simple_server import make_server import socket class FixedHandler(WSGIRequestHandler): def address_string(self): # Prevent reverse DNS lookups please. return self.client_address[0] def log_request(*args, **kw): if not self.quiet: return WSGIRequestHandler.log_request(*args, **kw) handler_cls = self.options.get("handler_class", FixedHandler) server_cls = self.options.get("server_class", WSGIServer) if ":" in self.host: # Fix wsgiref for IPv6 addresses. if getattr(server_cls, "address_family") == socket.AF_INET: class server_cls(server_cls): address_family = socket.AF_INET6 srv = make_server(self.host, self.port, app, server_cls, handler_cls) self.srv = srv ### THIS IS THE ONLY CHANGE TO THE ORIGINAL CLASS METHOD! srv.serve_forever() def shutdown(self): ### ADD SHUTDOWN METHOD. self.srv.shutdown() def start_server(): def begin(server): run(server=server) server = TestWSGIServer(host=host, port=port) Thread(target=begin, args=(server,)).start() return server if __name__ == "__main__": timestamp = reset_db(blank=False) server = start_server() sleep(timeout) # give server time to start expected = "Berlin, 52.520007,13.404954\nBrasilia, -14.235004,-51.92528\nLondon, 51.507351,-0.127758\nMecca, 21.389082,39.857912\nMilano, 45.465422,9.185924\nSofia, 42.697708,23.321868" test_service(root_url + "/at", expected.upper()) expected = "42.697708,23.321868" test_service(root_url + "/at?name=sofia", expected) expected = "42.7,23.0" test_service(root_url + "/at?name=sofia&latitude=42.7&longitude=23", expected) test_service(root_url + "/at?name=sofia", expected) test_service(root_url + "/where") test_service(root_url + "/where/sofia", expected) test_service(root_url + "/where/sofia/42.697708/23.321868") expected = "Berlin, 52.520007,13.404954\nBrasilia, -14.235004,-51.92528\nLondon, 51.507351,-0.127758\nMecca, 21.389082,39.857912\nMilano, 45.465422,9.185924\nSofia, 42.697708,23.321868" test_service(root_url + "/at", expected.upper()) print("Service tests passed!") server.shutdown() sleep(timeout) # give server time to stop restore_db(timestamp)
dc7d45d52c33153215a4ef8cc5ec0ebfa2f27db7
[ "Markdown", "Python" ]
7
Python
mapto/whereami
424b73ce9158279849a2bf42932d76b9a9925cb3
8f583de6a4a1d6582df6f503382ba1dc437efa79
refs/heads/master
<repo_name>henryjordan/iot-oximeter<file_sep>/Oximetro/oximeter-server.cpp // bibliotecas do socketserver #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include "eHealth.h" void error( char *msg ) { perror( msg ); exit(1); } int func1( int a ) { a = eHealth.getBPM(); return a; } int func2( int a ) { a = eHealth.getOxygenSaturation(); return a; } void sendData( int sockfd, int x ) { int n; char buffer[32]; sprintf( buffer, "%d\n", x ); if ( (n = write( sockfd, buffer, strlen(buffer) ) ) < 0 ) error( const_cast<char *>( "ERROR writing to socket") ); buffer[n] = '\0'; } int getData( int sockfd ) { char buffer[32]; int n; if ( (n = read(sockfd,buffer,31) ) < 0 ) error( const_cast<char *>( "ERROR reading from socket") ); buffer[n] = '\0'; return atoi( buffer ); } int cont = 0; void readPulsioximeter(); //lê um valor do oxímetro void setup() { eHealth.initPulsioximeter(); //configura os pinos do shield para o oximetro //Attach the inttruptions for using the pulsioximeter. attachInterrupt(6, readPulsioximeter, RISING); } //inicia o oxímetro anexando as interrupções dos pinos do shield /*void loop() { printf("PRbpm : %d",eHealth.getBPM()); printf(" %%SPo2 : %d\n", eHealth.getOxygenSaturation()); printf("============================="); digitalWrite(2,HIGH); delay(500); }*/ // recebe os dados dos batimentos cardíacos e nível de oxigênio no sangue e imprime os resultados void readPulsioximeter(){ cont ++; if (cont == 50) { //Get only of one 50 measures to reduce the latency eHealth.readPulsioximeter(); cont = 0; } } // realiza a leitura a cada 50 medições dos dados do oxímetro int main (int argc, char *argv[]){ setup(); // preparação do raspberrypi // dados do socketserver int sockfd, newsockfd, portno = 51717, clilen; char buffer[256]; struct sockaddr_in serv_addr, cli_addr; int n; int data1,data2; printf( "using port #%d\n", portno ); sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error( const_cast<char *>("ERROR opening socket") ); bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons( portno ); if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error( const_cast<char *>( "ERROR on binding" ) ); listen(sockfd,5); clilen = sizeof(cli_addr); while(1){ printf( "waiting for new client...\n" ); if ( ( newsockfd = accept( sockfd, (struct sockaddr *) &cli_addr, (socklen_t*) &clilen) ) < 0 ) error( const_cast<char *>("ERROR on accept") ); printf( "opened new communication with client\n" ); while ( 1 ){ //---- wait for a number for BPM from client --- data1 = getData( newsockfd ); printf( "got BPM: %d\n", data1 ); if ( data1 < 0 ) break; data1 = func1( data1 ); //--- send new data back --- printf( "sending back %d\n", data1 ); sendData( newsockfd, data1 ); //---- wait for a number for Spo2 from client --- data2 = getData( newsockfd ); printf( "got %%SPo2 %d\n", data2 ); if ( data2 < 0 ) break; data2 = func2( data2 ); //--- send new data back --- printf( "sending back %d\n", data2 ); sendData( newsockfd, data2 ); } digitalWrite(2,HIGH); close( newsockfd ); //--- if -2 sent by client, we can quit --- if ( data1 == -2 || data2 == -2) break; } return (0); } <file_sep>/cliente-saude.c #include "oc_api.h" // bibliotecas do socket-server #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> // funções do socket-server void sendData( int sockfd, int x ) { int n; char buffer[32]; sprintf( buffer, "%d\n", x ); if ( (n = write( sockfd, buffer, strlen(buffer) ) ) < 0 ) printf( "ERROR writing to socket\n"); buffer[n] = '\0'; } int getData( int sockfd ) { char buffer[32]; int n; if ( (n = read(sockfd,buffer,31) ) < 0 ) printf( "ERROR reading from socket\n"); buffer[n] = '\0'; return atoi( buffer ); } // funcções do simple-client static int app_init(void) { int ret = oc_init_platform("Apple", NULL, NULL); ret |= oc_add_device("/oic/d", "oic.d.phone", "Kishen's IPhone", "1.0", "1.0", NULL, NULL); return ret; } #define MAX_URI_LENGTH (30) static char a_oximeter[MAX_URI_LENGTH]; static oc_server_handle_t oximeter_server; static bool state; static int BPM; static oc_string_t name; char buffer[256]; int n, newsockfd; stop_observe(void *data) { (void)data; PRINT("Stopping OBSERVE\n"); oc_stop_observe(a_oximeter, &oximeter_server); return DONE; } static void observe_oximeter(oc_client_response_t *data) { PRINT("OBSERVE_oximeter:\n"); oc_rep_t *rep = data->payload; while (rep != NULL) { PRINT("key %s, value ", oc_string(rep->name)); switch (rep->type) { case BOOL: PRINT("%d\n", rep->value.boolean); state = rep->value.boolean; break; case INT: BPM = getData( newsockfd ); PRINT("%d\n", rep->value.integer); BPM = rep->value.integer; sendData( newsockfd, BPM ); break; case STRING: PRINT("%s\n", oc_string(rep->value.string)); if (oc_string_len(name)) oc_free_string(&name); oc_new_string(&name, oc_string(rep->value.string), oc_string_len(rep->value.string)); break; default: break; } rep = rep->next; } } static void get_oximeter(oc_client_response_t *data) { PRINT("GET_oximeter:\n"); oc_rep_t *rep = data->payload; //BPM = getData( newsockfd ); while (rep != NULL) { PRINT("key %s, value ", oc_string(rep->name)); switch (rep->type) { case BOOL: PRINT("%d\n", rep->value.boolean); state = rep->value.boolean; break; case INT: BPM = getData( newsockfd ); PRINT("%d\n", rep->value.integer); BPM = rep->value.integer; sendData( newsockfd, BPM ); break; case STRING: PRINT("%s\n", oc_string(rep->value.string)); if (oc_string_len(name)) oc_free_string(&name); oc_new_string(&name, oc_string(rep->value.string), oc_string_len(rep->value.string)); break; default: break; } rep = rep->next; } oc_do_observe(a_oximeter, &oximeter_server, NULL, &observe_oximeter, LOW_QOS, NULL); oc_set_delayed_callback(NULL, &stop_observe, 30); PRINT("Sent OBSERVE request\n"); } static oc_discovery_flags_t discovery(const char *di, const char *uri, oc_string_array_t types, oc_interface_mask_t interfaces, oc_server_handle_t *server, void *user_data) { PRINT("FAZENDO DISCOVERY\n"); (void)di; (void)user_data; (void)interfaces; int i; int uri_len = strlen(uri); uri_len = (uri_len >= MAX_URI_LENGTH) ? MAX_URI_LENGTH - 1 : uri_len; // retirei um dos argumentos do if implementados no simpleclient para realizar o GET for (i = 0; i < (int)oc_string_array_get_allocated_size(types); i++) { PRINT("DENTRO DO FOR\n"); char *t = oc_string_array_get_item(types, i); PRINT("%d \n", strncmp(t, "core.oximeter", 13)); if (strlen(t) == 13 && strncmp(t, "core.oximeter", 13) == 0) { memcpy(&oximeter_server, server, sizeof(oc_server_handle_t)); strncpy(a_oximeter, uri, uri_len); a_oximeter[uri_len] = '\0'; oc_do_get(a_oximeter, &oximeter_server, NULL, &get_oximeter, LOW_QOS, NULL); PRINT("Sent GET request\n"); return OC_STOP_DISCOVERY; } } return OC_CONTINUE_DISCOVERY; } static void issue_requests(void) { oc_do_ip_discovery("core.oximeter", &discovery, NULL); } #include "port/oc_clock.h" #include <pthread.h> #include <signal.h> #include <stdio.h> pthread_mutex_t mutex; pthread_cond_t cv; struct timespec ts; int quit = 0; static void signal_event_loop(void) { pthread_mutex_lock(&mutex); pthread_cond_signal(&cv); pthread_mutex_unlock(&mutex); } void handle_signal(int signal) { (void)signal; signal_event_loop(); quit = 1; } int main(void) { int init; struct sigaction sa; sigfillset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = handle_signal; sigaction(SIGINT, &sa, NULL); int sockfd, portno = 44445, clilen; struct sockaddr_in serv_addr, cli_addr; printf( "using port #%d\n", portno ); sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) printf("ERROR opening socket\n"); bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons( portno ); if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) printf( "ERROR on binding\n" ); listen(sockfd,5); clilen = sizeof(cli_addr); static const oc_handler_t handler = {.init = app_init, .signal_event_loop = signal_event_loop, .requests_entry = issue_requests }; oc_clock_time_t next_event; #ifdef OC_SECURITY oc_storage_config("./creds"); #endif /* OC_SECURITY */ init = oc_main_init(&handler); if (init < 0) return init; while(quit != 1){ printf( "waiting for new client...\n" ); if ( ( newsockfd = accept( sockfd, (struct sockaddr *) &cli_addr, (socklen_t*) &clilen) ) < 0 ) printf("ERROR on accept\n"); printf( "opened new communication with client\n" ); while (quit != 1) { next_event = oc_main_poll(); // onde ocorre o GET e OBSERVE pthread_mutex_lock(&mutex); if (next_event == 0) { pthread_cond_wait(&cv, &mutex); } else { ts.tv_sec = (next_event / OC_CLOCK_SECOND); ts.tv_nsec = (next_event % OC_CLOCK_SECOND) * 1.e09 / OC_CLOCK_SECOND; pthread_cond_timedwait(&cv, &mutex, &ts); } pthread_mutex_unlock(&mutex); } close( newsockfd ); } oc_main_shutdown(); return 0; } <file_sep>/sockets/socket-client-interface.py #!/usr/local/bin/python __author__ = 'kalcho' import socket #import struct target_host = '127.0.0.1' target_port = 51717 # create a floating socket object client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # connect the client client.connect((target_host, target_port)) print("Connected to {:s}:{:d}".format(target_host, target_port)) for n in range(10): client.send(str.encode("".join([str(n)]))) # send some data response = client.recv(4096) # receive some data print(response.decode('utf-8')) <file_sep>/SimpleServer/oximeter-client.c /* // Copyright (c) 2016 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ #include "oc_api.h" // bibliotecas do socketclient #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <netdb.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <arpa/inet.h> // funções do socketclient void sendData( int sockfd, int x ) { int n; char buffer[32]; sprintf( buffer, "%d\n", x ); if ( (n = write( sockfd, buffer, strlen(buffer) ) ) < 0 ) printf("ERROR writing to socket"); buffer[n] = '\0'; } int getData( int sockfd ) { char buffer[32]; int n; if ( (n = read(sockfd,buffer,31) ) < 0 ) printf("ERROR reading from socket"); buffer[n] = '\0'; return atoi( buffer ); } // código do simpleserver static bool state = false; int BPM, spo2; int sockfd; char buffer[256]; oc_string_t name; static int app_init(void) { int ret = oc_init_platform("Intel", NULL, NULL); ret |= oc_add_device("/oic/d", "oic.d.oximeter", "Oximeter", "1.0", "1.0", NULL, NULL); oc_new_string(&name, "Oxímetro", 12); return ret; } static void get_oximeter(oc_request_t *request, oc_interface_mask_t interface, void *user_data) { (void)user_data; // ++power; atualização dos dados sendData( sockfd, BPM ); BPM = getData( sockfd ); sendData( sockfd, spo2 ); spo2 = getData( sockfd ); PRINT("GET_oximeter:\n"); oc_rep_start_root_object(); switch (interface) { case OC_IF_BASELINE: oc_process_baseline_interface(request->resource); case OC_IF_RW: oc_rep_set_boolean(root, state, state); oc_rep_set_int(root, BPM, BPM); oc_rep_set_int(root, spo2, spo2); oc_rep_set_text_string(root, name, oc_string(name)); break; default: break; } oc_rep_end_root_object(); oc_send_response(request, OC_STATUS_OK); } static void register_resources(void) { oc_resource_t *res = oc_new_resource("/a/oximeter", 2, 0); oc_resource_bind_resource_type(res, "core.oximeter"); oc_resource_bind_resource_type(res, "core.oxygen"); oc_resource_bind_resource_interface(res, OC_IF_RW); oc_resource_set_default_interface(res, OC_IF_RW); oc_resource_set_discoverable(res, true); oc_resource_set_periodic_observable(res, 1); oc_resource_set_request_handler(res, OC_GET, get_oximeter, NULL); oc_add_resource(res); } #include "port/oc_clock.h" #include <pthread.h> #include <signal.h> #include <stdio.h> pthread_mutex_t mutex; pthread_cond_t cv; struct timespec ts; int quit = 0; static void signal_event_loop(void) { pthread_mutex_lock(&mutex); pthread_cond_signal(&cv); pthread_mutex_unlock(&mutex); } void handle_signal(int signal) { (void)signal; signal_event_loop(); quit = 1; } int main(int argc, char *argv[]) { int init, i; struct sigaction sa; sigfillset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = handle_signal; sigaction(SIGINT, &sa, NULL); int portno = 51717; char serverIp[] = "127.0.0.1"; struct sockaddr_in serv_addr; struct hostent *server; for(i=1;i<11;i++){ if (argc < 3) { // error( const_cast<char *>( "usage myClient2 hostname port\n" ) ); printf( "contacting %s on port %d\n", serverIp, portno ); // exit(0); } if ( ( sockfd = socket(AF_INET, SOCK_STREAM, 0) ) < 0 ){ printf( "ERROR opening socket"); continue; } if ( ( server = gethostbyname( serverIp ) ) == NULL ){ printf("ERROR, no such host\n"); continue; } bzero( (char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy( (char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); if ( connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0){ printf( "ERROR connecting\n"); sleep(1); continue; } else break; } static const oc_handler_t handler = {.init = app_init, .signal_event_loop = signal_event_loop, .register_resources = register_resources }; oc_clock_time_t next_event; #ifdef OC_SECURITY oc_storage_config("./creds"); #endif /* OC_SECURITY */ init = oc_main_init(&handler); if (init < 0) return init; while (quit != 1) { next_event = oc_main_poll(); pthread_mutex_lock(&mutex); if (next_event == 0) { pthread_cond_wait(&cv, &mutex); } else { ts.tv_sec = (next_event / OC_CLOCK_SECOND); ts.tv_nsec = (next_event % OC_CLOCK_SECOND) * 1.e09 / OC_CLOCK_SECOND; pthread_cond_timedwait(&cv, &mutex, &ts); } pthread_mutex_unlock(&mutex); } oc_main_shutdown(); return 0; } <file_sep>/SimpleServer/oc_api.h /* // Copyright (c) 2016 Intel Corporation // // 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. */ /** @brief Main API of IoTivity-constrained for client and server. @file */ #ifndef OC_API_H #define OC_API_H #include "messaging/coap/oc_coap.h" #include "oc_buffer_settings.h" #include "oc_rep.h" #include "oc_ri.h" #include "oc_signal_event_loop.h" #include "port/oc_storage.h" typedef struct { int (*init)(void); void (*signal_event_loop)(void); #ifdef OC_SERVER void (*register_resources)(void); #endif /* OC_SERVER */ #ifdef OC_CLIENT void (*requests_entry)(void); #endif /* OC_CLIENT */ } oc_handler_t; typedef void (*oc_init_platform_cb_t)(void *data); typedef void (*oc_add_device_cb_t)(void *data); int oc_main_init(const oc_handler_t *handler); oc_clock_time_t oc_main_poll(void); void oc_main_shutdown(void); int oc_add_device(const char *uri, const char *rt, const char *name, const char *spec_version, const char *data_model_version, oc_add_device_cb_t add_device_cb, void *data); #define oc_set_custom_device_property(prop, value) \ oc_rep_set_text_string(root, prop, value) int oc_init_platform(const char *mfg_name, oc_init_platform_cb_t init_platform_cb, void *data); #define oc_set_custom_platform_property(prop, value) \ oc_rep_set_text_string(root, prop, value) /** Server side */ oc_resource_t *oc_new_resource(const char *uri, uint8_t num_resource_types, int device); void oc_resource_bind_resource_interface(oc_resource_t *resource, uint8_t interface); void oc_resource_set_default_interface(oc_resource_t *resource, oc_interface_mask_t interface); void oc_resource_bind_resource_type(oc_resource_t *resource, const char *type); void oc_process_baseline_interface(oc_resource_t *resource); oc_resource_t *oc_new_collection(const char *uri, uint8_t num_resource_types, int device); oc_link_t *oc_new_link(oc_resource_t *resource); void oc_link_add_rel(oc_link_t *link, const char *rel); void oc_link_set_ins(oc_link_t *link, const char *ins); void oc_collection_add_link(oc_resource_t *collection, oc_link_t *link); bool oc_add_collection(oc_resource_t *collection); void oc_resource_make_public(oc_resource_t *resource); void oc_resource_set_discoverable(oc_resource_t *resource, bool state); void oc_resource_set_observable(oc_resource_t *resource, bool state); void oc_resource_set_periodic_observable(oc_resource_t *resource, uint16_t seconds); void oc_resource_set_request_handler(oc_resource_t *resource, oc_method_t method, oc_request_callback_t callback, void *user_data); bool oc_add_resource(oc_resource_t *resource); void oc_delete_resource(oc_resource_t *resource); /** @brief Callback for change notifications from the oic.wk.con resource. This callback is invoked to notify a change of one or more properties on the oic.wk.con resource. The \c rep parameter contains all properties, the function is not invoked for each property. When the function is invoked, all properties handled by the stack are already updated. The callee can use the invocation to optionally store the new values persistently. Once the callback returns, the response will be sent to the client and observers will be notified. @note As of now only the attribute "n" is supported. @note The callee shall not block for too long as the stack is blocked during the invocation. @param device_index index of the device to which the change was applied, 0 is the first device @parem rep list of properties and their new values */ typedef void(*oc_con_write_cb_t)(int device_index, oc_rep_t *rep); /** @brief Sets the callback to receive change notifications for the oic.wk.con resource. The function can be used to set or unset the callback. Whenever an attribute of the oic.wk.con resource is changed, the callback will be invoked. @param callback The callback to register or NULL to unset it. If the function is invoked a second time, then the previously set callback is simply replaced. */ void oc_set_con_write_cb(oc_con_write_cb_t callback); void oc_init_query_iterator(void); int oc_interate_query(oc_request_t *request, char **key, int *key_len, char **value, int *value_len); int oc_get_query_value(oc_request_t *request, const char *key, char **value); void oc_send_response(oc_request_t *request, oc_status_t response_code); void oc_ignore_request(oc_request_t *request); void oc_indicate_separate_response(oc_request_t *request, oc_separate_response_t *response); void oc_set_separate_response_buffer(oc_separate_response_t *handle); void oc_send_separate_response(oc_separate_response_t *handle, oc_status_t response_code); int oc_notify_observers(oc_resource_t *resource); /** Client side */ #include "oc_client_state.h" bool oc_do_ip_discovery(const char *rt, oc_discovery_handler_t handler, void *user_data); bool oc_do_get(const char *uri, oc_server_handle_t *server, const char *query, oc_response_handler_t handler, oc_qos_t qos, void *user_data); bool oc_do_delete(const char *uri, oc_server_handle_t *server, oc_response_handler_t handler, oc_qos_t qos, void *user_data); bool oc_init_put(const char *uri, oc_server_handle_t *server, const char *query, oc_response_handler_t handler, oc_qos_t qos, void *user_data); bool oc_do_put(void); bool oc_init_post(const char *uri, oc_server_handle_t *server, const char *query, oc_response_handler_t handler, oc_qos_t qos, void *user_data); bool oc_do_post(void); bool oc_do_observe(const char *uri, oc_server_handle_t *server, const char *query, oc_response_handler_t handler, oc_qos_t qos, void *user_data); bool oc_stop_observe(const char *uri, oc_server_handle_t *server); /** Common operations */ void oc_set_delayed_callback(void *cb_data, oc_trigger_t callback, uint16_t seconds); void oc_remove_delayed_callback(void *cb_data, oc_trigger_t callback); /** API for setting handlers for interrupts */ #define oc_signal_interrupt_handler(name) \ do { \ oc_process_poll(&(name##_interrupt_x)); \ _oc_signal_event_loop(); \ } while (0) #define oc_activate_interrupt_handler(name) \ (oc_process_start(&(name##_interrupt_x), 0)) #define oc_define_interrupt_handler(name) \ void name##_interrupt_x_handler(void); \ OC_PROCESS(name##_interrupt_x, ""); \ OC_PROCESS_THREAD(name##_interrupt_x, ev, data) \ { \ OC_PROCESS_POLLHANDLER(name##_interrupt_x_handler()); \ OC_PROCESS_BEGIN(); \ while (oc_process_is_running(&(name##_interrupt_x))) { \ OC_PROCESS_YIELD(); \ } \ OC_PROCESS_END(); \ } \ void name##_interrupt_x_handler(void) #endif /* OC_API_H */ <file_sep>/Interface Gráfica Python/oximeter.py from tkinter import * import socket target_host = '127.0.0.1' target_port = 44445 data1 = 0 data2 = 0 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((target_host, target_port)) print("Connected to {:s}:{:d}".format(target_host, target_port)) root = Tk() root.geometry("480x360") root.title("Cliente OCF") root.resizable(0,0) #background = PhotoImage(file="heart.png") #background_label = Label(root, image=background) #background_label.place(x=0, y=0, relwidth=1, relheight=1) photo = PhotoImage(file="OCF.png") img = Label(root, image=photo) img.place(relx=0.5, rely=0.2, anchor=CENTER) def printBPM(event): global data1, data2 client.send(str.encode("".join([str(data1)]))) # send some data data1 = client.recv(4096) # receive some data print(data1.decode('utf-8')) client.send(str.encode("".join([str(data2)]))) # send some data data2 = client.recv(4096) # receive some data print(data2.decode('utf-8')) valor1 = Label(root, text=data1, fg="black", width=4) valor1.place(relx=0.65, rely=0.5, anchor=CENTER) valor2 = Label(root, text=data2, fg="black", width=4) valor2.place(relx=0.65, rely=0.65, anchor=CENTER) bpm = Label(root, text="BPM", fg="black") bpm.place(relx=0.35, rely=0.5, anchor=CENTER) spo2 = Label(root, text="spO2", fg="black") spo2.place(relx=0.35, rely=0.65, anchor=CENTER) button1 = Button(text="Capturar Dados", width=12) button1.bind("<Button-1>", printBPM) button1.place(relx=0.5, rely=0.825, anchor=CENTER) credits = Label(root, text="Autor: <NAME>", fg="black") credits.pack(side=BOTTOM) root.mainloop()
894a95321772db9c7e7c4e50a942738a890b4b50
[ "C", "Python", "C++" ]
6
C++
henryjordan/iot-oximeter
54edd0a053efb028b1d38525739a09cac663a9fd
4120f7bcb3757855bb732341031b1e4a925c6942
refs/heads/master
<repo_name>maxnuf/df34_raw_conversion<file_sep>/db/src/data/loads/generate_declet.R a = 0:999; # Generate a list of 1000 declets in hexadecimal form positive1 = cbind(sprintf("%04X", a), "8", 0, sprintf("%03d",a)); # Generate a list wither the declet is 2 bits shifted positive2 = cbind(sprintf("%04X", bitwShiftL(a,2)), "8", 2, sprintf("%03d",a)); # For negative values, perform inverse counting negative1 = cbind(sprintf("%04X", a), "0", 0, sprintf("%03d",999-a)); negative2 = cbind(sprintf("%04X", bitwShiftL(a,2)), "0", 2, sprintf("%03d",999-a)); out = rbind(positive1, positive2, negative1, negative2); colnames(out) <- c("declet", "sign", "shift", "number"); write.csv(out, file="declets.csv", row.names = FALSE) <file_sep>/README.md # df34_raw_convesion Example DF34_RAW conversion in SQL
9ad500cde57c61b97ba6aa69425d03f7e654be3a
[ "Markdown", "R" ]
2
R
maxnuf/df34_raw_conversion
1dd3abbb1c6594aaf36da6cafe00714af6c0aba7
8268197f17bbda8d5d0fe0734827a12e657d5c12
refs/heads/master
<repo_name>Icedroid/notes<file_sep>/nginx.md # Nginx知识学习 ## Nginx信号 $(NginxMasterPID):表示Nginx Master进程ID ### Nginx优雅停止服务: ``` kill -QUIT $(NginxMasterPID) 或 nginx -s quit ``` ### Nginx立即停止服务: ``` kill -TERM $(NginxMasterPID) 或 kill -INT $(NginxMasterPID) 或 nginx -s stop ``` ### Nginx重载配置文件(work进程会重启): ``` kill -HUP $(NginxMasterPID) 或 nginx -s reload ``` ### Nginx重新开始记录日志文件(reopen): ``` kill -USR1 $(NginxMasterPID) 或 nginx -s reopen ``` ### Nginx热升级 ![Nginx热更新流程](img/Nginx热更新流程.jpg) ``` mv nginx nginx.old kill -USR2 $(NginxMasterPID) kill -WINCH $(NginxMasterPID) //这个时候旧的Master进程还是存在的: //要退出旧master进程,发送:kill -QUIT $(NginxMasterPID) //版本回退,发送:kill -HUP $(NginxMasterPID) ``` <file_sep>/bash/nginx_rotate_logs.sh # /bin/bash #添加到系统定时任务中crontab -e # 0 0 1 * * sh /opt/nginx/logs/nginx_rotate_logs.sh >/dev/null 2>&1 # 日志保存位置 base_path='/opt/nginx/logs' # 获取当前年信息和月信息 log_path=$(date -d yesterday +"%Y%m") # 获取昨天的日信息 day=$(date -d yesterday +"%d") # 按年月创建文件夹 mkdir -p $base_path/$log_path # 备份昨天的日志到当月的文件夹 mv $base_path/access.log $base_path/$log_path/access_$day.log # 输出备份日志文件名 # echo $base_path/$log_path/access_$day.log # 向Nginx Master进程发送重新打开日志文件信号 kill -USR1 $(cat /opt/nginx/logs/nginx.pid)
509bc3931c71d1477f4999d71fef3f969e20eed9
[ "Markdown", "Shell" ]
2
Markdown
Icedroid/notes
e297f1eae507d195b00109c11c608735afa280ae
2dbb13f3e8da24bb116a176a2c8263a097a3383c
refs/heads/main
<file_sep># PythonIntermedio Scripts - Curso Intermedio Python <file_sep> def main(): my_list = [1, "Hello", True, 4.5] my_dict = {"firstname": "Kevin", "lastname":"Cardenas"} super_list = [ {"firstname": "Kevin", "lastname":"Cardenas"}, {"firstname": "Miguel", "lastname":"Lopez"}, {"firstname": "Tania", "lastname":"Cardenas"}, {"firstname": "Bryan", "lastname":"Duque"} ] super_dict = { "natural_nums": [1, 2, 3, 4, 5], "integer_nums": [-1, -2, 0, 1, 2], "floating_nums": [1.1, 4.5, 6.43] } for key, value in super_dict.items(): print(key, "-", value) for idx in super_list: for key, value in idx.items(): print(key, "-", value) for idx in super_list: print(idx.items()) for idx in super_list: print(idx["firstname"], "-", idx["lastname"]) if __name__ == "__main__": main()<file_sep> from functools import reduce def main(): #filter # my_list = [1, 4, 5, 6, 9, 13, 19, 21] # odd = list(filter(lambda x: x % 2 != 0, my_list)) # print(odd) #map # my_list = [1, 2, 3, 4, 5] # squares = list(map(lambda x: x**2, my_list)) # print(squares) #reduce my_list = [2, 2, 2, 2, 2] all_multiplied = reduce(lambda a,b: a*b, my_list) print(all_multiplied) if __name__ == "__main__": main()<file_sep> def main(): squares = [] # for i in range (1,101): # squares.append(i**2) # print(squares) # for i in range (1,101): # if i % 3 != 0: # squares.append(i**2) # print(squares) #Example of list comprehensions # squares = [i**2 for i in range(1, 101) if i % 3 != 0] # print(squares) #Example 2 of list comprenhensions new_list = [i for i in range(1, 100000) if i % 4 == 0 and i % 6 == 0 and i % 9 == 0] print(new_list) if __name__ == "__main__": main()<file_sep>import random NUMBERS = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] def read_file(): WORDS = [] with open("./archivos/data.txt", "r", encoding="utf-8") as f: for line in f: WORDS.append(line.replace("\n", "")) return WORDS def random_word(words): idx = random.randint(0, len(words) - 1) return words[idx] def main(): print("* - * - * - * - * - * - * - * - *- *- *") print("B I E N V E N I D O A H A N G M A N") print("* - * - * - * - * - * - * - * - *- *- *") print("\n") print("¡Adivina la palabra oculta!") tries = 0 words = read_file() current_word = random_word(words) hidden_word = ['-' for i in current_word] print(hidden_word) try: while True: current_letter = input("Ingresa una letra: ") for i in range(len(NUMBERS)): if current_letter == NUMBERS[i]: raise ValueError("No ingreses números, solamente letras, por favor") letter_indexes = [] for idx in range(len(current_word)): if current_letter == current_word[idx]: letter_indexes.append(idx) if len(letter_indexes) == 0: tries += 1 if tries == 7: print(hidden_word) print("") print("¡Perdiste! La palabra correta era {}".format(current_word)) break else: for idx in letter_indexes: hidden_word[idx] = current_letter print(hidden_word) letter_indexes = [] try: hidden_word.index("-") except ValueError: print("¡Ganaste! La palabra era {}".format(current_word)) break except ValueError as ve: print(ve) if __name__ == "__main__": main() <file_sep> def main(): palindorme = lambda string: string == string[::-1] print(palindorme("ana")) if __name__ == "__main__": main()
cbaf31815035018008594b73e80e9c770bdf12d1
[ "Markdown", "Python" ]
6
Markdown
KevinCardenasDev/PythonIntermedio
022fa790ac57263df26cc44c68ea1e8b92e94cff
a9865967343f5bfb0623d4396f660ff52bab96e3
refs/heads/master
<repo_name>pethaniakshay/OAuth2-Playground<file_sep>/resource-server/src/main/java/com/codepuran/ors/dto/UserDto.java package com.codepuran.ors.dto; import lombok.*; import java.util.List; @Getter @Setter @Builder @ToString @NoArgsConstructor @AllArgsConstructor public class UserDto { private Long id; private String name; private String email; private String password; private List<Long> roleIds; public UserDto(Long id, String name, String email) { this.id = id; this.name = name; this.email = email; } } <file_sep>/resource-server/src/main/java/com/codepuran/ors/dto/IdNameDto.java package com.codepuran.ors.dto; public class IdNameDto {} <file_sep>/resource-server/src/main/java/com/codepuran/ors/service/RoleService.java package com.codepuran.ors.service; import org.springframework.stereotype.Service; @Service public class RoleService {} <file_sep>/README.md #### References https://www.baeldung.com/spring-security-5-oauth2-login https://github.com/dzinot/spring-boot-2-oauth2-authorization-jwt https://www.devglan.com/spring-security/spring-boot-security-oauth2-example https://github.com/rudiansen/copsboot-app https://www.infoq.com/minibooks/spring-boot-building-api-backend https://www.baeldung.com/sso-spring-security-oauth2 https://www.baeldung.com/spring-security-oauth2-enable-resource-server-vs-enable-oauth2-sso <file_sep>/resource-server/src/main/java/com/codepuran/ors/controller/RoleController.java package com.codepuran.ors.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api/v1/role") public class RoleController {} <file_sep>/resource-server/src/main/java/com/codepuran/ors/controller/UserController.java package com.codepuran.ors.controller; import com.codepuran.ors.dto.UserDto; import com.codepuran.ors.service.UserService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api/v1/user") public class UserController { private final UserService userService; public UserController(UserService userService) { this.userService = userService; } @PostMapping public ResponseEntity<?> createUser(@RequestBody UserDto userDto) { return new ResponseEntity<>(userService.createUser(userDto), HttpStatus.CREATED); } @GetMapping public ResponseEntity<?> getAllUser() { return new ResponseEntity<>(userService.getAllUser(), HttpStatus.OK); } @GetMapping("/{id}") public ResponseEntity<?> getUserById(@PathVariable("id") Long id) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } } <file_sep>/resource-server/src/main/java/com/codepuran/ors/entity/User.java package com.codepuran.ors.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.*; import javax.persistence.*; import java.util.HashSet; import java.util.Set; @Entity @Builder @Getter @Setter @Table(name = "user") @NoArgsConstructor @AllArgsConstructor public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String email; @JsonIgnore private String password; @ManyToMany(fetch = FetchType.EAGER) @JoinTable( name = "user_role", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) private Set<Role> roles = new HashSet<>(); }
4c036faa50ecc8daac27f311dcb5ffe67cdc3f43
[ "Markdown", "Java" ]
7
Java
pethaniakshay/OAuth2-Playground
bc455fd7f17ffbbf5fb6ae7a7fba12d491e4ba8b
6986272f5fa37eea6506e6b9000c8803d7c6731c
refs/heads/main
<file_sep>Example: ```local lbt = require("lbt") local test_string = [[<Trigger name="Take Bandage" state="False" id="6"/>]] local new = lbt.gsub(test_string, '<Trigger name="*s" state="*s" id="*s"/>', function(name, state, id) return 'Trigger name is ' .. name .. " state = " .. state:lower() .. " and id = " .. id end) print(new) <file_sep>local lbt = require("lbt") local test_string = [[<Trigger name="Take Bandage" state="False" id="6"/>]] local new = lbt.gsub(test_string, '<Trigger name="*s" state="*s" id="*s"/>', function(name, state, id) return 'Trigger name is ' .. name .. " state = " .. state:lower() .. " and id = " .. id end) print(new)
a0efe696d02cda74e199f9665cd5faae457d23a0
[ "Markdown", "Lua" ]
2
Markdown
borsuczyna/lbt.gsub
8e3f16d65717aff7e26537a98a4ad288342795d3
5e38917cf591a4bd13d8aca7c91758f055edfba1
refs/heads/master
<file_sep>Airbake .NET ============ **This is a work in progress, to create a new .NET notifier library.** <img src="http://f.cl.ly/items/0L0G1z0E2A1P3H2O042F/dotnet%2009.19.32.jpg" width=800px> Introduction ------------ Airbrake .NET is a C# library for [Airbrake][airbrake.io], the leading exception reporting service. Airbrake .NET provides minimalist API that enables the ability to send _any_ .NET exception to the Airbrake dashboard. The library is extremely lightweight, contains _no_ dependencies and perfectly suits for every .NET application, including ASP.NET MVC, WPF, WebAPI applications. Key features ------------ * Uses the new Airbrake JSON API (v3) * Simple, consistent and easy-to-use library [API](#api) * Asynchronous exception reporting (optional, enabled by default) * Flexible logging support (configure your own logger) * Flexible configuration options (configure as many Airbrake notifers in one application as you want) * Support for proxying * Filters support (filter out sensitive or unwated data that shouldn't be displayed) * Ability to ignore certain exceptions based on their data completely (based on exception class, backtrace and more) * SSL support (all communication with Airbrake is encrypted by default) * Support for fatal exceptions (the ones that terminate your program) * Last but not least, we follow [semantic versioning 2.0.0][semver2] Installation ------------ ### NuGet To install [Airbrake .NET][airbrake-nuget]), run the following command in the [Package Manager Console][pmc]): ```c# PM> Install-Package Airbrake ``` ### Manual Download the latest [Airbrake.dll](https://github.com/kyrylo/airbrake-dotnet/releases/latest) and reference it in your project. Examples -------- ### Basic example This is the minimal example that you can use to test Airbrake .NET with your project. ```c# using System.Collections.Generic; using Airbrake; Dictionary<string, string> config; config["projectId"] = "113743"; config["projectKey"] = "fd04e13d806a90f96614ad8e529b2822"; var airbrake = new Airbrake(config); try { int zero = 0; int n = 10 / zero; } catch (Exception ex) { airbrake.Notify(ex); } ``` Integrations with other frameworks offer _automatic_ exception reporting. ### ASP.NET MVC Applications 1. Configure Airbrake .NET inside the `Web.config` file (see the [Configuration](#configuration) section for available config options): ```c# <configuration> <configSections> <section name="airbrakeConfig" type="Airbrake.ConfigurationStorage.ConfigSection, Airbrake" /> </configSections> <airbrakeConfig projectId="113743" /> <airbrakeConfig projectKey="fd04e13d806a90f96614ad8e529b2822" /> </configuration> ``` 2. Import the `Airbrake.Clients` namespace into your application: ```c# using Airbrake.Clients; ``` 3. Find the `App_Start > FilterConfig.cs` file and add the `WebMVCClient` error handler inside the `RegisterWebApiFilters` function. ```c# filters.Add(WebMVCClient.ErrorHandler()); ``` ### WPF Applications 1. Configure Airbrake .NET inside the `App.config` file (see the [Configuration](#configuration) section for available config options): ```c# <configuration> <configSections> <section name="airbrakeConfig" type="Airbrake.ConfigurationStorage.ConfigSection, Airbrake" /> </configSections> <airbrakeConfig projectId="113743" /> <airbrakeConfig projectKey="fd04e13d806a90f96614ad8e529b2822" /> </configuration> ``` 2. Import the `Airbrake.Clients` namespace into your application: ```c# using Airbrake.Clients; ``` 3. Find the `App.xaml.cs` file and invoke `WPFClient.Start()` inside the `OnStartup` function. ### Web API Applications 1. Configure Airbrake .NET inside the `Web.config` file (see the [Configuration](#configuration) section for available config options): ```c# <configuration> <configSections> <section name="airbrakeConfig" type="Airbrake.ConfigurationStorage.ConfigSection, Airbrake" /> </configSections> <airbrakeConfig projectId="113743" /> <airbrakeConfig projectKey="fd04e13d806a90f96614ad8e529b2822" /> </configuration> ``` 2. Import the `Airbrake.Clients` namespace into your application: ```c# using Airbrake.Clients; ``` 3. Find the `App_Start > FilterConfig.cs` file and add the `WebAPIClient` error handler inside the `RegisterWebApiFilters` function. ```c# filters.Add(WebAPIClient.ErrorHandler()); ``` Configuration ------------- Configration is done per-instance. That is, to start configuring, simply instantiate the `Airbrake` class and pass the configuration `Dictionary<string, string>`. You can create as many instances with various configurations as you want. ```с# Dictionary<string, string> config = new Dictionary<string, string>(); config["projectId"] = "113743"; config["projectKey"] = "fd04e13d806a90f96614ad8e529b2822"; var airbrake = new Airbrake(config); ``` In order to reconfigure the notifier, simply create a new instance of the Airbrake class with the new options. ### Config options #### project_id & project_key You **must** set both `project_id` & `project_key`. To find your `project_id` and `project_key` navigate to your project's _General Settings_ and copy the values from the right sidebar. ![][project-idkey] ```с# Dictionary<string, string> config = new Dictionary<string, string>(); config["projectId"] = "113743"; config["projectKey"] = "fd04e13d806a90f96614ad8e529b2822"; var airbrake = new Airbrake(config); ``` #### proxy If your server is not able to directly reach Airbrake, you can use built-in proxy. By default, Airbrake .NET uses direct connection. ```c# Dictionary<string, string> config = new Dictionary<string, string>(); config["proxy"] = "john-doe:<EMAIL>:4038"; var airbrake = new Airbrake(config); ``` #### async By default, Airbrake .NET sends exceptions asynchronously, to minimise the impact on your application's performance. If this is unwanted behaviour, you can disable it. ```c# Dictionary<string, string> config = new Dictionary<string, string>(); config["async"] = "false"; var airbrake = new Airbrake(config); ``` #### logger By default, Airbrake .NET outputs to `STDOUT`. It's possible to add your custom logger. ```c# // Figure out how! ``` #### app_version The version of your application that you can pass to differentiate exceptions between multiple versions. It's not set by default. ```c# Dictionary<string, string> config = new Dictionary<string, string>(); config["app_version"] = "1.0.0"; var airbrake = new Airbrake(config); ``` #### host By default, it is set to `airbrake.io`. A `host` is a web address containing a scheme ("http" or "https"), a host and a port. You can omit the port (80 will be assumed) and the scheme ("https" will be assumed). ```c# Dictionary<string, string> config = new Dictionary<string, string>(); config["host"] = "http://localhost:8080"; var airbrake = new Airbrake(config); ``` API --- TBD. Additional notes ---------------- ### Exception limit The maximum size of an exception is 64KB. Exceptions that exceed this limit will be truncated to fit the size. Supported .NET versions ----------------------- * ? License ------- To be decided. [airbrake.io]: https://airbrake.io [airbrake-nuget]: https://www.nuget.org/packages/Airbrake/ [semver2]: http://semver.org/spec/v2.0.0.html [notice-v3]: https://airbrake.io/docs/#create-notice-v3 [project-idkey]: https://img-fotki.yandex.ru/get/3907/98991937.1f/0_b558a_c9274e4d_orig <file_sep>using System; namespace Airbrake { public class MyClass { public MyClass () { } } }
b42debf8f1e8188068de30c0661ec40ed5c654a9
[ "Markdown", "C#" ]
2
Markdown
kyrylo/airbrake-dotnet
3a16c4c107df407451df1f4992826814c521e00d
7da44ae29834ef56ad8e1ff9264990a05c32e9a9
refs/heads/master
<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! | */ /* <NAME> Route::get('/users/{id}/{name}',function($id,$name){ return 'Ovo je korisnik broj: '. $id.' a njegovo ime je: '. $name; }); */ /* RANIJE KORISCEN KOD Route::get('/', function () { return view('welcome'); }); Route::get('/about',function(){ return view('pages.about'); //vraca iz view stranicu pages/about }); */ Route::get('/','PagesController@pocetna'); //prvi argument je url koji ce biti,a drugi kontroler@fja i ta odredjena Route::get('/about','PagesController@about'); //fja npr vrati neki view i prikazuje neku stranicu Route::get('/materijali','PagesController@materijali'); Route::resource('posts','PostsController'); //samo pravi sve routove za fje koje smo prethodno napravili u PostsController Auth::routes(); Route::get('/dashboard', 'DashboardController@index'); <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Post; // i s ovim mozemo da koristimo koju hocemo fju modela use DB; //ako necemo elokvent da koristimo nego SQL //da bi mogli da koristimo storage i brisemo sliku potrebno nam je ovo ukljuciti use Illuminate\Support\Facades\Storage; class PostsController extends Controller { //TRAZI DA BUDEMO ULOGOVANI DA BI BILO STA VIDELI public function __construct() { //$this->middleware('auth'); OVIM NISTA NE MOZE DA SE VIDI DOK SE NE ULOGUJEMO,ali ako prosledimo dodatne parametre //onda mozemo jer to su posebni slucajevi $this->middleware('auth',[ 'except' => ['index','show'] ]); //ne moze bez logina se pristupi svemu osim index i show } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // ispisao bi sve podatke iz baze sa ovom komandom return Post::all(); // $posts = Post::all(); // $posts = DB::select('SELECT * FROM posts'); preko sql,radi isto sto i Post::all(); tj da nam citav post // $posts = Post::orderBy('created_at','desc')->take(1)->get(); i tako dobijemo PRIKAZAN samo jedan post //$posts = Post::orderBy('created_at','desc')->get(); //stavimo u posts sortirane sve postove $posts = Post::orderBy('created_at','desc')->paginate(3); //koliko postova da se prikaze po stranici u paginate se stavlja return view('posts.index')->with('posts',$posts); //argument u paginate je broj postova koje zelimo na jednoj //stranici prikazati } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('posts.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) //iz forme cemo uzimati varijable i to ce primati objekat request { //Validacija tj provera $this->validate($request, [ 'title' => 'required', 'body' => 'required', 'cover_image' => 'image|nullable|max:1999' //image znaci da moze da se ubaci slika,nullable- da ne mora,i ogranicavamo koliko max moze biti slika velicine ]); //Rukovanje uplodom fajla //ako osoba zapravo izabere da ubaci nesto (browse..) if($request->hasFile('cover_image')){ //dobijanje imena slike bez ekstenzije $filenameWithExt = $request->file('cover_image')->getClientOriginalName(); // s ovim dobijemo npr marko.jpg ali zbog mogucnosti da jos //neko uplouduje marko.jpg onda radimo sledece //dobijanje imena samo fajla $filename = pathinfo($filenameWithExt,PATHINFO_FILENAME); //php fja koja ekstrakuje ime fajla samo bez ekstenzije //dobijanje samo $extension = $request->file('cover_image')->getClientOriginalExtension(); //ime koje cuvamo na kraju $fileNameToStore = $filename .'_'.time().'.'.$extension; //i imamo originalno ime za svaku promenljivu //Upload slike $path = $request->file('cover_image')->storeAs('public/cover_images',$fileNameToStore); }else{ $fileNameToStore = 'noimage.jpg'; //ako nema slike da se stavi,stavicemo neku difolt sliku noimage.jpg } //Kreiranje posta $post = new Post; $post->title= $request->input('title'); $post->body = $request->input('body'); $post->user_id = auth()->user()->id; //uzima id trenutnog usera $post->cover_image = $fileNameToStore; $post->save(); return redirect('/posts')->with('success','Clanak je uspesno kreiran!'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) //pokazivacemo odredjeni post na osnovu id npr { //return Post::find($id); //nacice taj post(po idu) i prikazacemo ga $post = Post::find($id); return view('posts.show')->with('post',$post); //vracamo da prikazemo stranicu show(u folderu posts) //i jos prosledjujem citav post da moze da se koristi } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) //da bi znao koji post da edituje,imamo argument id { $post = Post::find($id); //provera korisnika if(auth()->user()->id !== $post->user_id){ //ako nije njegov post a pokusa edit,prebaci ga na /posts return redirect('/posts')->with('error','Nemas pristup ovoj stranici!'); } return view('posts.edit')->with('post',$post); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) //argument request jer dodajem novi post(jeste izmenjen ali je pak novi) { //id da bi znali o kome se radi //Validacija tj provera $this->validate($request, [ 'title' => 'required', 'body' => 'required' ]); //Rukovanje uplodom fajla //ako osoba zapravo izabere da ubaci nesto (browse..) if($request->hasFile('cover_image')){ //dobijanje imena slike bez ekstenzije $filenameWithExt = $request->file('cover_image')->getClientOriginalName(); // s ovim dobijemo npr marko.jpg ali zbog mogucnosti da jos //neko uplouduje marko.jpg onda radimo sledece //dobijanje imena samo fajla $filename = pathinfo($filenameWithExt,PATHINFO_FILENAME); //php fja koja ekstrakuje ime fajla samo bez ekstenzije //dobijanje samo $extension = $request->file('cover_image')->getClientOriginalExtension(); //ime koje cuvamo na kraju $fileNameToStore = $filename .'_'.time().'.'.$extension; //i imamo originalno ime za svaku promenljivu //Upload slike $path = $request->file('cover_image')->storeAs('public/cover_images',$fileNameToStore); } //Kreiranje posta $post = Post::find($id); //nadjemo taj post kako bi ga izmenili $post->title= $request->input('title'); $post->body = $request->input('body'); if($request->hasFile('cover_image')){ $post->cover_image = $fileNameToStore; } $post->save(); return redirect('/posts')->with('success','Clanak je uspesno izmenjen!'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) //id da bi znali koji post da unistimo { $post = Post::find($id); //provera korisnika if(auth()->user()->id!== $post->user_id){ //ako nije njegov post a pokusa delete,prebaci ga na /posts return redirect('/posts')->with('error','Nemas pristup ovoj stranici!'); } if($post->cover_image != 'noimage.jpg' ){ //obrisi sliku onda ,tj da ne bi slucajno izbrisali nasu difolt sliku (noimage.jpg) //use Illuminate\Support\Facades\Storage; to smo uradili i mozemo sad Storage:: da koristimo Storage::delete('public/cover_images/' . $post->cover_image); //i tako i sliku obrisemo } $post->delete(); //post obrisemo return redirect('/posts')->with('success','Clanak je uspesno uklonjen!'); } } <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { /* Kada pravimo jedan post,ima id,naslov,i telo i dve kolone od timestamps (jedna kad je kreirano jedna kad je update uradjen) */ Schema::create('posts', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('title'); //naslov posta $table->mediumText('body'); //malo veci tekst za telo posta $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { //Ako brisemo post,sve neka obrise,tj citav Schema::dropIfExists('posts'); } } <file_sep><p align="center"><img src="https://res.cloudinary.com/dtfbvvkyp/image/upload/v1566331377/laravel-logolockup-cmyk-red.svg" width="400"></p> ## Ideja Akumulirati sva stiva relevantna za jedan smer i usmerenje na nekom od fakulteta. Kako bi buduce generacije imale jedno koncizno i koncentrisano mesto na kome mogu pronaci sta im je potrebno. <file_sep><?php namespace App; //model se zove App use Illuminate\Database\Eloquent\Model; class Post extends Model //Naslov mu je Post { //ovako zelimo da izgleda nas model ,imamo neke po difoltu stvari ali ovo zelimo dodatno //Ime tabele protected $table ='posts'; //primarni kljuc public $primaryKey = 'id'; //Timestamps public $timestamps =true; //kreiranje relacije public function user(){ return $this->belongsTo('App\User'); //svaki post pripada nekom useru } }
5ed3055e0a3c84917b8adb3dfb2647bb11d9b8e9
[ "Markdown", "PHP" ]
5
PHP
vlaksi/KulminacijaZnanjaApp
815b055f51275c30f39cf6e6d0ff8141f12c5e9d
ce7f2ef53cd576cda6ef81431095e7775325197e
refs/heads/dillinger
<file_sep>/* * This file is part of Dorpsgek. * * Dorpsgek is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Dorpsgek is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Dorpsgek. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "definitions.h" #include "functions.h" uint64_t zobrist_piece[2][6][64]; uint64_t zobrist_side; uint64_t zobrist_castle[16]; uint64_t zobrist_ep[8]; static uint64_t rngseed = 0xd6fa57e9aea945e8ULL; /* 8 bytes from random.org */ uint64_t xorshift64star() { rngseed ^= rngseed >> 12; // a rngseed ^= rngseed << 25; // b rngseed ^= rngseed >> 27; // c return rngseed * 2685821657736338717ULL; } void InitZobrist() { int i, j, k; for (i = WHITE; i <= BLACK; i++) { for (j = KING; j <= PAWN; j++) { for (k = 0; k < 64; k++) { zobrist_piece[i][j][k] = xorshift64star(); } } } zobrist_side = xorshift64star(); for (i = 0; i < 16; i++) { zobrist_castle[i] = xorshift64star(); } for (i = 0; i < 8; i++) { zobrist_ep[i] = xorshift64star(); } /* hack to ensure correct initialisation */ hash_table.size = 0; } void CalculateHash(Board* b) { unsigned int side, piece, square; uint64_t hash = 0; for (int i = 0; i < 32; i++) { if (b->sidemask[WHITE].contains(i)) { side = WHITE; } else if (b->sidemask[BLACK].contains(i)) { side = BLACK; } else { continue; } square = b->piecelist[i]; piece = GetPieceByBit(b, Bitlist{i}); hash ^= zobrist_piece[side][piece][square]; } if (b->side == BLACK) { hash ^= zobrist_side; } hash ^= zobrist_castle[b->castle]; if (b->ep != INVALID) { hash ^= zobrist_ep[COL(b->ep)]; } b->hash = hash; } struct TT hash_table; #define hashfEXACT 0 #define hashfALPHA 1 #define hashfBETA 2 void ClearTT() { memset(hash_table.table, 0, hash_table.size * sizeof(struct TTEntry)); } void InitTT(int memory) { unsigned long long size, target; /* Hash table */ target = memory; if (target < 4) { target = 16; } if (target > 8192) { target = 8192; } target *= 1024 * 1024; for (size = 1; size != 0 && size <= target; size *= 2); size /= 2; // allocate table size /= sizeof(struct TTEntry); // Check if the size is identical to before. if (size == hash_table.size) { printf("# Ignoring duplicate 'memory' command; clearing hash.\n"); ClearTT(); return; } // Free TT if necessary if (hash_table.size != 0) { FreeTT(); } hash_table.size = size; // HACK to avoid testing for end of table hash_table.table = (struct TTEntry *) malloc(hash_table.size*sizeof(struct TTEntry)); if (hash_table.table == NULL) { fprintf(stderr, "# malloc() returned NULL\n"); exit(1); } printf("# Allocated %d megabyte hash table of %d elements.\n", (size*sizeof(struct TTEntry))/(1024*1024), size); ClearTT(); } void FreeTT() { BUG(hash_table.size != 0); printf("# Deallocated %d megabyte hash table of %d elements.\n", (hash_table.size*sizeof(struct TTEntry))/(1024*1024), hash_table.size); free(hash_table.table); hash_table.size = 0; } int ReadTT(Board* b, Move* m, int* tt_score, int depth, int alpha, int beta, int ply) { BUG(hash_table.size != 0); BUG(b->hash != 0); struct TTEntry* entry = &hash_table.table[b->hash % hash_table.size]; BUG(entry != NULL); tt_probes++; int val = entry->value; if (val >= 9500) { val = val - ply; } if (val <= -9500) { val = val + ply; } m->from = INVALID; m->dest = INVALID; m->type = INVALID; m->score = 0; if (entry->key == b->hash) { tt_hits++; if (entry->depth >= depth) { if (entry->flags == hashfEXACT) { *tt_score = val; return 1; } if ((entry->flags == hashfALPHA) && (val <= alpha)) { *tt_score = val; return 1; } if ((entry->flags == hashfBETA) && (val >= beta)) { *tt_score = val; return 1; } } m->from = entry->from; m->dest = entry->dest; m->type = entry->type; m->score = 0; //return 1; } return 0; } void WriteTT(Board* b, int depth, int val, int hashf, Move m, int ply) { BUG(hash_table.size != 0); BUG(b->hash != 0); BUG(m.from != INVALID); BUG(m.dest != INVALID); BUG(m.type >= 0 && m.type <= 13); struct TTEntry* entry = &hash_table.table[b->hash % hash_table.size]; if (val >= 9500) { val = val + ply; //hashf = hashfEXACT; } if (val <= -9500) { val = val - ply; //hashf = hashfEXACT; } entry->key = b->hash; entry->from = m.from; entry->dest = m.dest; entry->type = m.type; entry->value = val; entry->flags = hashf; entry->depth = depth; } <file_sep>/* * This file is part of Dorpsgek. * * Dorpsgek is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Dorpsgek is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Dorpsgek. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include "definitions.h" #include "functions.h" void DebugBitlists(Board* b) { int idx; Board c; ClearBoard(&c); for (idx = 0; idx < 64; idx++) { c.index[idx] = b->index[idx]; } for (idx = 0; idx < 32; idx++) { c.piecelist[idx] = b->piecelist[idx]; } for (idx = 0; idx < 6; idx++) { c.piecemask[idx] = b->piecemask[idx]; } c.sidemask[WHITE] = b->sidemask[WHITE]; c.sidemask[BLACK] = b->sidemask[BLACK]; RecalculateAttacksFromScratch(&c); for (idx = 0; idx < 64; idx++) { if (AttacksToSquare(*b, idx) != AttacksToSquare(c, idx)) { printf("================================\n"); printf("Bitlist at square %c%u for B:\n", 'a' + COL (idx), 1 + ROW (idx)); PrintBitlistForSquare(b, idx); printf("Bitlist at square %c%u for C:\n", 'a' + COL (idx), 1 + ROW (idx)); PrintBitlistForSquare(&c, idx); } } } void PrintBitlistForPiece(Board* b, int piece) { BUG(b != NULL); BUG(piece >= KING && piece <= PAWN); int i; for (i = 0; i < 64; i++) { if (!(AttacksToSquare(*b, i) & b->piecemask[piece]).empty()) { printf("X"); } else { printf("."); } if ((i&7)==7) { printf("\n"); } } } void PrintBitlistForSide(Board* b, int side) { BUG(b != NULL); BUG(side == WHITE || side == BLACK); int i; for (i = 0; i < 64; i++) { if (!(AttacksToSquare(*b, i) & b->sidemask[side]).empty()) { printf("X"); } else { printf("."); } if ((i&7)==7) { printf("\n"); } } } void PrintPieceMask(Board* b, int piece) { BUG(b != NULL); BUG(piece >= KING && piece <= PAWN); Bitlist index; int i, j, k; int l[32]; k = 0; for (i = 0; i < 32; i++) { l[i] = INVALID; } index = b->piecemask[piece]; for (const auto& i: index) { l[k++] = b->piecelist[i]; } for (i = 0; i < 64; i++) { k = 0; for (j = 0; j < 32; j++) { if (l[j] == INVALID) { break; } if (l[j] == i) { printf("X"), k++; } } if (!k) { printf("."); } if ((i&7)==7) { printf("\n"); } } } void PrintBitlistForSquare(Board* b, int square) { Bitlist i; int j; i = AttacksToSquare(*b, square); for (j = 0; j < 32; j++) { if (!i.contains(j)) { printf("."); continue; } switch (GetPieceByBit(b, Bitlist{j})) { case PAWN: printf("P"); break; case KNIGHT: printf("N"); break; case BISHOP: printf("B"); break; case ROOK: printf("R"); break; case QUEEN: printf("Q"); break; case KING: printf("K"); break; } } printf("\n"); for (j = 0; j < 32; j++) { if (!i.contains(j)) { printf("."); continue; } if (b->sidemask[WHITE].contains(j)) { printf("W"); } else { printf("B"); } } printf("\n"); } void LogBug(char * file, int line) { #ifndef NDEBUG FILE* f = fopen("D:\bugs.txt", "a"); fprintf(f, "BUG: %s: %d\n", file, line); fclose(f); #else return; #endif } <file_sep>#include <cassert> #include <cstdint> #include "definitions.h" #include "functions.h" std::uint8_t PieceIndex(const Board& b, const int sq) { assert(sq >= 0 && sq <= 63); return b.index[sq]; } Bitlist CurrentSideMask(const Board& b) { assert(b.side == WHITE || b.side == BLACK); return b.sidemask[b.side]; } Bitlist OppositeSideMask(const Board& b) { assert(b.side == WHITE || b.side == BLACK); return b.sidemask[!b.side]; } Bitlist AttacksToSquare(const Board& b, const int sq) { assert(sq >= 0 && sq <= 63); return b.bitlist[sq]; } bool IsEmptySquare(const Board& b, const int sq) { assert(sq >= 0 && sq <= 63); return PieceIndex(b, sq) == INVALID; } <file_sep>/* * This file is part of Dorpsgek. * * Dorpsgek is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Dorpsgek is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Dorpsgek. If not, see <http://www.gnu.org/licenses/>. */ #include <assert.h> #include <stdbool.h> #include <string.h> #include "definitions.h" #include "functions.h" namespace Attacks { enum UpdateType { Add, Remove }; template<UpdateType u> void UpdateBits(Board*, Bitlist, int) { static_assert(u == UpdateType::Add || u == UpdateType::Remove, "UpdateBits called without valid template parameter."); } template<> void UpdateBits<UpdateType::Add>(Board* b, Bitlist bit, int sq) { b->bitlist[sq] |= bit; } template<> void UpdateBits<UpdateType::Remove>(Board* b, Bitlist bit, int sq) { b->bitlist[sq] &= ~bit; } template<UpdateType update_type> void UpdateBitlist(Board* b, Bitlist bit, int piece, int from) { if (piece == PAWN) { int col = COL(from); if (!(bit & b->sidemask[WHITE]).empty()) { if (col) { UpdateBits<update_type>(b, bit, from + 7); } if (col < 7) { UpdateBits<update_type>(b, bit, from + 9); } } if (!(bit & b->sidemask[BLACK]).empty()) { if (col) { UpdateBits<update_type>(b, bit, from - 9); } if (col < 7) { UpdateBits<update_type>(b, bit, from - 7); } } } else { int delta; int from16x12 = TO16x12(from); for (int dir = 0; dir < 8; dir++) { delta = rays[piece][dir]; if (!delta) { break; } int to = from16x12 + delta; while (board16x12[to] != INVALID) { UpdateBits<update_type>(b, bit, board16x12[to]); assert(ray_vector[VECTOR(from16x12, to)] == delta); if (!slide[piece] || !IsEmptySquare(*b, board16x12[to])) { break; } to += delta; } } } } template<UpdateType update_type> void UpdateSliders(Board* b, int sq) { Bitlist bits = AttacksToSquare(*b, sq) & (b->piecemask[BISHOP] | b->piecemask[ROOK] | b->piecemask[QUEEN]); int sq16x12 = TO16x12(sq); for (const auto& bit: bits) { int from = b->piecelist[bit]; int from16x12 = TO16x12(from); int vec = VECTOR(from16x12, sq16x12); int dir = ray_vector[vec]; int to = sq16x12 + dir; while (board16x12[to] != INVALID) { UpdateBits<update_type>(b, PieceIndexToBit(bit), board16x12[to]); if (!IsEmptySquare(*b, board16x12[to])) { break; } to += dir; } } } } void RecalculateAttacksFromScratch(Board* b) { int idx, sq; Bitlist i; memset(b->bitlist, 0, sizeof(b->bitlist)); for (idx = 0; idx < 32; idx++) { sq = b->piecelist[idx]; if (sq == INVALID) { continue; } i = PieceIndexToBit(idx); Attacks::UpdateBitlist<Attacks::UpdateType::Add>(b, i, GetPieceByBit(b, i), sq); } } void RecalculateAttacks_New(Board* c, const Move m) { const int from = m.from; const int dest = m.dest; const int type = m.type; const bool is_capture = type == MoveTypeCapture || type >= MoveTypeCapturePromotionQueen; const bool is_promotion = type >= MoveTypePromotionQueen; const Bitlist bit = PieceIndexToBit(c->index[dest]); const int piece = is_promotion ? PAWN : GetPieceByBit(c, bit); Attacks::UpdateBitlist<Attacks::UpdateType::Remove>(c, bit, piece, from); if (!is_promotion) { Attacks::UpdateBitlist<Attacks::UpdateType::Add>(c, bit, piece, dest); } else { switch (m.type) { case MoveTypeCapturePromotionKnight: case MoveTypePromotionKnight: Attacks::UpdateBitlist<Attacks::UpdateType::Add>(c, bit, KNIGHT, dest); break; case MoveTypeCapturePromotionBishop: case MoveTypePromotionBishop: Attacks::UpdateBitlist<Attacks::UpdateType::Add>(c, bit, BISHOP, dest); break; case MoveTypeCapturePromotionRook: case MoveTypePromotionRook: Attacks::UpdateBitlist<Attacks::UpdateType::Add>(c, bit, ROOK, dest); break; case MoveTypeCapturePromotionQueen: case MoveTypePromotionQueen: Attacks::UpdateBitlist<Attacks::UpdateType::Add>(c, bit, QUEEN, dest); break; } } Attacks::UpdateSliders<Attacks::UpdateType::Add>(c, from); if (!is_capture) { Attacks::UpdateSliders<Attacks::UpdateType::Remove>(c, dest); } } void RecalculateAttacks(Board* c, const Move move) { if (move.type == MoveTypeNormal || move.type == MoveTypeDoublePush || move.type == MoveTypeCapture || (move.type >= MoveTypePromotionQueen)) { RecalculateAttacks_New(c, move); } else { RecalculateAttacksFromScratch(c); } } <file_sep>/* * This file is part of Dorpsgek. * * Dorpsgek is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Dorpsgek is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Dorpsgek. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "definitions.h" #include "functions.h" unsigned long long qnodes, nodes; int abortSearch; int nulls, nullsucceed; int lmrs, lmrsucceed; int seldepth; int tt_hits, tt_probes, tt_fails, tt_illegals; int eval_hits, eval_probes; enum { NodeTypePV, NodeTypeCut, NodeTypeAll }; #define FullDepthMoves 4 #define ReductionLimit 3 #define hashfEXACT 0 #define hashfALPHA 1 #define hashfBETA 2 #define MATE 10000 #define TT_MISS 11000 int cuts, first; int Quies(Board* b, int alpha, int beta, int ply) { BUG(b != NULL); Move m[128]; Board c; int movecount, i, value; int best, eval; int legalmoves = 0; qnodes++; if (seldepth < ply) { seldepth = ply; } if ((qnodes & 0x3FF) == 0 && StopSearch()) { abortSearch = 1; return 0; } best = eval = Eval(b); if (best >= beta) { return best; } if (best > alpha) { alpha = best; } movecount = GenerateCaptures(b, m); qsort(m, movecount, sizeof(Move), CompareMoves); for (i = 0; i < movecount; i++) { c = *b; MakeMove(&c, m[i]); RecalculateAttacks(&c, m[i]); if (IsIllegal(&c)) { continue; } value = -Quies(&c, -beta, -alpha, ply + 1); legalmoves++; if (abortSearch) { return 0; } if (value > best) { if (value > alpha) { if (value >= beta) { cuts++; if (legalmoves == 1) { first++; } return beta; } alpha = value; } best = value; } } return best; } Move killers[32][2]; int iids, futils, razors, ttcuts; int Search(Board* b, int alpha, int beta, int depth, int ply, struct PV* pv) { BUG(b != NULL); Move m[128], bestmove; Board c; struct PV child_pv; int movecount, i, value; int incheck = IsInCheck(b); int flag = hashfALPHA; int best = -MATE, ttvalue; int legalmoves = 0; int reduction; int nodetype = (alpha == beta-1) ? NodeTypeCut : NodeTypePV; nodes++; pv->count = 0; /* Time check */ if ((nodes & 0x3FF) == 0 && StopSearch()) { abortSearch = 1; return 0; } /* Calculate hash key; thanks to <NAME> for pointing out that * IsTrivialDraw() requires the hash key */ CalculateHash(b); if (IsTrivialDraw(b)) return 0; /* Avoid overflowing the killer move stack */ if (ply > 32) { pv->count = 0; return Eval(b); // Return Quies()? Shouldn't need killers. } if (depth <= 0 && !incheck) { pv->count = 0; return Quies(b, alpha, beta, ply); } int eval = Eval(b); if (nodetype != NodeTypePV && depth <= 2 && !incheck && eval - (100*depth) >= beta) { return eval - (100*depth); } if (depth >= 2 && nodetype != NodeTypePV && !incheck && (CurrentSideMask(*b) & ~b->piecemask[PAWN]).count() > 3 && eval >= beta) { c = *b; c.side ^= 1; c.fifty = 0; c.ep = INVALID; c.rep[0] = 0; int R = (depth >= 6) ? 4 : 3; value = -Search(&c, -beta, -beta+1, depth - 1 - R, ply + 1, &child_pv); if (value >= beta) { return value; } } Move ttm; ttm.from = INVALID; ttm.dest = INVALID; ttm.type = INVALID; ttm.score= 0; ttvalue = 0; if (ReadTT(b, &ttm, &ttvalue, depth, alpha, beta, ply) == 1) { if (nodetype != NodeTypePV) { pv->count = 0; ttcuts++; return ttvalue; } } movecount = Generate(b, m); for (i = 0; i < movecount; i++) { if (m[i].from == ttm.from && m[i].dest == ttm.dest && m[i].type == ttm.type) { m[i].score = 32000; continue; } if (m[i].from == killers[ply][0].from && m[i].dest == killers[ply][0].dest && m[i].type == killers[ply][0].type) { m[i].score = 16000; continue; } if (m[i].from == killers[ply][1].from && m[i].dest == killers[ply][1].dest && m[i].type == killers[ply][1].type) { m[i].score = 15900; continue; } if (ply >= 2) { if (m[i].from == killers[ply-2][0].from && m[i].dest == killers[ply-2][0].dest && m[i].type == killers[ply-2][0].type) { m[i].score = 15800; continue; } if (m[i].from == killers[ply-2][1].from && m[i].dest == killers[ply-2][1].dest && m[i].type == killers[ply-2][1].type) { m[i].score = 15700; continue; } } } qsort(m, movecount, sizeof(Move), CompareMoves); if (incheck) depth++; for (i = 0; i < movecount; i++) { c = *b; MakeMove(&c, m[i]); RecalculateAttacks(&c, m[i]); if (IsIllegal(&c)) { continue; } if (HistoryScore(b, m[i]) > tt_illegals) { tt_illegals = HistoryScore(b, m[i]); } if (!ply && TimeUsed() >= 2000) { printf("stat01: %d %llu %d %d %d ", TimeUsed()/10, qnodes+nodes, depth, movecount-i, movecount); PRINT_MOVE(m[i]); printf("\n"); } reduction = 1; if (nodetype != NodeTypePV && depth >= 3 && legalmoves >= 4 && !incheck && IsEmptySquare(*b, m[i].dest) && m[i].type != MoveTypeEnPassant) { reduction = 2; if (m[i].score == 0) { reduction = 3; } } research: if (flag == hashfALPHA) value = -Search(&c, -beta, -alpha, depth - reduction, ply + 1, &child_pv); else { value = -Search(&c, -alpha-1, -alpha, depth - reduction, ply + 1, &child_pv); if (value > alpha && value < beta) value = -Search(&c, -beta, -alpha, depth - reduction, ply + 1, &child_pv); } if (reduction > 1 && value > alpha) { reduction = 1; goto research; } legalmoves++; if (abortSearch) { return 0; } if (value > best) { if (value > alpha) { if (value >= beta) { WriteTT(b, depth, value, hashfBETA, m[i], ply); pv->count = 0; cuts++; if (legalmoves == 1) { first++; } if (IsEmptySquare(*b, m[i].dest) && m[i].type != MoveTypeEnPassant) { if (killers[ply][1].from != killers[ply][0].from || killers[ply][1].dest != killers[ply][0].dest || killers[ply][1].type != killers[ply][0].type) { killers[ply][1] = killers[ply][0]; } killers[ply][0] = m[i]; GoodMove(b, m[i], depth); } int j; for (j = 0; j < i; j++) { if (IsEmptySquare(*b, m[j].dest) && m[j].type != MoveTypeEnPassant) BadMove(b, m[j], depth); } return value; } alpha = value; BUG(child_pv.count >= 0 && child_pv.count <= 64); pv->moves[0] = m[i]; memcpy(pv->moves + 1, child_pv.moves, child_pv.count * sizeof(Move)); pv->count = child_pv.count + 1; flag = hashfEXACT; if (!ply) { int matescore = value; /* Convert mate scores to XBoard standard */ if (value >= MATE-500) { matescore = 100000 + (MATE - value)/2; } if (value <= -MATE+500) { matescore = -(100000 + (-MATE - value)/2); } int time = TimeUsed() / 10; /* Check extension affects depth printout, causing GUIs to do wacky things. */ if (!IsInCheck(b)) { printf("%d %d %d %llu ", depth, matescore, time, qnodes+nodes); } else { printf("%d %d %d %llu ", depth-1, matescore, time, qnodes+nodes); } PrintPV(b, pv); printf("\n"); } } best = value; bestmove = m[i]; } } if (legalmoves == 0) { if (!incheck) { pv->count = 0; return 0; } return -MATE + ply; } WriteTT(b, depth, best, flag, bestmove, ply); return best; } int RootSearch(Board* b, int maxdepth, struct PV* pv) { BUG(b != NULL); struct PV safepv; int i, value; int time; int depth; int alpha, beta; int matescore; qnodes = 0; nodes = 0; abortSearch = 0; nullsucceed = 0; nulls = 0; lmrsucceed = 0; lmrs = 0; tt_hits = 0; tt_probes = 0; tt_fails = 0; tt_illegals = 0; eval_hits = 0; eval_probes = 0; state.startTime = ReadClock(); alpha = -2*MATE; beta = +2*MATE; seldepth = 0; cuts = 0; first = 0; lmrs = 0; iids = 0; razors = 0; futils = 0; matescore = 0; pv->count = 0; ClearHistory(); for (depth = 1; depth <= maxdepth; depth++) { value = Search(b, alpha, beta, depth, 0, pv); /* Don't print incomplete output. */ if (abortSearch) { break; } /* Convert mate scores to XBoard standard */ if (value >= MATE-500) { value = 100000 + (MATE - value)/2; matescore = 1; } if (value <= -MATE+500) { value = -(100000 + (-MATE - value)/2); matescore = 1; } time = TimeUsed() / 10; printf("%d %d %d %llu ", depth, value, time, qnodes+nodes); PrintPV(b, pv); printf("\n"); printf("# 1st move cuts: %d total cuts: %d percent: %d\n", first, cuts, (cuts) ? (100*first)/cuts : 0); /* PV is trustworthy, save it */ safepv = *pv; if (!state.infinite && (TimeUsed() >= state.noNewIterationLimit || matescore)) { break; } } printf("# Quiescence nodes: %d Alpha-Beta nodes: %d\n", qnodes, nodes); printf("# LMRs: %d Razors: %d RFPs: %d IIDs: %d\n", lmrs, razors, futils, iids); printf("# TT probes: %d TT hits: %d\n", tt_probes, tt_hits); printf("# TT fails: %d\n", tt_fails); printf("# TT illegals: %d\n", tt_illegals); printf("# TT hit rate: %d%%\n", (tt_probes) ? (100*tt_hits)/tt_probes : 0); /* When we've aborted, the PV is completely unusable and empty. To combat this, we use the backup PV instead. */ if (abortSearch) { *pv = safepv; } return value; } uint64_t Perft(const Board* b, const int depth, const int divide) { BUG(b != NULL); Move m[128]; Board c; int movecount, i; uint64_t nodes = 0, tmp; if (depth == 0) { return 1; } movecount = Generate(b, m); for (i = 0; i < movecount; i++) { c = *b; MakeMove(&c, m[i]); RecalculateAttacks(&c, m[i]); if (IsIllegal(&c)) { continue; } if (divide) { PrintSAN(b, m[i]); } nodes += tmp = Perft(&c, depth - 1, 0); if (divide) { std::cout << " " << tmp << std::endl; } } return nodes; } <file_sep>BIN = dorpsgek CXX ?= g++ SRCS = attacks.cpp board.cpp check.cpp main.cpp debug.cpp definitions.h draw.cpp eval.cpp fen.cpp functions.h generate.cpp hash.cpp makemove.cpp movesort.cpp ray.cpp search.cpp time.cpp LIBS = attacks.cpp board.cpp check.cpp main.cpp debug.cpp draw.cpp eval.cpp generate.cpp fen.cpp hash.cpp makemove.cpp movesort.cpp ray.cpp search.cpp time.cpp OBJS = attacks.o board.o check.o main.o debug.o draw.o eval.o fen.o generate.o hash.o makemove.o movesort.o ray.o search.o time.o CXXFLAGS = -std=c++17 -O3 -flto -fwhole-program -Wno-char-subscripts -DNDEBUG -Wall -Wextra -g3 -Ixstd/include all: $(BIN) $(BIN): $(OBJS) $(CXX) $(CXXFLAGS) $(OBJS) -o $(BIN) ci: $(CXX) $(CXXFLAGS) -coverage $(LIBS) -o $(BIN) clean: rm -f $(BIN) $(BIN).tar $(BIN).output *.o *~ tar: tar -cvf $(BIN).tar $(SRCS) makefile test: cat perft-cpw.epd | ./dorpsgek cat bench.txt | ./dorpsgek <file_sep>/* * This file is part of Dorpsgek. * * Dorpsgek is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Dorpsgek is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Dorpsgek. If not, see <http://www.gnu.org/licenses/>. */ #ifndef DEFINITIONS_H_INCLUDED #define DEFINITIONS_H_INCLUDED #include <inttypes.h> #include <stdint.h> #include <stddef.h> #include "xstd/int_set.hpp" //using Bitlist = uint32_t; using Bitlist = xstd::int_set<32, uint32_t>; struct Board { Bitlist bitlist[64]; /* For each square, what pieces attack it? */ char piecelist[32]; /* For each piece, which square is it on? */ char index[64]; /* For each square, which piece is on it? */ Bitlist sidemask[2]; char side; char castle; char ep; char fifty; Bitlist piecemask[6]; uint64_t hash; uint32_t rep[100]; }; struct Move { char from; char dest; char type; int16_t score; uint8_t idx; /* For 16-byte alignment */ }; struct PV { unsigned int count; struct Move moves[32]; }; /* Stolen from HGM's Winboard protocol driver */ struct State { long long startTime; int mps; int timeControl; float inc; int timePerMove; int neverExceedLimit; int noNewMoveLimit; int noNewIterationLimit; int moveNr; int timeLeft; int infinite; struct Board rootpos; char buf[256]; }; enum { MoveTypeNormal, MoveTypeCapture, MoveTypeCastle, MoveTypeDoublePush, MoveTypeEnPassant, MoveTypePromotionQueen, MoveTypePromotionRook, MoveTypePromotionBishop, MoveTypePromotionKnight, MoveTypeCapturePromotionQueen, MoveTypeCapturePromotionRook, MoveTypeCapturePromotionBishop, MoveTypeCapturePromotionKnight }; extern uint64_t zobrist_piece[2][6][64]; extern uint64_t zobrist_side; extern uint64_t zobrist_castle[16]; extern uint64_t zobrist_ep[8]; extern struct State state; extern const char promotechar[13]; extern int tt_hits, tt_probes; extern const int PawnValue; extern const int KnightValue; extern const int BishopValue; extern const int RookValue; extern const int QueenValue; extern const int KingValue; struct TTEntry { uint64_t key; char depth; char flags; int16_t value; char from; char dest; char type; char packing; }; extern struct TT { struct TTEntry * table; unsigned long long size; } hash_table; #define INVALID 64 enum { KING, QUEEN, ROOK, BISHOP, KNIGHT, PAWN }; enum { WHITE, BLACK }; #define COL(x) ((x)&7) #define ROW(pos) (((unsigned)pos)>>3) #define PRINT_MOVE(m) PrintMove(m) #ifndef NDEBUG #include <assert.h> #define BUG(x) assert(x) #else #define BUG(x) #endif #if defined(__GNUC__) static inline int CountTrailingZeroes(int x) { return __builtin_ctz(x); } static inline int PopCount(int x) { return __builtin_popcount(x); } #elif defined(_MSC_VER) #include <intrin.h> #pragma intrinsic(_BitScanForward) static inline int CountTrailingZeroes(int x) { int r; if (!x) { return 32; } _BitScanForward(&r, x); return r; } static inline int PopCount(int x) { return __popcnt(x); } #endif static inline int CompareMoves(const void * p1, const void * p2) { struct Move * m1 = (struct Move *)p1; struct Move * m2 = (struct Move *)p2; if (m1->score > m2->score) return -1; /* m1 before */ if (m1->score < m2->score) return +1; /* m1 after */ /* Scores are equal; sort by index to preserve stability. */ if (m1->idx < m2->idx) return -1; if (m1->idx > m2->idx) return +1; return 0; } static inline int GetPieceByBit(const Board* b, const Bitlist& bit) { for (int i = KING; i <= PAWN; i++) { if (!xstd::empty(bit & b->piecemask[i])) { return i; } } // ??? return INVALID; } static constexpr Bitlist PieceIndexToBit(const int idx) { return Bitlist{idx}; } #define MIN(a, b) (((a)<(b))?(a):(b)) #define MAX(a, b) (((a)>(b))?(a):(b)) #define ABS(a) (((a)>=0)?(a):(-(a))) #define TO16x12(sq) ((sq)+((sq)&~7)+36) #define OFFSET 119 #define VECTOR(f,d) (OFFSET+((d)-(f))) #define NORTH +16 #define SOUTH -16 #define EAST +1 #define WEST -1 static const int slide[5] = {0, 1, 1, 1, 0}; static const int rays[5][8] = { {NORTH, NORTH+EAST, EAST, SOUTH+EAST, SOUTH, SOUTH+WEST, WEST, NORTH+WEST}, /* King */ {NORTH, NORTH+EAST, EAST, SOUTH+EAST, SOUTH, SOUTH+WEST, WEST, NORTH+WEST}, /* Queen */ {NORTH, EAST, SOUTH, WEST, 0, 0, 0, 0}, /* Rook */ {NORTH+EAST, SOUTH+EAST, SOUTH+WEST, NORTH+WEST, 0, 0, 0, 0}, /* Bishop */ {2*NORTH+EAST, NORTH+2*EAST, SOUTH+2*EAST, 2*SOUTH+EAST, /* Knight */ 2*SOUTH+WEST, SOUTH+2*WEST, NORTH+2*WEST, 2*NORTH+WEST} }; static const int board16x12[192] = { INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID, INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID, INVALID,INVALID,INVALID,INVALID, 0, 1, 2, 3, 4, 5, 6, 7,INVALID,INVALID,INVALID,INVALID, INVALID,INVALID,INVALID,INVALID, 8, 9, 10, 11, 12, 13, 14, 15,INVALID,INVALID,INVALID,INVALID, INVALID,INVALID,INVALID,INVALID, 16, 17, 18, 19, 20, 21, 22, 23,INVALID,INVALID,INVALID,INVALID, INVALID,INVALID,INVALID,INVALID, 24, 25, 26, 27, 28, 29, 30, 31,INVALID,INVALID,INVALID,INVALID, INVALID,INVALID,INVALID,INVALID, 32, 33, 34, 35, 36, 37, 38, 39,INVALID,INVALID,INVALID,INVALID, INVALID,INVALID,INVALID,INVALID, 40, 41, 42, 43, 44, 45, 46, 47,INVALID,INVALID,INVALID,INVALID, INVALID,INVALID,INVALID,INVALID, 48, 49, 50, 51, 52, 53, 54, 55,INVALID,INVALID,INVALID,INVALID, INVALID,INVALID,INVALID,INVALID, 56, 57, 58, 59, 60, 61, 62, 63,INVALID,INVALID,INVALID,INVALID, INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID, INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID,INVALID }; extern unsigned char ray_attacks[240]; extern signed char ray_vector[240]; #endif /* DEFINITIONS_H_INCLUDED */ <file_sep>/* * This file is part of Dorpsgek. * * Dorpsgek is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Dorpsgek is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Dorpsgek. If not, see <http://www.gnu.org/licenses/>. */ #include "definitions.h" #include "functions.h" #include <stdio.h> bool IsAttacked(const Board* b, const char index, const Bitlist sidemask) { return !(AttacksToSquare(*b, b->piecelist[index]) & sidemask).empty(); } int IsIllegal(const Board* b) { auto i = (b->piecemask[KING] & OppositeSideMask(*b)).front(); return IsAttacked(b, i, CurrentSideMask(*b)); } int IsInCheck(const Board* b) { auto i = (b->piecemask[KING] & CurrentSideMask(*b)).front(); return IsAttacked(b, i, OppositeSideMask(*b)); } <file_sep># Dorpsgek ======== [![Build Status](https://travis-ci.org/ZirconiumX/Dorpsgek.svg?branch=ambrosia)](https://travis-ci.org/ZirconiumX/Dorpsgek) [![Code Coverage](https://img.shields.io/codecov/c/github/ZirconiumX/Dorpsgek.svg)](https://codecov.io/gh/ZirconiumX/Dorpsgek) Dorpsgek is a somewhat CECP compatible chess program using "bitlists". For a chess program it is not very strong, but it will beat most human players who aren't named "<NAME>" or "<NAME>". ## Features ### Evaluation - Material - Adam Hair's PST tables - Tempo - Minor piece mobility - Bishop pair bonus - King safety based on attacks around king - Pawn structure - Passed pawns - Doubled pawns - Isolated pawns ### Search - Alpha-beta search with quiescence search - MVV/LVA capture ordering - History heuristic quiet ordering - Always-replace transposition table - Check extension - Null-move forward pruning - Late move reductions - Reverse futility pruning <file_sep>/* * This file is part of Dorpsgek. * * Dorpsgek is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Dorpsgek is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Dorpsgek. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <stdio.h> #include "xstd/include/xstd/int_set.hpp" #include "definitions.h" #include "functions.h" void AddMove(const Board* b, Move* m, int* movecount, int from, int dest, int type) { BUG(b != NULL); BUG(m != NULL); BUG(movecount != NULL); BUG(from >= 0 && from <= 63); BUG(dest >= 0 && dest <= 63); BUG(type >= MoveTypeNormal && type <= MoveTypeCapturePromotionKnight); Move n; n.from = from; n.dest = dest; n.type = type; n.score = MoveValue(b, n); // To prevent accidentally using this while undefined. n.idx = *movecount; m[*movecount] = n; *movecount = *movecount + 1; } int Generate(const Board* b, Move* m) { int movecount, type; int from, dest, bit; Bitlist index; movecount = 0; BUG(b != NULL); BUG(m != NULL); /* Iterate over all squares */ for (dest = 0; dest < 64; dest++) { /* Don't allow own-piece captures. */ if (!IsEmptySquare(*b, dest) && !(PieceIndexToBit(b->index[dest]) & CurrentSideMask(*b)).empty()) continue; /* Do we have any pieces attacking this square? */ if (!(index = (AttacksToSquare(*b, dest) & CurrentSideMask(*b))).empty()) { /* Yes, we do, iterate over them. */ for (const auto& bit: index) { from = b->piecelist[bit]; /* Retrieve the square it is on. */ type = (IsEmptySquare(*b, dest)) ? MoveTypeNormal : MoveTypeCapture; BUG(bit >= 0 && bit <= 32); BUG(from != INVALID); /* Don't allow pawns to capture diagonally when there is nothing to capture. */ if (GetPieceByBit(b, Bitlist{bit}) == PAWN) { if (b->ep != INVALID && dest == b->ep) { type = MoveTypeEnPassant; } if (type == MoveTypeNormal) { continue; } /* Captures with promotion */ if ((b->side == WHITE && ROW(from) == 6) || (b->side == BLACK && ROW(from) == 1)) { AddMove(b, m, &movecount, from, dest, MoveTypeCapturePromotionQueen); AddMove(b, m, &movecount, from, dest, MoveTypeCapturePromotionRook); AddMove(b, m, &movecount, from, dest, MoveTypeCapturePromotionBishop); AddMove(b, m, &movecount, from, dest, MoveTypeCapturePromotionKnight); continue; } } /* Add this move to the list and increment the pointer. */ AddMove(b, m, &movecount, from, dest, type); BUG(movecount >= 0 && movecount <= 256); } } } if (b->side == WHITE) { /* Iterate over all white pawns */ index = b->piecemask[PAWN] & b->sidemask[WHITE]; for (const auto& bit: index) { from = b->piecelist[bit]; BUG(bit >= 0 && bit <= 32); BUG(from != INVALID); BUG(movecount >= 0 && movecount <= 256); if (IsEmptySquare(*b, from + 8)) { dest = from + 8; if (ROW(from + 8) != 7) { AddMove(b, m, &movecount, from, dest, MoveTypeNormal); if (ROW(from) == 1 && IsEmptySquare(*b, from + 16)) { AddMove(b, m, &movecount, from, from + 16, MoveTypeDoublePush); } } else { AddMove(b, m, &movecount, from, dest, MoveTypePromotionQueen); AddMove(b, m, &movecount, from, dest, MoveTypePromotionRook); AddMove(b, m, &movecount, from, dest, MoveTypePromotionBishop); AddMove(b, m, &movecount, from, dest, MoveTypePromotionKnight); } } } /* Castling */ /* We can't castle out of check */ if (!IsInCheck(b)) { /* Find the king */ index = b->piecemask[KING] & CurrentSideMask(*b); bit = index.front(); from = b->piecelist[bit]; BUG(!index.empty()); BUG(bit >= 0 && bit <= 32); BUG(from != INVALID); if (b->castle & 1 && from == 4) { /* Can't castle through check */ if ((AttacksToSquare(*b, from+1) & OppositeSideMask(*b)).empty() && (AttacksToSquare(*b, from+2) & OppositeSideMask(*b)).empty() && IsEmptySquare(*b, from+1) && IsEmptySquare(*b, from+2)) { AddMove(b, m, &movecount, from, from + 2, MoveTypeCastle); } } if (b->castle & 2 && from == 4) { if ((AttacksToSquare(*b, from-1) & OppositeSideMask(*b)).empty() && (AttacksToSquare(*b, from-2) & OppositeSideMask(*b)).empty() && IsEmptySquare(*b, from-1) && IsEmptySquare(*b, from-2) && IsEmptySquare(*b, from-3)) { AddMove(b, m, &movecount, from, from - 2, MoveTypeCastle); } } } } if (b->side == BLACK) { /* Iterate over all black pawns */ index = b->piecemask[PAWN] & b->sidemask[BLACK]; for (const auto& bit: index) { from = b->piecelist[bit]; if (IsEmptySquare(*b, from - 8)) { dest = from - 8; if (ROW(from - 8) != 0) { AddMove(b, m, &movecount, from, dest, MoveTypeNormal); if (ROW(from) == 6 && IsEmptySquare(*b, from - 16)) { AddMove(b, m, &movecount, from, from - 16, MoveTypeDoublePush); } } else { AddMove(b, m, &movecount, from, dest, MoveTypePromotionQueen); AddMove(b, m, &movecount, from, dest, MoveTypePromotionRook); AddMove(b, m, &movecount, from, dest, MoveTypePromotionBishop); AddMove(b, m, &movecount, from, dest, MoveTypePromotionKnight); } } } /* Castling */ /* We can't castle out of check */ if (!IsInCheck(b)) { /* Find the king */ index = b->piecemask[KING] & CurrentSideMask(*b); bit = index.front(); from = b->piecelist[bit]; BUG(!index.empty()); BUG(bit >= 0 && bit <= 32); BUG(from != INVALID); if (b->castle & 4 && from == 60) { /* Can't castle through check */ if ((AttacksToSquare(*b, from+1) & OppositeSideMask(*b)).empty() && (AttacksToSquare(*b, from+2) & OppositeSideMask(*b)).empty() && IsEmptySquare(*b, from+1) && IsEmptySquare(*b, from+2)) { AddMove(b, m, &movecount, from, from + 2, MoveTypeCastle); } } if (b->castle & 8 && from == 60) { if ((AttacksToSquare(*b, from-1) & OppositeSideMask(*b)).empty() && (AttacksToSquare(*b, from-2) & OppositeSideMask(*b)).empty() && IsEmptySquare(*b, from-1) && IsEmptySquare(*b, from-2) && IsEmptySquare(*b, from-3)) { AddMove(b, m, &movecount, from, from - 2, MoveTypeCastle); } } } } return movecount; } int GenerateCaptures(const Board* b, Move* m) { int movecount; int from, dest; Bitlist index, attacks; movecount = 0; /* Iterate over all enemy piece */ index = OppositeSideMask(*b); for (const auto& bit: index) { dest = b->piecelist[bit]; /* Retrieve the square it is on. */ attacks = AttacksToSquare(*b, dest) & CurrentSideMask(*b); for (const auto& bit: attacks) { from = b->piecelist[bit]; /* Retrieve the square it is on. */ /* Captures with promotion */ if (GetPieceByBit(b, Bitlist{bit}) == PAWN && ((b->side == WHITE && ROW(from) == 6) || (b->side == BLACK && ROW(from) == 1))) { AddMove(b, m, &movecount, from, dest, MoveTypeCapturePromotionQueen); AddMove(b, m, &movecount, from, dest, MoveTypeCapturePromotionRook); AddMove(b, m, &movecount, from, dest, MoveTypeCapturePromotionBishop); AddMove(b, m, &movecount, from, dest, MoveTypeCapturePromotionKnight); continue; } /* Add this move to the list and increment the pointer. */ AddMove(b, m, &movecount, from, dest, MoveTypeCapture); } } /* En passant */ if (b->ep != INVALID) { dest = b->ep; attacks = AttacksToSquare(*b, dest) & CurrentSideMask(*b) & b->piecemask[PAWN]; for (const auto& bit: attacks) { from = b->piecelist[bit]; /* Retrieve the square it is on. */ /* Add this move to the list and increment the pointer. */ AddMove(b, m, &movecount, from, dest, MoveTypeEnPassant); } } return movecount; } <file_sep>/* * This file is part of Dorpsgek. * * Dorpsgek is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Dorpsgek is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Dorpsgek. If not, see <http://www.gnu.org/licenses/>. */ #ifndef FUNCTIONS_H_INCLUDED #define FUNCTIONS_H_INCLUDED #include <cstdint> #include "definitions.h" /* attacks.cpp */ extern void RecalculateAttacksFromScratch(Board*); extern void RecalculateAttacks(Board*, const Move); /* board.cpp */ extern Bitlist CurrentSideMask(const Board&); extern Bitlist OppositeSideMask(const Board&); extern Bitlist AttacksToSquare(const Board&, const int); extern bool IsEmptySquare(const Board&, const int); /* check.cpp */ extern int IsAttacked(const Board*, const char, const uint32_t); extern int IsIllegal(const Board*); extern int IsInCheck(const Board*); /* dan.cpp */ extern void PrintPV(const Board*, const PV*); extern void PrintSAN(const Board*, const Move); /* draw.cpp */ extern int IsTrivialDraw(Board*); /* debug.cpp */ extern void PrintBitlistForSquare(Board*, int); extern void PrintMove(Move); extern void LogBug(char*, int); /* eval.cpp */ namespace Evaluation { extern Bitlist GetPinnedMask(const Board*, int side); } extern void InitEval(); extern int Eval(const Board*); /* fen.cpp */ extern void ParseFEN(const char* FEN, Board*); /* generate.cpp */ extern int Generate(const Board*, Move*); extern int GenerateCaptures(const Board*, Move*); /* hash.cpp */ extern void InitZobrist(); extern void CalculateHash(Board*); extern void InitTT(int); extern void FreeTT(); extern void ClearTT(); extern int ReadTT(Board*, Move*, int*, int, int, int, int); extern void WriteTT(Board*, int, int, int, Move, int); /* main.cpp */ extern void ClearBoard(Board*); /* makemove.cpp */ extern void MakeMove(Board*, Move); /* movesort.cpp */ extern int HistoryScore(const Board*, const Move); extern int MoveValue(const Board*, const Move); extern void GoodMove(const Board*, const Move, const int); extern void BadMove(const Board*, const Move, const int); extern void ClearHistory(); /* ray.cpp */ extern void InitRays(); /* search.cpp */ extern uint64_t Perft(const Board*, const int, const int); extern int Quies(Board*, int, int, int); extern int RootSearch(Board*, int, struct PV*); /* time.cpp */ extern void InitTime(); extern long long ReadClock(); extern void SetTimeLimits(unsigned int); extern int TimeUsed(); extern int StopSearch(); #endif /* FUNCTIONS_H_INCLUDED*/ <file_sep>/* * This file is part of Dorpsgek. * * Dorpsgek is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Dorpsgek is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Dorpsgek. If not, see <http://www.gnu.org/licenses/>. */ #include <exception> #include <map> #include <unordered_set> #include <cassert> #include <cctype> #include "definitions.h" #include "functions.h" namespace FEN { const std::map<char, int> piece_char_to_piecetype { { 'k', KING }, { 'q', QUEEN }, { 'r', ROOK }, { 'b', BISHOP }, { 'n', KNIGHT }, { 'p', PAWN } }; const std::map<char, int> colour_char_to_colour { { 'w', WHITE }, { 'b', BLACK } }; enum CastleFlags { WhiteKingside = 1, WhiteQueenside = 2, BlackKingside = 4, BlackQueenside = 8 }; /* Cribbed from Fruit, thank you Fabien */ void ParsePieces(const char* fen, Board* b, unsigned int& idx) { unsigned int pcidx = 0; for (int rank = 7; rank >= 0; rank--) { for (int file = 0; file <= 7;) { int sq = 8*rank + file; char c = fen[idx]; if (c >= '1' && c <= '8') { int len = c - '0'; for (int i = 0; i < len; i++) { assert(file <= 7); file++; } } else { // Credit to Oxyd in ##c++-social for this piece of wizardry. if (std::unordered_set<char>{'k', 'q', 'r', 'b', 'n', 'p'}.count(std::tolower(c)) != 1) { throw std::invalid_argument("Invalid piece character in FEN."); } b->piecelist[pcidx] = sq; b->index[sq] = pcidx; b->sidemask[std::isupper(c) ? WHITE : BLACK] |= PieceIndexToBit(pcidx); b->piecemask[piece_char_to_piecetype.at(std::tolower(c))] |= PieceIndexToBit(pcidx); pcidx++; file++; } idx++; } if (rank > 0) { assert(fen[idx] == '/'); idx++; } } } void ParseCastling(const char* fen, Board* b, unsigned int& idx) { b->castle = 0; char c = fen[idx]; if (c == '-') { c = fen[++idx]; } else { if (c == 'K') { b->castle |= FEN::CastleFlags::WhiteKingside; c = fen[++idx]; } if (c == 'Q') { b->castle |= FEN::CastleFlags::WhiteQueenside; c = fen[++idx]; } if (c == 'k') { b->castle |= FEN::CastleFlags::BlackKingside; c = fen[++idx]; } if (c == 'q') { b->castle |= FEN::CastleFlags::BlackQueenside; c = fen[++idx]; } } } } void ParseFEN(const char* fen, Board* b) { char c; unsigned int idx; ClearBoard(b); idx = 0; FEN::ParsePieces(fen, b, idx); assert(std::isspace(fen[idx])); c = fen[++idx]; if (std::unordered_set<char>{'w', 'b'}.count(std::tolower(c)) != 1) { throw std::invalid_argument("Invalid colour character in FEN."); } b->side = FEN::colour_char_to_colour.at(c); c = fen[++idx]; assert(c == ' '); c = fen[++idx]; FEN::ParseCastling(fen, b, idx); assert(std::isspace(fen[idx])); c = fen[++idx]; if (c == '-') { b->ep = INVALID; } else { b->ep = c - 'a'; c = fen[++idx]; b->ep += 8*(c - '1'); } c = fen[++idx]; assert(c == ' '); c = fen[++idx]; b->fifty = c - '0'; c = fen[++idx]; if (c != ' ') { b->fifty *= 10; b->fifty += c - '0'; } RecalculateAttacksFromScratch(b); CalculateHash(b); } <file_sep>/* * This file is part of Dorpsgek. * * Dorpsgek is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Dorpsgek is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Dorpsgek. If not, see <http://www.gnu.org/licenses/>. */ #include "definitions.h" #include "functions.h" static int history[2][6][64]; static int butterfly[2][6][64]; void ClearHistory() { for (int i = 0; i < 2; i++) { for (int j = 0; j < 6; j++) { for (int k = 0; k < 64; k++) { history[i][j][k] = 0; butterfly[i][j][k] = 0; } } } } int HistoryScore(const Board* b, const Move m) { return history[b->side][GetPieceByBit(b, Bitlist{b->index[m.from]})][m.dest] / (butterfly[b->side][GetPieceByBit(b, Bitlist{b->index[m.from]})][m.dest]+1); } void GoodMove(const Board* b, const Move m, const int depth) { history[b->side][GetPieceByBit(b, Bitlist{b->index[m.from]})][m.dest] += depth*depth; if (history[b->side][GetPieceByBit(b, Bitlist{b->index[m.from]})][m.dest] > 16777216) { for (int i = 0; i < 2; i++) { for (int j = 0; j < 6; j++) { for (int k = 0; k < 64; k++) { history[i][j][k] /= 2; butterfly[i][j][k] /= 2; } } } } } void BadMove(const Board* b, const Move m, const int depth) { butterfly[b->side][GetPieceByBit(b, Bitlist{b->index[m.from]})][m.dest] += 1; } int MoveValue(const Board* b, const Move m) { int value; unsigned int i; int piecevals[6] = { KingValue, QueenValue, RookValue, BishopValue, KnightValue, PawnValue }; value = 0; i = b->index[m.dest]; switch (m.type) { case MoveTypePromotionQueen: case MoveTypeCapturePromotionQueen: value = piecevals[QUEEN] - piecevals[PAWN]; break; case MoveTypePromotionRook: case MoveTypeCapturePromotionRook: value = piecevals[ROOK] - piecevals[PAWN]; break; case MoveTypePromotionBishop: case MoveTypeCapturePromotionBishop: value = piecevals[BISHOP] - piecevals[PAWN]; break; case MoveTypePromotionKnight: case MoveTypeCapturePromotionKnight: value = piecevals[KNIGHT] - piecevals[PAWN]; break; } if (i != INVALID) { value += piecevals[GetPieceByBit(b, Bitlist{b->index[m.dest]})] - (6 - GetPieceByBit(b, Bitlist{b->index[m.from]})); return value+20000; } else if (m.type == MoveTypeEnPassant) { return (PawnValue - 1) + 20000; } else { value += HistoryScore(b, m); return value; } } <file_sep>/* * This file is part of Dorpsgek. * * Dorpsgek is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Dorpsgek is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Dorpsgek. If not, see <http://www.gnu.org/licenses/>. */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include "definitions.h" #include "functions.h" const int PawnValue = 100; const int KnightValue = 300; const int BishopValue = 300; const int RookValue = 500; const int QueenValue = 950; const int KingValue = 20000; static const int PawnPSTMG[64] = { //A1 H1 0, 0, 0, 0, 0, 0, 0, 0, -1, -7, -11, -35, -13, 5, 3, -5, 1, 1, -6, -19, -6, -7, -4, 10, 1, 14, 8, 4, 5, 4, 10, 7, 9, 30, 23, 31, 31, 23, 17, 11, 21, 54, 72, 56, 77, 95, 71, 11, 118, 121, 173, 168, 107, 82, -16, 22, 0, 0, 0, 0, 0, 0, 0, 0 //A8 H8 }; static const int PawnPSTEG[64] = { 0, 0, 0, 0, 0, 0, 0, 0, -17, -17, -17, -17, -17, -17, -17, -17, -11, -11, -11, -11, -11, -11, -11, -11, -7, -7, -7, -7, -7, -7, -7, -7, 16, 16, 16, 16, 16, 16, 16, 16, 55, 55, 55, 55, 55, 55, 55, 55, 82, 82, 82, 82, 82, 82, 82, 82, 0, 0, 0, 0, 0, 0, 0, 0 }; static const int KnightPSTMG[64] = { -99, -30, -66, -64, -29, -19, -61, -81, -56, -31, -28, -1, -7, -20, -42, -11, -38, -16, 0, 14, 8, 3, 3, -42, -14, 0, 2, 3, 19, 12, 33, -7, -14, -4, 25, 33, 10, 33, 14, 43, -22, 18, 60, 64, 124, 143, 55, 6, -34, 24, 54, 74, 60, 122, 2, 29, -60, 0, 0, 0, 0, 0, 0, 0 }; static const int KnightPSTEG[64] = { -99, -99, -94, -88, -88, -94, -99, -99, -81, -62, -49, -43, -43, -49, -62, -81, -46, -27, -15, -9, -9, -15, -27, -46, -22, -3, 10, 16, 16, 10, -3, -22, -7, 12, 25, 31, 31, 25, 12, -7, -2, 17, 30, 36, 36, 30, 17, -2, -7, 12, 25, 31, 31, 25, 12, -7, -21, -3, 10, 16, 16, 10, -3, -21 }; static const int BishopPSTMG[64] = { -7, 12, -8, -37, -31, -8, -45, -67, 15, 5, 13, -10, 1, 2, 0, 15, 5, 12, 14, 13, 10, -1, 3, 4, 1, 5, 23, 32, 21, 8, 17, 4, -1, 16, 29, 27, 37, 27, 17, 4, 7, 27, 20, 56, 91, 108, 53, 44, -24, -23, 30, 58, 65, 61, 69, 11, 0, 0, 0, 0, 0, 0, 0, 0 }; static const int BishopPSTEG[64] = { -27, -21, -17, -15, -15, -17, -21, -27, -10, -4, 0, 2, 2, 0, -4, -10, 2, 8, 12, 14, 14, 12, 8, 2, 11, 17, 21, 23, 23, 21, 17, 11, 14, 20, 24, 26, 26, 24, 20, 14, 13, 19, 23, 25, 25, 23, 19, 13, 8, 14, 18, 20, 20, 18, 14, 8, -2, 4, 8, 10, 10, 8, 4, -2 }; static const int RookPSTMG[64] = { -2, -1, 3, 1, 2, 1, 4, -8, -26, -6, 2, -2, 2, -10, -1, -29, -16, 0, 3, -3, 8, -1, 12, 3, -9, -5, 8, 14, 18, -17, 13, -13, 19, 33, 46, 57, 53, 39, 53, 16, 24, 83, 54, 75, 134, 144, 85, 75, 46, 33, 64, 62, 91, 89, 70, 104, 84, 0, 0, 37, 124, 0, 0, 153 }; static const int RookPSTEG[64] = { -32, -31, -30, -29, -29, -30, -31, -32, -27, -25, -24, -24, -24, -24, -25, -27, -15, -13, -12, -12, -12, -12, -13, -15, 1, 2, 3, 4, 4, 3, 2, 1, 15, 17, 18, 18, 18, 18, 17, 15, 25, 27, 28, 28, 28, 28, 27, 25, 27, 28, 29, 30, 30, 29, 28, 27, 16, 17, 18, 19, 19, 18, 17, 16 }; static const int QueenPSTMG[64] = { 1, -10, -11, 3, -15, -51, -83, -13, -7, 3, 2, 5, -1, -10, -7, -2, -11, 0, 12, 2, 8, 11, 7, -6, -9, 5, 7, 9, 18, 17, 26, 4, -6, 0, 15, 25, 32, 9, 26, 12, -16, 10, 13, 25, 37, 30, 15, 26, 1, 11, 35, 0, 16, 55, 39, 57, -13, 6, -42, 0, 29, 0, 0, 102 }; static const int QueenPSTEG[64] = { -61, -55, -52, -50, -50, -52, -55, -61, -31, -26, -22, -21, -21, -22, -26, -31, -8, -3, 1, 3, 3, 1, -3, -8, 9, 14, 17, 19, 19, 17, 14, 9, 19, 24, 28, 30, 30, 28, 24, 19, 23, 28, 32, 34, 34, 32, 28, 23, 21, 26, 30, 31, 31, 30, 26, 21, 12, 17, 21, 23, 23, 21, 17, 12 }; static const int KingPSTMG[64] = { 0, 0, 0, -9, 0, -9, 25, 0, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 }; static const int KingPSTEG[64] = { -34, -30, -28, -27, -27, -28, -30, -34, -17, -13, -11, -10, -10, -11, -13, -17, -2, 2, 4, 5, 5, 4, 2, -2, 11, 15, 17, 18, 18, 17, 15, 11, 22, 26, 28, 29, 29, 28, 26, 22, 31, 34, 37, 38, 38, 37, 34, 31, 38, 41, 44, 45, 45, 44, 41, 38, 42, 46, 48, 50, 50, 48, 46, 42 }; static const int* PSTMG[6] = { KingPSTMG, QueenPSTMG, RookPSTMG, BishopPSTMG, KnightPSTMG, PawnPSTMG }; static const int* PSTEG[6] = { KingPSTEG, QueenPSTEG, RookPSTEG, BishopPSTEG, KnightPSTEG, PawnPSTEG }; static const int PieceValue[6] = { KingValue, QueenValue, RookValue, BishopValue, KnightValue, PawnValue }; const int MobilityPoint = 4; const int RookOnOpenFileBonus = 30; const int DefendedKnightBonus = 10; const int BackwardPawnPenalty = 8; const int DoubledPawnPenalty = 10; const int PassedPawnBonus[8] = { 0, 0, 0, 0, 20, 40, 80, 0 }; const int IsolatedPawnPenalty = 20; const int TempoBonus = 10; const int BishopPairBonus = 40; const int UnstoppablePassedPawnBonus = 50; const int PawnShieldBonus = 20; static uint64_t PassedMask[2][64]; static uint64_t IsolatedMask[8]; static uint64_t FileMask[8]; static uint8_t KingShieldMask[8]; namespace Evaluation { /* Can be incrementally updated. */ int Phase(const Board* b) { int phase = 24; phase -= 1 * (b->piecemask[KNIGHT] | b->piecemask[BISHOP]).count(); phase -= 2 * (b->piecemask[ROOK]).count(); phase -= 4 * (b->piecemask[QUEEN]).count(); return phase; } /* Can be incrementally updated. */ void Material(const Board* b, int& midgame, int& endgame) { for (int piece = QUEEN; piece <= PAWN; piece++) { unsigned int white_material = (b->piecemask[piece] & b->sidemask[WHITE]).count(); unsigned int black_material = (b->piecemask[piece] & b->sidemask[BLACK]).count(); int material = (white_material - black_material) * PieceValue[piece]; midgame += material; endgame += material; } } /* Can be incrementally updated. */ void PST(const Board* b, int& midgame, int& endgame) { for (int piece = KING; piece <= PAWN; piece++) { Bitlist index = b->piecemask[piece] & b->sidemask[WHITE]; for (const auto& bit: index) { unsigned int sq = b->piecelist[bit]; midgame += PSTMG[piece][sq]; endgame += PSTEG[piece][sq]; } index = b->piecemask[piece] & b->sidemask[BLACK]; for (const auto& bit: index) { unsigned int sq = b->piecelist[bit] ^ 56; // Flip board vertically midgame -= PSTMG[piece][sq]; endgame -= PSTEG[piece][sq]; } } } template<int piece> int Mobility(const Board* b, const int sq64, const int colour) { int mobility = 0; Bitlist mask; if constexpr (piece == KNIGHT) { mask = b->sidemask[!colour] & b->piecemask[PAWN]; } else { mask.clear(); } int sq16x12 = TO16x12(sq64); for (int dir = 0; dir < 8; dir++) { int delta = rays[piece][dir]; if (!delta) { break; } int to = sq16x12 + delta; while (board16x12[to] != INVALID) { if ((AttacksToSquare(*b, board16x12[to]) & mask).empty()) { mobility += MobilityPoint; } if (!slide[piece] || !IsEmptySquare(*b, board16x12[to])) { break; } to += delta; } } return mobility; } int KnightMobility(const Board* b, const int sq, const int colour) { return Mobility<KNIGHT>(b, sq, colour); } int BishopMobility(const Board* b, const int sq) { return Mobility<BISHOP>(b, sq, b->side); } int KingAttacks(const Board* b, const int sq, const int colour) { unsigned int attcnt = 0; int sq16x12 = TO16x12(sq); for (int dir = 0; dir < 8; dir++) { int delta = rays[KING][dir]; int to = sq16x12 + delta; if (board16x12[to] != INVALID) { attcnt += (AttacksToSquare(*b, board16x12[to]) & b->sidemask[!colour]).count(); } } return attcnt; } /* Could maybe be used in movegen? */ Bitlist GetPinnedMask(const Board* b, int side) { Bitlist friendly = b->sidemask[side]; Bitlist pinned; /* Find king. */ int kingsq64 = b->piecelist[(b->piecemask[KING] & b->sidemask[side]).front()]; int kingsq16x12 = TO16x12(kingsq64); /* Loop over friendly pieces. */ for (const auto& currpc: friendly) { int sq64 = b->piecelist[currpc]; int sq16x12 = TO16x12(sq64); /* Is this piece attacked by the enemy? */ Bitlist attacks = AttacksToSquare(*b, sq64) & b->sidemask[!side]; if (attacks.empty()) { continue; } /* Get direction from king to this piece. */ int dir_kingpc = ray_vector[VECTOR(kingsq16x12, sq16x12)]; /* Loop over enemy attacks. */ for (const auto& bit: attacks) { int att64 = b->piecelist[bit]; int att16x12 = TO16x12(att64); /* Get direction from king to the attacker. */ int dir_kingatt = ray_vector[VECTOR(kingsq16x12, att16x12)]; /* Discard if the directions are different. */ if (!dir_kingatt || dir_kingatt != dir_kingpc) { continue; } int to16x12 = kingsq16x12 + dir_kingatt; int blockers = 0; // This should be 1 after the loop if the piece currently being considered is a pinning piece. /* Travel from the king to the attacker. */ while (to16x12 != att16x12) { /* Is a piece blocking between king and attacker? */ if (!IsEmptySquare(*b, board16x12[to16x12])) { blockers++; /* If there are two pieces, there is no pin here. */ if (blockers >= 2) { break; } } /* Next square. */ to16x12 += dir_kingatt; } /* If this piece is the only blocker, it is pinned. */ if (blockers == 1) { pinned |= Bitlist{currpc}; /* One pinner is enough to show this piece is pinned. */ break; } } } return pinned; } } void InitEval() { int sq, dest, file; uint64_t bb; /* Passed pawn masks. */ for (sq = 0; sq <= 63; sq++) { PassedMask[WHITE][sq] = PassedMask[BLACK][sq] = 0; bb = 0; dest = sq + 8; while (dest <= 63) { bb |= 1ULL << dest; if (COL(dest) != 0) { bb |= 1ULL << (dest - 1); } if (COL(dest) != 7) { bb |= 1ULL << (dest + 1); } dest += 8; } PassedMask[WHITE][sq] = bb; bb = 0; dest = sq - 8; while (dest >= 0) { bb |= 1ULL << dest; if (COL(dest) != 0) { bb |= 1ULL << (dest - 1); } if (COL(dest) != 7) { bb |= 1ULL << (dest + 1); } dest -= 8; } PassedMask[BLACK][sq] = bb; } for (file = 0; file <= 7; file++) { FileMask[file] = 0x0101010101010101ULL << file; IsolatedMask[file] = 0; KingShieldMask[file] = 1 << file; if (file >= 1) { IsolatedMask[file] |= FileMask[file-1]; KingShieldMask[file] |= 1 << (file - 1); } if (file <= 6) { IsolatedMask[file] |= FileMask[file+1]; KingShieldMask[file] |= 1 << (file + 1); } } } int KingDistance(int sq1, int sq2) { int file1, file2, rank1, rank2; int rankDistance, fileDistance; file1 = COL(sq1); file2 = COL(sq2); rank1 = ROW(sq1); rank2 = ROW(sq2); rankDistance = ABS(rank2 - rank1); fileDistance = ABS(file2 - file1); return MAX(rankDistance, fileDistance); } int Eval(const Board* b) { int sq, midgame, endgame, phase; Bitlist index; uint64_t pawnbb[2] = {0, 0}, pawns, tmpbb; BUG(b != NULL); BUG(b->side == WHITE || b->side == BLACK); midgame = 0; endgame = 0; phase = Evaluation::Phase(b); Evaluation::Material(b, midgame, endgame); Evaluation::PST(b, midgame, endgame); /* White pawns, phase 1 */ /* Initialise the bitboards and PST values. */ index = b->piecemask[PAWN] & b->sidemask[WHITE]; for (const auto& bit: index) { sq = b->piecelist[bit]; pawnbb[WHITE] |= 1ULL << sq; } /* Black pawns, phase 1 */ /* Initialise the bitboards and PST values. */ index = b->piecemask[PAWN] & b->sidemask[BLACK]; for (const auto& bit: index) { sq = b->piecelist[bit]; pawnbb[BLACK] |= 1ULL << sq; } /* White pawns, phase 2 */ /* Things that require knowledge of enemy pawn structure. */ pawns = pawnbb[WHITE]; while (pawns) { sq = __builtin_ctzll(pawns); pawns &= pawns - 1; /* Passed Pawns */ if (!(PassedMask[WHITE][sq] & pawnbb[BLACK])) { midgame += PassedPawnBonus[ROW(sq)]; endgame += PassedPawnBonus[ROW(sq)]; /* Unstoppable Passed Pawn */ int ksq = b->piecelist[(b->piecemask[KING] & b->sidemask[BLACK]).front()]; int promosq = 56 + COL(sq); int enemytempo = b->side == BLACK; if (MIN(5, KingDistance(sq, promosq)) < (KingDistance(ksq, promosq) - enemytempo)) { midgame += UnstoppablePassedPawnBonus; endgame += UnstoppablePassedPawnBonus; } } /* Doubled Pawns. */ tmpbb = pawnbb[WHITE] & FileMask[COL(sq)]; if (tmpbb & (tmpbb-1)) { midgame -= DoubledPawnPenalty; endgame -= DoubledPawnPenalty; } /* Isolated Pawns. */ tmpbb = pawnbb[WHITE] & IsolatedMask[COL(sq)]; if (!tmpbb) { midgame -= IsolatedPawnPenalty; endgame -= IsolatedPawnPenalty; } } /* Black pawns, phase 2 */ /* Things that require knowledge of enemy pawn structure. */ pawns = pawnbb[BLACK]; while (pawns) { sq = __builtin_ctzll(pawns); pawns &= pawns - 1; /* Passed Pawns */ if (!(PassedMask[BLACK][sq] & pawnbb[WHITE])) { midgame -= PassedPawnBonus[7-ROW(sq)]; endgame -= PassedPawnBonus[7-ROW(sq)]; /* Unstoppable Passed Pawn */ int ksq = b->piecelist[(b->piecemask[KING] & b->sidemask[WHITE]).front()]; int promosq = COL(sq); int enemytempo = b->side == WHITE; if (MIN(5, KingDistance(sq, promosq)) < (KingDistance(ksq, promosq) - enemytempo)) { midgame -= UnstoppablePassedPawnBonus; endgame -= UnstoppablePassedPawnBonus; } } /* Doubled Pawns. */ tmpbb = pawnbb[BLACK] & FileMask[COL(sq)]; if (tmpbb & (tmpbb-1)) { midgame += DoubledPawnPenalty; endgame += DoubledPawnPenalty; } /* Isolated Pawns. */ tmpbb = pawnbb[BLACK] & IsolatedMask[COL(sq)]; if (!tmpbb) { midgame += IsolatedPawnPenalty; endgame += IsolatedPawnPenalty; } } /* White knights */ index = b->piecemask[KNIGHT] & b->sidemask[WHITE]; for (const auto& bit: index) { sq = b->piecelist[bit]; int mobility = Evaluation::KnightMobility(b, sq, WHITE); midgame += mobility; endgame += mobility; } /* Black knights */ index = b->piecemask[KNIGHT] & b->sidemask[BLACK]; for (const auto& bit: index) { sq = b->piecelist[bit]; int mobility = Evaluation::KnightMobility(b, sq, BLACK); midgame -= mobility; endgame -= mobility; } /* White bishops */ index = b->piecemask[BISHOP] & b->sidemask[WHITE]; if (index.count() >= 2) { midgame += BishopPairBonus; endgame += BishopPairBonus; } for (const auto& bit: index) { sq = b->piecelist[bit]; int mobility = Evaluation::BishopMobility(b, sq); midgame += mobility; endgame += mobility; } /* Black bishops */ index = b->piecemask[BISHOP] & b->sidemask[BLACK]; if (index.count() >= 2) { midgame -= BishopPairBonus; endgame -= BishopPairBonus; } for (const auto& bit: index) { sq = b->piecelist[bit]; int mobility = Evaluation::BishopMobility(b, sq); midgame -= mobility; endgame -= mobility; } /* White rooks */ index = b->piecemask[ROOK] & b->sidemask[WHITE]; for (const auto& bit: index) { sq = b->piecelist[bit]; tmpbb = pawnbb[WHITE] | pawnbb[BLACK]; if (!(FileMask[COL(sq)] & tmpbb)) { midgame += RookOnOpenFileBonus; endgame += RookOnOpenFileBonus; } } /* Black rooks */ index = b->piecemask[ROOK] & b->sidemask[BLACK]; for (const auto& bit: index) { sq = b->piecelist[bit]; tmpbb = pawnbb[WHITE] | pawnbb[BLACK]; if (!(FileMask[COL(sq)] & tmpbb)) { midgame -= RookOnOpenFileBonus; endgame -= RookOnOpenFileBonus; } } /* White king */ index = b->piecemask[KING] & b->sidemask[WHITE]; for (const auto& bit: index) { sq = b->piecelist[bit]; unsigned int attcnt = Evaluation::KingAttacks(b, sq, WHITE); midgame -= attcnt * attcnt * 2; /* Pawn Shield */ uint64_t mask = KingShieldMask[COL(sq)] << (8 * (ROW(sq) + 1)); midgame += 2 * PawnShieldBonus * __builtin_popcountll(pawnbb[WHITE] & mask); mask = KingShieldMask[COL(sq)] << (8 * (ROW(sq) + 2)); midgame += PawnShieldBonus * __builtin_popcountll(pawnbb[WHITE] & mask); } /* Black king */ index = b->piecemask[KING] & b->sidemask[BLACK]; for (const auto& bit: index) { sq = b->piecelist[bit]; /* King attacks */ unsigned int attcnt = Evaluation::KingAttacks(b, sq, BLACK); midgame += attcnt * attcnt * 2; /* Pawn Shield */ uint64_t mask = KingShieldMask[COL(sq)] << (8ull * (ROW(sq) - 1ull)); midgame -= 2 * PawnShieldBonus * __builtin_popcountll(pawnbb[WHITE] & mask); mask = KingShieldMask[COL(sq)] << (8ull * (ROW(sq) - 2ull)); midgame -= PawnShieldBonus * __builtin_popcountll(pawnbb[WHITE] & mask); } /* Tempo */ if (b->side == WHITE) { midgame += TempoBonus; endgame += TempoBonus; } else { midgame -= TempoBonus; endgame -= TempoBonus; } phase = (phase * 256 + 12) / 24; int value = 0; value = ((midgame * (256 - phase)) + (endgame * phase)) / 256; if (b->side == BLACK) { value = -value; } return value; } <file_sep>/* * This file is part of Dorpsgek. * * Dorpsgek is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Dorpsgek is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Dorpsgek. If not, see <http://www.gnu.org/licenses/>. */ #define __STDC_FORMAT_MACROS #include <ctype.h> #include <inttypes.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "definitions.h" #include "functions.h" const char promotechar[13] = { ' ', ' ', ' ', ' ', ' ', 'q', 'r', 'b', 'n', 'q', 'r', 'b', 'n' }; void PrintMove(Move m) { BUG(m.from >= 0 && m.from <= 63); BUG(m.dest >= 0 && m.dest <= 63); BUG(m.type >= 0 && m.type <= 13); printf("%c%u%c%u", 'a' + COL ((m).from), 1 + ROW ((m).from), 'a' + COL ((m).dest), 1 + ROW ((m).dest)); if (promotechar[m.type] != ' ') { printf("%c", promotechar[m.type]); } } void PrintSAN(const Board* b, const Move m) { BUG(m.from >= 0 && m.from <= 63); BUG(m.dest >= 0 && m.dest <= 63); BUG(m.type >= 0 && m.type <= 13); char ffile = 'a' + COL ((m).from); int frank = 1 + ROW ((m).from); char dfile = 'a' + COL ((m).dest); int drank = 1 + ROW ((m).dest); char piececnt; int from; Bitlist index; if (b->piecemask[PAWN].contains(b->index[m.from])) { if (!IsEmptySquare(*b, m.dest) || m.type == MoveTypeEnPassant) { printf("%cx", ffile); } printf("%c%u", dfile, drank); if (m.type == MoveTypeEnPassant) { printf("e.p."); } if (m.type == MoveTypePromotionQueen || m.type == MoveTypeCapturePromotionQueen) { printf("Q"); } if (m.type == MoveTypePromotionRook || m.type == MoveTypeCapturePromotionRook) { printf("R"); } if (m.type == MoveTypePromotionBishop || m.type == MoveTypeCapturePromotionBishop) { printf("B"); } if (m.type == MoveTypePromotionKnight || m.type == MoveTypeCapturePromotionKnight) { printf("N"); } } else if (b->piecemask[KNIGHT].contains(b->index[m.from])) { printf("N"); if ((piececnt = (AttacksToSquare(*b, m.dest) & b->piecemask[KNIGHT] & CurrentSideMask(*b)).count()) > 1) { if (piececnt > 2) { printf("%c%u", ffile, frank); } else { index = AttacksToSquare(*b, m.dest) & b->piecemask[KNIGHT] & CurrentSideMask(*b); index.toggle(b->index[m.from]); from = b->piecelist[index.front()]; if (COL(m.from) != COL(from)) { printf("%c", ffile); } else { printf("%u", frank); } } } if (!IsEmptySquare(*b, m.dest)) { printf("x"); } printf("%c%u", dfile, drank); } else if (b->piecemask[BISHOP].contains(b->index[m.from])) { printf("B"); if ((piececnt = (AttacksToSquare(*b, m.dest) & b->piecemask[BISHOP] & CurrentSideMask(*b)).count()) > 1) { if (piececnt > 2) { printf("%c%u", ffile, frank); } else { index = AttacksToSquare(*b, m.dest) & b->piecemask[BISHOP] & CurrentSideMask(*b); index.toggle(b->index[m.from]); from = b->piecelist[(index).front()]; if (COL(m.from) != COL(from)) { printf("%c", ffile); } else { printf("%u", frank); } } } if (!IsEmptySquare(*b, m.dest)) { printf("x"); } printf("%c%u", dfile, drank); } else if (b->piecemask[ROOK].contains(b->index[m.from])) { printf("R"); if ((piececnt = (AttacksToSquare(*b, m.dest) & b->piecemask[ROOK] & CurrentSideMask(*b)).count()) > 1) { if (piececnt > 2) { printf("%c%u", ffile, frank); } else { index = AttacksToSquare(*b, m.dest) & b->piecemask[ROOK] & CurrentSideMask(*b); index.toggle(b->index[m.from]); from = b->piecelist[(index).front()]; if (COL(m.from) != COL(from)) { printf("%c", ffile); } else { printf("%u", frank); } } } if (!IsEmptySquare(*b, m.dest)) { printf("x"); } printf("%c%u", dfile, drank); } else if (b->piecemask[QUEEN].contains(b->index[m.from])) { printf("Q"); if ((piececnt = (AttacksToSquare(*b, m.dest) & b->piecemask[QUEEN] & CurrentSideMask(*b)).count()) > 1) { if (piececnt > 2) { printf("%c%u", ffile, frank); } else { index = AttacksToSquare(*b, m.dest) & b->piecemask[QUEEN] & CurrentSideMask(*b); index.toggle(b->index[m.from]); from = b->piecelist[(index).front()]; if (COL(m.from) != COL(from)) { printf("%c", ffile); } else { printf("%u", frank); } } } if (!IsEmptySquare(*b, m.dest)) { printf("x"); } printf("%c%u", dfile, drank); } else if (b->piecemask[KING].contains(b->index[m.from])) { if (m.type != MoveTypeCastle) { printf("K"); if (!IsEmptySquare(*b, m.dest)) { printf("x"); } printf("%c%u", dfile, drank); } else { if (COL(m.dest) == 6) { printf("O-O"); } if (COL(m.dest) == 2) { printf("O-O-O"); } } } else { PrintMove(m); } } void PrintPV(const Board* b, const PV* pv) { Board c; int movenr = state.moveNr+2; c = *b; printf("%d. ", movenr/2); if (b->side == BLACK) { printf("... "); //movenr++; } for (unsigned int i = 0; i < pv->count; i++) { PrintSAN(&c, pv->moves[i]); MakeMove(&c, pv->moves[i]); RecalculateAttacksFromScratch(&c); if (IsInCheck(&c)) { printf("+"); } printf(" "); movenr++; if ((movenr & 1) == 0 && i+1 < pv->count) { printf("%d. ", movenr/2); } } } void ClearBoard(Board* b) { int i; for (i = 0; i < 64; i++) { b->index[i] = INVALID; b->bitlist[i].clear(); } for (i = 0; i < 32; i++) { b->piecelist[i] = INVALID; } for (i = 0; i < 6; i++) { b->piecemask[i].clear(); } b->sidemask[WHITE].clear(); b->sidemask[BLACK].clear(); for (i = 0; i < 100; i++) { b->rep[i] = 0; } b->side = WHITE; b->castle = 0; b->ep = INVALID; b->fifty = 0; } void PrintBoard(Board* b) { int i, j; for (i = 0; i < 64; i++) { j = i ^ 56; if (IsEmptySquare(*b, j)) { printf("."); } else { Bitlist tmp{b->index[j]}; if (!(tmp & b->sidemask[WHITE]).empty()) { if (!(tmp & b->piecemask[PAWN]).empty()) { printf("P"); } else if (!(tmp & b->piecemask[KNIGHT]).empty()) { printf("N"); } else if (!(tmp & b->piecemask[BISHOP]).empty()) { printf("B"); } else if (!(tmp & b->piecemask[ROOK]).empty()) { printf("R"); } else if (!(tmp & b->piecemask[QUEEN]).empty()) { printf("Q"); } else if (!(tmp & b->piecemask[KING]).empty()) { printf("K"); } else { BUG(0); } } else if (!(tmp & b->sidemask[BLACK]).empty()) { if (!(tmp & b->piecemask[PAWN]).empty()) { printf("p"); } else if (!(tmp & b->piecemask[KNIGHT]).empty()) { printf("n"); } else if (!(tmp & b->piecemask[BISHOP]).empty()) { printf("b"); } else if (!(tmp & b->piecemask[ROOK]).empty()) { printf("r"); } else if (!(tmp & b->piecemask[QUEEN]).empty()) { printf("q"); } else if (!(tmp & b->piecemask[KING]).empty()) { printf("k"); } else { BUG(0); } } else { BUG(0); } } if ((j&7)==7) { printf("\n"); } } if (b->side == WHITE) { printf("White to move.\n"); } else if (b->side == BLACK) { printf("Black to move.\n"); } else { BUG(0); } if (b->castle & 1) { printf("K"); } if (b->castle & 2) { printf("Q"); } if (b->castle & 4) { printf("k"); } if (b->castle & 8) { printf("q"); } printf("\n"); if (b->ep != INVALID) { printf("%c%u\n", 'a' + COL(b->ep), 1 + ROW(b->ep)); } else { printf("-\n"); } printf("%" PRIx64 "\n", b->hash); } int main() { Board b; Move m[128]; uint64_t n; clock_t start, stop; float time; char str[80]; int depth; int idx, i, side, max_depth; side = 2; max_depth = 8; InitZobrist(); InitTime(); InitTT(20); InitRays(); InitEval(); SetTimeLimits(300000); ParseFEN("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", &b); setvbuf(stdout, NULL, _IONBF, 0); printf("# Dorpsgek Dillinger 1\n"); printf("# by <NAME> (<NAME>).\n"); printf("# Dedicated to my friends in #seekrit.club.\n"); printf("# \n"); printf("# 3 parts vodka\n"); printf("# 1 part triple sec\n"); printf("# 2 parts cranberry juice\n"); printf("# 1 part lime juice\n"); printf("# \n"); printf("# Shake all ingredients in cocktail shaker filled with ice.\n"); printf("# Strain into a large cocktail glass and garnish with a slice of lime.\n"); printf("tellics set 1 Dorpsgek Dillinger 1\n"); printf("tellics alias gameend seek 3 0\n"); FILE* conf = fopen("dorpsgek.conf", "r"); /* At Graham Banks' request, we now support a very small config file. */ if (conf != NULL) { while (fgets(str, 80, conf) != NULL) { if (!strncmp(str, "memory", 6)) { sscanf(str, "memory %d", &i); InitTT(i); } } fclose(conf); } while (1) { if (b.side == side) { struct PV p; SetTimeLimits(10*state.timeLeft); if (state.infinite) { printf("# infinite analysis mode\n"); } RootSearch(&b, max_depth, &p); if (p.count && !state.infinite) { printf("move "); PRINT_MOVE(p.moves[0]); printf("\n"); MakeMove(&b, p.moves[0]); RecalculateAttacksFromScratch(&b); CalculateHash(&b); state.moveNr++; } /* If we somehow don't have a PV, then just concede. */ if (!p.count) { printf("resign\n"); } } for (idx = 0; (state.buf[idx] = getchar()) != '\n' && idx < 250; idx++); state.buf[idx+1] = '\0'; sscanf(state.buf, "%8s", str); if (!strcmp(str, "xboard") || !strcmp(str, "accepted") || !strcmp(str, "rejected") || !strcmp(str, "otim") || !strcmp(str, "computer")) { continue; } if (!strcmp(str, "protover")) { printf("feature done=0 setboard=1 usermove=1 colors=0 debug=1 myname=\"<NAME> 1\" memory=1 analyze=1 ping=1 sigint=0 sigterm=0 done=1\n"); continue; } if (!strcmp(str, "setboard")) { ParseFEN(state.buf+9, &b); state.moveNr = b.side; side = 2; printf("# %s\n", state.buf+9); continue; } if (!strcmp(str, "quit")) { FreeTT(); return 0; } if (!strcmp(str, "usermove")) { /* extract squares from coordinates */ Move tmp; tmp.from = state.buf[9] - 'a'; tmp.from += 8*(state.buf[10] - '1'); tmp.dest = state.buf[11] - 'a'; tmp.dest += 8*(state.buf[12] - '1'); /* check if move is a promotion */ if (strlen(state.buf) >= 15) { if (state.buf[13] == 'q') { tmp.type = MoveTypePromotionQueen; } if (state.buf[13] == 'r') { tmp.type = MoveTypePromotionRook; } if (state.buf[13] == 'b') { tmp.type = MoveTypePromotionBishop; } if (state.buf[13] == 'n') { tmp.type = MoveTypePromotionKnight; } } else { /* MoveTypeNormal is used as a placeholder for "I don't know" */ tmp.type = MoveTypeNormal; } n = Generate(&b, m); for (i = 0; i < n; i++) { if (m[i].from == tmp.from && m[i].dest == tmp.dest) { if (tmp.type != MoveTypeNormal) { if (tmp.type == MoveTypePromotionQueen && m[i].type != MoveTypePromotionQueen && m[i].type != MoveTypeCapturePromotionQueen) { continue; } if (tmp.type == MoveTypePromotionRook && m[i].type != MoveTypePromotionRook && m[i].type != MoveTypeCapturePromotionRook) { continue; } if (tmp.type == MoveTypePromotionBishop && m[i].type != MoveTypePromotionBishop && m[i].type != MoveTypeCapturePromotionBishop) { continue; } if (tmp.type == MoveTypePromotionKnight && m[i].type != MoveTypePromotionKnight && m[i].type != MoveTypeCapturePromotionKnight) { continue; } } MakeMove(&b, m[i]); RecalculateAttacksFromScratch(&b); CalculateHash(&b); state.moveNr++; break; } } if (i == n) { printf("Illegal move\n"); } continue; } /* Workaround for GUIs that do not support 'usermove' */ if (state.buf[1] >= '1' && state.buf[1] <= '8' && state.buf[3] >= '1' && state.buf[3] <= '8') { /* extract squares from coordinates */ Move tmp; tmp.from = state.buf[0] - 'a'; tmp.from += 8*(state.buf[1] - '1'); tmp.dest = state.buf[2] - 'a'; tmp.dest += 8*(state.buf[3] - '1'); /* check if move is a promotion */ if (strlen(str) == 5) { if (state.buf[4] == 'q') { tmp.type = MoveTypePromotionQueen; } if (state.buf[4] == 'r') { tmp.type = MoveTypePromotionRook; } if (state.buf[4] == 'b') { tmp.type = MoveTypePromotionBishop; } if (state.buf[4] == 'n') { tmp.type = MoveTypePromotionKnight; } } else { /* MoveTypeNormal is used as a placeholder for "I don't know" */ tmp.type = MoveTypeNormal; } n = Generate(&b, m); for (i = 0; i < n; i++) { if (m[i].from == tmp.from && m[i].dest == tmp.dest) { if (tmp.type != MoveTypeNormal) { if (tmp.type == MoveTypePromotionQueen && m[i].type != MoveTypePromotionQueen && m[i].type != MoveTypeCapturePromotionQueen) { continue; } if (tmp.type == MoveTypePromotionRook && m[i].type != MoveTypePromotionRook && m[i].type != MoveTypeCapturePromotionRook) { continue; } if (tmp.type == MoveTypePromotionBishop && m[i].type != MoveTypePromotionBishop && m[i].type != MoveTypeCapturePromotionBishop) { continue; } if (tmp.type == MoveTypePromotionKnight && m[i].type != MoveTypePromotionKnight && m[i].type != MoveTypeCapturePromotionKnight) { continue; } } MakeMove(&b, m[i]); RecalculateAttacksFromScratch(&b); CalculateHash(&b); state.moveNr++; break; } } if (i == n) { printf("Illegal move\n"); } continue; } if (!strcmp(str, "new")) { ParseFEN("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", &b); side = BLACK; ClearTT(); InitTime(); continue; } if (!strcmp(str, "go")) { side = b.side; continue; } if (!strcmp(str, "force")) { side = 2; continue; } if (!strcmp(str, "ping")) { printf("pong%s", state.buf+4); continue; } if (!strcmp(str, "sd")) { sscanf(state.buf, "sd %d", &max_depth); continue; } if (!strcmp(str, "st")) { state.infinite = 0; sscanf(state.buf, "st %d", &state.timePerMove); continue; } if (!strcmp(str, "level")) { int min, sec=0; if (sscanf(state.buf, "level %d %d %f", &state.mps, &min, &state.inc) != 3) // if this does not work, it must be min:sec format sscanf(state.buf, "level %d %d:%d %f", &state.mps, &min, &sec, &state.inc); state.timeControl = 60*min + sec; state.timePerMove = -1; continue; } if (!strcmp(str, "time")) { sscanf(state.buf, "time %d", &state.timeLeft); SetTimeLimits(state.timeLeft*10); continue; } if (!strcmp(str, "memory")) { sscanf(state.buf, "memory %d", &i); InitTT(i); continue; } if (!strcmp(str, "analyze")) { state.infinite = 1; side = b.side; continue; } if (!strcmp(str, "exit")) { state.infinite = 0; side = 2; continue; } if (!strcmp(str, "divide")) { sscanf(state.buf, "divide %d", &depth); start = clock(); n = Perft(&b, depth, 1); stop = clock(); time = (float)(((float)(stop) - (float)(start)) / CLOCKS_PER_SEC); printf("Nodes: %" PRIu64 " in %.3f seconds\n", n, time); continue; } if (!strcmp(str, "perft")) { unsigned long long correct = 0; printf("# %s", state.buf); sscanf(state.buf, "perft %d %" SCNu64, &depth, &correct); printf("# Expecting %" PRIu64 "\n", correct); n = Perft(&b, depth, 0); if (n != correct) { printf("WRONG RESULT! Expected %" PRIu64 ", got %" PRIu64 "\n", correct, n); return 1; } continue; } if (!strcmp(str, "d")) { PrintBoard(&b); continue; } if (!strcmp(str, "recalc")) { RecalculateAttacksFromScratch(&b); continue; } if (!strcmp(str, "eval")) { printf("Eval: %d\n", Eval(&b)); continue; } if (!strcmp(str, "flipeval")) { b.side ^= 1; printf("Eval: %d\n", Eval(&b)); b.side ^= 1; continue; } if (!strcmp(str, "i")) { printf("%d\n", IsIllegal(&b)); continue; } if (!strcmp(str, "sort")) { n = Generate(&b, m); qsort(m, n, sizeof(Move), CompareMoves); for (i = 0; i < n; i++) { PRINT_MOVE(m[i]); printf(" %d\n", m[i].score); } continue; } if (!strcmp(str, "pinned")) { Bitlist pinned = Evaluation::GetPinnedMask(&b, b.side); printf("Pinned: %x", pinned); for (const auto& bit: pinned) { int sq = b.piecelist[bit]; printf("%c%d, ", 'a' + COL(sq), '1' + ROW(sq)); } printf("\n"); continue; } printf("Error (invalid command): %s\n", state.buf); } return 0; } <file_sep>/* * This file is part of Dorpsgek. * * Dorpsgek is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Dorpsgek is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Dorpsgek. If not, see <http://www.gnu.org/licenses/>. */ #include "definitions.h" #include "functions.h" unsigned char ray_attacks[240]; signed char ray_vector[240]; enum { FlagWhitePawn = 1, FlagBlackPawn = 2, FlagKnight = 4, FlagBishop = 8, FlagRook = 16, FlagKing = 32 }; /* Credit to <NAME> for the initialisation code */ void InitRays() { int tmp, dir, dist, delta; for (tmp = 0; tmp < 240; tmp++) { ray_attacks[tmp] = ray_vector[tmp] = 0; } /* Pawn */ ray_attacks[OFFSET+(NORTH+EAST)] |= FlagWhitePawn; ray_attacks[OFFSET+(NORTH+WEST)] |= FlagWhitePawn; ray_attacks[OFFSET+(SOUTH+EAST)] |= FlagBlackPawn; ray_attacks[OFFSET+(SOUTH+WEST)] |= FlagBlackPawn; /* Knight */ for (dir = 0; dir < 8; dir++) { delta = rays[KNIGHT][dir]; ray_attacks[OFFSET+delta] |= FlagKnight; ray_vector[OFFSET+delta] = delta; } /* Bishop/Queen */ for (dir = 0; dir < 4; dir++) { delta = rays[BISHOP][dir]; for (dist = 1; dist < 8; dist++) { tmp = delta*dist; ray_attacks[OFFSET+tmp] |= FlagBishop; ray_vector[OFFSET+tmp] = delta; } } /* Rook/Queen */ for (dir = 0; dir < 4; dir++) { delta = rays[ROOK][dir]; for (dist = 1; dist < 8; dist++) { tmp = delta*dist; ray_attacks[OFFSET+tmp] |= FlagRook; ray_vector[OFFSET+tmp] = delta; } } /* King */ for (dir = 0; dir < 8; dir++) { delta = rays[KING][dir]; ray_attacks[OFFSET+delta] |= FlagKing; ray_vector[OFFSET+delta] = delta; } } <file_sep>/* * This file is part of Dorpsgek. * * Dorpsgek is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Dorpsgek is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Dorpsgek. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef WINDOWS #include <errno.h> #include <sys/resource.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #else #include <windows.h> #endif #include "definitions.h" #include "functions.h" struct State state; #define GUESSEDLENGTH 30 void InitTime() { state.inc = 8.0; state.moveNr = 0; state.mps = 0; state.neverExceedLimit = 0; state.noNewIterationLimit = 0; state.noNewMoveLimit = 0; state.timeControl = 0; state.timePerMove = 0; state.timeLeft = 30000; state.infinite = 0; } void SetTimeLimits(unsigned int msecLeft) { msecLeft -= 20; int movesleft = state.mps ? state.mps - (state.moveNr/2) : GUESSEDLENGTH; /* As <NAME> pointed out, the TC logic did not handle a repeating time control well. * If (state.moveNr/2) == state.mps, we would divide by zero at timelimit, with obvious bad results. * If (state.moveNr/2) > state.mps, we would allocate negative search time, resulting in an immediate abort. * * Thus, we add the repeating control until we arrive in positive movesleft land. */ while (movesleft <= 0) { movesleft += state.mps; } printf("# TC: movesleft: %d\n", movesleft); /* As pointed out by <NAME>, timelimit should incorporate the increment. */ int inc = (int)(state.inc*1000.0); int timelimit = (inc * (movesleft-1) + msecLeft) / movesleft; if (state.timePerMove > 0) { timelimit = (int)(state.timePerMove*1000); } printf("# TC: DR time management mode.\n"); printf("# TC: %d msec / %d moves + %d msec per move.\n", msecLeft, movesleft, inc); state.noNewIterationLimit = timelimit/2; state.neverExceedLimit = timelimit; printf("# never exceed: %d no iteration: %d\n", state.neverExceedLimit, state.noNewIterationLimit); } long long ReadClock() { // returns wall-clock time in msec #ifdef WINDOWS return GetTickCount(); #else struct timeval t; gettimeofday(&t, NULL); return t.tv_sec*1000ll + t.tv_usec/1000ll; #endif } int TimeUsed() { return ReadClock() - state.startTime; } // Shamelessly stolen from Fruit. int InputWaiting() { #ifdef WINDOWS static int init = 0, is_pipe; static HANDLE stdin_h; DWORD val, error; if (stdin->_cnt > 0) return 1; // HACK: assumes FILE internals // input init (only done once) if (!init) { init = 1; stdin_h = GetStdHandle(STD_INPUT_HANDLE); is_pipe = !GetConsoleMode(stdin_h,&val); // HACK: assumes pipe on failure if (!is_pipe) { SetConsoleMode(stdin_h,val&~(ENABLE_MOUSE_INPUT|ENABLE_WINDOW_INPUT)); FlushConsoleInputBuffer(stdin_h); // no idea if we can lose data doing this } } // different polling depending on input type // does this code work at all for pipes? if (is_pipe) { if (!PeekNamedPipe(stdin_h,NULL,0,NULL,&val,NULL)) { return 1; // HACK: assumes EOF on failure } return val > 0; // != 0??? } else { GetNumberOfConsoleInputEvents(stdin_h,&val); return val > 1; // no idea why 1 } return 0; #else // assume POSIX int val; fd_set set[1]; struct timeval time_val[1]; FD_ZERO(set); FD_SET(STDIN_FILENO,set); time_val->tv_sec = 0; time_val->tv_usec = 0; val = select(STDIN_FILENO+1,set,NULL,NULL,time_val); if (val == -1 && errno != EINTR) { printf("input_available(): select(): %s\n",strerror(errno)); exit(1); } return val > 0; #endif } int StopSearch() { if (state.infinite) { return InputWaiting(); } else { return TimeUsed() >= state.neverExceedLimit; } } <file_sep>/* * This file is part of Dorpsgek. * * Dorpsgek is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Dorpsgek is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Dorpsgek. If not, see <http://www.gnu.org/licenses/>. */ #include <string.h> #include "definitions.h" #include "functions.h" static int castle_mask[64] = { 13, 15, 15, 15, 12, 15, 15, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 7, 15, 15, 15, 3, 15, 15, 11 }; void MakeMove(Board* b, Move m) { int from, dest, type, i, tmp; unsigned int index, capindex; BUG(b != NULL); BUG(m.from >= 0 && m.from <= 63); BUG(m.dest >= 0 && m.dest <= 63); BUG(m.type >= MoveTypeNormal && m.type <= MoveTypeCapturePromotionKnight); from = m.from; dest = m.dest; type = m.type; index = b->index[from]; b->ep = INVALID; tmp = 1u << index; capindex = b->index[dest]; b->index[dest] = b->index[from]; b->index[from] = INVALID; switch (type) { case MoveTypeNormal: /* Nothing to do here, really */ if (((PieceIndexToBit(b->index[dest])) & b->piecemask[PAWN]).empty()) { b->fifty++; } else { b->fifty = 0; } break; case MoveTypeCapture: b->sidemask[!b->side].toggle(capindex); b->piecemask[GetPieceByBit(b, Bitlist{static_cast<int>(capindex)})].toggle(capindex); b->fifty = 0; break; case MoveTypeDoublePush: if (b->side == WHITE) { b->ep = dest - 8; } else { b->ep = dest + 8; } b->fifty = 0; break; case MoveTypeEnPassant: if (b->side == WHITE) { capindex = b->index[dest - 8]; b->index[dest - 8] = INVALID; b->piecelist[capindex] = INVALID; b->piecemask[PAWN].toggle(capindex); b->sidemask[BLACK].toggle(capindex); } else { capindex = b->index[dest + 8]; b->index[dest + 8] = INVALID; b->piecelist[capindex] = INVALID; b->piecemask[PAWN].toggle(capindex); b->sidemask[WHITE].toggle(capindex); } b->fifty = 0; break; case MoveTypePromotionKnight: b->piecemask[PAWN].toggle(index); b->piecemask[KNIGHT].toggle(index); b->fifty = 0; break; case MoveTypePromotionBishop: b->piecemask[PAWN].toggle(index); b->piecemask[BISHOP].toggle(index); b->fifty = 0; break; case MoveTypePromotionRook: b->piecemask[PAWN].toggle(index); b->piecemask[ROOK].toggle(index); b->fifty = 0; break; case MoveTypePromotionQueen: b->piecemask[PAWN].toggle(index); b->piecemask[QUEEN].toggle(index); b->fifty = 0; break; case MoveTypeCapturePromotionKnight: b->sidemask[!b->side].toggle(capindex); b->piecemask[GetPieceByBit(b, Bitlist{static_cast<int>(capindex)})].toggle(capindex); b->piecemask[PAWN].toggle(index); b->piecemask[KNIGHT].toggle(index); b->fifty = 0; break; case MoveTypeCapturePromotionBishop: b->sidemask[!b->side].toggle(capindex); b->piecemask[GetPieceByBit(b, Bitlist{static_cast<int>(capindex)})].toggle(capindex); b->piecemask[PAWN].toggle(index); b->piecemask[BISHOP].toggle(index); b->fifty = 0; break; case MoveTypeCapturePromotionRook: b->sidemask[!b->side].toggle(capindex); b->piecemask[GetPieceByBit(b, Bitlist{static_cast<int>(capindex)})].toggle(capindex); b->piecemask[PAWN].toggle(index); b->piecemask[ROOK].toggle(index); b->fifty = 0; break; case MoveTypeCapturePromotionQueen: b->sidemask[!b->side].toggle(capindex); b->piecemask[GetPieceByBit(b, Bitlist{static_cast<int>(capindex)})].toggle(capindex); b->piecemask[PAWN].toggle(index); b->piecemask[QUEEN].toggle(index); b->fifty = 0; break; case MoveTypeCastle: /* Kingside - F1*/ if (dest == 6) { /* Move the rook */ b->index[from+1] = b->index[from+3]; b->index[from+3] = INVALID; b->piecelist[b->index[from+1]] = from + 1; } /* Queenside - C1 */ if (dest == 2) { /* Move the rook */ b->index[from-1] = b->index[from-4]; b->index[from-4] = INVALID; b->piecelist[b->index[from-1]] = from - 1; } /* Kingside - F8 */ if (dest == 62) { /* Move the rook */ b->index[from+1] = b->index[from+3]; b->index[from+3] = INVALID; b->piecelist[b->index[from+1]] = from + 1; } /* Queenside - C8*/ if (dest == 58) { /* Move the rook */ b->index[from-1] = b->index[from-4]; b->index[from-4] = INVALID; b->piecelist[b->index[from-1]] = from - 1; } b->fifty++; } if (capindex != INVALID) { b->piecelist[capindex] = INVALID; } b->piecelist[index] = dest; b->side ^= 1; b->castle &= castle_mask[from] & castle_mask[dest]; for (i = 99; i > 0; i--) { b->rep[i] = b->rep[i-1]; } b->rep[0] = b->hash >> 32; } <file_sep>/* * This file is part of Dorpsgek. * * Dorpsgek is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Dorpsgek is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Dorpsgek. If not, see <http://www.gnu.org/licenses/>. */ #include "definitions.h" #include "functions.h" int IsTrivialDraw(Board* bd) { int wq, wr, wb, wn, wp; /* White piece counts */ int bq, br, bb, bn, bp; /* Black piece counts */ int q, r, b, n, p; /* Piece counts */ int major, minor; /* Piece category counts */ int i, count; /* Fifty-move rule */ if (bd->fifty >= 100) return 1; /* Repetition check */ count = 0; for (i = 1; i < 100; i += 2) { if (bd->rep[i] == (bd->hash >> 32)) count++; if (count >= 2) return 1; } /* Count pieces on board */ wq = (bd->piecemask[QUEEN] & bd->sidemask[WHITE]).count(); bq = (bd->piecemask[QUEEN] & bd->sidemask[BLACK]).count(); q = wq + bq; if (q) { return 0; } wr = (bd->piecemask[ROOK] & bd->sidemask[WHITE]).count(); br = (bd->piecemask[ROOK] & bd->sidemask[BLACK]).count(); r = wr + br; if (r) { return 0; } major = q + r; wb = (bd->piecemask[BISHOP] & bd->sidemask[WHITE]).count(); bb = (bd->piecemask[BISHOP] & bd->sidemask[BLACK]).count(); b = wb + bb; wn = (bd->piecemask[KNIGHT] & bd->sidemask[WHITE]).count(); bn = (bd->piecemask[KNIGHT] & bd->sidemask[BLACK]).count(); n = wn + bn; minor = b + n; wp = (bd->piecemask[PAWN] & bd->sidemask[WHITE]).count(); bp = (bd->piecemask[PAWN] & bd->sidemask[BLACK]).count(); p = wp + bp; if (p) { return 0; } /* Two pieces */ /* KK */ if (!major && !minor) return 1; /* Three pieces */ /* Minor piece endings are always draws */ if (!major && minor == 1) { return 1; } /* Four pieces */ /* Minor piece endings can be draws */ if (!major && minor == 2) { /* KNNK is a draw */ if (wn == 2 || bn == 2) { return 1; } /* TODO: Bishop color check */ } return 0; }
95ad3485dc1bc74821b58ce7a1e7aac03148497c
[ "Markdown", "Makefile", "C++" ]
19
C++
ZirconiumX/Dorpsgek
ced5d954ba7641d67e74aea15b0a37480bb34a74
c1edd9615d29e9b4978ba67997b9f4cd0f029043
refs/heads/master
<repo_name>muratdogan17/muratdogan17.github.io<file_sep>/service-worker.js var cacheName = 'havadurumu-6'; var filesToCache = [ '/', 'index.html', 'assets/css/main.css', 'https://fonts.googleapis.com/css?family=Lato:400,700,700italic,400italic&subset=latin,latin-ext', 'assets/img/bulut.png', 'assets/img/ic_menu_24px.svg', 'assets/img/sf-bg.png' ]; var dataCacheName = 'weatherData-v6'; this.onfetch = function(e) { console.log('[ServiceWorker Fetch]', e.request.url); var dataUrl = 'http://api.openweathermap.org/data/2.5/weather?q=ANK,TR&appid=b1b15e88fa797225412429c1c50c122a'; if (e.request.url.indexOf(dataUrl) === 0) { e.respondWith( fetch(e.request) .then(function(response) { return caches.open(dataCacheName).then(function(cache) { cache.put(e.request.url, response.clone()); console.log('[ServiceWorker] Fetched&Cached Data'); return response; }) }) ); } else { e.respondWith( caches.match(e.request).then(function(response) { return response || fetch(e.request); }) ); } } this.oninstall = function(e) { console.log('[ServiceWorker] Install'); e.waitUntil( caches.open(cacheName).then(function(cache) { console.info('[ServiceWorker] Caching app shell'); return cache.addAll(filesToCache); }) ); } this.onactivate = function(e) { console.log('[ServiceWorker] Activate'); e.waitUntil( caches.keys().then(function(keyList) { return Promise.all(keyList.map(function(key) { console.warn('[ServiceWorker] Removing old cache', key); if(key !== cacheName){ return caches.delete(key); } })); }) ); }
0af11f88758929cc6811a18fb56d2ae17fee11be
[ "JavaScript" ]
1
JavaScript
muratdogan17/muratdogan17.github.io
07e017425a6a7ac560f14f608f854a29070f88b9
1bd43e7beeadab96f9c97a7be8c971e86eb6a391
refs/heads/master
<repo_name>tip2tail/ProtocolApplicationLauncher<file_sep>/MainForm.cs /* * Created by SharpDevelop. * User: youngm * Date: 19/08/2016 * Time: 13:43 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using Microsoft.Win32; using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.IO; using System.Windows.Forms; using t2tSQLiteObject; namespace ProtocolApplicationLauncher { /// <summary> /// Description of MainForm. /// </summary> public partial class MainForm : Form { private t2tSQLite oDB; private const int _DB_VERSION_REQUIRED = 1; private ProgramStorage oPrograms; private ProgramItem oEditingItem; private bool bHidden; private string sProgramName; private string sFullURL; public MainForm() { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); // // TODO: Add constructor code after the InitializeComponent() call. // } public MainForm(bool bHidden, string sProgramName = "", string sFullURL = "") { this.bHidden = bHidden; this.sProgramName = sProgramName; this.sFullURL = sFullURL; InitializeComponent(); } private void MainForm_Load(object sender, EventArgs e) { // Open the database OpenDatabase(); // If we are in hidden mode then we aren't event going to display the form if (this.bHidden) { this.Hide(); LaunchApplication(sProgramName, sFullURL); } else { // Create the ProgramStorage object oPrograms = new ProgramStorage(); // Populate the storage class PopulatePrograms(); // Refresh RefreshAfterLoadOrEdit(); if (Program.bDebugMode) { labDebug.Show(); } RegisterProtocol(); } } private void LaunchApplication(string sProgramName, string sFullURL) { Dictionary<string, object> dictQuery = new Dictionary<string, object>(); dictQuery["pname"] = sProgramName; DataTable dtRow = oDB.Select("SELECT * FROM `PROGRAMS` WHERE `ID` = @pname;", dictQuery); if (dtRow.Rows.Count != 1) { FatalError("Unable to find this program in the database."); } DataRow oRow = dtRow.Rows[0]; var sCommand = oRow.Field<string>("COMMAND"); var sParams = oRow.Field<string>("PARAMS"); if (Program.bDebugMode) { MessageBox.Show("Command: " + sCommand + Environment.NewLine + "Params: " + sParams, "Debug"); } sParams.Replace("%URL%", sFullURL); Process.Start(sCommand, sParams); Application.Exit(); } private void RefreshAfterLoadOrEdit() { // Rebuild the list of programs on the form RefreshProgramList(); // Disable the button controls, after all nothing is selected yet! EnableDisableEditDeleteButtons(false); // Initial state EnableDisableAllEditControls(false); } private void RefreshProgramList() { lstPrograms.Items.Clear(); foreach (var oThisPrgram in this.oPrograms.GetProgramItemsList()) { lstPrograms.Items.Add(oThisPrgram.ProgramName); } lstPrograms.SelectedIndex = -1; } private void PopulatePrograms() { DataTable dtPrograms; try { // Load the Programs into the required datatable dtPrograms = oDB.Select("SELECT * FROM `PROGRAMS`"); } catch (Exception eXcep) { var sError = "Database Query Failed - Error P040" + Environment.NewLine + Environment.NewLine + eXcep.Message; FatalError(sError); return; } var iProgramCount = dtPrograms.Rows.Count; if (iProgramCount > 0) { for (var iX = 0; iX < iProgramCount; iX++) { // Populate the ProgramItem from the database table DataRow oRow = dtPrograms.Rows[iX]; var oProgramItem = new ProgramItem(); oProgramItem.DatabaseRowID = (int)oRow.Field<long>("ID"); oProgramItem.ProgramName = oRow.Field<string>("PROGNAME"); oProgramItem.Command = oRow.Field<string>("COMMAND"); oProgramItem.Parameters = oRow.Field<string>("PARAMS"); oProgramItem.RunAsOtherUser = oRow.Field<bool>("RUNASUSER"); oProgramItem.OtherUsername = oRow.Field<string>("RUNUSER"); oProgramItem.OtherPassword = oRow.Field<string>("RUNPASS"); oProgramItem.LaunchCount = (int)oRow.Field<long>("LAUNCHCOUNT"); this.oPrograms.ActionProgramItem(oProgramItem, ProgramStorage.ProgramItemAction._PIA_ADD); } } } private void FatalError(string sError) { // This is a fatal error - exit the application MessageBox.Show(sError, "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } private void OpenDatabase() { var sDatabaseDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "tip2tail", "ProtocolApplicationLauncher"); var sDatabaseFile = Path.Combine(sDatabaseDirectory, "PAL.db"); bool bOK = false; string sError = ""; do { // Check the DB is there and copy in a new blank version if required if (File.Exists(sDatabaseFile) == false) { try { CopyBlankDatabase(sDatabaseDirectory, sDatabaseFile); } catch (Exception eXcep) { sError = "Database Copy Failed - Error P010" + Environment.NewLine + Environment.NewLine + eXcep.Message; break; } } // Open the DB connection try { oDB = new t2tSQLite(sDatabaseFile); oDB.SetDatabaseOpen(true); } catch (Exception eXcep) { sError = "Database Open Failed - Error P020" + Environment.NewLine + Environment.NewLine + eXcep.Message; break; } // Update Required? try { var iDBVersion = oDB.GetUserVersion(); if (iDBVersion < _DB_VERSION_REQUIRED) { UpgradeDatabase(iDBVersion); } } catch (Exception eXcep) { sError = "Database Update Failed - Error P030" + Environment.NewLine + Environment.NewLine + eXcep.Message; } // All OK - database is found, open and up-to-date bOK = true; } while (false); if (bOK == false) { FatalError(sError); } } private void UpgradeDatabase(int iDBVersion) { throw new NotImplementedException(); } private void CopyBlankDatabase(string sDatabaseDirectory, string sDatabaseFile) { if (Directory.Exists(sDatabaseDirectory) == false) { Directory.CreateDirectory(sDatabaseDirectory); } var sBlankDB = Path.Combine(Path.GetDirectoryName(Program.sApplicationExePath), "PAL_blank.db"); File.Copy(sBlankDB, sDatabaseFile); } private void RegisterProtocol() { // Define protocol string sProtocol = "pal"; if (Program.bDebugMode) { sProtocol = "paldebug"; } // Program.sApplicationExePath; // The command we need to use var sCommand = "\"" + Program.sApplicationExePath + "\" \"%1\""; // Update the registry with the valid path and protocol... bool bOK = false; var sError = ""; do { try { // Step 1 - create the url protocol class key var oReg = Registry.CurrentUser.CreateSubKey("Software\\Classes\\" + sProtocol); oReg.SetValue("", "URL:" + sProtocol + " Handler"); oReg.SetValue("URL Protocol", ""); // Step 2 - create the shell keys oReg = oReg.CreateSubKey("shell\\open\\command"); oReg.SetValue("", sCommand); } catch (Exception eXcep) { sError = eXcep.Message; break; } bOK = true; } while (false); if (bOK == false) { MessageBox.Show(sError, "Exception when registering protocol", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btnAdd_Click(object sender, EventArgs e) { var oNewItem = new ProgramItem(); StartEditingItem(ref oNewItem); } private void StartEditingItem(ref ProgramItem oItem) { txtProgramName.Text = oItem.ProgramName; txtCommand.Text = oItem.Command; txtParams.Text = oItem.Parameters; txtLaunchCount.Text = oItem.LaunchCount.ToString(); cbAdmin.Checked = oItem.RunAsOtherUser; txtUsername.Text = oItem.OtherUsername; txtPassword.Text = Decrypt(oItem.OtherPassword); EnableDisableAllEditControls(true); EnableDisableOtherUserGoupBox(); EnableDisableEditDeleteButtons(false); btnAdd.Enabled = false; oEditingItem = oItem; } private void EnableDisableAllEditControls(bool bEnable) { grpEditControls.Enabled = bEnable; } private void EnableDisableOtherUserGoupBox() { panOtherUser.Enabled = cbAdmin.Checked; } private string Decrypt(string sString) { return ""; } private void btnCancel_Click(object sender, EventArgs e) { // Clear the fields with this quick workaround var oNewItem = new ProgramItem(); StartEditingItem(ref oNewItem); oEditingItem = null; // Disable the controls EnableDisableAllEditControls(false); EnableDisableEditDeleteButtons(true); btnAdd.Enabled = true; } private void btnAbout_Click(object sender, EventArgs e) { // Show the About Dialog new AboutForm().ShowDialog(); } private void btnExit_Click(object sender, EventArgs e) { Close(); } private void lstPrograms_SelectedIndexChanged(object sender, EventArgs e) { EnableDisableEditDeleteButtons((lstPrograms.SelectedIndex > -1)); } private void EnableDisableEditDeleteButtons(bool bEnable) { // Override if there are no items if (lstPrograms.Items.Count < 1) { bEnable = false; } btnEdit.Enabled = bEnable; btnDelete.Enabled = bEnable; } private void btnEdit_Click(object sender, EventArgs e) { if (lstPrograms.SelectedIndex > -1) { var oEditItem = this.oPrograms.GetItemAtIndex(lstPrograms.SelectedIndex); StartEditingItem(ref oEditItem); } } private void btnSave_Click(object sender, EventArgs e) { oEditingItem.ProgramName = txtProgramName.Text; oEditingItem.Command = txtCommand.Text; oEditingItem.Parameters = txtParams.Text; oEditingItem.RunAsOtherUser = cbAdmin.Checked; oEditingItem.OtherUsername = txtUsername.Text; oEditingItem.OtherPassword = <PASSWORD>; if (SaveItemToDatabase()) { EnableDisableAllEditControls(false); EnableDisableEditDeleteButtons(true); btnAdd.Enabled = true; RefreshAfterLoadOrEdit(); } } private bool SaveItemToDatabase() { // Return value bool bReturn = false; // Build the dictionary Dictionary<string, object> dictQuery = new Dictionary<string, object>(); dictQuery["pname"] = oEditingItem.ProgramName; dictQuery["pcommand"] = oEditingItem.Command; dictQuery["pparms"] = oEditingItem.Parameters; dictQuery["prunas"] = oEditingItem.RunAsOtherUser; dictQuery["puser"] = oEditingItem.OtherUsername; dictQuery["ppass"] = oEditingItem.OtherPassword; if (oEditingItem.DatabaseRowID == -1) { // INSERT try { int iID = oDB.Insert("INSERT INTO `PROGRAMS` VALUES (NULL, @pname, @pcommand, @pparms, @prunas, @puser, @ppass, 0);", dictQuery); this.oPrograms.ActionProgramItem(oEditingItem, ProgramStorage.ProgramItemAction._PIA_ADD); bReturn = true; } catch (Exception eXcep) { var sError = "Database INSERT Query Failed - Error P050" + Environment.NewLine + Environment.NewLine + eXcep.Message; MessageBox.Show(sError, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { // UPDATE dictQuery["pid"] = oEditingItem.DatabaseRowID; try { int iRows = oDB.Query("UPDATE `PROGRAMS` SET `PROGNAME` = @pname, `COMMAND` = @pcommand, `PARAMS` = @pparms, `RUNASUSER` = @prunas, `RUNUSER` = @puser, `RUNPASS` = @ppass WHERE `ID` = @pid;", dictQuery); this.oPrograms.ActionProgramItem(oEditingItem, ProgramStorage.ProgramItemAction._PIA_UPDATE); bReturn = true; } catch (Exception eXcep) { var sError = "Database UPDATE Query Failed - Error P060" + Environment.NewLine + Environment.NewLine + eXcep.Message; MessageBox.Show(sError, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } } return bReturn; } private void btnDelete_Click(object sender, EventArgs e) { var dRes = MessageBox.Show("Are you sure you want to delete this program?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dRes == DialogResult.Yes) { // Load the item var oEditItem = this.oPrograms.GetItemAtIndex(lstPrograms.SelectedIndex); // Build the Query and send to the DB try { Dictionary<string, object> dictQuery = new Dictionary<string, object>(); dictQuery["pid"] = oPrograms.GetItemAtIndex(lstPrograms.SelectedIndex).DatabaseRowID; int iRows = oDB.Query("DELETE FROM `PROGRAMS` WHERE `ID` = @pid;", dictQuery); this.oPrograms.ActionProgramItem(oEditItem, ProgramStorage.ProgramItemAction._PIA_DELETE); } catch (Exception eXcep) { var sError = "Database DELETE Query Failed - Error P070" + Environment.NewLine + Environment.NewLine + eXcep.Message; MessageBox.Show(sError, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } // Reload EnableDisableAllEditControls(false); EnableDisableEditDeleteButtons(true); btnAdd.Enabled = true; RefreshAfterLoadOrEdit(); } } private void lstPrograms_DoubleClick(object sender, EventArgs e) { btnEdit_Click(sender, e); } } } <file_sep>/TextViewForm.cs 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.Windows.Forms; namespace ProtocolApplicationLauncher { public partial class TextViewForm : Form { private string sWindowTitle = ""; private string sFileName = ""; public TextViewForm(string sWindowTitle = "Text Viewer", string sFileName = "?none?") { InitializeComponent(); this.sFileName = sFileName; this.sWindowTitle = sWindowTitle; } private void TextViewForm_Load(object sender, EventArgs e) { Text = sWindowTitle; var sError = ""; if (sFileName != "?none?") { try { if (File.Exists(sFileName)) { txtContent.Text = File.ReadAllText(sFileName); txtContent.Select(0, 0); } else { sError = "File not found!"; } } catch (Exception eXcep) { sError = eXcep.Message; } if (sError != "") { MessageBox.Show(sError, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Close(); } } } } } <file_sep>/AboutForm.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Windows.Forms; namespace ProtocolApplicationLauncher { public partial class AboutForm : Form { public AboutForm() { InitializeComponent(); } private void AboutForm_Load(object sender, EventArgs e) { var sVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); var iLastPoint = sVersion.LastIndexOf("."); if (iLastPoint > -1) { sVersion = sVersion.Remove(iLastPoint); } if (Program.bDebugMode) { sVersion = sVersion + " [Debug Build]"; } labVersion.Text = sVersion; labBuildDate.Text = Assembly.GetExecutingAssembly().GetLinkerTime().ToString("dd MMMM yyyy HH:mm"); } private void btnClose_Click(object sender, EventArgs e) { Close(); } private void btnWebsite_Click(object sender, EventArgs e) { Program.LaunchURL("http://www.tip2tail.scot/"); } private void btnHelp_Click(object sender, EventArgs e) { Program.LaunchURL("http://www.tip2tail.scot/pal/help"); } private void btnReleaseNotes_Click(object sender, EventArgs e) { Program.LaunchURL("http://www.tip2tail.scot/pal/release-notes"); } private void btnGithub_Click(object sender, EventArgs e) { Program.LaunchURL("https://github.com/tip2tail/ProtocolApplicationLauncher"); } private void btnLicense_Click(object sender, EventArgs e) { var sLicFile = Path.Combine(Path.GetDirectoryName(Program.sApplicationExePath), "LICENSE.TXT"); new TextViewForm("License Information", sLicFile).ShowDialog(); } } } <file_sep>/ProgramStorageClasses.cs using System; using System.Collections.Generic; using System.IO; using System.Reflection; namespace ProtocolApplicationLauncher { public class ProgramStorage { private List<ProgramItem> Items; public enum ProgramItemAction { _PIA_ADD, _PIA_UPDATE, _PIA_DELETE } public ProgramStorage() { this.Items = new List<ProgramItem>(); } public ProgramItem GetItemAtIndex(int iIndex) { if (iIndex <= (Items.Count - 1)) { return this.Items[iIndex]; } return null; } public int ProgramCount() { return this.Items.Count; } public List<ProgramItem> GetProgramItemsList() { return this.Items; } public void ActionProgramItem(ProgramItem oItem, ProgramItemAction eAction) { switch (eAction) { case ProgramItemAction._PIA_ADD: AddProgramItem(oItem); break; case ProgramItemAction._PIA_DELETE: DeleteProgramItem(oItem); break; case ProgramItemAction._PIA_UPDATE: UpdateProgramItem(oItem); break; } } private void AddProgramItem(ProgramItem oItem) { this.Items.Add(oItem); } private void UpdateProgramItem(ProgramItem oItem) { Items.Insert(DeleteProgramItem(oItem), oItem); } private int DeleteProgramItem(ProgramItem oItem) { var iX = 0; for (iX = 0; iX < this.ProgramCount(); iX++) { if (Items[iX].DatabaseRowID == oItem.DatabaseRowID) { Items.RemoveAt(iX); break; } } return iX; } } public class ProgramItem { public int DatabaseRowID { get; internal set; } public string ProgramName { get; internal set; } public string Command { get; internal set; } public string Parameters { get; internal set; } public int LaunchCount { get; internal set; } public bool RunAsOtherUser { get; internal set; } public string OtherUsername { get; internal set; } public string OtherPassword { get; internal set; } public ProgramItem() { this.DatabaseRowID = -1; } } public static class ExtensionMethods { public static DateTime GetLinkerTime(this Assembly assembly, TimeZoneInfo target = null) { var filePath = assembly.Location; const int c_PeHeaderOffset = 60; const int c_LinkerTimestampOffset = 8; var buffer = new byte[2048]; using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) stream.Read(buffer, 0, 2048); var offset = BitConverter.ToInt32(buffer, c_PeHeaderOffset); var secondsSince1970 = BitConverter.ToInt32(buffer, offset + c_LinkerTimestampOffset); var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var linkTimeUtc = epoch.AddSeconds(secondsSince1970); var tz = target ?? TimeZoneInfo.Local; var localTime = TimeZoneInfo.ConvertTimeFromUtc(linkTimeUtc, tz); return localTime; } } } <file_sep>/Program.cs /* * Created by SharpDevelop. * User: youngm * Date: 19/08/2016 * Time: 13:43 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Diagnostics; using System.Text.RegularExpressions; using System.Windows.Forms; namespace ProtocolApplicationLauncher { /// <summary> /// Class with program entry point. /// </summary> internal sealed class Program { #if DEBUG public static bool bDebugMode = true; #else public static bool bDebugMode = false; #endif // Application Executable Path public static string sApplicationExePath; /// <summary> /// Program entry point. /// </summary> [STAThread] private static void Main(string[] args) { // Set the application exe path variable sApplicationExePath = System.Reflection.Assembly.GetExecutingAssembly().Location; // Do we even need to show the window? // If we are launching with an arg then unlikely! bool bHidden = false; if (args.Length > 0 && args[0].StartsWith("pal")) { var sURLKey = Regex.Match(args[0], @"(?<=://).+?(?=:|/|\Z)").Value; var sProgramName = sURLKey; if (sURLKey.IndexOf('?') > -1) { // There is an additional parameter here sProgramName = sURLKey.Substring(0, sURLKey.IndexOf('?')); } bHidden = true; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm(bHidden)); } internal static void LaunchURL(string sURL) { Process.Start(sURL); } } } <file_sep>/README.md # ProtocolApplicationLauncher A program to allow commands to be launched from a webpage A work in progress - Copyright © 2016 tip2tail Ltd - Developed by <NAME>. # Requirements to Build Create an Environment Variable called PALTT that points to TextTransform.exe on your machine. From the command prompt: `set PALTT="C:\Program Files (x86)\Microsoft Visual Studio\VS15Preview\Common7\IDE"` # License MIT License Copyright (c) 2016 tip2tail Ltd 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>/Properties/AssemblyInfo.cs using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Resources; // General Information [assembly: AssemblyTitle("Protocol Application Launcher - PAL")] [assembly: AssemblyDescription("Utility that allows commands to be executed by means of a webpage protocol")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("tip2tail Ltd")] [assembly: AssemblyProduct("ProtocolApplicationLauncher")] [assembly: AssemblyCopyright("Copyright 2016 tip2tail Ltd")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information [assembly: AssemblyVersion("0.0.22")] [assembly: NeutralResourcesLanguageAttribute( "en-GB" )] /* Output - Got ASSINFO Got matches - count = 1 Got revision = 0 Got build = 22 B */ // Build - true // Revision -
96e0456a5771a8e9a086a3f6e43da7b6ac591e31
[ "Markdown", "C#" ]
7
C#
tip2tail/ProtocolApplicationLauncher
1a31384961e35f96119915594b339f39df045b4c
da717ddba603cca42bf8123114f2354a1d300f7d
refs/heads/master
<file_sep>export default { IMAGE: { CAMERA: { OPEN: 'image.camera.open' }, CODE:{ SCANQRCODE:'image.code.scanQRCode' }, ALBUM:{ OPEN:'image.album.open' } }, UI:{ NAVIGATION:{ PUSH:'ui.navigation.push', POP:'ui.navigation.pop', CLOSE:'ui.navigation.close', PRESENT:'ui.navigation.present' }, STYLE:{ SET_NAVIGATION_BAR_HIDDEN:'ui.style.setNavigationBarHidden', SET_NAVIGATION_BACKGROUND_COLOR:'ui.style.setNavigationBackgroundColor', SET_NAVIGATION_TITLE:'ui.style.setNavigationTitle', SET_STATUS_BAR_HIDDEN:'ui.style.setStatusBarHidden', SET_NAVIGATION_ITEM_COLOR:'ui.style.setNavigationItemColor', SET_STATUS_BAR_STYLE:'ui.style.setStatusBarStyle', GET_NAVIGATION_BAR_HEIGHT:'ui.style.getNavigationBarHeight' }, SCREEN:{ GET_WIDTH:'ui.screen.getWidth', GET_HEIGHT:'ui.screen.getHeight', ROTATE:'ui.screen.rotate' } }, NET:{ HTTP:{ SYNC_REQUEST:'net.http.syncRequest', ASYNC_REQUEST:'net.http.asyncRequest', UPLOAD_FILE:'net.http.uploadFile', DOWNLOAD_FILE:'net.http.downloadFile' } }, IO:{ FILE:{ DELETE_LONG_TERM_FILE:'io.file.deleteLongTermFile', DELETE_SHORT_TERM_FILE:'io.file.deleteShortTermFile', CLEAR_ALL_LONG_TERM_FILES:'io.file.clearAllLongTermFiles', CLEAR_ALL_SHORT_TERM_FILES:'io.file.clearAllShortTermFiles' } }, MAP:{ LOCATION:{ GET_POSITION:'map.location.getPosition', ON_INSTANT_POSITION:'map.location.onInstantPosition', OFF_INSTANT_POSITION:'map.location.offInstantPosition', } }, CALL:{ CUSTOMS:{ CALL_CUSTOM:'call.customs.callCustom' } }, DATA:{ STORAGE:{ GET:'data.storage.get', SET:'data.storage.set', REMOVE:'data.storage.remove', CLEAR:'data.storage.clear' } }, BIOMETRICS:{ CHECK:{ START:'biometrics.check.start' } } }<file_sep>let push = (type, aim, config) => { __send_message( __TYPE.UI.NAVIGATION.PUSH, { aim: aim, type: type, config: config } ) } let pop = (layer) => { __send_message( __TYPE.UI.NAVIGATION.POP, { layer: layer } ) } let close = (layer) => { __send_message( __TYPE.UI.NAVIGATION.CLOSE, { layer: layer } ) } let present = (type, aim, config) => { __send_message( __TYPE.UI.NAVIGATION.PRESENT, { type: type, aim: aim, config: config } ) } export default { push, pop, close, present }<file_sep>let _platform = '' let _callbackObj = new Object() const __android__ = 'android' const __ios__ = 'ios' /** * 设置当前平台(通常由平台调用) * @param platform 平台名称:android / ios */ let setPlatform = (platform) => { _platform = platform } /** * 获取当前设置的所属平台 * @returns {string} 平台名称:android / ios */ let getPlatform = () => { return _platform } /** * 调用平台入口函数 * @param type * @param parameters */ let sendMessage = (type, parameters, isSync) => { let data = JSON.stringify({ type: type, params: parameters, sync: isSync }) if (getPlatform() === __android__) { // android消息发送 return window.__js_android__.message(data) } else if (getPlatform() === __ios__) { // ios消息发送7 let result = window.prompt(data) return result } } /** * 保存callback函数 * @param uuid * @param fn */ let saveCallback = (fn) => { let uuid = createUUID() _callbackObj[uuid] = fn return uuid } /** * 读取callback函数 * @param uuid * @returns {*} */ let loadCallback = function (uuid) { let arr = Array.prototype.slice.call(arguments) arr.splice(0, 1); return _callbackObj[uuid].apply(window, arr) } /** * 销毁uuid和callback映射关系 * @param uuid */ let distoryCallback = (uuid) => { delete _callbackObj[uuid] } /** * create uuid */ let createUUID = (function (uuidRegEx, uuidReplacer) { return function () { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase(); }; })(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c == "x" ? r : (r & 3 | 8); return v.toString(16); }) /** * 统一处理config,把config中的回调函数传入saveCallback * @param config * @returns {*} */ let handleConfig = (config) => { for (let key in config) { if (typeof config[key] === "function") { config[key] = saveCallback(config[key]) } } return config } export default { setPlatform, getPlatform, sendMessage, saveCallback, loadCallback, distoryCallback, createUUID, handleConfig }<file_sep>let openAlbum = (config) => { let hConfig = __handle_config(config) __send_message( __TYPE.IMAGE.ALBUM.OPEN, hConfig ) } export default { openAlbum }<file_sep>/** * 隐藏导航栏 * @param isHidden * * @return void */ let setNavigationBarHidden = (isHidden) => { __send_message( __TYPE.UI.STYLE.SET_NAVIGATION_BAR_HIDDEN, { isHidden: isHidden } ) } /** * 设置导航栏背景颜色 * @param color * * @return void */ let setNavigationBackgroundColor = (color) => { __send_message( __TYPE.UI.STYLE.SET_NAVIGATION_BACKGROUND_COLOR, { color: color } ) } /** * 设置导航标题 * @param title * * @return void */ let setNavigationTitle = (title) => { __send_message( __TYPE.UI.STYLE.SET_NAVIGATION_TITLE, { title: title } ) } let setStatusBarHidden = (isHidden) => { __send_message( __TYPE.UI.STYLE.SET_STATUS_BAR_HIDDEN, { isHidden: isHidden } ) } let setNavigationItemColor = (color) => { __send_message( __TYPE.UI.STYLE.SET_NAVIGATION_ITEM_COLOR, { color: color } ) } let setStatusBarStyle = (style) => { __send_message( __TYPE.UI.STYLE.SET_STATUS_BAR_STYLE, { style: style } ) } let getNavigationBarHeight = (config) => { let hConfig = __handle_config(config) __send_message( __TYPE.UI.STYLE.GET_NAVIGATION_BAR_HEIGHT, hConfig ) } export default { setNavigationBarHidden, setNavigationBackgroundColor, setNavigationTitle, setStatusBarHidden, setNavigationItemColor, setStatusBarStyle, getNavigationBarHeight }<file_sep>// 定位一次 let getLocation = (config)=>{ let hConfig = __handle_config(config) __send_message( __TYPE.MAP.LOCATION.GET_POSITION, hConfig ) } // 即时定位(打开) let onInstantLocation = (config)=>{ let hConfig = __handle_config(config) __send_message( __TYPE.MAP.LOCATION.ON_INSTANT_POSITION, hConfig ) } // 即时定位(关闭) let offInstantLocation = (config)=>{ let hConfig = __handle_config(config) __send_message( __TYPE.MAP.LOCATION.OFF_INSTANT_POSITION, hConfig ) } export default { getLocation, onInstantLocation, offInstantLocation }<file_sep>import image from './image' import core from './core' import TYPE from './type' import ui from './ui' import net from './net' import io from './io' import map from './map' import call from './call' import data from './data' import biometrics from './biometrics' window.$__set_platform__ = core.setPlatform window.__send_message = core.sendMessage window.__TYPE = TYPE window.__handle_config = core.handleConfig window.__load_callback = core.loadCallback window.__distory_callback = core.distoryCallback window.$__get_platform__ = core.getPlatform window.$lemix = { image, ui, net, io, map, call, data, biometrics } <file_sep># lemix-js-sdk lemix-js-sdk <file_sep>import location from './location' export default { location }<file_sep>let callCustom = (config)=>{ let hConfig = __handle_config(config) __send_message( __TYPE.CALL.CUSTOMS.CALL_CUSTOM, hConfig ) } export default { callCustom }<file_sep>let deleteLongTermFile = (fileKey) => { __send_message( __TYPE.IO.FILE.DELETE_LONG_TERM_FILE, { fileKey:fileKey } ) } let deleteShortTermFile = (fileKey) => { __send_message( __TYPE.IO.FILE.DELETE_SHORT_TERM_FILE, { fileKey:fileKey } ) } let clearAllLongTermFiles = () => { __send_message( __TYPE.IO.FILE.CLEAR_ALL_LONG_TERM_FILES, {} ) } let clearAllShortTermFiles = () => { __send_message( __TYPE.IO.FILE.CLEAR_ALL_SHORT_TERM_FILES, {} ) } export default { deleteLongTermFile, deleteShortTermFile, clearAllLongTermFiles, clearAllShortTermFiles }
f7651f1431bdb9401f2f3f2fb7f2600bed8b8400
[ "JavaScript", "Markdown" ]
11
JavaScript
lemix-project/lemix-js-sdk
1e8c7b34b21e9c25ab005b194f6a5ff5efb8d1c9
06311e8f82aebe683be2acbed20c71076a114d50
refs/heads/master
<repo_name>timothykoh/110_web_coding<file_sep>/my_imports.py import time import document class g: listCount = 0 class Debug: debugMode = False def log(s): if Debug.debugMode: print "<span class='blue-text'>" + s + "</span>", def logln(s): if Debug.debugMode: print "<span class='blue-text'>" + s + "</span>" class Dom: animate = False delay = 1 def create(kwargs): if "tag" in kwargs: tag = kwargs["tag"] else: tag = "div" elem = document.createElement(tag) if "html" in kwargs: elem.innerHTML = kwargs.pop("html") for key in kwargs: elem.setAttribute(key, kwargs[key]) return elem def get(key): if len(key) == 0: return None elif key[0] == "#": return document.getElementById(key[1:]) elif key[0] == ".": return document.getElementsByClassName(key[1:]) else: return document.getElementsByTagName(key) def appendAnimate(parent, elem): classNames = elem.getAttribute("class") + " hidden" elem.setAttribute("class", classNames) parent.appendChild(elem) time.sleep(0.1) elem.setAttribute("class", classNames.replace("hidden", "")) time.sleep(Dom.delay) def appendInstant(parent, elem): parent.appendChild(elem) def append(parent, elem): if Dom.animate: Dom.appendAnimate(parent, elem) else: Dom.appendInstant(parent, elem) def removeAnimate(parent, elem): classNames = elem.getAttribute("class") + " hidden" elem.setAttribute("class", classNames) time.sleep(Dom.delay) parent.removeChild(elem) def removeInstant(parent, elem): parent.removeChild(elem) def remove(parent, elem): if Dom.animate: Dom.removeAnimate(parent, elem) else: Dom.removeInstant(parent, elem) def setDebugMode(b): Debug.debugMode = b def setAnimate(b): Dom.animate = b class List(list): PARENT_ID = "list-visual-area" CLASS = "list-block" ITEM_CLASS = "list-block-item" NAME_CLASS = "list-name" def getDomId(self): return List.CLASS + str(self.id) def getItemClass(self): # used for css stylings genericClass = List.ITEM_CLASS # unique id differentiates one objects specificClass from another specificClass = List.ITEM_CLASS + str(self.id) return genericClass + " " + specificClass def __init__(self, lst, **kwargs): if "name" in kwargs: self.name = kwargs["name"] else: self.name = "list" Debug.log("Creating list: " + str(lst) + "...") g.listCount += 1 self.id = g.listCount # unique id # create dom elem for list self.domElem = Dom.create({ "tag": "div", "id": self.getDomId(), "class": List.CLASS }) listNameElem = Dom.create({ "tag": "div", "class": List.NAME_CLASS, "html": self.name }) Dom.appendInstant(self.domElem, listNameElem) # create dom elem for each item in list and append it to # the list dom elem for item in lst: listItemElem = Dom.create({ "tag": "div", "class": self.getItemClass(), "html": item }) Dom.appendInstant(self.domElem, listItemElem) # append dom list to the dom listArea = Dom.get("#" + List.PARENT_ID) Dom.append(listArea, self.domElem) Debug.logln("created") def append(self, item): Debug.log("Appending %s to %s..." % (item,self)) # create dom elem for the list item listItemElem = Dom.create({ "tag": "div", "class": self.getItemClass(), "html": item }) # append the dom elem to the list Dom.append(self.domElem, listItemElem) list.append(self, item) Debug.logln("result: %s" % (self,)) def remove(self, item): Debug.log("Removing %s from %s..." % (item,self)) listItemElems = Dom.get("." + self.getItemClass()) for listItem in listItemElems: if listItem.innerHTML == str(item): Dom.remove(self.domElem, listItem) break list.remove(self, item) Debug.logln("result: %s" % (self,)) def clearLists(): listArea = Dom.get("#" + List.PARENT_ID) listArea.innerHTML = "" clearLists()<file_sep>/js/script.js CODE_KEY = "CODE_KEY"; window.libStr = ""; var sampleCode = "setAnimate(True)\n"+ "setDebugMode(True)\n"+ "\n"+ "numList = [2,3,4]\n"+ "numList.append(5)\n"+ "numList.append(6)\n"+ "numList.remove(4)\n"+ "\n"+ "for i in range(0,2):\n"+ " numList.append(i)\n"+ "\n"+ "print('Done with numList operations')\n"+ "\n"+ "strList = ['hey', 'there']\n"+ "strList.append('friend')\n"+ "strList.remove('friend')\n"+ "strList.append('buddy')" // init code mirror var editor = CodeMirror($("#editor")[0], { mode: "python", indentUnit: 4, keyMap: "sublime", extraKeys: { Tab: function(cm) { var spaces = Array(cm.getOption("indentUnit") + 1).join(" "); cm.replaceSelection(spaces); } }, lineNumbers: true, lineWrapping: true, showCursorWhenSelecting: true, autoCloseBrackets: true, matchBrackets: true }); // init skulpt $(document).delegate('#code-input', 'keydown', function(e) { var keyCode = e.keyCode || e.which; if (keyCode == 9) { e.preventDefault(); var start = $(this).get(0).selectionStart; var end = $(this).get(0).selectionEnd; // set textarea value to: text before caret + tab + text after caret $(this).val($(this).val().substring(0, start) + "\t" + $(this).val().substring(end)); // put caret at right position again $(this).get(0).selectionStart = $(this).get(0).selectionEnd = start + 1; } }); function outputFunc(text){ $("#code-output").append(text); } function builtinRead(x){ if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined){ throw "File not found: '" + x + "'"; } return Sk.builtinFiles["files"][x]; } $("#run-btn").click(function(){ runCode(); }); function runPythonCode(code){ $("#code-output").html(""); Sk.pre = "code-output"; Sk.configure({ output: outputFunc, read: builtinRead }); // (Sk.TurtleGraphics || (Sk.TurtleGraphics = {})).target = "canvas-area"; var myPromise = Sk.misceval.asyncToPromise(function(){ return Sk.importMainWithBody("<stdin>", false, code, true); }); myPromise.then(function(mod){ console.log("success"); }, function(err){ $("#code-output").append("<span class='red-text'>" + err.toString() + "</span>"); console.error(err.toString()); }); } // load python lib $.ajax({ url: "my_imports.py", dataType: "text", success: function(data){ window.libStr = data + "\n"; }, error: function(err){ console.error(err); } }); var feedbackMsgTimeout; function showFeedbackMsg(){ $("#feedback-msg").removeClass("hidden"); window.clearTimeout(feedbackMsgTimeout); feedbackMsgTimeout = setTimeout(function(){ $("#feedback-msg").addClass("hidden"); }, 1000); } function saveCode(){ var code = editor.getValue(); localStorage.setItem(CODE_KEY, code); $("#feedback-msg").html("saved"); showFeedbackMsg(); } function runCode(){ var rawCode = editor.getValue(); // replace list assignments to use the custom list // i.e. lst = [1,2,3] becomes // lst = List([1,2,3],name='list') var listRegex = /(\w+)\s+=\s+\[(.*?)\]/g var matchArr = rawCode.match(listRegex); for (var i = 0; i < matchArr.length; i++){ matchedStr = matchArr[i] var capturedArr = /(\w+)\s+=\s+\[(.*?)\]/g.exec(matchedStr) var listName = capturedArr[1]; var listValues = capturedArr[2]; var newListStr = listName + " = List([" + listValues + "],name='" + listName + "')"; rawCode = rawCode.replace(matchedStr, newListStr) } console.log(rawCode); var code = window.libStr + rawCode // var code = rawCode; runPythonCode(code); $("#feedback-msg").html("running code"); showFeedbackMsg(); } function loadCode(){ var savedCode = localStorage.getItem(CODE_KEY); if (savedCode === undefined || savedCode === null){ savedCode = sampleCode; } editor.setValue(savedCode); } // init keypress handler $("#editor").keydown(function(e) { if ((e.metaKey || e.ctrlKey) && e.which == 83){ // cmd + s or ctrl + s pressed e.preventDefault(); saveCode(); } if ((e.metaKey || e.ctrlKey) && e.which == 82){ // cmd + r or ctrl + r pressed e.preventDefault(); runCode(); } }); $(document).ready(function(){ loadCode(); });
8be75b322c9258c23a61c8faacde4eea33b5f186
[ "JavaScript", "Python" ]
2
Python
timothykoh/110_web_coding
6a7201ab5f4048253c2883828a71c2183da684f5
eb3bf74e04dbf580add0477c3f7b7d4578984344
refs/heads/master
<file_sep><?php class DashboardController extends BaseController { protected $layout = 'layout'; public function index() { $provincia = 'tucuman'; $this->layout->content = View::make('dashboard.index', compact('provincia')); } } <file_sep><?php class ProvinciaController extends BaseController { protected $layout = 'layout'; public function callProvincia($provincia) { $method = camel_case($provincia); $this->$method(); } public function buenosAires() { $provincia = 'buenos-aires'; $mainmenu = View::make('partials.mainmenus.buenos-aires'); $news = News::whereIn('provincia_id', array(1, 2))->orderBy('updated_at', 'DESC')->paginate(5); $sliders = Homeslider::whereIn('provincia_id', array(1, 2))->get(); $ultimospartidos = Ultimospartidos::whereIn('provincia_id', array(1, 2))->get(); $this->layout->content = View::make('provincias', compact('provincia', 'sliders', 'news', 'mainmenu', 'ultimospartidos')); } public function catamarca() { $provincia = 'catamarca'; $mainmenu = View::make('partials.mainmenus.catamarca'); $news = News::whereIn('provincia_id', array(1, 3))->orderBy('updated_at', 'DESC')->paginate(5); $sliders = Homeslider::whereIn('provincia_id', array(1, 3))->get(); $this->layout->content = View::make('provincias', compact('provincia', 'sliders', 'news', 'mainmenu')); } public function cordoba() { $provincia = 'cordoba'; $mainmenu = View::make('partials.mainmenus.cordoba'); $news = News::whereIn('provincia_id', array(1, 4))->orderBy('updated_at', 'DESC')->paginate(5); $sliders = Homeslider::whereIn('provincia_id', array(1, 4))->get(); $this->layout->content = View::make('provincias', compact('provincia', 'sliders', 'news', 'mainmenu')); } public function elNacional() { $provincia = 'el-nacional'; $mainmenu = View::make('partials.mainmenus.el-nacional'); $news = News::whereIn('provincia_id', array(1, 5))->orderBy('updated_at', 'DESC')->paginate(5); $sliders = Homeslider::whereIn('provincia_id', array(1, 5))->get(); $this->layout->content = View::make('provincias', compact('provincia', 'sliders', 'news', 'mainmenu')); } public function jujuy() { $provincia = 'jujuy'; $mainmenu = View::make('partials.mainmenus.jujuy'); $news = News::whereIn('provincia_id', array(1, 6))->orderBy('updated_at', 'DESC')->paginate(5); $sliders = Homeslider::whereIn('provincia_id', array(1, 6))->get(); $this->layout->content = View::make('provincias', compact('provincia', 'sliders', 'news', 'mainmenu')); } public function santaFe() { $provincia = 'santa-fe'; $mainmenu = View::make('partials.mainmenus.santa-fe'); $news = News::whereIn('provincia_id', array(1, 7))->orderBy('updated_at', 'DESC')->paginate(5); $sliders = Homeslider::whereIn('provincia_id', array(1, 7))->get(); $this->layout->content = View::make('provincias', compact('provincia', 'sliders', 'news', 'mainmenu')); } public function santiago() { $provincia = 'santiago'; $mainmenu = View::make('partials.mainmenus.santiago'); $news = News::whereIn('provincia_id', array(1, 8))->orderBy('updated_at', 'DESC')->paginate(5); $sliders = Homeslider::whereIn('provincia_id', array(1, 8))->get(); $this->layout->content = View::make('provincias', compact('provincia', 'sliders', 'news', 'mainmenu')); } public function tucuman() { $provincia = 'tucuman'; $mainmenu = View::make('partials.mainmenus.tucuman'); $news = News::whereIn('provincia_id', array(1, 9))->orderBy('updated_at', 'DESC')->paginate(5); $sliders = Homeslider::whereIn('provincia_id', array(1, 9))->get(); $this->layout->content = View::make('provincias', compact('provincia', 'sliders', 'news', 'mainmenu')); } } <file_sep><?php class News extends \Eloquent { protected $table = 'news'; protected $fillable = ['title', 'body', 'provincia_id', 'slug']; public static $rules = [ 'title' => 'required', 'body' => 'required|min:20', 'provincia_id' => 'required', ]; // Relacion public function provincia() { return $this->belongsTo('Provincia'); } }<file_sep><?php // Composer: "fzaninotto/faker": "v1.3.0" //use Faker\Factory as Faker; class ProvinciaTableSeeder extends Seeder { public function run() { Provincia::create(['name' => 'Todas']); Provincia::create(['name' => 'Buenos Aires']); Provincia::create(['name' => 'Catamarca']); Provincia::create(['name' => 'Córdoba']); Provincia::create(['name' => 'El Nacional']); Provincia::create(['name' => 'Jujuy']); Provincia::create(['name' => 'Santa Fe']); Provincia::create(['name' => 'Santiago del Estero']); Provincia::create(['name' => 'Tucumán']); } }<file_sep><?php class NewsController extends \BaseController { protected $layout = 'layout'; public function __construct() { $this->beforeFilter('auth', array('only' => array('index', 'show', 'edit', 'update'))); } /** * Display a listing of the resource. * GET /news * @return Response */ public function index() { $news = News::with('provincia')->orderBy('updated_at', 'DESC')->paginate(5); $this->layout->content = View::make('news.index', compact('news')); } /** * Show the form for creating a new resource. * GET /news/create * * @return Response */ public function create() { $provincias = Provincia::lists('name', 'id'); $this->layout->content = View::make('news.create', compact('provincias')); } /** * Store a newly created resource in storage. * POST /news * * @return Response */ public function store() { $validator = Validator::make($data = Input::all(), News::$rules); if ($validator->fails()) { return Redirect::back()->withErrors($validator)->withInput(); } $newNew = Input::all(); $newNew['slug'] = Str::slug(Input::get('title')); News::create($newNew); return Redirect::to('news'); } /** * Display the specified resource. * GET /news/{id} * * @param int $id * @return Response */ public function show($id) { $news = News::find($id); $this->layout->content = View::make('news.show', compact('news')); } /** * @param $provincia * @param $slug */ public function showBySlug($provincia, $slug) { $news = News::where('slug', $slug)->first(); View::share('provincia', $provincia); $mainmenu = View::make('partials.mainmenus.'.$provincia); $this->layout->content = View::make('news.show', compact('news', 'mainmenu')); } /** * Show the form for editing the specified resource. * GET /news/{id}/edit * * @param int $id * @return Response */ public function edit($id) { $news = News::find($id); $provincias = Provincia::lists('name', 'id'); $this->layout->content = View::make('news.edit', compact('news', 'provincias')); } /** * Update the specified resource in storage. * PUT /news/{id} * * @param int $id * @return Response */ public function update($id) { $validator = Validator::make($data = Input::all(), News::$rules); if ($validator->fails()) { return Redirect::back()->withErrors($validator)->withInput(); } $news = News::findOrFail($id); $data['slug'] = Str::slug(Input::get('title')); $news->update($data); return Redirect::to('news'); } /** * Remove the specified resource from storage. * DELETE /news/{id} * * @param int $id * @return Response */ public function destroy($id) { $news = News::findOrFail($id); $news->delete(); return Redirect::to('news'); } }<file_sep><?php class HomesliderController extends BaseController { protected $layout = 'layout'; /** * Display a listing of the resource. * GET /news * * @return Response */ public function index() { $sliders = Homeslider::with('provincia')->get(); $this->layout->content = View::make('homeslider.index', compact('sliders')); } /** * Show the form for creating a new resource. * GET /homesliders/create * * @return Response */ public function create() { $provincias = Provincia::lists('name', 'id'); $this->layout->content = View::make('homeslider.create', compact('provincias')); } /** * Store a newly created resource in storage. * POST /homesliders * * @return Response */ public function store() { $validator = Validator::make($data = Input::all(), Homeslider::$rules); if ($validator->fails()) { return Redirect::back()->withErrors($validator)->withInput(); } $file = Input::file('image'); $newFileName = str_replace(' ', '', $file->getClientOriginalName()); $newFileName = time() . $newFileName; $file->move(public_path() . '/img/slider/' , $newFileName); $data['image'] = $newFileName; Homeslider::create($data); return Redirect::to('homeslider'); } /** * Display the specified resource. * GET /homesliders/{id} * * @param int $id * @return Response */ public function show($id) { $slider = Homeslider::find($id); $this->layout->content = View::make('homeslider.show', compact('slider')); } /** * Show the form for editing the specified resource. * GET /homesliders/{id}/edit * * @param int $id * @return Response */ public function edit($id) { $slider = Homeslider::find($id); $provincias = Provincia::lists('name', 'id'); $this->layout->content = View::make('homeslider.edit', compact('slider', 'provincias')); } /** * Update the specified resource in storage. * PUT /homesliders/{id} * * @param int $id * @return Response */ public function update($id) { $validator = Validator::make($data = Input::all(), Homeslider::$rulesUpdate); if ($validator->fails()) { return Redirect::back()->withErrors($validator)->withInput(); } $slider = Homeslider::findOrFail($id); if ( Input::hasFile('image') ) { $file = Input::file('image'); $newFileName = str_replace(' ', '', $file->getClientOriginalName()); $newFileName = time() . $newFileName; $file->move(public_path() . '/img/slider/' , $newFileName); $data['image'] = $newFileName; // Borramos el archivo viejo File::delete(public_path() . '/img/slider/' . $slider->image); } else { $data['image'] = $slider->image; } $slider->update($data); return Redirect::to('homeslider'); } /** * Remove the specified resource from storage. * DELETE /homesliders/{id} * * @param int $id * @return Response */ public function destroy($id) { // } }<file_sep><?php // Composer: "fzaninotto/faker": "v1.3.0" use Faker\Factory as Faker; class NewsTableSeeder extends Seeder { public function run() { $faker = Faker::create(); foreach(range(1, 40) as $index) { $title = $faker->sentence(); $date = $faker->dateTimeBetween('-1 years'); $n = new News; $n->provincia_id = $faker->numberBetween(1, 9); $n->title = $title; $n->slug = Str::slug($title); $n->body = $faker->text(2000); $n->created_at = $date; $n->updated_at = $date; $n->save(); } } }<file_sep><?php class Ultimospartidos extends \Eloquent { protected $table = 'ultimospartidos'; protected $fillable = ['provincia_id', 'team_a', 'team_b', 'results', 'description']; public static $rules = [ 'provincia_id' => 'required', 'team_a' => 'required', 'team_b' => 'required', 'results' => 'required', 'description' => 'required', ]; public function provincia() { return $this->belongsTo('Provincia'); } }<file_sep><?php /*['only' => ['index', 'show']]*/ Route::resource('homeslider', 'HomesliderController'); Route::resource('ultimospartidos', 'UltimospartidosController'); // Novedades Route::resource('news', 'NewsController'); Route::get('{provincia}/novedades/{slug}', array('uses' => 'NewsController@showBySlug')); Route::get('/', array('as' => 'home', 'uses' => 'PageController@home')); Route::get('torneo', array('as' => 'torneo', 'uses' => 'PageController@torneo')); Route::get('fixture', array('as' => 'fixture', 'uses' => 'PageController@fixture')); Route::get('tabla', array('as' => 'tabla', 'uses' => 'PageController@tabla')); Route::get('galeria', array('as' => 'galeria', 'uses' => 'PageController@galeria')); // Contacto por provincia Route::get('{provincia}/contacto', array('as' => 'contacto', 'uses' => 'PageController@contacto')); // Provincias Route::get('buenos-aires', array('uses' => 'ProvinciaController@buenosAires')); Route::get('tucuman', array('uses' => 'ProvinciaController@tucuman')); Route::get('cordoba', array('uses' => 'ProvinciaController@cordoba')); Route::get('catamarca', array('uses' => 'ProvinciaController@catamarca')); Route::get('santiago', array('uses' => 'ProvinciaController@santiago')); Route::get('jujuy', array('uses' => 'ProvinciaController@jujuy')); Route::get('el-nacional', array('uses' => 'ProvinciaController@elNacional')); Route::get('santa-fe', array('uses' => 'ProvinciaController@santaFe')); // Login Route::get('login', array('as' => 'login', 'uses' => 'AccountController@login')); Route::get('logout', array('as' => 'logout', 'uses' => 'AccountController@logout')); Route::post('authenticate', array('uses' => 'AccountController@authenticate')); // Rutas solo para admins Route::group(array('before' => 'auth'), function() { // Dashboard Route::get('dashboard', array('as' => 'dashboard', 'uses' => 'DashboardController@index')); Route::get('user/edit', array('as' => 'user.edit', 'uses' => 'AccountController@edit')); Route::patch('user/update', array('as' => 'user.update', 'uses' => 'AccountController@update')); }); <file_sep><?php class AccountController extends BaseController { protected $layout = 'layout'; public function login() { $provincia = 'tucuman'; $this->layout->content = View::make('account.login', compact('provincia')); } public function authenticate() { $rules = array( 'username' => 'required', 'password' => '<PASSWORD>' ); $validator = Validator::make(Input::all(), $rules); if ( $validator->fails() ) { return Redirect::back()->withInput()->withErrors($validator->messages()); } else { $username = Input::get('username'); $password = Input::get('password'); if (Auth::attempt(array('username' => $username, 'password' => $password))) { return Redirect::intended('dashboard'); } else { return Redirect::back()->withInput()->withErrors('Login Failed'); } } } public function logout() { Auth::logout(); return Redirect::to('login'); } public function edit() { $provincia = 'tucuman'; $this->layout->content = View::make('account.edit', compact('provincia')); } public function update() { $rules = array('password' => 'required|confirmed'); $validator = Validator::make(Input::all(), $rules); if ( $validator->fails() ) { return Redirect::back()->withInput()->withErrors($validator->messages()); } $user = User::find(Auth::id()); $user->password = <PASSWORD>(Input::get('password')); $user->save(); return Redirect::to('dashboard')->withMessage('Su contraseña se actualizo con éxito.'); } } <file_sep><?php class UltimospartidosController extends \BaseController { protected $layout = 'layout'; /** * Display a listing of the resource. * GET /ultimospartidos * * @return Response */ public function index() { $partidos = Ultimospartidos::with('provincia')->paginate(5); $this->layout->content = View::make('ultimospartidos.index', compact('partidos')); } /** * Show the form for creating a new resource. * GET /ultimospartidos/create * * @return Response */ public function create() { $provincias = Provincia::lists('name', 'id'); $this->layout->content = View::make('ultimospartidos.create', compact('provincias')); } /** * Store a newly created resource in storage. * POST /ultimospartidos * * @return Response */ public function store() { $validator = Validator::make($data = Input::all(), Ultimospartidos::$rules); if ($validator->fails()) { return Redirect::back()->withErrors($validator)->withInput(); } Ultimospartidos::create($data); return Redirect::to('ultimospartidos'); } /** * Show the form for editing the specified resource. * GET /ultimospartidos/{id}/edit * * @param int $id * @return Response */ public function edit($id) { $partido = Ultimospartidos::find($id); $provincias = Provincia::lists('name', 'id'); $this->layout->content = View::make('ultimospartidos.edit', compact('partido', 'provincias')); } /** * Update the specified resource in storage. * PUT /ultimospartidos/{id} * * @param int $id * @return Response */ public function update($id) { $validator = Validator::make($data = Input::all(), Ultimospartidos::$rules); if ($validator->fails()) { return Redirect::back()->withErrors($validator)->withInput(); } $news = Ultimospartidos::findOrFail($id); $news->update($data); return Redirect::to('ultimospartidos'); } /** * Remove the specified resource from storage. * DELETE /ultimospartidos/{id} * * @param int $id * @return Response */ public function destroy($id) { $partido = Ultimospartidos::findOrFail($id); $partido->delete(); return Redirect::to('ultimospartidos'); } }<file_sep><?php // Composer: "fzaninotto/faker": "v1.3.0" use Faker\Factory as Faker; class HomesliderTableSeeder extends Seeder { public function run() { $faker = Faker::create(); foreach(range(1, 3) as $index) { Homeslider::create([ 'image' => 'slider'.$index.'.jpg', 'title' => $faker->sentence(), 'body' => $faker->sentence(), 'provincia_id' => $faker->numberBetween(1, 8) ]); } } }<file_sep><?php class Homeslider extends \Eloquent { protected $table = 'homeslider'; protected $fillable = ['provincia_id', 'image', 'title', 'body']; public static $rules = [ 'title' => 'required', 'body' => 'required', 'image' => 'required', ]; public static $rulesUpdate = [ 'title' => 'required', 'body' => 'required' ]; // Relacion public function provincia() { return $this->belongsTo('Provincia'); } }<file_sep><?php class PageController extends BaseController { protected $layout = 'layout'; public function home() { return View::make('home'); } public function torneo() { $this->layout->content = View::make('torneo'); } public function fixture() { $this->layout->content = View::make('fixture'); } public function tabla() { $this->layout->content = View::make('tabla'); } public function galeria() { $this->layout->content = View::make('galeria'); } public function contacto() { $provincia = Request::segment(1); $mainmenu = View::make('partials.mainmenus.'.$provincia); $this->layout->content = View::make('contacto', compact('provincia', 'mainmenu')); } }
8dc34b5f98742e9a147c1141722232e88aaa636c
[ "PHP" ]
14
PHP
juanem1/torneo-de-campeones
a34bba3146edf129cf4b7f6dad226e580020b70b
0ca9f8a18ed8c372160d0951c7164c33c865ad50
refs/heads/master
<file_sep>import React from 'react'; import Modal from 'react-bootstrap/Modal'; import Button from 'react-bootstrap/Button' ; import { useQuery } from '@apollo/react-hooks'; import gql from "graphql-tag"; function InformatonPokemon(props) { const GET_POKEMON_INFO = gql` query samplePokeAPIquery { gen3_species: pokemon_v2_pokemonspecies(where: {pokemon_v2_generation: {name: {_eq: "generation-iii"}, pokemon_v2_abilities: {}}}, order_by: {id: asc}) { name id } } ` const { data, loading, error } = useQuery(GET_POKEMON_INFO); if (loading) return <p>Loading...</p>; if (error) return <p>Error</p>; return ( <Modal {...props} size="lg" aria-labelledby="contained-modal-title-vcenter" centered > <Modal.Header closeButton> <Modal.Title id="contained-modal-title-vcenter"> More Information at Pokemon </Modal.Title> </Modal.Header> <Modal.Body> <div className="container"> {data.gen3_species.map((pokemon, index) => ( <div key={index} className="card"> <div class="card-body"> <h3>{pokemon.name}</h3> </div> </div> ))} </div> </Modal.Body> <Modal.Footer> <Button onClick={props.onHide}>Close</Button> </Modal.Footer> </Modal> ); } export default InformatonPokemon <file_sep>import React from 'react' import 'bootstrap/dist/css/bootstrap.min.css' import Pokemon from './components/Pokemon'; import { ApolloClient } from 'apollo-client'; import { InMemoryCache } from 'apollo-cache-inmemory'; import { HttpLink } from 'apollo-link-http'; import { ApolloProvider } from '@apollo/react-hooks'; function App() { const cache = new InMemoryCache(); const link = new HttpLink({ uri : 'https://beta.pokeapi.co/graphql/v1beta/' }) const client = new ApolloClient({ cache, link }) return ( <ApolloProvider client={client}> <Pokemon /> </ApolloProvider> ); } export default App; <file_sep>import React, { useState,useRef, useCallback } from 'react' import ListPokemon from '../components/ListPokemon' import InformatonPokemon from '../components/InformatonPokemon'; function Pokemon() { const [query, setQuery] = useState('') const [pageNumber, setPageNumber] = useState(1) const [modalShow, setModalShow] = React.useState(false); const { pokemons, hasMore, loading, error } = ListPokemon(query, pageNumber) const observer = useRef() const lastPokemonElementRef = useCallback(node => { if (loading) return if (observer.current) observer.current.disconnect() observer.current = new IntersectionObserver(entries => { if (entries[0].isIntersecting && hasMore) { setPageNumber(prevPageNumber => prevPageNumber + 1) } }) if (node) observer.current.observe(node) }, [loading, hasMore]) function handleSearch(e) { setQuery(e.target.value) setPageNumber(1) } return ( <div data-testid="pokemon1" className="App"> <div className="container"> <div className="row"> <div className="col-md-6"> <h1>List Pokemons</h1> <input type="text" className="form-control" value={query} onChange={handleSearch}></input> <ul className="list-group"> {pokemons.map((pokemon, index) => { if (pokemons.length === index + 1) { return <li className="list-group-item mt-4" name="name" ref={lastPokemonElementRef} key={pokemon}>{pokemon} <div className="d-flex"> <button type="button" variant="primary" onClick={() => setModalShow(true)} className="btn btn-success btn-lg ml-auto">More Information</button></div> <InformatonPokemon show={modalShow} onHide={() => setModalShow(false)} /> </li> } else { return <li className="list-group-item mt-4" key={pokemon}>{pokemon} <div className="d-flex"> <button type="button" variant="primary" onClick={() => setModalShow(true)} className="btn btn-success btn-lg ml-auto">More Information</button></div> <InformatonPokemon show={modalShow} onHide={() => setModalShow(false)} /> </li> } })} </ul> <div>{loading && 'Loading...'}</div> <div>{error && 'Error'}</div> </div> </div> </div> </div> ) } export default Pokemon <file_sep>import React from 'react' import ReactDom from 'react-dom' import {render,screen,cleanup} from '@testing-library/react' import App from '../App' afterEach(()=>{ cleanup(); }) test("renders without crashing",()=>{ const div = document.createElement('div'); ReactDom.render(<App />,div) expect(true).toBe(true); }) test("should render App component",()=>{ render(<App />) const pokemon = screen.getByTestId('pokemon1'); expect(pokemon).toBeInTheDocument(); })
b1c91087b978b5b764cdfd6f9febc6e65a991563
[ "JavaScript" ]
4
JavaScript
amirsalam/CodingExercice-Imedia24
0c0f0b9e5514f648013da519e5d214840282e4da
94a63afaea3139d8994c5f046cef799830a151fa
refs/heads/master
<repo_name>doomnuggets/scrapebin<file_sep>/scrapebin/models.py import datetime import time from active_alchemy import ActiveAlchemy from sqlalchemy.types import TypeDecorator, DateTime, Integer from scrapebin.config import cfg db = ActiveAlchemy(cfg.get('database', 'uri')) class Paste(db.Model): __tablename__ = 'tbl_paste' __primary_key__ = 'key' id = db.Column(db.String(30), primary_key=True) title = db.Column(db.String(60)) date = db.Column(db.String(30)) size = db.Column(db.String(50)) expire = db.Column(db.String(10)) user = db.Column(db.String(120)) syntax = db.Column(db.String(120)) backup_created = db.Column(db.Boolean, default=0) def __init__(self, **kwargs): self.id = kwargs.get('key') self.title = kwargs.get('title') self.date = kwargs.get('date') self.size = kwargs.get('size') self.expire = kwargs.get('expire') self.user = kwargs.get('user') self.syntax = kwargs.get('syntax') self.backup_created = kwargs.get('backup_created', False) @property def human_readable_date(self): return datetime.datetime.utcfromtimestamp(int(self.date)) db.create_all() <file_sep>/scrapebin/pastebin.py import os import requests class Pastebin(object): def scrape(self, limit=50): """Scrape the last N paste metadata from pastebin. The optional limit parameter restricts how many pastes are returned.""" scrape_url = 'https://pastebin.com/api_scraping.php?limit={}'.format(limit) scrape_response = requests.get(scrape_url) return scrape_response.json() def fetch(self, paste_id): """Download a paste by it's identifier (key).""" paste_url = 'https://pastebin.com/api_scrape_item.php?i={}'.format(paste_id) response = requests.get(paste_url) return response.content def fetch_many(self, paste_ids): """Fetch multiple pastes identified by their key.""" for paste_id in paste_ids: yield paste_id, self.fetch(paste_id) <file_sep>/scrapebin.py import os import time import argparse import scrapebin.models from scrapebin.models import Paste from scrapebin import constants from scrapebin.database import Database from scrapebin.pastebin import Pastebin def dump_pastes_to_disk(paste_iter, data_dir): def write_to_file(output_file, data): with open(output_file, 'w') as fout: fout.write(data) for paste_id, data in paste_iter: print(paste_id) paste_meta = Paste.get(str(paste_id)) output_dir = os.path.join(data_dir, paste_meta.human_readable_date.strftime('%Y-%m-%d')) output_file = os.path.join(output_dir, paste_id) try: write_to_file(output_file, data) except IOError: os.makedirs(output_dir) write_to_file(output_file, data) def keep_scraping(args): pastebin = Pastebin() database = Database() while True: while True: try: pastes = pastebin.scrape(limit=args.pastes_per_request) except ValueError: time.sleep(3) pass else: break database.dump_many(pastes) paste_ids = [paste.get('key') for paste in pastes] paste_iter = pastebin.fetch_many(paste_ids) dump_pastes_to_disk(paste_iter, args.data_dir) print('\nsleeping...\n') time.sleep(args.sleep_duration) def main(args): scrapebin.models.db.create_all() try: keep_scraping(args) except KeyboardInterrupt: pass if __name__ == '__main__': ap = argparse.ArgumentParser() ap.add_argument('-s', '--sleep-duration', default=constants.SLEEP_DURATION) ap.add_argument('-d', '--data-dir', default=constants.DATA_DIR) ap.add_argument('-p', '--pastes-per-request', default=constants.PASTES_PER_REQUEST) args = ap.parse_args() exit(main(args)) <file_sep>/config.ini [database] uri=mysql+pymysql://root:@localhost:3306/db_scrapebin?charset=utf8 <file_sep>/scrapebin/database.py from sqlalchemy.exc import IntegrityError import scrapebin.models class Database(object): def __init__(self, db=None): self.db = db or scrapebin.models.db def dump_paste(self, paste_meta): """Dump a paste's metadata into the database.""" paste = scrapebin.models.Paste(**paste_meta) self.db.session.add(paste) self.db.commit() def dump_many(self, json_data): """Dump all paste metadata from a JSON blob into the database.""" for paste in json_data: try: self.dump_paste(paste) except IntegrityError: self.db.session.rollback() <file_sep>/scrapebin/config.py import os from configparser import ConfigParser from scrapebin.constants import CONFIG_FILE def _get_config(): with open(CONFIG_FILE) as cf: config_parser = ConfigParser() config_parser.readfp(cf) return config_parser cfg = _get_config() <file_sep>/scrapebin/constants.py import os PROJECT_ROOT = os.path.join(os.path.realpath(os.path.abspath(os.path.dirname(__file__))), '..') BACKUP_DIR = os.path.join(PROJECT_ROOT, 'backup') DATA_DIR = os.path.join(PROJECT_ROOT, 'pastes') CONFIG_FILE = os.path.join(PROJECT_ROOT, 'config.ini') PASTES_PER_REQUEST = 100 SLEEP_DURATION = 120 <file_sep>/requirements.txt Active-Alchemy==1.0.0 arrow==0.12.1 backports.functools-lru-cache==1.5 certifi==2018.1.18 chardet==3.0.4 configparser==3.5.0 idna==2.6 inflection==0.3.1 Paginator==0.5.1 pg8000==1.10.2 PyMySQL==0.6.6 python-dateutil==2.7.2 requests==2.18.4 six==1.11.0 SQLAlchemy==1.2.6 SQLAlchemy-Utils==0.33.2 urllib3==1.22
276e6d4fc894a90ffbde99ae2bd9e4a36162f03b
[ "Python", "Text", "INI" ]
8
Python
doomnuggets/scrapebin
8fabe9c019646f0e1a051f609609e1f9fb7720e1
9cede77dd9911371bb386e0ea97ab800063caf51
refs/heads/master
<repo_name>niciyan/minimal-vimrc<file_sep>/install.sh set -e cd "$(dirname "$0")" cp ./.vimrc ~/.vimrc mkdir -p ~/.vim/ git clone https://github.com/scrooloose/nerdtree.git ~/.vim/nerdtree echo "\nDone"
9bea6bb17320ac0d498e9785d7cccfc0a191d419
[ "Shell" ]
1
Shell
niciyan/minimal-vimrc
13c6176ba09d996b5aa4cf00d72551ccac0f4f68
229fe44a091cdf50672388d332fb9d1bc870be21
refs/heads/master
<file_sep>import Vue from "vue"; import App from "./App.vue"; import { library } from "@fortawesome/fontawesome-svg-core"; import { faAddressCard, faAngleDown, faCode, faGraduationCap, faHome, faLaptopCode, faAngleUp } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome"; import VueI18n from "vue-i18n"; import messages from "./messages"; Vue.use(VueI18n); const i18n = new VueI18n({ locale: "en", // set locale messages // set locale messages }); library.add(faCode); library.add(faHome); library.add(faLaptopCode); library.add(faGraduationCap); library.add(faAddressCard); library.add(faAngleDown); library.add(faAngleUp); Vue.component("font-awesome-icon", FontAwesomeIcon); Vue.config.productionTip = false; new Vue({ render: h => h(App), i18n }).$mount("#app");
50b44ccc7d1d2d9877c4262b7766d097717afbbb
[ "JavaScript" ]
1
JavaScript
kruuskarl2/portfolio
daa3fe088023f2ae60c3dcf4b4e4924a34427444
0f406259da5878f5f7ec1e77a9b7432b210261b8
refs/heads/master
<file_sep>const model = require("./model"); exports.creator = async (req, res) => { const entry = await model.create(req.body); res.status(200).json({ msg: "successfully created", data: entry, }); }; exports.getAll = async (req, res) => { const entry = await model.find(); res.status(200).json({ msg: "successful in getting all", data: entry, }); }; exports.getSingle = async (req, res) => { const entry = await model.findById(req.params.id); res.status(200).json({ msg: "successful in getting a single data", data: entry, }); }; exports.updator = async (req, res) => { const entry = await model.findByIdAndUpdate(req.params.id, req.body); res.status(200).json({ msg: "successfully updated", data: entry, }); }; exports.deletor = async (req, res) => { const entry = await model.findByIdAndRemove(req.params.id, req.body); res.status(200).json({ msg: "successfully created", data: entry, }); }; <file_sep>const express = require("express"); const router = express.Router(); const { creator, getAll, getSingle, updator, deletor, } = require("./controller"); router.route("/").get(getAll).post(creator); router.route("/:id").get(getSingle).delete(deletor).patch(updator); module.exports = router; <file_sep>const cloudinary = require('cloudinary').v2; const router = require('./router'); cloudinary.config({ cloud_name: 'userapi', api_key: '951792771124655', api_secret: '<KEY>' }); module.exports = cloudinary router.post("/", middleware, async(req, res)=>{ })<file_sep>const mongoose = require("mongoose"); const model = mongoose.Schema( { name: { type: String, required: true, }, course: { type: String, required: true, }, }, { timestamps: { default: true, }, } ); module.exports = mongoose.model("schema", model); <file_sep>const express = require("express"); const port = 3000; const mongoose = require("mongoose"); const url = "mongodb://localhost:userAPI"; const router = require("./router"); const app = express(); mongoose .connect(url, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false, }) .then(() => { console.log("DB connected 🦾"); }) .catch((error) => { console.log("error while connecting to the Db"); }); app.use(express.json()); app.get("/", (req, res) => { res.send("welcome. User"); }); app.use("/api", router); app.listen(port, () => { console.log(`port ${port} is listening`); }); <file_sep>const express = require("express"); const multer = require("multer"); const path = require("path"); const model = require("./model"); const router = express.Router(); const cloudinary = require("cloudinary").v2; cloudinary.config({ cloud_name: "userapi", api_key: "951792771124655", api_secret: "<KEY>", }); const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, "./uploads"); }, filename: (req, file, cb) => { cb(null, file.originalname); }, }); const fileFilter = (req, file, cb) => { if ( file.mimetype === "image/jpeg" || file.mimetype === "image/png" || file.mimetype === "image/jpg" ) { cb(null, true); } else { cb("file format not supported"); } }; const upload = multer({ storage: storage, fileFilter, }); router.get("/", async (req, res) => { try { const newData = await model.find(); res.status(200).json({ msg: "found all", data: newData, }); } catch (error) { res.status(404).json({ msg: "error", data: error, }); } }); router.get("/:id", async (req, res) => { try { const newData = await model.findById(req.params.id); res.status(200).json({ msg: "found single", data: newData, }); } catch (error) { res.status(404).json({ msg: "error", data: error, }); } }); // router.post("/", upload.single("avatar"), async (req, res) => { // try { // const newData = await model.create({ // userName: req.body.userName, // password: req.body.password, // email: req.body.email, // avatar: req.file.path, // }); // res.status(200).json({ // msg: "created", // data: newData, // }); // } catch (error) { // res.status(404).json({ // msg: "error", // data: error, // }); // } // }); router.post("/", upload.single("avatar"), async (req, res) => { const { email } = req.body; const ifUser = await model.findOne({ email }); if (ifUser) { res.status(404).json({ msg: "user already exist", }); } const result = await cloudinary.uploader.upload(req.file.path); // console.log(result); const newData = new model({ userName: req.body.userName, password: <PASSWORD>, email: req.body.email, avatar: result.secure_url, }); try { const newUser = await newData.save(); res.json(newUser); } catch (error) { res.status(404).json({ msg: "errror", data: error, }); } }); // router.patch("/:id", async(req, res)=>{ // try{ // const newData = await model.findByIdAndUpdate(req.params.id,{ // userName: req.body.userName, // password: <PASSWORD>, // email: req.body.email, // avater: req.file.path, // admin: req.body.admin, // }) // res.status(200).json({ // msg: "found all", // data: newData // }) // }catch(error){ // res.status(404).json({ // msg: "error", // data: error // }) // } // }) router.delete("/:id", async (req, res) => { try { const newData = await model.findByIdAndRemove(req.params.id, req.body); res.status(200).json({ msg: "deleted", data: newData, }); } catch (error) { res.status(404).json({ msg: "error", data: error, }); } }); module.exports = router;
59e59c544f95f5e6b3e405a303f2aa1ba3b1237e
[ "JavaScript" ]
6
JavaScript
romanusObialasor/TransPortApi
9ba91af484b2cfd32ca195dfafa9942b0c7b80e5
ca69e2d0d6bddeda7c9ae3df24d827548755c3db
refs/heads/master
<repo_name>SparkyTS/3OX<file_sep>/main/java/com/sparkyts/connect3/MainActivity.java package com.sparkyts.connect3; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.GridLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; public class MainActivity extends AppCompatActivity { enum Player { RED, YELLOW, UNKNOWN } Player currentPlayer = Player.YELLOW; Player[] gameState = {Player.UNKNOWN,Player.UNKNOWN,Player.UNKNOWN,Player.UNKNOWN,Player.UNKNOWN,Player.UNKNOWN,Player.UNKNOWN,Player.UNKNOWN,Player.UNKNOWN}; boolean gameIsActive = true; int count = 0; int[][]winningPositions = { {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}}; public void tossInPlayer(View view, Player player){ ImageView toss = (ImageView) view; toss.setTranslationY(-400f); toss.animate().translationYBy(400f).rotationXBy(360f).setDuration(200); toss.setImageResource(player == Player.RED ? R.drawable.red : R.drawable.yellow); } public void showResult(boolean render, String msg){ LinearLayout linearLayout = findViewById(R.id.playAgainScreen); if(!render) linearLayout.setVisibility(View.INVISIBLE); else{ linearLayout.setVisibility(View.VISIBLE); TextView result = findViewById(R.id.result); result.setText(msg); } } public void dropIn(View view){ int index = Integer.parseInt(view.getTag().toString()); //if place is already filled if(gameState[index]!=Player.UNKNOWN || !gameIsActive) return; count++; //changing control to the other player if(currentPlayer==Player.YELLOW){ tossInPlayer(view, Player.RED); gameState[index] = currentPlayer = Player.RED; } else{ tossInPlayer(view, Player.YELLOW); gameState[index] = currentPlayer = Player.YELLOW; } for(int[] winningPosition : winningPositions){ if(gameState[winningPosition[0]] == gameState[winningPosition[1]] && gameState[winningPosition[1]] == gameState[winningPosition[2]] && gameState[winningPosition[0]]!=Player.UNKNOWN){ gameIsActive = false; showResult(true, currentPlayer + " Wins !"); return; } } if(gameIsActive && count==9) showResult(true, "DRAW"); } public void playAgain(View view){ showResult(false,""); count = 0; for(int i = 0 ; i < gameState.length ; i++) gameState[i] = Player.UNKNOWN; gameIsActive = true; GridLayout gridLayout = findViewById(R.id.tossGrid); for(int i = 0 ; i < gridLayout.getChildCount() ; i++) ((ImageView)gridLayout.getChildAt(i)).setImageResource(0); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }<file_sep>/README.md # 3OX My First Android App(Game), It's same as tic-tac-toe but instead of using naughts and crosses I am using coin of 2 different colors. This one I actually learned form Online Course (https://www.udemy.com/complete-android-n-developer-course/)
3feb4bce4365dbdf6a4d3b9ed5cf14f4ea498755
[ "Markdown", "Java" ]
2
Java
SparkyTS/3OX
af8b5217174ee1e486408eaf0767d28d8424bd4b
2159fdec0713cf1199939eeb177530ba43171421
refs/heads/master
<file_sep><?php /** * Helper functions * * @package Talk_Plugin * @since 0.0.4 */ define('INC_PATH', untrailingslashit( plugin_dir_path( __FILE__ ) ) ); require INC_PATH . '/php-jwt/src/BeforeValidException.php'; require INC_PATH . '/php-jwt/src/ExpiredException.php'; require INC_PATH . '/php-jwt/src/SignatureInvalidException.php'; require INC_PATH . '/php-jwt/src/JWT.php'; use \Firebase\JWT\JWT; /** * Prints an admin notice. If the message contains two %s placeholders, * the content between them will be wrapped in a link to the plugin settings page * * @param string $type 'error', 'warning', 'success'. * @param string $message Translated message text. */ function coral_talk_print_admin_notice( $type = 'error', $message = 'Coral Talk error' ) { $has_link = ( 2 === substr_count( $message, '%s' ) ); ?> <div class="notice notice-<?php echo esc_attr( $type ); ?>"> <p><?php echo ! $has_link ? esc_html( $message ) : sprintf( esc_html( $message ), '<a href="' . esc_url( admin_url( 'options-general.php?page=talk-settings' ) ) . '">', '</a>' ); ?> </p> </div> <?php } function coral_talk_generate_jwt_token() { if (!is_user_logged_in()) { return false; } $current_user = wp_get_current_user(); $payload = ['user' => []]; $payload['user']['id'] = "$current_user->ID"; $payload['user']['email'] = $current_user->user_email; $payload['user']['username'] = $current_user->user_login; $payload['user']['url'] = $current_user->user_url; $key = get_option( 'coral_talk_jwt_secret'); $jwt = JWT::encode($payload, $key, 'HS256'); return $jwt; }
a2555b53fcc5c3ff1be9d5c8a2e7e00ef7cda6b7
[ "PHP" ]
1
PHP
Trizone-media/talk-wp-plugin-jwt
f5fbbda42168f2217a109f9547c8b56ca378c689
eac47f6e49b6767da540f80942fae370a97d4a91
refs/heads/master
<repo_name>DANISHPANDITA/facebookclone<file_sep>/src/firebase.js import firebase from "firebase"; const firebaseApp = firebase.initializeApp({ apiKey: "<KEY>", authDomain: "facebookclone-5b6c6.firebaseapp.com", projectId: "facebookclone-5b6c6", storageBucket: "facebookclone-5b6c6.appspot.com", messagingSenderId: "119602589389", appId: "1:119602589389:web:e06fdfaceb9b3f1b538384", measurementId: "G-70E540W1TP", }); const db = firebaseApp.firestore(); const storage = firebaseApp.storage(); export { storage }; export default db; <file_sep>/src/Post.js import { Avatar, IconButton } from "@material-ui/core"; import { ChatBubbleRounded, MoreHorizRounded, ShareRounded, ThumbUpAltRounded, } from "@material-ui/icons"; import React from "react"; import "./Post.css"; import ReactPlayer from "react-player"; function Post({ avatar, name, post, timestamp, postText }) { if (post.includes("photo")) { return ( <div className="post"> <div className="postHeader"> <div className="leftHeader"> <Avatar className="postAvatar" src={avatar} alt="" /> <div className="postGiver"> <h3 className="nameofMan">{name}</h3> <p className="timestamp"> {new Date(timestamp?.toDate()).toTimeString().slice(0, 8)} .🌐 </p> </div> </div> <div className="rightHeader"> <IconButton> <MoreHorizRounded /> </IconButton> </div> </div> <p className="text">{postText}</p> <img src={post} alt="" /> <div className="postFooter"> <div className="footerIcon"> <ThumbUpAltRounded /> <p>Like</p> </div> <div className="footerIcon"> <ChatBubbleRounded /> <p>Comment</p> </div> <div className="footerIcon"> <ShareRounded /> <p>Share</p> </div> </div> </div> ); } else { return ( <div className="post"> <div className="postHeader"> <div className="leftHeader"> <Avatar className="postAvatar" src={avatar} alt="" /> <div className="postGiver"> <h3 className="nameofMan">{name}</h3> <p className="timestamp"> {new Date(timestamp?.toDate()).toTimeString().slice(0, 8)} .🌐 </p> </div> </div> <div className="rightHeader"> <IconButton> <MoreHorizRounded /> </IconButton> </div> </div> <p className="text">{postText}</p> <ReactPlayer controls="true" url={post} /> <div className="postFooter"> <div className="footerIcon"> <ThumbUpAltRounded /> <p>Like</p> </div> <div className="footerIcon"> <ChatBubbleRounded /> <p>Comment</p> </div> <div className="footerIcon"> <ShareRounded /> <p>Share</p> </div> </div> </div> ); } } export default Post; <file_sep>/src/Contacts.js import { Avatar } from "@material-ui/core"; import React from "react"; import "./Contacts.css"; function Contacts({ image, name }) { return ( <div className="contact"> <Avatar src={image} alt="" /> <p>{name}</p> </div> ); } export default Contacts; <file_sep>/src/App.js import { IconButton } from "@material-ui/core"; import { EditRounded } from "@material-ui/icons"; import React from "react"; import "./App.css"; import Feeds from "./Feeds"; import NavBar from "./NavBar"; import SideBar from "./SideBar"; import SideRight from "./SideRight"; function App() { return ( <div className="App"> <div className="header"> <NavBar /> </div> <div className="mainBody"> <SideBar /> <Feeds /> <SideRight /> </div> <div className="addMessageBtn"> <IconButton className="addmessage"> <EditRounded className="addMessage" /> </IconButton> </div> </div> ); } export default App; <file_sep>/src/SideBarOption.js import React from "react"; import "./SideBarOption.css"; import { Icon } from "@iconify/react"; function SideBarOption({ icon, text }) { return ( <div className="SideBarOption"> <Icon icon={icon} className="optionIcon" color="#1B86E9" height="28px" /> <h4 className="OptionName">{text}</h4> </div> ); } export default SideBarOption; <file_sep>/src/Feeds.js import React, { useState, useEffect } from "react"; import "./Feeds.css"; import Stories from "./Stories"; import { Icon } from "@iconify/react"; import bxsRightArrowCircle from "@iconify-icons/bx/bxs-right-arrow-circle"; import { Avatar, IconButton } from "@material-ui/core"; import { AddToPhotosRounded, InsertEmoticonRounded, VideoCallRounded, SendRounded, } from "@material-ui/icons"; import firebase from "firebase"; import bxsVideo from "@iconify-icons/bx/bxs-video"; import arrowRightCircle from "@iconify-icons/bi/arrow-right-circle"; import Post from "./Post"; import db, { storage } from "./firebase"; function Feeds() { const [input, setinput] = useState(""); const [video, setvideo] = useState(null); const [photo, setphoto] = useState(null); const [progress, setprogress] = useState(0); const [Posts, setPosts] = useState([]); const [roomPeople, setroomPeople] = useState([]); const [stories, setstories] = useState([]); useEffect(() => { db.collection("facebook") .doc("111") .collection("posts") .orderBy("timestamp", "desc") .onSnapshot((snapshot) => setPosts( snapshot.docs.map((doc) => ({ id: doc.id, post: doc.data(), })) ) ); }, []); useEffect(() => { db.collection("facebook") .doc("113") .collection("RoomPeople") .onSnapshot((snapshot) => setroomPeople( snapshot.docs.map((doc) => ({ id: doc.id, room: doc.data(), })) ) ); }, []); useEffect(() => { db.collection("facebook") .doc("114") .collection("stories") .onSnapshot((snapshot) => setstories( snapshot.docs.map((doc) => ({ id: doc.id, story: doc.data(), })) ) ); }, []); const handlePost = (e) => { e.preventDefault(); if (photo) { const uploadTask = storage.ref(`photo/${photo}.name}`).put(photo); uploadTask.on( "state_changed", (snapshot) => { var progress = Math.floor( (snapshot.bytesTransferred / snapshot.totalBytes) * 100 ); console.log("Upload is " + progress + "% done"); setprogress(progress); switch (snapshot.state) { case firebase.storage.TaskState.PAUSED: console.log("Upload is paused"); break; case firebase.storage.TaskState.RUNNING: console.log("Upload is running"); break; default: console.log(".."); } }, (error) => { console.log(error); }, () => { uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) => { db.collection("facebook").doc("111").collection("posts").add({ postText: input, name: "Danish", avatar: "https://scontent.fixc1-3.fna.fbcdn.net/v/t31.0-8/26678281_2124824987803851_8707096542290141456_o.jpg?_nc_cat=103&ccb=2&_nc_sid=09cbfe&_nc_ohc=e5o8hJdtXDMAX-NsImU&_nc_ht=scontent.fixc1-3.fna&oh=19e95387687adf9a518af1b508ee89c1&oe=60115F5C", timestamp: firebase.firestore.FieldValue.serverTimestamp(), post: downloadURL, }); }); } ); setinput(""); } else if (video) { const uploadTask = storage.ref(`video/${video}.name}`).put(video); uploadTask.on( "state_changed", (snapshot) => { var progress = Math.floor( (snapshot.bytesTransferred / snapshot.totalBytes) * 100 ); console.log("Upload is " + progress + "% done"); setprogress(progress); switch (snapshot.state) { case firebase.storage.TaskState.PAUSED: console.log("Upload is paused"); break; case firebase.storage.TaskState.RUNNING: console.log("Upload is running"); break; default: console.log(".."); } }, (error) => { console.log(error); }, () => { uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) => { db.collection("facebook").doc("111").collection("posts").add({ postText: input, name: "<NAME>", avatar: "https://scontent.fixc1-3.fna.fbcdn.net/v/t31.0-8/26678281_2124824987803851_8707096542290141456_o.jpg?_nc_cat=103&ccb=2&_nc_sid=09cbfe&_nc_ohc=e5o8hJdtXDMAX-NsImU&_nc_ht=scontent.fixc1-3.fna&oh=19e95387687adf9a518af1b508ee89c1&oe=60115F5C", timestamp: firebase.firestore.FieldValue.serverTimestamp(), post: downloadURL, }); }); } ); setinput(""); } }; function buildVideoSelector() { const fileSelector = document.createElement("input"); fileSelector.setAttribute("type", "file"); fileSelector.setAttribute("accept", "video/mp4, video/mkv"); return fileSelector; } const Selectvideo = (e) => { e.preventDefault(); const fileSelector = buildVideoSelector(); fileSelector.click(); fileSelector.addEventListener("change", (event) => { const file = event.target.files[0]; setvideo(file); }); }; function buildPhotoSelector() { const fileSelector = document.createElement("input"); fileSelector.setAttribute("type", "file"); fileSelector.setAttribute("accept", "image/jpg, image/png"); return fileSelector; } const Selectphoto = (e) => { e.preventDefault(); const fileSelector = buildPhotoSelector(); fileSelector.click(); fileSelector.addEventListener("change", (event) => { const file = event.target.files[0]; setphoto(file); }); }; return ( <div className="Feeds"> <div className="feedsPart"> <div className="stories"> <Stories own /> {stories.map(({ story, id }) => ( <Stories key={id} avatar={story.avatar} storyImage={story.storyImage} name={story.name} /> ))} <Icon className="moreStories" height="44px" color="white" icon={bxsRightArrowCircle} /> </div> <div className="facebookWrite"> <div className="writePart"> <Avatar src="https://scontent.fixc1-3.fna.fbcdn.net/v/t31.0-8/26678281_2124824987803851_8707096542290141456_o.jpg?_nc_cat=103&ccb=2&_nc_sid=09cbfe&_nc_ohc=LBgCGKX_f2kAX_b8vbv&_nc_ht=scontent.fixc1-3.fna&oh=a269626d5b8c3f4ab40b6bca73c837be&oe=6009765C" alt="" /> <input value={input} placeholder="What's on your Mind Happening" onChange={(e) => setinput(e.target.value)} /> <IconButton> <SendRounded onClick={handlePost} /> </IconButton> </div> <div className="fileInputs"> <div className="fileinput"> <VideoCallRounded className="fileInputIcon" /> <p onClick={Selectvideo}>Choose Video</p> </div> <div className="fileinput"> <AddToPhotosRounded className="fileInputIconPhoto" /> <p onClick={Selectphoto}>Choose Photo</p> </div> <div className="fileinput"> <InsertEmoticonRounded className="fileInputIconActivity" /> <p>Feeling/Activity</p> </div> </div> </div> <div className="rooms"> <div className="roomIcon"> <Icon icon={bxsVideo} width="35px" height="30px" color="#AE49AE" /> <p>Create Room</p> </div> {roomPeople.map(({ id, room }) => ( <Avatar key={id} src={room.avatar} alt="" /> ))} <Icon className="moreForRoom" icon={arrowRightCircle} width="40" /> </div> <div className="posts"> {Posts.map(({ id, post }) => ( <Post className="post" key={id} post={post.post} name={post.name} avatar={post.avatar} timestamp={post.timestamp} postText={post.postText} /> ))} </div> </div> </div> ); } export default Feeds; <file_sep>/src/Stories.js import { Avatar } from "@material-ui/core"; import React from "react"; import "./Stories.css"; function Stories({ own, avatar, storyImage, name }) { return ( <div className={`story ${own && "story--own"} `}> {own ? ( <div className="story--own"> <img src="https://scontent.fixc1-3.fna.fbcdn.net/v/t31.0-8/26678281_2124824987803851_8707096542290141456_o.jpg?_nc_cat=103&ccb=2&_nc_sid=09cbfe&_nc_ohc=LBgCGKX_f2kAX_b8vbv&_nc_ht=scontent.fixc1-3.fna&oh=a269626d5b8c3f4ab40b6bca73c837be&oe=6009765C" alt="" /> <p>Create a Story</p> </div> ) : ( <div className="story"> <Avatar className="storyAvatar" src={avatar} alt="" /> <img src={storyImage} alt="" /> <p>{name}</p> </div> )} </div> ); } export default Stories;
d4d33812afa2a2b7eff27e0d64275e6781453862
[ "JavaScript" ]
7
JavaScript
DANISHPANDITA/facebookclone
d165109f4e0432841759b703b55d48c4dd2010a9
1f88923b4e8cb1af0a2a781ff3a9d0056ce771c6
refs/heads/master
<repo_name>alu0100888102/MenusSaludables<file_sep>/MenusSaludables/src/menusSaludables/Plato.java /** * PRACTICA 3: Programación dinámica * * Esta clase representa un plato, guardando los datos de este (valor nutriciona, nutrientes nocivos, nombre) * * @author alu0100888102 * @version 1.0 * <NAME> * <EMAIL> */ package menusSaludables; public class Plato{ private String nombre; private int nutrientes; private int nocivos; //constructores public Plato(){ setNutrientes(Integer.MIN_VALUE); setNocivos(Integer.MAX_VALUE); setNombre(""); } public Plato(String name, int nu, int no){ setNutrientes(nu); setNocivos(no); setNombre(name); } /** * Este constructor construye el plato a partir de un string * @param linea */ public Plato (String linea){ String division[] = linea.split("\\s+"); nombre = division[0]; nutrientes = Integer.parseInt(division[1]); nocivos = Integer.parseInt(division[2]); } //setters y getters public int getNutrientes() { return nutrientes; } public void setNutrientes(int nutrientes) { this.nutrientes = nutrientes; } public int getNocivos() { return nocivos; } public void setNocivos(int nocivos) { this.nocivos = nocivos; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String toString(){ return getNombre() + ": " + getNutrientes() + " nutrientes saludables, " + getNocivos() + " nutrientes nocivos."; } } <file_sep>/MenusSaludables/src/busquedaAlimentos/Nodo.java /** * PRACTICA 3: Programación dinámica * * Nodo para el problema opcional de recogida de alimentos * * @author alu0100888102 * @version 1.0 * <NAME> * <EMAIL> */ package busquedaAlimentos; public class Nodo { private int valor; private String direccion; public Nodo(){ setValor(0); setDireccion(""); } public Nodo(int v, String s){ setValor(v); setDireccion(s); } public int getValor() { return valor; } public void setValor(int valor) { this.valor = valor; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } } <file_sep>/MenusSaludables/src/Algoritmia/Resoluciones.java /** * PRACTICA 3: Programación dinámica * * Esta es la clase que implementea los algoritmos para resolver mediante recursividad y programación dinámica el poblema de los menús saludables * * @author alu0100888102 * @version 1.0 * <NAME> * <EMAIL> */ package Algoritmia; import java.util.ArrayList; import menusSaludables.*; public class Resoluciones { private MatrizValores matriz; private Menu menu; //constructores public Resoluciones(){ menu = new Menu(); matriz = new MatrizValores(); } public Resoluciones(Menu m){ menu = m; resetMatriz(); } //setters y getters public MatrizValores getMatriz() { return matriz; } public void setMatriz(MatrizValores matriz) { this.matriz = matriz; } public Menu getMenu() { return menu; } public void setMenu(Menu menu) { this.menu = menu; } /** * Este metodo nos sirve para reiniciar la matriz antes de cada método para así evitar conflictos */ public void resetMatriz(){ matriz = new MatrizValores(menu.getPlatos().size(), menu.getNocivoUmbral()); } /** * Para resolver el problema mediante un algoritmo recursivo de complejidad 2^n * * @return */ public int solveRecursive(){ resetMatriz(); return solveRecursiveStep(menu.getPlatos(), menu.getPlatos().size(), menu.getNocivoUmbral()); } private int solveRecursiveStep(ArrayList<Plato> lista, int index, int nocivoLeft){ if(index == 0 && nocivoLeft >= 0) return 0; if(nocivoLeft < 0) return Integer.MIN_VALUE; int v1 = solveRecursiveStep(lista, index-1, nocivoLeft); int v2 = solveRecursiveStep(lista, index-1, nocivoLeft- lista.get(index-1).getNocivos())+ lista.get(index-1).getNutrientes(); menu.setNutrientesTotal(Integer.max(v1, v2)); return Integer.max(v1, v2); } /** * Para resolver el problema mediante un algoritmo de programación dinámica con enfoque top-down y complejidad nW (siendo W el umbral de nutrientes nocivos) * * @return */ public int solveTopDown(){ resetMatriz(); return solveTopDownStep(getMatriz(), menu.getPlatos(), menu.getPlatos().size(), menu.getNocivoUmbral()); } private int solveTopDownStep(MatrizValores matrix, ArrayList<Plato> list, int index, int nocivoLeft){ if(index == 0 && nocivoLeft >= 0) return 0; if(nocivoLeft < 0) return Integer.MIN_VALUE; if(matrix.getElement(index, nocivoLeft) != -1) return matrix.getElement(index, nocivoLeft); int v1 = solveTopDownStep(matrix, list, index - 1, nocivoLeft); int v2 = solveTopDownStep(matrix, list, index - 1, nocivoLeft - list.get(index-1).getNocivos()) + list.get(index-1).getNutrientes(); matrix.setElement(index, nocivoLeft, Integer.max(v1, v2)); menu.setNutrientesTotal(matrix.getElement(index, nocivoLeft)); return matrix.getElement(index, nocivoLeft); } /** * Para resolver el problema mediante un algoritmo de programación dinámica con enfoque bottom-up y complejidad nW (siendo W el umbral de nutrientes nocivos) * * @return */ public void solveBottomUp(){ resetMatriz(); solveBottomUpStep(getMatriz(), menu.getPlatos(), menu.getPlatos().size(), menu.getNocivoUmbral()); } private void solveBottomUpStep(MatrizValores matrix, ArrayList<Plato> list, int index, int nocivoLeft){ for(int i =0; i<=nocivoLeft; i++) matrix.setElement(0, i, 0); for(int i = 1; i <= index; i++ ){ for(int j =0; j<= nocivoLeft; j++){ if(list.get(i-1).getNocivos() <= j){ int v1 = matrix.getElement(i - 1, j); int v2 = matrix.getElement(i - 1, j - list.get(i-1).getNocivos()) + list.get(i-1).getNutrientes(); matrix.setElement(i, j, Integer.max(v1, v2)); menu.setNutrientesTotal(matrix.getElement(i, j)); } else{ matrix.setElement(i, j, matrix.getElement(i - 1, j)); } } } } public String printSol(){ String out = printSol(getMatriz(), menu.getPlatos(), menu.getPlatos().size(), menu.getNocivoUmbral()); out += "Valor nutricional total: " + menu.getNutrientesTotal(); return out; } public static String printSol(MatrizValores matrix, ArrayList<Plato> list, int index, int nocivoLeft){ String out = new String(); out += "Los platos que hemos incluido son:\n"; int j = nocivoLeft; int nocivos=0; for(int i = index; i > 0; i--){ if((list.get(i-1).getNocivos() <= j) && ((matrix.getElement(i-1, j-(list.get(i-1).getNocivos())) + list.get(i-1).getNutrientes()) == matrix.getElement(i, j))){ out += list.get(i-1)+"\n"; j= j-list.get(i-1).getNocivos(); nocivos += list.get(i-1).getNocivos(); } } out += "Nutrientes nocivos totales: " + nocivos +"\n"; return out; } } <file_sep>/MenusSaludables/src/Algoritmia/Main.java /** * PRACTICA 3: Programación dinámica * * Esta es la clase principal que ejecuta el programa. * * @author alu0100888102 * @version 1.0 * <NAME> * <EMAIL> */ package Algoritmia; import menusSaludables.*; import java.io.*; public class Main { public static void main(String args[]){ Menu menu = new Menu(new File(args[0])); Resoluciones res = new Resoluciones(menu); System.out.println("Recursivo: "+ res.solveRecursive()+"\n"); res.solveTopDown(); System.out.println("Top Down:\n"+ res.printSol()+"\n"); res.solveBottomUp(); System.out.println("Bottom Up:\n"+ res.printSol()+"\n"); } } <file_sep>/MenusSaludables/src/busquedaAlimentos/BuscadorAlimentos.java /** * PRACTICA 3: Programación dinámica * * Esta es la clase que plantea el problema opcional de recogida de alimentos * * @author alu0100888102 * @version 1.0 * <NAME> * <EMAIL> */ package busquedaAlimentos; import java.io.*; import menusSaludables.MatrizValores; public class BuscadorAlimentos { private MatrizValores grid; // utilizamos la matriz desarrollada para la otra parte private Matrix route; private int ancho; private int alto; // constructores public BuscadorAlimentos(){ grid = new MatrizValores(); route = new Matrix(); } public BuscadorAlimentos(File input){ try{ FileInputStream istream = new FileInputStream(input); //Construct BufferedReader from InputStreamReader BufferedReader bufferreader = new BufferedReader(new InputStreamReader(istream)); String line = null; line = bufferreader.readLine(); ancho = Integer.parseInt(line); line = bufferreader.readLine(); alto = Integer.parseInt(line); grid = new MatrizValores(alto-1, ancho-1); route = new Matrix(alto, ancho); int nline = 0; while ((line = bufferreader.readLine()) != null) { if(line.isEmpty()) continue; String division[] = line.split("\\s+"); int j=0; for(String a : division){ grid.setElement(nline, j, Integer.parseInt(a)); j++; } nline++; } bufferreader.close(); } catch(FileNotFoundException e){ System.out.println("Error en el fichero: no se encuentra " + e); System.exit(1); } catch(IOException e){ System.out.println("Error en el fichero: error de entrada/salida " + e); System.exit(1); } } //setters y getters public MatrizValores getGrid() { return grid; } public void setGrid(MatrizValores grid) { this.grid = grid; } public Matrix getRoute() { return route; } public void setRoute(Matrix route) { this.route = route; } public int getAncho() { return ancho; } public void setAncho(int ancho) { this.ancho = ancho; } public int getAlto() { return alto; } public void setAlto(int alto) { this.alto = alto; } /** * El pseudo algoritmo es el siguiente: * Empezando por el nodo del final, miras a ver cuales son los valores acumulados del nodo superior y el de la izquierda de forma recursiva. * El valor acumulado del nodo es el mayor de ambos mas el propio valor. * Se guarda en la matriz de donde "viene" el camino junto con el valor acumulado, para no tener que repetir el problema. */ public void buscador(){ buscadorStep(getAlto()-1, getAncho()-1); } private int buscadorStep(int y, int x){ if(y < 0 || x < 0) return Integer.MIN_VALUE; if(!getRoute().getElement(y,x).getDireccion().isEmpty()) return route.getElement(y,x).getValor(); int valorCasilla = getGrid().getElement(y, x); if(x == 0 && y == 0){ Nodo node = new Nodo(valorCasilla, "start"); getRoute().setElement(y, x, node); return valorCasilla; } int valorArriba = buscadorStep(y-1,x); int valorIzda = buscadorStep(y,x-1); if(valorArriba >= valorIzda){ Nodo node = new Nodo(valorArriba + valorCasilla, "up"); getRoute().setElement(y, x, node); return valorArriba + valorCasilla; } else{ Nodo node = new Nodo(valorIzda + valorCasilla, "left"); getRoute().setElement(y, x, node); return valorIzda + valorCasilla; } } /** * imprime recursivamente empezando por el final */ public String toString(){ String out = recursiveWritting(getAlto()-1, getAncho()-1); return out; } private String recursiveWritting(int y, int x){ String out = new String(); if(getRoute().getElement(y, x).getDireccion().matches("up")){ out += recursiveWritting(y-1,x) + "("+x+","+y+")"; } else if(getRoute().getElement(y, x).getDireccion().matches("left")){ out += recursiveWritting(y,x-1)+ "("+x+","+y+")"; } else if(getRoute().getElement(y, x).getDireccion().matches("start")){ out += "(0,0)"; } out += " Recogemos "+ getGrid().getElement(y, x) + " kilos, "+getRoute().getElement(y, x).getValor()+" en total. \n"; return out; } } <file_sep>/MenusSaludables/src/menusSaludables/MatrizValores.java /** * PRACTICA 3: Programación dinámica * * Esta clase guarda la matriz que emplean los algoritmos de programación dinámica para resolver el problema. * La matriz tendrá tamaño n+1 * m+1, para incluir las filas de la 0 a la N * * @author alu0100888102 * @version 1.0 * <NAME> * <EMAIL> */ package menusSaludables; import java.util.*; public class MatrizValores { private ArrayList<ArrayList<Integer>> matrix; private int numPlatos; //numero de filas private int umbral; //numero de columnas //constructores public MatrizValores(){ matrix = new ArrayList<ArrayList<Integer>>(); numPlatos = 0; umbral =0; } public MatrizValores(int num, int umb){ matrix = new ArrayList<ArrayList<Integer>>(); numPlatos = num; umbral = umb; for(int i = 0; i <= numPlatos; i++) newRow(); } public MatrizValores(ArrayList<ArrayList<Integer>> n){ matrix = new ArrayList<ArrayList<Integer>>(); setMatrix(n); numPlatos = n.size(); umbral = n.get(0).size(); } //getters y setters public int getNumPlatos() { return numPlatos; } public void setNumPlatos(int numPlatos) { this.numPlatos = numPlatos; } public int getUmbral() { return umbral; } public void setUmbral(int umbral) { this.umbral = umbral; } public ArrayList<ArrayList<Integer>> getMatrix() { return matrix; } public void setMatrix(ArrayList<ArrayList<Integer>> matrix) { this.matrix = matrix; } public ArrayList<Integer> getRow(int n){ if(n < 0 || matrix.size() < n) throw new IllegalArgumentException("La fila "+ n + " no existe."); return matrix.get(n); } public void setRow(int n, ArrayList<Integer> row){ if(n < 0 || matrix.size() < n) throw new IllegalArgumentException("La fila "+ n +" no existe."); if(row.size()> umbral+1) throw new IllegalArgumentException("Fila demasiado grande"); if(row.size()<umbral+1) for(int i =row.size(); i < umbral+1; i++) row.add(-1); matrix.set(n, row); } public int getElement(int row, int index){ if(index < 0 || index > umbral) throw new IllegalArgumentException("Elemento invalido"); ArrayList<Integer> temp = getRow(row); return temp.get(index); } public void setElement(int row, int index, int value){ if(index < 0 || index > umbral) throw new IllegalArgumentException("Elemento invalido"); ArrayList<Integer> temp = getRow(row); temp.set(index, value); setRow(row, temp); } public void addRow(ArrayList<Integer> row){ if(row.size()>umbral+1) throw new IllegalArgumentException("Fila demasiado grande"); if(row.size()<umbral) for(int i =row.size(); i <= umbral; i++) row.add(-1); matrix.add(row); } public void newRow(){ ArrayList<Integer> temp = new ArrayList<Integer>(); for(int i =0; i <= umbral; i++) temp.add(-1); addRow(temp); } public String toString(){ String out = new String(); for(ArrayList<Integer> row : getMatrix()){ for(Integer i : row){ out += i+" "; } out += "\n"; } return out; } }
35c64d89307e0ff85ef02716769943cb877a5239
[ "Java" ]
6
Java
alu0100888102/MenusSaludables
96066d2643e7a34f3c6ba446d219ef2956dcd216
519613c2a7b422ab71c6c1fffac7dfe1aa510159
refs/heads/master
<file_sep>Program ini merupakan scanner bahasa buatan "Sanca" yang bertujuan mengubah source menjadi token-token. scanner ini menggunakan metode divide and conquer. untuk contoh bahasa Sanca ada di file "input_file" -Cara penggunaan : masukan perintah ini di terminal ./main [nama/lokasifile] masukan perintah ini di terminal ./main [nama/lokasifile] -o [nama/lokasifile] <file_sep>#include <iostream> #include <string.h> #include <fstream> using namespace std; struct node{ int id; int stat; string data; string token; node *next; }; node *awl_smpl_alp = NULL; node *awl_smpl_dgt = NULL; node *awl_smpl_sym = NULL; int talp=0,tdgt=0,tsym=0; node *gbng_p1 = NULL; node *gbng_p2 = NULL; //Devide void inpt_list_alp(int c,string data){ node *temp, *temp2; temp = new node; temp->id = c; temp->stat = 0; temp->data = data; temp->next = NULL; if (awl_smpl_alp == NULL) awl_smpl_alp = temp; else{ temp2 = awl_smpl_alp; while (temp2->next != NULL) temp2 = temp2->next; temp2->next = temp; } } void inpt_list_dgt(int c,string data){ node *temp, *temp2; temp = new node; temp->id = c; temp->stat = 0; temp->data = data; temp->next = NULL; if (awl_smpl_dgt == NULL) awl_smpl_dgt = temp; else{ temp2 = awl_smpl_dgt; while (temp2->next != NULL) temp2 = temp2->next; temp2->next = temp; } } void inpt_list_sym(int c,string data){ node *temp, *temp2; temp = new node; temp->id = c; temp->stat = 0; temp->data = data; temp->next = NULL; if (awl_smpl_sym == NULL) awl_smpl_sym = temp; else{ temp2 = awl_smpl_sym; while (temp2->next != NULL) temp2 = temp2->next; temp2->next = temp; } } void bagikat(char filebuk[]){ char kar,h_kar; int c=0; string teks; string digit; ifstream file(filebuk); if(file.is_open()){ while(true!=(file.eof())){ file >> noskipws >> kar; if(isalpha(kar)){ int k=1; do{ if(k==1){teks = kar;}; if(k==0){teks += kar;}; file >> noskipws >> kar; k = 0; }while(isalnum(kar)); c = c+1; talp = talp + 1; inpt_list_alp(c,teks); teks = '\0'; } if(isdigit(kar)){ int k=1; do{ if(k==1){digit = kar;}; if(k==0){digit += kar;}; file >> noskipws >> kar; k = 0; }while((isdigit(kar))||(kar=='.')); c = c+1; tdgt = tdgt + 1; inpt_list_dgt(c,digit); digit = '\0'; } if(kar == '"'){ teks = kar; do{ file >> noskipws >> kar; teks += kar; if(kar=='"'){ kar='\n'; } }while(kar !='\n'); c = c+1; tsym=tsym+1; inpt_list_sym(c,teks); teks = '\0'; } if(kar == '\''){ teks = kar; do{ file >> noskipws >> kar; teks += kar; if(kar=='\''){ kar='\n'; } }while(kar !='\n'); c = c+1; tsym=tsym+1; inpt_list_sym(c,teks); teks = '\0'; } if(kar =='#'){ while(kar!='\n'){ file >> noskipws >> kar; } } if( (kar==';')||(kar==':')||(kar=='(')|| (kar==')')||(kar=='+')||(kar=='-')|| (kar=='/')||(kar=='\\')||(kar=='%')|| (kar=='>')||(kar=='<')||(kar=='=')|| (kar=='*')||(kar=='.')||(kar==',')|| (kar=='{')||(kar=='}')||(kar=='[')|| (kar==']')||(kar=='!') ){ c = c+1; teks = kar; tsym=tsym+1; inpt_list_sym(c,teks); teks='\0'; } } file.close(); } } string alp_konver(string bantu){ int c; bool ketemu; string keyword[20] ={"var","mulai","selesai","int","string","program" ,"float","tulis","baca","jika","maka","atau" ,"ketika","lakukan","untuk","sampai","prosedur" ,"kembalikan","fungsi"}; c =0; ketemu = false; while(c!=19){ if(keyword[c]==bantu){ return "T_key_" + keyword[c]; ketemu = true; c = 18; } c++; } if(ketemu==false){ return "T_ident"; } } string dgt_konver(string bantu){ int k,g; bool ketemu; g = 0; ketemu = false; k = bantu.length(); while(g!=k){ if(bantu[g]=='.'){ ketemu = true; return "T_float"; g = k; }else{ g++; } } if(ketemu==false){ return "T_int"; } } string sym_konver(string bantu){ int k,g; if(bantu[0]=='"'){ if(bantu[bantu.length()-1]=='"'){ return "T_string"; }else{ return "Error"; } }else if(bantu[0]=='\''){ if(bantu.length()>4){ return "T_char"; }else{ return "Error"; } }else if(bantu==";"){return "T_tikom";} else if(bantu==":"){return "T_tikdua";} else if(bantu=="("){return "T_bukrung";} else if(bantu==")"){return "T_tuprung";} else if(bantu=="+"){return "T_tambah";} else if(bantu=="-"){return "T_garbaw";} else if(bantu=="/"){return "T_mirkir";} else if(bantu=="\\"){return "T_mirkan";} else if(bantu=="%"){return "T_persen";} else if(bantu==">"){return "T_lebdar";} else if(bantu=="<"){return "T_kurdar";} else if(bantu=="="){return "T_samdeng";} else if(bantu=="*"){return "T_kali";} else if(bantu=="."){return "T_titik";} else if(bantu==","){return "T_koma";} else if(bantu=="{"){return "T_bukraw";} else if(bantu=="}"){return "T_tupraw";} else if(bantu=="["){return "T_bukkurkot";} else if(bantu=="]"){return "T_tupkurkot";} else if(bantu=="!"){return "T_seru";} } void merge(node *a1, node *a2, node *a,int kat){ node *kiri; node *kanan; node *temp, *temp2; kiri = a1; kanan = a2; do{ int ada=0; if(kiri==NULL){ //masukan semua data yang ada di kanan; do{ temp = new node; temp->id = kanan->id; temp->data = kanan->data; if(kanan->stat == 0){ kanan->stat = 1; if(kat==1){ temp->token = alp_konver(kanan->data); }else if(kat==2){ temp->token = dgt_konver(kanan->data); } else if(kat==3){ temp->token = sym_konver(kanan->data); } }else{ temp->token = kanan->token; } temp->next = NULL; if (a == NULL) a = temp; else{ temp2 = a; while (temp2->next != NULL) temp2 = temp2->next; temp2->next = temp; } kanan = kanan->next; }while(kanan!=NULL); }else if(kanan==NULL){ //masukan semua data yang ada di kiri; do{ temp = new node; temp->id = kiri->id; temp->data = kiri->data; if(kiri->stat == 0){ kiri->stat = 1; if(kat==1){ temp->token = alp_konver(kiri->data); }else if(kat==2){ temp->token = dgt_konver(kiri->data); } else if(kat==3){ temp->token = sym_konver(kiri->data); } }else{ temp->token = kiri->token; } temp->next = NULL; if (a == NULL) a = temp; else{ temp2 = a; while (temp2->next != NULL) temp2 = temp2->next; temp2->next = temp; } kiri = kiri->next; }while(kiri!=NULL); }else if(kiri->id < kanan->id){ //inputkirikelist temp = new node; temp->id = kiri->id; temp->data = kiri->data; if(kiri->stat == 0){ kiri->stat = 1; if(kat==1){ temp->token = alp_konver(kiri->data); }else if(kat==2){ temp->token = dgt_konver(kiri->data); } else if(kat==3){ temp->token = sym_konver(kiri->data); } }else{ temp->token = kiri->token; } temp->next = NULL; if (a == NULL) a = temp; else{ temp2 = a; while (temp2->next != NULL){ temp2 = temp2->next; if(temp->id == temp2->id){ ada = 1; temp2->next=NULL; } } if(ada==0){ temp2->next = temp; } } kiri = kiri->next; }else if(kiri->id > kanan->id){ //inputkananlist temp = new node; temp->id = kanan->id; temp->data = kanan->data; if(kanan->stat == 0){ kanan->stat = 1; if(kat==1){ temp->token = alp_konver(kanan->data); }else if(kat==2){ temp->token = dgt_konver(kanan->data); } else if(kat==3){ temp->token = sym_konver(kanan->data); } }else{ temp->token = kanan->token; } temp->next = NULL; if (a == NULL) a = temp; else{ temp2 = a; while (temp2->next != NULL){ temp2 = temp2->next; if(temp->id == temp2->id){ ada = 1; temp2->next=NULL; } } if(ada==0){ temp2->next = temp; } } kanan = kanan->next; } }while((kanan!=NULL)||(kiri!=NULL)); } void sort1(){ node *kiri; node *kanan; node *temp, *temp2; kiri = awl_smpl_alp; kanan = awl_smpl_dgt; do{ if(kiri==NULL){ //masukan semua data yang ada di kanan; do{ temp = new node; temp->id = kanan->id; temp->data = kanan->data; temp->token = kanan->token; temp->next = NULL; if (gbng_p1 == NULL) gbng_p1 = temp; else{ temp2 = gbng_p1; while (temp2->next != NULL) temp2 = temp2->next; temp2->next = temp; } kanan = kanan->next; }while(kanan!=NULL); }else if(kanan==NULL){ //masukan semua data yang ada di kiri; do{ temp = new node; temp->id = kiri->id; temp->data = kiri->data; temp->token = kiri->token; temp->next = NULL; if (gbng_p1 == NULL) gbng_p1 = temp; else{ temp2 = gbng_p1; while (temp2->next != NULL) temp2 = temp2->next; temp2->next = temp; } kiri = kiri->next; }while(kiri!=NULL); }else if(kiri->id < kanan->id){ //inputkirikelist temp = new node; temp->id = kiri->id; temp->data = kiri->data; temp->token = kiri->token; temp->next = NULL; if (gbng_p1 == NULL) gbng_p1 = temp; else{ temp2 = gbng_p1; while (temp2->next != NULL) temp2 = temp2->next; temp2->next = temp; } kiri = kiri->next; }else if(kiri->id > kanan->id){ //inputkananlist temp = new node; temp->id = kanan->id; temp->data = kanan->data; temp->token = kanan->token; temp->next = NULL; if (gbng_p1 == NULL) gbng_p1 = temp; else{ temp2 = gbng_p1; while (temp2->next != NULL) temp2 = temp2->next; temp2->next = temp; } kanan = kanan->next; } }while((kanan!=NULL)||(kiri!=NULL)); } void sort2(){ node *kiri; node *kanan; node *temp, *temp2; kiri = awl_smpl_sym; kanan = gbng_p1; do{ if(kiri==NULL){ //masukan semua data yang ada di kanan; do{ temp = new node; temp->id = kanan->id; temp->data = kanan->data; temp->token = kanan->token; temp->next = NULL; if (gbng_p2 == NULL) gbng_p2 = temp; else{ temp2 = gbng_p2; while (temp2->next != NULL) temp2 = temp2->next; temp2->next = temp; } kanan = kanan->next; }while(kanan!=NULL); }else if(kanan==NULL){ //masukan semua data yang ada di kiri; do{ temp = new node; temp->id = kiri->id; temp->data = kiri->data; temp->token = kiri->token; temp->next = NULL; if (gbng_p2 == NULL) gbng_p2 = temp; else{ temp2 = gbng_p2; while (temp2->next != NULL) temp2 = temp2->next; temp2->next = temp; } kiri = kiri->next; }while(kiri!=NULL); }else if(kiri->id < kanan->id){ //inputkirikelist temp = new node; temp->id = kiri->id; temp->data = kiri->data; temp->token = kiri->token; temp->next = NULL; if (gbng_p2 == NULL) gbng_p2 = temp; else{ temp2 = gbng_p2; while (temp2->next != NULL) temp2 = temp2->next; temp2->next = temp; } kiri = kiri->next; }else if(kiri->id > kanan->id){ //inputkananlist temp = new node; temp->id = kanan->id; temp->data = kanan->data; temp->token = kanan->token; temp->next = NULL; if (gbng_p2 == NULL) gbng_p2 = temp; else{ temp2 = gbng_p2; while (temp2->next != NULL) temp2 = temp2->next; temp2->next = temp; } kanan = kanan->next; } }while((kanan!=NULL)||(kiri!=NULL)); } void tampil_list(char filebuk[]){ node *bantu; cout << "Hasil Scan file "<< filebuk << " : "<<endl; cout << "no || lexeme || Token"<<endl<<endl; if (gbng_p2 == NULL) cout << "Data Kosong"; else{ bantu = gbng_p2; do{ cout << bantu->id << " "; cout << bantu->data << " "; cout << bantu->token<<endl; bantu = bantu->next; }while (bantu != NULL); } } void simpan(char filebuk[],char filesim[]){ node *bantu; ofstream file; file.open(filesim); file << "Hasil Scan file "<< filebuk << " : "<<endl; file << "no || lexeme || Token"<<endl<<endl; if (gbng_p2 == NULL) file << "Data Kosong"; else{ bantu = gbng_p2; do{ file << bantu->id << " "; file << bantu->data << " "; file << bantu->token<<endl; bantu = bantu->next; }while (bantu != NULL); } file.close(); } void hapus(){ node *bantu; if(awl_smpl_alp->next == NULL){ delete awl_smpl_alp; }else{ do{ bantu = awl_smpl_alp; awl_smpl_alp = awl_smpl_alp->next; delete bantu; }while(awl_smpl_alp !=NULL); } if(awl_smpl_dgt->next == NULL){ delete awl_smpl_dgt; }else{ do{ bantu = awl_smpl_dgt; awl_smpl_dgt = awl_smpl_dgt->next; delete bantu; }while(awl_smpl_dgt !=NULL); } if(awl_smpl_sym->next == NULL){ delete awl_smpl_dgt; }else{ do{ bantu = awl_smpl_sym; awl_smpl_sym = awl_smpl_sym->next; delete bantu; }while(awl_smpl_sym !=NULL); } if(gbng_p1->next == NULL){ delete gbng_p1; }else{ do{ bantu = gbng_p1; gbng_p1 = gbng_p1->next; delete bantu; }while(gbng_p1 !=NULL); } if(gbng_p2->next == NULL){ delete gbng_p2; }else{ do{ bantu = gbng_p2; gbng_p2 = gbng_p2->next; delete bantu; }while(gbng_p2 !=NULL); } } void dandc(node *a,int n,int kat){ if(n>1){ //-----------------Bagi Menjadi dua bagian---------------- int n1,n2,i; n1= n/2; n2= n1+1; node *a1 = NULL,*a2=NULL,*kiri,*kanan,*temp,*temp2,*bantu; kiri = a; kanan = a; for(i=1;i<=n2;i++){ kanan = kanan->next; } //bagi menjadi dua; for(i=1;i<=n1;i++){ temp = new node; temp->id = kiri->id; temp->data = kiri->data; temp->token = kiri->token; temp->next = NULL; if (a1 == NULL) a1 = temp; else{ temp2 = a1; while (temp2->next != NULL) temp2 = temp2->next; temp2->next = temp; } kiri = kiri->next; } kanan = kiri; do{ temp = new node; temp->id = kanan->id; temp->data = kanan->data; temp->token = kanan->token; temp->next = NULL; if (a2 == NULL) a2 = temp; else{ temp2 = a2; while (temp2->next != NULL) temp2 = temp2->next; temp2->next = temp; } kanan = kanan->next; }while(kanan!=NULL); //-----------------------------------------------------------------end dari pembagian menjadi dua dandc(a1,n1,kat); dandc(a2,n2-1,kat); merge(a1,a2,a,kat); //Simpan hasilnya ke simpul yang sesuai if(kat==1){ awl_smpl_alp = a; }else if(kat==2){ awl_smpl_dgt = a; }else if(kat==3){ awl_smpl_sym = a; } } } int main(int argc, char* argv[]) { if(argc>1){ char filesim[41],filebuk[41]; strcpy(filebuk,argv[1]); //Membagi menjadi tiga kategori bagikat(filebuk); //Divide and Conquer dandc(awl_smpl_alp,talp,1); dandc(awl_smpl_dgt,tdgt,2); dandc(awl_smpl_sym,tsym,3); //Memgabung ketiga kategori sort1(); sort2(); if(argc >= 3){ if((strcmp(argv[2],"-o"))==0){ strcpy(filesim,argv[3]); simpan(filebuk,filesim); } }else{ tampil_list(filebuk); } hapus(); }else{ cout << "Error :Tidak ada file input"<<endl; cout << "Scanner dihentikan. "<<endl; } return 0; }
5b65949bccb3bf5adc1dcc8283b33d03ab1e532f
[ "Markdown", "C++" ]
2
Markdown
Divewing/scannersanca
c68979aa2aae2688e14baaf47d0adb3cfff3a3d1
d6fc855e09a4e26cc3e210fecdd84c0f5224768a
refs/heads/master
<repo_name>metaphori/Paper-2019-PMC-SmartCam<file_sep>/build.gradle.kts plugins { id("org.danilopianini.gradle-latex") version "0.1.1" } latex { "elsarticle-template" { bib = "mybibfile.bib" } }
51b1085ea6868f15128c1cadc613a14fa75bed45
[ "Kotlin" ]
1
Kotlin
metaphori/Paper-2019-PMC-SmartCam
6dd3ec99c0bdfebb304f7f76ee680ab1f5f57a5b
b647a6b1070193d94f4444e24050c7aa23076f00
refs/heads/main
<repo_name>Joshua1171/ejemplos_practicos<file_sep>/src/main/resources/application.properties spring.datasource.url=jdbc:mysql://localhost:3306/db_microservicios_examenes?serverTimezone=America/Mexico_City&useSSL=false&allowPublicKeyRetrieval=true spring.datasource.username=pruebas spring.datasource.password=<PASSWORD> spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect spring.jpa.generate-ddl=true logging.level.org.hibernate.SQL=debug<file_sep>/src/main/java/com/ejemplos/relaciones/entities/Respuesta1.java package com.ejemplos.relaciones.entities; import lombok.Data; import java.util.Date; @Data public class Respuesta1 { private Date email; private int numControl; private int edad; } <file_sep>/src/main/java/com/ejemplos/relaciones/controllers/AlumnoController.java package com.ejemplos.relaciones.controllers; import com.ejemplos.relaciones.entities.Alumno; import com.ejemplos.relaciones.entities.Respuesta1; import com.ejemplos.relaciones.services.IAlumnoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import static org.springframework.http.HttpStatus.*; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @RestController public class AlumnoController { @Autowired private IAlumnoService alumnoService; @GetMapping("/alumnos") public List<Alumno> index(){ return alumnoService.findAll(); } @GetMapping("/alumnos/filtro2/{terminaCon}/{mayorQue}/{iniciaCon}") public List<Respuesta1> filtro2(@PathVariable String terminaCon,@PathVariable int mayorQue,@PathVariable String iniciaCon){ return alumnoService.findRespuesta1(terminaCon,mayorQue,iniciaCon); } @PostMapping("/alumnos") public ResponseEntity<?> crear(@Valid @RequestBody Alumno alumno, BindingResult result){ Alumno a =null; Map<String,Object> response = new HashMap<>(); if (result.hasErrors()){ /* * List<String> errors = new ArrayList<>(); for(FieldError err: result.getFieldErrors()) { errors.add("El campo '" + err.getField() +"' "+ err.getDefaultMessage()); } * */ List<String> errors=result.getFieldErrors() .stream() .map(err -> "El campo "+err.getField()+""+err.getDefaultMessage()) .collect(Collectors.toList()); response.put("errors",errors); return new ResponseEntity<Map<String,Object>>(response, BAD_REQUEST); } try{ a=alumnoService.save(alumno); }catch (DataAccessException e){ response.put("mensaje","No se pudo insertar en la base de datos"); response.put("error",e.getMessage().concat(":").concat(e.getMostSpecificCause().getMessage())); new ResponseEntity<Map<String,Object>>(response,INTERNAL_SERVER_ERROR); } response.put("mensaje","El cliente fue creado satisfactoriamente"); response.put("alumnos",a); return new ResponseEntity<Map<String,Object>>(response,CREATED); } } <file_sep>/src/main/java/com/ejemplos/relaciones/services/AlumnoServiceImpl.java package com.ejemplos.relaciones.services; import com.ejemplos.relaciones.dao.IAlumnoDao; import com.ejemplos.relaciones.entities.Alumno; import com.ejemplos.relaciones.entities.Respuesta1; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service public class AlumnoServiceImpl implements IAlumnoService{ @Autowired private IAlumnoDao alumnoDao; @Override @Transactional(readOnly=true) public List<Alumno> findAll() { return (List<Alumno>) alumnoDao.findAll(); } @Override @Transactional public Alumno save(Alumno a) { return alumnoDao.save(a); } @Override @Transactional(readOnly = true) public List<Respuesta1> findRespuesta1(String terminacion,int mayorQue,String empiezaCon) { return alumnoDao.findByEmailEndingWithAndEdadGreaterThanAndNumControlStartsWith(terminacion, mayorQue, empiezaCon); } @Override public List<Respuesta1> findRespuesta2(String a, int b, int c) { return alumnoDao.filtrar(a,b,c); } } <file_sep>/README.md "# ejemplos_practicos"
e935de5956bed5cff693675cb3138dc1f5b60f60
[ "Markdown", "Java", "INI" ]
5
INI
Joshua1171/ejemplos_practicos
f9d6c5dc2ccda68b7f1d92678535645d21b271cc
9d384af748d3962204d7f436c15055da83f99942
refs/heads/master
<repo_name>EMMYMP20e/Sem-Sistemas-Operativos<file_sep>/03-AlgortimoDePlanificacionFCFS/SimuladorProcesoPorLotes/BCP.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 SimuladorProcesoPorLotes { public partial class BCP : Form { List<Proceso> list; public BCP(List<Proceso> n) { InitializeComponent(); list = n; Despliega(); } private void Despliega() { int retorno; string respuesta; //list.Sort((x, y) => x.getID().CompareTo(y.getID())); foreach (Proceso p in list) { listBox1.Items.Add("\tID: " + p.getID()+"\n"); if (p.getError()) { respuesta = "Error"; } else { respuesta = p.getRespuesta().ToString(); } listBox1.Items.Add(" Ope: " + p.getOpe()+ " = "+respuesta+"\n"); listBox1.Items.Add(" TME: " + p.getTime() + "\n"); listBox1.Items.Add(" T de Llegada: " + p.getLlegada() + "\n"); listBox1.Items.Add(" T de Finalización: " + p.getFinalizacion() + "\n"); retorno = p.getFinalizacion() - p.getLlegada(); listBox1.Items.Add(" T de Retorno: " + retorno + "\n"); listBox1.Items.Add(" T de Servicio: " + p.getServicio() + "\n"); listBox1.Items.Add(" T de Espera: " + (retorno-p.getServicio())+ "\n"); listBox1.Items.Add(" T de Respuesta: " + p.getRespuesta() + "\n"); listBox1.Items.Add("---------------------------------------------"); } } } } <file_sep>/04-AlgortimoDePlanificacionFCFSContinuacion/SimuladorProcesoPorLotes/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 SimuladorProcesoPorLotes { public partial class Form1 : Form { int cantidad; public Form1() { InitializeComponent(); this.ControlBox = false; } public int getCantidad() { return cantidad; } private void IngresaButton_Click(object sender, EventArgs e) { cantidad = (int)cantidadBox.Value; this.Hide(); } } } <file_sep>/03-AlgortimoDePlanificacionFCFS/SimuladorProcesoPorLotes/Proceso.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SimuladorProcesoPorLotes { public class Proceso { string id; string ope; int time; int result; int transcurrido; int llegada; int finalizacion; int respuesta; int bloqueado; int servicio; bool error=false; bool primera = false; public Proceso() {} public Proceso(string i, string o, int t) { id = i; ope = o; time = t; transcurrido = 0; llegada = 0; finalizacion = 0; respuesta = 0; bloqueado = -1; servicio = 0; } public void setPrimera() { primera = true; } public bool getPrimera() { return primera; } public void setServicio(int s) { servicio = s; } public int getServicio() { return servicio; } public void setError() { error = true; } public bool getError() { return error; } public string getID() { return id; } public string getOpe() { return ope; } public int getTime() { return time; } public int getResult() { return result; } public int getTrans() { return transcurrido; } public int getLlegada() { return llegada; } public int getFinalizacion() { return finalizacion; } public int getRespuesta() { return respuesta; } public int getBloqueado() { return bloqueado; } public void setTrans(int t) { transcurrido = t; } public void setLlegada(int l) { llegada = l; } public void setFinalizacion(int f) { finalizacion = f; } public void setRespuesta(int r) { respuesta = r; } public void setBloqueado(int b) { bloqueado = b; } public bool esValido() { int state = 0; bool error = false; foreach (char c in ope) { switch (state) { case 0: if (c >= '0' && c <= '9') { state = 1; } else { error = true; } break; case 1: if (c >= '0' && c <= '9') { state = 1; } else if (c == '+' || c == '-' || c == '*') { state = 2; } else if (c == '%' || c == '/') { state = 3; } else { error = true; } break; case 2: if (c >= '0' && c <= '9') { state = 4; } else { error = true; } break; case 3: if (c >= '1' && c <= '9') { state = 4; } else { error = true; } break; case 4: if (c >= '0' && c <= '9') { state = 4; } else { error = true; } break; } if (error) { return false; } } if (state == 4) { return true; } else { return false; } return true; } public void resolver() { string uno="", dos=""; int one, two; bool sim=false,sum = false, res = false, mul = false, div = false, mod = false; foreach (char c in ope) { switch (c) { case '+': sum = true; sim = true; break; case '-': res = true; sim = true; break; case '*': mul = true; sim = true; break; case '/': div = true; sim = true; break; case '%': mod = true; sim = true; break; default: if (sim) { dos += c; } else { uno += c; } break; } } one = Int32.Parse(uno); two = Int32.Parse(dos); if (sum) { result = one + two; } if (res) { result = one - two; } if (mul) { result = one * two; } if (div) { result = one / two; } if (mod) { result = one % two; } } } } <file_sep>/04-AlgortimoDePlanificacionFCFSContinuacion/SimuladorProcesoPorLotes/main.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.Threading; namespace SimuladorProcesoPorLotes { public partial class main : Form { List<Proceso> lista; int cantidad; Thread hilo; bool interrupt = false, error = false, pause = false, nuevo = false, mostrar=false; Random r = new Random(DateTime.Now.Millisecond); string[] opes = { "+", "-", "/", "%", "*" }; int rest; List<Proceso> aux; List<Proceso> bloqueados; List<Proceso> terminados; List<Proceso> all; public main() { inicio(); procesos(); InitializeComponent(); CheckForIllegalCrossThreadCalls = false; hilo = new Thread(new ThreadStart(procesado)); simulacion(); } private void inicio() { Form1 form = new Form1(); form.ShowDialog(); cantidad = form.getCantidad(); } private void procesos() { Random r = new Random(DateTime.Now.Millisecond); string[] opes = { "+", "-", "/", "%", "*" }; lista = new List<Proceso>(); ; for (int i = 0; i < cantidad; i++) { agregaProceso(i); } } public void agregaProceso(int i) { int rName = r.Next(0, 9); int rUno = r.Next(0, 9); int rDos = r.Next(1, 9); int rOpe = r.Next(0, 4); int rTime = r.Next(7, 18); string ecuacion = rUno.ToString() + opes[rOpe] + rDos.ToString(); Proceso proc = new Proceso((i + 1).ToString(), ecuacion, rTime); lista.Add(proc); } public void simulacion() { hilo.Start(); } public void recolecta() { all = new List<Proceso>(); bool first = true; all.Clear(); foreach (Proceso p in aux) { p.setEstado(0); all.Add(p); } foreach (Proceso p in lista) { if (!first) { p.setEstado(1); all.Add(p); } first = false; } foreach (Proceso p in bloqueados) { p.setEstado(2); all.Add(p); } foreach (Proceso p in terminados) { p.setEstado(3); all.Add(p); } } public void procesado() { int cont = 0; int sig = 0; rest = cantidad; int total, restante; int conto = 0; int tme; int tres = 0; int servicioTranscurrido = 0; labelContador.Text = sig.ToString(); labelPendientes.Text = cantidad.ToString(); BCP bcp; aux = new List<Proceso>(); bloqueados = new List<Proceso>(); terminados = new List<Proceso>(); Proceso p; Proceso nP; while (lista.Count != 0) { p = lista.First<Proceso>(); listBox1.Items.Add(p.getID() + "\t\t" + p.getTime() + "\t" + p.getTrans()); p.setLlegada(conto); aux.Add(p); cont++; tres++; rest--; labelPendientes.Text = rest.ToString(); while (tres == 3 || cont == cantidad) { while (aux.Count == 0) { labelID.Text = ""; labelOpe.Text = ""; labelTme.Text = ""; labelTt.Text = ""; labelTr.Text = ""; this.Refresh(); if (!pause) { Thread.Sleep(700); } else { try { Thread.Sleep(Timeout.Infinite); } catch (ThreadInterruptedException) { } /*if (mostrar) { mostrar = false; recolecta(); bcp = new BCP(all); bcp.ShowDialog(); }*/ } if (bloqueados.Count > 0) { listBox3.Items.Clear(); int cDelete = 0; foreach (Proceso b in bloqueados) { b.setBloqueado(b.getBloqueado() + 1); b.setEspera(b.getEspera() + 1); if (b.getBloqueado() < 10) { listBox3.Items.Add(b.getID() + "\t\t" + b.getBloqueado()); } else { listBox1.Items.Add(b.getID() + "\t\t" + b.getTime() + "\t" + b.getTrans()); b.setBloqueado(-1); aux.Add(b); cDelete++; } } for (int k = 0; k < cDelete; k++) { bloqueados.RemoveAt(k); } } conto++; labelContador.Text = conto.ToString(); if (nuevo) { if (tres == 3) { //rest++; labelPendientes.Text = rest.ToString(); } else { nP = lista.Last<Proceso>(); listBox1.Items.Add(nP.getID() + "\t\t" + nP.getTime() + "\t" + nP.getTrans()); nP.setLlegada(conto); aux.Add(nP); tres++; cont++; rest--; lista.RemoveAt(lista.Count - 1); } nuevo = false; } } listBox1.Items.RemoveAt(0); Proceso n = aux.First<Proceso>(); if (!n.getPrimera()) { n.setRespuesta(conto - n.getLlegada()); n.setPrimera(); } labelID.Text = n.getID(); labelOpe.Text = n.getOpe(); labelTme.Text = n.getTime().ToString(); total = 0; restante = n.getTime(); labelTt.Text = n.getTrans().ToString(); labelTr.Text = (n.getTime() - n.getTrans()).ToString(); int i = n.getTrans(); if (n.getTrans() != 0) { total = i; restante = n.getTime() - i; } tme = n.getTime(); if (aux.Count == 0) { tme = 10; } for (int j = i; j < tme; j++) { n.setServicio(total+1); foreach (Proceso d in aux) { if (d.getID() != n.getID()) { d.setEspera(d.getEspera() + 1); } } if (!pause) { Thread.Sleep(800); } else { try { Thread.Sleep(Timeout.Infinite); } catch (ThreadInterruptedException) { } /*if (mostrar) { mostrar = false; recolecta(); bcp = new BCP(all); bcp.ShowDialog(); }*/ } //this.Refresh(); total++; restante--; labelTt.Text = total.ToString(); labelTr.Text = restante.ToString(); conto++; labelContador.Text = conto.ToString(); if (error) { servicioTranscurrido = j; j = n.getTime(); } if (interrupt) { n.setTrans(total); j = n.getTime(); bloqueados.Add(n); } if (nuevo) { if (tres == 3) { //rest++; labelPendientes.Text = rest.ToString(); } else { nP = lista.Last<Proceso>(); listBox1.Items.Add(nP.getID() + "\t\t" + nP.getTime() + "\t" + nP.getTrans()); nP.setLlegada(conto); aux.Add(nP); tres++; cont++; rest--; lista.RemoveAt(lista.Count-1); } nuevo = false; } if (bloqueados.Count > 0) { listBox3.Items.Clear(); int cDelete = 0; foreach (Proceso b in bloqueados) { b.setBloqueado(b.getBloqueado() + 1); b.setEspera(b.getEspera() + 1); if (b.getBloqueado() < 10) { listBox3.Items.Add(b.getID() + "\t\t" + b.getBloqueado()); } else { listBox1.Items.Add(b.getID() + "\t\t" + b.getTime() + "\t" + b.getTrans()); b.setBloqueado(-1); aux.Add(b); cDelete++; } } for (int k = 0; k < cDelete; k++) { bloqueados.RemoveAt(k); } } if (bloqueados.Count == 3 || (bloqueados.Count + listBox2.Items.Count) == cantidad) { labelID.Text = ""; labelOpe.Text = ""; labelTme.Text = ""; labelTt.Text = ""; labelTr.Text = ""; } } if (interrupt) { interrupt = false; } else { if (error) { if (bloqueados.Count != 3 && (bloqueados.Count + listBox2.Items.Count) != cantidad) { listBox2.Items.Add(n.getID() + " \t" + n.getOpe() + "\t\tError"); tres--; error = false; n.setFinalizacion(conto); n.setError(); n.setServicio(servicioTranscurrido); n.setRespuesta(n.getRespuesta() + 1); terminados.Add(n); } } else { tres--; n.setFinalizacion(conto); n.setServicio(n.getTime()); n.resolver(); terminados.Add(n); listBox2.Items.Add(n.getID() + " \t" + n.getOpe() + "\t\t" + n.getResult().ToString()); } } sig++; aux.RemoveAt(0); if (listBox2.Items.Count == cantidad) { break; } } lista.RemoveAt(0); } labelID.Text = ""; labelOpe.Text = ""; labelTme.Text = ""; labelTt.Text = ""; labelTr.Text = ""; all.Clear(); foreach (Proceso v in terminados) { v.setEstado(3); all.Add(v); } bcp = new BCP(terminados); bcp.ShowDialog(); } private void main_KeyPress(object sender, KeyPressEventArgs e) { char c; BCP bcp; c = e.KeyChar; switch (c) { case 'e': error = true; break; case 'i': interrupt = true; break; case 'p': pause = true; break; case 'n': nuevo = true; agregaProceso(cantidad); cantidad++; rest++; break; case 'c': if (pause) { hilo.Interrupt(); } pause = false; error = false; interrupt = false; break; case 't': pause = true; /*while (hilo.ThreadState!=ThreadState.WaitSleepJoin) { Console.WriteLine("g"); }*/ recolecta(); bcp = new BCP(all); bcp.ShowDialog(); break; } } } } <file_sep>/05-RoundRobin/SimuladorProcesoPorLotes/BCP.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 SimuladorProcesoPorLotes { public partial class BCP : Form { List<Proceso> list; public BCP(List<Proceso> n) { InitializeComponent(); Rectangle r = Screen.FromPoint(this.Location).WorkingArea; //int x = r.Left + (r.Width - this.Width) / 2; int x = r.Right-this.Width; int y = r.Top +(r.Height-this.Height)/2; this.Location = new Point(x, y); list = n; Despliega(); } private void Despliega() { int retorno=0; string respuesta; foreach (Proceso p in list) { listBox1.Items.Add("\tID: " + p.getID() + "\n"); /*if (p.getTime() == p.getServicio()) { p.setEstado(3); }*/ switch (p.getEstado()) { case 0: listBox1.Items.Add("Estado: En Sistema\n"); listBox1.Items.Add(" Ope: " + p.getOpe() + "\n"); listBox1.Items.Add(" T de Llegada: " + p.getLlegada() + "\n"); listBox1.Items.Add(" T de Espera: " + p.getEspera() + "\n"); listBox1.Items.Add(" T de Servicio: " + p.getServicio() + "\n"); listBox1.Items.Add(" T Restante en CPU: " + (p.getTime() - p.getServicio()) + "\n"); listBox1.Items.Add(" T de Respuesta: " + p.getRespuesta() + "\n"); listBox1.Items.Add(" TME: " + p.getTime() + "\n"); break; case 1: listBox1.Items.Add("Estado: Nuevo\n"); listBox1.Items.Add(" Ope: " + p.getOpe() + "\n"); break; case 2: listBox1.Items.Add("Estado: Bloqueado\n"); listBox1.Items.Add(" Ope: " + p.getOpe() + "\n"); listBox1.Items.Add(" T de Llegada: " + p.getLlegada() + "\n"); listBox1.Items.Add(" T de Espera: " + p.getEspera() + "\n"); listBox1.Items.Add(" T de Servicio: " + p.getServicio() + "\n"); listBox1.Items.Add(" T Restante en CPU: " + (p.getTime() - p.getServicio()) + "\n"); listBox1.Items.Add(" T Restante Bloqueado: " + (9 - p.getBloqueado()) + "\n"); listBox1.Items.Add(" T de Respuesta: " + p.getRespuesta() + "\n"); listBox1.Items.Add(" TME: " + p.getTime() + "\n"); break; case 3: if (p.getError()) { respuesta = "Error"; } else { respuesta = p.getResult().ToString(); } listBox1.Items.Add("Estado: Terminado\n"); listBox1.Items.Add(" Ope: " + p.getOpe() + " = " + respuesta + "\n"); listBox1.Items.Add(" TME: " + p.getTime() + "\n"); listBox1.Items.Add(" T de Llegada: " + p.getLlegada() + "\n"); listBox1.Items.Add(" T de Finalización: " + p.getFinalizacion() + "\n"); retorno = p.getFinalizacion() - p.getLlegada(); listBox1.Items.Add(" T de Retorno: " + retorno + "\n"); listBox1.Items.Add(" T de Servicio: " + p.getServicio() + "\n"); listBox1.Items.Add(" T de Espera: " + (retorno-p.getServicio()) + "\n"); listBox1.Items.Add(" T de Respuesta: " + p.getRespuesta() + "\n"); break; } listBox1.Items.Add("---------------------------------------------"); } } } } <file_sep>/01-SimuladorProcesoPorLotes/SimuladorProcesoPorLotes/Form2.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 SimuladorProcesoPorLotes { public partial class Form2 : Form { List<Proceso> list; public Form2(List<Proceso> nueva) { InitializeComponent(); this.ControlBox = false; list = nueva; } private void InputButton_Click(object sender, EventArgs e) { Proceso actual = new Proceso(textNombre.Text, textID.Text, textOpe.Text, (int)textTime.Value); foreach (Proceso a in list) { if (a.getID() == actual.getID()) { MessageBox.Show("ID no válido"); return; } } if (!actual.esValido()) { MessageBox.Show("Operación no válida"); } else if (textNombre.Text == "") { MessageBox.Show("Error: Nombre vacío"); } else if (textID.Text == "") { MessageBox.Show("Error: ID vacío"); } else { list.Add(actual); this.Hide(); } } } } <file_sep>/01-SimuladorProcesoPorLotes/SimuladorProcesoPorLotes/main.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.Threading; namespace SimuladorProcesoPorLotes { public partial class main : Form { List<Proceso> lista; int cantidad; public main() { inicio(); procesos(); InitializeComponent(); } private void inicio() { Form1 form = new Form1(); form.ShowDialog(); cantidad = form.getCantidad(); } private void procesos() { lista= new List<Proceso>(); ; for (int i = 0; i < cantidad; i++) { Form2 form = new Form2(lista); form.ShowDialog(); } } public void simulacion() { int cont = 0; int sig = 0; int rest = cantidad/3; int total, restante; int lote = 1; int conto = 0; labelContador.Text = sig.ToString(); /*if (cantidad % 3 != 0) { rest++; }*/ labelPendientes.Text = rest.ToString(); List<Proceso> aux = new List<Proceso>(); foreach (Proceso p in lista) { listBox1.Items.Add(p.getName() +"\t\t"+ p.getTime()); aux.Add(p); cont++; if ((cont % 3) == 0|| cont == cantidad) { foreach (Proceso n in aux) { labelNombre.Text = n.getName(); labelID.Text = n.getID(); labelOpe.Text = n.getOpe(); labelTme.Text = n.getTime().ToString(); total = 0; restante = n.getTime(); labelTt.Text = "0"; labelTr.Text = n.getTime().ToString(); for (int i = 0; i < n.getTime(); i++) { this.Refresh(); Thread.Sleep(1200); total++; conto++; restante--; labelTt.Text = total.ToString(); labelTr.Text = restante.ToString(); labelContador.Text = conto.ToString(); } listBox1.Items.RemoveAt(0); n.resolver(); listBox2.Items.Add(n.getID() + " \t" + n.getOpe() + "=" + n.getResult().ToString() + "\t\t "+ lote.ToString()); sig++; } lote++; rest--; if (rest == -1) { rest = 0; } listBox2.Items.Add("-------------------------------------------------"); labelPendientes.Text = rest.ToString(); aux.Clear(); } } MessageBox.Show("Fin de Simulación"); } } } <file_sep>/02-MultiprogrmacionPorLotes/SimuladorProcesoPorLotes/main.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.Threading; namespace SimuladorProcesoPorLotes { public partial class main : Form { List<Proceso> lista; int cantidad; Thread hilo; bool interrupt=false, error=false, pause=false; public main() { inicio(); procesos(); InitializeComponent(); CheckForIllegalCrossThreadCalls = false; hilo = new Thread(new ThreadStart(procesado)); simulacion(); } private void inicio() { Form1 form = new Form1(); form.ShowDialog(); cantidad = form.getCantidad(); } private void procesos() { Random r = new Random(DateTime.Now.Millisecond); string[] names = { "Miguel", "Edgar", "Marco", "Carlos", "Ulises", "Julio", "Hugo", "Saul", "Luis", "Juan" }; string[] opes = { "+", "-", "/", "%", "*" }; lista= new List<Proceso>(); ; for (int i = 0; i < cantidad; i++) { int rName= r.Next(0, 9); int rUno = r.Next(0, 9); int rDos = r.Next(1, 9); int rOpe = r.Next(0, 4); int rTime = r.Next(7, 18); string ecuacion = rUno.ToString() + opes[rOpe] + rDos.ToString(); Proceso proc = new Proceso(names[rName],(i+1).ToString(),ecuacion,rTime); lista.Add(proc); } } public void simulacion() { hilo.Start(); } public void procesado() { int cont = 0; int sig = 0; int rest = cantidad/3; int total, restante; int lote = 1; int conto = 0; labelContador.Text = sig.ToString(); labelPendientes.Text = rest.ToString(); List<Proceso> aux = new List<Proceso>(); List<Proceso> aux2 = new List<Proceso>(); foreach (Proceso p in lista) { listBox1.Items.Add(p.getID() +"\t\t"+ p.getTime()+"\t"+p.getTrans()); aux.Add(p); cont++; if ((cont % 3) == 0 || cont == cantidad) { while(aux.Count>0) { Proceso n = aux.First<Proceso>(); labelNombre.Text = n.getName(); labelID.Text = n.getID(); labelOpe.Text = n.getOpe(); labelTme.Text = n.getTime().ToString(); total = 0; restante = n.getTime(); labelTt.Text = n.getTrans().ToString(); labelTr.Text = (n.getTime()-n.getTrans()).ToString(); int i = n.getTrans(); if (n.getTrans() != 0) { total = i; restante = n.getTime() - i; } for (int j=i; j < n.getTime(); j++) { this.Refresh(); if (!pause) { Thread.Sleep(700); } else { try { Thread.Sleep(Timeout.Infinite); } catch (ThreadInterruptedException) {} } total++; conto++; restante--; labelTt.Text = total.ToString(); labelTr.Text = restante.ToString(); labelContador.Text = conto.ToString(); if (error) { j = n.getTime(); } if (interrupt) { n.setTrans(total); j = n.getTime(); listBox1.Items.Add(n.getID() + "\t\t" + n.getTime() + "\t" + n.getTrans()); aux.Add(n); } } listBox1.Items.RemoveAt(0); if (interrupt) { interrupt = false; } else { if (error) { listBox2.Items.Add(n.getID() + " \t" + n.getOpe() + "\t\tError"); error = false; } else { n.resolver(); listBox2.Items.Add(n.getID() + " \t" + n.getOpe() + "\t\t" + n.getResult().ToString()); } } sig++; aux.RemoveAt(0); } lote++; rest--; if (rest == -1) { rest = 0; } listBox2.Items.Add("-----------------------------------------------------"); labelPendientes.Text = rest.ToString(); aux.Clear(); } } MessageBox.Show("Fin de Simulación"); } private void main_KeyPress(object sender, KeyPressEventArgs e) { char c; c = e.KeyChar; switch (c) { case 'e': error = true; break; case 'i': interrupt = true; break; case 'p': pause = true; break; case 'c': if (pause) { hilo.Interrupt(); } pause = false; error = false; interrupt = false; break; } } } } <file_sep>/06-ProductorConsumidor/06-ProductorConsumidor/Main.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.Threading; namespace _06_ProductorConsumidor { public partial class Main : Form { List<Label> labels; Thread hilo; Random r = new Random(DateTime.Now.Millisecond); int punteroProducir = 0; int punteroConsumir = 0; public Main() { InitializeComponent(); this.ControlBox = false; inicio(); CheckForIllegalCrossThreadCalls = false; hilo = new Thread(new ThreadStart(procesos)); hilo.Start(); } public void inicio() { labels = new List<Label>(); labels.Add(l1); labels.Add(l2); labels.Add(l3); labels.Add(l4); labels.Add(l5); labels.Add(l6); labels.Add(l7); labels.Add(l8); labels.Add(l9); labels.Add(l10); labels.Add(l11); labels.Add(l12); labels.Add(l13); labels.Add(l14); labels.Add(l15); labels.Add(l16); labels.Add(l17); labels.Add(l18); labels.Add(l19); labels.Add(l20); labels.Add(l21); labels.Add(l22); labels.Add(l23); labels.Add(l24); labels.Add(l25); labels.Add(l26); labels.Add(l27); labels.Add(l28); labels.Add(l29); labels.Add(l30); labels.Add(l31); labels.Add(l32); labels.Add(l33); labels.Add(l34); labels.Add(l35); foreach (Label l in labels) { l.Text = " "; } labelProductor.Text = "Dormido"; labelConsumidor.Text = "Dormido"; } public void procesos() { while (true) { int rP = r.Next(0, 2); if (rP == 0) { labelProductor.Text = "Intentando Ingresar"; producir(); labelProductor.Text = "Dormido"; } else { labelConsumidor.Text = "Intentando Ingresar"; consumir(); labelConsumidor.Text = "Dormido"; } } } public void consumir() { int rP = r.Next(4, 9); int anterior = punteroConsumir; for (int i = 0; i < rP; i++) { if (punteroConsumir == 35) { punteroConsumir = 0; } if (anterior == 35) { anterior = 0; } if (labels.ElementAt<Label>(punteroConsumir).Text == " ") { labels.ElementAt<Label>(anterior).Text = " "; return; } labels.ElementAt<Label>(anterior).Text = " "; labels.ElementAt<Label>(punteroConsumir).Text = "C☼"; Thread.Sleep(800); labelConsumidor.Text = "Trabajando"; anterior = punteroConsumir; punteroConsumir++; } labels.ElementAt<Label>(anterior).Text = " "; } public void producir() { int rP = r.Next(4, 9); int anterior=punteroProducir; for (int i = 0; i < rP; i++) { if (punteroProducir == 35) { punteroProducir = 0; } if (anterior == 35) { anterior = 0; } if (labels.ElementAt<Label>(punteroProducir).Text == "☼") { labels.ElementAt<Label>(anterior).Text = "☼"; return; } labels.ElementAt<Label>(anterior).Text = "☼"; labels.ElementAt<Label>(punteroProducir).Text="P☼"; Thread.Sleep(800); labelProductor.Text = "Trabajando"; anterior = punteroProducir; punteroProducir++; } labels.ElementAt<Label>(anterior).Text = "☼"; } private void Main_KeyPress(object sender, KeyPressEventArgs e) { char c; c = e.KeyChar; Console.WriteLine(c); if (c== (char)27) { hilo.Abort(); this.Dispose(); } } } } <file_sep>/README.md # Sem-Sistemas-Operativos Actividades de Seminario de Sistemas Operativos
72bba4d7effd8f8417c6e812f8f615eebf42bfde
[ "Markdown", "C#" ]
10
C#
EMMYMP20e/Sem-Sistemas-Operativos
2a5e4a722cb93ef9a38559b5cc10309d9238159c
b3c75bcb30da3203442a19f660ed9ff6266c1605
refs/heads/master
<file_sep>sass-classnames =========== [![Version](http://img.shields.io/npm/v/@helioscompanies/sass-classnames.svg)](https://www.npmjs.org/package/@helioscompanies/sass-classnames) [Sass](https://sass-lang.com/) implementation of [classnames](https://www.npmjs.org/package/classnames). Install with [npm](https://www.npmjs.com/) or [Yarn](https://yarnpkg.com/): npm: ```sh npm install @helioscompanies/sass-classnames ``` Yarn (note that `yarn add` automatically saves the package to the `dependencies` in `package.json`): ```sh yarn add @helioscompanies/sass-classnames ``` ## Usage The `class-names` function takes any number of arguments which can be a `string`, `list`, `arglist` or `map` (other types are ignored). ```scss @debug class-names(foo, (bar: true), (baz, ted)); // .foo.bar.baz.ted ``` ### Keywords The `class-names` function supports any number of [keywords](https://sass-lang.com/documentation/functions/map#keywords). If the value associated with a given keyword is falsy (is equal to `false`, `null`, `0` or an empty string), that keyword won't be included in the output. ```scss @debug class-names($foo: false, $bar: null, $baz: 0, $ted: ''); // null @debug class-names($foo: true, $bar: 1, $bar: non-empty-string, $ted: #fff); // .foo.bar.baz.ted ``` ### Maps If the value associated with a given key is falsy, that key won't be included in the output. ```scss @debug class-names((foo: false, bar: null, baz: 0, ted: '')); // null @debug class-names((foo: true)); // .foo @debug class-names((foo: true, bar: true)); // .foo.bar @debug class-names((foo: true), (bar: true)); // .foo.bar ``` ### Strings The `string` argument `foo` (or `'foo'` or `"foo"`) is short for `(foo: true)`. ```scss @debug class-names(foo, bar); // .foo.bar @debug class-names("foo", "bar"); // .foo.bar @debug class-names('foo', 'bar'); // .foo.bar ``` ### Lists Lists will be recursively flattened as per the rules above: ```scss @debug class-names(a, (b, (c: true, d: false))); // .a.b.c ``` Real-world example: ```scss @import "node-modules/@helioscompanies/sass-classnames/index"; #{ class-names(message) } { color: #000; } #{ class-names(message, error) } { color: red; } // .message { color: #000 } // .message.error { color: red } ``` ## License The sass-classnames package is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT).<file_sep>const path = require('path'); const sassTrue = require('sass-true'); const sass = require('sass'); const file = path.resolve(__dirname, 'class-names.spec.scss'); const includePaths = [__dirname, path.resolve(__dirname, '../src')]; describe('node-sass', () => { sassTrue.runSass({ file, includePaths }, { describe, it }); }); describe('dart-sass', () => { sassTrue.runSass({ file, includePaths }, { sass, describe, it }); });
6c99d2f366bf6cc0d744c493e4ce4985fac557ac
[ "Markdown", "JavaScript" ]
2
Markdown
alexander-shipilov/sass-classnames
6e8cab7f9095f0bde785a8ba73c1e30d4476e30b
df63e416689cf1776de325b560f9c09460c2572a
refs/heads/master
<repo_name>VillzVic/Clean-Architecture<file_sep>/core/src/main/java/com/vic/villz/core/app/providers/DataProvider.kt package com.vic.villz.core.app.providers interface DataProvider<T> { //asynchronous fun requestData(callback: (items:T) -> Unit) //synchronous fun requestData() : T = throw NotImplementedError() //throw this error so any existing implementations of this interface will still compile }<file_sep>/topartists/src/main/java/com/vic/villz/topartists/di/topartists/DatabaseModule.kt package com.vic.villz.topartists.di.topartists import android.app.Application import androidx.room.Room import com.vic.villz.core.app.providers.DataMapper import com.vic.villz.core.app.providers.DataPersister import com.vic.villz.topartists.database.* import com.vic.villz.topartists.entities.Artist import dagger.Module import dagger.Provides @Module object DatabaseModule { @Provides @JvmStatic internal fun provideDatabase(context: Application): TopArtistsDatabase = Room.databaseBuilder(context, TopArtistsDatabase::class.java, "top-artists").build() @Provides @JvmStatic internal fun providesTopArtistsDao(database: TopArtistsDatabase) = database.topArtistsDao() @Provides @JvmStatic internal fun providesTopArtistsMapper(): DataMapper<Triple<Int, Artist, Long>, Pair<DbArtist, Collection<DbImage>>> = DatabaseTopArtistsMapper() @Provides @JvmStatic internal fun providesDatabasePersister( dao: TopArtistsDao, mapper: DataMapper<Triple<Int, Artist, Long>, Pair<DbArtist, Collection<DbImage>>> ): DataPersister<List<Artist>> = DatabaseTopArtistsPersister(dao, mapper) }<file_sep>/app/src/main/java/com/vic/villz/artists/di/ActivitiesBuildersModule.kt package com.vic.villz.artists.di import com.vic.villz.artists.MuseleeActivity import dagger.Module import dagger.android.ContributesAndroidInjector @Module abstract class ActivitiesBuildersModule { @ContributesAndroidInjector abstract fun contributeMuseleeActivity(): MuseleeActivity }<file_sep>/topartists/src/main/java/com/vic/villz/topartists/di/topartists/EntitiesModule.kt package com.vic.villz.topartists.di.topartists import com.vic.villz.core.app.providers.DataPersister import com.vic.villz.core.app.providers.DataProvider import com.vic.villz.core.app.providers.UpdateScheduler import com.vic.villz.topartists.di.topartists.TopArtistsModule import com.vic.villz.topartists.entities.Artist import com.vic.villz.topartists.entities.TopArtistsRepository import com.vic.villz.topartists.entities.TopArtistsState import dagger.Module import dagger.Provides import javax.inject.Named @Module object EntitiesModule { @Provides @Named(TopArtistsModule.ENTITIES) @JvmStatic internal fun providesTopArtistsRepository( persistence: DataPersister<List<Artist>>, @Named(TopArtistsModule.NETWORK) networkProvider: DataProvider<TopArtistsState>, scheduler: UpdateScheduler<Artist> ): DataProvider<TopArtistsState> = TopArtistsRepository(persistence, networkProvider, scheduler) }<file_sep>/dependencies.gradle ext { androidMinSdkVersion = 19 androidTargetSdkVersion = 28 androidCompileSdkVersion = 28 androidBuildToolsVersion = '3.4.1' jetpackVersion = '1.1.0-alpha01' constraintLayoutVersion = '2.0.0-alpha3' kotlinVersion = '1.3.31' ktxVersion = '1.1.0-alpha03' daggerVersion = '2.24' junit4Version = '4.13-beta-1' buildPlugins = [ androidGradlePlugin: "com.android.tools.build:gradle:$androidBuildToolsVersion", kotlinGradlePlugin : "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" ] libraries = [ kotlinStdLib : "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion", appCompat : "androidx.appcompat:appcompat:$jetpackVersion", constraintLayout: "androidx.constraintlayout:constraintlayout:$constraintLayoutVersion", ktxCore : "androidx.core:core-ktx:$ktxVersion", dagger : "com.google.dagger:dagger:$daggerVersion", daggerAndroid: "com.google.dagger:dagger-android:$daggerVersion", daggerSupportAndroid : "com.google.dagger:dagger-android-support:$daggerVersion", daggerCompiler : "com.google.dagger:dagger-compiler:$daggerVersion", daggerAndroidCompiler: "com.google.dagger:dagger-android-processor:$daggerVersion", ] testLibraries = [ junit4: "junit:junit:$junit4Version", ] projectModules = [ core : project(':core'), topartists: project(':topartists') ] }<file_sep>/app/src/main/java/com/vic/villz/artists/MuseleeApplication.kt package com.vic.villz.artists import android.app.Application import androidx.work.Configuration import androidx.work.WorkManager import com.vic.villz.artists.di.DaggerAppComponent import com.vic.villz.core.app.work.DaggerWorkerFactory import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.HasAndroidInjector import javax.inject.Inject class MuseleeApplication : Application(), HasAndroidInjector{ @Inject lateinit var androidInjector: DispatchingAndroidInjector<Any> @Inject lateinit var workerFactory: DaggerWorkerFactory override fun onCreate() { super.onCreate() DaggerAppComponent.builder().application(this).build().inject(this) WorkManager.initialize( this, Configuration.Builder() .setWorkerFactory(workerFactory) .build() ) } override fun androidInjector() = androidInjector }<file_sep>/topartists/src/main/java/com/vic/villz/topartists/viewmodels/TopArtistsViewModel.kt package com.vic.villz.topartists.viewmodels import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.vic.villz.core.app.connectivity.ConnectivityLiveData import com.vic.villz.core.app.providers.DataProvider import com.vic.villz.topartists.di.topartists.TopArtistsModule import com.vic.villz.topartists.entities.TopArtistsState import com.vic.villz.topartists.ui.TopArtistsViewState import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject import javax.inject.Named class TopArtistsViewModel @Inject constructor( @Named(TopArtistsModule.ENTITIES) private val topArtistsProvider: DataProvider<TopArtistsState>, val connectivityLiveData: ConnectivityLiveData ): ViewModel(){ private val mutableLiveData: MutableLiveData<TopArtistsViewState> = MutableLiveData() val topArtistsViewState:LiveData<TopArtistsViewState> get() = mutableLiveData init { load() } fun load() = viewModelScope.launch { withContext(Dispatchers.IO){ topArtistsProvider.requestData { artistsState -> update(artistsState) } } } private fun update(artistsState: TopArtistsState) = viewModelScope.launch { withContext(Dispatchers.Main) { mutableLiveData.value = when (artistsState) { TopArtistsState.Loading -> TopArtistsViewState.InProgress is TopArtistsState.Error -> TopArtistsViewState.ShowError(artistsState.message) is TopArtistsState.Success -> TopArtistsViewState.ShowTopArtists(artistsState.artists) } } } } <file_sep>/topartists/build.gradle.kts import org.jetbrains.kotlin.gradle.dsl.KotlinJvmOptions plugins { id(BuildPlugins.androidLibrary) id(BuildPlugins.kotlinAndroid) id(BuildPlugins.kotlinAndroidExtensions) id(BuildPlugins.kotlinKapt) id(BuildPlugins.detekt) version(BuildPlugins.Versions.detekt) } android { compileSdkVersion(AndroidSdk.compile) defaultConfig { minSdkVersion(AndroidSdk.min) targetSdkVersion(AndroidSdk.target) versionCode = 1 versionName ="1.0" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } buildTypes { getByName("release") { isMinifyEnabled = false proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") } } compileOptions { targetCompatibility = JavaVersion.VERSION_1_8 sourceCompatibility = JavaVersion.VERSION_1_8 } (kotlinOptions as KotlinJvmOptions).apply { jvmTarget = JavaVersion.VERSION_1_8.toString() } } dependencies { // implementation fileTree(org.gradle.internal.impldep.bsh.commands.dir: 'libs', include: ['*.jar']) implementation(project(ProjectModules.core)) implementation(Libraries.appCompat) implementation(Libraries.appCompat) implementation(Libraries.ktxCore) implementation(Libraries.constraintLayout) implementation(Libraries.dagger) implementation(Libraries.daggerAndroid) implementation(Libraries.daggerSupportAndroid) implementation(Libraries.legacySupport) implementation(Libraries.glide) implementation(Libraries.lifecycle) implementation(Libraries.archLifecycle) implementation(Libraries.coroutinesCore) implementation(Libraries.coroutinesAndroid) implementation(Libraries.designLibary) implementation(Libraries.lifecycleViewModel) implementation(Libraries.workVersion) api(Libraries.archRoomRuntime) kapt(Libraries.archRoomCompiler) api(Libraries.retrofit) implementation(Libraries.retrofitMoshi) kapt(Libraries.daggerCompiler) kapt(Libraries.daggerAndroidCompiler) kapt(Libraries.glideCompiler) testImplementation(TestLibraries.junit4) androidTestImplementation(TestLibraries.testRunner) androidTestImplementation(TestLibraries.espresso) implementation(Libraries.ktxCore) implementation((Libraries.kotlinStdLib)) } repositories { mavenCentral() } <file_sep>/core/src/main/java/com/vic/villz/core/app/di/CoreDataModule.kt package com.vic.villz.core.app.di import dagger.Module @Module object CoreDataModule { //provide database module here, then each other module can have a datamodule that provides specific Daos and has entities etc. }<file_sep>/topartists/src/main/java/com/vic/villz/topartists/di/topartists/TopArtistsModule.kt package com.vic.villz.topartists.di.topartists import androidx.lifecycle.ViewModel import com.vic.villz.core.app.di.BaseViewModule import com.vic.villz.core.app.di.ViewModelKey import com.vic.villz.core.app.di.WorkerKey import com.vic.villz.core.app.work.DaggerWorkerFactory import com.vic.villz.topartists.schedulers.TopArtistsUpdateWorker import com.vic.villz.topartists.ui.TopArtistsFragment import com.vic.villz.topartists.viewmodels.TopArtistsViewModel import dagger.Binds import dagger.Module import dagger.android.ContributesAndroidInjector import dagger.multibindings.IntoMap @Module(includes = [ DatabaseModule::class, NetworkModule::class, BaseViewModule::class, EntitiesModule::class, SchedulerModule::class, LastFmTopArtistsModule::class]) abstract class TopArtistsModule { companion object { const val ENTITIES = "ENTITIES" const val NETWORK = "NETWORK" } @ContributesAndroidInjector abstract fun contributeTopFragment(): TopArtistsFragment @Binds @IntoMap @ViewModelKey(TopArtistsViewModel::class) abstract fun bindChartsViewModel(viewModel: TopArtistsViewModel): ViewModel //makes TopArtistsViewModel available to the ViewModelFactory that we created in the Core module @Binds @IntoMap @WorkerKey(TopArtistsUpdateWorker::class) abstract fun bindTopArtistsUpdateWorker(factory: TopArtistsUpdateWorker.Factory): DaggerWorkerFactory.ChildWorkerFactory }<file_sep>/topartists/src/main/java/com/vic/villz/topartists/net/LastFmTopArtistsProvider.kt package com.vic.villz.topartists.net import com.vic.villz.core.app.ConnectivityChecker import com.vic.villz.core.app.providers.DataMapper import com.vic.villz.core.app.providers.DataProvider import com.vic.villz.topartists.entities.Artist import com.vic.villz.topartists.entities.TopArtistsState import okhttp3.internal.http.HttpDate import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.concurrent.TimeUnit //I can do this in my repository and add inject to the constructors(the datamapper will be listArtistDatamapaer) class LastFmTopArtistsProvider( private val topArtistsApi: LastFmTopArtistsApi, private val connectivityChecker: ConnectivityChecker, private val mapper: DataMapper<Pair<LastFmArtists, Long>, List<Artist>> ): DataProvider<TopArtistsState>{ override fun requestData(callback: (topArtists: TopArtistsState) -> Unit) { if (!connectivityChecker.isConnected) { callback(TopArtistsState.Error("No network connectivity")) return } callback(TopArtistsState.Loading) //convert to rxjava single topArtistsApi.getTopArtists().enqueue(object : Callback<LastFmArtists> { override fun onFailure(call: Call<LastFmArtists>, t: Throwable) { callback(TopArtistsState.Error(t.localizedMessage)) } override fun onResponse(call: Call<LastFmArtists>, response: Response<LastFmArtists>) { response.body()?.also { topArtists -> callback(TopArtistsState.Success(mapper.encode(topArtists to response.expiry))) } } }) } override fun requestData(): TopArtistsState { return if(!connectivityChecker.isConnected){ TopArtistsState.Error("No network connectivity") } else { val response = topArtistsApi.getTopArtists().execute() response.takeIf { it.isSuccessful}?.body()?.let { artists -> TopArtistsState.Success(mapper.encode(artists to response.expiry)) } ?: TopArtistsState.Error(response.errorBody()?.string() ?: "Network Error") //sweet } } private val Response<LastFmArtists>.expiry: Long get() { //Use EXPIRES header if it exists val expires: Long? = if (headers().names().contains(HEADER_EXPIRES)) { HttpDate.parse(headers().get(HEADER_EXPIRES)).time } else null //Use Cache-Control header if that exists val cacheControlMaxAge = raw().cacheControl().maxAgeSeconds().toLong() //Use Access-Control-Max-Age if that exists val maxAge: Long? = cacheControlMaxAge.takeIf { it >= 0 } ?: headers().get(HEADER_AC_MAX_AGE)?.toLong() //Defaults to one day val date = if (headers().names().contains(HEADER_DATE)) { HttpDate.parse(headers().get(HEADER_DATE)).time } else { System.currentTimeMillis() } return expires ?: maxAge?.let { date + TimeUnit.SECONDS.toMillis(it) } ?: date + TimeUnit.DAYS.toMillis(1) } companion object { private const val HEADER_DATE = "Date" private const val HEADER_EXPIRES = "Expires" private const val HEADER_AC_MAX_AGE = "Access-Control-Max-Age" } }<file_sep>/core/src/main/java/com/vic/villz/core/app/ConnectivityChecker.kt package com.vic.villz.core.app import android.net.ConnectivityManager import javax.inject.Inject class ConnectivityChecker @Inject constructor(private val connectivityManager: ConnectivityManager){ val isConnected: Boolean get() = connectivityManager.activeNetworkInfo?.isConnected ?: false }<file_sep>/core/src/main/java/com/vic/villz/core/app/di/CoreNetworkModule.kt package com.vic.villz.core.app.di import com.vic.villz.core.BuildConfig import dagger.Module import dagger.Provides import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor @Module object CoreNetworkModule { @Provides @JvmStatic internal fun providesLoggingInterceptor(): HttpLoggingInterceptor? = if(BuildConfig.DEBUG){ HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } } else null @Provides @JvmStatic internal fun providesOkhttpClientBuilder(loggingInterceptor: HttpLoggingInterceptor?): OkHttpClient.Builder = OkHttpClient.Builder() .apply { loggingInterceptor?.also { addInterceptor(it) } } //add retrofit }<file_sep>/topartists/src/main/java/com/vic/villz/topartists/schedulers/TopArtistsScheduler.kt package com.vic.villz.topartists.schedulers import androidx.work.* import com.vic.villz.core.app.providers.UpdateScheduler import com.vic.villz.topartists.entities.Artist import java.util.concurrent.TimeUnit class TopArtistsScheduler() : UpdateScheduler<Artist>{ override fun scheduleUpdate(items: List<Artist>) { WorkManager.getInstance() .enqueueUniqueWork( UNIQUE_WORK_ID, ExistingWorkPolicy.REPLACE, OneTimeWorkRequestBuilder<TopArtistsUpdateWorker>() .setInitialDelay(items.earliestUpdate(), TimeUnit.MILLISECONDS) .setConstraints( Constraints.Builder() .setRequiredNetworkType(NetworkType.UNMETERED) .setRequiresBatteryNotLow(true) .build() ).build() ) } private fun List<Artist>.earliestUpdate() = (minBy { it.expiry }?.expiry?.let { it - System.currentTimeMillis() } ?: TimeUnit.DAYS.toMillis(1)) / 2 companion object { private const val UNIQUE_WORK_ID: String = "TopArtistsScheduler" } }<file_sep>/topartists/src/main/java/com/vic/villz/topartists/di/topartists/LastFmTopArtistsModule.kt package com.vic.villz.topartists.di.topartists import com.vic.villz.core.app.ConnectivityChecker import com.vic.villz.core.app.providers.DataMapper import com.vic.villz.core.app.providers.DataProvider import com.vic.villz.topartists.entities.Artist import com.vic.villz.topartists.entities.TopArtistsState import com.vic.villz.topartists.net.LastFmArtists import com.vic.villz.topartists.net.LastFmArtistsMapper import com.vic.villz.topartists.net.LastFmTopArtistsApi import com.vic.villz.topartists.net.LastFmTopArtistsProvider import dagger.Module import dagger.Provides import javax.inject.Named @Module object LastFmTopArtistsModule{ @Provides @JvmStatic fun provideLastFmMapper(): DataMapper<Pair<LastFmArtists, Long>, List<Artist>> = LastFmArtistsMapper() @Provides @Named(TopArtistsModule.NETWORK) @JvmStatic fun providesTopArtistsProvider( lastFmTopArtistsApi: LastFmTopArtistsApi, connectivityChecker: ConnectivityChecker, mapper: DataMapper<Pair<LastFmArtists, Long>, List<Artist>> ): DataProvider<TopArtistsState> = LastFmTopArtistsProvider( lastFmTopArtistsApi, connectivityChecker, mapper ) }<file_sep>/app/src/main/java/com/vic/villz/artists/di/AppComponent.kt package com.vic.villz.artists.di import android.app.Application import com.vic.villz.artists.MuseleeApplication import com.vic.villz.topartists.di.topartists.TopArtistsModule import dagger.BindsInstance import dagger.Component import dagger.android.AndroidInjector import dagger.android.support.AndroidSupportInjectionModule import javax.inject.Singleton @Component(modules = [ AndroidSupportInjectionModule::class, ActivitiesBuildersModule::class, TopArtistsModule::class, AppModule::class ]) @Singleton interface AppComponent:AndroidInjector<MuseleeApplication>{ @Component.Builder interface Builder{ @BindsInstance fun application(application: Application) : Builder fun build(): AppComponent } }<file_sep>/core/src/main/java/com/vic/villz/core/app/providers/DataMapper.kt package com.vic.villz.core.app.providers interface DataMapper<S, R> { fun encode(source:S):R fun decode(source: R): S = throw NotImplementedError() }<file_sep>/app/src/main/java/com/vic/villz/artists/MuseleeActivity.kt package com.vic.villz.artists import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.vic.villz.topartists.ui.TopArtistsFragment import dagger.android.AndroidInjection class MuseleeActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { AndroidInjection.inject(this) super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) supportFragmentManager.beginTransaction().apply { replace(R.id.main_fragment, TopArtistsFragment()) commit() } } } <file_sep>/app/src/main/java/com/vic/villz/artists/di/AppModule.kt package com.vic.villz.artists.di import android.app.Application import android.content.Context import android.net.ConnectivityManager import androidx.core.content.getSystemService import com.vic.villz.artists.MuseleeApplication import com.vic.villz.core.app.connectivity.ConnectivityLiveData import dagger.Module import dagger.Provides import javax.inject.Singleton @Module object AppModule { //all other library modules can access this module and inject stuffs from here, if you need other module to access app level stuff use this format(so as to avoid cyclic dependency) // @Provides // @JvmStatic // @Singleton // internal fun provideApplication(app: MuseleeApplication): Application{ //this context can be provide to other module for use // return app // } @Provides @JvmStatic @Singleton fun provideConnectivityManager(app: Application): ConnectivityManager{ return app.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager } @Provides @JvmStatic @Singleton fun providesConnectivityLiveData(app: Application) = ConnectivityLiveData(app) }<file_sep>/topartists/src/main/java/com/vic/villz/topartists/di/topartists/SchedulersModule.kt package com.vic.villz.topartists.di.topartists import com.vic.villz.core.app.providers.UpdateScheduler import com.vic.villz.topartists.entities.Artist import com.vic.villz.topartists.schedulers.TopArtistsScheduler import dagger.Module import dagger.Provides @Module object SchedulerModule { @Provides @JvmStatic fun providesScheduler(): UpdateScheduler<Artist> = TopArtistsScheduler() }<file_sep>/topartists/src/main/java/com/vic/villz/topartists/net/LastFmArtistsMapper.kt package com.vic.villz.topartists.net import com.vic.villz.core.app.providers.DataMapper import com.vic.villz.topartists.entities.Artist import javax.inject.Inject //andd constructor @Inject so that you can use this in the repository class LastFmArtistsMapper :DataMapper<Pair<LastFmArtists, Long>, List<Artist>> { override fun encode(source: Pair<LastFmArtists, Long>): List<Artist> { val (lastFmArtists, expiry) = source return lastFmArtists.artists.artist.map { artist -> Artist(artist.name, artist.normalisedImages(), expiry) } } private fun LastFmArtist.normalisedImages() = images.map { it.size.toImageSize() to it.url }.toMap() private fun String.toImageSize(): Artist.ImageSize = when (this) { "small" -> Artist.ImageSize.SMALL "medium" -> Artist.ImageSize.MEDIUM "large" -> Artist.ImageSize.LARGE "extralarge" -> Artist.ImageSize.EXTRA_LARGE else -> Artist.ImageSize.UNKNOWN } }<file_sep>/topartists/src/main/java/com/vic/villz/topartists/schedulers/TopArtistsUpdateWorker.kt package com.vic.villz.topartists.schedulers import android.content.Context import androidx.work.ListenableWorker import androidx.work.Worker import androidx.work.WorkerParameters import com.vic.villz.core.app.providers.DataPersister import com.vic.villz.core.app.providers.DataProvider import com.vic.villz.core.app.providers.UpdateScheduler import com.vic.villz.core.app.work.DaggerWorkerFactory import com.vic.villz.topartists.di.topartists.TopArtistsModule import com.vic.villz.topartists.entities.Artist import com.vic.villz.topartists.entities.TopArtistsState import java.lang.IllegalStateException import javax.inject.Inject import javax.inject.Named class TopArtistsUpdateWorker ( private val provider: DataProvider<TopArtistsState>, private val persister: DataPersister<List<Artist>>, private val scheduler: UpdateScheduler<Artist>, context: Context, workerParams: WorkerParameters ) : Worker(context, workerParams) { override fun doWork(): Result = when(val state = provider.requestData()) { //using the synchronous form of requestData cos we are in the background is TopArtistsState.Success -> { persister.persistData(state.artists) scheduler.scheduleUpdate(state.artists) //if the data was successful, schedule it again Result.success() } is TopArtistsState.Error -> Result.retry() is TopArtistsState.Loading -> throw IllegalStateException("Unexpected Loading State") } class Factory @Inject constructor( @Named(TopArtistsModule.NETWORK) private val provider: DataProvider<TopArtistsState>, private val persister: DataPersister<List<Artist>>, private val scheduler: UpdateScheduler<Artist> ) : DaggerWorkerFactory.ChildWorkerFactory { override fun create(appContext: Context, params: WorkerParameters): ListenableWorker = TopArtistsUpdateWorker(provider, persister, scheduler, appContext, params) } }<file_sep>/core/src/main/java/com/vic/villz/core/app/providers/DataPersister.kt package com.vic.villz.core.app.providers interface DataPersister<T> : DataProvider<T>{ fun persistData(data:T) }<file_sep>/core/src/main/java/com/vic/villz/core/app/di/BaseViewModule.kt package com.vic.villz.core.app.di import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.vic.villz.core.app.view.ViewModelFactory import dagger.Binds import dagger.Module import javax.inject.Singleton //import androidx.lifecycle.ViewModelProvider @Module @Suppress("unused") abstract class BaseViewModule{ @Singleton @Binds abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory }<file_sep>/core/src/main/java/com/vic/villz/core/app/providers/UpdateScheduler.kt package com.vic.villz.core.app.providers interface UpdateScheduler <T> { fun scheduleUpdate(items: List<T>) }
50157995f64655fa66bb69919201c49bc234485d
[ "Kotlin", "Gradle" ]
25
Kotlin
VillzVic/Clean-Architecture
427737b0e643271da78cdbb6222d9bc6d9336431
7778335d8d9c683617178e5c3c766f97c38d4371
refs/heads/master
<file_sep>package com.lchrislee.longjourney.activities; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.support.wearable.view.WatchViewStub; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.lchrislee.longjourney.LongJourneyApplication; import com.lchrislee.longjourney.R; import com.lchrislee.longjourney.model.actors.Player; import com.lchrislee.longjourney.utility.NotificationUtility; import com.lchrislee.longjourney.utility.SharedPreferenceUtility; public class TravelActivity extends Activity { private static final String TAG = TravelActivity.class.getSimpleName(); private TextView levelText; private TextView goldText; private TextView stepsText; private SensorManager sensorManager; private StepDetectorUpdateManager stepDetectorListener; private Player player; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_travel); player = ((LongJourneyApplication) getApplication()).getPlayer(); initializeUI(); } private void initializeUI(){ final WatchViewStub watchViewStub = (WatchViewStub) findViewById(R.id.travel_layout_stub); watchViewStub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() { @Override public void onLayoutInflated(WatchViewStub watchViewStub) { levelText = (TextView) findViewById(R.id.travel_text_level); goldText = (TextView) findViewById(R.id.travel_text_gold); stepsText = (TextView) findViewById(R.id.travel_text_steps); Button b = (Button) findViewById(R.id.travel_button_temp_notification); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { NotificationUtility.launchBattleNotification(v.getContext(), R.drawable.slime); } }); updateUI(); } }); } @Override protected void onResume() { super.onResume(); initializeStepSensors(); } private void initializeStepSensors(){ sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); Sensor stepDetector = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR); Sensor stepCounter = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER); if (stepDetector == null || stepCounter == null){ Log.e(TAG, "Insufficient step detection!"); Toast.makeText(getApplicationContext(), "Sorry, you can't use this app!", Toast.LENGTH_SHORT).show(); }else { Log.d(TAG, "Step counter and detector found!"); stepDetectorListener = new StepDetectorUpdateManager(); sensorManager.registerListener(stepDetectorListener, stepDetector, SensorManager.SENSOR_DELAY_GAME); StepCounterUpdateManager stepCounterListener = new StepCounterUpdateManager(); sensorManager.registerListener(stepCounterListener, stepCounter, SensorManager.SENSOR_DELAY_GAME); } } private void updateUI(){ levelText.setText(String.valueOf(player.getLevel())); goldText.setText(String.valueOf(player.getGold())); stepsText.setText(String.valueOf(player.getStepCount())); } @Override protected void onPause() { super.onPause(); sensorManager.unregisterListener(stepDetectorListener); saveDataToPreferences(); } private void saveDataToPreferences(){ SharedPreferences sharedPreferences = getSharedPreferences(SharedPreferenceUtility.STEP_PREF_NAME, MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putLong(SharedPreferenceUtility.STEP_REFERENCE, player.getStepReference()); editor.putLong(SharedPreferenceUtility.STEP_COUNT, player.getStepCount()); editor.apply(); } private class StepDetectorUpdateManager implements SensorEventListener{ @Override public void onSensorChanged(SensorEvent event) { player.increaseStepCountBy(1); if (stepsText != null) { stepsText.setText(String.valueOf(player.getStepCount())); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } } private class StepCounterUpdateManager implements SensorEventListener{ @Override public void onSensorChanged(SensorEvent event) { long newTotalCount = (long) event.values[0]; long ref = player.getStepReference(); if (newTotalCount > ref){ player.increaseStepCountBy(newTotalCount - ref); } sensorManager.unregisterListener(this); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } } } <file_sep>package com.lchrislee.longjourney.model.actors; import com.lchrislee.longjourney.R; import com.lchrislee.longjourney.model.items.UsableItem; import com.lchrislee.longjourney.model.items.Weapon; import java.io.Serializable; import java.util.ArrayList; /** * Created by <NAME> on 7/15/16. */ public class Player extends Actor implements Serializable{ private ArrayList<UsableItem> items; private long stepCount; private long stepReference; private int xpNeeded; private Player(long level, int health, int currentHealth, long gold, int strength, int defense, long stepCount, long stepReference, int xp) { super(level, health, currentHealth, gold, strength, defense, xp); this.stepCount = stepCount; this.stepReference = stepReference; items = new ArrayList<>(); generateXpNeeded(getLevel()); buildWeapon(); } public ArrayList<UsableItem> getItems() { return items; } public void addItem(UsableItem inItem){ items.add(inItem); } public long getStepCount() { return stepCount; } public void increaseStepCountBy(long stepDifference) { this.stepCount += stepDifference; } public long getStepReference() { return stepReference; } public int getXpNeeded() { return xpNeeded; } private void generateXpNeeded(long level){ if (level == 0){ xpNeeded = 10; }else{ generateXpNeeded(level - 1); xpNeeded += (int) level; } } public boolean gainXPAndCheckLevelUp(int xpGain){ increaseXpBy(xpGain); if (getXp() >= getXpNeeded()){ levelUp(); return true; } return false; } private void levelUp(){ increaseLevelBy(1); generateXpNeeded(getLevel()); increaseStats(); } protected void increaseStats() { // TODO FILL } @Override protected void buildWeapon() { Weapon.Builder builder = new Weapon.Builder(); builder.name("Fists"); builder.description("Your hands."); builder.attack(1); builder.image(R.drawable.rubber_chicken); setWeapon(builder.build()); } public static class Builder extends Actor.Builder{ private long stepCount; private long stepReference; public Builder stepCount(long stepCount) { this.stepCount = stepCount; return this; } public Builder stepReference(long stepReference) { this.stepReference = stepReference; return this; } public Player build(){ return new Player(level, health, currentHealth, gold, strength, defense, stepReference, stepCount, xp); } } } <file_sep>include ':LJ Watch' <file_sep>package com.lchrislee.longjourney.model.actors; import android.support.annotation.NonNull; import com.lchrislee.longjourney.model.items.Weapon; /** * Created by <NAME> on 7/15/16. */ public abstract class Actor { private Weapon weapon; private long level; private int maxHealth; private int currentHealth; private long gold; private int strength; private int defense; private int xp; Actor(long level, int maxHealth, int currentHealth, long gold, int strength, int defense, int xp) { this.maxHealth = maxHealth; this.currentHealth = currentHealth; this.gold = gold; this.level = level; this.strength = strength; this.defense = defense; this.xp = xp; this.currentHealth = this.maxHealth; } public int getMaxHealth() { return maxHealth; } public int getCurrentHealth() { return currentHealth; } public void changeCurrentHealthBy(int change) { this.currentHealth += change; if (this.currentHealth > this.maxHealth){ this.currentHealth = this.maxHealth; } } public long getGold() { return gold; } public long getLevel() { return level; } void increaseLevelBy(long levelIncrease){ this.level += levelIncrease; } public int getStrength() { return strength; } public int getDefense() { return defense; } public int getXp() { return xp; } void increaseXpBy(int change) { this.xp += change; } public @NonNull Weapon getWeapon() { return weapon; } void setWeapon(@NonNull Weapon weapon) { this.weapon = weapon; } protected abstract void buildWeapon(); public int getTotalDamage(){ return strength + weapon.getAttack(); } public static abstract class Builder{ long level; int health; int currentHealth; long gold; int strength; int defense; int xp; public Builder level(long level) { this.level = level; return this; } public Builder maxHealth(int maxHealth) { this.health = maxHealth; return this; } public Builder currentHealth(int currentHealth) { this.currentHealth = currentHealth; return this; } public Builder gold(long gold) { this.gold = gold; return this; } public Builder strength(int strength) { this.strength = strength; return this; } public Builder defense(int defense) { this.defense = defense; return this; } public Builder xp(int xp) { this.xp = xp; return this; } } } <file_sep>package com.lchrislee.longjourney.activities; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.wearable.view.WatchViewStub; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import com.lchrislee.longjourney.LongJourneyApplication; import com.lchrislee.longjourney.R; import com.lchrislee.longjourney.model.actors.Monster; import com.lchrislee.longjourney.model.actors.Player; import com.lchrislee.longjourney.utility.BattleUtility; import com.lchrislee.longjourney.utility.NotificationUtility; public class SpoilsActivity extends Activity { public static final String CONCLUSION = "com.lchrislee.longjourney.activities.SpoilsActivity.CONCLUSION"; private TextView levelText; private TextView goldText; private TextView spoilsText; private TextView statusText; private ProgressBar xp; private Player player; private Monster monster; private int conclusion; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_spoils); Intent i = getIntent(); if (i != null){ conclusion = i.getIntExtra(CONCLUSION, -1); NotificationUtility.cancelNotification(this); } player = ((LongJourneyApplication) getApplication()).getPlayer(); monster = ((LongJourneyApplication) getApplication()).getMonster(); initializeUI(); } private void initializeUI(){ final WatchViewStub watchViewStub = (WatchViewStub) findViewById(R.id.spoils_layout_stub); watchViewStub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() { @Override public void onLayoutInflated(WatchViewStub watchViewStub) { levelText = (TextView) findViewById(R.id.spoils_text_level); goldText = (TextView) findViewById(R.id.spoils_text_gold); spoilsText = (TextView) findViewById(R.id.spoils_text_spoils); statusText = (TextView) findViewById(R.id.spoils_status); xp = (ProgressBar) findViewById(R.id.spoils_progress_xp); // TODO Animate, take a look at http://stackoverflow.com/questions/8035682/animate-progressbar-update-in-android xp.setProgress(0); xp.setSecondaryProgress(0); xp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { xp.setProgress(xp.getProgress() + 10); } }); updateUI(); } }); } private void updateUI(){ levelText.setText(String.valueOf(player.getLevel())); goldText.setText(String.valueOf(player.getGold())); xp.setProgress(player.getXp()); if (conclusion == BattleUtility.BATTLE_OPTION_SNEAK){ spoilsText.setVisibility(View.INVISIBLE); statusText.setText(R.string.conclusion_sneak); }else if(conclusion == BattleUtility.BATTLE_OPTION_RUN){ spoilsText.setText(String.valueOf(-1 * monster.getGold())); statusText.setText(R.string.conclusion_run); } else if (monster.getCurrentHealth() <= 0){ spoilsText.setText(String.valueOf(monster.getGold())); statusText.setText(R.string.conclusion_victory); int xpChange = player.getXp() + monster.getXp(); if (xpChange >= player.getXpNeeded()){ xp.setSecondaryProgress(xp.getMax()); xp.setProgress(xp.getMax()); }else{ xp.setSecondaryProgress(xpChange); xp.setProgress(xpChange); } }else{ spoilsText.setText(R.string.zero); statusText.setText(R.string.conclusion_loss); } } } <file_sep>package com.lchrislee.longjourney.activities; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.wearable.view.WatchViewStub; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.lchrislee.longjourney.R; import com.lchrislee.longjourney.utility.BattleUtility; import com.lchrislee.longjourney.utility.NotificationUtility; public class BattleSneakActivity extends Activity { private ImageView monster; private Button left; private Button right; private SneakButtonListener listener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sneak); Intent i = getIntent(); if (i != null){ NotificationUtility.cancelNotification(this); } final WatchViewStub stub = (WatchViewStub) findViewById(R.id.sneak_view_stub); stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() { @Override public void onLayoutInflated(WatchViewStub stub) { monster = (ImageView) stub.findViewById(R.id.sneak_image_monster); left = (Button) stub.findViewById(R.id.sneak_button_left); right = (Button) stub.findViewById(R.id.sneak_button_right); updateUI(); } }); listener = new SneakButtonListener(); } private void updateUI(){ left.setOnClickListener(listener); right.setOnClickListener(listener); monster.setImageDrawable(BattleUtility.getMonsterDrawable(this)); } private class SneakButtonListener implements Button.OnClickListener{ @Override public void onClick(View v) { Intent nextActivity; if(BattleUtility.determineSneakSuccess(v.getContext())){ nextActivity = new Intent(v.getContext(), SpoilsActivity.class); nextActivity.putExtra(SpoilsActivity.CONCLUSION, BattleUtility.BATTLE_OPTION_SNEAK); }else{ nextActivity = new Intent(v.getContext(), BattleFightActivity.class); nextActivity.putExtra(BattleFightActivity.FROM, BattleUtility.BATTLE_OPTION_SNEAK); } startActivity(nextActivity); } } } <file_sep>package com.lchrislee.longjourney.model.items; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; /** * Created by <NAME> on 7/15/16. */ public class Weapon extends UsableItem { private int attack; private Weapon(@NonNull String name, @NonNull String description, @DrawableRes int image, int attack) { super(name, description, image); this.attack = attack; } public int getAttack() { return attack; } public static class Builder{ private String name; private String description; private int attack; private int image; public @NonNull Builder name(@NonNull String name){ this.name = name; return this; } public @NonNull Builder description(@NonNull String description){ this.description = description; return this; } public @NonNull Builder attack(int attack){ this.attack = attack; return this; } public @NonNull Builder image(@DrawableRes int image){ this.image = image; return this; } public Weapon build(){ return new Weapon(name, description, image, attack); } } }
1fa6b169bd3d47414f8fcdf95c2314c11dfde5cb
[ "Java", "Gradle" ]
7
Java
lchrislee/LongJourney
4409666ae1d1fca1b6ffac1b6aef6d37c6fb73f2
891044b971572cf74b89b2a1f893bee8175cdc7a
refs/heads/master
<file_sep>using System.IO; using System.Net; using System.Threading.Tasks; namespace Mixer.Base.Web { public class OAuthHttpListenerServer : HttpListenerServerBase { public const string URL_CODE_IDENTIFIER = "/?code="; private const string defaultSuccessResponse = "<!DOCTYPE html><html><body><h1 style=\"text-align:center;\">Logged In Successfully</h1><p style=\"text-align:center;\">You have been logged in, you may now close this webpage</p></body></html>"; private string loginSuccessHtmlPageFilePath = null; private string OAuthTokenModel = null; public OAuthHttpListenerServer(string address) : base(address) { } public OAuthHttpListenerServer(string address, string loginSuccessHtmlPageFilePath) : this(address) { this.loginSuccessHtmlPageFilePath = loginSuccessHtmlPageFilePath; } public async Task<string> WaitForAuthorizationCode() { for (int i = 0; i < 30; i++) { if (!string.IsNullOrEmpty(this.OAuthTokenModel)) { break; } await Task.Delay(1000); } return this.OAuthTokenModel; } protected override HttpStatusCode RequestReceived(HttpListenerRequest request, string data, out string result) { result = "OK"; if (request.RawUrl.Contains(URL_CODE_IDENTIFIER)) { string token = request.RawUrl.Substring(URL_CODE_IDENTIFIER.Length); int endIndex = token.IndexOf("&"); if (endIndex > 0) { token = token.Substring(0, endIndex); } this.OAuthTokenModel = token; result = defaultSuccessResponse; if (this.loginSuccessHtmlPageFilePath != null && File.Exists(this.loginSuccessHtmlPageFilePath)) { result = File.ReadAllText(this.loginSuccessHtmlPageFilePath); } } return HttpStatusCode.OK; } } } <file_sep>using Mixer.Base.Util; using System; using System.IO; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; namespace Mixer.Base.Web { public abstract class HttpListenerServerBase { private string address; private HttpListener listener; private CancellationTokenSource listenerThreadCancellationTokenSource = new CancellationTokenSource(); public HttpListenerServerBase(string address) { this.address = address; this.listener = new HttpListener(); } public void Start() { this.listener.Prefixes.Add(this.address); this.listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous; this.listener.Start(); Task.Factory.StartNew(this.Listen, listenerThreadCancellationTokenSource.Token); } public void End() { this.listenerThreadCancellationTokenSource.Cancel(); this.listener.Abort(); } protected virtual void RequestReceived(HttpListenerContext context, string data) { string streamResult = string.Empty; HttpStatusCode code = this.RequestReceived(context.Request, data, out streamResult); context.Response.Headers["Access-Control-Allow-Origin"] = "*"; context.Response.StatusCode = (int)code; context.Response.StatusDescription = code.ToString(); byte[] buffer = Encoding.UTF8.GetBytes(streamResult); context.Response.OutputStream.Write(buffer, 0, buffer.Length); context.Response.Close(); } protected virtual HttpStatusCode RequestReceived(HttpListenerRequest request, string data, out string result) { result = string.Empty; return HttpStatusCode.OK; } private void Listen(object s) { while (!this.listenerThreadCancellationTokenSource.IsCancellationRequested) { this.listenerThreadCancellationTokenSource.Token.ThrowIfCancellationRequested(); var result = this.listener.BeginGetContext(this.ListenerCallback, this.listener); result.AsyncWaitHandle.WaitOne(); } this.listenerThreadCancellationTokenSource.Token.ThrowIfCancellationRequested(); } private void ListenerCallback(IAsyncResult result) { try { var context = listener.EndGetContext(result); Thread.Sleep(1000); var data_text = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding).ReadToEnd(); var cleanedData = HttpUtility.UrlDecode(data_text); this.RequestReceived(context, cleanedData); } catch (Exception ex) { Logger.Log(ex); } } } } <file_sep>using System; using System.Net; using System.Net.Http; namespace Mixer.Base.Util { public class RestServiceRequestException : HttpRequestException { public HttpStatusCode StatusCode { get; private set; } public string Reason { get; private set; } public string Content { get; private set; } public RestServiceRequestException() : base() { } public RestServiceRequestException(string message) : base(message) { } public RestServiceRequestException(string message, Exception inner) : base(message, inner) { } public RestServiceRequestException(HttpResponseMessage response) : this(response.ReasonPhrase) { this.StatusCode = response.StatusCode; this.Reason = response.ReasonPhrase; this.Content = response.Content.ReadAsStringAsync().Result; } } } <file_sep>using Mixer.Base.Util; using System; using System.IO; using System.Net; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Mixer.Base.Clients { public abstract class WebSocketClientBase { private const int bufferSize = 1000000; public event EventHandler<string> OnSentOccurred; public event EventHandler<string> OnReceivedOccurred; public event EventHandler<WebSocketCloseStatus> OnDisconnectOccurred; public event EventHandler OnReconnectionOccurred; private string endpoint; private bool autoReconnect; private CancellationTokenSource cancellationTokenSource; private ClientWebSocket webSocket; private UTF8Encoding encoder = new UTF8Encoding(); private SemaphoreSlim webSocketSemaphore = new SemaphoreSlim(1); public virtual async Task<bool> Connect(string endpoint, bool autoReconnect = true) { this.endpoint = endpoint; this.autoReconnect = autoReconnect; try { this.cancellationTokenSource = new CancellationTokenSource(); this.webSocket = this.CreateWebSocket(); await this.webSocket.ConnectAsync(new Uri(endpoint), this.cancellationTokenSource.Token); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed this.Receive(); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed return true; } catch (Exception ex) { await this.Disconnect(); if (ex is WebSocketException && ex.InnerException is WebException) { WebException webException = (WebException)ex.InnerException; if (webException.Response != null && webException.Response is HttpWebResponse) { HttpWebResponse response = (HttpWebResponse)webException.Response; StreamReader reader = new StreamReader(response.GetResponseStream()); string responseString = reader.ReadToEnd(); throw new WebSocketException(string.Format("{0} - {1} - {2}", response.StatusCode, response.StatusDescription, responseString), ex); } } throw; } } public Task Disconnect(WebSocketCloseStatus closeStatus = WebSocketCloseStatus.NormalClosure) { if (this.webSocket != null) { try { #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed this.webSocket.CloseAsync(closeStatus, string.Empty, this.cancellationTokenSource.Token); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } catch (Exception ex) { Logger.Log(ex); } } this.webSocket = null; if (this.OnDisconnectOccurred != null) { this.OnDisconnectOccurred(this, closeStatus); } return Task.FromResult(0); } public bool IsOpen() { return (this.GetState() == WebSocketState.Open || this.GetState() == WebSocketState.Connecting); } public WebSocketState GetState() { if (this.webSocket != null) { return this.webSocket.State; } return WebSocketState.Closed; } public virtual async Task Send(string packet, bool checkIfAuthenticated = true) { byte[] buffer = this.encoder.GetBytes(packet); await this.webSocketSemaphore.WaitAsync(); try { if (this.IsOpen()) { await this.webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None); } } catch (InvalidOperationException) { if (this.autoReconnect) { #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed this.Reconnect(); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } throw; } finally { this.webSocketSemaphore.Release(); } if (this.OnSentOccurred != null) { this.OnSentOccurred(this, packet); }; } protected abstract Task ProcessReceivedPacket(string packetJSON); protected virtual ClientWebSocket CreateWebSocket() { return new ClientWebSocket(); } protected virtual void DisconnectOccurred(WebSocketCloseStatus? result) { if (this.OnDisconnectOccurred != null) { this.OnDisconnectOccurred(this, result.GetValueOrDefault()); } } protected async Task Reconnect() { Logger.Log("Disconnection occurred, starting reconnection process"); await this.webSocketSemaphore.WaitAsync(); do { await this.Disconnect(); Logger.Log("Attempting reconnection..."); } while (!await this.Connect(this.endpoint)); this.webSocketSemaphore.Release(); Logger.Log("Reconnection successful"); if (this.OnReconnectionOccurred != null) { this.OnReconnectionOccurred(this, new EventArgs()); } } protected async Task WaitForResponse(Func<bool> valueToCheck) { for (int i = 0; i < 50 && !valueToCheck(); i++) { await Task.Delay(100); } } private async Task Receive() { string jsonBuffer = string.Empty; byte[] buffer = new byte[WebSocketClientBase.bufferSize]; WebSocketCloseStatus closeStatus = WebSocketCloseStatus.NormalClosure; try { while (this.IsOpen()) { try { Array.Clear(buffer, 0, buffer.Length); WebSocketReceiveResult result = await this.webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); if (result != null) { if (result.CloseStatus == null || result.CloseStatus == WebSocketCloseStatus.Empty) { jsonBuffer += this.encoder.GetString(buffer); if (result.EndOfMessage) { if (this.OnReceivedOccurred != null) { this.OnReceivedOccurred(this, jsonBuffer); } await this.ProcessReceivedPacket(jsonBuffer); jsonBuffer = string.Empty; } } else { closeStatus = result.CloseStatus.GetValueOrDefault(); } } } catch (Exception ex) { Logger.Log(ex); } } } catch (Exception ex) { Logger.Log(ex); } if (this.GetState() == WebSocketState.Aborted && this.autoReconnect) { await this.Reconnect(); } else { await this.Disconnect(closeStatus); } } } }
955bf1e2e8425a4506f584af62961ed0c26e8491
[ "C#" ]
4
C#
D3thw0lf/mixer-client-csharp
f998ab97b73a084a20565665d8650c0847cef49f
7ac4f6e89d280c9c0b0bda0487276b5c143e761f
refs/heads/master
<file_sep>markdown_viewer =============== 1. mkdir document 2. .md file in the document folder 3. access markdown_viewer.php 4. rewrite footer,header. <file_sep><?php include_once "markdown.php"; include_once "function.php"; $filelist = getFileList('/var/www/html/document'); ?> <html> <head> <meta http-equiv="content-Type" content ="text/html; charset=UTF-8"> <title>Markdown Viewer</title> <link href="markdown.css" rel="stylesheet"> <link href="main.css" rel="stylesheet"> </head> <body> <div class="header">Markdown Viewer</div> <div class="list"> <?php $i=0; foreach($filelist as $value){ ${"html_".$i} = Markdown(file_get_contents("$value")); $name = "$html_".$i; echo "<a href=#" .$name.">" . basename($value,".md") ."</a><br />"; $i++; } ?> </div> <div class="view"> <?php $i=0; while(isset(${"html_".$i})){ echo "<div id=".$i.">"; echo ${"html_".$i}; echo "<div id=sep><hr></div>"; echo "</div>"; $i++; } ?> </div> <div class="footer">&copy; 2014 Red C Lab.</div> </body>
f76c3b28d8cb49d7df89bbfab31125b4932f7fd8
[ "Markdown", "PHP" ]
2
Markdown
s-nojima/markdown_viewer
6758a2f20ff8fa6b387fa6795abfbcb3069f842e
92499f97d0738c7777d78588d871812fe554afdd
refs/heads/master
<file_sep>class Article < ApplicationRecord validates :title, presence: true validates :body, presence: true end # (1..10).each_with_index do |i| # Article.create(title: "title title title 0#{i}", body: "test test test est test etste test etste teest test 0#{i}") # end
9f0ecc1d90f863e5cde8f29908a25008c0d9d3c4
[ "Ruby" ]
1
Ruby
y-okamoto-1113/portfolio
22f2734dd76146875cdcb18b6b5ddbd9accc5de5
bfd3e3601f5cc34f7b4f2f184b934524d09dd82d
refs/heads/master
<repo_name>Supandi/OSX_MediaCenter_ElCapitan<file_sep>/scripts/install_couchpotato_agent.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { INSTALL_AGENT="local.couchpotato.couchpotato.plist" if ! file_exists '/Library/LaunchAgents/$INSTALL_AGENT'; then ask_for_sudo sudo cp ../config/launchctl/$INSTALL_AGENT /Library/LaunchAgents/ #print_result $? 'Copy PlexPy launch agent' sudo chown root:wheel /Library/LaunchAgents/$INSTALL_AGENT sudo chmod 644 /Library/LaunchAgents/$INSTALL_AGENT launchctl load /Library/LaunchAgents/$INSTALL_AGENT fi print_result $? 'LaunchAgent CouchPotato' } main<file_sep>/scripts/osx_loginwindow_info_enable.sh #!/bin/bash main() { # Reveal IP address, hostname, OS version, etc. when clicking the clock in the login window sudo defaults write /Library/Preferences/com.apple.loginwindow AdminHostInfo HostName print_result $? 'Enhance login window' } main <file_sep>/scripts/install_mysql55.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { if ! cmd_exists 'mysql'; then # Sanity check if ! cmd_exists 'brew'; then print_error 'Homebrew required' exit fi brew install homebrew/versions/mysql55 ln -sfv /usr/local/opt/mysql55/*.plist ~/Library/LaunchAgents launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql55.plist mysql.server start mysql_secure_installation ## brew unlink mysql57 ## brew switch mysql 5.5 ## brew unlink mysql && brew link mysql55 --force fi print_result $? 'MySQL 5.5' } main<file_sep>/scripts/install_osx_pip.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { if ! cmd_exists 'pip'; then ask_for_sudo sudo easy_install pip fi print_result $? 'pip - package management system' } main<file_sep>/scripts/install_couchpotato.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { if ! folder_exists $COUCHPOTATO_FOLDER; then if [ "${COUCHPOTATO_FOLDER}" == "" ] ; then echo "Error: Not all config setting have been found set, please check config.sh." exit 1 fi sudo mkdir -p $COUCHPOTATO_FOLDER sudo chown -R `whoami`:staff $COUCHPOTATO_FOLDER git clone https://github.com/RuudBurger/CouchPotatoServer.git $COUCHPOTATO_FOLDER print_result $? 'Download Couch Potato' fi # open http://localhost:5050/ # echo " --- press any key to continue ---" # read -n 1 -s print_result $? 'CouchPotato' } main <file_sep>/scripts/install_plex_redirect.sh cd /Users/Plex/ git clone https://github.com/ITRav4/PlexRedirect.git sudo ln -s /Users/Plex/PlexRedirect /Library/Server/Web/Data/Sites/Default/plexredirect <file_sep>/temp/rename_qoq.php <?php // Change Spotweb Spot Title // // This script will rename the spot title in case a year was detected. // The script assumes the title syntax is like: "TV Show title (year) release info" // // Original idea inspired from MR_Blobby http://gathering.tweakers.net/forum/list_message/43647658#43647658 // DBTV lookup inspired from http://pastebin.com/yfB1GiJf // ==================================================================================================================== // PARAMETERS // ==================================================================================================================== // Location of Spotweb db settings file $dbsettingsfile = "/Users/Plex/Spotweb/dbsettings.inc.php"; // Should we send some output? Ie for logging use: php addrating.php >> /var/log/spotweb $debug = false; $quiet = false; $timestamp = false; // Timestamp in logging // Age of spots to query for (in seconds): $age = 86400; // 86400 equals 1 day // Minimum string similarity between movie title from spot and movie title from IMDB (http://php.net/manual/en/function.similar-text.php) // Percentage (100 is exact match): $min_similar_text = 75; // set the default timezone to use. Available since PHP 5.1 date_default_timezone_set('CET'); // ==================================================================================================================== // DO NOT EDIT BELOW // ==================================================================================================================== // Show that we are starting doLog("Started tv show renamer"); $found = 0; $rated = 0; $percent = 0; $match = ''; $new_title_for_spot = ''; // Create MySQL connection (fill in correct values): require($dbsettingsfile); $con = mysqli_connect($dbsettings['host'], $dbsettings['user'], $dbsettings['pass'], $dbsettings['dbname']); // Check connection: if (mysqli_connect_errno($con)) doLog("Failed to connect to MySQL: " . mysqli_connect_error()); else { // Connection is ok $timestamp = time() - $age; // This query will return all x264 movies (category 0 is "images", subcatz z0 is "movies" and subcata a09 is "x264"): $query = "SELECT * FROM spots WHERE spotterid = 'C7w1uw' AND subcatz = 'z1|' AND stamp>" . $timestamp . " ORDER BY stamp"; $result = mysqli_query($con,$query); // Process all results: while ($row = mysqli_fetch_array($result)) { $found++; $title = str_replace("&period;", ".", $row['title']); doLog("Spot \t\t\t: ".$title); if($debug) { doLog(" - Row \t\t: ".$row['messageid']); } // Regular expression to try to get a "clean" movietitle from the spot title (all text until "year"): //$pattern = '/(.+)[ \(\.]((19|20)\d{2})/'; $pattern = '/(.+)[ \(\.]((19|20)\d{2})/'; //preg_match($pattern, $title, $matches); //print_r($matches); //print_r('-----------------'); if ((preg_match($pattern, $title, $matches)) == 1) { $title_from_spot = trim($matches[1]); $year = trim($matches[2]); $title_from_spot = str_replace(".", " ", $title_from_spot); if($debug) { doLog(" - Spot Title \t: ".$title_from_spot); } if($debug) { doLog(" - Spot Year \t\t: ".$year); } // Regular expression to try to get extra info from the spot title (all text as of "year"): $pattern = '/((19|20)\d{2})[ \)\.] (S|s)(\d{2}+)(E|e)\d{2} (.+)/'; preg_match($pattern, $title, $matches); //print_r($matches); //print_r('-----------------'); if ((preg_match($pattern, $title, $matches)) == 1) { $info_from_spot = trim($matches[6]); $info_from_spot = str_replace('(WEB-DL)', 'WEB-DL', $info_from_spot); $info_from_spot = str_replace('Q o Q', 'QoQ', $info_from_spot); if($debug) { doLog(" - Spot quality info \t: " . $info_from_spot); } if (preg_match('/(S|s)([0-9]+)(E|e)([0-9]+)/', $title)) { //doLog("Show name: " . $title); $seasonarray = get_season_number($title); if($debug) { doLog(" - Season number \t: " . $seasonarray['res']); } $episodearray = get_episode_number($title); if($debug) { doLog(" - Episode number \t: " . $episodearray['res']); } $tvdb_series_info = get_tvdb_seriesinfo('\'' . $title_from_spot . '\''); if ($tvdb_series_info === false) { doLog("- TVDB \t\t: Skipping, title not found"); } else { if($debug) { doLog(" - The TVDB Name \t: " . $tvdb_series_info['name']); } $seriesName = $tvdb_series_info['name']; // Calculate the similarity between the movietitle from the spot and the movietitle found in TVDB: $percent = compareTitles(strtolower($title_from_spot), strtolower($seriesName)); if($debug) { doLog(" - The TVDB ID \t: " . $tvdb_series_info['id'] . ", ".round($percent, 2)."% match"); } if($debug) { doLog(" - TheTVDB ID \t: " . $tvdb_series_info['id'] . ", ".round($percent, 2)."% match"); } if ($percent >= $min_similar_text) { doLog("- TVDB \t\t: Matched " . $tvdb_series_info['name'] . " with TVDB ID " . $tvdb_series_info['id'] . " for " . round($percent, 2) . "%"); //doLog("- TheTVDB ID \t\t: " . $tvdb_series_info['id']); $tvdb_episode_info = get_tvdb_episodeinfo($tvdb_series_info['id'], $episodearray['res'], $seasonarray['res']); if ($tvdb_episode_info === false) { doLog("- TVDB \t\t\t: Skipping, no episode information found"); } else { if($debug) { doLog(" - TheTVDB Season \t: " . $tvdb_episode_info['season']); } if($debug) { doLog(" - TheTVDB Episode \t: " . $tvdb_episode_info['episode']); } $new_title_for_spot = gen_proper_spotname($title_from_spot, $tvdb_series_info['name'], $tvdb_episode_info['episode'], $tvdb_episode_info['season'], $info_from_spot); doLog(" - New File Name \t: " . $new_title_for_spot); setSpotTitle($con, $new_title_for_spot, $row['id']); $rated++; } } else { doLog(" - TVDB\t\t: Skipping, found TVDB show doesn't match"); } } } else { doLog(" - TVDB\t\t: Skipping, no season or episode information found."); } } else { doLog("\t\t\t: Skipping, no season or episode information found"); } } else { doLog("\t\t\t: Skipping, no year in title found"); } } // Close MySQL connection: mysqli_close($con); doLog($found." spots processed of wich ".$rated." renamed"); } // ==================================================================================================================== // Functions // ==================================================================================================================== function doLog($message) { global $quiet; global $timestamp; if(!$quiet) { if($timestamp) echo date(DATE_ATOM)." "; echo $message.PHP_EOL; } } //Strip titles and compare function compareTitles($string1, $string2) { //Replace HTML characters $string1 = html_entity_decode($string1, ENT_QUOTES); $string2 = html_entity_decode($string2, ENT_QUOTES); //Lowercase $string1 = strtolower($string1); $string2 = strtolower($string2); //Remove unnecessary characters $string1 = preg_replace('~[^A-Za-z0-9]~', "", $string1); $string2 = preg_replace('~[^A-Za-z0-9]~', "", $string2); //Do we have a match? similar_text($string1, $string2, $percentage); return $percentage; } function setSpotTitle($con, $title, $id) { //$updateresult = mysqli_query($con, "UPDATE spots SET spotrating = '".$rating."' WHERE id = ".$id); $updateresult = mysqli_query($con, "UPDATE spots SET title= '".$title."' WHERE id = ".$id); print_r($updateresult); } function gen_proper_spotname($input, $name, $episode, $season, $extra_spot_info) { $delimiter = ' '; $extension = get_extension($input); if ($episode > 99) { $string = 'S' . str_pad($season, 2, "0", STR_PAD_LEFT) . 'E' . str_pad($episode, 3, "0", STR_PAD_LEFT); } else { $string = 'S' . str_pad($season, 2, "0", STR_PAD_LEFT) . 'E' . str_pad($episode, 2, "0", STR_PAD_LEFT); } //[TheTVDB Series Name].[season episode].[extra spot information] $output = $name . $delimiter . $string . $delimiter . $extra_spot_info; return $output; } function get_tvdb_seriesinfo($input) { $thetvdb = "http://www.thetvdb.com/"; $result = file_get_contents($thetvdb . 'api/GetSeries.php?seriesname='.urlencode($input)); $postemp1 = strpos($result, "<seriesid>") + strlen("<seriesid>"); $postemp2 = strpos($result, "<", $postemp1); $seriesid = substr($result, $postemp1, $postemp2 - $postemp1); if (is_numeric($seriesid) === false) { return false; } $postemp1 = strpos($result, "<SeriesName>") + strlen("<SeriesName>"); $postemp2 = strpos($result, "<", $postemp1); $seriesname = substr($result, $postemp1, $postemp2 - $postemp1); $tvdb = array('id' => $seriesid, 'name' => $seriesname); return $tvdb; } function get_tvdb_episodeinfo($seriesid, $episode, $season) { if (empty($season)) { $thetvdb = "http://www.thetvdb.com/"; $result = file_get_contents($thetvdb . 'api/F0A9519B01D1C096/series/'.$seriesid.'/absolute/'.$episode); if ($result === false) { return false; } $postemp1 = strpos($result, "<EpisodeNumber>") + strlen("<EpisodeNumber>"); $postemp2 = strpos($result, "<", $postemp1); $episodenumber = substr($result, $postemp1, $postemp2 - $postemp1); $postemp1 = strpos($result, "<SeasonNumber>") + strlen("<SeasonNumber>"); $postemp2 = strpos($result, "<", $postemp1); $episodeseason = substr($result, $postemp1, $postemp2 - $postemp1); $tvdb = array('episode' => $episodenumber, 'season' => $episodeseason); } else { $tvdb = array('episode' => $episode, 'season' => $season); } return $tvdb; } function get_show_name($input) { $pattern = '/' . '\[[^]]+\]|\([^]]+\)' . '/i'; $result = preg_replace($pattern,"",$input); $result = str_replace("-", " ",$result); $result = str_replace("_", " ",$result); $result = str_replace(".", " ",$result); // remove double spaces in the middle while (sizeof ($array=explode (" ",$result)) != 1) { $result = implode (" ",$array); } return trim($result); } function rid_extension($thefile) { if (strpos($thefile,'.') === false) { return $thefile; } else { return substr($thefile, 0, strrpos($thefile,'.')); } } function get_extension($thefile) { return substr($thefile, strrpos($thefile,'.')); } function get_episode_number($input) { if (preg_match('/' . '(E|e)([0-9]+)' . '/', $input, $episodenumber) > 0) { $episodenumber = array('del' => $episodenumber[0], 'res' => $episodenumber[2]); return $episodenumber; } else { preg_match_all('/' . '[0-9]+' . '/', $input, $matches); //Kijk voor alle episodes $matches = $matches[0]; for ($i=0; $i < count($matches); $i++) { $lastnum = $matches[$i]; } $lastnum = array('del' => $lastnum, 'res' => $lastnum); return $lastnum; } } function get_season_number($input) { $pattern = '/' . '(S|s)([0-9]+)' . '/'; if (preg_match($pattern, $input, $match) > 0) { $match = array('del' => $match[0], 'res' => $match[2]); return $match; } else { return false; } } function rec_listFiles( $from = '.') { if(! is_dir($from)) return false; $files = array(); if( $dh = opendir($from)) { while( false !== ($file = readdir($dh))) { // Skip '.' and '..' if( $file == '.' || $file == '..') continue; $path = $from . '/' . $file; if( is_dir($path) ) $files=array_merge($files,rec_listFiles($path)); else $files[] = $path; } closedir($dh); } return $files; } ?> <file_sep>/scripts/osx_smartquotes_disable.sh #!/bin/bash main() { # Disable smart quotes defaults write NSGlobalDomain NSAutomaticQuoteSubstitutionEnabled -bool false # Disable smart dashes defaults write NSGlobalDomain NSAutomaticDashSubstitutionEnabled -bool false print_result $? 'Disable smart quotes and dashes' } main <file_sep>/dotfiles/bash_functions #!/bin/bash # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # cd: Always list directory contents upon 'cd' cd() { builtin cd "$@"; ll; } # cdr: Change working directory to the top-most Finder window location cdf() { cd "$(osascript -e 'tell app "Finder" to POSIX path of (insertion location as alias)')"; } # extract: Extract most know archives with one command extract() { if [ -f $1 ] ; then case $1 in *.tar.bz2) tar xjf $1 ;; *.tar.gz) tar xzf $1 ;; *.bz2) bunzip2 $1 ;; *.rar) unrar e $1 ;; *.gz) gunzip $1 ;; *.tar) tar xf $1 ;; *.tbz2) tar xjf $1 ;; *.tgz) tar xzf $1 ;; *.zip) unzip $1 ;; *.Z) uncompress $1 ;; *.7z) 7z x $1 ;; *) echo "'$1' cannot be extracted via extract()" ;; esac else echo "'$1' is not a valid file" fi } # ff: Find file under the current directory ff() { /usr/bin/find . -name "$@" ; } # ffs: Find file whose name starts with a given string ffs() { /usr/bin/find . -name "$@"'*' ; } # ffe: Find file whose name ends with a given string ffe() { /usr/bin/find . -name '*'"$@" ; } # findPid: find out the pid of a specified process findPid() { lsof -t -c "$@" ; } # hist: Find a command in the history, e.g hist man hist() { history | grep $1; } # httpDebug: Download a web page and show info on what took time httpDebug() { /usr/bin/curl $@ -o /dev/null -w "dns: %{time_namelookup} connect: %{time_connect} pretransfer: %{time_pretransfer} starttransfer: %{time_starttransfer} total: %{time_total}\n" ; } # mcd: Makes new Dir and jumps inside mcd() { mkdir -p "$1" && cd "$1"; } # my_ps: List processes owned by my user my_ps() { ps $@ -u $USER -o pid,%cpu,%mem,start,time,bsdtime,command ; } # list all folders in PATH environment variable more readable (non existent folders in red) function paths { IFS=$':' for i in $PATH; do if [ -d $(eval echo $i) ]; then echo $i; else echo -e "\033[0;31m$i\033[0m"; fi; done; unset IFS } # psg: grep for a process psg() { FIRST=`echo $1 | sed -e 's/^\(.\).*/\1/'` REST=`echo $1 | sed -e 's/^.\(.*\)/\1/'` ps aux | grep "[$FIRST]$REST" } # ql: Opens any file in MacOS Quicklook Preview ql() { qlmanage -p "$*" >& /dev/null; } # showa: to remind yourself of an alias (given some part of it) showa() { /usr/bin/grep --color=always -i -a1 $@ ~/Library/init/bash/aliases.bash | grep -v '^\s*$' | less -FSRXc ; } # spotlight: Search for a file using MacOS Spotlight's metadata spotlight() { mdfind "kMDItemDisplayName == '$@'wc"; } # trash: Moves a file to the MacOS trash trash() { command mv "$@" ~/.Trash ; } # mans: Search manpage given in agument '1' for term given in argument '2' (case insensitive) displays paginated result with colored search terms and two lines surrounding each hit. mans() { man $1 | grep -iC2 --color=always $2 | less } # ii: display useful host related informaton ii() { echo -e "$(tput setaf 5)You are logged on:$(tput sgr0) " ; echo $(hostname | sed -e 's/\..*//') echo -e "$(tput setaf 5)Additionnal information:$(tput sgr0) " ; uname -a echo -e "$(tput setaf 5)Users logged on:$(tput sgr0) " ; w -h echo -e "$(tput setaf 5)Current date :$(tput sgr0) " ; date echo -e "$(tput setaf 5)Machine stats :$(tput sgr0) " ; uptime echo -e "$(tput setaf 5)Current network location :$(tput sgr0) " ; scselect echo -e "$(tput setaf 5)Public facing IP Address :$(tput sgr0) " ; myip ; echo "" echo -e "$(tput setaf 5)Geographical information :$(tput sgr0) " ; curl ipinfo.io #echo -e "\n${RED}DNS Configuration:$PS_CLEAR " ; scutil --dns echo } <file_sep>/temp/sh/temp.fish-colours.sh set fish_color_error ff8a00 # c0 to c4 progress from dark to bright # ce is the error colour set -g c0 (set_color 005284) set -g c1 (set_color 0075cd) set -g c2 (set_color 009eff) set -g c3 (set_color 6dc7ff) set -g c4 (set_color ffffff) set -g ce (set_color $fish_color_error) <file_sep>/scripts/set_keyboard_preferences.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then echo "Loading functions file (1)" source _functions.sh elif [ -f ../_functions.sh ]; then echo "Loading functions file (2)" source ../_functions.sh else echo "Config file functions.sh does not exist" fi if [ -f config.sh ]; then echo "Loading config file (1)" source config.sh elif [ -f ../config.sh ]; then echo "Loading config file (2)" source ../config.sh else echo "Config file config.sh does not exist" fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - set_preferences() { # execute 'defaults write NSGlobalDomain AppleKeyboardUIMode -int 3' \ # 'Enable full keyboard access for all controls' execute 'defaults write NSGlobalDomain ApplePressAndHoldEnabled -bool false' \ 'Disable press-and-hold in favor of key repeat' execute 'defaults write NSGlobalDomain "InitialKeyRepeat_Level_Saved" -int 15' \ 'Set delay until repeat' execute 'defaults write NSGlobalDomain KeyRepeat -int 2' \ 'Set the key repeat rate to fast' execute 'defaults write NSGlobalDomain NSAutomaticQuoteSubstitutionEnabled -bool false' \ 'Disable smart quotes' execute 'defaults write NSGlobalDomain NSAutomaticDashSubstitutionEnabled -bool false' \ 'Disable smart dashes' } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { print_in_purple '\n Keyboard\n\n' set_preferences } main<file_sep>/scripts/install_dotfiles.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi declare -a FILES_TO_SYMLINK=( 'dotfiles/bash_aliases' 'dotfiles/bash_autocomplete' 'dotfiles/bash_colors' 'dotfiles/bash_exports' 'dotfiles/bash_functions' 'dotfiles/bash_logout' 'dotfiles/bash_options' 'dotfiles/bash_profile' 'dotfiles/bash_prompt' 'dotfiles/bashrc' # 'shell/curlrc' # 'shell/inputrc' # 'dotfiles/screenrc' ) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { local i='' local sourceFile='' local targetFile='' # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - for i in ${FILES_TO_SYMLINK[@]}; do sourceFile="$(cd .. && pwd)/$i" targetFile="$HOME/.$(printf "%s" "$i" | sed "s/.*\/\(.*\)/\1/g")" if [ ! -e "$targetFile" ]; then cp $sourceFile $targetFile else ask_for_confirmation "'$targetFile' already exists, do you want to overwrite it?" if answer_is_yes; then cp -rf $sourceFile $targetFile else print_error "$targetFile → $sourceFile" fi fi done print_result $? 'Dotfiles' } main <file_sep>/scripts/install_nzbtomedia.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { if ! folder_exists $NZBTOMEDIA_FOLDER; then if [ "${NZBTOMEDIA_FOLDER}" == "" ] ; then echo "Error: Not all config setting have been found set, please check config.sh." exit 1 fi ask_for_sudo sudo mkdir -p $NZBTOMEDIA_FOLDER sudo chown -R `whoami`:staff $NZBTOMEDIA_FOLDER git clone https://github.com/clinton-hall/nzbToMedia.git $NZBTOMEDIA_FOLDER print_result $? 'Download NzbToMedia' fi ln -s /usr/bin/python2.7 /usr/local/bin/python2 print_result $? 'NzbToMedia' } main <file_sep>/bin/spotweb/addrating.php <?php // AddRating // // This script will add IMDB ratings to the spot title, like: "Movietitle (2014) release info [6.5] // It will also adjust the spot rating, based on the IMDB rating // The script assumes the spot title syntax is like: "Movie title (year) release info" // // Original code from MR_Blobby http://gathering.tweakers.net/forum/list_message/43647658#43647658 // Edited by Rowdy - http://rowdy.nl // ==================================================================================================================== // PARAMETERS, ESIT FOR YOUR INSTALLATION // ==================================================================================================================== // Location of Spotweb db settings file $dbsettingsfile = "/Users/Plex/Spotweb/dbsettings.inc.php"; // Should we send some output? Ie for logging use: php addrating.php >> /var/log/spotweb $quiet = false; $timestamp = false; // Timestamp in logging // Age of spots to query for (in seconds): $age = 86400; // 1 day // Minimum string similarity between movie title from spot and movie title from IMDB (http://php.net/manual/en/function.similar-text.php) // Percentage (100 is exact match): $min_similar_text = 75; // set the default timezone to use. Available since PHP 5.1 date_default_timezone_set('CET'); // ==================================================================================================================== // DO NOT EDIT BELOW // ==================================================================================================================== // Show that we are starting doLog("Started rating of movies"); $found = 0; $rated = 0; // Create MySQL connection (fill in correct values): require($dbsettingsfile); $con = mysqli_connect($dbsettings['host'], $dbsettings['user'], $dbsettings['pass'], $dbsettings['dbname']); // Initiate the IMDB class: require("./imdb.php"); $imdb = new Imdb(); // Check connection: if (mysqli_connect_errno($con)) doLog("Failed to connect to MySQL: " . mysqli_connect_error()); else { // Connection is ok $timestamp = time() - $age; // This query will return all x264 movies (category 0 is "images", subcatz z0 is "movies" and subcata a09 is "x264"): $query = "SELECT * FROM spots WHERE category=0 AND subcatz='z0|' AND subcata='a9|' AND stamp>" . $timestamp . " ORDER BY stamp"; $result = mysqli_query($con,$query); // Process all results: while ($row = mysqli_fetch_array($result)) { $found++; $title = str_replace("&period;", ".", $row['title']); doLog("Spot: ".$title."(".$row['messageid'].")"); // Regular expression to try to get a "clean" movietitle from the spot title (all text until "year"): if ((preg_match('/(.+)[ \(\.]((19|20)\d{2})/', $title, $matches)) == 1) { $title_from_spot = trim($matches[1]); $year = trim($matches[2]); $title_from_spot = str_replace(".", " ", $title_from_spot); doLog("Using as title \"".$title_from_spot."\", year: ".$year); // Search movie info from IMDB: $movieArray = $imdb->getMovieInfo($title_from_spot . " (" . $year . ")", False); if (isset($movieArray['title_id']) and !empty($movieArray['title_id'])) { // Succesfully found $imdb_year = trim($movieArray['year']); $imdb_title = $movieArray['title']; $imdb_url = $movieArray['imdb_url']; // Calculate the similarity between the movietitle from the spot and the movietitle found in IMDB: $percent = compareTitles(strtolower($title_from_spot), strtolower($imdb_title)); doLog("Found: ".$imdb_title." (".$imdb_year."), ".round($percent, 2)."% match"); // Assume the correct movie is found in IMDB when the similarity is higher then defined and the year from IMDB is the same as from the spot: if (($imdb_year == $year) and ($percent >= $min_similar_text)) { $imdb_rating = $movieArray['rating']; if (!empty($imdb_rating)) { // Rating found if ((preg_match('/(.+)( \[\d\.\d\])/', $title, $matches)) == 1) // If the rating had already been added to the title, strip it $title = $matches[1]; // Add the rating to the spot title: $newtitle = str_replace(".", "&period;", $title)." [".$imdb_rating."]"; $updateresult = mysqli_query($con, "UPDATE spots SET title = '".$newtitle."' WHERE id = ".$row['id']); $spotrating = 0; // Calculate the spotrating based on imdb rating (only valid spotrating when imdb rating is at least 6.0): if ($imdb_rating >= 6.0) {$spotrating = 1;} if ($imdb_rating >= 6.2) {$spotrating = 2;} if ($imdb_rating >= 6.4) {$spotrating = 3;} if ($imdb_rating >= 6.6) {$spotrating = 4;} if ($imdb_rating >= 6.8) {$spotrating = 5;} if ($imdb_rating >= 7.0) {$spotrating = 6;} if ($imdb_rating >= 7.2) {$spotrating = 7;} if ($imdb_rating >= 7.4) {$spotrating = 9;} if ($imdb_rating >= 7.6) {$spotrating = 10;} setSpotRating($con, $spotrating, $row['id']); doLog("Rating of ".$imdb_rating." found. Spotrating ".$spotrating." set."); $rated++; } else { // Clear spotrating if no rating found in IMDB setSpotRating($con, 0, $row['id']); doLog("No rating found found"); } } else { // Clear spotrating if the correct movie is not found in IMDB setSpotRating($con, 0, $row['id']); doLog("No matching movie found"); } } else { // Clear spotrating if no movie is found in IMDB setSpotRating($con, 0, $row['id']); doLog("No movie found"); } } else { // Clear spotrating if the movie title could not be extracted from the spot title setSpotRating($con, 0, $row['id']); doLog("No title found"); } } // Close MySQL connection: mysqli_close($con); doLog($found." movies processed, of wich ".$rated." rated"); } // ==================================================================================================================== // Functions // ==================================================================================================================== function doLog($message) { global $quiet; global $timestamp; if(!$quiet) { if($timestamp) echo date(DATE_ATOM)." "; echo $message.PHP_EOL; } } //Strip titles and compare function compareTitles($string1, $string2) { //Replace HTML characters $string1 = html_entity_decode($string1, ENT_QUOTES); $string2 = html_entity_decode($string2, ENT_QUOTES); //Lowercase $string1 = strtolower($string1); $string2 = strtolower($string2); //Remove unnecessary characters $string1 = preg_replace('~[^A-Za-z0-9]~', "", $string1); $string2 = preg_replace('~[^A-Za-z0-9]~', "", $string2); //Do we have a match? similar_text($string1, $string2, $percentage); return $percentage; } function setSpotRating($con, $rating, $id) { $updateresult = mysqli_query($con, "UPDATE spots SET spotrating = '".$rating."' WHERE id = ".$id); } ?> <file_sep>/scripts/install_osx_pip_cheetah.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { ## Sanity check if ! cmd_exists 'pip'; then print_error 'pip required' fi ## Let's do it if ! cmd_exists 'cheetah'; then ask_for_sudo sudo -H pip install cheetah fi print_result $? 'cheetah' } main<file_sep>/README.md # OSX_MediaCenter ######El Capitan edition ![minions](img/cheering_minions.gif) ![El_Capitan](img/elcapitan_64x64.jpg) ![OSX_Server](img/osx_server_64x64.jpg) ![Plex_Client](img/plex_client_64x64.jpg) ![Plex_Server](img/plex_server_64x64.png) ![SABnzbd](img/sabnzbd_64x64.png) ![SickBeard](img/sickBeard_64x64.png) ![CouchPotato](img/couchpotato_64x64.png) ![Trakt](img/trakt_64x64.png) Note: ===== A clean install will erase all of the contents on your disk drive. Make sure to back up your important files, settings and apps before proceeding. If needed, upgrade the system to [El Capitan](https://itunes.apple.com/nl/app/os-x-el-capitan/id1018109117) Performing a clean install: 1. Restart your Mac and hold down the Command key and the R key (cmd⌘+R). Press and hold these keys until the Apple logo appears. 2. For a clean install, open up Disk Utility and erase your main hard drive. Once you've done so, you can go back to the Install OS X Mavericks disk and choose "Install a new copy of OS X." Install ===== ###### OS X Additions - [x] Cheetah - [ ] Dotfiles * [x] bash_aliases * [x] bash_autocomplete * [x] bash_exports * [x] bash_functions * [x] bash_options * [x] bash_profile * [x] bash_prompt - [x] HomeBrew * [x] ffmpeg - [x] MySQL - [x] OS X Server - [x] Python PIP (Package Manager) * [x] Python LXML ###### Applications - [x] Auto-Sub (https://github.com/BenjV/autosub) :small_red_triangle: * [x] LaunchAgent - [x] CouchPotato (https://couchpota.to) * [x] LaunchAgent * [ ] WebApp Proxy * [ ] SabNZBD+ integration * [ ] Spotweb integration - [ ] NewzNAB - [x] NzbToMedia - [ ] Plex Home Theater - [ ] Plex Media Server * [ ] Channel: Custom app store * [x] Channel: HelloHue (https://github.com/ledge74/HelloHue) * [x] Channel: TraktTV - [x] SABnzbd+ * [x] LaunchAgent * [ ] WebApp Proxy * [x] Folder creation * [x] NzbToMedia (SickBeard) - [-] SickBeard -> Replaced by Sonarr * [x] LaunchAgent * [ ] WebApp Proxy * [x] SABnzbd+ integration (text step-by-step, not (yet) automated) * [x] Spotweb integration (text step-by-step, not (yet) automated) :small_red_triangle: - [x] Sonarr * [ ] WebApp Proxy - [x] Spotweb :small_red_triangle: * [x] API enablement check * [x] LaunchAgent: Periodic retrieval * [x] SabNZBD+ integration (text step-by-step, not (yet) automated) - [ ] etc. Usefull links: ===== ###### Plex Information page(s) - Client names: https://plex.tv/devices.xml - User names: http://app.plex.tv/web/app#!/settings/users - Friend names: https://plex.tv/pms/friends/all - Current sessions: http://localhost:32400/status/sessions ###### Hue informatino page(s) - Hue bridge IP: https://www.meethue.com/api/nupnp ###### OS X Server - /Library/Server/Web/Config/apache2/sites/ - /Library/Server/Web/Config/Apache2/httpd_server_app.conf - /Library/Server/web/config/apache2/httpd_server_app.conf.default - sudo serveradmin settings web:definedWebApps - sudo serveradmin start web / sudo serveradmin stop web - sudo serveradmin fullstatus web - sudo serveradmin settings web - sudo serveradmin command web:command=restoreFactorySettings - http://jason.pureconcepts.net/2014/11/configure-apache-virtualhost-mac-os-x/ - https://clickontyler.com/support/a/41/osx-server-app-virtualhostx/ - http://matt.coneybeare.me/how-to-map-plex-media-server-to-your-home-domain/ - https://discussions.apple.com/thread/3566643?start=0&tstart=0 - http://www.themacosxserveradmin.com/2011_09_01_archive.html - http://gathering.tweakers.net/forum/list_messages/1641228 - http://smashingfiasco.com/setting-up-aspnetmono-on-mac-os-server.html - http://serverfault.com/questions/441722/apache-2-2-on-mountain-lion-ignoring-proxypass-and-sending-request-to-documentro ###### Github - sphp https://github.com/conradkleinespel/sphp-osx ###### lsd error - sudo mkdir /private/var/db/lsd - xattr -wr com.apple.finder.copy.source.checksum#N 4 /private/var/db/lsd - xattr -wr com.apple.metadata:_kTimeMachineNewestSnapshot 50 /private/var/db/lsd - xattr -wr com.apple.metadata:_kTimeMachineOldestSnapshot 50 /private/var/db/lsd - sudo touch /private/var/db/lsd/com.apple.lsdschemes.plist - sudo /usr/libexec/repair_packages --repair --standard-pkgs --volume / - https://support.apple.com/en-us/HT203129 ###### OS X Server WebApp - Running Node.js + Ghost as a webapp on OS X Mavericks with Server 3.2 (https://gist.github.com/joey-coleman/11111811) - Creating a apache-proxy webapp on OS X using Server.app (https://gist.github.com/joey-coleman/10016371) - Configuring Jenkins on OS X Server (http://pablin.org/2015/04/30/configuring-jenkins-on-os-x-server/) - unning Django webapps with OS X Server.app (http://jelockwood.blogspot.nl/2013/06/running-django-webapps-with-os-x.html) ###### Other - https://github.com/spotweb/spotweb/wiki/Performance-tips - https://github.com/bstascavage/plexReport or https://github.com/jakewaldron/PlexEmail ###### Sed - sudo sed -i "s/^;date.timezone =.*/date.timezone = Europe\/Amsterdam/" /etc/php5/*/php.ini - sudo sed -i 's/"$/:\/usr\/local\/mysql\/bin"/' /etc/environment - sudo sed -i 's/basedir = \/usr/basedir =\/usr\/local\/mysql/' /etc/mysql/my.cnf - sudo sed -i 's/lc-messages-dir = \/usr\/share\/mysql/lc-messages-dir = \/usr\/local\/mysql\/share\nlc-messages =en_GB\n/' /etc/mysql/my.cnf - sudo sed -i 's/myisam-recover /myisam-recover-options /' /etc/mysql/my.cnf - sudo sed -i 's/key-buffer /key-buffer-size /' /etc/mysql/my.cnf - sed -i '/bind-address/d' /etc/mysql/my.cnf ###### Food for Thought - http://stackoverflow.com/questions/26493762/yosemite-el-capitan-php-gd-mcrypt-installation - http://www.michaelbagnall.com/blogs/php-gd-fixing-your-php-server-mac-os-x-without-homebrewmacports - https://github.com/ElusiveMind/osx_server_enhancements - https://github.com/philcook/brew-php-switcher - https://www.reddit.com/r/PleX/wiki/tools ###### PHP Extentions - mkdir -p /usr/local/php5530_ext ###### gettext - cd ~/Github/osx_server_enhancements/packages/php-5.5.30/ext/gettext - phpize - ./configure --with-gettext=/usr/local/opt/gettext - make clean - make - INSTALL_ROOT=/usr/local/php5530_ext make install ###### gd - cd ~/Github/osx_server_enhancements/packages/php-5.5.30/ext/gd - phpize - sudo CFLAGS="-arch x86_64 -g -Os -pipe -no-cpp-precomp" CCFLAGS="-arch x86_64 -g -Os -pipe" CXXFLAGS="-arch x86_64 -g -Os -pipe" LDFLAGS="-arch x86_64 -bind_at_load" './configure' '--prefix=/usr' '--mandir=/usr/share/man' '--infodir=/usr/share/info' '--with-config-file-path=/etc/' '--with-config-file-scan-dir=/opt/local/var/db/php5' '--enable-bcmath' '--enable-ctype' '--enable-dom' '--enable-fileinfo' '--enable-filter' '--enable-hash' '--enable-json' '--enable-libxml' '--enable-pdo' '--enable-phar' '--enable-session' '--enable-simplexml' '--enable-tokenizer' '--enable-xml' '--enable-xmlreader' '--enable-xmlwriter' '--with-bz2=/opt/local' '--with-mhash=/opt/local' '--with-pcre-regex=/opt/local' '--with-readline=/opt/local' '--with-libxml-dir=/opt/local' '--with-zlib=/opt/local' '--disable-cgi' '--with-ldap=/usr' '--with-apxs2=/opt/local/apache2/bin/apxs' '--with-mysqli=/usr/local/mysql/bin/mysql_config' '--with-openssl' '--with-mcrypt=/opt/local/' '--with-mysql=/usr/local/mysql-5.1.42-osx10.6-x86_64/' '--with-iconv=/usr' '--with-curl=/opt/local' '--enable-mbstring' '--with-gd' '--with-jpeg-dir=/opt/local' '--with-png-dir=/opt/local' '--with-freetype-dir=/opt/local' '--enable-gd-native-ttf' --with-ttf - make clean - make - INSTALL_ROOT=/usr/local/php5530_ext make install ####### /Library/Server/Web/Config/php/extensions.ini extension=/usr/local/php5530_ext/usr/lib/php/extensions/no-debug-non-zts-20121212/gd.so extension=/usr/local/php5530_ext/usr/lib/php/extensions/no-debug-non-zts-20121212/gettext.so ###### Installing something new - curl https://install.meteor.com/ | sh - https://github.com/lokenx/plexrequests-meteor - https://github.com/ITRav4/PlexRedirect ###### Installing something new - Netdata - https://github.com/Kuroyukihimeeee/PlexRedirect - https://github.com/firehol/netdata - https://github.com/firehol/netdata/issues/52 - $ ./netdata-installer.sh --install /opt - $ sudo dseditgroup -o create Netdata - $ dscl . -read /Groups/Netdata - $ dscl . search /Groups GroupMembership Netdata - $ killall netdata - $ /opt/netdata/usr/sbin/netdata ####### Check php -i ####### Tweaks Safari - enable Safari’s debug menu: defaults write com.apple.Safari IncludeInternalDebugMenu 1 - disable Safari autoplay video: Safari > Debug > Media Flags and select Disallow Inline Video ####### Fix slow starting Terminal sudo rm /private/var/log/asl/*.asl <file_sep>/scripts/brew_update.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then echo "Loading functions file (1)" source _functions.sh elif [ -f ../_functions.sh ]; then echo "Loading functions file (2)" source ../_functions.sh else echo "Config file functions.sh does not exist" fi if [ -f config.sh ]; then echo "Loading config file (1)" source config.sh elif [ -f ../config.sh ]; then echo "Loading config file (2)" source ../config.sh else echo "Config file config.sh does not exist" fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { if cmd_exists 'brew'; then execute 'brew update' 'brew (update)' execute 'brew upgrade --all' 'brew (upgrade)' fi } main<file_sep>/scripts/install_osx_server.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { if ! folder_exists "$FOLDER_INSTALL/Server.app"; then DMG_FILE="$FOLDER_INSTALL/OS_X_Server_5.0.15.dmg" if file_exists "$DMG_FILE"; then ask_for_sudo install_dmg "$DMG_FILE" else if folder_exists "$FOLDER_INSTALL/Server.app"; then ask_for_sudo cp -R "$FOLDER_INSTALL/Server.app" "/Applications/Server.app" else print_error 'OS X Server App file NOT found in $FOLDER_INSTALL!\n' exit 1 fi fi fi print_result $? 'OS X Server' } main<file_sep>/temp/sh/tst_sed_get_var.sh #!/bin/bash # sabnzbd.ini # api_key # nzb_key ## Notes # http://serverfault.com/questions/419533/edit-a-file-via-bash-script ## Working # sed -n -e '/^api_key/ s/.*\= *//p' sabnzbd.ini function sedeasy { if [ $# -ne 3 ]; then echo "usage: sedasy CURRENT REPLACEMENT FILENAME" return fi sed -i "s/$(echo $1 | sed -e 's/\([[\/.*]\|\]\)/\\&/g')/$(echo $2 | sed -e 's/[\/&]/\\&/g')/g" $3 } sed_replace_in_file() { if [ "$#" != 3 ]; then echo "Usage: greplace file_pattern search_pattern replacement" return 1 else file_pattern=$1 search_pattern=$2 replacement=$3 # This works with BSD grep and the sed bundled with OS X. # GNU grep takes `-Z` instead of `--null`. # Other versions of sed may not support the `-i ''` syntax. find . -name "$file_pattern" -exec grep -lw --null "$search_pattern" {} + | xargs -0 sed -i '' "s/[[:<:]]$search_pattern[[:>:]]/$replacement/g" fi } sed_find_var_in_file() { if [ "$#" != 2 ]; then echo "Usage: sed_find_in_file file_name search_pattern" return 1 else file_name=$1 search_pattern=$2 sed -n -e '/'$search_pattern'/ s/.*\= *//p' $file_name fi } #echo $(sed_find_var_in_file 'sabnzbd.ini' '^api_key') echo $(sed_replace_in_file 'sabnzbd.ini' 'dir = ""' 'dir = "assd"') <file_sep>/scripts/osx_xcode.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { if ! xcode-select --print-path &> /dev/null; then # Prompt user to install the XCode Command Line Tools xcode-select --install &> /dev/null # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Wait until the XCode Command Line Tools are installed until xcode-select --print-path &> /dev/null; do sleep 5 done print_result $? 'Install XCode Command Line Tools' # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Point the `xcode-select` developer directory to # the appropriate directory from within `Xcode.app` # https://github.com/alrra/dotfiles/issues/13 sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer print_result $? 'Make "xcode-select" developer directory point to Xcode' # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Prompt user to agree to the terms of the Xcode license # https://github.com/alrra/dotfiles/issues/10 sudo xcodebuild -license print_result $? 'Agree with the XCode Command Line Tools licence' fi print_result $? 'XCode Command Line Tools' } main<file_sep>/scripts/set_xcode_preferences.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then echo "Loading functions file (1)" source _functions.sh elif [ -f ../_functions.sh ]; then echo "Loading functions file (2)" source ../_functions.sh else echo "Config file functions.sh does not exist" fi if [ -f config.sh ]; then echo "Loading config file (1)" source config.sh elif [ -f ../config.sh ]; then echo "Loading config file (2)" source ../config.sh else echo "Config file config.sh does not exist" fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - set_preferences() { execute 'xcrun simctl delete unavailable' \ 'Remove unavailable simulators' } main() { print_in_purple '\n Xcode\n\n' set_preferences killall 'Xcode' &> /dev/null } main<file_sep>/dotfiles/_backup.1/bash_aliases #!/bin/bash # Detect which `ls` flavor is in use if ls --color > /dev/null 2>&1; then # GNU `ls` colorflag="--color" else # OS X `ls` colorflag="-G" fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Easier navigation alias ~="cd ~" # ~: Go Home alias cd..='cd ../' # Go back 1 directory level (for fast typers) alias ..='cd ../' # Go back 1 directory level alias ...='cd ../../' # Go back 2 directory levels alias .3='cd ../../../' # Go back 3 directory levels alias .4='cd ../../../../' # Go back 4 directory levels alias .5='cd ../../../../../' # Go back 5 directory levels alias .6='cd ../../../../../../' # Go back 6 directory levels alias -- -="cd -" # Shortcuts alias h="history" # List files alias ll='ls -FGlAhp' # Preferred 'ls' implementation alias l="ls -lF ${colorflag}" # List all files colorized in long format alias la="ls -laF ${colorflag}" # List all files colorized in long format, including dot files alias lsd="ls -lF ${colorflag} | grep --color=never '^d'" # List only directories alias ls="command ls ${colorflag}" # Always use color output for `ls #export LS_COLORS='no=00:fi=00:di=01;34:ln=01;36:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.gz=01;31:*.bz2=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.avi=01;35:*.fli=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.ogg=01;35:*.mp3=01;35:*.wav=01;35:' alias cp='cp -iv' # Preferred 'cp' implementation alias mv='mv -iv' # Preferred 'mv' implementation alias mkdir='mkdir -pv' # Preferred 'mkdir' implementation #alias edit='subl' # edit: Opens any file in sublime editor alias f='open -a Finder ./' # f: Opens current directory in MacOS Finder alias which='type -all' # which: Find executables alias path='echo -e ${PATH//:/\\n}' # path: Echo all executable Paths alias show_options='shopt' # Show_options: display bash options settings alias fix_stty='stty sane' # fix_stty: Restore terminal settings when screwed up alias cic='set completion-ignore-case On' # cic: Make tab-completion case-insensitive alias battery='ioreg -w0 -l | grep Capacity | cut -d " " -f 17-50' # display battery info alias DT='tee ~/Desktop/terminalOut.txt' # DT: Pipe content to file on MacOS Desktop alias grep='grep --color=auto' alias less='less -FSRXc' # Preferred 'less' implementation alias updatedb="sudo /usr/libexec/locate.updatedb" # Get OS X Software Updates, and update installed Ruby gems, Homebrew, npm, and their installed packages alias update='sudo softwareupdate -i -a; brew update; brew upgrade --all; brew cleanup; npm install npm -g; npm update -g; sudo gem update --system; sudo gem update' # Flush Directory Service cache alias clear-dns-cache='dscacheutil -flushcache && killall -HUP mDNSResponder' # Clean up LaunchServices to remove duplicates in the “Open With” menu alias lscleanup="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -domain local -domain system -domain user && killall Finder" # View HTTP traffic alias sniff="sudo ngrep -d 'en1' -t '^(GET|POST) ' 'tcp and port 80'" alias httpdump="sudo tcpdump -i en1 -n -s 0 -w - | grep -a -o -E \"Host\: .*|GET \/.*\"" # Trim new lines and copy to clipboard alias c="tr -d '\n' | pbcopy" # Hide/Show hidden files in Finder alias hide-hidden-files='defaults write com.apple.finder AppleShowAllFiles -bool false && killall Finder' alias show-hidden-files='defaults write com.apple.finder AppleShowAllFiles -bool true && killall Finder' # Hide/show all desktop icons (useful when presenting) alias hidedesktop="defaults write com.apple.finder CreateDesktop -bool false && killall Finder" alias showdesktop="defaults write com.apple.finder CreateDesktop -bool true && killall Finder" # Disable/Enable Spotlight alias spotoff="sudo mdutil -a -i off" alias spoton="sudo mdutil -a -i on" # PlistBuddy alias, because sometimes `defaults` just doesn’t cut it alias plistbuddy="/usr/libexec/PlistBuddy" # Ring the terminal bell, and put a badge on Terminal.app’s Dock icon (useful when executing time-consuming commands) alias badge="tput bel" # Intuitive map function # For example, to list all directories that contain a certain file: # find . -name .gitattributes | map dirname alias map="xargs -n1" # Lock the screen (when going AFK) alias afk="/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend" # Reload the shell (i.e. invoke as a login shell) alias reload="exec $SHELL -l" <file_sep>/scripts/install_pms_channel_trakttv-beta.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ## https://forums.plex.tv/discussion/102818/rel-trakt ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { ## Sanity check if [ "${PLEX_PMS_TRAKTTV}" == "" ]; then echo "Error: Not all config setting have been found set, please check config.sh." exit 1 fi ## Let's do it if ! folder_exists $PLEX_PMS_TRAKTTV; then ask_for_sudo sudo mkdir -p $PLEX_PMS_TRAKTTV sudo chown -R `whoami`:staff $PLEX_PMS_TRAKTTV git clone -b beta https://github.com/trakt/Plex-Trakt-Scrobbler.git $PLEX_PMS_TRAKTTV print_result $? 'Download PMS channel TraktTV' ln -s $PLEX_PMS_TRAKTTV/Trakttv.bundle $HOME/Library/Application\ Support/Plex\ Media\ Server/Plug-ins/TraktTV-beta.bundle fi print_result $? 'Plex PMS - TraktTV' } main <file_sep>/scripts/install_plex_pms_email.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { if ! file_exists '/Users/Plex/PlexEmail/scripts/plexEmail.py'; then ask_for_sudo sudo easy_install requests cd /Users/Plex git clone https://github.com/jakewaldron/PlexEmail.git nano PlexEmail/scripts/config.conf # python plexEmail.py -t fi print_result $? 'Plex E-mail' } main <file_sep>/scripts/install_sickrage.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { if ! folder_exists $SICKRAGE_FOLDER; then if [ "${SICKRAGE_FOLDER}" == "" ] ; then echo "Error: Not all config setting have been found set, please check config.sh." exit 1 fi ask_for_sudo sudo mkdir -p $SICKRAGE_FOLDER sudo chown -R `whoami`:staff $SICKRAGE_FOLDER git clone https://github.com/SiCKRAGETV/SickRage.git $SICKRAGE_FOLDER print_result $? 'Download SickRage' fi # cd $SICKRAGE_FOLDER # python SickBeard.py # #python sickbeard.py -d # # open http://localhost:8081/ # echo " --- press any key to continue ---" # read -n 1 -s print_result $? 'Sickbeard' } main <file_sep>/dotfiles/bash_prompt #!/bin/bash # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - enable_color_support() { #declare DOTFILES_DIR_PATH="$(dirname $(dirname $(readlink $BASH_SOURCE)))" if [[ $COLORTERM == gnome-* && $TERM == xterm ]] && infocmp gnome-256color &> /dev/null; then export TERM='gnome-256color' elif infocmp xterm-256color &> /dev/null; then export TERM='xterm-256color' fi } is_git_repo() { git rev-parse --is-inside-work-tree &> /dev/null } get_git_branch() { local branch_name # Get the short symbolic ref branch_name=$(command git symbolic-ref --quiet --short HEAD 2> /dev/null) || # If HEAD isn't a symbolic ref, get the short SHA branch_name=$(command git rev-parse --short HEAD 2> /dev/null) || # Otherwise, just give up branch_name="(unknown)" echo $branch_name } # Git status information function prompt_git() { local git_info git_state uc us ut st if ! is_git_repo; then return 1 fi git_info=$(get_git_branch) # Check for uncommitted changes in the index if ! `command git diff --quiet --ignore-submodules --cached`; then uc="+" fi # Check for unstaged changes if ! `command git diff-files --quiet --ignore-submodules --`; then us="!" fi # Check for untracked files if [ -n "$(command git ls-files --others --exclude-standard)" ]; then ut="?" fi # Check for stashed files if `command git rev-parse --verify refs/stash &>/dev/null`; then st="$" fi git_state=$uc$us$ut$st # Combine the branch name and state information if [[ $git_state ]]; then git_info="$git_info[$git_state]" fi printf " on ${YELLOW}git:${git_info}" } set_prompts() { local black='' blue='' bold='' cyan='' green='' orange='' \ purple='' red='' reset='' white='' yellow='' if [ -x /usr/bin/tput ] && tput setaf 1 &> /dev/null; then tput sgr0 # Reset colors bold=$(tput bold) reset=$(tput sgr0) # Solarized colors # https://github.com/altercation/solarized/tree/master/iterm2-colors-solarized#the-values black=$(tput setaf 0) blue=$(tput setaf 33) cyan=$(tput setaf 37) green=$(tput setaf 64) orange=$(tput setaf 166) magenta=$(tput setaf 9) purple=$(tput setaf 125) red=$(tput setaf 124) white=$(tput setaf 15) yellow=$(tput setaf 136) else bold='' reset="\e[0m" black="\e[1;30m" blue="\e[1;34m" cyan="\e[1;36m" green="\e[1;32m" magenta="\e[1;31m" orange="\e[1;33m" purple="\e[1;35m" red="\e[1;31m" white="\e[1;37m" yellow="\e[1;33m" fi # Highlight the user name when logged in as root. if [[ "${USER}" == "root" ]]; then userStyle="${red}"; else userStyle="${orange}"; fi; # Highlight the hostname when connected via SSH. if [[ "${SSH_TTY}" ]]; then hostStyle="${bold}${red}"; else hostStyle="${yellow}"; fi; # Prompt Statement variables # http://ss64.com/bash/syntax-prompt.html # ------------------------------------------------------------------ # | PS1 - Default interactive prompt | # ------------------------------------------------------------------ symbol="λ " PS1="\[\033]0;\w\007\]"; PS1+="\[${bold}${white}\]$symbol" # newline PS1+="\[${userStyle}\]\u \[$white\]" # username PS1+="at \[$hostStyle\]\h \[$white\]" # host PS1+="in \[$green\]\${PWD/#\$HOME/~}\[$white\]" # Working directory PS1+="\$(prompt_git)\[$white\]" # Git repository details PS1+="\n → \[$reset\]" export PS1 # ------------------------------------------------------------------ # | PS2 - Continuation interactive prompt | # ------------------------------------------------------------------ PS2="\[$orange\]⚡ \[$reset\]" export PS2 # # ------------------------------------------------------------------ # # | PS4 - Debug prompt | # # ------------------------------------------------------------------ # # # e.g: # # # # The GNU `date` command has the `%N` interpreted sequence while # # other implementations don't (on OS X `gdate` can be used instead # # of the native `date` if the `coreutils` package was installed) # # # # local dateCmd="" # # # # if [ "$(date +%N)" != "N" ] || \ # # [ ! -x "$(command -v 'gdate')" ]; then # # dateCmd="date +%s.%N" # # else # # dateCmd="gdate +%s.%N" # # fi # # # # PS4="+$( tput cr && tput cuf 6 && # # printf "$yellow %s $green%6s $reset" "$($dateCmd)" "[$LINENO]" )" # # # # PS4 output: # # # # ++ 1357074705.875970000 [123] '[' 1 == 0 ']' # # └──┬─┘└────┬───┘ └───┬───┘ └──┬─┘ └──────┬─────┘ # # │ │ │ │ │ # # │ │ │ │ └─ command # # │ │ │ └─ line number # # │ │ └─ nanoseconds # # │ └─ seconds since 1970-01-01 00:00:00 UTC # # └─ depth-level of the subshell # # PS4="+$( tput cr && tput cuf 6 && printf "%s $reset" )" # # export PS4 # PS4 for debugging purposes written intially by awesome @janmoesen for `tilde` # Include the current file and line number when tracing using "set -x". (You # can also include "\$FUNCNAME" to get the currently executing function, if # any.) ps4_parts=( # Same as the default: start with a plus sign that gets repeated based on # the current stack depth. (Bash repeats the first character of PS4.) '+ ' # Make the following extra information stand out less. "${magenta}${bold}" # Show the name of the current shell function, if any. '${FUNCNAME}' # Show the basename and line number of the source file or function, if # any. If there was a function name, put an "@" between the function name # and the file/function. '${BASH_SOURCE:+${FUNCNAME:+@}}' "${orange}" # Note that LINENO is reset from 1 inside a function body. Sometimes, # $LINENO is a negative number. I could not find any reference to this in # the man page, but it seems to have to happen when returning from another # function. Until I understand this more completely, I wrap it in # parentheses to clarify that it is not a regular line number. '${BASH_SOURCE:+${BASH_SOURCE##*/}:${LINENO/#-*/($LINENO)}}' # Use a tab to separate the file/function and line number from the actual # line of code, rather than a space, because this helps legibility. (It # decreases the "jaggedness" caused by differing lengthts of file names # and line numbers.) I prefer this to a newline because it keeps the trace # more compact. $'\t' # Reset the colour and style. "${reset}" ) printf -v PS4 '%s' "${ps4_parts[@]}" export PS4 unset ps4_parts } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { enable_color_support set_prompts } main # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Cleanup unset -f enable_color_support unset -f main unset -f set_prompts <file_sep>/temp/sh/temp.toggle_hidden_files.sh #!/bin/bash value=$(defaults read com.apple.finder AppleShowAllFiles) echo "**************************************************" echo "\"Show All files\" is $value. (0='off' and 1='on')" echo "**************************************************" if [ $value -eq 0 ] then echo "I just turned them on (1)" echo "**************************" defaults write com.apple.finder AppleShowAllFiles 1 && killall Finder else echo "I just turned them off (0)" echo "**************************" defaults write com.apple.finder AppleShowAllFiles 0 && killall Finder fi <file_sep>/scripts/osx_create_directories_media.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - declare -a DIRECTORIES=( "$HOME/Media" "$HOME/Media/Documentary" "$HOME/Media/Movies" "$HOME/Media/Series" ) main() { for i in ${DIRECTORIES[@]}; do mkd "$i" done } main<file_sep>/scripts/install_ffmpeg_homebrew.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi declare -a BREW_PACKAGES=( 'ffmpeg' ) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ## Installing dependencies for ffmpeg: pkg-config, gettext, texi2html, yasm, x264, lame, libvo-aacenc, xvid, l main() { if ! cmd_exists 'brew'; then print_error 'Brew not detected' exit 1; fi local i='' local sourceFile='' local targetFile='' for i in ${BREW_PACKAGES[@]}; do sourceFile=$i if ! cmd_exists "$sourceFile"; then if [ "$sourceFile" == 'ffmpeg' ]; then #sourceFile='ffmpeg --with-fdk-aac --with-ffplay --with-freetype --with-frei0r --with-libass --with-libvo-aacenc --with-libvorbis --with-libvpx --with-opencore-amr --with-openjpeg --with-opus --with-rtmpdump --with-speex --with-theora --with-tools' sourceFile='ffmpeg --with-fdk-aac --with-ffplay --with-freetype --with-libass --with-libquvi --with-libvorbis --with-libvpx --with-opus --with-x265 --with-tools' fi brew install $sourceFile fi print_result $? 'Install '$sourceFile done } main<file_sep>/scripts/osx_init.sh #!/usr/bin/env bash if [ -f _functions.sh ]; then echo "Loading functions file (1)" source _functions.sh elif [ -f ../_functions.sh ]; then echo "Loading functions file (2)" source ../_functions.sh else echo "Config file functions.sh does not exist" fi verify_os || exit 1 ask_for_sudo # Step 1: Update the OS and Install Xcode Tools echo "------------------------------" echo "Updating OSX. If this requires a restart, run the script again." # Install all available updates #sudo softwareupdate -iva # Install only recommended available updates #sudo softwareupdate -irv echo "------------------------------" echo "Installing Xcode Command Line Tools." # Install Xcode command line tools if ! command -v pngout > /dev/null 2>&1 ; then # Prompt user to install the XCode Command Line Tools xcode-select --install &> /dev/null # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Wait until the XCode Command Line Tools are installed until xcode-select --print-path &> /dev/null; do sleep 5 done print_result $? 'Install XCode Command Line Tools' # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Point the `xcode-select` developer directory to # the appropriate directory from within `Xcode.app` # https://github.com/alrra/dotfiles/issues/13 sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer print_result $? 'Make "xcode-select" developer directory point to Xcode' # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Prompt user to agree to the terms of the Xcode license # https://github.com/alrra/dotfiles/issues/10 sudo xcodebuild -license print_result $? 'Agree with the XCode Command Line Tools licence' fi<file_sep>/scripts/install_homebrew.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { if ! cmd_exists 'brew'; then printf "\n" | ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" &> /dev/null # └─ simulate the ENTER keypress fi print_result $? 'Homebrew' } main<file_sep>/config.sh.default #!/usr/bin/env bash ### Copy this file to config.sh ### DO NOT EDIT THIS FILE, BUT EDIT CONFIG.SH INSTEAD ############################################################## ###################### EDITS START HERE ###################### ############################################################## ## Check and install OS X Updates INST_OSX_UPDATES="false" #----------------------------------------------------------- FOLDER_DOWNLOAD="$HOME/Downloads" FOLDER_INSTALL="$HOME/Downloads/Install" ## OSX Settings ENABLE_LIBRARY_VIEW="false" ENABLE_MOUSE_TAPTOCLICK="false" ## MySQL Settings MYSQL_ROOT_UID="root" MYSQL_ROOT_PW="" ## Plex PLEX_UID="" PLEX_PW="" PLEX_PUBLIC="false" PLEX_RELEASE="64-bit" PLEX_PMS_HELLOHUE="/Users/Plex/HelloHue" PLEX_PMS_TRAKTTV="/Users/Plex/TraktTV" PLEX_PMS_WEBTOOLS="/Users/Plex/WebTools" ## PlexPy PLEXPY_FOLDER="/Users/Plex/PlexPy" ## Autosub AUTOSUB_FOLDER="/Users/Plex/Autosub" ## CouchPotato COUCHPOTATO_FOLDER="/Users/Plex/CouchPotato" ## NzbToMedia NZBTOMEDIA_FOLDER="/Users/Plex/NzbToMedia" ## Sickbeard SICKBEARD_FOLDER="/Users/Plex/SickBeard" ## SickRage SICKRAGE_FOLDER="/Users/Plex/SickRage" ## Sonarr SONARR_FOLDER="/Users/Plex/Sonarr" ## Spotweb SPOTWEB_FOLDER="/Users/Plex/Spotweb" SPOTWEB_MYSQL_DB="spotweb" SPOTWEB_MYSQL_UID="spotweb" SPOTWEB_MYSQL_PW="" # Host used to test Internet connection PING_HOST="www.google.com" # Setting some color constants COLOR_GREEN=$'\x1b[0;32m' COLOR_YELLOW=$'\x1b[0;33m' COLOR_RED=$'\x1b[0;31m' COLOR_RESET=$'\x1b[0m' BLUE=$'\x1b[0;34m' # Setting some escaped characters CHAR_CHECKMARK=$'\xE2\x9C\x93' CHAR_XMARK=$'\xE2\x9C\x97' <file_sep>/scripts/tmp_install_pms.sh #!/bin/bash ## https://github.com/mrworf/plexupdate/blob/master/plexupdate.sh ## Initializing if [ -f config.sh ]; then echo "Loading config file (1)" source config.sh elif [ -f ../config.sh ]; then echo "Loading config file (2)" source ../config.sh else echo "Config file config.sh does not exist" fi if [ -z "${BASH_VERSINFO}" ]; then echo "ERROR: You must execute this script with BASH" exit 255 fi # Sanity check if [ "${EMAIL}" == "" -o "${PASS}" == "" ] && [ "${PUBLIC}" == "false" ]; then echo "Error: Need username & password to download PlexPass version. Otherwise run with -p to download public version." exit 1 fi # Remove any ~ or other oddness in the path we're given echo "checking dowload folder: $FOLDER_DOWNLOAD" FOLDER_DOWNLOAD="$(eval cd ${FOLDER_DOWNLOAD// /\\ } ; if [ $? -eq 0 ]; then pwd; fi)" if [ -z "${FOLDER_DOWNLOAD}" ]; then echo "Error: Download directory does not exist or is not a directory" exit 1 fi ################################################################# # Don't change anything below this point # KEEP=no # Current pages we need - Do not change unless Plex.tv changes again PLEX_URL_LOGIN=https://plex.tv/users/sign_in PLEX_URL_DOWNLOAD=https://plex.tv/downloads?channel=plexpass PLEX_URL_DOWNLOAD_PUBLIC=https://plex.tv/downloads # If user wants, we skip authentication, but only if previous auth exists if [ "${KEEP}" != "yes" -o ! -f /tmp/kaka ] && [ "${PUBLIC}" == "no" ]; then echo -n "Authenticating..." # Clean old session rm /tmp/kaka 2>/dev/null # Get initial seed we need to authenticate SEED=$(wget --save-cookies /tmp/kaka --keep-session-cookies ${URL_LOGIN} -O - 2>/dev/null | grep 'name="authenticity_token"' | sed 's/.*value=.\([^"]*\).*/\1/') if [ $? -ne 0 -o "${SEED}" == "" ]; then echo "Error: Unable to obtain authentication token, page changed?" exit 1 fi # Build post data echo -ne >/tmp/postdata "$(keypair "utf8" "&#x2713;" )" echo -ne >>/tmp/postdata "&$(keypair "authenticity_token" "${SEED}" )" echo -ne >>/tmp/postdata "&$(keypair "user[login]" "${EMAIL}" )" echo -ne >>/tmp/postdata "&$(keypair "user[password]" "${PASS}" )" echo -ne >>/tmp/postdata "&$(keypair "user[remember_me]" "0" )" echo -ne >>/tmp/postdata "&$(keypair "commit" "Sign in" )" # Authenticate wget --load-cookies /tmp/kaka --save-cookies /tmp/kaka --keep-session-cookies "${URL_LOGIN}" --post-file=/tmp/postdata -O /tmp/raw 2>/dev/null if [ $? -ne 0 ]; then echo "Error: Unable to authenticate" exit 1 fi # Delete authentication data ... Bad idea to let that stick around rm /tmp/postdata # Provide some details to the end user if [ "$(cat /tmp/raw | grep 'Sign In</title')" != "" ]; then echo "Error: Username and/or password incorrect" exit 1 fi echo "OK" else # It's a public version, so change URL and make doubly sure that cookies are empty rm 2>/dev/null >/dev/null /tmp/kaka touch /tmp/kaka URL_DOWNLOAD=${URL_DOWNLOAD_PUBLIC} fi <file_sep>/scripts/install_autosub.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { # Sanity check if [ "${AUTOSUB_FOLDER}" == "" ] ; then echo "Error: Not all config setting have been found set, please check config.sh." exit 1 fi # Let's do it if ! folder_exists $AUTOSUB_FOLDER; then sudo mkdir -p $AUTOSUB_FOLDER sudo chown -R `whoami`:staff $AUTOSUB_FOLDER ## Unstable version #git clone https://github.com/BenjV/autosub.git $AUTOSUB_FOLDER ## Stable version git clone https://github.com/clone1612/autosub-bootstrapbill.git $AUTOSUB_FOLDER print_result $? 'Download Autosub' #cp ../config/autosub/config.properties $AUTOSUB_FOLDER/ fi # open http://localhost:8080 # echo " --- press any key to continue ---" # read -n 1 -s print_result $? 'Spotweb' } main <file_sep>/scripts/install_mysql56.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { # Sanity check if ! cmd_exists 'brew'; then print_error 'Homebrew required' fi #Let's do it if ! cmd_exists 'mysql'; then brew install homebrew/versions/mysql56 ln -sfv /usr/local/opt/mysql56/*.plist ~/Library/LaunchAgents launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql56.plist mysql.server start mysql_secure_installation ## brew unlink mysql57 ## brew switch mysql 5.7.10 fi print_result $? 'MySQL 5.6' } main<file_sep>/scripts/install_pms_channel_webtools.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ## https://forums.plex.tv/discussion/126254/rel-webtools ## https://github.com/dagalufh/WebTools.bundle ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { ## Sanity check if [ "${PLEX_PMS_WEBTOOLS}" == "" ]; then echo "Error: Not all config setting have been found set, please check config.sh." exit 1 fi ## Let's do it if ! folder_exists $PLEX_PMS_WEBTOOLS; then ask_for_sudo sudo mkdir -p $PLEX_PMS_WEBTOOLS sudo chown -R `whoami`:staff $PLEX_PMS_WEBTOOLS git clone https://github.com/dagalufh/WebTools.bundle.git $PLEX_PMS_WEBTOOLS/WebTools.bundle print_result $? 'Download PMS channel WebTools' ln -s $PLEX_PMS_WEBTOOLS/WebTools.bundle $HOME/Library/Application\ Support/Plex\ Media\ Server/Plug-ins/WebTools.bundle fi print_result $? 'Plex PMS - WebTools' } main <file_sep>/temp/sh/temp.fish_git-branch-and-dirty.sh # Git branch and dirty files git_branch if set -q git_branch set out $git_branch if test $git_dirty_count -gt 0 set out "$out$c0:$ce$git_dirty_count" end section git $out end <file_sep>/scripts/osx_darkmode_enable.sh #!/bin/bash main() { # Enable the dark mode toggle of control-option-command-T sudo defaults write /Library/Preferences/.GlobalPreferences.plist _HIEnableThemeSwitchHotKey -bool true print_result $? 'Disable smart quotes and dashes' } main <file_sep>/scripts/_functions.sh #!/bin/bash echo "loading _functions" abort() { echo "$1" exit 1 } answer_is_yes() { [[ "$REPLY" =~ ^[Yy]$ ]] \ && return 0 \ || return 1 } ask() { print_question "$1" read } ask_for_confirmation() { print_question "$1 (y/n) " read -n 1 printf "\n" } ask_for_sudo() { # Ask for the administrator password upfront sudo -v &> /dev/null # Update existing `sudo` time stamp until this script has finished # https://gist.github.com/cowboy/3118588 while true; do sudo -n true sleep 60 kill -0 "$$" || exit done &> /dev/null & } brew_install() { declare -r CMD="$4" declare -r FORMULA="$2" declare -r FORMULA_READABLE_NAME="$1" declare -r TAP_VALUE="$3" # Check if `Homebrew` is installed if ! cmd_exists 'brew'; then print_error "$FORMULA_READABLE_NAME (\`brew\` is not installed)" return 1 fi # If `brew tap` needs to be executed, check if it executed correctly if [ -n "$TAP_VALUE" ]; then if ! brew_tap "$TAP_VALUE"; then print_error "$FORMULA_READABLE_NAME (\`brew tap $TAP_VALUE\` failed)" return 1 fi fi # Install the specified formula if brew "$CMD" list "$FORMULA" &> /dev/null; then print_success "$FORMULA_READABLE_NAME" else execute "brew $CMD install $FORMULA" "$FORMULA_READABLE_NAME" fi } brew_tap() { brew tap "$1" &> /dev/null } cmd_exists() { command -v "$1" &> /dev/null return $? } current_folder() { SOURCE="${BASH_SOURCE[0]}" DIR="$( dirname "$SOURCE" )" while [ -h "$SOURCE" ] do SOURCE="$(readlink "$SOURCE")" [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" done DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" return $? } download() { local url="$1" local output="$2" if command -v 'curl' &> /dev/null; then curl -LsSo "$output" "$url" &> /dev/null # │││└─ write output to file # ││└─ show error messages # │└─ don't show the progress meter # └─ follow redirects return $? elif command -v 'wget' &> /dev/null; then wget -qO "$output" "$url" &> /dev/null # │└─ write output to file # └─ don't show output return $? fi return 1 } execute() { eval "$1" &> /dev/null print_result $? "${2:-$1}" } extract() { local archive="$1" local outputDir="$2" if command -v 'tar' &> /dev/null; then tar -zxf "$archive" --strip-components 1 -C "$outputDir" return $? fi return 1 } file_exists() { if [ -f "$1" ]; then #echo "file EXISTS (1): $?" return $? else #echo "file NOT exists (2): $?" return 1 fi echo "file EXISTS : $?" } folder_exists() { if [ -d "$1" ]; then return $? else return 1 fi } get_answer() { printf "$REPLY" } get_os() { declare -r OS_NAME="$(uname -s)" local os='' if [ "$OS_NAME" == "Darwin" ]; then os='osx' elif [ "$OS_NAME" == "Linux" ] && [ -e "/etc/lsb-release" ]; then os='ubuntu' else os="$OS_NAME" fi printf "%s" "$os" } get_os_arch() { printf "%s" "$(getconf LONG_BIT)" } is_git_repository() { git rev-parse &> /dev/null return $? } is_supported_version() { declare -a v1=(${1//./ }) declare -a v2=(${2//./ }) local i='' # Fill empty positions in v1 with zeros for (( i=${#v1[@]}; i<${#v2[@]}; i++ )); do v1[i]=0 done for (( i=0; i<${#v1[@]}; i++ )); do # Fill empty positions in v2 with zeros if [[ -z ${v2[i]} ]]; then v2[i]=0 fi if (( 10#${v1[i]} < 10#${v2[i]} )); then return 1 fi done } ## TESTING LAUNCHCTL - START launchctl_list_labels() { LAUNCHCTL_LIST='launchctl list | tail -n +2 | grep -v -e "0x[0-9a-fA-F]" | awk '{print $3}'' } launchctl_list_started () { LAUNCHCTL_STARTED='launchctl list | tail -n +2 | grep -v "^-" | grep -v -e "0x[0-9a-fA-F]" | awk '{print $3}'' } launchctl_list_stopped () { LAUNCHCTL_STOPPED='launchctl list | tail -n +2 | grep "^-" | grep -v -P "0x[0-9a-fA-F]" | awk '{print $3}'' } funct_launchctl_check () { if [ "$os_name" = "Darwin" ]; then launchctl_service=$1 required_status=$2 log_file="$launchctl_service.log" if [ "$required_status" = "on" ] || [ "$required_status" = "enable" ]; then required_status="enabled" change_status="load" else required_status="disabled" change_status="unload" fi total=`expr $total + 1` check_value=`launchctl list |grep $launchctl_service |awk '{print $3}'` if [ "$check_value" = "$launchctl_service" ]; then actual_status="enabled" else actual_status="disabled" fi if [ "$audit_mode" != 2 ]; then echo "Checking: Service $launchctl_service is $required_status" if [ "$actual_status" != "$required_status" ]; then insecure=`expr $insecure + 1` echo "Warning: Service $launchctl_service is $actual_status [$insecure Warnings]" funct_verbose_message "" fix funct_verbose_message "sudo launchctl $change_status -w $launchctl_service.plist" fix funct_verbose_message "" fix if [ "$audit_mode" = 0 ]; then log_file="$work_dir/$log_file" echo "$actual_status" > $log_file echo "Setting: Service $launchctl_service to $required_status" sudo launchctl $change_status -w $launchctl_service.plist fi else if [ "$audit_mode" = 1 ]; then secure=`expr $secure + 1` echo "Secure: Service $launchctl_service is $required_status [$secure Passes]" fi fi else log_file="$restore_dir/$log_file" if [ -f "$log_file" ]; then restore_status=`cat $log_file` if [ "$restore_status" = "enabled" ]; then change_status="load" else change_status="unload" fi if [ "$restore_status" != "$actual_status" ]; then sudo launchctl $change_status -w $launchctl_service.plist fi fi fi fi } ## ---- function list() { { set +x; } 2>/dev/null ( set -x; launchctl list | grep sh.launchd ) } function load() { { set +x; } 2>/dev/null ( set -x; launchctl load -w "$1" ) } function unload() { { set +x; } 2>/dev/null ( set -x; launchctl unload -w "$1" ) } function reload() { { set +x; } 2>/dev/null unload $@ load $@ } # .plist function plist() { { set +x; } 2>/dev/null ( set -x; plutil -convert xml1 "$1" ) } ## TESTING LAUNCHCTL - END ## TESTING OTHER - START check_server_ping() { ping -c 5 -W 2 -i 0.2 "${server}" &> /dev/null if [ $? -eq 0 ] then return 0 else echo "Unable to ping the server specified, exiting" return 1 fi } check_server_port() { echo "" > /dev/tcp/${server}/${port} if [ $? -eq 0 ] then return 0 else echo "Unable to connect to specified port \"${port}\" on the server ${server}, exiting" return 1 fi } variable_replace() { _variable="${1}" _replace="${2}" _file="${3}" _return_file"{4}" echo "$(cat "{_file}" | sed "s/\$(_variable)/\$(_replace)/g" > "${_return_file}")" if [ ${rc} -eq 0 ] then return 0 else return 1 fi } ## TESTING OTHER - END mkd() { if [ -n "$1" ]; then if [ -e "$1" ]; then if [ ! -d "$1" ]; then print_error "$1 - a file with the same name already exists!" else print_success "$1" fi else execute "mkdir -p $1" "$1" fi fi } mysql_config_login_add() { mySqlHost="${1}" mySqlUser="${2}" mySqlPassword="${3}" expect -c " spawn mysql_config_editor set --login-path=$mySqlUser --host=$mySqlHost --user=$mySqlUser --password expect -nocase \"Enter password:\" {send \"$my<PASSWORD>\r\"; interact} " return $? } mysql_db_exist() { MYSQL_DBNAME="${1}" MYSQL_DBUSER="${2}" MYSQL_DBPW="${3}" if [ -z "`mysql_config_editor print --login-path=root`" ]; then echo "mySQL login root NOT exist" DBEXISTS=$(mysql -u$MYSQL_DBUSER -p$MYSQL_DBPW --batch --skip-column-names -e "SHOW DATABASES LIKE '"$MYSQL_DBNAME"';" | grep "$MYSQL_DBNAME" > /dev/null; echo "$?") else echo "mySQL login root exists " DBEXISTS=$(mysql --login-path=root --batch --skip-column-names -e "SHOW DATABASES LIKE '"$MYSQL_DBNAME"';" | grep "$MYSQL_DBNAME" > /dev/null; echo "$?") fi if [ $DBEXISTS -eq 0 ];then #echo "A database with the name $MYSQL_DBNAME already exists." return $? else #echo " database $MYSQL_DBNAME does not exist." return 1 fi } install_dmg () { ## !! ERROR on find with volume having a space !! ## APPLICATION_FOLDER="/Applications" #echo "Mounting image..." volume=`hdiutil mount -nobrowse "$1" | tail -n1 | perl -nle '/(\/Volumes\/[^ ]+)/; print $1'` # Locate .app folder and move to /Applications app=`find $volume/. -name *.app -maxdepth 1 -type d -print0` #echo "Copying `echo $app | awk -F/ '{print $NF}'` into Application folder ..." echo "sudo cp -R $app $APPLICATION_FOLDER/" read -p "Press any key..." sudo cp -R $app $APPLICATION_FOLDER/ return $? # Unmount volume, delete temporal file hdiutil unmount $volume -quiet #rm "$1" } print_error() { print_in_red " [✖] $1 $2\n" } print_in_green() { printf "\e[0;32m$1\e[0m" } print_in_purple() { printf "\e[0;35m$1\e[0m" } print_in_red() { printf "\e[0;31m$1\e[0m" } print_in_yellow() { printf "\e[0;33m$1\e[0m" } print_info() { print_in_purple "\n $1\n\n" } print_question() { print_in_yellow " [?] $1" } print_result() { [ $1 -eq 0 ] \ && print_success "$2" \ || print_error "$2" return $1 } print_success() { print_in_green " [✔] $1\n" } verify_os() { declare -r MINIMUM_OS_X_VERSION='10.11' declare -r OS_NAME="$(uname -s)" declare OS_VERSION='' # Check if the OS is `OS X` and # it's above the required version if [ "$OS_NAME" == "Darwin" ]; then OS_VERSION="$(sw_vers -productVersion)" is_supported_version "$OS_VERSION" "$MINIMUM_OS_X_VERSION" \ && return 0 \ || printf "Sorry, this script is intended only for OS X $MINIMUM_OS_X_VERSION+" else printf 'Sorry, this script is intended only for OS X!' fi return 1 } <file_sep>/temp/sh/temp.install_random.sh #!/usr/bin/env bash # Assume we're not on the UVic computers. function UVic { local AT_UVIC = false echo $HELLO in function } # Check whether we can do a quick local install, since I've already # downloaded the .dmg and .zip files to my UVic Netdrive if [[ $HOSTNAME = *".uvic.ca"* && $USER = *"sahoward"* ]] then $AT_UVIC = 1; fi #################################### # Software acquisition #################################### chromium_version='43.0.2357.81' chromium_url='http://downloads.sourceforge.net/sourceforge/osxportableapps/Chromium_OSX_'$chromium_version'.dmg' iterm_version='2_1_1' iterm_url='https://iterm2.com/downloads/beta/iTerm2-'$iterm_version'.zip' sublimetext_version='3083' sublimetext_url='http://c758482.r82.cf2.rackcdn.com/Sublime%20Text%20Build%20'$sublimetext_version'.dmg' cyberduck_version='4.7' cyberduck_url='https://update.cyberduck.io/Cyberduck-'$cyberduck_version'.zip' flux_version='' flux_url='https://justgetflux.com/mac/Flux.zip' spotify_version='' spotify_url='https://www.spotify.com/Spotify.dmg' # Begin moving files to Desktop cd ~/Desktop; if [[ "AT_UVIC" = true ]]; then echo "" echo "Copying the following files from UVic Individual Temp storage:" echo "" ln -s "/Volumes/UVic Individual Temp/s/sahoward" ~/Desktop/ cp -vr "/Volumes/UVic Individual Temp/s/sahoward/workspace-OSX" ~/Desktop; echo "" echo "Finished copying." echo "" else echo "" echo "Downloading Chromium, iTerm2, Cyberduck, Sublime Text 3, F.lux, and Spotify" echo "" mkdir ~/Desktop/workspace-OSX cd ~/Desktop/workspace-OSX curl -LO $chromium_url curl -LO $iterm_url curl -LO $cyberduck_url curl -LO $sublimetext_url curl -LO $flux_url curl -Os $spotify_url fi echo "" echo Now customizing Mac OS X settings. echo "" #################################### # General UI/UX #################################### # Disable the "are you sure you want to open this file" dialog for apps on Desktop xattr -d -r com.apple.quarantine ~/Desktop # Set a blazingly fast keyboard repeat rate defaults write NSGlobalDomain KeyRepeat -int 0 # Increase window resize speed for Cocoa applications defaults write NSGlobalDomain NSWindowResizeTime -float 0.001 # Expand save panel by default defaults write NSGlobalDomain NSNavPanelExpandedStateForSaveMode -bool true defaults write NSGlobalDomain NSNavPanelExpandedStateForSaveMode2 -bool true # Finder: show path bar defaults write com.apple.finder ShowPathbar -bool true # Finder: allow text selection in Quick Look defaults write com.apple.finder QLEnableTextSelection -bool true # Display full POSIX path as Finder window title defaults write com.apple.finder _FXShowPosixPathInTitle -bool true # Enable Text Selection in Quick Look Windows defaults write com.apple.finder QLEnableTextSelection -bool TRUE killall Finder # Always Show the User Library Folder chflags nohidden ~/Library/ # Remove shadow from screenshot defaults write com.apple.screencapture disable-shadow -bool true; killall SystemUIServer # Show only currently active apps in the Mac OS X Dock defaults write com.apple.dock static-only -bool TRUE #################################### # Dock, Dashboard, and hot corners #################################### # Enable highlight hover effect for the grid view of a stack (Dock) defaults write com.apple.dock mouse-over-hilite-stack -bool true # Set the icon size of Dock items to 36 pixels if [[ $AT_UVIC = 1 ]]; then defaults write com.apple.dock tilesize -int 64 else defaults write com.apple.dock tilesize -int 36 fi # Change minimize/maximize window effect defaults write com.apple.dock mineffect -string "scale" # Minimize windows into their application’s icon defaults write com.apple.dock minimize-to-application -bool true # Enable spring loading for all Dock items defaults write com.apple.dock enable-spring-load-actions-on-all-items -bool true # Show indicator lights for open applications in the Dock defaults write com.apple.dock show-process-indicators -bool true #################################### # Chromium #################################### echo "" echo "Installing Chromium" echo "" cd ~/Desktop open ~/Desktop/workspace-OSX/Chromium*.dmg sleep 10 cp -R /Volumes/Chromium*/Chromium.app ~/Desktop sleep 15 diskutil unmountDisk /Volumes/Chromium* echo "" echo "Done." echo "" #################################### # iTerm #################################### echo "" echo "Opening iTerm2 and installing colour schemes." echo "" cd ~/Desktop unzip -oq ~/Desktop/workspace-OSX/iTerm*.zip sleep 5 if [[ $AT_UVIC = 1 ]]; then # Install preferences ~/Desktop/iTerm.app/Contents/MacOS/iTerm ~/Desktop/extensions/iterm/com.* sleep 5 # Install colour schemes open ~/Desktop/extensions/iterm/*.itermcolors fi echo "" echo "Done." echo "" #################################### # Sublime Text #################################### echo "" echo "Installing Sublime Text 3." echo "" cd ~/Desktop open ~/Desktop/Sublime*.dmg sleep 10 cp -R /Volumes/Sublime\ Text/Sublime\ Text.app ~/Desktop/ & sleep 5 diskutil unmountDisk /Volumes/Sublime* open ~/Desktop/Sublime\ Text.app/Contents/MacOS/Sublime\ Text sleep 5 if [[ $AT_UVIC = 1 ]]; then chmod u+x ~/Desktop/extensions/subl/Sublime\ Text killall Sublime\ Text cp ~/Desktop/extensions/subl/Sublime\ Text ~/Desktop/Sublime\ Text.app/Contents/MacOS/Sublime\ Text fi # add the "subl" launch shortcut ln -s ~/Desktop/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl echo "" echo "Done." echo "" #################################### # F.lux #################################### echo "" echo "Installing F.lux" echo "" cd ~/Desktop unzip -oq ~/Desktop/Flux*.zip sleep 5 echo "" echo "Done." echo "" #################################### # Spotify #################################### echo "" echo "Installing Spotify" echo "" cd ~/Desktop open ~/Desktop/Spotify*.dmg cp -R "/Volumes/Spotify*/Spotify.app" ~/Desktop sleep 5 diskutil unmountDisk /Volumes/Spotify* echo "" echo "Done." echo "" #################################### # Cyberduck #################################### echo "" echo "Installing Cyberduck" echo "" cd ~/Desktop unzip -oq ~/Desktop/Cyberduck*.zip echo "" echo "Done." echo "" #################################### # Clean Up #################################### rm -r ~/Desktop/*.zip rm -rf ~/Desktop/_* killall Dock Finder iTerm Sublime\ Text Chromium echo "Mac setup is complete." sleep 3 echo "" echo "Looks tight." echo "" sleep 2 echo "" echo "Enjoy" echo "" sleep 3 killall Terminal <file_sep>/scripts/tmp_install_pms_plexpy.sh #!/bin/bash ## https://github.com/drzoidberg33/plexpy ## Initializing if [ -f config.sh ]; then echo "Loading config file (1)" source config.sh elif [ -f ../config.sh ]; then echo "Loading config file (2)" source ../config.sh else echo "Config file config.sh does not exist" fi if [ -z "${BASH_VERSINFO}" ]; then echo "ERROR: You must execute this script with BASH" exit 255 fi # Sanity check if [ "${EMAIL}" == "" -o "${PASS}" == "" ] && [ "${PUBLIC}" == "false" ]; then echo "Error: Need username & password to download PlexPass version. Otherwise run with -p to download public version." exit 1 fi # Remove any ~ or other oddness in the path we're given echo "checking dowload folder: $FOLDER_DOWNLOAD" FOLDER_DOWNLOAD="$(eval cd ${FOLDER_DOWNLOAD// /\\ } ; if [ $? -eq 0 ]; then pwd; fi)" if [ -z "${FOLDER_DOWNLOAD}" ]; then echo "Error: Download directory does not exist or is not a directory" exit 1 fi ################################################################# # Don't change anything below this point # if [ ! -d $PLEXPY_FOLDER ] ; then echo "${COLOR_YELLOW}${CHAR_XMARK}${COLOR_RESET} $PLEXPY_FOLDER doesn't exists, creating ..." sudo mkdir -p $PLEXPY_FOLDER sudo chown `whoami`:staff $PLEXPY_FOLDER else echo "${COLOR_GREEN}${CHAR_CHECKMARK}${COLOR_RESET} Folder PLEXPY_FOLDER exists." fi git clone https://github.com/drzoidberg33/plexpy.git PlyPy if [ ! -d "$HOME/Library/LaunchAgents" ] ; then echo "${COLOR_YELLOW}${CHAR_XMARK}${COLOR_RESET} $PLEXPY_FOLDER doesn't exists, creating ..." sudo mkdir -p "$HOME/Library/LaunchAgents" else echo "${COLOR_GREEN}${CHAR_CHECKMARK}${COLOR_RESET} Library folder LaunchAgents exists." fi # /Library/LaunchDaemons #[ -a .pow ] || ln -s "$POW_ROOT/Hosts" .pow #cd $DIR<file_sep>/scripts/install_nzbtomedia_sickbeard.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { if [ "${NZBTOMEDIA_FOLDER}" == "" ]; then echo "Error: Not all config setting have been found set, please check config.sh." exit 1 fi if ! folder_exists $NZBTOMEDIA_FOLDER; then print_error 'Error: Folder not detected - '$NZBTOMEDIA_FOLDER exit 1 fi if ! folder_exists '/Applications/SABnzbd.app/'; then print_error 'Error: Application not detected - SABnzbd' exit 1 fi if ! file_exists $NZBTOMEDIA_FOLDER'/autoProcessMedia.cfg'; then cp $NZBTOMEDIA_FOLDER'/autoProcessMedia.cfg.spec' $NZBTOMEDIA_FOLDER'/autoProcessMedia.cfg' fi print_result $? 'NzbToMedia for SickBeard' } main <file_sep>/temp/sh/temp.fish_time_taken.sh # Track the last non-empty command. It's a bit of a hack to make sure # execution time and last command is tracked correctly. set -l cmd_line (commandline) if test -n "$cmd_line" set -g last_cmd_line $cmd_line set -ge new_prompt else set -g new_prompt true end # Show last execution time and growl notify if it took long enough set -l now (date +%s) if test $last_exec_timestamp set -l taken (math $now - $last_exec_timestamp) if test $taken -gt 10 -a -n "$new_prompt" error taken $taken echo "Returned $last_status, took $taken seconds" | \ growlnotify -s $last_cmd_line # Clear the last_cmd_line so pressing enter doesn't repeat set -ge last_cmd_line end end set -g last_exec_timestamp $now <file_sep>/scripts/test.sh #!/bin/bash while :; do # Loop until valid input is entered or Cancel is pressed. name=$(osascript -e 'Tell application "System Events" to display dialog "Enter the project name:" default answer ""' -e 'text returned of result' 2>/dev/null) if (( $? )); then exit 1; fi # Abort, if user pressed Cancel. name=$(echo -n "$name" | sed 's/^ *//' | sed 's/ *$//') # Trim leading and trailing whitespace. if [[ -z "$name" ]]; then # The user left the project name blank. osascript -e 'Tell application "System Events" to display alert "You must enter a non-blank project name; please try again." as warning' >/dev/null # Continue loop to prompt again. else # Valid input: exit loop and continue. break fi done <file_sep>/scripts/set_dashboard_preferences.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then echo "Loading functions file (1)" source _functions.sh elif [ -f ../_functions.sh ]; then echo "Loading functions file (2)" source ../_functions.sh else echo "Config file functions.sh does not exist" fi if [ -f config.sh ]; then echo "Loading config file (1)" source config.sh elif [ -f ../config.sh ]; then echo "Loading config file (2)" source ../config.sh else echo "Config file config.sh does not exist" fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - set_preferences() { execute 'defaults write com.apple.dashboard mcx-disabled -bool true' \ 'Disable Dashboard' } main() { print_in_purple '\n Dashboard\n\n' set_preferences # 'killall Dashboard' doesn't actually do anything. To apply # the changes for Dashboard, 'killall Dock' is enough as Dock # is Dashboard's parent process. killall 'Dock' &> /dev/null } main<file_sep>/temp/sh/temp.check_osx_swupdate.sh #!/bin/bash # Check OS X Software Update Server # by <NAME> # http://jedda.me # v1.0 - 03 Dec 2012 # Initial release. # Script that uses serveradmin to check that the OS X Software Update service is listed as running. # If all is OK, it returns performance data for the number of mirrored and enabled packages, as well as the size of the update store. # Can also ensure that updates are auto syncing with Apple, and that the latest check was OK. # Optional Flags: # -a Tells the script to ensure that automatic mirroring of updates is on, and that the last check succeeded. If your setup is manual, don't use this. # Example: # ./check_osx_swupdate.sh -a # Performance Data - this script returns the followng Nagios performance data: # mirroredPkgs - Number of packages mirrored by your Software Update Server. # enabledPkgs - Number of packages currently enabled by your Software Update Server. # sizeOfUpdates - Size of your specified updates directory in Kilobytes. # Compatibility - this script has been tested on and functions on the following stock OSes: # 10.6 Server # 10.7 Server # 10.8 Server if [[ $EUID -ne 0 ]]; then printf "ERROR - This script must be run as root.\n" exit 1 fi # check that the swupdate service is running swupdateStatus=`serveradmin fullstatus swupdate | grep 'swupdate:state' | sed -E 's/swupdate:state.+"(.+)"/\1/'` if [ "$swupdateStatus" != "RUNNING" ]; then printf "CRITICAL - Software Update service is not running!\n" exit 2 fi # grab our performance data numOfMirroredPkg=`serveradmin fullstatus swupdate | grep 'swupdate:numOfMirroredPkg ' | grep -E -o "[0-9]+$"` numOfEnabledPkg=`serveradmin fullstatus swupdate | grep 'swupdate:numOfEnabledPkg ' | grep -E -o "[0-9]+$"` updatesDocRoot=`serveradmin fullstatus swupdate | grep 'swupdate:updatesDocRoot' | sed -E 's/swupdate:updatesDocRoot.+"(.+)"/\1/'` sizeOfUpdatesDocRoot=`du -sk "$updatesDocRoot" | grep -E -o "[0-9]+"` # see if we need to check auto mirror status if [ "$1" == "-a" ]; then autoMirrorToggle=`serveradmin fullstatus swupdate | grep 'swupdate:autoMirror ' | grep -E -o "[a-z]+$"` if [ "$autoMirrorToggle" != "yes" ]; then printf "WARNING - Auto mirroring of packages is off! | mirroredPkgs=$numOfMirroredPkg; enabledPkgs=$numOfEnabledPkg; sizeOfUpdates=$sizeOfUpdatesDocRoot;\n" exit 1 fi autoMirrorCheckError=`serveradmin fullstatus swupdate | grep 'swupdate:checkError ' | grep -E -o "[a-z]+$"` if [ "$autoMirrorCheckError" != "no" ]; then printf "WARNING - Auto mirroring of packages encountered an error on last check! | mirroredPkgs=$numOfMirroredPkg; enabledPkgs=$numOfEnabledPkg; sizeOfUpdates=$sizeOfUpdatesDocRoot;\n" exit 1 fi fi # lastly, make sure that we can connect to the service port swupdateServicePort=`serveradmin settings swupdate | grep 'swupdate:portToUse' | grep -E -o "[0-9]+$"` curl -silent localhost:$swupdateServicePort > /dev/null if [ $? == 7 ]; then printf "CRITICAL - Could not connect to the Software Update service port ($swupdateServicePort). | mirroredPkgs=$numOfMirroredPkg; enabledPkgs=$numOfEnabledPkg; sizeOfUpdates=$sizeOfUpdatesDocRoot;\n" exit 2 fi printf "OK - Software Update service appears to be running OK. | mirroredPkgs=$numOfMirroredPkg; enabledPkgs=$numOfEnabledPkg; sizeOfUpdates=$sizeOfUpdatesDocRoot;\n" exit 0 <file_sep>/scripts/set_trackpad_preferences.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then echo "Loading functions file (1)" source _functions.sh elif [ -f ../_functions.sh ]; then echo "Loading functions file (2)" source ../_functions.sh else echo "Config file functions.sh does not exist" fi if [ -f config.sh ]; then echo "Loading config file (1)" source config.sh elif [ -f ../config.sh ]; then echo "Loading config file (2)" source ../config.sh else echo "Config file config.sh does not exist" fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - set_preferences() { execute 'defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad Clicking -bool true && defaults write NSGlobalDomain com.apple.mouse.tapBehavior -int 1 && defaults -currentHost write NSGlobalDomain com.apple.mouse.tapBehavior -int 1' \ 'Enable "Tap to click"' execute 'defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad TrackpadRightClick -bool true && defaults -currentHost write NSGlobalDomain com.apple.trackpad.enableSecondaryClick -bool true && defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad TrackpadCornerSecondaryClick -int 0 && defaults -currentHost write NSGlobalDomain com.apple.trackpad.trackpadCornerClickBehavior -int 0' \ 'Map "click or tap with two fingers" to the secondary click' } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { print_in_purple '\n Trackpad\n\n' set_preferences } main<file_sep>/install.sh #!/usr/bin/env bash ######## PLAY TIME ############## ### Exit the script if any statement returns a non-true return value. #set -o errexit ##set -e # ### Check for uninitialised variables ##set -o nounset # ######## PLAY TIME - END ######## ## ---------------------------------------------------------------------------- DEBUG=0 PRINTF_MASK="%-50s %s %10s %s\n" TIMESTAMP=`date +%Y%m%d%H%M%S` # Setting some color constants COLOR_GREEN=$'\x1b[0;32m' COLOR_RED=$'\x1b[0;31m' COLOR_RESET=$'\x1b[0m' BLUE=$'\x1b[0;34m' # Setting some escaped characters CHAR_CHECKMARK=$'\xE2\x9C\x93' CHAR_XMARK=$'\xE2\x9C\x97' ## ---------------------------------------------------------------------------- ## Main if [ -f _functions.sh ]; then source _functions.sh elif [ -f scripts/_functions.sh ]; then source scripts/_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi echo echo "Checking a few things to make sure we are good to go..." echo verify_os if [ ! -f config.sh ]; then clear echo "No config.sh found. Creating file, please edit the required values" cp config.sh.default config.sh pico config.sh fi source config.sh if [[ $AGREED == "no" ]]; then echo "Please edit the config.sh file" exit fi # Check if the current account is in the admin group if groups | grep -w -q admin 2>&1 then echo "${COLOR_GREEN}${CHAR_CHECKMARK}${COLOR_RESET} You are an admin." else abort "${COLOR_RED}${CHAR_XMARK}${COLOR_RESET} You are not an admin." fi # # Checking for an Internet connection # if /sbin/ping -s1 -t4 -o ${PING_HOST} >/dev/null 2>&1 # then # echo "${COLOR_GREEN}${CHAR_CHECKMARK}${COLOR_RESET} We have an Internet connection." # else # abort "${COLOR_RED}${CHAR_XMARK}${COLOR_RESET} We do not have an Internet connection." # fi #------------------------------------------------------------------------------ # Keep-alive: update existing sudo time stamp until finished #------------------------------------------------------------------------------ # Ask for the administrator password upfront # echo "--------------------------------------" # echo "| Please enter the root password |" # echo "--------------------------------------" # sudo -v # echo "--------------------------------------" # # # Keep-alive: update existing `sudo` time stamp until finished # while true; do sudo -n true; sleep 60; kill -0 "$$" || exit; done 2>/dev/null & #------------------------------------------------------------------------------ # Checking if system is up-to-date #------------------------------------------------------------------------------ ## Run software update and reboot # if [[ $INST_OSX_UPDATES == "true" ]]; then # echo "${COLOR_RED}${CHAR_XMARK}${COLOR_RESET} System is not up-to-date, updating ..." # sudo softwareupdate --list # sudo softwareupdate --install --all # else # echo "${COLOR_GREEN}${CHAR_CHECKMARK}${COLOR_RESET} System is up-to-date." # fi #------------------------------------------------------------------------------ # Changing default system behaviour #------------------------------------------------------------------------------ # if [[ $ENABLE_LIBRARY_VIEW == "true" ]]; then # source "$DIR/scripts/osx_libraryview_enable.sh" # fi # if [[ $ENABLE_MOUSE_TAPTOCLICK == "true" ]]; then # source "$DIR/scripts/osx_mouse_taptoclick_enable.sh" # fi <file_sep>/temp/sh/temp.fish_python-virtualenv.sh # Virtualenv if set -q VIRTUAL_ENV section env (basename "$VIRTUAL_ENV") end <file_sep>/dotfiles/_backup.1/bash_functions #!/bin/bash # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd() { builtin cd "$@"; ll; } # Always list directory contents upon 'cd' cdf() { cd "$(osascript -e 'tell app "Finder" to POSIX path of (insertion location as alias)')"; } # cdr: Change working directory to the top-most Finder window location mcd () { mkdir -p "$1" && cd "$1"; } # mcd: Makes new Dir and jumps inside trash () { command mv "$@" ~/.Trash ; } # trash: Moves a file to the MacOS trash ql () { qlmanage -p "$*" >& /dev/null; } # ql: Opens any file in MacOS Quicklook Preview <file_sep>/scripts/install_spotweb_api_test.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { if ! cmd_exists 'curl'; then print_error 'Error: Not all config setting have been found set, please check config.sh' exit 1 fi URL="http://localhost/spotweb/api?t=c" TMPFILE=`mktemp /tmp/spotweb.XXXXXX` curl -s -o ${TMPFILE} ${URL} 2>/dev/null if [ "$?" -ne "0" ]; then print_error 'Unable to connect to ${URL}' echo " --- press any key to continue ---" read -n 1 -s exit 2 fi RES=`grep -i "Spotweb API Index" ${TMPFILE}` if [ "$?" -ne "0" ]; then print_error 'String Spotweb API Index not found in '${URL} print_error 'Copy the SpotWEB htaccess file and restart Apache' echo ' --- press any key to continue ---' read -n 1 -s exit 2 else print_success 'String Spotweb API Index found in '$URL fi print_result $? 'Spotweb API test' } main <file_sep>/temp/sh/temp.gateKeeperAppStoreIdentifiedDevelopers.sh #This script will change the Gatekeeper setting to allow applications downloaded from the Mac App Store and identified developers. #!/bin/sh /usr/sbin/spctl --enable<file_sep>/scripts/install_nzbtomedia_extras.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { if folder_exists $NZBTOMEDIA_FOLDER; then if ! cmd_exists 'brew'; then print_error 'Homebrew required' exit 1 fi brew update && brew upgrade if ! cmd_exists 'x264'; then brew install x264 fi if ! cmd_exists 'x265'; then brew install x265 fi if ! cmd_exists 'freetype'; then brew install freetype fi if ! cmd_exists 'libvorbis'; then brew install libvorbis fi if ! cmd_exists 'opus'; then brew install opus fi if ! cmd_exists 'libvpx'; then brew install libvpx fi if ! cmd_exists 'ffmpeg'; then brew uninstall ffmpeg fi if ! cmd_exists '7z'; then brew uninstall p7zip fi brew install ffmpeg --with-fdk-aac --with-libfdk-aac --with-ffplay --with-freetype --with-libass --with-libquvi --with-libvorbis --with-libvpx --with-opus --with-x264 --with-x265 print_result $? 'Download NzbToMedia Extras' fi print_result $? 'NzbToMedia Extras' } main <file_sep>/temp/sh/temp.check_osx_launchd.sh #!/bin/bash # Check launchd Tasks # by <NAME> # http://jedda.me # v1.0 - 1 Aug 2012 # Initial release. # This script calls `launchctl list` and parses the output to report non-zero exit codes for tasks. This is very useful in # finding tasks that cannot launch and are 'Throttling respawn', as well as locating bad exit codes for scheduled tasks. # !! IMPORTANT: It is important that the script is run as a super user so that system tasks are included - otherwise you are just monitoring # tasks in the 'local' domain, which is unlikely to be anything you care about. # The preset_exceptions array below exists because some tasks exit with non-zero codes as standard, such as Apple's XProtect # anti-malware tool, which exits with a code of 252 when there are no new definitions on Apple's server. The execptions allow # for these kind of known tasks whose exit status is not pertinent to the monitoring of the system. # The -e flag allows you to supply extra exceptions as an argument. This is a comma delimited list of identifiers (see example below). # The -c flag allows you to supply critical processes as an argument. This is a comma delimited list of identifiers (see example below). # The default return for finding a process with a non-zero exit code is WARNING. This allows you to define processes that # will return CRITICAL. # The script takes the above arguments like this: # ./check_osx_launchd.sh -e com.apple.iCloudHelper,com.apple.NotesMigratorService -c com.apple.servermgrd preset_exceptions="com.apple.printuitool.agent,com.apple.coreservices.appleid.authentication,com.apple.afpstat-qfa,com.apple.mrt.uiagent,com.apple.printtool.agent,com.apple.accountsd,com.apple.xprotectupdater,com.apple.pfctl" preset_criticals="org.postgresql.postgres" # don't edit below this line unless you know what to do provided_exceptions="" provided_criticals="" non_zero=0 critical=0 non_zero_label_array=( ) while getopts "e:c:" optionName; do case "$optionName" in e) provided_exceptions=( $OPTARG );; c) provided_criticals=( $OPTARG );; esac done exceptions=$preset_exceptions","$provided_exceptions criticals=$preset_criticals","$provided_criticals # list all launchd processes, and look at exit codes launchctl list | { while read line ; do ld_pid=`echo $line | cut -d ' ' -f 1` ld_exit=`echo $line | cut -d ' ' -f 2` ld_label=`echo $line | cut -d ' ' -f 3` # skip exceptions case "${exceptions[@]}" in *"$ld_label"*) continue ;; esac # check tasks if [ "$ld_pid" != "-" ]; then # task is active let active++ #echo "$ld_label is active" else # task is inactive let inactive++ # look at last exit code if [ "$ld_exit" != "0" ]; then case "${criticals[@]}" in *"$ld_label"*) critical=1 ;; esac let non_zero++ non_zero_label_array[${#non_zero_label_array[*]}]="$ld_label" fi fi done non_zero_labels=`printf ",%s" "${non_zero_label_array[@]}" | cut -c2-` if [ $non_zero -gt 0 ] && [ $critical == 0 ]; then printf "WARNING - daemon/s ($non_zero_labels) exited with a non-zero code! | active=$active; inactive=$inactive; error=$non_zero;\n" exit 1 elif [ $non_zero -gt 0 ] && [ $critical == 1 ]; then printf "CRITICAL - critical daemon/s ($non_zero_labels) exited with a non-zero code! | active=$active; inactive=$inactive; error=$non_zero;\n" exit 2 else printf "OK - All daemons are active or exited successfully. | active=$active; inactive=$inactive; error=$non_zero;\n" exit 0 fi } <file_sep>/temp/sh/temp.fish_shell.sh brew install fish # add Fish to /etc/shells echo "/usr/local/bin/fish" | sudo tee -a /etc/shells # Change default shell to Fish chsh -s /usr/local/bin/fish # Create the Fish config directory mkdir -p ~/.config/fish # Create initial config file #vim ~/.config/fish/config.fish # add /usr/local/bin to the PATH environment variable #set -g -x PATH /usr/local/bin $PATH fish_config # Disable Fish welcome greeting #echo "set -g -x fish_greeting ''" >> ~/.config/fish/config.fish <file_sep>/temp/sh/temp.fish_disk-free.sh # Show disk usage when low set -l du (df / | tail -n1 | sed "s/ */ /g" | cut -d' ' -f 5 | cut -d'%' -f1) if test $du -gt 80 error du $du%% end <file_sep>/temp/sh/temp.fish_load-average.sh # Show loadavg when too high set -l load1m (uptime | grep -o '[0-9]\+\.[0-9]\+' | head -n1) set -l load1m_test (math $load1m \* 100 / 1) if test $load1m_test -gt 100 error load $load1m end <file_sep>/temp/sh/temp.gateKeeperRequireAppStore.sh #This script will change the Gatekeeper setting to allow applications downloaded from the Mac App Store only. #!/bin/sh /usr/sbin/spctl --disable <file_sep>/temp/sh/temp.fish_current-date.sh printf (date "+$c2%H$c0:$c2%M$c0:$c2%S, ") <file_sep>/scripts/install_sabnzbd.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { if ! folder_exists '/Applications/SABnzbd.app/'; then SABNZBD_VERSION=`curl -s http://sabnzbdplus.sourceforge.net/version/latest | head -n1` SABNZBD_DIR="SABnzbd-${SABNZBD_VERSION}" SABNZBD_GZ="${SABNZBD_DIR}-osx.dmg" download "http://freefr.dl.sourceforge.net/project/sabnzbdplus/sabnzbdplus/${SABNZBD_VERSION}/${SABNZBD_GZ}" "$FOLDER_DOWNLOAD/${SABNZBD_DIR}-osx.dmg" print_result $? 'Download SabNZBD' ask_for_sudo install_dmg "$FOLDER_DOWNLOAD/${SABNZBD_DIR}-osx.dmg" fi print_result $? 'SabNZBD' } main <file_sep>/scripts/install_spotweb.sh #!/bin/bash ## Initializing if [ -f _functions.sh ]; then source _functions.sh elif [ -f ../_functions.sh ]; then source ../_functions.sh else echo "Config file functions.sh does not exist" exit 1 fi if [ -f config.sh ]; then source config.sh elif [ -f ../config.sh ]; then source ../config.sh else echo "Config file config.sh does not exist" exit 1 fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { # Sanity check if [ "${SPOTWEB_FOLDER}" == "" ] || [ "${SPOTWEB_MYSQL_DB}" == "" ] || [ "${MYSQL_ROOT_UID}" == "" ] || [ "${SPOTWEB_MYSQL_PW}" == "" ] || [ "${MYSQL_ROOT_UID}" == "" ] || [ "${MYSQL_ROOT_PW}" == "" ] ; then echo "Error: Not all config setting have been found set, please check config.sh." exit 1 fi # Let's do it if ! folder_exists $SPOTWEB_FOLDER; then ask_for_sudo sudo mkdir -p $SPOTWEB_FOLDER sudo chown -R `whoami`:staff $SPOTWEB_FOLDER git clone https://github.com/spotweb/spotweb.git $SPOTWEB_FOLDER print_result $? 'Download Spotweb' sudo ln -s $SPOTWEB_FOLDER /Library/Server/Web/Data/Sites/Default/spotweb fi if [ -z "`mysql_config_editor print --login-path=$MYSQL_ROOT_UID`" ]; then mysql_config_login_add 'localhost' $MYSQL_ROOT_UID $MYSQL_ROOT_PW print_result $? 'Stored MySQL authentication credential of '"$MYSQL_ROOT_UID"' to localhost' fi if ! mysql_db_exist $SPOTWEB_MYSQL_DB $MYSQL_ROOT_UID $MYSQL_ROOT_PW; then print_error 'DB not found' mysql --login-path=root -e "CREATE DATABASE $SPOTWEB_MYSQL_DB;" print_result $? 'Created MySQL database $SPOTWEB_MYSQL_DB' mysql --login-path=root -e "CREATE USER $SPOTWEB_MYSQL_UID@'localhost' IDENTIFIED BY '$SPOTWEB_MYSQL_PW';" print_result $? 'Created user $SPOTWEB_MYSQL_UID in the MySQL database $SPOTWEB_MYSQL_DB' mysql --login-path=root -e "GRANT ALL PRIVILEGES ON $SPOTWEB_MYSQL_DB.* TO $SPOTWEB_MYSQL_UID@'localhost' IDENTIFIED BY '$SPOTWEB_MYSQL_PW';" mysql -uroot -p -e "GRANT ALL PRIVILEGES ON $SPOTWEB_MYSQL_DB.* TO spotweb@'localhost' IDENTIFIED BY 'spotweb@mini';" print_result $? 'Granted access of user $SPOTWEB_MYSQL_UID to the MySQL database $SPOTWEB_MYSQL_DB' fi ## PHP extension: gettext - Not OK ## GD : FreeType Support - Not OK ## Cache directory is writable? - Not OK ## Own settings file - NOT OK (optional) # /Library/Server/Web/Config/apache2/webapps/ # cat /Library/Server/Web/Config/apache2/httpd_server_app.conf # Include /Library/Server/Web/Config/apache2/sites/*.conf # http://synology.brickman.nl/syn_howto/HowTo%20-%20install%20Spotweb.txt # http://pablin.org/2015/04/30/configuring-jenkins-on-os-x-server/ # http://mar2zz.tweakblogs.net/blog/6724/spotweb-als-provider.html # http://www.happylark.nl/spotweb-instellen/ exit #open http://localhost/spotweb/install.php #echo " --- press any key to continue ---" #read -n 1 -s print_result $? 'Spotweb' } main <file_sep>/dotfiles/bash_aliases #!/bin/bash # Detect which `ls` flavor is in use if ls --color > /dev/null 2>&1; then # GNU `ls` colorflag="--color" else # OS X `ls` colorflag="-G" fi # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Easier navigation alias ~="cd ~" # ~: Go Home alias cd..='cd ../' # Go back 1 directory level (for fast typers) alias ..='cd ../' # Go back 1 directory level alias ...='cd ../../' # Go back 2 directory levels alias .3='cd ../../../' # Go back 3 directory levels alias .4='cd ../../../../' # Go back 4 directory levels alias .5='cd ../../../../../' # Go back 5 directory levels alias .6='cd ../../../../../../' # Go back 6 directory levels alias -- -="cd -" # Shortcuts alias h="history" # List files alias ll='ls -FGlAhp' # Preferred 'ls' implementation alias l="ls -lF ${colorflag}" # List all files colorized in long format alias la="ls -laF ${colorflag}" # List all files colorized in long format, including dot files alias lsd="ls -lF ${colorflag} | grep --color=never '^d'" # List only directories alias ls="command ls ${colorflag}" # Always use color output for `ls alias lr='ls -R | grep ":$" | sed -e '\''s/:$//'\'' -e '\''s/[^-][^\/]*\//--/g'\'' -e '\''s/^/ /'\'' -e '\''s/-/|/'\'' | less' alias cp='cp -iv' # Preferred 'cp' implementation alias mv='mv -iv' # Preferred 'mv' implementation alias mkdir='mkdir -pv' # Preferred 'mkdir' implementation #alias edit='subl' # edit: Opens any file in sublime editor alias f='open -a Finder ./' # f: Opens current directory in MacOS Finder alias which='type -all' # which: Find executables alias path='echo -e ${PATH//:/\\n}' # path: Echo all executable Paths alias show_options='shopt' # Show_options: display bash options settings alias fix_stty='stty sane' # fix_stty: Restore terminal settings when screwed up alias cic='set completion-ignore-case On' # cic: Make tab-completion case-insensitive alias battery='ioreg -w0 -l | grep Capacity | cut -d " " -f 17-50' # display battery info alias DT='tee ~/Desktop/terminalOut.txt' # DT: Pipe content to file on MacOS Desktop alias less='less -FSRXc' # Preferred 'less' implementation alias updatedb="sudo /usr/libexec/locate.updatedb" # Get macOS Software Updates, and update installed Ruby gems, Homebrew, npm, and their installed packages alias update='sudo softwareupdate -i -a; which brew > /dev/null && brew update && brew upgrade && brew cleanup; which npm > /dev/null && npm install npm -g && npm update -g; which gem > /dev/null && sudo gem update --system && sudo gem update && sudo gem cleanup; which nix-channel > /dev/null && nix-channel --update && nix-env -u --keep-going;' # Always enable colored `grep` output alias grep='grep --color=auto' alias fgrep='fgrep --color=auto' alias egrep='egrep --color=auto' # restart: Restart the Apple Remote Desktop service alias restart-ard='sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.screensharing.plist && sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.screensharing.plist' # memHogsTop, memHogsPs: Find memory hogs # ----------------------------------------------------- alias memHogsTop='top -l 1 -o rsize | head -20' alias memHogsPs='ps wwaxm -o pid,stat,vsize,rss,time,command | head -10' # cpuHogs: Find CPU hogs # ----------------------------------------------------- alias cpuHogsPs='ps wwaxr -o pid,stat,%cpu,time,command | head -10' # topForever: Continual 'top' listing (every 10 seconds) # ----------------------------------------------------- alias topForever='top -l 9999999 -s 10 -o cpu' # ttop: Recommended 'top' invocation to minimize resources # ------------------------------------------------------------ # Taken from this macosxhints article # http://www.macosxhints.com/article.php?story=20060816123853639 # ------------------------------------------------------------ alias ttop="top -R -F -s 10 -o rsize" alias numFiles='echo $(ls -1 | wc -l)' # numFiles: Count of non-hidden files in current dir alias make1mb='mkfile 1m ./1MB.dat' # make1mb: Creates a file of 1mb size (all zeros) alias make5mb='mkfile 5m ./5MB.dat' # make5mb: Creates a file of 5mb size (all zeros) alias make10mb='mkfile 10m ./10MB.dat' # make10mb: Creates a file of 10mb size (all zeros) # `cat` with beautiful colors alias cc='pygmentize -O style=monokai -f console256 -g' # Get OS X Software Updates, and update installed Ruby gems, Homebrew, npm, and their installed packages alias update='sudo softwareupdate -i -a; brew update; brew upgrade --all; brew cleanup; npm install npm -g; npm update -g; sudo gem update --system; sudo gem update' # Flush Directory Service cache alias clear-dns-cache='dscacheutil -flushcache && killall -HUP mDNSResponder' # Clean up LaunchServices to remove duplicates in the “Open With” menu alias lscleanup="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -domain local -domain system -domain user && killall Finder" # View HTTP traffic alias sniff="sudo ngrep -d 'en1' -t '^(GET|POST) ' 'tcp and port 80'" alias httpdump="sudo tcpdump -i en1 -n -s 0 -w - | grep -a -o -E \"Host\: .*|GET \/.*\"" # Trim new lines and copy to clipboard alias cn="tr -d '\n' | pbcopy" # Hide/Show hidden files in Finder alias hide-hidden-files='defaults write com.apple.finder AppleShowAllFiles -bool false && killall Finder' alias show-hidden-files='defaults write com.apple.finder AppleShowAllFiles -bool true && killall Finder' # Hide/show all desktop icons (useful when presenting) alias hidedesktop="defaults write com.apple.finder CreateDesktop -bool false && killall Finder" alias showdesktop="defaults write com.apple.finder CreateDesktop -bool true && killall Finder" # Disable/Enable Spotlight alias spotoff="sudo mdutil -a -i off" alias spoton="sudo mdutil -a -i on" # PlistBuddy alias, because sometimes `defaults` just doesn’t cut it alias plistbuddy="/usr/libexec/PlistBuddy" # Ring the terminal bell, and put a badge on Terminal.app’s Dock icon (useful when executing time-consuming commands) alias badge="tput bel" # Intuitive map function # For example, to list all directories that contain a certain file: # find . -name .gitattributes | map dirname alias map="xargs -n1" # Lock the screen (when going AFK) alias afk="/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend" # Restart Infrared alias restart-ir='sudo kextunload /System/Library/Extensions/AppleIRController.kext; sudo kextload /System/Library/Extensions/AppleIRController.kext;' # Reload the shell (i.e. invoke as a login shell) alias reload="exec $SHELL -l" #export LS_COLORS='no=00:fi=00:di=01;34:ln=01;36:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.gz=01;31:*.bz2=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.avi=01;35:*.fli=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.ogg=01;35:*.mp3=01;35:*.wav=01;35:'
de54c720536e64008c3350cb2f2e6c45db9793f5
[ "Markdown", "PHP", "Shell" ]
62
Shell
Supandi/OSX_MediaCenter_ElCapitan
d0868f0632f1c1f579d064b6477c359f71fde86c
698c1b4a333f46f1fea721ed1e2c4419f54257f1
refs/heads/master
<file_sep>{% extends 'base.html' %} {% block title %} Registration Form {% endblock %} {% block content %} <h1>Registration Form</h1> <!-- email, age, zipcode, password --> <form action="/register" method="POST"> Email: <input type="email" name="email" required><br> Password: <input type="<PASSWORD>" name="<PASSWORD>" required><br> Age: <input type="number" name="age" required><br> Zipcode: <input type="number" name="zipcode" required><br> <input type="submit"> </form> {% endblock %}<file_sep>"""Movie Ratings.""" from jinja2 import StrictUndefined from flask import Flask, render_template, redirect, request, flash, session, jsonify from flask_debugtoolbar import DebugToolbarExtension from model import connect_to_db, db, User, Rating, Movie app = Flask(__name__) # Required to use Flask sessions and the debug toolbar app.secret_key = "ABC" # Normally, if you use an undefined variable in Jinja2, it fails # silently. This is horrible. Fix this so that, instead, it raises an # error. app.jinja_env.undefined = StrictUndefined @app.route('/') def index(): """Homepage.""" return render_template('homepage.html') @app.route('/users') def user_list(): """Show a list of all users.""" users = User.query.all() return render_template('user_list.html', users=users) @app.route('/register', methods=["GET"]) def register_form(): """ Registration form """ return render_template('register_form.html') @app.route('/register', methods=["POST"]) def register_process(): """ Process registration """ email = request.form.get('email') password = <PASSWORD>.form.get('<PASSWORD>') age = request.form.get('age') zipcode = request.form.get('zipcode') user = User(email=email, password=<PASSWORD>, age=age, zipcode=zipcode) db.session.add(user) db.session.commit() flash('Yay! Successfully added!') return redirect('/') @app.route('/login') def login(): """Renders log in page""" return render_template('login.html') @app.route('/logged-in') def check_logged_in(): """Check if use is in database and login if is""" email = request.args.get("email") password = request.args.get("password") user_object = User.query.filter_by(email=email).first() if user_object: if user_object.password == <PASSWORD>: session["login"] = user_object.user_id flash(f"Hey, welcome back {user_object.email} of zipcode {user_object.zipcode}") return redirect(f"/user/{user_object.user_id}") else: flash(f"""You're wrong. Are you even {user_object.email} of zipcode {user_object.zipcode}? The password is actually {user_object.password}""") return redirect("/login") else: flash(f"""You're not real.""") return redirect("/login") @app.route("/log-out") def log_out(): """Log user out""" session["login"] = False flash("Logged out") return redirect("/") @app.route("/user/<user_id>") def user_page(user_id): user = User.query.get(user_id) return render_template('user_page.html', user=user) @app.route("/movies") def movie_list(): movies = Movie.query.order_by('title').all() return render_template("movie_list.html", movies=movies) @app.route("/movie/<movie_id>") def movie_details(movie_id): movie = Movie.query.get(movie_id) return render_template('movie_page.html', movie=movie) @app.route("/rate-movie", methods=["POST"]) def rate_movie(): """Process movie ratings """ rating = request.form.get("rating") score, movie_id = rating.split() user_id = session['login'] movie = Movie.query.get(movie_id) existing_user_rating = Rating.query.filter((Rating.user_id==user_id) & (Rating.movie_id==movie_id)).first() if existing_user_rating: print("Before", existing_user_rating.score) existing_user_rating.score = score print("After", existing_user_rating.score) else: rating = Rating( movie_id=movie_id, user_id=user_id, score=score ) db.session.add(rating) db.session.commit() return redirect(f"/movies") if __name__ == "__main__": # We have to set debug=True here, since it has to be True at the # point that we invoke the DebugToolbarExtension app.debug = True # make sure templates, etc. are not cached in debug mode app.jinja_env.auto_reload = app.debug connect_to_db(app) # Use the DebugToolbar DebugToolbarExtension(app) app.run(port=5000, host='0.0.0.0')
06fc0b821d6aa9a8bc6dfc242ed5f580388ac2ee
[ "Python", "HTML" ]
2
HTML
MenaAdams/ratings
c2ba82cb0a3ad501467e215193539ccbcff50798
442d0292b462b45f2ddac896c28d53c53c2f16f2
refs/heads/master
<file_sep>"use strict"; $(document).ready(function() { // Offset initialization and updating var offset = setOffset() $(window).resize(function () { offset = setOffset() }) function setOffset () { if ($('#navbar').is(':visible')) { return 50 } else { return 0 } } // Wow scroll animations var wow = new WOW( { boxClass: 'wow', // default animateClass: 'animated', // default offset: 200, mobile: true, // default live: false } ) wow.init() // Scrollspy $('body').scrollspy({target: '#navbar', offset: offset}) // Navbar clicks offset $('#navbar li a').click(function(event) { event.preventDefault() if ($(this).attr('href') == '#home') { $('html, body').animate({scrollTop: 0}, 500) } else { var target = $(this.hash) $('html, body').animate({scrollTop: target.offset().top - offset}, 500) } }) // Scroll back when opening a skill panel $('.skills .panel-heading').click(function() { $('html, body').animate({scrollTop: $('.skills .section-title').offset().top - offset}, 500) }) // Navbar shadow after main div $(document).scroll(function() { var y = $(this).scrollTop() var height = $(window).height() - (offset + 1) if (y > height) { $('#navbar').css('box-shadow', 'inset 0 -3px 5px -1px rgba(51, 51, 51, .6)') $('#navbar').css('z-index', '') } else { $('#navbar').css('box-shadow', 'none') $('#navbar').css('z-index', '1') } }) })<file_sep>var gulp = require('gulp') var jade = require('gulp-jade') var rename = require('gulp-rename') var cssnano = require('gulp-cssnano') var uglify = require('gulp-uglify') var livereload = require('gulp-livereload') var imagemin = require('gulp-imagemin') var pngquant = require('imagemin-pngquant') gulp.task('default', ['jades', 'styles', 'scripts', 'images', 'fonts']) gulp.task('dev', ['default', 'watch']) gulp.task('jades', function() { gulp.src('dev/jade/skel.jade') .pipe(jade({})) .pipe(rename('index.html')) .pipe(gulp.dest('./dist')) }) gulp.task('styles', function() { gulp.src(['dev/css/*.css', '!dev/css/*.min.css']) .pipe(cssnano()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest('./dist/css')) gulp.src('dev/css/*.min.css') .pipe(gulp.dest('./dist/css')) }) gulp.task('scripts', function() { gulp.src(['dev/js/*.js', '!dev/js/*.min.js']) .pipe(uglify()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest('./dist/js')) gulp.src('dev/js/*.min.js') .pipe(gulp.dest('./dist/js')) }) gulp.task('images', function() { gulp.src('dev/img/*.png') .pipe(imagemin( { optimizationLevel: 3, use: [pngquant()] } )) .pipe(gulp.dest('dist/img')) gulp.src('dev/img/svg/*.svg') .pipe(imagemin( { svgoPlugins: [{removeViewBox: false}] } )) .pipe(gulp.dest('dist/img/svg')) }) gulp.task('fonts', function() { gulp.src('dev/fonts/*') .pipe(gulp.dest('dist/fonts')) }) gulp.task('watch', function() { livereload.listen() gulp.watch(['dev/css/*.css', '!dev/css/*.min.css'], ['styles']) gulp.watch(['dev/js/*.js', 'dev/js/*.min.js'], ['scripts']) gulp.watch('dev/jade/*.jade', ['jades']) gulp.watch('dev/img/*.png', ['images']) gulp.watch('dev/img/svg/*.svg', ['images']) })<file_sep># dispix My personal website, using node.js, gulp, jade and more. <file_sep>var compress = require('compression') var express = require('express') var app = express() app.use(compress()) app.use(express.static(__dirname + '/dist')) app.set('views', __dirname + '/dist') app.set('view engine', 'html') app.get('/', function(req, res) { res.render('index.html') res.end() }) app.listen(8080)
f0c67022da7c109f2a2420c911cf7347e8f2e775
[ "JavaScript", "Markdown" ]
4
JavaScript
dispix/dispix
bcf12205ba2409a40385c38eeca2036727153e9a
4d24b94598cbb4b0e548226380b024c1dba5ae01
refs/heads/master
<file_sep>package com.kotlab.supreme.paging import android.arch.paging.PageKeyedDataSource import android.util.Log import com.example.pagination.RetrofitClient import com.example.pagination.Utils import com.example.pagination.Utils.Companion.NEWS_URL import com.kotlab.supreme.paging.response.ApiResponse import com.kotlab.supreme.paging.response.Article import retrofit2.Call import retrofit2.Callback import retrofit2.Response class FeedDataSource : PageKeyedDataSource<Int, Article>() { private val mTag = FeedDataSource::class.java.simpleName companion object { private const val PAGE: Int = 1 const val PAGE_SIZE: Int = 2 private const val COUNTRY: String = "in" } override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, Article>) { Log.d(mTag, "loadInitial called") val apiServices = RetrofitClient().sampleTest(NEWS_URL).create(RetrofitClient.Api::class.java) val result: Call<ApiResponse> = apiServices.getTopHeadlinesEndless(PAGE, PAGE_SIZE, COUNTRY, Utils.KEY_NEWS) result.enqueue(object : Callback<ApiResponse> { override fun onResponse(call: Call<ApiResponse>, response: Response<ApiResponse>) { if (response.body() != null) { callback.onResult(response.body()!!.articles!!, null, PAGE + 1) } } override fun onFailure(call: Call<ApiResponse>, t: Throwable) { } }) } override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, Article>) { Log.d(mTag, "loadBefore called") val apiServices = RetrofitClient().sampleTest(NEWS_URL).create(RetrofitClient.Api::class.java) val result: Call<ApiResponse> = apiServices.getTopHeadlinesEndless(params.key, PAGE_SIZE, COUNTRY, Utils.KEY_NEWS) result.enqueue(object : Callback<ApiResponse> { override fun onResponse(call: Call<ApiResponse>, response: Response<ApiResponse>) { val adjacentKey = (if (params.key > 1) params.key - 1 else null)!!.toInt() if (response.body() != null) { //val key = if (params.key > 1) params.key - 1 else null callback.onResult(response.body()!!.articles!!, adjacentKey) } } override fun onFailure(call: Call<ApiResponse>, t: Throwable) { } }) } override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, Article>) { Log.d(mTag, "loadAfter called") val apiServices = RetrofitClient().sampleTest(NEWS_URL).create(RetrofitClient.Api::class.java) val result: Call<ApiResponse> = apiServices.getTopHeadlinesEndless(params.key, PAGE_SIZE, COUNTRY, Utils.KEY_NEWS) result.enqueue(object : Callback<ApiResponse> { override fun onResponse(call: Call<ApiResponse>, response: Response<ApiResponse>) { if (response.body() != null) { callback.onResult(response.body()!!.articles!!, params.key + 1) } } override fun onFailure(call: Call<ApiResponse>, t: Throwable) { } }) } }<file_sep>package com.kotlab.supreme.paging import android.arch.lifecycle.MutableLiveData import android.arch.paging.DataSource import android.arch.paging.PageKeyedDataSource import com.kotlab.supreme.paging.response.Article class FeedDataSourceFactory : DataSource.Factory<Int, Article>() { private val itemLiveDataSource = MutableLiveData<PageKeyedDataSource<Int, Article>>() override fun create(): FeedDataSource { val itemDataSource = FeedDataSource() itemLiveDataSource.postValue(itemDataSource) return itemDataSource } fun getItemLiveDataSource(): MutableLiveData<PageKeyedDataSource<Int, Article>> { return itemLiveDataSource } }<file_sep>package com.kotlab.supreme.paging import android.arch.paging.PagedListAdapter import android.content.Context import android.support.v7.util.DiffUtil 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.bumptech.glide.Glide import com.example.pagination.R import com.kotlab.supreme.paging.response.Article class FeedPagedAdapter(private var cxt: Context?) : PagedListAdapter<Article, RecyclerView.ViewHolder>(DIFF_CALLBACK) { companion object { private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Article>() { override fun areItemsTheSame(oldItem: Article, newItem: Article): Boolean { return oldItem.url === newItem.url } override fun areContentsTheSame(oldItem: Article, newItem: Article): Boolean { return oldItem == newItem } } } override fun onCreateViewHolder(p0: ViewGroup, p1: Int): RecyclerView.ViewHolder { val view: View = LayoutInflater.from(cxt).inflate(R.layout.card_apps, p0, false) return MyViewHolder(view) } override fun onBindViewHolder(p0: RecyclerView.ViewHolder, p1: Int) { val feedModel: Article = this.getItem(p1)!! if (p0 is MyViewHolder) { p0.tvTitle.text = feedModel.title p0.tvDescription.text = feedModel.description Glide.with(cxt!!).load(feedModel.urlToImage).into(p0.ivUrlToImage) } } private class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) { var ivUrlToImage: ImageView = view.findViewById(R.id.iv_urlToImage) var tvTitle: TextView = view.findViewById(R.id.tv_title) var tvDescription: TextView = view.findViewById(R.id.tv_description) } }<file_sep>package com.example.pagination import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.widget.LinearLayout import com.kotlab.supreme.paging.FeedPagedAdapter import com.kotlab.supreme.paging.FeedViewModel class MainActivity : AppCompatActivity() { private lateinit var feedViewModel: FeedViewModel private lateinit var feedListAdapter: FeedPagedAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initData() } private fun initData() { feedViewModel = ViewModelProviders.of(this).get(FeedViewModel::class.java) feedListAdapter = FeedPagedAdapter(applicationContext) val recyclerView: RecyclerView = findViewById(R.id.recyclerView) recyclerView.layoutManager = LinearLayoutManager(applicationContext, LinearLayout.VERTICAL, false) feedViewModel.itemPagedList.observe(this, Observer { feedListAdapter.submitList(it) }) recyclerView.adapter = feedListAdapter } }<file_sep>package com.example.pagination import com.kotlab.supreme.paging.response.ApiResponse import okhttp3.* import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Query import java.io.IOException import java.util.concurrent.TimeUnit class RetrofitClient { private var retrofit: Retrofit? = null fun sampleTest(url: String): Retrofit { //logging interceptor val logging = HttpLoggingInterceptor() logging.level = HttpLoggingInterceptor.Level.BODY //okhttp library val client = OkHttpClient.Builder() client.connectTimeout(30, TimeUnit.SECONDS) client.readTimeout(30, TimeUnit.SECONDS) client.writeTimeout(30, TimeUnit.SECONDS) //client.cache(cache) client.build() //want to avoid custom url encoding , here is solution client.addInterceptor(object : Interceptor { @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() var string = request.url().toString() string = string.replace("%2C", ",") //string = string.replace("%3D", "="); val newRequest = Request.Builder() .url(string) .build() return chain.proceed(newRequest) } }) if (BuildConfig.DEBUG) { client.addInterceptor(logging) } if (retrofit == null) { retrofit = Retrofit.Builder() .baseUrl(url) .addConverterFactory(GsonConverterFactory.create()) .client(client.build()) .build() } return retrofit!! } interface Api { /** * feed top head line in endless manner */ @GET("top-headlines") fun getTopHeadlinesEndless( @Query("page") page: Int, @Query("pageSize") pageSize: Int, @Query("country") country: String, @Query("apiKey") apiKey: String ): Call<ApiResponse> /** * feed top head line with lazy loading */ @GET("top-headlines") fun getTopHeadlinesLazy( @Query("country") country: String, @Query("apiKey") apiKey: String ): Call<ResponseBody> /** * weather information api using query */ @GET("weather") fun getWeather( @Query("q") cityNameAndCountryCode: String, @Query("appid") appid: String ): Call<ResponseBody> /** * weather information api using query */ @GET("weather") fun getWeatherLatLon( @Query("lat") lat: String, @Query("lon") lon: String, @Query("appid") appid: String ): Call<ResponseBody> } }<file_sep>package com.kotlab.supreme.paging import android.arch.lifecycle.LiveData import android.arch.lifecycle.ViewModel import android.arch.paging.LivePagedListBuilder import android.arch.paging.PageKeyedDataSource import android.arch.paging.PagedList import com.kotlab.supreme.paging.response.Article class FeedViewModel : ViewModel() { var itemPagedList: LiveData<PagedList<Article>> private var liveDataSource: LiveData<PageKeyedDataSource<Int, Article>> init { val itemDataSourceFactory = FeedDataSourceFactory() liveDataSource = itemDataSourceFactory.getItemLiveDataSource() val config = PagedList.Config.Builder() .setEnablePlaceholders(false) .setPageSize(FeedDataSource.PAGE_SIZE) .build() itemPagedList = LivePagedListBuilder(itemDataSourceFactory, config).build() } }
2f1b7791b939f96d0696d566f1bc08cde3135ceb
[ "Kotlin" ]
6
Kotlin
technologist25/Pagination
3c233d111f31768bfc7d9f5b10171d8dd2134fc5
bf3b063f253db3ef5557f6e637c3afc9361b4931
refs/heads/master
<file_sep># git-bash-linux git-bash-linux # 在/etc/bashrc 和 ~/.bashrc 前面添加这些代码 ```bash function get_git_branch_now { git branch --no-color 2> /dev/null | awk '/\*/{printf "\033[34m[>"$2"]\033[0m" }' return 0 } function get_git_status_now { #合并冲突状态 git status 2> /dev/null | grep -q "Unmerged paths" && echo -e '\033[41;37m*\033[0m' && return 0 #未暂存状态 git status 2> /dev/null | grep -qE "Changes not staged for commit|Changed but not updated" && echo -e '\033[31m*\033[0m' && return 0 #未提交状态 git status 2> /dev/null | grep -q "Changes to be committed" && echo -e '\033[33m*\033[0m' && return 0 } [ "$PS1" = "\\s-\\v\\\$ " ] && PS1="\[\e[36m\][\u\[\e[0m\]\[\e[5m\] \[\e[0m\]\h \[\e[32m\]\w\[\e[36m\]]\[\e[0m\]\$(get_git_branch_now)\$(get_git_status_now)\\$ " ``` **** # 在命令行中敲这些命令 ```bash git config --global color.status auto git config --global color.diff auto git config --global color.branch auto git config --global color.interactive auto ``` **** # 在命令行中敲这些命令 ```bash git config --global alias.lg "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'" ``` <file_sep>#include<stdio.h> #include<stdlib.h> #include <pthread.h> typedef struct threadArg{ int tid; char s; int tx; }tArg; void *funcA(void *p){ tArg * x = (tArg *)p; int i = 0; for(;i < 5 ; i++){ printf("线程%d第%d次执行!其中tx为:%d。s字符为:%s%c%s。\n",x->tid,i,x->tx,"=======",x->s,"======"); //if(p)free(p); x->tx = 123400 + x->tid; sleep(1); } return (void *)x; } int main(){ int i = 0; for(; i < 10 ; i++){ pthread_t t_1; tArg *p = (tArg *)malloc(sizeof(tArg)); p->s = 'x'; p->tid = i ; if(pthread_create(&t_1,NULL,funcA,(void*)p)){ printf("funcA_t create failed!\n"); } //tArg *sdf = NULL; //pthread_join(t_1,(void **)&sdf); //printf("wo huo zhe chu lai la!=============> %d\n",sdf->tx); } pthread_exit(NULL); //while(1){ // sleep(5); //} //return 0; }
b6adfe9f8eaf118c85500cfec50dfc180a032c53
[ "Markdown", "C" ]
2
Markdown
niroshea/git-bash-linux
bffc0485177f59e9e5732de95755f252b039f2d8
2ef55f53c132538e3cbbdf3c318face7cebcb82f
refs/heads/master
<file_sep>#!/usr/bin/env node const fs = require('fs'); const chalk = require('chalk'); const path = require('path'); const targetDir = process.argv[2] || process.cwd(); fs.readdir(targetDir, async (err, filenames) => { if (err !== null) { console.log(err) return; } const statPromises = filenames.map(filename => { return lstat(path.join(targetDir, filename)) }); const allStats = await Promise.all(statPromises); for (let stats of allStats) { const index = allStats.indexOf(stats); if (stats.isFile()) console.log(filenames[index]) else console.log(chalk.bold(filenames[index])) } }); const lstat = filename => { return new Promise((res, rej) => { fs.lstat(filename, (err, stats) => { if (err !== null) { rej(err); } res(stats); }); }); }
7d2c178e44f545f18e2e3b16f7684a9bb5aa7e0a
[ "JavaScript" ]
1
JavaScript
marcburnie/node-ls
4179183574f35756255466883378b062465e7752
3ad2df71f334a3a1fe362436315e93773883cd9a
refs/heads/master
<file_sep>#!/usr/bin/env python # coding: utf-8 import argparse import os import glob import time from torch.utils.data import Dataset, DataLoader import pandas as pd from torchvision import transforms, utils, datasets from PIL import Image import torch from torch import nn from torch.nn import functional as F import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import torchvision import matplotlib.pyplot as plt import numpy as np import SYNet import sklearn.metrics import itertools from tensorboardX import SummaryWriter writer = SummaryWriter('runs/nonupsampled_resnet18') log = "" class_names = ["concrete_cement","healthy_metal","incomplete","irregular","other"] def plot_confusion_matrix(cm, class_names): figure = plt.figure(figsize=(8, 8)) plt.imshow(cm, interpolation='nearest', cmap=plt.cm.YlGn) plt.title("Confusion matrix") plt.colorbar() tick_marks = np.arange(len(class_names)) plt.xticks(tick_marks, class_names, rotation=45) plt.yticks(tick_marks, class_names) # Normalize the confusion matrix. cm = np.around(cm.astype('float') / cm.sum(axis=1)[:, np.newaxis], decimals=2) # Use white text if squares are dark; otherwise black. threshold = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): color = "gray" if cm[i, j] > threshold else "black" plt.text(j, i, cm[i, j], horizontalalignment="center", color=color) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') return figure def log_confusion_matrix(epoch, output, label): # Calculate the confusion matrix. cm = sklearn.metrics.confusion_matrix(label, output) # Log the confusion matrix as an image summary. figure = plot_confusion_matrix(cm, class_names=class_names) # Log the confusion matrix as an image summary. writer.add_figure('Valid/confusion_matrix', figure, epoch) class EarlyStopping: def __init__(self, patience=5, verbose=False, delta=0, backbone=None): self.patience = patience self.verbose = verbose self.counter = 0 self.best_score = None self.early_stop = False self.val_loss_min = np.Inf self.delta = delta self.best_step = -1 self.backbone = backbone def __call__(self, val_loss, model, epoch): score = -val_loss if self.best_score is None: self.best_score = score self.save_checkpoint(val_loss, model, epoch) elif score < self.best_score - self.delta: self.counter += 1 print(f'EarlyStopping counter: {self.counter} out of {self.patience}') print("current min val loss:", self.val_loss_min) if self.counter >= int(self.patience): self.early_stop = True else: self.best_score = score self.save_checkpoint(val_loss, model, epoch) self.counter = 0 def save_checkpoint(self, val_loss, model, epoch): if self.verbose: print(f'Validation loss decreased at epoch {epoch} ({self.val_loss_min:.6f} --> {val_loss:.6f}). Saving model ...') torch.save(model.state_dict(), '{}_checkpoint.pt'.format(self.backbone)) self.val_loss_min = val_loss self.best_step = epoch class RoofDataset(Dataset): def __init__(self, train_image_paths, train_images_labels,transform=None): self.image_paths = train_image_paths self.image_labels = train_images_labels self.transform=transform def __getitem__(self, index): roof_image = Image.open(self.image_paths[index]) roof_image = roof_image.convert('RGB') if self.transform is not None: roof_image = self.transform(roof_image) material_type = torch.LongTensor(self.image_labels[index]) return roof_image, material_type def __len__(self): return len(self.image_paths) def load_data(batch_size, upsampling, retrain, options): # Define Class Labels concrete_cement_type = [1.0, 0.0, 0.0, 0.0, 0.0] healthy_metal_type = [0.0, 1.0, 0.0, 0.0, 0.0] incomplete_type = [0.0, 0.0, 1.0, 0.0, 0.0] irregular_metal_type = [0.0, 0.0, 0.0, 1.0, 0.0] other_type = [0.0, 0.0, 0.0, 0.0, 1.0] #1387 concrete_cement_images = glob.glob('./training/unmasked/concrete_cement/*.png') a= [concrete_cement_type] * len(concrete_cement_images) #7381 healthy_metal_images = glob.glob('./training/masked/healthy_metal/*.png') b=[healthy_metal_type] * len(healthy_metal_images) #668 incomplete_images = glob.glob('./training/masked/incomplete/*.png') if upsampling: incomplete_images = incomplete_images * 2 c=[incomplete_type] * len(incomplete_images) #5241 irregular_metal_images = glob.glob('./training/masked/irregular_metal/*.png') d=[irregular_metal_type] * len(irregular_metal_images) #193 other_images = glob.glob('./training/masked/other/*.png') if upsampling: other_images = other_images * 5 e=[other_type] * len(other_images) train_images = [concrete_cement_images, healthy_metal_images, incomplete_images, irregular_metal_images, other_images] train_images_labels = [a,b,c,d,e] train_images = [item for sublist in train_images for item in sublist] train_images_labels = [item for sublist in train_images_labels for item in sublist] scale = 299 if options.pretrained_name=='inception' else 224 transformations = transforms.Compose([ transforms.RandomHorizontalFlip(), transforms.RandomRotation(degrees = 90, resample = False, expand = True), transforms.RandomVerticalFlip(), transforms.Resize((scale,scale)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) print('Length of given dataset : {}'.format(len(train_images))) validation_images = train_images[::5] validation_images_labels = train_images_labels[::5] if not retrain: indices = [i for i in range(len(train_images)) if (i) % 5] train_images = [train_images[i] for i in indices] train_images_labels = [train_images_labels[i] for i in indices] train_dataset = RoofDataset(train_images, train_images_labels, transformations) train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=0 ) valid_transforms = transforms.Compose([ transforms.Resize((scale,scale)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) valid_dataset = RoofDataset(validation_images, validation_images_labels, valid_transforms) valid_loader = DataLoader(valid_dataset, batch_size=batch_size, shuffle=False, num_workers=0) print('Length of train_loader : {} | Length of valid_loader : {}'.format(len(train_loader.dataset), len(valid_loader.dataset))) return train_loader, valid_loader def train(epochs, train_loader, valid_loader, options, best_step=None): global log model = SYNet.Baseline(options.pretrained_name, eval(options.train_all)) model.cuda() optimizer = optim.SGD(model.parameters(), lr=float(options.lr), momentum=float(options.momentum), weight_decay=float(options.weight_decay)) #class_weights = [7381/1387, 7381/7381, 7381/668, 7381/5241, 7381/193] #if eval(options.upsampling): # class_weights = [7381/1387, 7381/7381, 7381/(668 * 2), 7381/5241, 7381/(193 * 5)] #class_weights = torch.FloatTensor(class_weights) #criterion = nn.CrossEntropyLoss(weight=class_weights.cuda()) criterion = nn.CrossEntropyLoss() train_tag = 'Train' valid_tag = 'Valid' if best_step is None: early_stopping = EarlyStopping(patience=options.patience, verbose=True, backbone=options.pretrained_name) if best_step is not None: epochs = best_step train_tag = "Retrain" valid_tag = "Revalid" for epoch in range(1, epochs + 1): train_losses = [] for batch_idx, (data, target) in enumerate(train_loader): model.train() data = data.cuda(async=True) target = target.cuda(async=True) optimizer.zero_grad() output = model(data) # Output format different for inception output = output[0] if options.pretrained_name == 'inception' else output _, idx = torch.max(target,1) loss = criterion(output, idx) train_losses.append(loss.item()) loss.backward() optimizer`.step() if batch_idx % 30 == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.data)) writer.add_scalar('{}/batch_loss'.format(train_tag), loss.item(), (epoch - 1) * len(train_loader) + batch_idx) valid_losses = [] nll_losses = [] predlist = torch.zeros(0,dtype=torch.long, device='cpu') labellist = torch.zeros(0,dtype=torch.long, device='cpu') with torch.no_grad(): for batch_idx, (data, target) in enumerate(valid_loader): model.eval() data, target = data.cuda(), target.cuda() # Output format different for inception output = model(data) output = output[0] if options.pretrained_name == 'inception' else output _, idx = torch.max(target, 1) _, pred = torch.max(output, 1) predlist=torch.cat([predlist,pred.view(-1).cpu()]) labellist = torch.cat([labellist,idx.view(-1).cpu()]) loss = criterion(output, idx) subloss = nn.functional.nll_loss(nn.functional.log_softmax(output, dim=1), idx) valid_losses.append(loss.item()) nll_losses.append(subloss.item()) if batch_idx % 30 == 0: writer.add_scalar('{}/batch_loss'.format(valid_tag), loss.item(), (epoch - 1) * len(valid_loader) + batch_idx) if best_step is None and epoch % 10 == 0: log_confusion_matrix(epoch, predlist.numpy(), labellist.numpy()) print('\nEpoch: [{} / {}], Train Loss: {} | Validation Loss: {}\n'.format(epoch, epochs, np.average(train_losses), np.average(valid_losses))) print("nllLoss: {}\n".format(np.average(nll_losses))) writer.add_scalar('{}/epoch_loss'.format(train_tag), np.average(train_losses), epoch) writer.add_scalar('{}/epoch_loss'.format(valid_tag), np.average(valid_losses), epoch) writer.add_scalar('{}/epoch_nll_loss'.format(valid_tag), np.average(nll_losses), epoch) if best_step is None: early_stopping(np.average(valid_losses), model, epoch) if early_stopping.early_stop: print("Early Stopping") break if best_step is None: best_step = early_stopping.best_step log += "Best step achieved: {}\n".format(best_step) log += "Best valloss achieved: {}\n".format(early_stopping.val_loss_min) model.load_state_dict(torch.load('{}_checkpoint.pt'.format(options.pretrained_name))) print("Best model loaded from checkpoint successfully") log += "Final Validation Error achieved: {}\n".format(np.average(valid_losses)) return model, best_step def main(): parser = argparse.ArgumentParser() parser.add_argument('--batch_size', dest='batch_size', default=32, help='batch size for training') parser.add_argument('--learning_rate', dest='lr', default=0.0001, help='(initial)learning rate for training') parser.add_argument('--momentum', dest='momentum', default=0.5, help='momentum for optimizer') parser.add_argument('--weight_decay', dest='weight_decay', default=0.01, help='value of weight decay') parser.add_argument('--epoch', dest='epoch', default=50, help='epochs for training') parser.add_argument('--model_name', dest="model_name", required=True, help="name of model to be saved to .pt file") parser.add_argument('--pretrained_name', dest='pretrained_name', required=True, help="name of pretrained model to be used for transfer learning") parser.add_argument('--train_all', dest='train_all', default=False, help='whether to finetune on all layers') parser.add_argument('--upsampling', dest='upsampling', default=True, help='whether to use upsampling or not') parser.add_argument('--retrain', dest='retrain', default=False, help='whether to retrain on best step acquired from early Stopping') parser.add_argument('--patience', dest='patience', default=30, help='patience value for early stopping') parser.add_argument('--note', dest='note', required=True, help="brief description of model being trained") options = parser.parse_args() print(options.pretrained_name) global log log += "=====================================\n" log += "{}\n".format(options.note) log += "Backbone used: {}\n".format(options.pretrained_name) log += "Model name to be saved: {}\n".format(options.model_name) log += "upsampling used?: {}\n".format(options.upsampling) log += "Retrain after early stopping? {}\n".format(options.retrain) log += "How many Layers are going to be frozen? {}\n".format(options.train_all) log += "\nHyperparameters Used:: \n" log += "Batch size: {} | Learning Rate: {}\n".format(options.batch_size, options.lr) log += "Momentum : {} | Weight decay : {}\n".format(options.momentum, options.weight_decay) log += "Epoch: {} | Patience : {}\n".format(options.epoch, options.patience) train_loader, valid_loader = \ load_data(int(options.batch_size), eval(options.upsampling), False, options) log += "\n Training summary: \n" model, best_step = train(int(options.epoch), train_loader, valid_loader, options) torch.save(model.state_dict(), './models/{}'.format(options.model_name)) print("Model {} has been saved successfully after {} epochs.".format( options.model_name, best_step)) if eval(options.retrain): log += "\n Retraining summary: \n" print("\nRetraining INCLUDING valset, up to {} epochs".format(best_step)) train_loader, valid_loader = \ load_data(int(options.batch_size), eval(options.upsampling), True, options) model, _ = train(int(options.epoch), train_loader, valid_loader, options, best_step) torch.save(model.state_dict(), './models/retrained_{}'.format(options.model_name)) print("Retrained model has been saved. {}".format('./models/retrained_{}'.format(options.model_name))) log += "=====================================\n" with open ("log.txt", "a") as f: f.write(log) if __name__ == '__main__': main() <file_sep>#!/usr/bin/env python # coding: utf-8 import math import torch import torch.nn as nn import torch.nn.functional as F import torchvision from torchvision import datasets, models class SYNet(nn.Module): """Container module for SYNet""" def __init__(self, params): super(SYNet, self).__init__() pass def init_weights(self): pass def forward(modelsself, input, hidden): pass def init_hidden(self, bsz): pass def Baseline(model_name, train_all): i = 0 if(model_name == 'resnet18'): model = models.resnet18(pretrained = True) for child in model.children(): i += 1 if i <= train_all: for param in child.parameters(): param.required_grad = False num_ftrs = model.fc.in_features model.fc = nn.Linear(num_ftrs, 5) elif(model_name == 'resnet50'): model = models.resnet50(pretrained = True) for child in model.children(): i += 1 if i <= train_all: for param in child.parameters(): param.required_grad = False num_ftrs = model.fc.in_features model.fc = nn.Linear(num_ftrs, 5) elif(model_name == 'resnet101'): model = models.resnet101(pretrained = True) for child in model.children(): i += 1 if i <= train_all: for param in child.parameters(): param.required_grad = False num_ftrs = model.fc.in_features model.fc = nn.Linear(num_ftrs, 5) elif(model_name == 'vgg16'): if(train_all): model = models.vgg16(pretrained=True) num_ftrs = model.classifier[6].in_features model.classifier[6] = nn.Linear(num_ftrs, 5, bias=True) else: model = models.vgg16(pretrained = True) for param in model.parameters(): param.required_grad = False num_ftrs = model.classifier[6].in_features model.classifier[6] = nn.Linear(num_ftrs, 5, bias=True) elif(model_name == 'densenet121'): if(train_all): model = models.densenet121(pretrained=True) num_ftrs = model.classifier.in_features model.classifier = nn.Linear(num_ftrs, 5, bias=True) else: model = models.densenet121(pretrained = True) for param in model.parameters(): param.required_grad = False num_ftrs = model.classifier.in_features model.classifier = nn.Linear(num_ftrs, 5, bias=True) elif(model_name == 'mnasnet1_0'): if(train_all): model = models.mnasnet1_0(pretrained=True) num_ftrs = model.classifier[1].in_features model.classifier[1] = nn.Linear(num_ftrs, 5, bias=True) else: model = models.mnasnet1_0(pretrained = True) for param in model.parameters(): param.required_grad = False num_ftrs = model.classifier[1].in_features model.classifier[1] = nn.Linear(num_ftrs, 5, bias=True) return model <file_sep># Training python train.py \ --batch_size 32 \ --learning_rate 0.0001 \ --momentum 0.5 \ --weight_decay 0.01 \ --epoch 150 \ --model_name temp.pt \ --pretrained_name resnet18 \ --train_all False \ --upsampling True \ --retrain True \ --patience 20 \ --note with_class_weights_maxOverMin # Testing # if retrain==True, and you want to test on the retrained model # append "retrained_" in front of model_name python test.py \ --model_name temp.pt \ --pretrained_name resnet18 python test.py \ --model_name retrained_temp.pt \ --pretrained_name resnet18 <file_sep>#!/usr/bin/env python # coding: utf-8 import argparse from torch.utils.data import Dataset, DataLoader import pandas as pd from PIL import Image import torch import torch.nn as nn import torchvision from torchvision import transforms import SYNet import time class RoofTestDataset(Dataset): def __init__(self, image_paths, transform=None): self.image_paths = image_paths self.transform=transform def __getitem__(self, index): roof_id = self.image_paths[index].replace('./testing/masked/', '').replace('.png', '') roof_image = Image.open(self.image_paths[index]) roof_image = roof_image.convert('RGB') if self.transform is not None: roof_image = self.transform(roof_image) return roof_image, roof_id def __len__(self): return len(self.image_paths) def load_data(): test_images = list(pd.read_csv("submission_format.csv",index_col=0).index.values) test_images = ['./testing/masked/' + str(i) + '.png' for i in test_images] transformations = transforms.Compose([ transforms.Resize((224,224)), transforms.ToTensor() ]) test_dataset = RoofTestDataset(test_images, transformations) test_loader = DataLoader(test_dataset, batch_size = 1, num_workers = 0) return test_loader def test(model, test_loader): for p in model.parameters(): if p.grad is not None: del p.grad torch.cuda.empty_cache() test_id = [] test_label = [] list_from_labelTensor = [] model.eval() predictions = [] for data, roof_id in test_loader: replaced_roof_id = roof_id[0] test_id.append(replaced_roof_id) data = data.cuda(async=True) # On GPU output_res = model(data) list_from_labelTensor = \ torch.nn.functional.softmax(output_res, dim=1).tolist() test_label.append(list_from_labelTensor) return test_id, test_label def pred_to_csv(test_id, test_label, model_name): submission_dict = {} submission_dict['id'] = [] submission_dict['concrete_cement'] = [] submission_dict['healthy_metal'] = [] submission_dict['incomplete'] = [] submission_dict['irregular_metal'] = [] submission_dict['other'] = [] for i, j in zip(test_id, test_label): submission_dict['id'].append(i) submission_dict['concrete_cement'].append(j[0][0]) submission_dict['healthy_metal'].append(j[0][1]) submission_dict['incomplete'].append(j[0][2]) submission_dict['irregular_metal'].append(j[0][3]) submission_dict['other'].append(j[0][4]) csv_filename = model_name.split('.')[0] + '.csv' pd.DataFrame(submission_dict).to_csv( "./submissions/{}".format(csv_filename), index = False) print("Prediction results have been successfully saved to {}".format( "./submissions/{}".format(csv_filename))) def main(): parser = argparse.ArgumentParser() parser.add_argument('--model_name', dest="model_name", required=True, help="name of model to be retrieved from .pt file") parser.add_argument('--pretrained_name', dest="pretrained_name", required=True, help="name of pretrained model being used") options = parser.parse_args() model = SYNet.Baseline(options.pretrained_name, True) model.load_state_dict(torch.load('./models/{}'.format(options.model_name))) model.cuda() test_loader = load_data() test_id, test_label = test(model, test_loader) pred_to_csv(test_id, test_label, options.model_name) if __name__ == '__main__': main() <file_sep># OpenAI_Caribbean_Challenge 2019 Fall Semester Computer Vision Project Final Rank: 21st Code to be updated
b4ff80ed32f7a7660096169dbcdddb283fd2e91b
[ "Markdown", "Python", "Shell" ]
5
Python
wookiekim/OpenAI_Caribbean_Challenge
e5ec8bbfaa68bf4e7c2d57667dbd0742b2984060
4f09f8e24df0eb70ae113f8c2c80b2e641461a9b
refs/heads/master
<file_sep>#Autor: <NAME> #Grupo 02 #Descripción: Con una serie de funciones se crea figuaras geometricas. import pygame # Librería de pygame import math #Librería de matematicas de python # Dimensiones de la pantalla ANCHO = 800 ALTO = 800 # Colores BLANCO = (255, 255, 255) # R,G,B en el rango [0,255], 0 ausencia de color, 255 toda la intensidad #Crea colores aleatorios. def color(): return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255) #Dibuja la primera figura. def figura1(ventana): l = 2 radioMenor = 50 radioMayor = 140 k = radioMenor / radioMayor r = radioMenor // math.gcd(radioMenor, radioMayor) for angulo in range(0, 360 * r + 1): a = math.radians(angulo) x = int(radioMayor * ((1 - k) * math.cos(a) + l * k * math.cos((1 - k) * a / k))) y = int(radioMayor * ((1 - k) * math.sin(a) - l * k * math.sin((1 - k) * a / k))) pygame.draw.circle(ventana, color(), (x + ANCHO // 2, ALTO // 2 - y), 1) #Dibuja la segunda figura. def figura2(ventana): l = .8 radioMenor = 70 radioMayor = 300 k = radioMenor / radioMayor r = radioMenor // math.gcd(radioMenor, radioMayor) for angulo in range(0, 360 * r + 1): a = math.radians(angulo) x = int(radioMayor * ((1 - k) * math.cos(a) + l * k * math.cos((1 - k) * a / k))) y = int(radioMayor * ((1 - k) * math.sin(a) - l * k * math.sin((1 - k) * a / k))) pygame.draw.circle(ventana, color(), (x + ANCHO // 2, ALTO // 2 - y), 1) #Dibuja la tercerafigura. def figura3(ventana): l = .6 radioMenor = 5 radioMayor = 150 k = radioMenor / radioMayor r = radioMenor // math.gcd(radioMenor, radioMayor) for angulo in range(0, 360 * r + 1): a = math.radians(angulo) x = int(radioMayor * ((1 - k) * math.cos(a) + l * k * math.cos((1 - k) * a / k))) y = int(radioMayor * ((1 - k) * math.sin(a) - l * k * math.sin((1 - k) * a / k))) pygame.draw.circle(ventana, color(), (x + ANCHO // 2, ALTO // 2 - y), 1) #Dibuja la cuarta figura. def figura4(ventana): l = .6 radioMenor = 70 radioMayor = 400 k = radioMenor / radioMayor r = radioMenor // math.gcd(radioMenor, radioMayor) for angulo in range(0, 360 * r + 1): a = math.radians(angulo) x = int(radioMayor * ((1 - k) * math.cos(a) + l * k * math.cos((1 - k) * a / k))) y = int(radioMayor * ((1 - k) * math.sin(a) - l * k * math.sin((1 - k) * a / k))) pygame.draw.circle(ventana,color(), (x + ANCHO // 2, ALTO // 2 - y), 1) #Dibuja la quinta figura. def figura5(ventana): l = 7 radioMenor = 40 radioMayor = 100 k = radioMenor / radioMayor r = radioMenor // math.gcd(radioMenor, radioMayor) for angulo in range(0, 360 * r + 1): a = math.radians(angulo) x = int(radioMayor * ((1 - k) * math.cos(a) + l * k * math.cos((1 - k) * a / k))) y = int(radioMayor * ((1 - k) * math.sin(a) - l * k * math.sin((1 - k) * a / k))) pygame.draw.circle(ventana, color(), (x + ANCHO // 2, ALTO // 2 - y), 1) #Inicia Pygame, llama a las funciones de para dibujar las figuras. def dibujarEspirografo(): # Estructura básica de un programa que usa pygame para dibujar # Inicializa el motor de pygame pygame.init() # Crea una ventana de ANCHO x ALTO ventana = pygame.display.set_mode((ANCHO, ALTO)) # Crea la ventana donde dibujará reloj = pygame.time.Clock() # Para limitar los fps termina = False # Bandera para saber si termina la ejecución, iniciamos suponiendo que no while not termina: # Ciclo principal, MIENTRAS la variable termina sea False, el ciclo se repite automáticamente # Procesa los eventos que recibe for evento in pygame.event.get(): if evento.type == pygame.QUIT: # El usuario hizo click en el botón de salir termina = True # Queremos terminar el ciclo # Borrar pantalla ventana.fill(BLANCO) # Dibujar, aquí haces todos los trazos que requieras # Normalmente llamas a otra función y le pasas -ventana- como parámetro, por ejemplo, dibujarLineas(ventana) # Consulta https://www.pygame.org/docs/ref/draw.html para ver lo que puede hacer draw figura1(ventana) figura2(ventana) figura3(ventana) figura4(ventana) figura5(ventana) pygame.display.flip() # Actualiza trazos (Si no llamas a esta función, no se dibuja) reloj.tick(40) # 40 fps # Después del ciclo principal pygame.quit() # termina pygame #Funcion main llama a la funcion que inicia pygam y dibuja las figuras. def main(): dibujarEspirografo() #LLama a la funcion main. main()
1f1223351b9ccf1f56cd834523ba30ffc1e5c9c7
[ "Python" ]
1
Python
DanCordova/Mision_06
0702bfdf82c282525fa3d0bc24f3460c72c31c02
7f6caf287a2098bf1362afa5c700d38a877acec4