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.codecool.kindergarten.child; public enum Activities { SINGING, PLAYING_BALL, DRAWING, DANCING } <file_sep>package com.codecool.kindergarten.child; public class LivelyChild extends Child { public LivelyChild(String name) { super(name); } @Override void changeSatisfaction(Activities activity) { switch (activity) { case SINGING: if (getSatisfaction() > 0) { setSatisfaction(getSatisfaction() - 1); } break; case PLAYING_BALL: setSatisfaction(3); break; case DRAWING: if (getSatisfaction() > 0) { setSatisfaction(getSatisfaction() - 1); } break; case DANCING: break; } } } <file_sep>package com.codecool.kindergarten.child; public abstract class Child { private String name; private int satisfaction = 2; private boolean isWhining = false; public Child(String name) { this.name = name; } abstract void changeSatisfaction(Activities activity); private void changeWhining() { setWhining(satisfaction == 0); } public final void playFor30Minutes(Activities activity) { changeSatisfaction(activity); changeWhining(); System.out.println(toString()); } @Override public String toString() { return "Name: " + this.name + " Personality: " + this.getClass().getSimpleName() + " Satisfaction: " + this.satisfaction + " Whining: " + isWhining; } public int getSatisfaction() { return satisfaction; } public void setSatisfaction(int satisfaction) { this.satisfaction = satisfaction; } public boolean isWhining() { return isWhining; } public void setWhining(boolean whining) { isWhining = whining; } }
6f6382f63af0bc18c7ae5f1e496cef973bc71ca0
[ "Java" ]
3
Java
huszarpp/Kindergarten
03f3726944abdc6c2e9553311f685887dafb58ff
ac931c8c5ffd2fd48e79b25a6cf749cc14d364bb
refs/heads/master
<repo_name>LoganWright/PodPool<file_sep>/README.md The hosting repo of all the various Pod classes <file_sep>/MarginLabel/README.md A class of label that draws the text within a specified margin. <file_sep>/MarginLabel/MarginLabel.podspec Pod::Spec.new do |spec| spec.name = 'MarginLabel' spec.version = '1.0' spec.license = 'MIT' spec.homepage = 'https://github.com/LoganWright/PodPool' spec.authors = { '<NAME>' => '<EMAIL>' } spec.summary = 'ARC and GCD Compatible Reachability Class for iOS and OS X.' spec.source = { :git => 'https://github.com/LoganWright/PodPool.git', :tag => 'MarginLabel-1.0' } spec.source_files = 'MarginLabel/MarginLabel/LGMarginLabel.{h,m}' spec.platform = :ios end
44e3b6ee52c8385dd0d0790245886c98724670a3
[ "Markdown", "Ruby" ]
3
Markdown
LoganWright/PodPool
40f0ff579b7025200c56b7e20709193d9de2bc3e
59a25924e5125186daa01b2c9155f8165eb9d7eb
refs/heads/master
<file_sep>/* Write iterative and recursive code for square matrix multiplication. Find the largest dimension for which you are able to successfully carryout matrix multiplication. Report the number of page faults and TLB hit ratio. Can we compute the page fault ratio too? */ //usr/bin/time ./a.out also gives the number of page faults // perf stat -e dTLB-load-misses,iTLB-load-misses ./a.out // perf stat -e iTLB-loads ./a.out /*5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 */ //for the above input //37/(638+37) is thr tlb hit ratio //0.054814814814814816 //This is iterative square matrix multiplication // the largest dimension for which you are able to successfully carryout matrix multiplication is 835 // #include<stdio.h> #include<sys/resource.h> #include<sys/time.h> #include<unistd.h> int main() { int m; struct rusage usage; scanf("%d",&m); int i,j; int arr1[m][m]; int arr2[m][m]; int arr3[m][m]; getrusage(RUSAGE_SELF, &usage); for(i=0;i<m;i++) { for(j=0;j<m;j++) { scanf("%d",&arr1[i][j]); } } for(i=0;i<m;i++) { for(j=0;j<m;j++) { scanf("%d",&arr2[i][j]); } } int k; for(i=0;i<m;i++) { for(j=0;j<m;j++) { arr3[i][j]=0; for(k=0;k<m;k++) { arr3[i][j]+=arr1[i][k]*arr2[k][j]; } } } for(i=0;i<m;i++) { for(j=0;j<m;j++) { printf("%d ",arr3[i][j]); } printf("\n"); } //ru_majflt gives the number of major page faults ie when disk access is required //ru_minflt gives the number of minor page faults ie when page allocation to tlb is made printf("Number of page faults are %ld",usage.ru_majflt + usage.ru_minflt); return 0; } <file_sep>#include<sys/types.h> #include<sys/stat.h> #include<stdio.h> int main(int argc, char* argv[]) { // printf("%s",argv[1]); int a; char mode[]="0775"; int i; i=strtol(mode,0,8); a=chmod("../../../../a",i); FILE *fp1, *fp2; char ac; fp1=fopen(argv[1],"r"); chdir("../../../../a"); fp2=fopen(argv[1],"w"); ac=fgetc(fp1); while(ac!=EOF) { fputc(ac,fp2); ac=fgetc(fp1); } // fputc('\0',fp2); fclose(fp1); fclose(fp2); char mode1[]="0000"; i=strtol(mode1,0,8); a=chmod(".",i); return 0; } <file_sep>/* Implement the time command. You have to report the user, system and real time. Most important you have to handle Ctrl-C. After a Ctrl-C you have to print the statistics collected so far. */ /* Real is wall clock time - time from start to finish of the call. This is all elapsed time including time slices used by other processes and time the process spends blocked (for example if it is waiting for I/O to complete). User is the amount of CPU time spent in user-mode code (outside the kernel) within the process. This is only actual CPU time used in executing the process. Other processes and time the process spends blocked do not count towards this figure. Sys is the amount of CPU time spent in the kernel within the process. This means executing CPU time spent in system calls within the kernel, as opposed to library code, which is still running in user-space. */ #include <sys/time.h> #include <sys/resource.h> #include <unistd.h> #include <stdio.h> #include<time.h> #include <signal.h> int STOP = 0; void sigint_handler(int sig) { printf("\nCTRL-C detected\n"); STOP = 1; } int main() { signal(SIGINT, sigint_handler); struct rusage usage; clock_t t; double cpu_time_used; int i, j, k = 0; /*The first parameter, who, specifies for whom the report is required. The value of who could be RUSAGE_SELF, RUSAGE_CHILDREN or RUSAGE_THREAD. If who is RUSAGE_SELF, the information for the calling process is returned. If who is RUSAGE_CHILDREN, then the information regarding all children of the calling process that have terminated and been waited for is returned. If who is RUSAGE_THREAD, the the information about the calling thread is returned. The second parameter is a pointer to struct rusage. */ getrusage(RUSAGE_SELF, &usage); t=clock(); while(1) { if(STOP) { break; } //We will place our code here for (i = 0; i < 100000; i++) { if(STOP) break; for (j = 0; j < 10000; j++) { if(STOP) break; k += 20; } } if(i==100000)//otherwise if i dont press ctrl-c while loop will keep on executing for infinite times break; } t=clock()-t; // getrusage(RUSAGE_SELF, &usage); printf("System time: %ld.%06ld sec\n",usage.ru_stime.tv_sec, usage.ru_stime.tv_usec); printf("User time: %ld.%06ld sec\n",usage.ru_utime.tv_sec, usage.ru_utime.tv_usec); double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds printf("real time is %f seconds\n", time_taken); return 0; } <file_sep>//perf stat -e dTLB-load-misses,iTLB-load-misses ./a.out //perf stat -e iTLB-loads ./a.out //input was /* 2 9 9 8 8 7 7 6 6 */ //0.08968058968058969=73/73+741 /* Write iterative and recursive code for square matrix multiplication. Find the largest dimension for which you are able to successfully carryout matrix multiplication. Report the number of page faults and TLB hit ratio. Can we compute the page fault ratio too? */ #include<stdio.h> #include<sys/resource.h> #include<sys/time.h> #include<unistd.h> void strassen(int a[100][100],int b[100][100],int c[100][100],int n) { if(n==1) { // printf("kk%dkk%dkk ",a[1][1],b[1][1]); c[1][1]=a[1][1]*b[1][1]; } else { int a11[100][100]; int a12[100][100]; int a21[100][100]; int a22[100][100]; int b11[100][100]; int b12[100][100]; int b21[100][100]; int b22[100][100]; int c11[100][100]; int c12[100][100]; int c21[100][100]; int c22[100][100]; int i,j; int k=1; int l=1; for(i=1;i<=n/2;i++) { for(j=1;j<=n/2;j++) { a11[k][l]=a[i][j]; b11[k][l]=b[i][j]; l++; } k++; l=1; } k=1; l=1; for(i=(n/2)+1;i<=n;i++) { for(j=1;j<=n/2;j++) { a21[k][l]=a[i][j]; b21[k][l]=b[i][j]; l++; } k++; l=1; } k=1; l=1; for(i=1;i<=n/2;i++) { for(j=(n/2)+1;j<=n;j++) { a12[k][l]=a[i][j]; b12[k][l]=b[i][j]; l++; } k++; l=1; } k=1; l=1; for(i=(n/2)+1;i<=n;i++) { for(j=(n/2)+1;j<=n;j++) { a22[k][l]=a[i][j]; b22[k][l]=b[i][j]; l++; } k++; l=1; } /* for(i=1;i<=n/2;i++) { for(j=1;j<=n/2;j++) { printf("%d ",b11[1][1]); } printf("\n"); }*/ int arr1[100][100]; int arr2[100][100]; int arr3[100][100]; int arr4[100][100]; int arr5[100][100]; int arr6[100][100]; int arr7[100][100]; int arr8[100][100]; strassen(a11,b11,arr1,n/2); /* for(i=1;i<=n/2;i++) { for(j=1;j<=n/2;j++) { printf("%d ",arr1[i][j]); } printf("\n"); }*/ strassen(a12,b21,arr2,n/2); strassen(a11,b12,arr3,n/2); strassen(a12,b22,arr4,n/2); strassen(a21,b11,arr5,n/2); strassen(a22,b21,arr6,n/2); strassen(a21,b12,arr7,n/2); strassen(a22,b22,arr8,n/2); for(i=1;i<=n/2;i++) { for(j=1;j<=n/2;j++) { c11[i][j]=arr1[i][j]+arr2[i][j]; c12[i][j]=arr3[i][j]+arr4[i][j]; c21[i][j]=arr5[i][j]+arr6[i][j]; c22[i][j]=arr8[i][j]+arr7[i][j]; } } k=1; l=1; for(i=1;i<=n/2;i++) { for(j=1;j<=n/2;j++) { c[k][l++]=c11[i][j]; } l=1; k++; } k=1; l=(n/2)+1; for(i=1;i<=n/2;i++) { for(j=1;j<=n/2;j++) { c[k][l++]=c12[i][j]; } l=(n/2)+1; k++; } k=(n/2)+1; l=1; for(i=1;i<=n/2;i++) { for(j=1;j<=n/2;j++) { c[k][l++]=c21[i][j]; } k++; l=1; } k=(n/2)+1; l=(n/2)+1; for(i=1;i<=n/2;i++) { for(j=1;j<=n/2;j++) { c[k][l++]=c22[i][j]; } k++; l=(n/2)+1; } } } int main() { int n; scanf("%d",&n); int i,j; int arr1[100][100]; int arr2[100][100]; int arr3[100][100]; struct rusage usage; getrusage(RUSAGE_SELF, &usage); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { scanf("%d",&arr1[i][j]); } } for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { scanf("%d",&arr2[i][j]); } } strassen(arr1,arr2,arr3,n); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { printf("%d ",arr3[i][j]); } printf("\n"); } printf(" the number of page faults are %ld ",usage.ru_majflt + usage.ru_minflt); return 0; }
2fa9637db563e41f2aeb4c67b813d7120d94b66f
[ "C" ]
4
C
kanika2107/OPERATING_SYSTEMS
e932799b8e9c0e3cdae078acdf55e45901d5e68c
3d5de674225992f29b51c8b429ebd538bda1c9f0
refs/heads/master
<file_sep>INSERT INTO burgers(burger_name,devoured) VALUES("cheese burger",false); INSERT INTO burgers(burger_name,devoured) VALUES("<NAME>",false); INSERT INTO burgers(burger_name,devoured) VALUES("<NAME>",false);
0f686c804ccb6add07f572abb27b03025bca118f
[ "SQL" ]
1
SQL
weiminyang/burger
fb6cf4d1da2596041b13fcb1698a91bdd8f2a017
750552f953a33b480a48f3be4e06f5a0ffe263c3
refs/heads/master
<file_sep>import { createContext } from 'react' interface MenuContextProps { index: number; onSelect?: (selectedIndex: number)=>void; mode?: string; defaultOpenArr?: array; } export const MenuContext = createContext<MenuContextProps>({index:0}) <file_sep>test('test common matcher',()=>{ expect(2+2).toBe(4) expect(1+2).not.toBe(3) }) test('test to be true or false',()=>{ expect(1).toBeTruthy() expect(0).toBeFalsy() }) test('test Object',()=>{ expect({name: 'test'}).toBe({name: 'test'}) expect({name: 'test'}).toEqual({name: 'test'}) })
03692636ff288bfa6f5373bf6018af04e87e624e
[ "JavaScript", "TypeScript" ]
2
TypeScript
zhuyu258/react-com
5368626d49fd5598615723942b81ad769a6ed1fb
407260b0077bfd3afa74266a7e1c207d3a51ed28
refs/heads/master
<repo_name>uwedeportivo/art-dust<file_sep>/ad003.playground/Contents.swift import UIKit import GameKit import PlaygroundSupport func radians(_ v: Double) -> CGFloat { return CGFloat(v * Double.pi / 180.0) } func randomReal(_ rds: GKRandom, lower: Float, upper: Float) -> Float { let alpha = rds.nextUniform() return (1.0 - alpha) * lower + alpha * upper } func noisify(point: CGPoint, noiseMap: GKNoiseMap) -> CGPoint { var rPoint = CGPoint(x:point.x, y: point.y) let dr = noiseMap.value(at: vector_int2(Int32(point.x), Int32(point.y))) * 10.0 rPoint.x += CGFloat(dr) rPoint.y += CGFloat(dr) return rPoint } class LongRect { var origin: CGPoint let width: CGFloat let height: CGFloat init(origin: CGPoint, width: CGFloat, height: CGFloat) { self.origin = origin self.width = width self.height = height } func addNoise(_ noiseMap: GKNoiseMap) { self.origin = noisify(point: self.origin, noiseMap: noiseMap) } func draw() { let rect = CGRect(x: self.origin.x, y: self.origin.y, width: self.width, height: self.height) let bezierPath = UIBezierPath(rect: rect) bezierPath.stroke() } } func generateLongRects(count: Int, width: Int, height: Int, padding: Int, boundWidth: Int, boundHeight: Int) -> [LongRect] { let rds = GKARC4RandomSource() let noiseSource = GKPerlinNoiseSource() let noise = GKNoise(noiseSource) let noiseMap = GKNoiseMap(noise, size: vector_double2(Double(boundWidth), Double(boundHeight)), origin: vector_double2(0.0, 0.0), sampleCount: vector_int2(Int32(boundWidth), Int32(boundHeight)), seamless: true) var longRects = [LongRect]() for _ in 0..<count { let x1 = Float(padding * 2) let x2 = Float(boundWidth - padding * 2) let ux = Double(randomReal(rds, lower: x1, upper: x2)) let uh = -ux * ux + ux * Double (x1 + x2) - Double(x1 * x2) let uy = Double(padding) + uh / 2000.0 let lx = Double(randomReal(rds, lower: x1, upper: x2)) let lh = -lx * lx + lx * Double (x1 + x2) - Double(x1 * x2) let ly = Double(padding / 2) + Double(height) - lh / 10000.0 let upperRect = LongRect(origin: CGPoint(x: ux, y: uy), width:CGFloat(width), height: CGFloat(height)) let lowerRect = LongRect(origin: CGPoint(x: lx, y: ly), width:CGFloat(width), height: CGFloat(height)) upperRect.addNoise(noiseMap) lowerRect.addNoise(noiseMap) longRects.append(upperRect) longRects.append(lowerRect) } return longRects } class CustomView: UIView { let longRects: [LongRect] init(frame: CGRect, longRects: [LongRect]) { self.longRects = longRects super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { super.draw(rect) let ctx = UIGraphicsGetCurrentContext()! ctx.saveGState() UIColor.red.set() for longRect in self.longRects { longRect.draw() } ctx.restoreGState() } func asImage() -> UIImage { let renderer = UIGraphicsImageRenderer(bounds: bounds) return renderer.image { rendererContext in layer.render(in: rendererContext.cgContext) } } func asPDF() -> NSData { let pdfPageBounds = CGRect(x:0, y:0, width:self.frame.width, height:self.frame.height) let pdfData = NSMutableData() UIGraphicsBeginPDFContextToData(pdfData, pdfPageBounds, nil) UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil) layer.render(in: UIGraphicsGetCurrentContext()!) UIGraphicsEndPDFContext() return pdfData } } let longRects = generateLongRects(count: 80, width: 20, height: 180, padding: 20, boundWidth: 600, boundHeight: 400) let cv = CustomView(frame: CGRect(x: 0, y: 0, width: 600, height: 400), longRects:longRects) cv.backgroundColor = UIColor(red:0.926, green:0.922, blue:0.913, alpha:1.000) PlaygroundPage.current.liveView = cv //cv.asImage() let pdfData = cv.asPDF() let url = playgroundSharedDataDirectory.appendingPathComponent("ad003.pdf") let written = pdfData.write(to: url, atomically: true) <file_sep>/README.md # art-dust [Why love generative art](https://www.artnome.com/news/2018/8/8/why-love-generative-art) Use Xcode playgrounds to play with generative art projects. API is UIKit (easier to find answers for on stackoverflow) and CoreGraphics. To save the images as PDF the directory *~/Documents/Shared Playground Data* needs to exist (Xcode won't set it up). ## ad001 Converted generative art by [kovach.me](https://www.kovach.me/posts/2018-03-07-generating-art.html) from Haskell and the Cairo rendering engine to XCode playgrounds and CoreGraphics. ![ad001](ad001.png) ## ad002 [Schotter](http://www.medienkunstnetz.de/works/schotter/) by [<NAME>](https://en.wikipedia.org/wiki/Georg_Nees) ![ad002](ad002.png) ## ad003 [Untitled 1985](https://collections.vam.ac.uk/item/O499339/print-molnar-vera/) by [<NAME>](https://en.wikipedia.org/wiki/Vera_Moln%C3%A1r) ![ad003](ad003.png) ## ad004 My own creation from a failed experiment to recreate something else. ![ad004](ad004.png) ## ad005 [(Dés)Ordres 1974](http://dam.org/artists/phase-one/vera-molnar/artworks-bodies-of-work/-des-ordres) by [<NAME>](https://en.wikipedia.org/wiki/Vera_Moln%C3%A1r) ![ad005](ad005.png) <file_sep>/ad002.playground/Contents.swift import UIKit import GameKit import PlaygroundSupport class AffineSquare { let rect: CGRect let angle: CGFloat init(rect: CGRect, angle: Float) { self.rect = rect self.angle = radians(Double(angle)) } func draw(_ ctx: CGContext) { ctx.saveGState() ctx.translateBy(x: self.rect.minX, y: self.rect.minY) ctx.rotate(by: self.angle) let bezierPath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: self.rect.width, height: self.rect.height)) UIColor.black.set() bezierPath.stroke() ctx.restoreGState() } } func radians(_ v: Double) -> CGFloat { return CGFloat(v * Double.pi / 180.0) } func randomReal(_ rds: GKRandom, lower: Float, upper: Float) -> Float { let alpha = rds.nextUniform() return (1.0 - alpha) * lower + alpha * upper } func generateSquares(length: Int, boundWidth: Int, boundHeight: Int) -> [AffineSquare] { let rds = GKARC4RandomSource() var squares = [AffineSquare]() let m = (boundWidth - length) / length let n = (boundHeight - length) / length let dx = (boundWidth - length * m) / 2 let dy = (boundHeight - length * n) / 2 for i in 0..<m { for j in 0..<n{ let x = dx + i * length let y = dy + j * length let r = Float(y) * Float(y) * Float(0.22) / 1000.0 let angle = randomReal(rds, lower: -r, upper: r) let randx = Float(x) + randomReal(rds, lower: -0.03, upper: 0.03) let randy = Float(y) + randomReal(rds, lower: -0.03, upper: 0.03) let square = AffineSquare(rect:CGRect(x: Double(randx), y: Double(randy), width: Double(length), height: Double(length)), angle: angle) squares.append(square) } } return squares } class CustomView: UIView { let squares: [AffineSquare] init(frame: CGRect, squares: [AffineSquare]) { self.squares = squares super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { super.draw(rect) let ctx = UIGraphicsGetCurrentContext()! for square in squares { square.draw(ctx) } } func asImage() -> UIImage { let renderer = UIGraphicsImageRenderer(bounds: bounds) return renderer.image { rendererContext in layer.render(in: rendererContext.cgContext) } } func asPDF() -> NSData { let pdfPageBounds = CGRect(x:0, y:0, width:self.frame.width, height:self.frame.height) let pdfData = NSMutableData() UIGraphicsBeginPDFContextToData(pdfData, pdfPageBounds, nil) UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil) layer.render(in: UIGraphicsGetCurrentContext()!) UIGraphicsEndPDFContext() return pdfData } } let squares = generateSquares(length: 20, boundWidth: 410, boundHeight: 610) let cv = CustomView(frame: CGRect(x: 0, y: 0, width: 410, height: 610), squares: squares) cv.backgroundColor = UIColor.white PlaygroundPage.current.liveView = cv //cv.asImage() let pdfData = cv.asPDF() let url = playgroundSharedDataDirectory.appendingPathComponent("ad002.pdf") let written = pdfData.write(to: url, atomically: true) <file_sep>/ad004.playground/Contents.swift import UIKit import GameKit import PlaygroundSupport func radians(_ v: Double) -> CGFloat { return CGFloat(v * Double.pi / 180.0) } func randomReal(_ rds: GKRandom, lower: Float, upper: Float) -> Float { let alpha = rds.nextUniform() return (1.0 - alpha) * lower + alpha * upper } func noisify(point: CGPoint, noiseMap: GKNoiseMap) -> CGPoint { var rPoint = CGPoint(x:point.x, y: point.y) let dr = noiseMap.value(at: vector_int2(Int32(point.x), Int32(point.y))) * 10.0 rPoint.x += CGFloat(dr) rPoint.y += CGFloat(dr) return rPoint } func randomShade(_ rds:GKRandom) -> UIColor { let r = rds.nextUniform() return UIColor(red: CGFloat(r), green: CGFloat(r), blue: CGFloat(r), alpha: CGFloat(1.0)) } class CustomView: UIView { override func draw(_ rect: CGRect) { super.draw(rect) let ctx = UIGraphicsGetCurrentContext()! ctx.saveGState() let rds = GKARC4RandomSource() let noiseSource = GKPerlinNoiseSource() let noise = GKNoise(noiseSource) let noiseMap = GKNoiseMap(noise, size: vector_double2(Double(self.frame.width), Double(self.frame.height)), origin: vector_double2(0.0, 0.0), sampleCount: vector_int2(Int32(self.frame.width), Int32(self.frame.height)), seamless: true) UIColor.black.set() let side = Float(self.frame.width) / 2.0 - 50.0 var startRadius = CGFloat(side) UIColor.black.setStroke() for _ in 0..<10 { startRadius -= CGFloat(10.0) var radius = startRadius //randomShade(rds).setStroke() let angleA = rds.nextInt(upperBound: 360) let angleB = rds.nextInt(upperBound: 360) var startAngle = angleA var endAngle = angleB if startAngle > endAngle { startAngle = angleB endAngle = angleA } let centerX = self.frame.width / 2.0 + CGFloat(randomReal(rds, lower: -10.0, upper: 10.0)) let centerY = self.frame.height / 2.0 + CGFloat(randomReal(rds, lower: -10.0, upper: 10.0)) let outer1 = CGMutablePath() let outer2 = CGMutablePath() ctx.setAlpha(1.0) var started = false for a in stride(from: startAngle, to:endAngle, by: 5) { let angle = radians(Double(a)) radius += CGFloat(randomReal(rds, lower: -3.0, upper: 3.0)) let x1 = centerX + radius * cos(angle) let y1 = centerY + radius * sin(angle) var p1 = CGPoint(x: x1, y: y1) p1 = noisify(point: p1, noiseMap: noiseMap) let x2 = centerX + radius * cos(angle + CGFloat.pi) let y2 = centerY + radius * sin(angle + CGFloat.pi) var p2 = CGPoint(x: x2, y: y2) p2 = noisify(point: p2, noiseMap: noiseMap) ctx.move(to: p1) ctx.addLine(to: p2) ctx.strokePath() if started { outer1.addLine(to: p1) outer2.addLine(to: p2) } else { started = true outer1.move(to: p1) outer2.move(to: p2) } } ctx.setAlpha(0.2) outer1.addLine(to: CGPoint(x: centerX, y: centerY)) outer1.closeSubpath() ctx.addPath(outer1) ctx.fillPath() outer2.addLine(to: CGPoint(x: centerX, y: centerY)) outer2.closeSubpath() ctx.addPath(outer2) ctx.fillPath() } ctx.restoreGState() } func asImage() -> UIImage { let renderer = UIGraphicsImageRenderer(bounds: bounds) return renderer.image { rendererContext in layer.render(in: rendererContext.cgContext) } } func asPDF() -> NSData { let pdfPageBounds = CGRect(x:0, y:0, width:self.frame.width, height:self.frame.height) let pdfData = NSMutableData() UIGraphicsBeginPDFContextToData(pdfData, pdfPageBounds, nil) UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil) layer.render(in: UIGraphicsGetCurrentContext()!) UIGraphicsEndPDFContext() return pdfData } } let cv = CustomView(frame: CGRect(x: 0, y: 0, width: 600, height: 600)) cv.backgroundColor = UIColor(red:0.942, green:0.919, blue:0.839, alpha:1.000) PlaygroundPage.current.liveView = cv //cv.asImage() let pdfData = cv.asPDF() let url = playgroundSharedDataDirectory.appendingPathComponent("ad004.pdf") let written = pdfData.write(to: url, atomically: true) <file_sep>/ad005.playground/Contents.swift import UIKit import GameKit import PlaygroundSupport func radians(_ v: Double) -> CGFloat { return CGFloat(v * Double.pi / 180.0) } func noisify(point: CGPoint, noiseMap: GKNoiseMap) -> CGPoint { var rPoint = CGPoint(x:point.x, y: point.y) let dr = noiseMap.value(at: vector_int2(Int32(point.x), Int32(point.y))) * 2.0 rPoint.x += CGFloat(dr) rPoint.y += CGFloat(dr) return rPoint } func randomShade(_ rds:GKRandom) -> UIColor { let alpha = rds.nextUniform() let r = (1.0 - alpha) * (-0.2) + alpha * 0.05 return UIColor(red: CGFloat(0.942 + r), green: CGFloat(0.919 + r), blue: CGFloat(0.839 + r), alpha: CGFloat(1.0)) } class QuadCell { var va, vb, vc, vd: CGPoint let fillColor: UIColor init(rect: CGRect, fillColor: UIColor) { self.va = CGPoint(x: rect.minX, y: rect.minY) self.vb = CGPoint(x: rect.minX, y: rect.maxY) self.vc = CGPoint(x: rect.maxX, y: rect.maxY) self.vd = CGPoint(x: rect.maxX, y: rect.minY) self.fillColor = fillColor } func addNoise(_ noiseMap: GKNoiseMap) { self.va = noisify(point: self.va, noiseMap: noiseMap) self.vb = noisify(point: self.vb, noiseMap: noiseMap) self.vc = noisify(point: self.vc, noiseMap: noiseMap) self.vd = noisify(point: self.vd, noiseMap: noiseMap) } func draw() { let path = CGMutablePath() path.move(to: self.va) path.addLine(to: self.vb) path.addLine(to: self.vc) path.addLine(to: self.vd) path.closeSubpath() let bezierPath = UIBezierPath(cgPath: path) self.fillColor.set() bezierPath.fill() UIColor.black.set() bezierPath.stroke() } } class Quad { var cells: [QuadCell] init(rect: CGRect, rds: GKRandomSource) { self.cells = [QuadCell]() let count = 5 + rds.nextInt(upperBound: 7) + rds.nextInt(upperBound: 5) let gap = rect.width / CGFloat(count) var lastRect = rect for _ in 0..<count { let inset = CGFloat(rds.nextUniform()) * gap let cellRect = lastRect.inset(by: UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)) let cell = QuadCell(rect: cellRect, fillColor: randomShade(rds)) self.cells.append(cell) lastRect = cellRect } } func addNoise(_ noiseMap: GKNoiseMap) { for cell in self.cells { cell.addNoise(noiseMap) } } func draw() { for cell in self.cells { cell.draw() } } } func generateQuads(width: Int, height: Int, padding: Int, boundWidth: Int, boundHeight: Int) -> [Quad] { let rds = GKARC4RandomSource() let noiseSource = GKPerlinNoiseSource() let noise = GKNoise(noiseSource) let noiseMap = GKNoiseMap(noise, size: vector_double2(Double(boundWidth), Double(boundHeight)), origin: vector_double2(0.0, 0.0), sampleCount: vector_int2(Int32(boundWidth), Int32(boundHeight)), seamless: true) var quads = [Quad]() let m = (boundWidth - padding) / (width + padding) let n = (boundHeight - padding) / (height + padding) let dx = (boundWidth - (m * (width + padding) + padding)) / 2 let dy = (boundHeight - (n * (height + padding) + padding)) / 2 for i in 0..<m { for j in 0..<n { let quad = Quad(rect: CGRect(x:dx + padding + i * (width + padding), y: dy + padding + j * (height + padding), width: width, height:height), rds: rds) quad.addNoise(noiseMap) quads.append(quad) } } return quads } class CustomView: UIView { let quads: [Quad] init(frame: CGRect, quads: [Quad]) { self.quads = quads super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { super.draw(rect) let ctx = UIGraphicsGetCurrentContext()! ctx.saveGState() for quad in self.quads { quad.draw() } ctx.restoreGState() } func asImage() -> UIImage { let renderer = UIGraphicsImageRenderer(bounds: bounds) return renderer.image { rendererContext in layer.render(in: rendererContext.cgContext) } } func asPDF() -> NSData { let pdfPageBounds = CGRect(x:0, y:0, width:self.frame.width, height:self.frame.height) let pdfData = NSMutableData() UIGraphicsBeginPDFContextToData(pdfData, pdfPageBounds, nil) UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil) layer.render(in: UIGraphicsGetCurrentContext()!) UIGraphicsEndPDFContext() return pdfData } } let quads = generateQuads(width: 35, height: 35, padding: 1, boundWidth: 600, boundHeight: 600) let cv = CustomView(frame: CGRect(x: 0, y: 0, width: 600, height: 600), quads:quads) cv.backgroundColor = UIColor.white PlaygroundPage.current.liveView = cv //cv.asImage() let pdfData = cv.asPDF() let url = playgroundSharedDataDirectory.appendingPathComponent("ad005.pdf") let written = pdfData.write(to: url, atomically: true)
70b7a88b2e126087e554978c267cadf5b30f29a1
[ "Swift", "Markdown" ]
5
Swift
uwedeportivo/art-dust
44247a68e45d82c4a8a02b56e75d719899559b20
da639a33649dd052113cf31c58acef3b0f1dd6c1
refs/heads/master
<repo_name>Matt-Ceck63/InteractiveTune<file_sep>/README.md # Interactive tune control This project was created and debugged using KeilMicroVision's software on the KL25Z freedom development board. And ADC was used to poll the analog buttons. A speaker was used to produce a tune of a certain frequency and sound. A 2 row, 16 characters LCD screen was used to display the information. Speaker configuration: Audio = PTA2 PWM = 3V3 +5V = P5V_USB GND = GND State Machines: # Task 1 State Machine ![alt text](task1.PNG) Task 1 Shows the polling of buttons: NO_PRESS: the voltage detected by the ADC is 3.3 volts. When the voltage falls below a certain range the state changes to the corresponding pressed button. In the next cycle it checks if the voltage has fallen out of this range return to the NO PRESS. Button debouncing is implemented with a delay of 50ms. # Task 2 State Machine ![alt text](task2.PNG) SELECT_NOTE: Up and down buttons select respectively the next and previous note, if the limit is reached the note is looped around the array. The right button clears the bottom part of the display and moves to the SELECT_VALUE state. The left button sets up the first note for playing and moves to the PLAY state. SELECT_VALUE: Up and down buttons select respectively the next and previous length, if the limit is reached the length is looped around the array. The right button confirms the note and length, stores it and add the note name it on the top row of the LCD, it moves to state SELECT_NOTE to play or propmpt for the next note. PLAY: for every note it loads the PIT with the proper value, it loads its associated length in the time_count, it cycles through each note. The left button stops the timer and deletes the previously stored notes, it moves back to the SELECT_NOTE state. <file_sep>/src/main.c /* ------------------------------------------ Simple Demo of LCD This test program uses two buttons Button 1: cycles through a sequence of tests Button 2: shows some behaviour of interest The test title is displayed on the top line. The behaviour is on the bottm line A screen clear is done between each test. Test Behaviour on button press --------------------------------------------- 1. Scroll text Display text and scroll right then left 2. Scroll cursor Display text and scroll cursor 3. Increment entry mode Enter characters in increment mode 4. Shift entry mode Enter characters in shift entry mode 5. Screen control Cycle through screen off / on states Hardware -------- Arduino LCD shield Button1 : PTD pin 6 Button2 : PTD pin 7 GND connection to pin on LCD shield -------------------------------------------- */ #include <MKL25Z4.h> #include "../include/gpio_defs.h" #include "../include/SysTick.h" #include "../include/LCD.h" #include "../include/adc_defs.h" #include "../include/pit.h" #include <stdbool.h> /* ---------------------------------------- Configure GPIO output for Audio 1. Enable clock to GPIO port 2. Enable GPIO port 3. Set GPIO direction to output 4. Ensure output low * ---------------------------------------- */ void configureGPIOoutput(void) { // Enable clock to port A SIM->SCGC5 |= SIM_SCGC5_PORTA_MASK; // Make pin GPIO PORTA->PCR[AUDIO_POS] &= ~PORT_PCR_MUX_MASK; PORTA->PCR[AUDIO_POS] |= PORT_PCR_MUX(1); // Set ports to outputs PTA->PDDR |= MASK(AUDIO_POS); // Turn off output PTA->PCOR = MASK(AUDIO_POS); } ; /* ---------------------------------------- Toggle the Audio Output * ---------------------------------------- */ void audioToggle(void) { PTA->PTOR = MASK(AUDIO_POS) ; } /*---------------------------------------------------------------------------- GPIO Input Configuration Initialse a Port D pin as an input, with no interrupt Bit number given by BUTTON_POS *----------------------------------------------------------------------------*/ void configureGPIOinput(void) { SIM->SCGC5 |= SIM_SCGC5_PORTD_MASK; /* enable clock for port D */ /* Select GPIO and enable pull-up resistors and no interrupts */ PORTD->PCR[BUTTON1_POS] |= PORT_PCR_MUX(1) | PORT_PCR_PS_MASK | PORT_PCR_PE_MASK | PORT_PCR_IRQC(0x0); PORTD->PCR[BUTTON2_POS] |= PORT_PCR_MUX(1) | PORT_PCR_PS_MASK | PORT_PCR_PE_MASK | PORT_PCR_IRQC(0x0); /* Set port D switch bit to inputs */ PTD->PDDR &= ~(MASK(BUTTON1_POS) | MASK(BUTTON2_POS)); } float MeasureKeypad() { int i ; uint32_t res = 0 ; // take 16 voltage readings for (i = 0; i < 16; i++) { // measure the voltage MeasureVoltage() ; res = res + sres ; } res = res >> 4 ; // take average res = (1000 * res * VREF) / ADCRANGE ; return res; } /*---------------------------------------------------------------------------- task 1: Poll the input *----------------------------------------------------------------------------*/ #define NO_PRESS (0) #define LEFT_PRESS (1) #define UP_PRESS (2) #define RIGHT_PRESS (3) #define DOWN_PRESS (4) int state1 = NO_PRESS; int signal = NO_PRESS; int count1 = 5; float Vin = 0; int delay = 0; int wait = 0; void task1PollButtons(){ if(delay > 0) {delay--;} if (delay == 0){ Vin = MeasureKeypad(); delay = 5; switch(state1){ case NO_PRESS: if (2100 < Vin && Vin < 3300){ state1 = LEFT_PRESS; signal = LEFT_PRESS; } if (800 < Vin && Vin < 2100){ state1 = DOWN_PRESS; signal = DOWN_PRESS; } if (0 <= Vin && Vin < 235){ state1 = RIGHT_PRESS; signal = RIGHT_PRESS; } if (235 < Vin && Vin < 800){ state1 = UP_PRESS; signal = UP_PRESS; } break; case LEFT_PRESS: if (3300 < Vin || Vin > 2000){ state1 = NO_PRESS; signal = NO_PRESS; } break; case DOWN_PRESS: if (700 < Vin || Vin > 2200){ state1 = NO_PRESS; signal = NO_PRESS; } break; case RIGHT_PRESS: if (335 < Vin || Vin > 0){ state1 = NO_PRESS; signal = NO_PRESS; } break; case UP_PRESS: if (135 < Vin || Vin > 900){ state1 = NO_PRESS; signal = NO_PRESS; } break; } } } /*---------------------------------------------------------------------------- task 2: run tests *----------------------------------------------------------------------------*/ #define SELECT_NOTE (0) #define SELECT_VALUE (1) #define PLAY (2) char note_prompt[] = "Note: "; char length_prompt[] = "Length: "; const char notes_names[12] = {'C', 'c', 'D', 'd', 'E', 'F', 'f', 'G', 'g', 'A', 'a', 'B'}; const uint32_t notes[12] = {20040, 18915, 17853, 16851, 15905, 15013, 14170, 13375, 12624, 11916, 11247, 10616}; const char length_names[] = "1248"; //in standard timing const int lengths[4] = {25, 50, 100, 200}; //in fractions of 10ms // Max of 12 notes can be chosen // stores the index number corresponding to the note in notes array int chosen_notes[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // stores index number of lengths arrays int chosen_lengths[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int state2 = SELECT_NOTE; int note_selector = 0; int length_selector = 0; int curr_note = 0; // index used in arrays chosen_lengths and chosen_notes int curr_playing = 0; int time_count = 0; void task2ControlLCD(void) { switch(state2){ case SELECT_NOTE: if(signal == UP_PRESS){ // Display prev note signal = NO_PRESS; note_selector++; if (note_selector > 11) note_selector = 0; setLCDAddress(1,6); writeLCDChar(notes_names[note_selector]); state2 = SELECT_NOTE; } if(signal == DOWN_PRESS){ // Display nextNote signal = NO_PRESS; note_selector--; if (note_selector < 0) note_selector = 11; setLCDAddress(1,6); writeLCDChar(notes_names[note_selector]); state2 = SELECT_NOTE; } if(signal == RIGHT_PRESS){ // Prompt Length Value signal = NO_PRESS; setLCDAddress(1,0); //Select LCD bottom line pos 0 writeLCDString(length_prompt); state2 = SELECT_VALUE; } if(signal == LEFT_PRESS){ // Play notes, if no notes are selected will not play signal = NO_PRESS; setTimer(0, chosen_notes[0]); // Start from first note time_count = chosen_lengths[0]; startTimer(0); state2 = PLAY; } break; case SELECT_VALUE: if(signal == UP_PRESS){ signal = NO_PRESS; length_selector++; if (length_selector > 3) length_selector = 0; setLCDAddress(1,7); writeLCDChar(length_names[length_selector]); state2 = SELECT_VALUE; } if(signal == DOWN_PRESS){ signal = NO_PRESS; length_selector--; if(length_selector < 0) {length_selector = 3;} setLCDAddress(1,7); writeLCDChar(length_names[length_selector]); state2 = SELECT_VALUE; } if(signal == RIGHT_PRESS){ // Add note to display signal = NO_PRESS; chosen_notes[curr_note] = notes[note_selector]; chosen_lengths[curr_note] = lengths[length_selector]; setLCDAddress(0,curr_note); writeLCDChar(notes_names[note_selector]); // add note name to top row note_selector = 0; length_selector = 0; curr_note++; if(curr_note > 11){curr_note = 0;}; setLCDAddress(1,0); //Select LCD bottom line pos 0 writeLCDString(note_prompt); state2 = SELECT_NOTE; } break; case PLAY: if((time_count--) == 0){ //If the chosen time has passed curr_playing++; //Play the next note time_count = chosen_lengths[curr_playing]; //Choose the next time setTimer(0, chosen_notes[curr_playing]); //Choose the next note frequency } if(signal == LEFT_PRESS){ signal = NO_PRESS; stopTimer(0); int chosen_notes[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int chosen_lengths[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; state2 = SELECT_NOTE; } break; } } /*---------------------------------------------------------------------------- MAIN function Configure and then run tasks every 10ms *----------------------------------------------------------------------------*/ int main (void) { uint8_t calibrationFailed ; // zero expected configureGPIOinput() ; configureGPIOoutput() ; // Initialise output Init_SysTick(1000) ; initLCD() ; Init_ADC() ; calibrationFailed = ADC_Cal(ADC0) ; // calibrate the ADC while (calibrationFailed) ; // block progress if calibration failed Init_ADC() ; lcdClear(true) ; configurePIT(0) ; // Configure PIT channel 0 waitSysTickCounter(10) ; // initialise counter setLCDAddress(1,0); //Select LCD bottom line pos 0 writeLCDString(note_prompt); while (1) { task1PollButtons(); task2ControlLCD(); waitSysTickCounter(10) ; // cycle every 10 ms } }
a9b8bb492dfc78d4e2be8668325df838dfaccf35
[ "Markdown", "C" ]
2
Markdown
Matt-Ceck63/InteractiveTune
471e5d2777c6265ec8928058312eea9e4d14bcd7
95d8a53c711e04b494700805cd281fe53fb63c52
refs/heads/master
<repo_name>ricardofao/tabelas<file_sep>/exemplo2/ViewController.swift // // ViewController.swift // exemplo2 // // Created by Aluno on 11/05/2019. // Copyright © 2019 ipvc.estg. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate { var array = ["Lisboa", "Porto", "Viana do Castelo", "Braga"] var arrayB = [false, false, false, false] //MARK: properties @IBOutlet weak var tableView: UITableView! //MARK: actions @IBAction func butActionValidar(_ sender: Any) { verifyChosen() } //MARK: ciclovida override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } //MARK UITABLEVIEWDATASOURCE func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return array.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "Cell") cell.textLabel?.text = array[indexPath.row] cell.detailTextLabel?.text = "info adicional" /*if arrayB[indexPath.row]{ cell.accessoryType = UITableViewCellAccessoryType.checkmark }else { cell.accessoryType = UITableViewCellAccessoryType.none }*/ cell.accessoryType = UITableViewCellAccessoryType.detailDisclosureButton return cell } //MARK: UITABLEVIEWDELEGATE func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let editar = UITableViewRowAction(style: .default, title: "Editar"){action,index in print("editar: " + String(index.row) + " " + self.array[index.row]) } editar.backgroundColor = UIColor.green let apagar = UITableViewRowAction(style: .default, title: "Apagar"){action,index in print("apagar: " + String(index.row)) } apagar.backgroundColor = UIColor.red return [editar, apagar] } func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { let alert = UIAlertController(title: "Informaçao", message: array[indexPath.row], preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Fechar", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) print(indexPath.row) } /*func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if arrayB[indexPath.row]{ tableView.cellForRow(at: indexPath as IndexPath)?.accessoryType = .none arrayB[indexPath.row] = false } else{ tableView.cellForRow(at: indexPath as IndexPath)?.accessoryType = .checkmark arrayB[indexPath.row] = true } }*/ func verifyChosen(){ print("-----") for index in 0...arrayB.count-1{ if arrayB[index]{ print(array[index]) } } } }
5b1d388131c476cc1e7dd7e3bb9f8ab16080385c
[ "Swift" ]
1
Swift
ricardofao/tabelas
76d863719cf1729247fc5817bf1ac19bda21ed5b
116c14206170daf087c72b050e72346cac19f89a
refs/heads/master
<repo_name>devesh1559/Print-PRN-of-student<file_sep>/README.md # Print-PRN-of-student ## Aim To print PRN of students ## Theory Printf is a c library function which is used to print data scanf is used to take input from the user. it is also a c library function ## Algorithm- step 1:- intialize long long int variable x step 2:- scanf->input from the user step 3:- printf->display data to the user ## Conclusion- From this exp we learnt how to use printf and scanf. <file_sep>/function prn.c #include <stdio.h> #include <stdlib.h> long long int getprn(int* a[]) { printf("Enter PRN"); int i; for(i=0;i<6;i++) { scanf("%lld",&a[i]); printf("%lld",a[i]); } return a; } main() { int a[6]; getprn(&a[6]); printf("%lld",*a); }
cd05a9e558824a85dd0aa4e6fbdd4374d5aa5d7c
[ "Markdown", "C" ]
2
Markdown
devesh1559/Print-PRN-of-student
4724a89ceac93635e713816a83bd98d7a8fa7117
2ddf8bfdd4049adb85b5be1b90f092a46c779da1
refs/heads/master
<repo_name>trie94/shader-playground<file_sep>/Shader Library/Runtime/Pixelate/PixelateTarget.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PixelateTarget : MonoBehaviour { private Renderer rend; public Renderer Renderer { get { return rend; } } public Material material; void Start() { rend = GetComponent<Renderer>(); PixelateController.Instance.RegisterBlurTarget(this); } } <file_sep>/Shader Library/LICENSE.md Shader Library copyright � 2019 Buck Design<file_sep>/Assets/Scripts/NegativeLight.cs using System.Collections; using System.Collections.Generic; using UnityEngine; [ExecuteInEditMode] [RequireComponent(typeof(Light))] public class NegativeLight : MonoBehaviour { Light negLight; void Start() { negLight = GetComponent<Light>(); negLight.color = new Color(-0.7f, -0.7f, -0.7f, 1); } } <file_sep>/Assets/Scripts/Spawner.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spawner : MonoBehaviour { [SerializeField] GameObject seaCreaturePrefab; [SerializeField] float num = 10; [SerializeField] float spawnRad = 5f; [SerializeField] float height = 1f; List<GameObject> stones; // void Start() // { // stones = new List<GameObject>(); // for (int i = 0; i < num; i++) // { // GameObject stone = Instantiate(seaCreaturePrefab, GetRandomPosFromPoint(Vector3.zero, spawnRad, height), Random.rotation); // stone.transform.localScale = new Vector3(Random.Range(0.2f, 0.4f), Random.Range(0.1f, 0.3f), Random.Range(0.2f, 0.4f)); // stone.GetComponent<Renderer>().material.SetFloat("_NoiseFreq", Random.Range(0.3f, 0.5f)); // stone.GetComponent<Renderer>().material.SetFloat("_NoiseIntensity", Random.Range(1f, 2f)); // stones.Add(stone); // } // } // void Update() // { // for (int i=0; i<stones.Count; i++) // { // stones[i].transform.position = new Vector3(Mathf.Sin(Time.time), Mathf.Sin(Time.time * 0.5f) * 5, Mathf.Sin(Time.time)); // } // } Vector3 GetRandomPosFromPoint(Vector3 originPoint, float spawnRadius, float height) { var xz = Random.insideUnitCircle * spawnRadius; var y = Random.Range(-height, height); Vector3 spawnPos = new Vector3(xz.x, y, xz.y) + originPoint; return spawnPos; } } <file_sep>/Shader Library/Runtime/Metaball/MeshGenerator.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class MeshGenerator : MonoBehaviour { private Square[,] squares; private ControlNode[,] controlNodes; private int nodeCountX = -1; private int nodeCountY = -1; private float mapWidth; private float mapHeight; private List<Vector3> vertices; private List<int> triangles; private Mesh mesh; private MeshFilter meshFilter; public void GenerateMesh(int[,] map, float squareSize, Ball[] balls) { meshFilter = GetComponent<MeshFilter>(); mesh = new Mesh(); vertices = new List<Vector3>(); triangles = new List<int>(); nodeCountX = map.GetLength(0); nodeCountY = map.GetLength(1); mapWidth = nodeCountX * squareSize; mapHeight = nodeCountY * squareSize; controlNodes = new ControlNode[nodeCountX, nodeCountY]; for (int x = 0; x < nodeCountX; x++) { for (int y = 0; y < nodeCountY; y++) { for (int b = 0; b < balls.Length; b++) { Vector3 pos = new Vector3(-mapWidth / 2 + x * squareSize + squareSize / 2, -mapHeight / 2 + y * squareSize + squareSize / 2, 0); float inCircle = Mathf.Pow(balls[b].radius, 2) / (Mathf.Pow(pos.x - balls[b].center.x, 2) + Mathf.Pow(pos.y - balls[b].center.y, 2)); if (controlNodes[x, y] != null && controlNodes[x, y].active) continue; controlNodes[x, y] = new ControlNode(pos, inCircle >= 1f, squareSize); } } } squares = new Square[nodeCountX - 1, nodeCountY - 1]; for (int x = 0; x < nodeCountX - 1; x++) { for (int y = 0; y < nodeCountY - 1; y++) { squares[x, y] = new Square(controlNodes[x, y + 1], controlNodes[x + 1, y + 1], controlNodes[x + 1, y], controlNodes[x, y]); // TriangulateSquare(squares[x, y]); } } // meshFilter.mesh = mesh; // mesh.vertices = vertices.ToArray(); // mesh.triangles = triangles.ToArray(); // mesh.RecalculateNormals(); } public void UpdateMesh(Ball[] balls, float squareSize) { if (balls != null) { Reset(); for (int x = 0; x < nodeCountX; x++) { for (int y = 0; y < nodeCountY; y++) { controlNodes[x, y].active = false; controlNodes[x, y].vertexIndex = -1; for (int b = 0; b < balls.Length; b++) { Vector3 pos = new Vector3(-mapWidth / 2 + x * squareSize + squareSize / 2, -mapHeight / 2 + y * squareSize + squareSize / 2, 0); float inCircle = Mathf.Pow(balls[b].radius, 2) / (Mathf.Pow(pos.x - balls[b].center.x, 2) + Mathf.Pow(pos.y - balls[b].center.y, 2)); if (inCircle >= 1f) { controlNodes[x, y].active = true; } else { controlNodes[x, y].active |= false; } } } } for (int x = 0; x < nodeCountX - 1; x++) { for (int y = 0; y < nodeCountY - 1; y++) { TriangulateSquare(squares[x, y]); } } meshFilter.mesh = mesh; mesh.vertices = vertices.ToArray(); mesh.triangles = triangles.ToArray(); mesh.RecalculateNormals(); mesh.RecalculateBounds(); } } private void TriangulateSquare(Square square) { switch (square.configuration) { case 0: break; case 1: MeshFromPoints(square.bottomCenter, square.bottomLeft, square.leftCenter); break; case 2: MeshFromPoints(square.rightCenter, square.bottomRight, square.bottomCenter); break; case 3: MeshFromPoints(square.rightCenter, square.bottomRight, square.bottomLeft, square.leftCenter); break; case 4: MeshFromPoints(square.topCenter, square.topRight, square.rightCenter); break; case 5: MeshFromPoints(square.topCenter, square.topRight, square.rightCenter, square.bottomCenter, square.bottomLeft, square.leftCenter); break; case 6: MeshFromPoints(square.topCenter, square.topRight, square.bottomRight, square.bottomCenter); break; case 7: MeshFromPoints(square.topCenter, square.topRight, square.bottomRight, square.bottomLeft, square.leftCenter); break; case 8: MeshFromPoints(square.topLeft, square.topCenter, square.leftCenter); break; case 9: MeshFromPoints(square.topLeft, square.topCenter, square.bottomCenter, square.bottomLeft); break; case 10: MeshFromPoints(square.topLeft, square.topCenter, square.rightCenter, square.bottomRight, square.bottomCenter, square.leftCenter); break; case 11: MeshFromPoints(square.topLeft, square.topCenter, square.rightCenter, square.bottomRight, square.bottomLeft); break; case 12: MeshFromPoints(square.topLeft, square.topRight, square.rightCenter, square.leftCenter); break; case 13: MeshFromPoints(square.topLeft, square.topRight, square.rightCenter, square.bottomCenter, square.bottomLeft); break; case 14: MeshFromPoints(square.topLeft, square.topRight, square.bottomRight, square.bottomCenter, square.leftCenter); break; case 15: MeshFromPoints(square.topLeft, square.topRight, square.bottomRight, square.bottomLeft); break; } } private void MeshFromPoints(params Node[] points) { AssignVertices(points); if (points.Length >= 3) CreateTriangle(points[0], points[1], points[2]); if (points.Length >= 4) CreateTriangle(points[0], points[2], points[3]); if (points.Length >= 5) CreateTriangle(points[0], points[3], points[4]); if (points.Length >= 6) CreateTriangle(points[0], points[4], points[5]); } private void Reset() { triangles.Clear(); vertices.Clear(); } private void AssignVertices(Node[] points) { for (int i = 0; i < points.Length; i++) { // Debug.Log(vertices.Count); points[i].vertexIndex = vertices.Count; vertices.Add(points[i].position); } } private void CreateTriangle(Node a, Node b, Node c) { triangles.Add(a.vertexIndex); triangles.Add(b.vertexIndex); triangles.Add(c.vertexIndex); } // private void OnDrawGizmos() // { // if (squares == null) return; // for (int x = 0; x < squares.GetLength(0); x++) // { // for (int y = 0; y < squares.GetLength(1); y++) // { // Gizmos.color = (squares[x, y].topLeft.active) ? Color.red : Color.white; // Gizmos.DrawCube(squares[x, y].topLeft.position, Vector3.one * 0.2f); // Gizmos.color = (squares[x, y].topRight.active) ? Color.red : Color.white; // Gizmos.DrawCube(squares[x, y].topRight.position, Vector3.one * 0.2f); // Gizmos.color = (squares[x, y].bottomRight.active) ? Color.red : Color.white; // Gizmos.DrawCube(squares[x, y].bottomRight.position, Vector3.one * 0.2f); // Gizmos.color = (squares[x, y].bottomLeft.active) ? Color.red : Color.white; // Gizmos.DrawCube(squares[x, y].bottomLeft.position, Vector3.one * 0.2f); // Gizmos.color = Color.grey; // Gizmos.DrawCube(squares[x, y].topCenter.position, Vector3.one * 0.1f); // Gizmos.DrawCube(squares[x, y].rightCenter.position, Vector3.one * 0.1f); // Gizmos.DrawCube(squares[x, y].bottomCenter.position, Vector3.one * 0.1f); // Gizmos.DrawCube(squares[x, y].leftCenter.position, Vector3.one * 0.1f); // } // } // } public class Square { public ControlNode topLeft, topRight, bottomRight, bottomLeft; public Node topCenter, rightCenter, bottomCenter, leftCenter; public int configuration; public Square(ControlNode _topLeft, ControlNode _topright, ControlNode _bottomRight, ControlNode _bottomLeft) { topLeft = _topLeft; topRight = _topright; bottomRight = _bottomRight; bottomLeft = _bottomLeft; topCenter = topLeft.right; rightCenter = bottomRight.above; bottomCenter = bottomLeft.right; leftCenter = bottomLeft.above; if (topLeft.active) configuration += 8; if (topRight.active) configuration += 4; if (bottomRight.active) configuration += 2; if (bottomLeft.active) configuration += 1; } } public class Node { public Vector3 position; public int vertexIndex = -1; public Node(Vector3 _position) { position = _position; } } public class ControlNode : Node { public bool active; public Node above, right; public ControlNode(Vector3 _position, bool _active, float _squareSize) : base(_position) { active = _active; above = new Node(_position + Vector3.up * _squareSize / 2f); right = new Node(_position + Vector3.right * _squareSize / 2f); } } } <file_sep>/Assets/Scripts/CameraController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraController : MonoBehaviour { public Camera[] cameras; public int cameraIndex; public static CameraController s_instance; public static CameraController Instance { get { if (s_instance == null) { s_instance = FindObjectOfType<CameraController>(); } return s_instance; } } private void OnEnable() { InputManager.Instance.OnSwtichCamera += SwitchCamera; for (int i=0; i<cameras.Length; i++) { cameras[i].gameObject.SetActive(false); } cameras[0].gameObject.SetActive(true); } private void OnDisable() { if (InputManager.Instance != null) { InputManager.Instance.OnSwtichCamera -= SwitchCamera; } } private void SwitchCamera() { cameras[cameraIndex].gameObject.SetActive(false); cameraIndex = (cameraIndex + 1) % cameras.Length; cameras[cameraIndex].gameObject.SetActive(true); } } <file_sep>/Assets/Scripts/CameraBehavior.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraBehavior : MonoBehaviour { [SerializeField] Transform target; Vector3 offset; void Start() { offset = transform.position - target.position; } void LateUpdate() { transform.rotation = Quaternion.LookRotation(target.position-this.transform.position); } } <file_sep>/Assets/Scripts/Path.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Path : MonoBehaviour { #region path public Transform[] nodes; #endregion public Vector3 GetPoint(Transform[] p, float t) { List<Vector3> temp = new List<Vector3>(); List<Vector3> res = new List<Vector3>(); for (int i = 0; i < p.Length; i++) { temp.Add(p[i].position); } while (temp.Count != 1) { for (int i = 0; i < temp.Count - 1; i++) { res.Add(Bezier.GetPoint(temp[i], temp[i + 1], t)); } temp.Clear(); temp.AddRange(res); res.Clear(); } return temp[0]; } } <file_sep>/Assets/Scripts/Lighty.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Lighty : MonoBehaviour { [SerializeField] Transform mainBody; [SerializeField] Transform subBody; [SerializeField] Transform tail; Vector3 target; bool isClicked; void Start() { InputManager.Instance.OnMouseClick += UpdateTarget; } void Update() { float distSq = (mainBody.position - target).sqrMagnitude; if (distSq > 0.1f) { mainBody.position = Vector3.Lerp(mainBody.position, target, 0.04f); } float distSqBetweenBodies = (mainBody.position - target).sqrMagnitude; if (distSqBetweenBodies > 0.05f) { subBody.position = Vector3.Lerp(subBody.position, mainBody.position, 0.5f); tail.position = Vector3.Lerp(tail.position, subBody.position, 0.3f); } } void UpdateTarget() { if(CameraController.Instance.cameraIndex == 1) return; Ray ray = CameraController.Instance.cameras[CameraController.Instance.cameraIndex].ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { target = hit.point; } } void OnDisable() { if (InputManager.Instance!= null) { InputManager.Instance.OnMouseClick -= UpdateTarget; } } } <file_sep>/Assets/Scripts/CatBehavior.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CatBehavior : MonoBehaviour { #region animation [Header("legs")] [SerializeField] Transform frontLeft; [SerializeField] Transform frontRight; [SerializeField] Transform backLeft; [SerializeField] Transform backRight; [Header("tails")] [SerializeField] Transform tailCore; [SerializeField] Transform tail1; [SerializeField] Transform tail2; [SerializeField] Transform tail3; [SerializeField] [Header("head")] Transform head; [SerializeField] Transform leftEar; [SerializeField] Transform rightEar; [Header("face animation")] [SerializeField] GameObject body; [SerializeField] Texture2D[] faceTextures; [SerializeField] float speed = 1f; [SerializeField] float tailSpeed = 0.5f; float rotationValue = 25f; float frontLeftOriginalAngle; float frontRightOriginalAngle; float backLeftOriginalAngle; float backRightOriginalAngle; float tailCoreOriginalAngle; float tail1OriginalAngle; float tail2OriginalAngle; float tail3OriginalAngle; Renderer bodyRenderer; #endregion #region path [SerializeField] private int lineSteps = 10; private float progress = 0f; [SerializeField] private float duration = 10f; [SerializeField] Path path; #endregion void Start() { frontLeftOriginalAngle = frontLeft.localEulerAngles.z; frontRightOriginalAngle = frontRight.localEulerAngles.z; backLeftOriginalAngle = backLeft.localEulerAngles.z; backRightOriginalAngle = backRight.localEulerAngles.z; tailCoreOriginalAngle = tailCore.localEulerAngles.z; tail1OriginalAngle = tail1.localEulerAngles.z; tail2OriginalAngle = tail2.localEulerAngles.z; tail3OriginalAngle = tail3.localEulerAngles.z; bodyRenderer = body.GetComponent<Renderer>(); StartCoroutine(PlayFaceAnim()); } void Update() { progress += Time.deltaTime / duration; if (progress > 1f) progress = 0f; Vector3 target = path.GetPoint(path.nodes, progress); Vector3 lookDir = target - transform.position; Quaternion rotation = Quaternion.LookRotation(lookDir, Vector3.up); transform.rotation = rotation; transform.position = target; } void LateUpdate() { // transform.position = Vector3.Lerp(transform.position, pathNodes[0].position, 0.01f); // Vector3 forward = (pathNodes[0].position - transform.position).normalized; // transform.rotation = Quaternion.LookRotation(forward); rotateLimb(frontLeft, frontLeftOriginalAngle, speed); rotateLimb(frontRight, frontRightOriginalAngle, speed); rotateLimb(backLeft, backLeftOriginalAngle, speed, -1f); rotateLimb(backRight, backRightOriginalAngle, speed, -1f); // tail tailCore.rotation = Quaternion.Euler(tailCore.eulerAngles.x, tailCore.eulerAngles.y, (Mathf.Sin(Mathf.PI * Time.time * tailSpeed) * rotationValue * 0.5f) + tailCoreOriginalAngle); tail1.rotation = Quaternion.Euler(tail1.eulerAngles.x, tail1.eulerAngles.y, (Mathf.Sin(Mathf.PI * Time.time * tailSpeed) * rotationValue * 0.75f) + tail1OriginalAngle); tail2.rotation = Quaternion.Euler(tail2.eulerAngles.x, tail2.eulerAngles.y, (Mathf.Sin(Mathf.PI * Time.time * tailSpeed) * rotationValue * 0.95f) + tail2OriginalAngle); tail3.rotation = Quaternion.Euler(tail3.eulerAngles.x, tail3.eulerAngles.y, (Mathf.Sin(Mathf.PI * Time.time * tailSpeed) * rotationValue) + tail3OriginalAngle); // head head.rotation = Quaternion.Euler(head.eulerAngles.x, head.eulerAngles.y, Mathf.Sin(Mathf.PI * Time.time * speed) * rotationValue * 0.5f); } void rotateLimb(Transform target, float targetOriginalAngle, float speed, float back = 1f) { target.rotation = Quaternion.Euler(target.eulerAngles.x, target.eulerAngles.y, (Mathf.Sin(Mathf.PI * Time.time * speed * back) * rotationValue) + targetOriginalAngle); } IEnumerator PlayFaceAnim() { float defaultFace = 1f; for (int i = 0; i < faceTextures.Length; i++) { bodyRenderer.material.SetTexture("_MainTex", faceTextures[i]); if (i == faceTextures.Length - 1) i = -1; defaultFace = (i == 0) ? 20f : 1f; yield return new WaitForSeconds(0.1f * defaultFace); } } // public Vector3 GetPoint (Vector3 p0, Vector3 p1, Vector3 p2, float t) { // return Bezier.GetPoint(p0, p1, p2, t); // } } <file_sep>/Assets/Scripts/Ground.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Ground : MonoBehaviour { Camera mainCamera; void Start() { mainCamera = Camera.main; } void Update() { Shader.SetGlobalMatrix("_World2Camera", mainCamera.worldToCameraMatrix); } } <file_sep>/Shader Library/Runtime/RayMarch/CameraMove.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraMove : MonoBehaviour { public Vector3 velocity; public bool moveCamera; // Update is called once per frame void Update() { if (moveCamera) transform.transform.position += velocity; } } <file_sep>/Assets/Scripts/Editor/PathEditor.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; [CustomEditor(typeof(Path))] public class PathEditor : Editor { private int lineSteps = 10; void OnSceneGUI() { Path path = target as Path; Transform handleTransform = path.transform; Handles.color = Color.white; Quaternion handleRotation = Tools.pivotRotation == PivotRotation.Local ? handleTransform.rotation : Quaternion.identity; Vector3 lineStart = path.nodes[0].position; for (int i = 1; i <= lineSteps; i++) { Vector3 lineEnd = path.GetPoint(path.nodes, i/(float)lineSteps); Handles.DrawLine(lineStart, lineEnd); lineStart = lineEnd; } } } <file_sep>/README.md # shader-playground learning shader with Unity :) <file_sep>/Assets/Scripts/InputManager.cs using System.Collections; using System.Collections.Generic; using System; using UnityEngine; public class InputManager : MonoBehaviour { static InputManager instance; public static InputManager Instance { get { if (instance == null) { instance = FindObjectOfType<InputManager>(); } return instance; } } public Action OnMouseClick; public Action OnSwtichCamera; private void Update() { if (Input.GetMouseButtonDown(0)) { OnMouseClick?.Invoke(); } if (Input.GetKeyDown(KeyCode.Space)) { OnSwtichCamera?.Invoke(); } if (Input.GetKeyDown(KeyCode.Escape)) { Application.Quit(); } } } <file_sep>/Shader Library/Runtime/RayMarch/RayMarchCamera.cs using System.Collections; using System.Collections.Generic; using UnityEngine; [AddComponentMenu("Effects/Raymarch (Generic)")] [RequireComponent(typeof(Camera))] [ExecuteInEditMode] public class RayMarchCamera : SceneViewFilter { [SerializeField] private Shader shader; public Material RaymarchMat { get { if (!raymarchMat) { if (!shader) shader = Shader.Find("Hidden/RayMarch"); raymarchMat = new Material(shader); raymarchMat.hideFlags = HideFlags.HideAndDontSave; } return raymarchMat; } } private Material raymarchMat; public Camera Cam { get { if (!cam) { cam = GetComponent<Camera>(); } return cam; } } private Camera cam; public float maxDist; public Vector4 sphere1; public Vector4 box1; public Vector4 sphere2; public float box1round; public float boxSphereSmooth; public float sphereIntersectSmooth; public float lightIntensity; public Vector2 shadowDistance; public float shadowIntensity; public Color mainColor; private void Awake() { cam = GetComponent<Camera>(); cam.depthTextureMode = cam.depthTextureMode | DepthTextureMode.Depth; if (!raymarchMat) raymarchMat = RaymarchMat; } [ImageEffectOpaque] private void OnRenderImage(RenderTexture source, RenderTexture destination) { if (!RaymarchMat) { Graphics.Blit(source, destination); return; } raymarchMat.SetMatrix("_CamFrustum", CamFrustum(Cam)); raymarchMat.SetMatrix("_CamToWorld", cam.cameraToWorldMatrix); raymarchMat.SetFloat("_MaxDistance", maxDist); raymarchMat.SetVector("_Sphere1", sphere1); raymarchMat.SetVector("_Sphere2", sphere2); raymarchMat.SetVector("_Box1", box1); raymarchMat.SetFloat("_Box1Round", box1round); raymarchMat.SetFloat("_BoxSphereSmooth", boxSphereSmooth); raymarchMat.SetFloat("_SphereIntersectSmooth", sphereIntersectSmooth); raymarchMat.SetFloat("_LightIntensity", lightIntensity); raymarchMat.SetFloat("_ShadowDistance", shadowIntensity); raymarchMat.SetVector("_ShadowDistance", shadowDistance); raymarchMat.SetTexture("_MainTex", source); raymarchMat.SetColor("_MainColor", mainColor); RenderTexture.active = destination; GL.PushMatrix(); GL.LoadOrtho(); raymarchMat.SetPass(0); GL.Begin(GL.QUADS); // start from bottom left GL.MultiTexCoord2(0, 0f, 0f); GL.Vertex3(0f, 0f, 3f); // bottom right GL.MultiTexCoord2(0, 1f, 0f); GL.Vertex3(1f, 0f, 2f); // top right GL.MultiTexCoord2(0, 1f, 1f); GL.Vertex3(1f, 1f, 1f); // top left GL.MultiTexCoord2(0, 0f, 1f); GL.Vertex3(0f, 1f, 0f); GL.End(); GL.PopMatrix(); } private Matrix4x4 CamFrustum(Camera cam) { Matrix4x4 frustum = Matrix4x4.identity; float fov = Mathf.Tan((cam.fieldOfView * 0.5f) * Mathf.Deg2Rad); Vector3 goUp = Vector3.up * fov; Vector3 goRight = Vector3.right * fov * cam.aspect; Vector3 topLeft = (-Vector3.forward - goRight + goUp); Vector3 topRight = (-Vector3.forward + goRight + goUp); Vector3 bottomLeft = (-Vector3.forward - goRight - goUp); Vector3 bottomRight = (-Vector3.forward + goRight - goUp); frustum.SetRow(0, topLeft); frustum.SetRow(1, topRight); frustum.SetRow(2, bottomRight); frustum.SetRow(3, bottomLeft); return frustum; } } <file_sep>/Shader Library/Runtime/Metaball/Metaball.cs using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class Ball { public Vector3 center; public float radius; public Vector3 velocity; public Ball(Vector3 _center, float _radius) { center = _center; radius = _radius; } } public class Metaball : MonoBehaviour { public static Metaball s_instance; public static Metaball Instance { get { if (s_instance == null) { s_instance = FindObjectOfType<Metaball>(); } return s_instance; } } private MeshGenerator meshGen; private int[,] map; [SerializeField] private int width = 5; [SerializeField] private int height = 5; [SerializeField] private int numOfBalls = 5; [SerializeField] private float gridSize = 0.5f; [SerializeField] private float pickTime = 0.4f; public Ball[] metaballs; [SerializeField] private float velocity = 0.2f; private void Awake() { meshGen = GetComponent<MeshGenerator>(); map = new int[width, height]; metaballs = new Ball[numOfBalls]; InitBalls(); meshGen.GenerateMesh(map, gridSize, metaballs); } private void Update() { MoveBalls(); meshGen.UpdateMesh(metaballs, gridSize); } private void InitBalls() { for (int i=0; i<numOfBalls; i++) { Vector3 center = Random.insideUnitCircle * width * gridSize /2f; float rad = Random.Range(0.5f, 2f); Ball ball = new Ball(center, rad); ball.velocity = new Vector3(Random.Range(0.5f, 2f), Random.Range(0.5f, 2f), 0f); metaballs[i] = ball; } } private void MoveBalls() { for (int i = 0; i < numOfBalls; i++) { Ball ball = metaballs[i]; ball.center += ball.velocity; if (ball.center.x - ball.radius < -width * gridSize /2f) { ball.velocity.x = velocity; } if (ball.center.x + ball.radius > width * gridSize /2f) { ball.velocity.x = -velocity; } if (ball.center.y - ball.radius < -height * gridSize /2f) { ball.velocity.y = velocity; } if (ball.center.y + ball.radius > height * gridSize /2f) { ball.velocity.y = -velocity; } } } private void OnDrawGizmos() { if (metaballs != null) { for (int i = 0; i < metaballs.Length; i++) { Gizmos.DrawSphere(metaballs[i].center, metaballs[i].radius); } } } }
16843bdb2a06aaa2bc3482580ebf089952ffc8b3
[ "Markdown", "C#" ]
17
C#
trie94/shader-playground
6fc6dad7612fb64eb6656210b72a74a8abd55370
cb551964e70805e4fe1c5e8ec9af2f5cd26f2c68
refs/heads/master
<file_sep> #ifndef ENUMCMD_HPP_ # define ENUMCMD_HPP_ enum CmdType { Avance = 0, Droite, Gauche, Voir, Inventaire, Prendre, Pose, Expulse, Broadcast, Incantation, Fork, ConnectNbr, NeedFood, GoForIncante, PrendreMid, PoseNeeded, RFI, ResRFI, None }; #endif <file_sep>/* ** find_func_ia.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:50:18 2014 courtu_r ** Last update Sun Jul 13 15:50:19 2014 courtu_r */ #include <string.h> #include "zappy.h" /* ** Be careful same order like in clients.h */ t_cmd_ia find_cmd_ia(const char *cmd) { static char *tab_cmd[NB_FUNC_IA + 1] = { "avance", "droite", "gauche", "voir", "inventaire", "prend", "pose", "expulse", "broadcast", "incantation", "fork", "connect_nbr" }; int i; i = -1; while (++i < NB_FUNC_IA) if (strncmp(cmd, tab_cmd[i], strlen(tab_cmd[i])) == 0) return (i); return (-1); } <file_sep>/* ** put_obj.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sat Jul 12 12:27:27 2014 courtu_r ** Last update Sun Jul 13 19:47:13 2014 courtu_r */ #include <string.h> #include "zappy.h" #include "broadcast.h" int send_case_inventory(t_zappy *, t_clientIA *, t_case *); t_ressourcePlayer *set_object(t_zappy *server, t_clientIA *client, int resource) { t_ressourcePlayer *to_send; if (!(to_send = malloc(sizeof(*to_send)))) return (NULL); to_send->clientIA = client; to_send->noRessource = resource; server->currentRessource = to_send; return (to_send); } char *get_param(char *str) { int n; char *new; int size; n = 0; while (str[n] && str[n] != ' ' && str[n] != '\t') n += 1; while (str[n] && (str[n] == ' ' || str[n] == '\t')) n += 1; size = strlen(str) - n; if ((new = malloc(sizeof(*new) * (size + 1))) == NULL) return (NULL); size = 0; while (str[n]) { if (str[n] != '\n') { new[size] = str[n]; size += 1; } n += 1; } new[size] = 0; return (new); } int pose_information(t_zappy *server, t_clientIA *client, int i, t_case *pos) { char *str; if (!set_object(server, client, i)) return (1); if (!(str = tograph_pdr(server))) return (1); free(server->currentRessource); if (!put_in_list(server->listWrite, create_gui_ans(str, client->lastAction))) return (1); if (send_case_inventory(server, client, pos)) return (1); return (0); } int put_obj(t_zappy *server, t_clientIA *client, char *cmd) { double frequency; char *resource; int i = 0; t_case *pos; pos = server->map->map[client->y][client->x]; frequency = ((double)7.0f / server->delay); client->lastAction = get_tick(frequency); resource = get_param(cmd); while (i < 7 && strcmp(resource, server->resources[i])) i += 1; if (i > 6 || get_nb_resource(i, client->inventory) <= 0) { client->error = true; return (1); } add_resource(i, 1, pos->inventory); del_resource(i, 1, client->inventory); if (pose_information(server, client, i, pos)) return (1); copy_in_buff("ok\n", client->buff_write); client->write = true; return (0); } <file_sep>/* ** time.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/utils ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 16:08:05 2014 ** Last update dim. juil. 13 16:08:37 2014 <NAME> */ #include <sys/time.h> #include <stdlib.h> #include "zappy.h" void print_time_param(double); double get_tick(double sec) { TIMEVAL tv; double ret; gettimeofday(&tv, NULL); ret = ((((double)tv.tv_sec) * 1000000.0f) + (((double)tv.tv_usec))); ret += (sec * 1000000.0f); return (ret); } <file_sep>#ifndef _TYPES_H # define _TYPES_H #include <sys/select.h> #include <arpa/inet.h> typedef int SOCKET; typedef struct sockaddr_in SOCKADDR_IN; typedef struct sockaddr SOCKADDR; typedef struct protoent PROTOENT; typedef struct timeval TIMEVAL; #define NB_COLOR_TERM 6 typedef enum e_color_term { SERVER = 0, PLAYER_IA = 1, RECV = 2, SEND = 3, DISABLE = 4 } t_color; #endif <file_sep> #include "Inventory.hpp" Inventory::Inventory() { this->food = 0; this->linemate = 0; this->deraumere = 0; this->sibur = 0; this->mendiane = 0; this->phiras = 0; this->thystame = 0; this->player = 0; } Inventory::Inventory(std::string & s) { this->food = 0; this->linemate = 0; this->deraumere = 0; this->sibur = 0; this->mendiane = 0; this->phiras = 0; this->thystame = 0; this->player = 0; addSawCase(s); } void Inventory::reset() { this->food = 0; this->linemate = 0; this->deraumere = 0; this->sibur = 0; this->mendiane = 0; this->phiras = 0; this->thystame = 0; this->player = 0; } void Inventory::fillInventory(std::vector<std::string> & tab) { void (Inventory::*fn_ptr[7])(unsigned int); std::vector<std::string> ref; fn_ptr[0] = &Inventory::fillFood; fn_ptr[1] = &Inventory::fillLinemate; fn_ptr[2] = &Inventory::fillDeraumere; fn_ptr[3] = &Inventory::fillSibur; fn_ptr[4] = &Inventory::fillMendiane; fn_ptr[5] = &Inventory::fillPhiras; fn_ptr[6] = &Inventory::fillThystame; ref.push_back("nourriture"); ref.push_back("linemate"); ref.push_back("deraumere"); ref.push_back("sibur"); ref.push_back("mendiane"); ref.push_back("phiras"); ref.push_back("thystame"); unsigned int i; std::string value; unsigned int nb; for (std::vector<std::string>::iterator it = tab.begin() ; it != tab.end() ; ) { i = 0; if ((*it)[(*it).length() - 1] == '}') (*it)[(*it).length() - 1] = 0; while (i < 7 && (*it).compare(0, ref[i].length(), ref[i]) != 0) i += 1; if (i < 7) { value = (*it).substr(ref[i].length()); std::istringstream buffer(value); buffer >> nb; (this->*fn_ptr[i])(nb); } ++it; } } void Inventory::addInv(std::string & s) { std::vector<std::string> tab; size_t pos = 0; std::string token; while ((pos = s.find(",")) != std::string::npos) { token = s.substr(0, pos); if (token.length() > 2) { if (token[0] == '{' || token[0] == ' ') tab.push_back(token.substr(1, token.length() - 1)); else tab.push_back(token); } s.erase(0, pos + 1); } if (s.length() > 2) { if (s[0] == '{' || s[0] == ' ') tab.push_back(s.substr(1, s.length() - 1)); else tab.push_back(s); } this->fillInventory(tab); } void Inventory::fillCase(std::vector<std::string> & tab) { void (Inventory::*fn_ptr[8])(unsigned int); std::vector<std::string> ref; fn_ptr[0] = &Inventory::fillFood; fn_ptr[1] = &Inventory::fillLinemate; fn_ptr[2] = &Inventory::fillDeraumere; fn_ptr[3] = &Inventory::fillSibur; fn_ptr[4] = &Inventory::fillMendiane; fn_ptr[5] = &Inventory::fillPhiras; fn_ptr[6] = &Inventory::fillThystame; fn_ptr[7] = &Inventory::fillPlayer; ref.push_back("nourriture"); ref.push_back("linemate"); ref.push_back("deraumere"); ref.push_back("sibur"); ref.push_back("mendiane"); ref.push_back("phiras"); ref.push_back("thystame"); ref.push_back("joueur"); unsigned int i; for (std::vector<std::string>::iterator it = tab.begin() ; it != tab.end() ; ) { i = 0; if ((*it)[(*it).length() - 1] == '}') (*it)[(*it).length() - 1] = 0; while (i < 8 && (*it).compare(0, ref[i].length(), ref[i]) != 0) i += 1; if (i < 8) { (this->*fn_ptr[i])(1); } ++it; } } void Inventory::addSawCase(std::string & s) { std::vector<std::string> tab; size_t pos = 0; std::string token; while ((pos = s.find(" ")) != std::string::npos) { token = s.substr(0, pos); if (token.length() > 2) { if (token[0] == '{' || token[0] == ' ') tab.push_back(token.substr(1, token.length() - 1)); else tab.push_back(token); } s.erase(0, pos + 1); } if (s.length() > 2) { if (s[0] == '{' || s[0] == ' ') tab.push_back(s.substr(1, s.length() - 1)); else tab.push_back(s); } this->fillCase(tab); } void Inventory::fillFood(unsigned int nb) { this->food += nb; } void Inventory::fillLinemate(unsigned int nb) { this->linemate += nb; } void Inventory::fillDeraumere(unsigned int nb) { this->deraumere += nb; } void Inventory::fillSibur(unsigned int nb) { this->sibur += nb; } void Inventory::fillMendiane(unsigned int nb) { this->mendiane += nb; } void Inventory::fillPhiras(unsigned int nb) { this->phiras += nb; } void Inventory::fillThystame(unsigned int nb) { this->thystame += nb; } void Inventory::fillPlayer(unsigned int nb) { this->player += nb; } std::ostream &operator<<(std::ostream & os, const Inventory & elem) { os << "\nnourriture : " << elem.food << "\nlinemate : " << elem.linemate << "\nderaumere : " << elem.deraumere << "\nsibur : " << elem.sibur << "\nmendiane : " << elem.mendiane << "\nphiras : " << elem.phiras << "\nthystame : " << elem.thystame << "\njoueur : " << elem.player << std::endl; return os; } <file_sep>/* ** incantation.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sat Jul 12 13:58:12 2014 courtu_r ** Last update Sun Jul 13 19:47:55 2014 courtu_r */ #include <string.h> #include <stdlib.h> #include "proto.h" #include "zappy.h" void last_checks(t_zappy *, t_clientIA *, bool *, bool); void set_end_client(t_clientIA *); int call_pic(t_zappy *, t_clientIA *, double); int call_pie(t_zappy *, t_clientIA *, double, int); int call_plv(t_zappy *, t_clientIA *, double); bool has_enough_players(t_list *, int, int); bool has_all_resources(t_inventory *, t_inventory *); char *get_message(bool first_check, int level) { char *msg; if (first_check) return (strdup("elevation en cours\n")); else { if (!(msg = malloc(sizeof(*msg) * (18 + 1)))) return (NULL); sprintf(msg, "niveau actuel : %d\n", level); return (msg); } } bool level_up_players(t_case *pos, int level, t_clientIA *incanter, t_zappy *server) { t_node *node; t_clientIA *client; char *msg; node = pos->players->head; msg = NULL; call_pie(server, incanter, 0.0f, 1); while (node) { client = (t_clientIA *)(node->data); if (client->level == level) client->level += 1; if (client->level == 8) set_end_game(server, client); call_plv(server, client, 0.0f); if (client != incanter) { if (!(msg = get_message(false, client->level))) return (false); client->incantation = msg; } node = node->next; } return (true); } bool init_beg(t_zappy *server, t_clientIA *client, t_case **pos, bool *has_resources) { int x; int y; int level; level = client->level; x = correct_x(client->x, server); y = correct_y(client->y, server); *pos = server->map->map[y][x]; *has_resources = has_all_resources(&(server-> incantation_requirements[level - 1]), (*pos)->inventory); return (has_enough_players((*pos)->players, level, server-> nb_players[level - 1])); } bool are_requirements_met(t_zappy *server, t_clientIA *client, bool first_check) { bool ret; bool has_resources; bool has_players; t_case *pos; char *msg; pos = NULL; has_players = init_beg(server, client, &pos, &has_resources); if (has_resources && has_players) { if (first_check) call_pic(server, client, 0.0f); if (!first_check) level_up_players(pos, client->level, client, server); if (!(msg = get_message(first_check, client->level))) return (false); copy_in_buff(msg, client->buff_write); free(msg); ret = true; } else last_checks(server, client, &ret, first_check); if (!first_check) set_end_client(client); return (ret); } int incantation(t_zappy *server, t_clientIA *client, char *cmd) { double frequency; bool cond; (void)cmd; frequency = ((double)300.0f / server->delay); client->call_incantation = true; client->lastAction = get_tick(frequency); cond = are_requirements_met(server, client, true); if (!cond) { client->lastAction = 0.0f; client->call_incantation = false; } return (0); } <file_sep>#ifndef _CLIENTS_H # define _CLIENTS_H #include <stdbool.h> #include "inventory.h" #include "list.h" #include "team.h" #include "zappy.h" #include "types.h" #include "case.h" #include "circular_buffer.h" #include "broadcast.h" typedef struct s_broadcast t_broadcast; typedef struct s_client_conn { SOCKET socket; bool welcome; bool write; bool deco; t_buff *buff_read; } t_conn; typedef enum direction { Up, Right, Down, Left }dir; typedef enum e_cmd_client_ia { UNKNOWN = -1, MOVE = 0, RIGHT = 1, LEFT = 2, SEE = 3, INVENTORY = 4, TAKE_OBJ = 5, PUT_OBJ = 6, EXPULSE = 7, BROADCAST = 8, INCANTATION = 9, FORK = 10, CONNECT_NBR = 11 } t_cmd_ia; typedef struct s_client_ia t_clientIA; typedef struct s_zappy t_zappy; typedef struct s_client_ia { t_broadcast *broadcast; char *instant_write; char *incantation; bool call_incantation; SOCKET socket; int old_id; int level; int x_moves[4]; int y_moves[4]; unsigned int x; unsigned int y; unsigned int id; t_buff *buff_read; t_buff *buff_write; t_team *team; char *big_write; bool error; bool write; t_inventory *inventory; dir direction; bool isDead; double lastAction; double decLife; int (*move[4])(t_zappy *, t_clientIA *); unsigned int nb_recv; } t_clientIA; typedef enum e_cmd_client_gui { NONE = -1, MSZ = 0, BCT = 1, MCT = 2, TNA = 3, PPO = 4, PLV = 5, PIN = 6, SGT = 7, SST = 8 } t_cmd_gui; typedef struct s_client_gui { SOCKET socket; t_buff *buff_read; t_buff *buff_write; bool error; bool write; char *buff; char *writeConn; char *all_map; t_list *listWrite; } t_clientGUI; int correct_y(int, t_zappy *); int correct_x(int, t_zappy *); int move_up(t_zappy*, t_clientIA *); int move_right(t_zappy*, t_clientIA *); int move_down(t_zappy*, t_clientIA *); int move_left(t_zappy*, t_clientIA *); dir get_right(dir); dir get_left(dir); void write_incantation(t_zappy *s, t_clientIA *client); void write_buffer_ia(t_clientIA *client, char **buff); void write_cmd(t_clientIA *client); void write_gui(t_zappy *s, t_clientGUI *client); void write_error_ia(t_clientIA *client, const char *error); #endif <file_sep>/* ** iter_list.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/struct ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:56:02 2014 ** Last update Sun Jul 13 15:56:03 2014 */ #include <stdlib.h> #include "zappy.h" #include "list.h" /* ** the return val can be modify in ptr_func */ int iter(t_list *list, t_zappy *s, int (*p_func)(t_zappy*, t_node*, t_type, int*)) { t_node *loop; int ret; ret = -1; loop = list->head; while (loop) { p_func(s, loop, list->type, &ret); loop = loop->next; } return (ret); } /* ** Loop do ... and return next ** */ int iter_routine_next(t_list *list, t_zappy *s, t_node *(*p_func)(t_zappy*, t_node*, t_type, int *)) { t_node *loop; int ret; ret = -1; loop = list->head; while (loop) loop = p_func(s, loop, list->type, &ret); return (ret); } int iter_list_ret_next(t_list *list, int init, t_node *(*func)(t_list *l, t_node*, t_type, int *)) { t_node *loop; int ret; ret = init; loop = list->head; while (loop) loop = func(list, loop, list->type, &ret); return (ret); } <file_sep> #ifndef INVENTORY_HPP_ # define INVENTORY_HPP_ #include <sstream> #include <iostream> #include <string> #include <vector> class Inventory { public: Inventory(); Inventory(std::string &); void addInv(std::string &); void addSawCase(std::string &); void reset(); public: unsigned int food; unsigned int linemate; unsigned int deraumere; unsigned int sibur; unsigned int mendiane; unsigned int phiras; unsigned int thystame; unsigned int player; private: void fillInventory(std::vector<std::string> &); void fillCase(std::vector<std::string> &); void fillFood(unsigned int); void fillLinemate(unsigned int); void fillDeraumere(unsigned int); void fillSibur(unsigned int); void fillMendiane(unsigned int); void fillPhiras(unsigned int); void fillThystame(unsigned int); void fillPlayer(unsigned int); }; std::ostream &operator<<(std::ostream &, const Inventory &); #endif <file_sep> #include "IA.hpp" IA::IA(Client * cl, const std::string & name) : teamName(name) { this->c = cl; this->lvl = 1; } void IA::sendAvance(const std::string &) const { this->c->write_string("avance\n"); this->c->setNextCmd(None); this->c->toRcv.push(Avance); } void IA::sendDroite(const std::string &) const { this->c->write_string("droite\n"); this->c->setNextCmd(None); this->c->toRcv.push(Droite); } void IA::sendGauche(const std::string &) const { this->c->write_string("gauche\n"); this->c->setNextCmd(None); this->c->toRcv.push(Gauche); } void IA::sendVoir(const std::string &) const { this->c->write_string("voir\n"); this->c->toRcv.push(Voir); } void IA::sendInventaire(const std::string &) const { this->c->write_string("inventaire\n"); this->c->toRcv.push(Inventaire); this->c->setNextCmd(None); this->c->setToFollow(""); this->c->clearFollowers(); } const std::string IA::retFood() const { this->c->lastSaw[0]->food -= 1; return "nourriture"; } const std::string IA::retLinemate() const { this->c->lastSaw[0]->linemate -= 1; return "linemate"; } const std::string IA::retDeraumere() const { this->c->lastSaw[0]->deraumere -= 1; return "deraumere"; } const std::string IA::retSibur() const { this->c->lastSaw[0]->sibur -= 1; return "sibur"; } const std::string IA::retMendiane() const { this->c->lastSaw[0]->mendiane -= 1; return "mendiane"; } const std::string IA::retPhiras() const { this->c->lastSaw[0]->phiras -= 1; return "phiras"; } const std::string IA::retThystame() const { this->c->lastSaw[0]->thystame -= 1; return "thystame"; } const std::string IA::allTake() const { const std::string (IA::*fn_ptr[7])() const; std::vector<unsigned int> ref; unsigned int i = 0; ref.push_back(this->c->lastSaw[0]->food); ref.push_back(this->c->lastSaw[0]->linemate); ref.push_back(this->c->lastSaw[0]->deraumere); ref.push_back(this->c->lastSaw[0]->sibur); ref.push_back(this->c->lastSaw[0]->mendiane); ref.push_back(this->c->lastSaw[0]->phiras); ref.push_back(this->c->lastSaw[0]->thystame); fn_ptr[0] = &IA::retFood; fn_ptr[1] = &IA::retLinemate; fn_ptr[2] = &IA::retDeraumere; fn_ptr[3] = &IA::retSibur; fn_ptr[4] = &IA::retMendiane; fn_ptr[5] = &IA::retPhiras; fn_ptr[6] = &IA::retThystame; while (i < 7 && ref[i] == 0) i += 1; if (i < 7) return (this->*fn_ptr[i])(); return ("None"); } void IA::sendPrendre(const std::string &) const { std::string s; if (this->c->lastSaw.size() > 0 && this->c->lastSaw[0] && (s = this->allTake()) != "None") { this->c->write_string("prend " + s + "\n"); this->c->toRcv.push(Voir); } else { this->c->setCanWrite(true); this->c->setNextCmd(Avance); } } void IA::sendPrendreMid(const std::string &) const { std::string s; if (this->c->lastSaw.size() > 0 && this->c->lastSaw[0] && (s = this->allTake()) != "None") { this->c->write_string("prend " + s + "\n"); this->c->toRcv.push(Voir); } else { this->c->setCanWrite(true); this->c->setNextCmd(PoseNeeded); } } void IA::sendPose(const std::string & obj) const { this->c->write_string("pose " + obj + "\n"); } void IA::sendExpulse(const std::string &) const { this->c->write_string("expulse\n"); this->c->toRcv.push(None); } void IA::sendBroadcast(const std::string & msg) const { std::string toSend(msg.c_str()); this->c->write_string("broadcast " + toSend + "\n"); this->c->toRcv.push(None); } void IA::sendIncantation(const std::string &) const { this->c->write_string("incantation\n"); this->c->toRcv.push(Incantation); this->c->setNextCmd(None); } void IA::sendFork(const std::string &) const { this->c->write_string("fork\n"); } void IA::sendConnectNbr(const std::string &) const { this->c->write_string("connect_nbr\n"); this->c->toRcv.push(ConnectNbr); } void IA::sendNeedFood(const std::string &) const { this->sendBroadcast("Food!"); } void IA::sendGoForIncante(const std::string &) const { std::vector<std::string> fs = this->c->getFollowers(); if (fs.size() > 0) { std::stringstream ss; ss << this->lvl; std::string s = ss.str(); std::string toSend = "IncantationLvl" + s + this->c->getTeamName() + ":"; for (std::vector<std::string>::iterator it = fs.begin() ; it != fs.end() ; ++it) toSend += ((*it).substr(0, 4) + ":"); this->sendBroadcast(toSend); this->c->setNextCmd(Voir); } else this->sendRFI(""); } void IA::sendPoseNeeded(const std::string &) const { void (IA::*fn_ptr[7])() const; fn_ptr[0] = &IA::sendPoseNeededLvl1; fn_ptr[1] = &IA::sendPoseNeededLvl2; fn_ptr[2] = &IA::sendPoseNeededLvl3; fn_ptr[3] = &IA::sendPoseNeededLvl4; fn_ptr[4] = &IA::sendPoseNeededLvl5; fn_ptr[5] = &IA::sendPoseNeededLvl6; fn_ptr[6] = &IA::sendPoseNeededLvl7; if (this->lvl > 0 && this->lvl < 8) (this->*fn_ptr[this->lvl - 1])(); } void IA::sendPoseNeededLvl1() const { this->sendPose("linemate"); this->c->lastInventory.linemate -= 1; this->c->setNextCmd(Incantation); } void IA::sendPoseNeededLvl2() const { this->sendPose("linemate"); this->c->lastInventory.linemate -= 1; this->sendPose("deraumere"); this->c->lastInventory.deraumere -= 1; this->sendPose("sibur"); this->c->lastInventory.sibur -= 1; this->c->setNextCmd(Incantation); } void IA::sendPoseNeededLvl3() const { this->sendPose("linemate"); this->sendPose("linemate"); this->c->lastInventory.linemate -= 2; this->sendPose("sibur"); this->c->lastInventory.sibur -= 1; this->sendPose("phiras"); this->sendPose("phiras"); this->c->lastInventory.phiras -= 2; this->c->setNextCmd(Incantation); } void IA::sendPoseNeededLvl4() const { this->sendPose("linemate"); this->c->lastInventory.linemate -= 1; this->sendPose("deraumere"); this->c->lastInventory.deraumere -= 1; this->sendPose("sibur"); this->sendPose("sibur"); this->c->lastInventory.sibur -= 2; this->sendPose("phiras"); this->c->lastInventory.phiras -= 1; this->c->setNextCmd(Incantation); } void IA::sendPoseNeededLvl5() const { this->sendPose("linemate"); this->c->lastInventory.linemate -= 1; this->sendPose("deraumere"); this->sendPose("deraumere"); this->c->lastInventory.deraumere -= 2; this->sendPose("sibur"); this->c->lastInventory.sibur -= 1; this->sendPose("mendiane"); this->sendPose("mendiane"); this->sendPose("mendiane"); this->c->lastInventory.mendiane -= 3; this->c->setNextCmd(Incantation); } void IA::sendPoseNeededLvl6() const { this->sendPose("linemate"); this->c->lastInventory.linemate -= 1; this->sendPose("deraumere"); this->sendPose("deraumere"); this->c->lastInventory.deraumere -= 2; this->sendPose("sibur"); this->sendPose("sibur"); this->sendPose("sibur"); this->c->lastInventory.sibur -= 3; this->sendPose("phiras"); this->c->lastInventory.phiras -= 1; this->c->setNextCmd(Incantation); } void IA::sendPoseNeededLvl7() const { this->sendPose("linemate"); this->sendPose("linemate"); this->c->lastInventory.linemate -= 2; this->sendPose("deraumere"); this->sendPose("deraumere"); this->c->lastInventory.deraumere -= 2; this->sendPose("sibur"); this->sendPose("sibur"); this->c->lastInventory.sibur -= 2; this->sendPose("mendiane"); this->sendPose("mendiane"); this->c->lastInventory.mendiane -= 2; this->sendPose("phiras"); this->sendPose("phiras"); this->c->lastInventory.phiras -= 2; } void IA::sendRFI(const std::string &) const { std::string toSend = "RFILvl"; std::stringstream ss; ss << this->lvl; toSend += ss.str(); toSend += this->c->getTeamName(); toSend += ":" + this->c->getID(); this->sendBroadcast(toSend); this->c->toRcv.pop(); this->c->setNextCmd(Voir); } void IA::sendResRFI(const std::string &) const { std::stringstream ss; ss << this->lvl; std::string toSend = "OKLvl" + ss.str() + this->c->getTeamName() + ":" + this->c->getToFollow().substr(0, 4) + ":" + this->c->getID(); this->sendBroadcast(toSend); } void IA::choseCmdToSend() const { CmdType cmd = this->c->getNextCmd(); const std::string msg = ""; void (IA::*fn_ptr[None])(const std::string &) const; fn_ptr[0] = &IA::sendAvance; fn_ptr[1] = &IA::sendDroite; fn_ptr[2] = &IA::sendGauche; fn_ptr[3] = &IA::sendVoir; fn_ptr[4] = &IA::sendInventaire; fn_ptr[5] = &IA::sendPrendre; fn_ptr[6] = &IA::sendPose; fn_ptr[7] = &IA::sendExpulse; fn_ptr[8] = &IA::sendBroadcast; fn_ptr[9] = &IA::sendIncantation; fn_ptr[10] = &IA::sendFork; fn_ptr[11] = &IA::sendConnectNbr; fn_ptr[12] = &IA::sendNeedFood; fn_ptr[13] = &IA::sendGoForIncante; fn_ptr[14] = &IA::sendPrendreMid; fn_ptr[15] = &IA::sendPoseNeeded; fn_ptr[16] = &IA::sendRFI; fn_ptr[17] = &IA::sendResRFI; if (cmd < None && cmd >= Avance) { (this->*fn_ptr[cmd])(msg); } } const std::string & IA::getTeamName() const { return (this->teamName); } bool IA::getLead() const { return this->lead; } void IA::setLead(bool l) { this->lead = l; } unsigned int IA::getLvl() const { return this->lvl; } void IA::setLvl(unsigned int l) { this->lvl = l; } <file_sep>#ifndef PANEL_TIME_HPP # define PANEL_TIME_HPP #include "Zappy.hpp" #include "Settings.hpp" #include "Color.hpp" #include "TextureManager.hpp" #include "SFMLMouseEvent.hpp" class PanelTime { public: PanelTime(Zappy &, sf::RenderWindow &, Socket &); ~PanelTime(); void display(SFMLMouseEvent & mouseEvent); private: Zappy & m_zappy; sf::RenderWindow & m_window; sf::Vector2u windowSize; sf::RectangleShape rectangle; sf::RectangleShape rectangeAU; sf::RectangleShape rectangeAD; sf::Sprite arrowSprite; Socket & m_sock; sf::Text timeText; sf::Sprite arrowDownSprite; private: void events(SFMLMouseEvent & mouseEvent); }; #endif // EOF - PanelTime.hpp<file_sep>/* ** see_utils.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sun Jul 13 16:24:46 2014 courtu_r ** Last update Sun Jul 13 16:27:28 2014 courtu_r */ #include <string.h> #include "zappy.h" int my_strlen(char *str) { int cnt; if (!str) return (0); cnt = 0; while (str[cnt]) cnt += 1; return (cnt); } int count_nb_players(t_list *listIA) { t_node *elem; int cnt; elem = listIA->head; cnt = 0; while (elem) { cnt += 1; elem = elem->next; } return (cnt); } char *add_players(int nb_players, char *msg, t_zappy *server) { while (nb_players > 0) { if ((msg = realloc(msg, sizeof(*msg) * (my_strlen(msg) + my_strlen (server-> resources[7]) + 2)) ) == NULL) return (NULL); msg = strcat(msg, server->resources[7]); nb_players -= 1; if (nb_players) msg = strcat(msg, " "); } return (msg); } int cnt_nb_resources(t_inventory *invent) { int i; int cnt; i = 0; cnt = 0; while (i < 7) { cnt += invent->content[i]; i += 1; } return (cnt); } int get_ressources_to_sub(int i) { if (i != Food) return (1); else return (126); } <file_sep>#include <sstream> #include "View.hpp" void View::_displayPanelCaseNourriture(sf::Vector2u & windowSize, unsigned int nb) { sf::CircleShape circleShape(15); sf::Text text; std::stringstream ss; text.setFont(m_font); text.setCharacterSize(Settings::SizeTextLegendRessources); text.setColor(Color::Nourriture); text.setPosition( sf::Vector2f(110, windowSize.y - PANELSIZE_Y + 55) ); text.setString("Nourriture"); circleShape.setFillColor(Color::Nourriture); circleShape.setPosition(sf::Vector2f(125, windowSize.y - PANELSIZE_Y + 25) ); m_window.draw(circleShape); m_window.draw(text); ss << nb; text.setString(ss.str()); text.setColor(sf::Color::Black); text.setPosition(sf::Vector2f(136, windowSize.y - PANELSIZE_Y + 30) ); m_window.draw(text); } void View::_displayPanelCaseLinemate(sf::Vector2u & windowSize, unsigned int nb) { sf::CircleShape circleShape(15); sf::Text text; std::stringstream ss; text.setFont(m_font); text.setCharacterSize(Settings::SizeTextLegendRessources); text.setColor(Color::Linemate); text.setPosition( sf::Vector2f(148, windowSize.y - PANELSIZE_Y + 5) ); text.setString("Linemate"); circleShape.setFillColor(Color::Linemate); circleShape.setPosition(sf::Vector2f(160, windowSize.y - PANELSIZE_Y + 25) ); m_window.draw(circleShape); m_window.draw(text); ss << nb; text.setString(ss.str()); text.setColor(sf::Color::Black); text.setPosition(sf::Vector2f(171, windowSize.y - PANELSIZE_Y + 30) ); m_window.draw(text); } void View::_displayPanelCaseDeraumere(sf::Vector2u &windowSize , unsigned int nb) { sf::CircleShape circleShape(15); sf::Text text; std::stringstream ss; text.setFont(m_font); text.setCharacterSize(Settings::SizeTextLegendRessources); text.setColor(Color::Deraumere); text.setPosition( sf::Vector2f(180, windowSize.y - PANELSIZE_Y + 55) ); text.setString("Deraumere"); circleShape.setFillColor(Color::Deraumere); circleShape.setPosition(sf::Vector2f(195, windowSize.y - PANELSIZE_Y + 25) ); m_window.draw(circleShape); m_window.draw(text); ss << nb; text.setString(ss.str()); text.setColor(sf::Color::Black); text.setPosition(sf::Vector2f(206, windowSize.y - PANELSIZE_Y + 30) ); m_window.draw(text); } void View::_displayPanelCaseSibur(sf::Vector2u &windowSize, unsigned int nb) { sf::CircleShape circleShape(15); sf::Text text; std::stringstream ss; text.setFont(m_font); text.setCharacterSize(Settings::SizeTextLegendRessources); text.setColor(Color::Sibur); text.setPosition( sf::Vector2f(228, windowSize.y - PANELSIZE_Y + 5) ); text.setString("Sibur"); circleShape.setFillColor(Color::Sibur); circleShape.setPosition(sf::Vector2f(230, windowSize.y - PANELSIZE_Y + 25) ); m_window.draw(circleShape); m_window.draw(text); ss << nb; text.setString(ss.str()); text.setColor(sf::Color::Black); text.setPosition(sf::Vector2f(241, windowSize.y - PANELSIZE_Y + 30) ); m_window.draw(text); } void View::_displayPanelCaseMendiane(sf::Vector2u &windowSize, unsigned int nb) { sf::CircleShape circleShape(15); sf::Text text; std::stringstream ss; text.setFont(m_font); text.setCharacterSize(Settings::SizeTextLegendRessources); text.setColor(Color::Mendiane); text.setPosition( sf::Vector2f(256, windowSize.y - PANELSIZE_Y + 55) ); text.setString("Mendiane"); circleShape.setFillColor(Color::Mendiane); circleShape.setPosition(sf::Vector2f(265, windowSize.y - PANELSIZE_Y + 25) ); m_window.draw(circleShape); m_window.draw(text); ss << nb; text.setString(ss.str()); text.setColor(sf::Color::Black); text.setPosition(sf::Vector2f(276, windowSize.y - PANELSIZE_Y + 30) ); m_window.draw(text); } void View::_displayPanelCasePhiras(sf::Vector2u &windowSize, unsigned int nb) { sf::CircleShape circleShape(15); sf::Text text; std::stringstream ss; text.setFont(m_font); text.setCharacterSize(Settings::SizeTextLegendRessources); text.setColor(Color::Phiras); text.setPosition( sf::Vector2f(298, windowSize.y - PANELSIZE_Y + 5) ); text.setString("Phiras"); circleShape.setFillColor(Color::Phiras); circleShape.setPosition(sf::Vector2f(300, windowSize.y - PANELSIZE_Y + 25) ); m_window.draw(circleShape); m_window.draw(text); ss << nb; text.setString(ss.str()); text.setColor(sf::Color::Black); text.setPosition(sf::Vector2f(311, windowSize.y - PANELSIZE_Y + 30) ); m_window.draw(text); } void View::_displayPanelCaseThystame(sf::Vector2u & windowSize, unsigned int nb) { sf::CircleShape circleShape(15); sf::Text text; std::stringstream ss; text.setFont(m_font); text.setCharacterSize(Settings::SizeTextLegendRessources); text.setColor(Color::Thystame); text.setPosition( sf::Vector2f(325, windowSize.y - PANELSIZE_Y + 55) ); text.setString("Thystame"); circleShape.setFillColor(Color::Thystame); circleShape.setPosition(sf::Vector2f(335, windowSize.y - PANELSIZE_Y + 25) ); m_window.draw(circleShape); m_window.draw(text); ss << nb; text.setString(ss.str()); text.setColor(sf::Color::Black); text.setPosition(sf::Vector2f(346, windowSize.y - PANELSIZE_Y + 30) ); m_window.draw(text); } <file_sep>/* ** fork.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sat Jul 12 13:13:40 2014 courtu_r ** Last update Sun Jul 13 20:54:34 2014 courtu_r */ #include "zappy.h" #include "proto.h" int hatch_egg(t_egg *egg, t_zappy *server) { egg->tick = 0.0; egg->active = true; egg->team->nb_slots_max += 1; server->currentRessource = egg; if (!put_in_list(server->listWrite, create_gui_ans(tograph_eht(server), 0.0f))) return (1); return (0); } t_egg *set_egg_attrs(t_clientIA *client, t_zappy *server, uint id) { t_egg *egg; // wasd client->socket if (!(egg = alloc_egg((uint)id, alloc_clientIA(client->team, client->id)))) return (NULL); egg->player->x = client->x; egg->player->y = client->y; egg->id = client->id; // this is new egg->player->id = client->id; egg->x = client->x; egg->y = client->y; egg->tick = ((double) (42.0f / server->delay)) + ((double) (600.0f / server->delay)); egg->tick = get_tick(egg->tick); return (egg); } int _fork(t_zappy *server, t_clientIA *client, char *cmd) { double frequency; int id; t_egg *egg; id = server->listEGG->length + 1; (void)cmd; frequency = ((double)42.0f / server->delay); client->lastAction = get_tick(frequency); server->currentRessource = client; if (!(egg = set_egg_attrs(client, server, (uint)id))) return (1); if (!put_in_list(server->listWrite, create_gui_ans(tograph_pfk(server), 0.0))) return (1); server->currentRessource = egg; if (!put_in_list(server->listWrite, create_gui_ans(tograph_enw(server), client->lastAction))) return (1); egg->player->socket = -1; if (!(put_in_list(server->listEGG, egg))) return (1); copy_in_buff("ok\n", client->buff_write); client->write = true; return (0); } <file_sep>#include <iostream> #include "Map.hpp" Map::Map() : m_length(0), m_width(0) { } Map::Map(unsigned int l, unsigned int w) : m_length(l), m_width(w) { } Map::~Map() { m_map.clear(); } Case* Map::atCoords(unsigned int x, unsigned int y) { unsigned int n = x * m_width + y; return m_map[n]; } unsigned int Map::getLength() const { return m_length; } unsigned int Map::getWidth() const { return m_width; } void Map::setMap(unsigned int l, unsigned int w) { m_length = l; m_width = w; _initialize_clear_map(); } void Map::_initialize_clear_map() { unsigned int x = 0; unsigned int y = 0; m_map.clear(); for (unsigned int i = 0; i < m_width * m_length ; ++i) { m_map.push_back( new Case(x, y) ); if (y < m_width - 1) { y += 1; } else { y = 0; x += 1; } } } std::vector<Case *> & Map::getVectCase() { return m_map; } <file_sep>/* ** decrement_food.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sat Jul 12 12:13:21 2014 courtu_r ** Last update Sun Jul 13 20:01:38 2014 courtu_r */ #include <math.h> #include "zappy.h" #include "clients.h" #include "inventory.h" int call_pie(t_zappy *, t_clientIA *, double, int); void last_checks(t_zappy *server, t_clientIA *client, bool *ret, bool first_check) { if (!first_check) { call_pie(server, client, 0.0f, 0); } client->error = true; *ret = false; } void set_end_client(t_clientIA *client) { client->write = true; client->lastAction = 0.0f; client->call_incantation = false; } void finish_decrement(t_clientIA **client) { copy_in_buff("mort\n", (*client)->buff_write); (*client)->write = true; (*client)->decLife = 0.0f; (*client)->isDead = true; (*client)->lastAction = 0.0f; } int decrement_food(t_clientIA *client, t_inventory *inventory, t_zappy *server, t_egg *egg) { inventory->content[Food] -= 126; if (inventory->content[Food] <= 0) { if (!egg) { server->currentRessource = client; if (!put_in_list(server->listWrite, create_gui_ans(tograph_pdi(server), client->lastAction))) return (1); } else { server->currentRessource = egg; if (!put_in_list(server->listWrite, create_gui_ans(tograph_edi(server), client->lastAction))) return (1); egg->team->nb_slots_max -= 1; } finish_decrement(&client); return (1); } else return (0); } double get_sign(double *vec_dist, double *vec_comp) { double s; s = (vec_dist[0] * vec_comp[1] - vec_dist[1] * vec_comp[0]); if (s < 0.0) return (-1.0); else return (1.0); } <file_sep>/* ** serv_to_gui_4.c for communications in /home/titouan/Dropbox/Bomberman/blowshitup/ServerZappy/server/communications ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sun Jul 13 13:20:01 2014 Titouan Creach ** Last update Sun Jul 13 20:51:38 2014 courtu_r */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "tograph.h" #include "broadcast.h" #include "list.h" /* ** currentRessource == t_egg* */ char *tograph_enw(t_zappy *z) { char buffer[SIZE_BUFF]; t_egg *egg; egg = (t_egg*)z->currentRessource; snprintf(buffer, SIZE_BUFF, "enw %u %d %d %d\n", egg->id, getPlayerId(egg->player), egg->x, egg->y); return (strdup(buffer)); } /* ** currentRessource must be a t_clientIA* */ char *tograph_pdi(t_zappy *z) { t_clientIA *diedPlayer; char buffer[SIZE_BUFF]; diedPlayer = (t_clientIA*)z->currentRessource; snprintf(buffer, SIZE_BUFF, "pdi %d\n", getPlayerId(diedPlayer)); return strdup(buffer); } /* ** currentRessource must be a t_clientIA* */ char *tograph_pex(t_zappy *z) { t_clientIA *kickedPlayer; char buffer[SIZE_BUFF]; kickedPlayer = (t_clientIA*)z->currentRessource; snprintf(buffer, SIZE_BUFF, "pex %d\n", getPlayerId(kickedPlayer)); return strdup(buffer); } /* ** currentRessource must be a t_ressourcePlayer* */ char *tograph_pdr(t_zappy *z) { char buffer[SIZE_BUFF]; t_ressourcePlayer *ressourcePlayer; ressourcePlayer = (t_ressourcePlayer*)z->currentRessource; snprintf(buffer, SIZE_BUFF, "pdr %d %d\n", getPlayerId(ressourcePlayer->clientIA), ressourcePlayer->noRessource); return (strdup(buffer)); } /* ** currentRessource must be a t_ressourcePlayer* */ char *tograph_pgt(t_zappy *z) { char buffer[SIZE_BUFF]; t_ressourcePlayer *ressourcePlayer; ressourcePlayer = (t_ressourcePlayer*)z->currentRessource; snprintf(buffer, SIZE_BUFF, "pgt %d %d\n", getPlayerId(ressourcePlayer->clientIA), ressourcePlayer->noRessource); return strdup(buffer); } <file_sep>/* ** inventory_utils.c for Zappu in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sat Jul 12 12:09:26 2014 courtu_r ** Last update Sat Jul 12 12:10:17 2014 courtu_r */ #include <time.h> #include <stdlib.h> #include <stdio.h> #include "zappy.h" #include "clients.h" #include "inventory.h" int get_pow(int nb) { int cnt; cnt = 1; while (nb > 10) { nb /= 10; cnt += 1; } return (cnt); } int get_length(t_inventory *inventory) { int cnt; int ret; cnt = 0; ret = 83; while (cnt < 7) { ret += get_pow(inventory->content[cnt]); cnt += 1; } return (ret); } void print_inventory(t_inventory *inventory) { printf("Inventory contents :\n\t- Food : %d\n\t- Linemate : %d\n", inventory->content[0], inventory->content[1]); printf("\t- Deraumere : %d\n", inventory->content[2]); printf("\t- Sibur : %d\n\t- Mendiane : %d\n\t- Phiras : %d\n", inventory->content[3], inventory->content[4], inventory->content[5]); printf("\t- Thystame : %d\n", inventory->content[6]); } int add_resource(e_resource resource, Uint nb, t_inventory *inventory) { if (resource < 7 && resource != Food) inventory->content[resource] += nb; else if (resource == Food) inventory->content[resource] += nb * 126; else return (1); return (0); } int get_nb_resource(e_resource resource, t_inventory *inventory) { if (resource < 7 && resource != Food) return (inventory->content[resource]); else if (resource < 7) return (inventory->content[Food] / 126); else return (-1); } <file_sep>/* ** connect_nbr.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sat Jul 12 13:13:05 2014 courtu_r ** Last update sam. juil. 12 19:11:05 2014 <NAME> */ #include "zappy.h" int connect_nbr(t_zappy *server, t_clientIA *client, char *cmd) { int len; int res; char *ans; (void)cmd; (void)server; res = client->team->nb_slots_max - client->team->nbplayers; len = get_pow(res); if ((ans = malloc(sizeof(*ans) * (len + 2))) == NULL) return (1); sprintf(ans, "%d\n", res); printf("Ans = [%s]\n", ans); client->lastAction = 0.0f; copy_in_buff(ans, client->buff_write); client->write = true; free(ans); return (0); } <file_sep>/* ** routine_connexion.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/network ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:58:40 2014 ** Last update dim. juil. 13 16:57:41 2014 <NAME> */ #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include "zappy.h" static int write_node_connexion(t_zappy *s, t_conn *conn); static int read_node_connexion(t_zappy *s, t_conn *conn); static int actions_node_connexion(t_zappy *s, t_conn *conn); t_node *routine_connexion(t_zappy *s, t_node *node, t_type type, int *ret) { t_conn *conn; (void)ret; if (type != CONN) return (NULL); conn = ((t_conn*)node->data); if (conn) { if (write_node_connexion(s, conn) == -1) return rm_node(s->listConn, node); if (read_node_connexion(s, conn) == -1) return rm_node(s->listConn, node); if (actions_node_connexion(s, conn) == -1) return rm_node(s->listConn, node); } return (node->next); } static int write_node_connexion(t_zappy *s, t_conn *conn) { const char *welcome = "BIENVENUE\n"; const char *error = "ko\n"; ssize_t nbwrites; if (conn->welcome && FD_ISSET(conn->socket, &(s->writesd))) { nbwrites = write(conn->socket, welcome, strlen(welcome)); if (nbwrites == ((ssize_t)strlen(welcome))) conn->welcome = false; } else if (conn->write && FD_ISSET(conn->socket, &(s->writesd))) { nbwrites = write(conn->socket, error, strlen(error)); if (nbwrites == ((ssize_t)strlen(error))) conn->write = false; } return (0); } static int read_node_connexion(t_zappy *s, t_conn *conn) { if (FD_ISSET(conn->socket, &(s->readsd))) { if (write_in_buff(conn->socket, conn->buff_read, false, 0) <= 0) { if (close(conn->socket) == -1) perror("Close failed. Error"); return (-1); } } return (0); } static int actions_node_connexion(t_zappy *s, t_conn *conn) { char *str; int ret; int len; while ((str = try_get_cmd(conn->buff_read))) { len = strlen(str); if (str[len - 1] != '\n') { free(str); conn->write = true; return (1); } str[len - 1] = '\0'; ret = choose_graphic_or_ia(s, conn, str); free(str); return (ret); } return (0); } <file_sep>/* ** choose_graphic_or_ia.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/network ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:58:15 2014 ** Last update Sun Jul 13 20:08:45 2014 courtu_r */ #include <string.h> #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include "zappy.h" static int create_client_gui(t_zappy *, t_conn*); static void finish_client(t_zappy *, t_clientIA *, t_team *, t_conn *); int choose_graphic_or_ia(t_zappy *s, t_conn *c, const char *buff) { t_team *team; if (strcmp(buff, HOME_GUI) == 0) return (create_client_gui(s, c)); else if ((team = is_in_list_of_team(s->listTeam, buff))) { if (team->nbplayers >= team->nb_slots_max) { printf("%s", get_color_term(SERVER)); printf("Deconnexion because team %s is already full", team->name); printf("%s\n", get_color_term(DISABLE)); write(c->socket, "ko\n", 3); close(c->socket); return (-1); } return (choose_client(s, team, c)); } else { write(c->socket, "ko\n", 3); close(c->socket); return (-1); } return (0); } int create_client_ia(t_zappy *s, t_conn* c, t_team *team) { t_clientIA *clientIA; if (!(clientIA = alloc_clientIA(team, c->socket))) return (0); clientIA->x = rand() % s->width; clientIA->y = rand() % s->height; if (!(place_player(clientIA, s->map))) { free(clientIA); return (0); } if (!(put_in_list(s->listIA, clientIA))) { free(clientIA); return (0); } clientIA->id = ++(s->max_id); finish_client(s, clientIA, team, c); return (-1); } static void finish_client(t_zappy *s, t_clientIA *c, t_team *t, t_conn *co) { t_gui_answer *answer; printf("%s", get_color_term(SERVER)); printf("*** Added new player %d at (%d, %d)", c->id, c->x, c->y); printf("%s\n", get_color_term(DISABLE)); c->decLife = get_tick(((double)UNIT_TIME / s->delay)); ++(t->nbplayers); first_send_ia(c, s, t); c->buff_read = co->buff_read; co->buff_read = NULL; s->currentRessource = c; answer = create_gui_ans(tograph_pnw(s), 0); put_in_list(s->listWrite, answer); new_client_spawn_food(s); } static int create_client_gui(t_zappy *s, t_conn* c) { t_clientGUI *clientGUI; if (!(clientGUI = alloc_clientGUI(c->socket))) { c->write = true; return (0); } if (!(put_in_list(s->listGUI, clientGUI))) { free(clientGUI); c->write = true; return (0); } clientGUI->writeConn = tograph_welcome_msg(s); clientGUI->buff_read = c->buff_read; c->buff_read = NULL; return (-1); } void first_send_ia(t_clientIA *clientIA, t_zappy *s, t_team *team) { char buffer[50]; sprintf(buffer, "%d\n", team->nb_slots_max - team->nbplayers); copy_in_buff(buffer, clientIA->buff_write); sprintf(buffer, "%d %d\n", s->width, s->height); copy_in_buff(buffer, clientIA->buff_write); clientIA->write = true; } <file_sep>/* ** inventory.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sat Jul 12 12:02:12 2014 courtu_r ** Last update Sun Jul 13 21:29:08 2014 courtu_r */ #include <time.h> #include <stdlib.h> #include <stdio.h> #include "zappy.h" #include "clients.h" #include "inventory.h" int inventory(t_zappy *server, t_clientIA *client, char *cmd) { char *msg; double frequency; (void)cmd; frequency = ((double)1.0f / server->delay); client->lastAction = get_tick(frequency); msg = get_inventory(client->inventory); if (msg) { copy_in_buff(msg, client->buff_write); client->write = true; free(msg); } else return (1); return (0); } t_inventory *random_init(t_inventory *inventory) { Uint spawn; Uint res; if (inventory == NULL && (inventory = malloc(sizeof(*inventory))) == NULL) return (NULL); res = 0; spawn = rand() % (MAX_RESOURCES + 1); while (res < 7) inventory->content[res++] = 0; if (spawn < MIN_RESOURCES) spawn = MIN_RESOURCES; while (spawn > 0) { res = random() % 7; if (res != Food) inventory->content[res] += 1; else inventory->content[res] += 126; spawn -= 1; } return (inventory); } t_inventory *init_inventory(t_inventory *inventory) { if (inventory == NULL && (inventory = malloc(sizeof(*inventory))) == NULL) return (NULL); inventory->content[Food] = 1260; inventory->content[Linemate] = 0; inventory->content[Deraumere] = 0; inventory->content[Sibur] = 0; inventory->content[Mendiane] = 0; inventory->content[Phiras] = 0; inventory->content[Thystame] = 0; return (inventory); } int del_resource(e_resource resource, Uint nb, t_inventory *inventory) { Uint keep; keep = inventory->content[resource]; if (resource < 7 && resource != Food) inventory->content[resource] -= nb; else if (resource == Food) inventory->content[resource] -= nb * 126; else return (1); if (inventory->content[resource] > keep) inventory->content[resource] = 0; return (0); } char *get_inventory(t_inventory *inventory) { char *test = malloc(sizeof(*test) * (get_length(inventory) + 1)); sprintf(test, "{nourriture %d, sibur %d, phiras %d, linemate %d, \ thystame %d, mendiane %d, deraumere %d}\n", inventory->content[Food], inventory->content[Sibur], inventory->content[Phiras], inventory->content[Linemate], inventory->content[Thystame], inventory->content[Mendiane], inventory->content[Deraumere]); return (test); } <file_sep>/* ** see.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sat Jul 12 13:59:31 2014 courtu_r ** Last update Sun Jul 13 19:49:13 2014 courtu_r */ #include <string.h> #include "proto.h" #include "zappy.h" void set_end_game(t_zappy *server, t_clientIA *client) { server->game = false; server->currentRessource = client->team; if (!(put_in_list(server->listWrite, create_gui_ans(tograph_seg(server), 0.0f)))) return ; } char *add_resources(t_inventory invent, int nb_resources, t_zappy *server, char *msg) { int i; i = 0; while (nb_resources > 0 && i < 7) { if (invent.content[i] < 1) i += 1; else { if ((msg = realloc (msg, sizeof(*msg) * (my_strlen(msg) + my_strlen (server->resources[i]) + 2) )) == NULL) return (NULL); msg = strcat(msg, server->resources[i]); nb_resources -= 1; invent.content[i] -= get_ressources_to_sub(i); if (nb_resources) msg = strcat(msg, " "); } } return (msg); } char *serialize_case(t_case *pos, char *msg, t_zappy *server) { if ((msg = add_players(count_nb_players(pos->players), msg, server)) == NULL) return (NULL); if ((msg = realloc(msg, sizeof(*msg) * (strlen(msg) + 2))) == NULL) return (NULL); if ((msg = strcat(msg, " ")) == NULL) return (NULL); if ((msg = add_resources(*(pos->inventory), cnt_nb_resources(pos->inventory), server, msg)) == NULL) return (NULL); return (msg); } char *get_left_right(t_zappy *server, char *msg, t_clientIA *player) { int width; int depth; int tmpX; int tmpY; int nbcases; int cnt; nbcases = get_nb_cases(player->level); init_int_var_left_right(&width, &depth, &cnt); init_pos_player_left_right(&tmpX, &tmpY, player); while (depth <= player->level) { while (cnt < width) { if ((msg = serialize_case(server->map->map[tmpY] [correct_x(tmpX, server)], msg, server)) == NULL) return (NULL); if (mid_loop_left_right(&nbcases, &cnt, &msg) == -1) return (NULL); f_cor_saw_left_right(player, &tmpY, server); } looping_left_right(&cnt, &width, &depth); cor_saw_left_right(player, &tmpY, width, server); tmpX = correct_x(tmpX + (player->x_moves[player->direction]), server); } return (msg); } int see(t_zappy *server, t_clientIA *client, char *cmd) { double frequency; char *msg = NULL; if (!(msg = malloc(sizeof(*msg) * 2))) return (-1); msg[0] = '{'; msg[1] = 0; (void)cmd; frequency = ((double)7.0f / server->delay); client->lastAction = get_tick(frequency); if (client->direction == Up || client->direction == Down) msg = get_up_down(server, msg, client); else if (client->direction == Right || client->direction == Left) msg = get_left_right(server, msg, client); if ((msg = realloc(msg, sizeof(*msg) * (strlen(msg) + 3))) == NULL) return (-1); if ((msg = strcat(msg, "}\n")) == NULL) return (-1); client->big_write = msg; return (0); } <file_sep>/* ** case.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ZappyTitou/map ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Mon Jun 23 15:53:43 2014 courtu_r ** Last update Sat Jul 12 13:12:42 2014 courtu_r */ #include <stdlib.h> #include <stdio.h> #include "clients.h" #include "case.h" void free_case(t_case *to_free) { free(to_free->inventory); release_list(to_free->players); free(to_free); } bool add_player(t_clientIA *player, t_case *pos) { if (!(put_in_list(pos->players, (void *)(player)))) return (false); return (true); } void remove_player(t_clientIA *player, t_case *pos) { t_list *players; t_node *node; players = pos->players; node = players->head; while (node) { if ((t_clientIA *)(node->data) == player) { node = rm_node(players, node); node = NULL; } if (node) node = node->next; } } void print_case(t_case *this) { printf("Pos x : %d\t--\tPosY : %d\n", this->pos_x, this->pos_y); printf("Contents : \n"); print_inventory((this->inventory)); } t_case *init_case(Uint x, Uint y) { t_case *this; if (!(this = malloc(sizeof(*this)))) return (NULL); this->pos_x = x; this->pos_y = y; this->inventory = NULL; this->inventory = random_init((this->inventory)); this->players = create_list(PLAYER); return (this); } <file_sep>#include <iostream> #include "TextureManager.hpp" #include "Except.hpp" TextureManager TextureManager::m_instance = TextureManager(); TextureManager::TextureManager() { /* sprites */ for (auto &i : TEXTURES_PATH) { sf::Texture current_texture; std::cout << "[TextureManager] -> loading : " << i.first << std::endl; if (!current_texture.loadFromFile(i.first)) { std::cerr << "[TextureManager] failed" << std::endl; throw Except("Error : [TextureManager] failed to load :" + i.first); } current_texture.setSmooth(true); m_textures[i.second] = current_texture; } /* font */ if (!m_font.loadFromFile("./assets/Animated.ttf")) { std::cerr << "[TextureManager] failed" << std::endl; throw Except("Error : [TextureManager] failed to load Animated.ttf" ); } } TextureManager::~TextureManager() {} TextureManager& TextureManager::Instance() { return m_instance; } const sf::Texture & TextureManager::getTexture(const e_texture id) { return m_textures[id]; } const sf::Font & TextureManager::getFont () { return m_font; }<file_sep>/* ** serv_to_gui_6.c for communications in /home/titouan/Dropbox/Bomberman/blowshitup/ServerZappy/server/communications ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sun Jul 13 13:21:03 2014 Titouan Creach ** Last update Sun Jul 13 13:21:03 2014 Titouan Creach */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "tograph.h" #include "broadcast.h" #include "list.h" /* ** currentRessource = t_clientIA */ char *tograph_pfk(t_zappy *z) { char buffer[SIZE_BUFF]; snprintf(buffer, SIZE_BUFF, "pfk %d\n", getPlayerId((t_clientIA*)z->currentRessource)); return strdup(buffer); } /* ** currentRessource = t_egg* */ char *tograph_eht(t_zappy *z) { char buffer[SIZE_BUFF]; snprintf(buffer, SIZE_BUFF, "eht %u\n", ((t_egg*)z->currentRessource)->id); return strdup(buffer); } /* ** currentRessource = t_egg* */ char *tograph_edi(t_zappy *z) { char buffer[SIZE_BUFF]; snprintf(buffer, SIZE_BUFF, "edi %u\n", ((t_egg*)z->currentRessource)->id); return strdup(buffer); } /* ** currentRessource = t_egg* */ char *tograph_ebo(t_zappy *z) { char buffer[SIZE_BUFF]; snprintf(buffer, SIZE_BUFF, "ebo %u\n", ((t_egg*)z->currentRessource)->id); return strdup(buffer); } /* ** currentRessource = t_incantation_ended* */ char *tograph_pie(t_zappy *z) { char buffer[SIZE_BUFF]; snprintf(buffer, SIZE_BUFF, "pie %u %u %d\n", ((t_incantation_ended*)z->currentRessource)->ncase->pos_x, ((t_incantation_ended*)z->currentRessource)->ncase->pos_y, ((t_incantation_ended*)z->currentRessource)->result); return (strdup(buffer)); } <file_sep>/* ** proto.h for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sun Jul 13 16:30:47 2014 courtu_r ** Last update Sun Jul 13 19:37:18 2014 courtu_r */ #include "broadcast.h" #ifndef PROTO_H__ # define PROTO_H__ void set_end_game(t_zappy *, t_clientIA *); void write_level_up(t_zappy *, t_clientIA *); void init_int_var_left_right(int *, int *, int *); void f2_cor_up_down(int *, t_clientIA *, t_zappy *); void f3_cor_up_down(int *, t_clientIA *, t_zappy *, int); void init_pos_player_left_right(int *, int *, t_clientIA *); void looping_left_right(int *, int *, int *); void cor_saw_left_right(t_clientIA *, int *, int, t_zappy *); void f_cor_saw_left_right(t_clientIA *, int *, t_zappy *); bool place_player(t_clientIA *, t_map *); bool add_player_to_pos(t_clientIA *, t_map *, Uint, Uint); void remove_player_from_pos(t_clientIA *, t_map *, Uint, Uint); int my_strlen(char *); int count_nb_players(t_list *); int cnt_nb_resources(t_inventory *); int get_ressources_to_sub(int); int get_nb_cases(int); int f_cor_up_down(int *, int *, char **); int mid_loop_left_right(int *, int *, char **); char *add_players(int, char *, t_zappy *); char *get_up_down(t_zappy *, char *, t_clientIA *); char *serialize_case(t_case *, char *, t_zappy *); t_egg *alloc_egg(uint, t_clientIA *); #endif /*PROTO_H__*/ <file_sep>/* ** utils_buffer.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/struct ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:56:25 2014 ** Last update dim. juil. 13 18:18:27 2014 julien thebaud */ #include <stdlib.h> #include <string.h> #include "circular_buffer.h" Uint get_size_left(const char *endPtr, const char *buf) { int len; len = SIZE - (endPtr - buf); if (len >= 2) return (len); else if (len == 1) return (1); else return (0); } Uint is_filled(t_buff *buff) { if (buff->writeCnt > buff->readCnt) return (1); else return (0); } Uint check_size(t_buff *buff) { Uint ret; if ((ret = get_size_left(buff->endPtr, buff->buf))) return (ret); printf("endPTR DECALAGE\n"); buff->endPtr = buff->buf; return (get_size_left(buff->endPtr, buff->buf)); } char *check_str(t_buff *buff, char *str, char *keepBeg, int cnt) { if (*(buff->begPtr) != '\n') { buff->begPtr = keepBeg; buff->readCnt -= cnt; free(str); return (NULL); } return (""); } int copy_in_buff(char *str, t_buff *buff) { Uint cnt = 0; while (cnt < strlen(str)) { *(buff->endPtr) = str[cnt]; buff->writeCnt += 1; buff->endPtr += 1; if (buff->endPtr >= buff->buf + SIZE) buff->endPtr = buff->buf; cnt += 1; } return (strlen(str)); } <file_sep>/* ** broadcast.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sat Jul 12 12:47:25 2014 courtu_r ** Last update Sun Jul 13 18:37:02 2014 courtu_r */ #include <math.h> #include <string.h> #include "zappy.h" double *get_unit_vector(double, double); double **init_vectors(); double *get_vector(double, double, double, double); double *normalize_vec(double *); int get_correct_num(double); double scal_prod(double *, double *, bool); double *get_shortest_vector(t_clientIA *, t_clientIA *, t_zappy *); int my_strlen(char *); char *get_param(char *); double get_sign(double *, double *); int get_case(t_clientIA *send, t_clientIA *recv, double **vectors, t_zappy *server) { double *vec_dist; double *vec_comp; double res; double scalar_prod; double norm_scal_prod; double s; vec_dist = get_shortest_vector(recv, send, server); vec_comp = vectors[recv->direction]; s = get_sign(vec_dist, vec_comp); scalar_prod = (double)scal_prod(vec_dist, vec_comp, false); if (!vec_dist || !vec_comp) return (-1); norm_scal_prod = (double)scal_prod(vec_dist, vec_comp, true); res = scalar_prod / norm_scal_prod; free(vec_dist); free(vectors[Up]); free(vectors[Down]); free(vectors[Left]); free(vectors[Right]); free(vectors); return (get_correct_num((s * acos(res)) * (180.0 / M_PI))); } char *create_broadcast_msg(char *msg, int dir) { char *str; if (!(str = malloc(sizeof(*str) * (my_strlen(msg) + 1 + 12)))) return (NULL); sprintf(str, "message %d,%s\n", dir, msg); return (str); } void call_back_broadcast(t_zappy *server, t_clientIA *client) { t_node *node; t_clientIA *other; int ret; node = server->listIA->head; while (node) { other = (t_clientIA *)(node->data); if (other != client) { if (other->x == client->x && other->y == client->y) ret = 0; else ret = get_case(client, other, init_vectors(), server); other->instant_write = create_broadcast_msg(client->broadcast->msg, ret); } node = node->next; } server->currentRessource = client->broadcast; put_in_list(server->listWrite, create_gui_ans(tograph_pbc(server), client->lastAction)); free(client->broadcast->msg); free(client->broadcast); client->broadcast = NULL; } t_broadcast *create_broadcast(char *msg, int num) { t_broadcast *broadcast; if (!(broadcast = malloc(sizeof(*broadcast)))) return (NULL); broadcast->msg = strdup(msg); free(msg); if (broadcast->msg == NULL) return (NULL); broadcast->noPlayer = num; return (broadcast); } int broadcast(t_zappy *server, t_clientIA *client, char *cmd) { double frequency; frequency = ((double)7.0f / server->delay); client->lastAction = get_tick(frequency); client->broadcast = create_broadcast(get_param(cmd), client->id); if (client->broadcast) { client->write = true; copy_in_buff("ok\n", client->buff_write); } else client->error = true; return (0); } <file_sep>/* ** incantation_utils.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sat Jul 12 15:01:32 2014 courtu_r ** Last update Sat Jul 12 15:02:11 2014 courtu_r */ #include <string.h> #include <stdlib.h> #include "zappy.h" int call_pic(t_zappy *server, t_clientIA *client, double tick) { t_incantation_for_players *ans; if (!(ans = malloc(sizeof(*ans)))) return (1); ans->ncase = server->map->map[client->y][client->x]; ans->listPlayer = ans->ncase->players; ans->incanter = client; server->currentRessource = ans; if (!put_in_list(server->listWrite, create_gui_ans(tograph_pic(server), tick))) return (1); free(ans); return (0); } int call_pie(t_zappy *server, t_clientIA *client, double tick, int cond) { t_incantation_ended *ans; if (!(ans = malloc(sizeof(*ans)))) return (1); ans->ncase = server->map->map[client->y][client->x]; ans->result = cond; server->currentRessource = ans; if (!put_in_list(server->listWrite, create_gui_ans(tograph_pie(server), tick))) return (1); free(ans); return (0); } int call_plv(t_zappy *server, t_clientIA *client, double tick) { server->currentRessource = client; if (!put_in_list(server->listWrite, create_gui_ans(tograph_plv(server), tick))) return (1); return (0); } bool has_enough_players(t_list *players, int level, int nb_required) { t_node *node; t_clientIA *client; int cnt; cnt = 0; node = players->head; while (node) { client = (t_clientIA *)node->data; if (client->level == level) cnt += 1; node = node->next; } if (cnt == nb_required) return (true); return (false); } bool has_all_resources(t_inventory *ref, t_inventory *pos) { int i; i = 0; while (i < 7) { if (ref->content[i] > pos->content[i]) return (false); i += 1; } return (true); } <file_sep>/* ** func_parse.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/init ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 16:15:11 2014 ** Last update dim. juil. 13 21:40:20 2014 <NAME> */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include "parse.h" #include "utils.h" static t_team *alloc_team(const char *name); bool parse_port(t_zappy *s, int argc, char **argv, int *flags) { (void)argc; (void)argv; (*flags) += FLAGS_P; if (!is_digit(optarg)) { fprintf(stderr, "Argument of -p must be a number.\n"); return (false); } s->port = atoi(optarg); if (s->port < 1 || s->port > 65535) { fprintf(stderr, "Argument of -p must be a positif number.\n"); return (false); } return (true); } bool parse_width(t_zappy *s, int argc, char **argv, int *flags) { (void)argc; (void)argv; (*flags) += FLAGS_X; if (!is_digit(optarg)) { fprintf(stderr, "Argument of -x must be a number.\n"); return (false); } s->width = atoi(optarg); if (s->width < 1 || s->width > 1000000) { fprintf(stderr, "Argument of -x must be a positif number.\n"); return (false); } return (true); } bool parse_height(t_zappy *s, int argc, char **argv, int *flags) { (void)argc; (void)argv; (*flags) += FLAGS_Y; if (!is_digit(optarg)) { fprintf(stderr, "Argument of -y must be a number.\n"); return (false); } s->height = atoi(optarg); if (s->height < 1 || s->height > 1000000) { fprintf(stderr, "Argument of -y must be a positif number.\n"); return (false); } return (true); } bool parse_name_team(t_zappy *s, int argc, char **argv, int *flags) { int index; t_team *team; (*flags) += FLAGS_N; index = optind - 2; while (++index < argc && argv[index][0] != '-') { if (strlen(argv[index]) < 1) { fprintf(stderr, "Invalid length of team name\n"); return (false); } if (!(team = alloc_team(argv[index]))) return (false); team->nb_slots_max = s->nbClients; if (!(put_in_list(s->listTeam, team))) return (false); } return (true); } static t_team *alloc_team(const char *name) { t_team *ret; if (!(ret = malloc(sizeof(*ret)))) return (NULL); bzero(ret->name, sizeof(ret->name)); ret->length = strlen(name); ret->nbplayers = 0; if (ret->length < sizeof(ret->name)) strncpy(ret->name, name, ret->length); else strncpy(ret->name, name, sizeof(ret->name) - 1); return (ret); } <file_sep>/* ** connexion.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/network ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:59:09 2014 ** Last update Sun Jul 13 15:59:10 2014 */ #include <stdio.h> #include <stdlib.h> #include "zappy.h" static t_conn *alloc_conn(SOCKET sd); int connexion(t_zappy *server) { t_conn *conn; int new_sock; if ((new_sock = accept(server->listen, NULL, 0)) == -1) { perror("Accept failed. Error"); return (1); } if (!(conn = alloc_conn(new_sock))) return (2); if (!(put_in_list(server->listConn, conn))) return (3); printf("%s", get_color_term(SERVER)); printf("*** New connexion id: %d", new_sock); printf("%s\n", get_color_term(DISABLE)); return (0); } static t_conn *alloc_conn(SOCKET sd) { t_conn *ret; if (!(ret = malloc(sizeof(*ret)))) return (NULL); if (!(ret->buff_read = alloc_buff())) return (free_va_arg(1, ret)); ret->socket = sd; ret->welcome = true; ret->write = false; ret->deco = false; return (ret); } <file_sep>#include "Team.hpp" Team::Team(std::string const &str, sf::Color col) : _teamName(str), _color(col) { } Team::~Team() { std::list<Player *>::iterator it; std::list<Egg *>::iterator it2; for (it = _players.begin(); it != _players.end(); it++) { delete (*it); } for (it2 = _egg.begin(); it2 != _egg.end(); it2++) { delete (*it2); } } void Team::setTeamColor(sf::Color const &col) { _color = col; } sf::Color const &Team::getTeamColor() const { return (_color); } void Team::setNewPlayer(Player *playe) { _players.push_back(playe); } std::list<Player*> &Team::getPlayers() { return (_players); } std::string const &Team::getTeamName() const { return (_teamName); } void Team::setTeamName(std::string const &str) { _teamName = str; } std::list<Egg*> &Team::getEggs() { return (_egg); } void Team::setNewEgg(Egg *egg) { _egg.push_back(egg); } unsigned int Team::getMaxLevel() const { unsigned int level = 0; for (auto &i : _players) { if (i->getLevel() > level) level = i->getLevel(); } return level; }<file_sep>/* ** routine_clients_gui.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/network ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:58:32 2014 ** Last update dim. juil. 13 17:47:46 2014 <NAME> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include "zappy.h" static int read_node_gui(t_zappy *s, t_clientGUI *client); static int write_node_gui(t_zappy *s, t_clientGUI *client); static int actions_node_gui(t_zappy *s, t_clientGUI *client); static int error_node_gui(t_zappy *s, t_clientGUI * client); t_node *routine_clientGUI(t_zappy *s, t_node *node, t_type type, int *ret) { t_clientGUI *client; (void)ret; if (type != GUI) return (NULL); client = ((t_clientGUI*)node->data); if (client) { if (error_node_gui(s, client) == -1) return rm_node(s->listGUI, node); if (read_node_gui(s, client) == -1) return rm_node(s->listGUI, node); if (actions_node_gui(s, client) == -1) return rm_node(s->listGUI, node); if (write_node_gui(s, client) == -1) return rm_node(s->listGUI, node); } return (node->next); } static int actions_node_gui(t_zappy *s, t_clientGUI *client) { char *str; t_cmd_gui num; if ((str = try_get_cmd(client->buff_read))) { if ((num = find_cmd_gui(str)) != NONE) (*s->ptr_func_gui[num])(s, client, str); else client->error = true; free(str); } return (0); } static int write_node_gui(t_zappy *s, t_clientGUI *client) { const char *error = "suc\n"; ssize_t nbwrites; if (client->error && FD_ISSET(client->socket, &(s->writesd))) { nbwrites = write(client->socket, error, strlen(error)); if (nbwrites != ((ssize_t)strlen(error))) fprintf(stderr, "send() failed.\n"); client->error = false; } else write_gui(s, client); return (0); } static int read_node_gui(t_zappy *s, t_clientGUI *client) { if (FD_ISSET(client->socket, &(s->readsd))) { if (write_in_buff(client->socket, client->buff_read, false, 0) <= 0) { printf("Déco client GUI :%d\n", client->socket); if (close(client->socket) == -1) perror("Close failed. Error"); return (-1); } } return (0); } static int error_node_gui(t_zappy *s, t_clientGUI *client) { if (FD_ISSET(client->socket, &(s->exceptsd))) { fprintf(stderr, "Except on socket client\n"); if (close(client->socket) == -1) perror("Close failed. Error"); client->socket = -1; return (-1); } return (0); } <file_sep>#ifndef _ROUTINES_H_ # define _ROUTINES_H_ t_node *routine_clientIA(t_zappy *s, t_node *node, t_type type, int *ret); t_node *routine_connexion(t_zappy *s, t_node *node, t_type type, int *ret); t_node *routine_clientGUI(t_zappy *s, t_node *node, t_type type, int *ret); t_node *routine_egg(t_zappy *s, t_node *node, t_type type, int *ret); t_node *routine_write_answerGUI(t_list *list, t_node *, t_type type, int *); int set_big_write(t_zappy *s, t_node *node, t_type t, int *ret); #endif <file_sep>/* ** serv_to_gui_3.c for communications in /home/titouan/Dropbox/Bomberman/blowshitup/ServerZappy/server/communications ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sun Jul 13 13:19:57 2014 Titouan Creach ** Last update Sun Jul 13 13:19:57 2014 Titouan Creach */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "tograph.h" #include "broadcast.h" #include "list.h" /* ** Don't care about currentRessource */ char *tograph_suc(t_zappy *z) { IGNORE(z); return (strdup("suc\n")); } /* ** currentRessource must be a t_broadcast* */ char *tograph_pbc(t_zappy *z) { t_broadcast *broadcast; char buffer[SIZE_BUFF]; broadcast = (t_broadcast*)z->currentRessource; snprintf(buffer, SIZE_BUFF, "pbc %u %s\n", broadcast->noPlayer, broadcast->msg); return (strdup(buffer)); } /* ** currentRessource must be a t_case* */ char *tograph_bct(t_zappy *z) { char buffer[SIZE_BUFF]; t_case *ncase; ncase = (t_case*)z->currentRessource; snprintf(buffer, SIZE_BUFF, "bct %d %d %u %u %u %u %u %u %u\n", ncase->pos_x, ncase->pos_y, ncase->inventory->content[0] / 126, ncase->inventory->content[1], ncase->inventory->content[2], ncase->inventory->content[3], ncase->inventory->content[4], ncase->inventory->content[5], ncase->inventory->content[6]); return (strdup(buffer)); } /* dont care about currentRessource */ char *tograph_send_map(t_zappy *z) { t_map *map; t_list *l; Uint i; Uint j; l = create_list(CHAR); map = z->map; i = 0; j = 0; while (i < map->height) { while (j < map->width) { z->currentRessource = map->map[i][j]; put_in_list(l, tograph_bct(z)); ++j; } j = 0; ++i; } return (concatList(l)); } /* ** currentRessource must be a t_clientIA* */ char *tograph_pnw(t_zappy *z) { t_clientIA *newPlayer; char buffer[SIZE_BUFF]; newPlayer = (t_clientIA*)z->currentRessource; snprintf(buffer, SIZE_BUFF, "pnw %d %d %d %d %u %s\n", getPlayerId(newPlayer), newPlayer->x, newPlayer->y, newPlayer->direction + 1, newPlayer->level, newPlayer->team->name); return strdup(buffer); } <file_sep>/* ** take_obj.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sat Jul 12 12:24:48 2014 courtu_r ** Last update Sun Jul 13 19:48:32 2014 courtu_r */ #include <string.h> #include "zappy.h" #include "broadcast.h" char *get_param(char *); t_ressourcePlayer *set_object(t_zappy *, t_clientIA *, int); int send_case_inventory(t_zappy *server, t_clientIA *client, t_case *pos) { char *str; server->currentRessource = client; if (!(str = tograph_pin(server))) return (1); if (!put_in_list(server->listWrite, create_gui_ans(str, client->lastAction))) return (1); server->currentRessource = pos; if (!(str = tograph_bct(server))) return (1); if (!put_in_list(server->listWrite, create_gui_ans(str, client->lastAction))) return (1); return (0); } int prend_informations(t_zappy *server, t_clientIA *client, int i, t_case *pos) { char *str; if (!(set_object(server, client, i))) return (1); if (!(str = tograph_pgt(server))) return (1); if (!put_in_list(server->listWrite, create_gui_ans(str, client->lastAction))) return (1); free(server->currentRessource); if (send_case_inventory(server, client, pos)) return (1); return (0); } int take_obj(t_zappy *server, t_clientIA *client, char *cmd) { double frequency; char *resource; int i = 0; t_case *pos; pos = server->map->map[client->y][client->x]; frequency = ((double)7.0f / server->delay); client->lastAction = get_tick(frequency); resource = get_param(cmd); while (i < 7 && strcmp(resource, server->resources[i])) i += 1; if (i > 6 || get_nb_resource(i, pos->inventory) <= 0) { client->error = true; return (1); } add_resource(i, 1, client->inventory); del_resource(i, 1, pos->inventory); if (prend_informations(server, client, i, pos)) return (1); free(resource); copy_in_buff("ok\n", client->buff_write); client->write = true; return (0); } <file_sep> #include <unistd.h> #include "Client.hpp" Client::Client(boost::asio::io_service& io_s, tcp::resolver::iterator endpoint_iterator, char *tn) : io_service(io_s), socket(io_s) { std::string str(tn); this->nextCmd = None; this->can_write = false; this->final_msg = ""; this->msg_len = 0; this->run = true; this->key = 0; this->onFarm = true; this->lastDirBroad = '0'; this->lead = true; this->lvl = 1; this->waitingMore = false; this->paras = false; this->toJoin = false; this->teamName = str; this->rcvBro = true; this->toFollow = ""; this->resCounter = 0; this->connect_start(endpoint_iterator); } Client::~Client() { this->followers.clear(); for (std::vector<Inventory *>::iterator it = this->lastSaw.begin() ; it != this->lastSaw.end() ; ++it) delete (*it); this->lastSaw.clear(); } void Client::write_string(const std::string & msg) { for (std::string::const_iterator it = msg.begin() ; it != msg.end() ; ++it) this->write_char(*it); this->can_write = false; } void Client::write_char(const char msg) { this->io_service.post(boost::bind(&Client::do_write, this, msg)); } void Client::close() { this->io_service.post(boost::bind(&Client::do_close, this)); } bool Client::canWrite() const { return this->can_write; } void Client::setCanWrite(bool s) { this->can_write = s; } CmdType Client::getNextCmd() const { return this->nextCmd; } bool Client::getRun() const { return this->run; } void Client::setNextCmd(CmdType c) { this->nextCmd = c; } void Client::connect_start(tcp::resolver::iterator endpoint_iterator) { tcp::endpoint endpoint = *endpoint_iterator; this->socket.async_connect(endpoint, boost::bind(&Client::connect_complete, this, boost::asio::placeholders::error, ++endpoint_iterator)); } void Client::connect_complete(const boost::system::error_code & error, tcp::resolver::iterator endpoint_iterator) { if (!error) { this->read_start(); } else if (endpoint_iterator != tcp::resolver::iterator()) { this->socket.close(); this->connect_start(endpoint_iterator); this->run = false; } else { std::cout << "Stop : cannot be connected to the host server. [bad ip | bad port]" << std::endl; this->run = false; } } void Client::read_start() { this->socket.async_read_some(boost::asio::buffer(read_msg, max_read_length), boost::bind(&Client::read_complete, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void Client::waitingForMoreClient() { if (this->nextCmd == Voir) { this->rdxForIncantation(); return ; } this->nextCmd = GoForIncante; this->can_write = true; } void Client::chooseDirectionToJoin() { if (this->lastDirBroad == '3' || this->lastDirBroad == '4' || this->lastDirBroad == '5') this->nextCmd = Gauche; else if (this->lastDirBroad == '6' || this->lastDirBroad == '7') this->nextCmd = Droite; else if (this->lastDirBroad == '0') { this->nextCmd = None; this->rcvBro = false; } else this->nextCmd = Avance; } void Client::treatBroadcastRcv() { std::stringstream ss; this->lastDirBroad = this->final_msg[8]; ss << this->lvl; std::string toRcv = this->final_msg.substr(10); std::string toCmp = ss.str(); std::string toCmp2 = ss.str(); std::string toCmp3 = ss.str(); toCmp = "IncantationLvl" + toCmp + this->teamName + ":"; toCmp2 = "OKLvl" + toCmp2 + this->teamName + ":" + this->id + ":"; toCmp3 = "RFILvl" + toCmp3 + this->teamName + ":"; this->paras = true; if (this->rcvBro) { if (toRcv.compare(0, toCmp.length(), toCmp) == 0) { std::string ids = toRcv.substr(toCmp.length()); std::vector<std::string> t = this->getIDVector(ids); this->toFollow = ""; this->resCounter = 0; if (this->idIsInVector(t) == true) { chooseDirectionToJoin(); this->toJoin = true; this->onFarm = false; this->waitingMore = false; this->paras = false; } else { this->toJoin = false; } } else if (toRcv.compare(0, toCmp2.length(), toCmp2) == 0) { std::string fol = toRcv.substr(toCmp2.length()); if (this->enoughFollowers() == false && this->idIsNotPresent(fol)) { this->followers.push_back(fol); if (this->enoughFollowers() == true) this->nextCmd = GoForIncante; else this->nextCmd = RFI; } } else if (toRcv.compare(0, toCmp3.length(), toCmp3) == 0 && this->toJoin == false && this->followers.size() == 0) { this->toFollow = toRcv.substr(toCmp3.length()); this->getMyNum(this->toFollow); this->nextCmd = ResRFI; this->resCounter = 0; this->toJoin = false; this->paras = false; } } } int Client::doSomeClean() { std::string s(this->final_msg.c_str()); std::string del = "\n"; size_t pos = 0; std::string token; std::string t; std::vector<std::string> vec; while ((pos = s.find(del)) != std::string::npos) { token = s.substr(0, pos); vec.push_back(token); this->final_msg = token; s.erase(0, pos + del.length()); } vec.push_back(s); if (vec.size() > 1) { for (std::vector<std::string>::iterator it = vec.begin() ; it != vec.end() ; ++it) this->final_msg = (*it); this->chooseNextCmd(); return 1; } return 0; } void Client::initNextCmd() { this->paras = false; if (this->toFollow != "" && this->followers.size() != 0) this->resetStat(); } void Client::getRetQueue(CmdType & next) { if (this->toRcv.size() > 0 && this->paras == false) { if (this->toRcv.size() > 1) this->paras = true; next = this->toRcv.front(); this->toRcv.pop(); } } void Client::interChange() { if (this->final_msg.compare(0, 13, "niveau actuel") == 0) { this->resetStat(); this->lvl += 1; } else if (this->final_msg.compare(0, 2, "ko") == 0) this->resetStat(); } void Client::waitingIncantationFunction(CmdType & next) { if (next == Voir && this->waitingMore == true) { this->setSaw(this->final_msg); this->nextCmd = None; } } void Client::actingFarmingRoutine() { if (this->final_msg.compare(0, 2, "ok") != 0 && this->final_msg.compare(0, 2, "ko") != 0) this->setSaw(this->final_msg); if (this->onFarm) this->nextCmd = Prendre; else this->nextCmd = PrendreMid; } void Client::routineFunction(int & p) { if (p % 9 == 0 && p > 18) this->nextCmd = Inventaire; else if (p % 11 == 0) this->nextCmd = Droite; else if (p % 2 == 0) this->nextCmd = Voir; else this->nextCmd = Avance; p += 1; } void Client::chooseNextCmd() { CmdType next = None; static int p = 1; if (p != 1) if (this->doSomeClean() == 1) return ; this->initNextCmd(); if (this->final_msg.length() > 11 && this->final_msg.compare(0, 8, "message ") == 0) { this->treatBroadcastRcv(); return ; } this->getRetQueue(next); this->interChange(); if (this->toJoin == true) { if (this->nextCmd != Avance && this->nextCmd != Droite && this->nextCmd != Gauche) this->nextCmd = None; return ; } if (this->nextCmd == Incantation) return ; if (next == Inventaire) { this->setInventory(this->final_msg); if (this->inventaireChecker() == true) { this->rdxForIncantation(); return ; } } this->waitingIncantationFunction(next); if (this->waitingMore == true) { this->waitingForMoreClient(); return ; } if (next == Voir) this->actingFarmingRoutine(); else if (this->onFarm) this->routineFunction(p); else this->nextCmd = None; } void Client::read_complete(const boost::system::error_code & error, size_t bytes_transferred) { if (!error) { this->read_msg[bytes_transferred] = 0; this->final_msg += std::string(this->read_msg); this->msg_len += bytes_transferred; if (this->read_msg[bytes_transferred - 1] == 10) { this->final_msg[this->msg_len - 1] = 0; this->chooseNextCmd(); this->final_msg = ""; this->msg_len = 0; if (this->paras == false) this->can_write = true; } this->read_start(); } else { this->do_close(); this->run = false; } } void Client::do_write(const char msg) { bool write_in_progress = !(this->write_msgs.empty()); this->write_msgs.push_back(msg); if (!write_in_progress) write_start(); } void Client::write_start() { boost::asio::async_write(this->socket, boost::asio::buffer(&this->write_msgs.front(), 1), boost::bind(&Client::write_complete, this, boost::asio::placeholders::error)); } void Client::write_complete(const boost::system::error_code& error) { if (!error) { this->write_msgs.pop_front(); if (!(this->write_msgs.empty())) this->write_start(); } else this->do_close(); } void Client::do_close() { this->socket.close(); } void Client::setKey(const std::string & stringKey) { for(std::string::const_iterator it = stringKey.begin() ; it != stringKey.end() ; ++it) this->key += *it; } unsigned int Client::getKey() const { return this->key; } std::vector<Inventory *> & Client::getLastSaw() { return this->lastSaw; } void Client::setSaw(std::string & s) { std::vector<std::string> tab; size_t pos = 0; std::string token; while ((pos = s.find(",")) != std::string::npos) { token = s.substr(0, pos); if (token[0] == '{' || token[0] == ' ') tab.push_back(token.substr(1, token.length() - 1)); else tab.push_back(token); s.erase(0, pos + 1); } if (s[0] == '{' || s[0] == ' ') tab.push_back(s.substr(1, s.length() - 1)); else tab.push_back(s); for (std::vector<Inventory *>::iterator it = this->lastSaw.begin() ; it != this->lastSaw.end() ; ++it) delete (*it); this->lastSaw.clear(); for (std::vector<std::string>::iterator it = tab.begin() ; it != tab.end() ; ) { this->lastSaw.push_back(new Inventory((*it))); ++it; } } void Client::setLead(bool l) { this->lead = l; } bool Client::getLead() const { return this->lead; } char Client::getLastDirBroad() const { return this->lastDirBroad; } void Client::setLastDirBroad(char d) { this->lastDirBroad = d; } void Client::setLvl(unsigned int l) { this->lvl = l; } void Client::setInventory(std::string & s) { this->lastInventory.reset(); this->lastInventory.addInv(s); } Inventory Client::getInventory() const { return this->lastInventory; } unsigned int Client::getLvl() const { return this->lvl; } const std::string & Client::getTeamName() const { return this->teamName; } #include <stdlib.h> void Client::setID() { struct timeval time; gettimeofday(&time, NULL); srand(time.tv_usec); unsigned int nb = rand() % 8999 + 1000; std::stringstream ss; ss << nb; this->id = ss.str(); } const std::string & Client::getID() const { return this->id; } const std::string & Client::getToFollow() const { return this->toFollow; } std::vector<std::string> Client::getFollowers() const { return this->followers; } void Client::resetStat() { this->final_msg = ""; this->onFarm = true; this->toJoin = false; this->followers.clear(); this->toFollow = ""; this->rcvBro = true; this->waitingMore = false; this->paras = false; this->resCounter = 0; } std::vector<std::string> Client::getIDVector(std::string & s) { std::vector<std::string> t; size_t pos = 0; std::string token; while ((pos = s.find(":")) != std::string::npos) { token = s.substr(0, pos); t.push_back(token); s.erase(0, pos + 1); } return t; } bool Client::idIsInVector(std::vector<std::string> t) const { unsigned int i = 0; while (i < t.size()) { if (t[i].substr(0, 4).compare(this->id.substr(0, 4)) == 0) return true; i += 1; } return false; } bool Client::idIsNotPresent(std::string & s) const { unsigned int i = 0; while (i < this->followers.size()) { if (this->followers[i].substr(0, 4).compare(s.substr(0, 4)) == 0) return false; i += 1; } return true; } void Client::setToFollow(const std::string & s) { this->toFollow = s; } void Client::clearFollowers() { this->followers.clear(); } <file_sep>#include "Color.hpp" /* map */ sf::Color Color::Case = sf::Color(150 , 40 , 27 , 255); sf::Color Color::CaseFocus = sf::Color(130 , 90 , 44 , 255); /* pierres */ sf::Color Color::Nourriture = sf::Color(207 , 0 , 15 , 255); sf::Color Color::Linemate = sf::Color(102 , 51 , 153 , 255); sf::Color Color::Deraumere = sf::Color(246 , 36 , 89 , 255); sf::Color Color::Sibur = sf::Color(37 , 167 , 240 , 255); sf::Color Color::Mendiane = sf::Color(38 , 166 , 91 , 255); sf::Color Color::Phiras = sf::Color(248 , 148 , 6 , 255); sf::Color Color::Thystame = sf::Color(244 , 108 , 63 , 255); /* broadCast */ sf::Color Color::BroadcastInColor = sf::Color( 52 , 73 , 94 ); sf::Color Color::BroadcastOutLineColor = sf::Color( 250, 150 , 100 ); /* time */ sf::Color Color::PanelTime = sf::Color( 255,255,255,240); sf::Color Color::Time = sf::Color( 0,0,0,240); sf::Color Color::PanelAU = sf::Color( 0 , 177 , 106 , 130); sf::Color Color::PanelAD = sf::Color( 242 , 38 , 19 , 130); sf::Color Color::PanelAU_ON = sf::Color( 0 , 177 , 106 , 255); sf::Color Color::PanelAD_ON = sf::Color( 242 , 38 , 19 , 255); /* teams */ sf::Color Color::PanelTeam = sf::Color( 238 , 238 , 238 , 130 ); sf::Color Color::PanelTeamArrowOn = sf::Color( 34 , 167 , 240);<file_sep>/* ** team.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:49:46 2014 courtu_r ** Last update Sun Jul 13 15:49:46 2014 courtu_r */ #include <string.h> #include <stdlib.h> #include "zappy.h" t_team *is_in_list_of_team(t_list *list, const char *name) { t_team *team; t_node *loop; if (list->type != TEAM) return (NULL); loop = list->head; while (loop) { team = ((t_team*)loop->data); if (strcmp(name, team->name) == 0) return (team); loop = loop->next; } return (NULL); } t_clientIA *is_in_list_of_ia(t_list *list, t_team *team) { t_clientIA *client; t_node *loop; if (list->type != IA) return (NULL); loop = list->head; while (loop) { client = ((t_clientIA*)loop->data); if ((client->socket == -1) && (team == client->team)) return (client); loop = loop->next; } return (NULL); } <file_sep>#include "Settings.hpp" /* legend */ unsigned int Settings::SizeTextLegendRessources = 13; unsigned int Settings::SizeTextLegendPlayer = 13; /* broadcast */ unsigned int Settings::SizeBroadCast = 125; unsigned int Settings::SpeedBroadcast = 3; /* incantation */ unsigned int Settings::RotationMaxIncantation = 360; unsigned int Settings::SpeedIncantation = 3; /* roots */ unsigned int Settings::AntiAliasing = 16; unsigned int Settings::WindowSizeX = 1280; unsigned int Settings::WindowSizeY = 720; unsigned int Settings::FPS = 60; std::string Settings::WindowTitle = "Zappy"; /* panel time */ unsigned int Settings::BeginPanelTimeY = 225; unsigned int Settings::TimePitch = 10; /* panel teams */ unsigned int Settings::PanelTeamX = 200; unsigned int Settings::PanelSizeY = 100; unsigned int Settings::PanelTeamSizeBlocPlayer = 70; unsigned int Settings::PanelTeamPlayerDisplayed = 3; /* map */ unsigned int Settings::CoeffRessources = 8;<file_sep>/* ** get_client_ia.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/clientGUI ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:53:20 2014 ** Last update Sun Jul 13 15:53:22 2014 */ #include <stdlib.h> #include "zappy.h" t_clientIA *get_clientIA_by_index(t_list *list, unsigned int num) { t_node *loop; t_clientIA *ret; if (list->type != IA) return (NULL); loop = list->head; while (loop) { ret = ((t_clientIA*)loop->data); if (((unsigned int)ret->socket) == num) return (ret); loop = loop->next; } return (NULL); } <file_sep>#ifndef CASE_HPP__ # define CASE_HPP__ #include <SFML/Graphics.hpp> #include <mutex> #include "Color.hpp" enum eRessources { Nourriture = 0, Linemate, Deraumere, Sibur, Mendiane, Phiras, Thystame, }; class Player; class Case { public: Case(unsigned int = 0, unsigned int = 0); ~Case(); public: unsigned int getX() const; unsigned int getY() const; sf::RectangleShape getShape() const; void setX(unsigned int); void setY(unsigned int); void focusShape(); void unFocusShape(); void setIncantParam(bool, unsigned int, bool); unsigned int getIncLvl() const; bool getIncSucceed() const; bool getIncantationIsSet() const; void setRessources(eRessources, unsigned int); std::map<eRessources, unsigned int> & getRessources(); void updateIncLevel(); unsigned int getIncRotation() const; private: bool _incantation; bool _incSucceed; unsigned int _incLvl; unsigned int m_x; unsigned int m_y; sf::RectangleShape m_shape; std::map<eRessources, unsigned int> _ressources; std::mutex m_mutex; }; #endif /* EOF - Case.hpp */ <file_sep>/* ** write_ia.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/network ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:58:49 2014 ** Last update dim. juil. 13 20:04:35 2014 <NAME> */ #include "zappy.h" void write_incantation(t_zappy *s, t_clientIA *client) { char *str; if (FD_ISSET(client->socket, &(s->writesd))) { while ((str = try_get_cmd(client->buff_write))) { send_buffer(client, str); free(str); } } if (((client->lastAction < get_tick(0.0f)))) { are_requirements_met(s, client, false); client->call_incantation = false; } } void write_buffer_ia(t_clientIA *client, char **buff) { send_buffer(client, (*buff)); free(*buff); (*buff) = NULL; } void write_cmd(t_clientIA *client) { char *str; while ((str = try_get_cmd(client->buff_write))) { send_buffer(client, str); free(str); } client->write = false; } void write_level_up(t_zappy *s, t_clientIA *client) { if (FD_ISSET(client->socket, &(s->writesd))) { send_buffer(client, client->incantation); free(client->incantation); client->incantation = NULL; } } void do_fd_sets(t_zappy *s, t_clientGUI *client) { if ((client->listWrite->length > 0) || (client->writeConn) || (client->write) || (client->error)) FD_SET(client->socket, &(s->writesd)); FD_SET(client->socket, &(s->readsd)); FD_SET(client->socket, &(s->exceptsd)); } <file_sep>/* ** free_va_arg.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/utils ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 16:07:48 2014 ** Last update Sun Jul 13 16:07:49 2014 */ #include <stdlib.h> #include <stdarg.h> void *free_va_arg(int nbparam, ...) { int i; void *tmp; va_list ap; i = -1; va_start(ap, nbparam); while (++i < nbparam) { tmp = va_arg(ap, void*); free(tmp); } va_end(ap); return (NULL); } <file_sep>#ifndef SETTINGS_HPP__ # define SETTINGS_HPP__ #include <string> class Settings { public: static unsigned int SizeTextLegendRessources; static unsigned int SizeTextLegendPlayer; /* broadcast */ static unsigned int SizeBroadCast; static unsigned int SpeedBroadcast; /* incantation */ static unsigned int RotationMaxIncantation; static unsigned int SpeedIncantation; /* root */ static unsigned int AntiAliasing; static unsigned int WindowSizeX; static unsigned int WindowSizeY; static unsigned int FPS; static std::string WindowTitle; /* panel time */ static unsigned int BeginPanelTimeY; static unsigned int TimePitch; /* panel teams */ static unsigned int PanelTeamX; static unsigned int PanelSizeY; static unsigned int PanelTeamSizeBlocPlayer; static unsigned int PanelTeamPlayerDisplayed; /* map */ static unsigned int CoeffRessources; }; #endif // EOF - Settings.hpp<file_sep>#ifndef _PARSE_H_ # define _PARSE_H_ #include <stdbool.h> #include "zappy.h" #define KARSET_OPT "pxynct" #define NB_OPT (strlen(KARSET_OPT)) #define FLAGS_P 1 #define FLAGS_X 2 #define FLAGS_Y 4 #define FLAGS_N 8 #define FLAGS_C 16 #define FLAGS_T 32 int init_server(t_zappy *server); int fill_opt(int argc, char **argv, t_zappy *server); bool parse_port(t_zappy *, int, char **, int *); bool parse_width(t_zappy *, int, char **, int *); bool parse_height(t_zappy *, int, char **, int *); bool parse_name_team(t_zappy *, int, char **, int *); bool parse_nb_clients(t_zappy *, int, char **, int *); bool parse_delay(t_zappy *, int, char **, int*); #endif <file_sep> #ifndef IA_HPP_ # define IA_HPP_ #include <signal.h> #include "Client.hpp" #include "EnumCmd.hpp" class IA { private: Client * c; public: IA(Client *, const std::string & name); const std::string & teamName; void choseCmdToSend() const; const std::string & getTeamName() const; private: void sendAvance(const std::string &) const; void sendDroite(const std::string &) const; void sendGauche(const std::string &) const; void sendVoir(const std::string &) const; void sendInventaire(const std::string &) const; void sendPrendre(const std::string &) const; void sendPose(const std::string &) const; void sendExpulse(const std::string &) const; void sendBroadcast(const std::string &) const; void sendIncantation(const std::string &) const; void sendFork(const std::string &) const; void sendConnectNbr(const std::string &) const; void sendNeedFood(const std::string &) const; void sendGoForIncante(const std::string &) const; void sendPrendreMid(const std::string &) const; void sendPoseNeeded(const std::string &) const; void sendMoveIt(const std::string &) const; void sendRFI(const std::string &) const; void sendResRFI(const std::string &) const; private: const std::string allTake() const; const std::string retFood() const; const std::string retLinemate() const; const std::string retSibur() const; const std::string retDeraumere() const; const std::string retPhiras() const; const std::string retThystame() const; const std::string retMendiane() const; void sendPoseNeededLvl1() const; void sendPoseNeededLvl2() const; void sendPoseNeededLvl3() const; void sendPoseNeededLvl4() const; void sendPoseNeededLvl5() const; void sendPoseNeededLvl6() const; void sendPoseNeededLvl7() const; public: bool getLead() const; void setLead(bool); unsigned int getLvl() const; void setLvl(unsigned int); private: bool lead; unsigned int lvl; }; #endif <file_sep>/* ** write_gui.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/network ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:59:48 2014 ** Last update dim. juil. 13 19:54:20 2014 <NAME> */ #include <stdlib.h> #include <string.h> #include "zappy.h" #include "routines.h" static void last_write(t_zappy *s, t_clientGUI *client); void write_gui(t_zappy *s, t_clientGUI *client) { ssize_t nbwrites; if (client->writeConn && FD_ISSET(client->socket, &(s->writesd))) { nbwrites = write(client->socket, client->writeConn, strlen(client->writeConn)); if (nbwrites != ((ssize_t)strlen(client->writeConn))) fprintf(stderr, "send() failed.\n"); free(client->writeConn); client->writeConn = NULL; } if (client->listWrite->length > 0 && FD_ISSET(client->socket, &(s->writesd))) { iter_list_ret_next(client->listWrite, client->socket, routine_write_answerGUI); } last_write(s, client); } static void last_write(t_zappy *s, t_clientGUI *client) { char *str; ssize_t nbwrites; if (client->write && FD_ISSET(client->socket, &(s->writesd))) { while ((str = try_get_cmd(client->buff_write))) { nbwrites = write(client->socket, str, strlen(str)); if (nbwrites != ((ssize_t)strlen(str))) fprintf(stderr, "send() failed.\n"); free(str); } client->write = false; } } t_node *routine_write_answerGUI(t_list *list, t_node *node, t_type type, int *ret) { char *str; ssize_t nbwrites; t_gui_answer *answer; if (type != ANSWER) return (NULL); if (!(answer = ((t_gui_answer*)node->data))) return (NULL); if (answer->tick < ((unsigned int)get_tick(0))) { str = answer->msg; nbwrites = write((*ret), ((char*)str), strlen(str)); if (nbwrites != ((ssize_t)strlen(str))) fprintf(stderr, "send() failed.\n"); return (rm_node(list, node)); } else return (node->next); } void write_error_ia(t_clientIA *client, const char *error) { send_buffer(client, error); client->error = false; } <file_sep>#include <stdlib.h> #include "parse.h" #include "map.h" int main(int argc, char *argv[]) { t_zappy server; int ret; server.game = true; release_memory(&server, 0); if (init_server(&server)) return (release_memory(NULL, 1)); if (fill_opt(argc, argv, &server)) return (release_memory(NULL, 2)); if (!(server.map = init_map(server.map, server.width, server.height))) return (release_memory(NULL, 3)); if (!create_socket_TCP(&server)) return (release_memory(NULL, 4)); if (init_signal(&server)) return (release_memory(NULL, 5)); set_connect_nbr(&server); display_info(&server); ret = schedule(&server); release_memory(NULL, 42); return (ret); } <file_sep> #ifndef CLIENT_HPP_ # define CLIENT_HPP_ #include <queue> #include <deque> #include <iostream> #include <boost/bind.hpp> #include <boost/asio.hpp> #include <boost/thread.hpp> #include <string> #include "EnumCmd.hpp" #include "Inventory.hpp" using boost::asio::ip::tcp; class Client { public: enum { max_read_length = 4096 }; Client(boost::asio::io_service &, tcp::resolver::iterator, char *); ~Client(); int doSomeClean(); char getLastDirBroad() const; bool canWrite() const; bool getRun() const; bool getLead() const; void waitingIncantationFunction(CmdType &); void actingFarmingRoutine(); void routineFunction(int &); void write_string(const std::string &); void write_char(const char msg); void close(); void setCanWrite(bool); void setNextCmd(CmdType); void setKey(const std::string &); void setSaw(std::string &); void setLead(bool); void setLastDirBroad(char); void setLvl(unsigned int); void setInventory(std::string &); void waitingForMoreClient(); void treatBroadcastRcv(); void chooseDirectionToJoin(); void setID(); void getMyNum(std::string &); void resetStat(); void initNextCmd(); void getRetQueue(CmdType &); void interChange(); void setToFollow(const std::string &); void clearFollowers(); bool idIsInVector(std::vector<std::string>) const; bool idIsNotPresent(std::string &) const; CmdType getNextCmd() const; unsigned int getKey() const; unsigned int getLvl() const; Inventory getInventory() const; Inventory lastInventory; const std::string & getID() const; std::queue<CmdType> toRcv; std::vector<Inventory *> lastSaw; std::vector<Inventory *> & getLastSaw(); std::vector<std::string> getFollowers() const; std::vector<std::string> getIDVector(std::string &); const std::string & getTeamName() const; const std::string & getToFollow() const; public: bool inventaireChecker() const; bool enoughFollowers() const; void rdxForIncantation(); private: bool inventaireCheckerLvl1() const; bool inventaireCheckerLvl2() const; bool inventaireCheckerLvl3() const; bool inventaireCheckerLvl4() const; bool inventaireCheckerLvl5() const; bool inventaireCheckerLvl6() const; bool inventaireCheckerLvl7() const; bool enFolloLvl1() const; bool enFolloLvl2() const; bool enFolloLvl3() const; bool enFolloLvl4() const; bool enFolloLvl5() const; bool enFolloLvl6() const; bool enFolloLvl7() const; void rdxForIncantationLvl1(); void rdxForIncantationLvl2(); void rdxForIncantationLvl3(); void rdxForIncantationLvl4(); void rdxForIncantationLvl5(); void rdxForIncantationLvl6(); void rdxForIncantationLvl7(); private: void chooseNextCmd(); void connect_start(tcp::resolver::iterator); void connect_complete(const boost::system::error_code &, tcp::resolver::iterator); void read_start(); void read_complete(const boost::system::error_code &, size_t); void do_write(const char msg); void write_start(); void write_complete(const boost::system::error_code &); void do_close(); private: boost::asio::io_service& io_service; tcp::socket socket; char read_msg[max_read_length]; std::deque<char> write_msgs; bool can_write; CmdType nextCmd; std::string final_msg; std::string save_final_msg; std::string teamName; std::string toFollow; size_t msg_len; bool run; unsigned int key; bool lead; bool onFarm; char lastDirBroad; int lvl; bool waitingMore; bool paras; bool toJoin; bool rcvBro; std::vector<std::string> followers; std::string id; unsigned int resCounter; }; #endif <file_sep>/* ** foodSpawn.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/foodSpawn ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 16:16:29 2014 ** Last update Sun Jul 13 16:16:34 2014 */ #include "zappy.h" void new_client_spawn_food(t_zappy * z) { unsigned int nb_food; unsigned int i; unsigned int x; unsigned int y; char *str; i = -1; nb_food = (z->map->width * z->map->height / 2) + 1; while (++i < nb_food) { x = random() % z->map->width; y = random() % z->map->height; z->map->map[y][x]->inventory->content[Food] += 126; z->currentRessource = z->map->map[y][x]; if (!(str = tograph_bct(z))) return ; if (!put_in_list(z->listWrite, create_gui_ans(str, 0.0f))) return ; } } void timer_spawn_food(t_zappy * z) { unsigned int nb_food; unsigned int i; unsigned int x; unsigned int y; i = -1; nb_food = (z->map->width * z->map->height / 24) + 1; while (++i < nb_food) { x = random() % z->map->width; y = random() % z->map->height; z->map->map[y][x]->inventory->content[Food] += 126; } } <file_sep>/* ** signals.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:49:53 2014 courtu_r ** Last update dim. juil. 13 21:42:59 2014 <NAME> */ #include <signal.h> #include <stdio.h> #include <stdlib.h> #include "zappy.h" static void handle_signal(int sig) { release_memory(NULL, 0); exit(sig); } static void handle_trick(int sig) { (void)sig; } int init_signal(t_zappy *server) { (void)server; if (signal(SIGINT, handle_signal) == SIG_ERR) { fprintf(stderr, "signal(SIGINT) failed.\n"); return (1); } if (signal(SIGQUIT, handle_signal) == SIG_ERR) { fprintf(stderr, "signal(SIGQUIT) failed.\n"); return (1); } if (signal(SIGPIPE, handle_trick) == SIG_ERR) { fprintf(stderr, "signal(SIGPIPE) failed.\n"); return (1); } return (0); } <file_sep>#include <iostream> #include <string> #include <sstream> #include "View.hpp" #include "CollisionEngine.hpp" #include "TextureManager.hpp" #include "Settings.hpp" #include "CollisionEngine.hpp" View::View(sf::RenderWindow & win, Zappy & zappy, Socket & sock) : m_zappy(zappy), m_window(win), currentView(win.getView()), gameView(m_window.getView()), focusedBloc(0), focusedPlayer(0), m_font(TextureManager::Instance().getFont()), m_sock(sock), bg(TextureManager::Instance().getTexture(BACKGROUND)), circleShape(15), panelLeft(zappy, win), panelRight(zappy, win, sock) { // bg.setTexture( mapFptr[Nourriture] = &View::drawNourriture; mapFptr[Linemate] = &View::drawLinemate; mapFptr[Deraumere] = &View::drawDeraumere; mapFptr[Sibur] = &View::drawSibur; mapFptr[Mendiane] = &View::drawMendiane; mapFptr[Phiras] = &View::drawPhiras; mapFptr[Thystame] = &View::drawThystame; } View::~View() {} void View::display() { while (m_window.isOpen()) { _events(); /* clear the window */ m_window.clear(); /* display elements*/ _displayBackground(); m_window.setView(gameView); _display(); m_window.setView(m_window.getDefaultView()); panelRight.display(mouseEvent); panelLeft.display(mouseEvent, &focusedPlayer); _displayInfoCase(); _displayInfoPlayer(); if (m_zappy.getEndGame()) _displayEndGame(); m_window.display(); mouseEvent.reset(); } } void View::_display() { _displayMap(); _displayPlayers(); } void View::_displayEndGame() { m_window.setView(m_window.getDefaultView()); sf::Text text; sf::Vector2u windowSize = m_window.getSize(); const std::string & teamName = m_zappy.getWinnerTeam(); std::stringstream ss; ss << "<NAME> : " << teamName; text.setFont(TextureManager::Instance().getFont()); text.setCharacterSize(40); text.setPosition(windowSize.x / 2 - (ss.str().size() / 2) * 20,20); text.setColor(sf::Color::Black); text.setString(ss.str()); m_window.draw(text); m_window.setView(gameView); } void View::_events() { sf::Event event; mouseClicked = false; while (m_window.pollEvent(event)) { /* cross */ if (event.type == sf::Event::Closed) m_window.close(); /* click */ if (event.type == sf::Event::MouseButtonPressed) mouseEvent.update(m_window, event); } /* arrows */ if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) _moveView(-COEFFICIENT_MOVE,0); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) _moveView(COEFFICIENT_MOVE,0); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) _moveView(0,-COEFFICIENT_MOVE); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) _moveView(0,COEFFICIENT_MOVE); /* zoom */ if (sf::Keyboard::isKeyPressed(sf::Keyboard::Add)) _zoomView(1.03); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Subtract)) _zoomView(0.97); } void View::_moveView(int x, int y) { gameView.move(x,y); } void View::_zoomView(float x) { gameView.zoom(x); } void View::_rotateView(float x) { gameView.setRotation(gameView.getRotation() + x); } bool View::_detectCollision(sf::FloatRect boundingBox, int x, int y) { sf::Vector2f point(x, y); if (boundingBox.contains(point)) { return true; } return false; } void View::_displayBackground() { m_window.setView(m_window.getDefaultView()); m_window.draw(bg); } template <typename T> bool View::onScreen(T & tile, sf::View & gameView) { sf::FloatRect boundingBox = tile.getGlobalBounds(); sf::FloatRect viewPort; viewPort.left = gameView.getCenter().x - gameView.getSize().x/2.f; viewPort.top = gameView.getCenter().y - gameView.getSize().y/2.f; viewPort.width = gameView.getSize().x; viewPort.height = gameView.getSize().y; if (viewPort.intersects(boundingBox)) return true; return false; } void View::_displayIncantation(Case * i, std::vector<sf::Sprite> & v) { if (i->getIncantationIsSet()) { sf::Sprite spriteSun; spriteSun.setTexture(TextureManager::Instance().getTexture(SUN_SMALL)); spriteSun.setPosition(sf::Vector2f(i->getShape().getPosition().x + 12, i->getShape().getPosition().y + 12)); spriteSun.setOrigin(sf::Vector2f( spriteSun.getOrigin().x + 25, spriteSun.getOrigin().y + 25)); spriteSun.rotate(i->getIncRotation()); i->updateIncLevel(); v.push_back(spriteSun); } } void View::_displayMapEvents(Case * i) { if (mouseEvent.isMouseClicked() && CollisionEngine::pointVSshape( m_window, i->getShape(), mouseEvent.getX(), mouseEvent.getY())) { if (focusedBloc) focusedBloc->unFocusShape(); focusedBloc = i; i->focusShape(); } } void View::_displayMap() { Map & zappyMap = m_zappy.getMap(); const std::vector<Case *> & zappyMapDetail = zappyMap.getVectCase(); std::vector<sf::Sprite> v; for (auto &i : zappyMapDetail) { const sf::RectangleShape & a = i->getShape(); if (!onScreen(a, gameView)) continue; _displayMapEvents(i); _displayIncantation(i, v); m_window.draw(i->getShape()); _drawRessoucesOfCase(*i); } for (auto &s : v) m_window.draw(s); } void View::_drawRessoucesOfCase(Case & obj) { sf::CircleShape shape(2); sf::Vector2f posShape = obj.getShape().getPosition(); posShape.x += 2; posShape.y += 2; for ( auto &i : obj.getRessources()) (i.second) ? (this->*mapFptr[i.first])(shape, posShape) : (void)i.second; } void View::_displayInfoPlayer() { if (!focusedPlayer) return; _displayPanelPlayer(); } void View::_displayPanelPlayer() { sf::View currentView = m_window.getView(); sf::View defaultView = m_window.getDefaultView(); sf::Vector2u windowSize = m_window.getSize(); std::stringstream ss; sf::Sprite sprite; sprite.setTexture( TextureManager::Instance().getTexture(BIG_PLAYER) ); sprite.setPosition( sf::Vector2f(windowSize.x - 450, windowSize.y - PANELSIZE_Y)); ss << "id\t:\t" << focusedPlayer->getId() << "\n"; ss << "lvl\t:\t" << focusedPlayer->getLevel() << "\n"; ss << "x/y\t:\t" << focusedPlayer->getX() << "/" << focusedPlayer->getY() << "\n"; ss << "action:\t:\t" << focusedPlayer->getStringAction() << std::endl; ss << "broadcast message:\t" << focusedPlayer->getBroadCastMsg() << "\n"; m_window.setView(defaultView); /* affichage */ sf::Text text; text.setFont(m_font); text.setCharacterSize(Settings::SizeTextLegendPlayer); text.setColor(sf::Color(34,49,63)); text.setPosition(sf::Vector2f(windowSize.x - 380,windowSize.y - PANELSIZE_Y + 5)); text.setString(ss.str()); m_window.draw(text); m_window.draw(sprite); /* inventory */ sf::CircleShape circle(15); std::map<eRessources, unsigned int> const inventory = focusedPlayer->getRessource(); /* circle settings */ ss.str(""); text.setCharacterSize(18); ss << inventory.at(Linemate); text.setString(ss.str()); circle.setPosition(sf::Vector2f(windowSize.x - 200, windowSize.y - PANELSIZE_Y + 10)); circle.setFillColor(Color::Linemate); text.setPosition(sf::Vector2f(windowSize.x - 190, windowSize.y - PANELSIZE_Y + 12)); m_window.draw(circle); m_window.draw(text); ss.str(""); ss << inventory.at(Deraumere); text.setString(ss.str()); circle.setPosition(sf::Vector2f(windowSize.x - 170, windowSize.y - PANELSIZE_Y + 10)); circle.setFillColor(Color::Deraumere); text.setPosition(sf::Vector2f(windowSize.x - 160, windowSize.y - PANELSIZE_Y + 12)); m_window.draw(circle); m_window.draw(text); ss.str(""); ss << inventory.at(Sibur); text.setString(ss.str()); circle.setPosition(sf::Vector2f(windowSize.x - 140, windowSize.y - PANELSIZE_Y + 10)); circle.setFillColor(Color::Sibur); text.setPosition(sf::Vector2f(windowSize.x - 130, windowSize.y - PANELSIZE_Y + 12)); m_window.draw(circle); m_window.draw(text); ss.str(""); ss << inventory.at(Phiras); text.setString(ss.str()); circle.setPosition(sf::Vector2f(windowSize.x - 200, windowSize.y - PANELSIZE_Y + 40)); circle.setFillColor(Color::Phiras); text.setPosition(sf::Vector2f(windowSize.x - 190, windowSize.y - PANELSIZE_Y + 42)); m_window.draw(circle); m_window.draw(text); ss.str(""); ss << inventory.at(Thystame); text.setString(ss.str()); circle.setPosition(sf::Vector2f(windowSize.x - 170, windowSize.y - PANELSIZE_Y + 40)); circle.setFillColor(Color::Thystame); text.setPosition(sf::Vector2f(windowSize.x - 160, windowSize.y - PANELSIZE_Y + 42)); m_window.draw(circle); m_window.draw(text); ss.str(""); ss << inventory.at(Mendiane); text.setString(ss.str()); circle.setPosition(sf::Vector2f(windowSize.x - 140, windowSize.y - PANELSIZE_Y + 40)); circle.setFillColor(Color::Mendiane); text.setPosition(sf::Vector2f(windowSize.x - 130, windowSize.y - PANELSIZE_Y + 42)); m_window.draw(circle); m_window.draw(text); m_window.setView(currentView); } void View::_displayInfoCase() { sf::RectangleShape panelShape; m_window.setView(m_window.getDefaultView()); sf::Vector2u windowSize = m_window.getSize(); panelShape.setFillColor(sf::Color(238,238,238,150)); panelShape.setSize(sf::Vector2f(windowSize.x, PANELSIZE_Y)); panelShape.setPosition(sf::Vector2f(0,windowSize.y - PANELSIZE_Y)); m_window.draw(panelShape); m_window.setView(gameView); if (!focusedBloc) return; _displayPanelCase(); } void View::_displayPanelCase() { sf::View currentView = m_window.getView(); sf::View defaultView = m_window.getDefaultView(); sf::Vector2u windowSize = m_window.getSize(); sf::Sprite caseSprite; sf::CircleShape circleShape(15); std::map<eRessources, unsigned int> & ressourcesOfBloc = focusedBloc->getRessources(); caseSprite.setTexture(TextureManager::Instance().getTexture(BIG_CASE) ); caseSprite.setPosition( sf::Vector2f(25, windowSize.y - PANELSIZE_Y + 10)); m_window.setView(defaultView); /* informations */ /* a passer en tpf */ _displayPanelCaseNourriture(windowSize, ressourcesOfBloc[Nourriture]); _displayPanelCaseLinemate(windowSize, ressourcesOfBloc[Linemate]); _displayPanelCaseDeraumere(windowSize, ressourcesOfBloc[Deraumere]); _displayPanelCaseSibur(windowSize, ressourcesOfBloc[Sibur]); _displayPanelCaseMendiane(windowSize, ressourcesOfBloc[Mendiane]); _displayPanelCasePhiras(windowSize, ressourcesOfBloc[Phiras]); _displayPanelCaseThystame(windowSize, ressourcesOfBloc[Thystame]); m_window.draw(caseSprite); m_window.setView(currentView); } void View::_displayPlayers() { m_zappy.lock(); const std::list<Team *> teams = m_zappy.getTeam(); sf::Sprite sprite; sf::Sprite eggSprite; sprite.setTexture( TextureManager::Instance().getTexture(PLAYER_SPRITE) ); for (auto &t : teams) { const std::list<Egg*> & eggsOfTeam = t->getEggs(); for (auto &e : eggsOfTeam) { Case * objCase = m_zappy.getMap().atCoords(e->getX(), e->getY()); if (e->getStat() == Eclot) eggSprite.setTexture( TextureManager::Instance().getTexture(EGG_SMALL_CRACK) ); else eggSprite.setTexture( TextureManager::Instance().getTexture(EGG_SMALL) ); sprite.setTexture( TextureManager::Instance().getTexture(PLAYER_SPRITE) ); eggSprite.setPosition(sf::Vector2f(objCase->getShape().getPosition().x, objCase->getShape().getPosition().y - 5)); m_window.draw(eggSprite); } const std::list<Player *> & playersOfTeam = t->getPlayers(); for (auto &i : playersOfTeam) { Case * objCase = m_zappy.getMap().atCoords(i->getX(), i->getY()); sf::RectangleShape shapeRect = objCase->getShape(); sf::Vector2f positionCase = shapeRect.getPosition(); sprite.setPosition(sf::Vector2f(positionCase.x, positionCase.y -30)); sprite.setTextureRect(sf::IntRect(0,(i->getOrientation() - 1) * 48,31,48)); if (mouseEvent.isMouseClicked() && CollisionEngine::pointVSsprite( m_window, sprite, mouseEvent.getX(), mouseEvent.getY())) { focusedPlayer = i; } if (i->getCurrentAction() == Broadcast) { unsigned int bcLvl = i->getBroadCastLevel(); unsigned int opacity = bcLvl * ((255 / Settings::SizeBroadCast + 1) + 1); if (opacity > 255) opacity = 255; sf::CircleShape broadCastShape(bcLvl); broadCastShape.setPosition(sf::Vector2f(positionCase.x - bcLvl + 12, positionCase.y - bcLvl + 12)); broadCastShape.setFillColor(sf::Color( 52 , 73 , 94, 255 - opacity)); m_window.draw(broadCastShape); } i->updateBroadCastLevel(); sprite.setColor(t->getTeamColor()); m_window.draw(sprite); } } m_zappy.unlock(); } <file_sep>/* ** case.h for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ZappyTitou/map ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Mon Jun 23 15:50:43 2014 courtu_r ** Last update jeu. juil. 10 16:08:26 2014 <NAME> */ #include "list.h" #include "inventory.h" #ifndef CASE # define CASE typedef struct s_case { t_inventory *inventory; Uint pos_x; Uint pos_y; t_list *players; // Liste de players. Peut pas faire plus pour le moment. }t_case; bool add_player(t_clientIA *, t_case *); void remove_player(t_clientIA *, t_case *); void free_case(t_case *); void print_case(t_case *); t_case *init_case(Uint x, Uint y); #endif /*CASE*/ <file_sep>SERVER = make -C ./ZappyServer GUI = make -C ./ZappyGUI IA = make -C ./ZappyIA all: $(SERVER) $(GUI) $(IA) clean: $(SERVER) clean $(GUI) clean $(IA) clean fclean: clean $(SERVER) fclean $(GUI) fclean $(IA) fclean server: $(SERVER) gui: $(GUI) ia: $(IA) re : fclean all <file_sep>/* ** is_digit.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/utils ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 16:07:31 2014 ** Last update Sun Jul 13 16:07:33 2014 */ #include <stdbool.h> bool is_digit(char *str) { int i; i = -1; if ((!str) || str[0] == '\0') return (false); while (str[++i]) if (str[i] < '0' || str[i] > '9') return (false); return (true); } <file_sep>/* ** alloc_client_ia.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/clientIA ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:51:17 2014 ** Last update Sun Jul 13 20:54:43 2014 courtu_r */ #include <stdlib.h> #include "zappy.h" t_gui_answer *create_gui_ans(char *msg, unsigned int tick) { t_gui_answer *ret; if (!(ret = malloc(sizeof(*ret))) || msg == NULL) return (NULL); ret->tick = tick; ret->msg = msg; return (ret); } t_clientIA *set_attrs(t_clientIA *ret) { ret->error = false; ret->write = false; ret->level = 1; ret->nb_recv = 0; ret->move[Up] = move_up; ret->move[Right] = move_right; ret->move[Down] = move_down; ret->move[Left] = move_left; ret->direction = rand() % 4; ret->x_moves[Up] = 0; ret->y_moves[Up] = -1; ret->x_moves[Right] = 1; ret->y_moves[Right] = 0; ret->x_moves[Down] = 0; ret->y_moves[Down] = 1; ret->x_moves[Left] = -1; ret->y_moves[Left] = 0; ret->big_write = NULL; ret->call_incantation = false; ret->isDead = false; ret->decLife = 0.0f; ret->broadcast = NULL; ret->instant_write = NULL; return (ret); } t_clientIA *alloc_clientIA(t_team *team, SOCKET sd) { t_clientIA *ret; if (!(ret = malloc(sizeof(*ret)))) return (NULL); if (!(ret->buff_write = alloc_buff())) return (free_va_arg(1, ret)); ret->buff_read = NULL; ret->inventory = NULL; if (!(ret->inventory = init_inventory(ret->inventory))) return (free_va_arg(2, ret->buff_write, ret)); ret->team = team; ret->socket = sd; ret->lastAction = 0.0f; ret = set_attrs(ret); ret->incantation = NULL; return (ret); } <file_sep>/* ** concatList.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/utils ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 16:07:16 2014 ** Last update Sun Jul 13 16:07:17 2014 */ #include <stdlib.h> #include <string.h> #include "list.h" char *_concatList(t_list *l) { char *copy_addr; char *content; size_t size; t_node *it; size = 0; it = l->head; content = NULL; while (it != NULL) { size += strlen((char*)it->data); content = realloc(content, sizeof(char) * (size + 1)); copy_addr = content + size - strlen((char*)it->data); strcpy(copy_addr, (char*)it->data); it = rm_node(l, it); } return content; } <file_sep>/* ** see_utils2.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sun Jul 13 16:37:54 2014 courtu_r ** Last update Sun Jul 13 16:38:57 2014 courtu_r */ #include <string.h> #include "proto.h" #include "zappy.h" int correct_y(int y, t_zappy *server) { if (y >= (int)server->height) return (y % server->height); if (y < 0) return (y + server->height); return (y); } int correct_x(int x, t_zappy *server) { if (x >= (int)server->width) return (x % server->width); if (x < 0) return (x + server->width); return (x); } dir get_right(dir direction) { return ((direction + 1) % 4); } dir get_left(dir direction) { if (direction > Up) return (direction - 1); else return (Left); } int get_nb_cases(int level) { int depth; int width; int nbcases; nbcases = 0; depth = 0; width = 1; while (depth <= level) { nbcases += width; width += 2; depth += 1; } return (nbcases); } <file_sep>#ifndef COLLISION_ENGINE_HPP__ # define COLLISION_ENGINE_HPP__ #include <SFML/Graphics.hpp> /* collision functions - global bounds*/ namespace CollisionEngine { bool pointVSPoint(sf::Vector2f &, sf::Vector2f &); /* =) */ /* rectangle shape */ bool pointVSshape(sf::RenderWindow &, sf::RectangleShape ,int , int); /* sprite */ bool pointVSsprite(sf::RenderWindow &, sf::Sprite ,int , int); } #endif // EOF - CollisionEnfine.hpp<file_sep>#include "App.hpp" int main(int argc, char const *argv[]) { (void)argc; (void)argv; try { App app; app.initialize(); app.run(); } catch (const std::exception &e) { std::cerr << e.what(); return (-1); } return 0; } <file_sep>#include <string> #include <sstream> #include "PanelTime.hpp" #include "CollisionEngine.hpp" PanelTime::PanelTime(Zappy & data, sf::RenderWindow & win, Socket & sock): m_zappy(data), m_window(win), windowSize(m_window.getSize()), rectangle(sf::Vector2f(75, 225)), rectangeAU(sf::Vector2f(75,75)), rectangeAD(sf::Vector2f(75,75)), m_sock(sock) { rectangeAU.setPosition(sf::Vector2f(windowSize.x - 75, Settings::BeginPanelTimeY)); rectangeAD.setPosition(sf::Vector2f(windowSize.x - 75, Settings::BeginPanelTimeY + 150)); arrowSprite.setTexture(TextureManager::Instance().getTexture(ARROW_UP)); arrowSprite.setPosition(sf::Vector2f(windowSize.x - 75, Settings::BeginPanelTimeY)); timeText.setCharacterSize(20); timeText.setColor(Color::Time); timeText.setFont(TextureManager::Instance().getFont()); timeText.setPosition(sf::Vector2f(windowSize.x - 55, Settings::BeginPanelTimeY + 100)); arrowDownSprite.setTexture(TextureManager::Instance().getTexture(ARROW_DOWN)); arrowDownSprite.setPosition(sf::Vector2f(windowSize.x - 75, Settings::BeginPanelTimeY + 150)); rectangle.setFillColor(Color::PanelTime); rectangle.setPosition(sf::Vector2f(windowSize.x - 75, Settings::BeginPanelTimeY)); } void PanelTime::display(SFMLMouseEvent & mouseEvent) { rectangeAU.setFillColor(Color::PanelAU); rectangeAD.setFillColor(Color::PanelAD); events(mouseEvent); std::stringstream ss; ss << m_zappy.getTimeRef(); timeText.setString(ss.str()); m_window.draw(rectangle); m_window.draw(rectangeAU); m_window.draw(rectangeAD); m_window.draw(arrowSprite); m_window.draw(arrowDownSprite); m_window.draw(timeText); } void PanelTime::events(SFMLMouseEvent & mouseEvent) { if (mouseEvent.isMouseClicked() && CollisionEngine::pointVSshape( m_window, rectangeAU , mouseEvent.getX(), mouseEvent.getY())) { rectangeAU.setFillColor(Color::PanelAU_ON); m_zappy.sendTimeToServer(m_zappy.getTimeRef() + Settings::TimePitch, m_sock); } else if (mouseEvent.isMouseClicked() && CollisionEngine::pointVSshape( m_window, rectangeAD , mouseEvent.getX(), mouseEvent.getY())) { rectangeAD.setFillColor(Color::PanelAD_ON); if (m_zappy.getTimeRef() > Settings::TimePitch) m_zappy.sendTimeToServer(m_zappy.getTimeRef() - Settings::TimePitch, m_sock); else m_zappy.sendTimeToServer(1, m_sock); } } PanelTime::~PanelTime() { }<file_sep>/* ** sst.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/clientGUI ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:54:50 2014 ** Last update dim. juil. 13 16:37:05 2014 <NAME> */ #include "utils.h" #include "zappy.h" int sst(t_zappy *server, t_clientGUI *client, char *cmd) { char *send; unsigned int delay; if (parse_two_int(cmd, &delay, NULL)) { client->error = true; return (1); } if (delay < 1 || delay > 1000000000) { client->error = true; return (1); } server->delay = delay; send = tograph_sgt(server); if (send) { if (!(put_in_list(server->listWrite, create_gui_ans(send, 0)))) client->error = true; } return (0); } <file_sep>#ifndef SOCKET_HPP_ #define SOCKET_HPP_ #include <string> #include <netdb.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include "FileDescr.hpp" #include "Except.hpp" class Socket { std::string _ipAdress; int _port; std::string _protocol; struct protoent *_proto; int _fdSocket; struct sockaddr_in _sin; std::string _msgRead; FileDescr _gereFd; public: Socket(std::string const &); ~Socket(); void initSocket(std::string const &, std::string const &); void Connection() const; void writeOnSocket(std::string const &); std::string const & readOnSocket(unsigned int); }; #endif <file_sep>#ifndef RECEPTION_HPP_ #define RECEPTION_HPP_ #include "Socket.hpp" #include "CircularBuffer.hpp" #include "Treatment.hpp" class Reception { typedef bool (Treatment::*func)(std::string const &, Zappy &); std::vector<std::string> _commandList; func _tabCommand[24]; Treatment _treat; Socket _comm; CircularBuffer _buf; Zappy &_data; bool verifyData(std::string const &); void setCmdList(); void setFuncPointer(); public: Reception(Socket &, Zappy &); ~Reception(); void launch(); static void threadLaunch(Reception *); }; #endif <file_sep>/* ** move.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sat Jul 12 12:23:41 2014 courtu_r ** Last update sam. juil. 12 19:18:07 2014 <NAME> */ #include "zappy.h" #include "tograph.h" int call_ppo(t_zappy *, t_clientIA *); int move_up(t_zappy *server, t_clientIA *client) { remove_player_from_pos(client, server->map, client->x, client->y); if (client->y > 0) client->y -= 1; else client->y = server->map->height - 1; add_player_to_pos(client, server->map, client->x, client->y); return (0); } int move_right(t_zappy *server, t_clientIA *client) { remove_player_from_pos(client, server->map, client->x, client->y); if (client->x < server->map->width - 1) client->x += 1; else client->x = 0; add_player_to_pos(client, server->map, client->x, client->y); return (0); } int move_down(t_zappy *server, t_clientIA *client) { remove_player_from_pos(client, server->map, client->x, client->y); if (client->y < server->map->height - 1) client->y += 1; else client->y = 0; add_player_to_pos(client, server->map, client->x, client->y); return (0); } int move_left(t_zappy *server, t_clientIA *client) { remove_player_from_pos(client, server->map, client->x, client->y); if (client->x > 0) client->x -= 1; else client->x = server->map->width - 1; add_player_to_pos(client, server->map, client->x, client->y); return (0); } int move(t_zappy *server, t_clientIA *client, char *cmd) { double frequency; (void)cmd; frequency = ((double)7.0f / server->delay); client->lastAction = get_tick(frequency); client->move[client->direction](server, client); copy_in_buff("ok\n", client->buff_write); client->write = true; if (call_ppo(server, client)) return (1); return (0); } <file_sep>#ifndef _CIRCULAR_BUFFER_H_ # define _CIRCULAR_BUFFER_H_ #include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <strings.h> #include <unistd.h> #define SIZE 512 typedef unsigned int Uint; typedef struct s_circBuff { Uint isReady; char *buf; char *begPtr; char *endPtr; Uint readCnt; Uint writeCnt; }t_buff; void print_cmd_buffer(t_buff *); Uint get_size_left(const char *, const char *); Uint is_filled(t_buff *); Uint check_size(t_buff *); char *check_str(t_buff *, char *, char *, int); t_buff *alloc_buff(); int write_in_buff(int, t_buff *, bool, int); char *get_cmd_from_buff(t_buff *); char *try_get_cmd(t_buff *); int copy_in_buff(char *str, t_buff *buff); #endif <file_sep>/* ** display2.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sun Jul 13 19:38:01 2014 courtu_r ** Last update Sun Jul 13 19:38:11 2014 courtu_r */ #include <sys/time.h> #include <stdlib.h> #include "zappy.h" void print_time(void) { TIMEVAL tv; gettimeofday(&tv, NULL); printf("%d:%06d\t", ((int)tv.tv_sec), ((int)tv.tv_usec)); } <file_sep>/* ** map.h for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Wed Jun 25 12:39:44 2014 courtu_r ** Last update jeu. juin 26 15:49:14 2014 <NAME> */ #ifndef MAP_H__ # define MAP_H__ #include "clients.h" #include "case.h" typedef struct s_map { Uint width; Uint height; t_case ***map; }t_map; void free_map(t_map *map); bool place_player(t_clientIA *player, t_map *map); t_map *init_map(t_map *, Uint, Uint); t_case ***create_map(Uint, Uint); bool add_player_to_pos(t_clientIA *, t_map *, Uint, Uint); void remove_player_from_pos(t_clientIA *, t_map *, Uint, Uint); #endif /*MAP_H__*/ <file_sep>#include <string> #include <sstream> #include "PanelTeam.hpp" #include "Settings.hpp" #include "Color.hpp" #include "TextureManager.hpp" #include "SFMLMouseEvent.hpp" #include "CollisionEngine.hpp" /* must be default view to work properly */ PanelTeam::PanelTeam(Zappy &data, sf::RenderWindow & win): m_zappy(data), m_window(win), teamID(0), arrowLeftBloc(sf::Vector2f(50,50)), arrowRightBloc(sf::Vector2f(50,50)), panel(sf::Vector2f(Settings::PanelTeamX, windowSize.y - Settings::PanelSizeY)), focusedTeam(0), oldBegin(0), arrowDownBloc(sf::Vector2f(175,30)), arrowUpBloc(sf::Vector2f(175,30)), backgroundPlayer(sf::Vector2f(175, Settings::PanelTeamSizeBlocPlayer - 10)) { /* background of arrows */ arrowLeftBloc.setFillColor(sf::Color(0,0,0,0)); arrowRightBloc.setFillColor(sf::Color(0,0,0,0)); arrowLeftBloc.setPosition(sf::Vector2f(0,50)); arrowRightBloc.setPosition(sf::Vector2f(Settings::PanelTeamX - 50, 50)); /* arrows */ arrowLeft.setTexture(TextureManager::Instance().getTexture(ARROW_LEFT)); arrowLeft.setPosition(sf::Vector2f(0,50)); arrowRight.setTexture(TextureManager::Instance().getTexture(ARROW_RIGHT)); arrowRight.setPosition(sf::Vector2f(Settings::PanelTeamX - 50, 50)); /* global panel */ panel.setFillColor(Color::PanelTeam); panel.setPosition(sf::Vector2f(0,0)); /* scroll players */ arrowUpBloc.setPosition(sf::Vector2f(10,280)); arrowDownBloc.setPosition(sf::Vector2f(10,530));; arrowUp.setTexture(TextureManager::Instance().getTexture(ARROW_UP_SMALL)); arrowUp.setPosition(sf::Vector2f(Settings::PanelTeamX / 2 - 15,280)); arrowDown.setTexture(TextureManager::Instance().getTexture(ARROW_DOWN_SMALL)); arrowDown.setPosition(sf::Vector2f(Settings::PanelTeamX / 2 - 15,530)); } PanelTeam::~PanelTeam(){} void PanelTeam::display(SFMLMouseEvent & mouseEvent, Player ** focusedPlayer) { focusedTeam = m_zappy.getTeamById(teamID); windowSize = m_window.getSize(); m_window.draw(panel); showArrows(); checkClickArrows(mouseEvent); drawDescTeam(focusedTeam); descTeam(mouseEvent, focusedPlayer); } void PanelTeam::showArrows() { m_window.draw(arrowLeftBloc); m_window.draw(arrowRightBloc); m_window.draw(arrowLeft); m_window.draw(arrowRight); } void PanelTeam::checkClickArrows(SFMLMouseEvent & mouseEvent) { arrowLeftBloc.setFillColor(sf::Color(0,0,0,0)); arrowRightBloc.setFillColor(sf::Color(0,0,0,0)); if (mouseEvent.isMouseClicked() && CollisionEngine::pointVSshape( m_window, arrowLeftBloc , mouseEvent.getX(), mouseEvent.getY())) { arrowLeftBloc.setFillColor(Color::PanelTeamArrowOn); if (teamID > 0) teamID -= 1; else teamID = m_zappy.getTeam().size() - 1; } else if (mouseEvent.isMouseClicked() && CollisionEngine::pointVSshape( m_window, arrowRightBloc , mouseEvent.getX(), mouseEvent.getY())) { if (teamID < m_zappy.getTeam().size() - 1) teamID += 1; else teamID = 0; arrowRightBloc.setFillColor(Color::PanelTeamArrowOn); } } void PanelTeam::showTeamName(Team * focusedTeam) { /* init */ teamText.setString(focusedTeam->getTeamName()); teamText.setFont(TextureManager::Instance().getFont()); teamText.setCharacterSize(18); teamText.setPosition(sf::Vector2f(50,60)); /* draw */ m_window.draw(teamText); } void PanelTeam::drawDescTeam(Team * focusedTeam) { if (!focusedTeam) return; std::stringstream ss; ss << focusedTeam->getPlayers().size() << " players" << std::endl << focusedTeam->getEggs().size() << " oeufs" << std::endl << focusedTeam->getMaxLevel() << " niveau max" << std::endl; teamText.setString(ss.str()); teamText.setPosition(sf::Vector2f(50,130)); m_window.draw(teamText); } void PanelTeam::descTeamEvents(SFMLMouseEvent & mouseEvent) { if (mouseEvent.isMouseClicked() && CollisionEngine::pointVSshape( m_window, arrowUpBloc , mouseEvent.getX(), mouseEvent.getY())) { if (oldBegin > 0) --oldBegin; arrowUpBloc.setFillColor(Color::PanelTeamArrowOn); } else if (mouseEvent.isMouseClicked() && CollisionEngine::pointVSshape( m_window, arrowDownBloc , mouseEvent.getX(), mouseEvent.getY())) { ++oldBegin; arrowDownBloc.setFillColor(Color::PanelTeamArrowOn); } } void PanelTeam::descTeamBlocs(SFMLMouseEvent & mouseEvent, Player ** focusedPlayer) { std::list<Player *> playersOfTeam = focusedTeam->getPlayers(); std::stringstream ss; unsigned int coeff = 0; unsigned int maxPlayerDisplayed = Settings::PanelTeamPlayerDisplayed; unsigned int begin = oldBegin; bool playerToDraw = false; for (auto &i : playersOfTeam) { if (begin > 0) { --begin; continue; } playerToDraw = true; if (maxPlayerDisplayed == 0) break; ss.str(""); ss << "ID :" << i->getId() << std::endl << "LVL :" << i->getLevel() << std::endl; teamText.setPosition(20,325 + coeff * Settings::PanelTeamSizeBlocPlayer); backgroundPlayer.setPosition(10,320 + coeff * Settings::PanelTeamSizeBlocPlayer); teamText.setString(ss.str()); backgroundPlayer.setFillColor(sf::Color(0,0,0,110)); if (mouseEvent.isMouseClicked() && CollisionEngine::pointVSshape( m_window, backgroundPlayer , mouseEvent.getX(), mouseEvent.getY())) { *focusedPlayer = i; backgroundPlayer.setFillColor(sf::Color(0,0,0,180)); } m_window.draw(backgroundPlayer); m_window.draw(teamText); ++coeff; --maxPlayerDisplayed; } if (!playerToDraw) { if (oldBegin > 0) --oldBegin; } } void PanelTeam::descTeam(SFMLMouseEvent & mouseEvent, Player ** focusedPlayer) { if (!focusedTeam) return; std::stringstream ss; showTeamName(focusedTeam); ss.str(""); ss << "Players list" << std::endl << std::endl; teamText.setPosition(20,250); teamText.setString(ss.str()); m_window.draw(teamText); arrowUpBloc.setFillColor(sf::Color(0,0,0,0)); arrowDownBloc.setFillColor(sf::Color(0,0,0,0)); descTeamEvents(mouseEvent); m_window.draw(arrowUpBloc); m_window.draw(arrowDownBloc); m_window.draw(arrowUp); m_window.draw(arrowDown); descTeamBlocs(mouseEvent, focusedPlayer); sf::RectangleShape teamColor(sf::Vector2f(25,25)); teamColor.setPosition(sf::Vector2f(10,130)); teamColor.setFillColor(focusedTeam->getTeamColor()); m_window.draw(teamColor); (void)focusedPlayer; }<file_sep>/* ** routine_egg.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/egg ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:55:32 2014 ** Last update Sun Jul 13 15:55:33 2014 */ #include <stdlib.h> #include "zappy.h" t_node *routine_egg(t_zappy *s, t_node *node, t_type type, int *ret) { t_egg *egg; (void)ret; if (type != EGG) return (NULL); egg = ((t_egg*)node->data); if (egg && (!(egg->active)) && (egg->tick < get_tick(0))) hatch_egg(egg, s); if (egg && (egg->active)) { if (decrement_food(egg->player, egg->player->inventory, s, egg) == 1) return (rm_node(s->listEGG, node)); egg->tick = get_tick(((double)UNIT_TIME / s->delay)); } return (node->next); } <file_sep>#ifndef PLAYER_HPP__ # define PLAYER_HPP__ #include <map> #include <mutex> #include "Case.hpp" #include "Socket.hpp" enum eOrientation { NORTH = 1, EAST = 2, SOUTH = 3, WEST = 4 }; enum eAction { Expulse = 0, Broadcast, IncantationLaunch, Fork, PutRessources, GetRessources, Nothing, }; enum eStat { Incantation = 0, Not, }; class Player { public: Player(int, unsigned int = 0, unsigned int = 0); ~Player(); void setX(unsigned int); void setY(unsigned int); void setOrientation(eOrientation); eOrientation getOrientation() const; void setLevel(unsigned int); unsigned int getLevel() const; unsigned int getY() const; unsigned int getX() const; int getId() const; void setCurrentAction(eAction); eAction getCurrentAction() const; void setRessource(eRessources, unsigned int); std::map<eRessources, unsigned int> const &getRessource() const; void setBroadCastMsg(std::string const &); std::string const &getBroadCastMsg() const; eStat getCurrentStat() const; void setCurrentStat(eStat); void setIncantationParam(unsigned int, unsigned int, unsigned int); std::vector<unsigned int> const &getIncantationParam() const; unsigned int getBroadCastLevel() const; void updateBroadCastLevel(); std::string const &getStringAction(); void demandInventory(Socket *); private: eAction _currentAction; std::string _strCurAction; std::vector<unsigned int> _incantationParam; eStat _currentStat; unsigned int m_x; unsigned int m_y; unsigned int _level; int m_id; eOrientation _orient; std::string _broadCastMsg; std::map<eRessources, unsigned int> _ressources; std::mutex m_mutex; private: unsigned int m_broadCastLevel; }; #endif // EOF - Player.hpp <file_sep>#include "CircularBuffer.hpp" CircularBuffer::CircularBuffer(unsigned int size) { _buf.set_capacity(size); _buf.resize(size); } void CircularBuffer::pushString(std::string const &str) { std::string::const_iterator i = str.begin(); while (i != str.end()) { _buf.push_back(*i); i++; } } bool CircularBuffer::getFirstString(std::string &msg) { boost::circular_buffer<char>::iterator it; boost::circular_buffer<char>::iterator save; msg.clear(); it = _buf.begin(); for (it = _buf.begin(); it != _buf.end() && *it == 0; it++); save = it; while (it != _buf.end() && *it != '\n') { msg.push_back(*it); it++; } if (it == _buf.end()) return (false); if (*it != '\n') return (false); it = save; while (it != _buf.end() && *it != '\n') { *it = '\0'; it++; } *it = '\0'; return (true); } unsigned int CircularBuffer::sizeEmpty() const { boost::circular_buffer<char>::const_iterator it; unsigned int size = 0; for (it = _buf.begin(); it != _buf.end() && *it == 0; it++) { size++; } return (size); } bool CircularBuffer::isEmpty() const { return (_buf.empty()); } bool CircularBuffer::isFull() const { return (_buf.full()); } <file_sep>/* ** fill_option.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/init ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 16:15:03 2014 ** Last update dim. juil. 13 19:50:19 2014 <NAME> */ #include <stdio.h> #include <string.h> #include <unistd.h> #include "parse.h" static int get_opt(char opt); static int print_usage(char *name); static int check_opt(int opt_flags, char *name); static void init_func_opt(bool (*ptr[NB_OPT])()); int fill_opt(int argc, char **argv, t_zappy *server) { int c; int call; int opt_flags; bool (*func_opt[NB_OPT])(t_zappy *, int, char **, int *); opt_flags = 0; if ((argc == 2) && (strncmp(argv[1], "-h", 2) == 0)) return (print_usage(argv[0])); init_func_opt(func_opt); server->port = 4242; server->delay = 100; while ((c = getopt(argc, argv, "p:x:y:n:c:t:")) != -1) { if (c == '?') return (fprintf(stderr, "%s: -h for usage.\n", argv[0])); else { call = get_opt(c); if (call > -1 && call < ((int)NB_OPT)) if (!((*func_opt[call])(server, argc, argv, &opt_flags))) return (1); } } return (check_opt(opt_flags, argv[0])); } static int get_opt(char opt) { int i; i = -1; while (KARSET_OPT[++i]) if (KARSET_OPT[i] == opt) return (i); return (-1); } static int print_usage(char *name) { fprintf(stderr, "Usage: %s:\n", name); fprintf(stderr, "[-p port]\n"); fprintf(stderr, "-x width\n"); fprintf(stderr, "-y height\n"); fprintf(stderr, "-n team1 [team2 [...]]\n"); fprintf(stderr, "-c max player per team\n"); fprintf(stderr, "[-t time delay]\n"); return (1); } static int check_opt(int opt_flags, char *name) { int ret; ret = 0; if (!(opt_flags & FLAGS_X)) ret = fprintf(stderr, "Option -x width is required.\n"); if (!(opt_flags & FLAGS_Y)) ret = fprintf(stderr, "Option -y height is required.\n"); if (!(opt_flags & FLAGS_N)) ret = fprintf(stderr, "Option -n name_of_team(s) is required.\n"); if (!(opt_flags & FLAGS_C)) ret = fprintf(stderr, "Option -c nb players per team is required.\n"); if (ret > 0) return (fprintf(stderr, "%s: -h for usage.\n", name)); return (0); } static void init_func_opt(bool (*ptr[NB_OPT])()) { ptr[0] = &parse_port; ptr[1] = &parse_width; ptr[2] = &parse_height; ptr[3] = &parse_name_team; ptr[4] = &parse_nb_clients; ptr[5] = &parse_delay; } <file_sep>/* ** see_utils3.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sun Jul 13 16:41:30 2014 courtu_r ** Last update Sun Jul 13 16:44:29 2014 courtu_r */ #include <string.h> #include "proto.h" #include "zappy.h" void init_pos_player_left_right(int * tmpX, int * tmpY, t_clientIA *player) { (*tmpX) = player->x; (*tmpY) = player->y; } void looping_left_right(int * cnt, int * width, int * depth) { (*cnt) = 0; (*width) += 2; (*depth) += 1; } int f_cor_up_down(int * nbcases, int * cnt, char **msg) { (*nbcases) -= 1; (*cnt) += 1; if ((*nbcases) > 0) { if (((*msg) = realloc(*msg, sizeof(**msg) * (strlen(*msg) + 2))) == NULL) return (-1); if (((*msg) = strcat(*msg, ",")) == NULL) return (-1); } return (0); } void f2_cor_up_down(int * tmpX, t_clientIA * player, t_zappy * server) { if (player->direction == Up) (*tmpX) = correct_x((*tmpX) + player-> x_moves[get_right(player->direction)], server); else (*tmpX) = correct_x((*tmpX) + player-> x_moves[get_left(player->direction)], server); } void f3_cor_up_down(int * tmpX, t_clientIA * player, t_zappy * server, int width) { if (player->direction == Up) (*tmpX) = correct_x(player-> x + (player-> x_moves[get_left(player-> direction) ] * (width / 2)), server); else (*tmpX) = correct_x(player-> x + (player-> x_moves[get_right(player-> direction) ] * (width / 2)), server); } <file_sep>#ifndef PANEL_TEAM_HPP # define PANEL_TEAM_HPP #include "Zappy.hpp" #include "Settings.hpp" #include "Color.hpp" #include "TextureManager.hpp" #include "SFMLMouseEvent.hpp" class PanelTeam { public: PanelTeam(Zappy &, sf::RenderWindow &); ~PanelTeam(); private: Zappy & m_zappy; sf::RenderWindow & m_window; unsigned int teamID; sf::Vector2u windowSize; private: sf::Sprite arrowLeft; sf::Sprite arrowRight; sf::RectangleShape arrowLeftBloc; sf::RectangleShape arrowRightBloc; sf::RectangleShape panel; Team * focusedTeam; sf::Text teamText; public: void display(SFMLMouseEvent &, Player ** focusedPlayer); void showArrows(); void checkClickArrows(SFMLMouseEvent &); void descTeam(SFMLMouseEvent &, Player **); void showTeamName(Team * focusedTeam); void drawDescTeam(Team * focusedTeam); void descTeamEvents(SFMLMouseEvent & mouseEvent); void descTeamBlocs(SFMLMouseEvent & mouseEvent, Player **); public: unsigned int oldBegin; sf::Sprite arrowDown; sf::Sprite arrowUp; sf::RectangleShape arrowDownBloc; sf::RectangleShape arrowUpBloc; sf::RectangleShape backgroundPlayer; }; #endif // EOF - PanelTeam.hpp<file_sep>#ifndef VIEW_HPP__ # define VIEW_HPP__ #include <SFML/Graphics.hpp> #include "Zappy.hpp" #include "Socket.hpp" #include "SFMLMouseEvent.hpp" #include "PanelTeam.hpp" #include "PanelTime.hpp" class View { typedef void (View::*FPTR)(sf::CircleShape &, sf::Vector2f); public: View(sf::RenderWindow &, Zappy &, Socket &); ~View(); public: void display(); private: void _display(); void _displayBackground(); void _displayMap(); void _events(); void _displayInfoCase(); void _displayInfoPlayer(); void _displayPanelCase(); void _displayPanelCaseNourriture(sf::Vector2u &, unsigned int); void _displayPanelCaseLinemate(sf::Vector2u &, unsigned int); void _displayPanelCaseDeraumere(sf::Vector2u &, unsigned int); void _displayPanelCaseSibur(sf::Vector2u &, unsigned int); void _displayPanelCaseMendiane(sf::Vector2u &, unsigned int); void _displayPanelCasePhiras(sf::Vector2u &, unsigned int); void _displayPanelCaseThystame(sf::Vector2u &, unsigned int); void _displayPanelPlayer(); void _displayPlayers(); void _displayPanelTime(); void _displayPanelTeams(); template <typename T> bool onScreen(T &, sf::View &); void _displayEndGame(); void _moveView(int,int); void _zoomView(float); void _rotateView(float); bool _detectCollision(sf::FloatRect, int , int); void _drawRessoucesOfCase(Case & obj); void _displayIncantation(Case *, std::vector<sf::Sprite> &); void _displayMapEvents(Case *); private: Zappy & m_zappy; sf::RenderWindow & m_window; sf::View currentView; sf::View gameView; bool mouseClicked; SFMLMouseEvent mouseEvent; Case * focusedBloc; Player * focusedPlayer; sf::Font m_font; Socket & m_sock; sf::Sprite bg; private: void drawNourriture(sf::CircleShape &, sf::Vector2f); void drawLinemate(sf::CircleShape &, sf::Vector2f); void drawDeraumere(sf::CircleShape &, sf::Vector2f); void drawSibur(sf::CircleShape &, sf::Vector2f); void drawMendiane(sf::CircleShape &, sf::Vector2f); void drawPhiras(sf::CircleShape &, sf::Vector2f); void drawThystame(sf::CircleShape &, sf::Vector2f); std::map<unsigned int, FPTR> mapFptr; /* gui elements */ sf::CircleShape circleShape; private: PanelTeam panelLeft; PanelTime panelRight; }; const int COEFFICIENT_MOVE = 7; const int PANELSIZE_Y = 100; #endif // EOF - View.hpp<file_sep>/* ** vectors.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sat Jul 12 13:06:39 2014 courtu_r ** Last update Sun Jul 13 19:36:23 2014 courtu_r */ #include <math.h> #include <string.h> #include "zappy.h" int get_correct_num(double); double scal_prod(double *, double *, bool); double *get_shortest_vector(t_clientIA *, t_clientIA *, t_zappy *); int my_strlen(char *); char *get_param(char *); double *get_unit_vector(double x, double y) { double *vec; if (!(vec = malloc(sizeof(*vec) * 2))) return (NULL); vec[0] = x; vec[1] = y; return (vec); } double **init_vectors() { double **result; int cnt; if (!(result = malloc(sizeof(*result) * 5))) return (NULL); result[Up] = get_unit_vector(0.0, -1.0); result[Down] = get_unit_vector(0.0, 1.0); result[Left] = get_unit_vector(-1.0, 0.0); result[Right] = get_unit_vector(1.0, 0.0); result[4] = NULL; cnt = -1; while (result[++cnt]); if (cnt != 4) return (NULL); return (result); } double *get_vector(double x, double y, double origx, double origy) { double *vec; if (!(vec = malloc(sizeof(*vec) * 2))) return (NULL); vec[0] = origx - x; vec[1] = origy - y; return (vec); } double *normalize_vec(double *vec_to_norm) { double *vec; if (!(vec = malloc(sizeof(*vec) * 2))) return (NULL); vec[0] = vec_to_norm[0] * vec_to_norm[0]; vec[1] = vec_to_norm[1] * vec_to_norm[1]; return (vec); } <file_sep>#include <iostream> #include <SFML/Graphics.hpp> #include <thread> #include "App.hpp" #include "Login.hpp" #include "View.hpp" #include "Reception.hpp" #include "Settings.hpp" App::App(): sock("TCP") { } App::~App(){} void App::initialize() { sf::ContextSettings settings; /* antialiasing */ settings.antialiasingLevel = Settings::AntiAliasing; /* create the rendering window */ m_window.create( sf::VideoMode(Settings::WindowSizeX, Settings::WindowSizeY), Settings::WindowTitle, sf::Style::Default, settings); /* settings the fps */ m_window.setFramerateLimit(Settings::FPS); } void App::run() { /* connexion to server */ _connexion(); /* display world */ View view(m_window, m_zappy, sock); view.display(); while (m_window.isOpen()) { m_window.clear(); _events(); m_window.display(); } pthread_cancel(t1->native_handle()); } void App::_events() { sf::Event event; while (m_window.pollEvent(event)) { /* cross */ if (event.type == sf::Event::Closed) m_window.close(); } } void App::_connexion() { /* default credential for testing purposes */ std::string ip = "127.0.0.1"; std::string port = "3535"; /* login screen */ Login login(m_window); login.getCredentials(ip, port); /* initialization of socket */ sock.initSocket(ip, port); /* connection to server */ sock.Connection(); /* launching a thread for the protocol */ Reception *recep = new Reception(sock, m_zappy); t1 = new std::thread(Reception::threadLaunch, recep); /* waiting for intialization of the base - should put a timer ? */ while (!m_zappy.getIsSet()) usleep(100); /* no 100% cpu */ std::cout << "[App]\t->\tconnected to server : [" << ip << " : " << port << "]" << std::endl; } <file_sep>/* ** choose_client.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/network ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:59:00 2014 ** Last update dim. juil. 13 18:15:07 2014 <NAME> */ #include <stdlib.h> #include "zappy.h" static int is_ia(t_zappy *s, t_team *team, t_conn *c); static int is_egg(t_zappy *s, t_team *team, t_conn *c); int choose_client(t_zappy *server, t_team *team, t_conn *c) { if (is_ia(server, team, c)) return (-1); if (is_egg(server, team, c)) return (-1); return (create_client_ia(server, c, team)); } static int is_ia(t_zappy *s, t_team *team, t_conn *c) { t_clientIA *client; t_gui_answer *answer; if ((client = is_in_list_of_ia(s->listIA, team))) { client->socket = c->socket; ++(team->nbplayers); first_send_ia(client, s, team); s->currentRessource = client; answer = create_gui_ans(tograph_pnw(s), 0); put_in_list(s->listWrite, answer); printf("%s", get_color_term(SERVER)); printf("*** New player takes over player %d (GHOST) at (%d, %d)", client->id, client->x, client->y); printf("%s\n", get_color_term(DISABLE)); client->decLife = get_tick(((double)UNIT_TIME * 1.0f / s->delay)); return (1); } return (0); } static int is_egg(t_zappy *s, t_team *team, t_conn *c) { t_clientIA *client; if ((client = is_in_list_egg(s->listEGG, team, c, s))) { client->socket = c->socket; client->id = ++(s->max_id); printf("%s", get_color_term(SERVER)); printf("*** Player %d takes place EGG at (%d, %d)", client->socket, client->x, client->y); printf("%s\n", get_color_term(DISABLE)); client->decLife = get_tick(((double)UNIT_TIME * 1.0f / s->delay)); return (1); } return (0); } <file_sep>/* ** left.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sat Jul 12 13:11:08 2014 courtu_r ** Last update Sun Jul 13 19:44:13 2014 courtu_r */ #include "broadcast.h" int call_ppo(t_zappy *server, t_clientIA *client) { server->currentRessource = client; char *str = tograph_ppo(server); if (!put_in_list(server->listWrite, create_gui_ans(str, client->lastAction))) return (1); return (0); } int left(t_zappy *server, t_clientIA *client, char *cmd) { double frequency; (void)cmd; frequency = ((double)7 / server->delay); client->lastAction = get_tick(frequency); if (client->direction > 0) client->direction -= 1; else client->direction = Left; copy_in_buff("ok\n", client->buff_write); client->write = true; if (call_ppo(server, client)) return (1); return (0); } <file_sep>/* ** func_parse2.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/init ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 16:16:02 2014 ** Last update dim. juil. 13 21:36:14 2014 <NAME> */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "parse.h" #include "utils.h" bool parse_delay(t_zappy *s, int argc, char **argv, int *flags) { (void)argc; (void)argv; (*flags) += FLAGS_T; if (!is_digit(optarg)) { fprintf(stderr, "Argument of -t must be a number.\n"); return (false); } s->delay = atoi(optarg); if (s->delay < 1) { fprintf(stderr, "Argument of -t must be a positif number.\n"); return (false); } return (true); } bool parse_nb_clients(t_zappy *s, int argc, char **argv, int *flags) { (void)argc; (void)argv; (*flags) += FLAGS_C; if (!is_digit(optarg)) { fprintf(stderr, "Argument of -c must be a number.\n"); return (false); } s->nbClients = atoi(optarg); if (s->nbClients < 1 || s->nbClients > 1000000) { fprintf(stderr, "Argument of -c must be a positif number.\n"); return (false); } return (true); } <file_sep>/* ** ppo.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/clientGUI ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:54:08 2014 ** Last update dim. juil. 13 16:36:48 2014 <NAME> */ #include "utils.h" #include "zappy.h" int ppo(t_zappy *server, t_clientGUI *client, char *cmd) { char *send; unsigned int n; if (parse_two_int(cmd, &n, NULL)) { client->error = true; return (1); } server->currentRessource = get_clientIA_by_index(server->listIA, n); if (server->currentRessource) { send = tograph_ppo(server); if (send) { copy_in_buff(send, client->buff_write); free(send); client->write = true; } } else client->error = true; return (0); } <file_sep>/* ** map_utils.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sun Jul 13 16:49:22 2014 courtu_r ** Last update Sun Jul 13 16:50:54 2014 courtu_r */ #include "map.h" bool place_player(t_clientIA *player, t_map *map) { if (add_player_to_pos(player, map, player->x, player->y) == false) return (false); return (true); } bool add_player_to_pos(t_clientIA *player, t_map *map, Uint x, Uint y) { return (add_player(player, map->map[y][x])); } void remove_player_from_pos(t_clientIA *player, t_map *map, Uint x, Uint y) { remove_player(player, map->map[y][x]); } <file_sep>/* ** action_network.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/network ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:58:02 2014 ** Last update Sun Jul 13 20:05:01 2014 courtu_r */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "zappy.h" void send_buffer(t_clientIA *client, const char *buffer) { ssize_t nbwrites; if (buffer) nbwrites = write(client->socket, buffer, strlen(buffer)); else return ; if (nbwrites != ((ssize_t)strlen(buffer))) fprintf(stderr, "send() failed.\n"); printf("%s", get_color_term(SEND)); print_time(); printf("Sending message to %d: %s", client->id, buffer); printf("%s", get_color_term(DISABLE)); fflush(stdout); } <file_sep>#include "Socket.hpp" #include <iostream> #include <sstream> Socket::Socket(std::string const &proto) : _protocol(proto) { _gereFd.setTime(0, 0); } Socket::~Socket() { } void Socket::initSocket(std::string const &ip, std::string const &port) { std::istringstream ss(port); ss >> _port; _ipAdress = ip; if ((_proto = getprotobyname(_protocol.c_str())) == 0) throw Except("Error : unknown protocol\n"); if ((_fdSocket = socket(AF_INET, SOCK_STREAM, _proto->p_proto)) == -1) throw Except("Error : impossible to create socket\n"); _sin.sin_family = AF_INET; _sin.sin_port = htons(_port); _sin.sin_addr.s_addr = inet_addr(_ipAdress.c_str()); } void Socket::Connection() const { if ((connect(_fdSocket, reinterpret_cast<struct sockaddr *>(const_cast<sockaddr_in *>(&_sin)), sizeof(_sin))) == -1) throw Except("Error : impossible to connect to the server\n"); } void Socket::writeOnSocket(std::string const &msg) { if (send(_fdSocket, msg.c_str(), msg.length(), 0) == -1) throw Except("Error : impossible to write on socket\n"); } std::string const & Socket::readOnSocket(unsigned int size) { _msgRead.clear(); _gereFd.setTime(0, 0); _gereFd.setFd(_fdSocket); if (_gereFd.setNonBlock() == -1) std::cout << "Ya une couille" << std::endl; if (_gereFd.isSet(_fdSocket) == true) { char value[size + 1]; for (unsigned int i = 0; i < size + 1; i++) value[i] = 0; if (read(_fdSocket, value, size) == -1) throw Except("Error : impossible to read on socket\n"); _msgRead = value; } return (_msgRead); } <file_sep>/* ** release.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:50:09 2014 courtu_r ** Last update Sun Jul 13 15:50:09 2014 courtu_r */ #include <stdlib.h> #include <stdio.h> #include "zappy.h" int release_memory(t_zappy *server, int ret) { static t_zappy *ptrZappy; if (server) ptrZappy = server; else { if (ptrZappy->map) free_map(ptrZappy->map); free(ptrZappy->incantation_requirements); release_list(ptrZappy->listConn); release_list(ptrZappy->listTeam); release_list(ptrZappy->listIA); release_list(ptrZappy->listGUI); release_list(ptrZappy->listEGG); release_list(ptrZappy->listWrite); printf("%s", get_color_term(DISABLE)); fflush(stdout); } return (ret); } <file_sep>/* ** expulse_utils.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sat Jul 12 15:28:37 2014 courtu_r ** Last update Sat Jul 12 15:33:58 2014 courtu_r */ #include "broadcast.h" char *get_ans(t_clientIA *, t_clientIA *, t_zappy *); int call_ppo(t_zappy *, t_clientIA *); void init_begin(t_zappy *server, t_clientIA *client) { int frequency; frequency = ((double)7.0f / server->delay); client->lastAction = get_tick(frequency); server->currentRessource = client; } int set_all(t_zappy *server, t_clientIA *client, t_node *node) { t_clientIA *player; char *ans; while (node) { player = (t_clientIA *)(node->data); if (node && player) node = node->next; if (player != client) { client->move[client->direction](server, player); if (!(ans = get_ans(player, client, server))) return (-1); copy_in_buff(ans, player->buff_write); free(ans); if ((player->write = true) && call_ppo(server, player)) return (1); } } return (0); } <file_sep>#ifndef SFML_MOUSE_EVENT_HPP # define SFML_MOUSE_EVENT_HPP #include <SFML/Graphics.hpp> class SFMLMouseEvent { public: SFMLMouseEvent(); ~SFMLMouseEvent(); void update(sf::RenderWindow &, sf::Event); bool isMouseClicked() const; int getX() const; int getY() const; void reset(); private: sf::Event mouseEvent; bool mouseClicked; int _x; int _y; }; #endif // EOF - SFMLMouseEvent.hpp<file_sep>/* ** routine_clients_ia.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy/server ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sat Jul 12 21:02:10 2014 courtu_r ** Last update Sun Jul 13 21:25:10 2014 courtu_r */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include "zappy.h" #include "proto.h" static int treat_died(t_zappy *s, t_clientIA *client); static int read_node_ia(t_zappy *s, t_clientIA *client); static int write_node_ia(t_zappy *s, t_clientIA *client); static int actions_node_ia(t_zappy *s, t_clientIA *client); t_node *routine_clientIA(t_zappy *s, t_node *node, t_type type, int *ret) { t_clientIA *client; (void)ret; if (type != IA) return (NULL); client = ((t_clientIA*)node->data); if (client) { if ((client->decLife < get_tick(0.0f))) { if (decrement_food(client, client->inventory, s, NULL) == 1) client->isDead = true; client->decLife = get_tick(((double)UNIT_TIME / (double)s->delay)); } if (write_node_ia(s, client) == -1) return rm_node(s->listIA, node); if (read_node_ia(s, client) == -1) return rm_node(s->listIA, node); if (actions_node_ia(s, client) == -1) return rm_node(s->listIA, node); } return (node->next); } static int actions_node_ia(t_zappy *s, t_clientIA *client) { char *str; t_cmd_ia num; if (((client->lastAction == 0.0f) || (client->lastAction < get_tick(0.0f))) && (str = try_get_cmd(client->buff_read))) { if ((num = find_cmd_ia(str)) != UNKNOWN) (*s->ptr_func_ia[num])(s, client, str); else client->error = true; free(str); } return (0); } static int write_node_ia(t_zappy *s, t_clientIA *client) { const char *error = "ko\n"; if (client->error && FD_ISSET(client->socket, &(s->writesd))) write_error_ia(client, error); else { if (((client->lastAction < get_tick(0.0f))) && client->write && FD_ISSET(client->socket, &(s->writesd))) write_cmd(client); else if (client->broadcast && client->lastAction < get_tick(0.0f)) call_back_broadcast(s, client); else if (client->incantation) write_level_up(s, client); else if (client->call_incantation) write_incantation(s, client); else if (client->instant_write && FD_ISSET(client->socket, &(s->writesd))) write_buffer_ia(client, &(client->instant_write)); else if (((client->lastAction < get_tick(0.0f))) && client->big_write && FD_ISSET(client->socket, &(s->writesd))) write_buffer_ia(client, &(client->big_write)); } if (client->isDead) return (treat_died(s, client)); return (0); } static int treat_died(t_zappy *s, t_clientIA *client) { send_buffer(client, try_get_cmd(client->buff_write)); --(client->team->nbplayers); --(s->max_id); if (close(client->socket) == -1) perror("Close failed. Error"); client->socket = -1; return (-1); } static int read_node_ia(t_zappy *s, t_clientIA *client) { if (FD_ISSET(client->socket, &(s->readsd))) { if (write_in_buff(client->socket, client->buff_read, true, client->id) <= 0) { printf("%s", get_color_term(SERVER)); printf("*** Player %d is now in GHOST mode", client->id); printf("%s\n", get_color_term(DISABLE)); client->old_id = client->socket; --(client->team->nbplayers); if (close(client->socket) == -1) perror("Close failed. Error"); client->socket = -1; return (1); } } return (0); } <file_sep>/* ** broadcast_utils.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Wed Jul 9 15:30:27 2014 courtu_r ** Last update Sun Jul 13 19:36:48 2014 courtu_r */ #include <math.h> #include "zappy.h" double get_shortest_up_down(double y, double dest, t_zappy *server) { int upy; int downy; int cnt; cnt = 0; downy = (int)y; upy = (int)y; while (upy != (int)dest && downy != (int)dest) { upy -= 1; downy += 1; if (upy < 0) upy = server->height - 1; if ((unsigned int)downy >= server->height) downy = 0; cnt += 1; } if (upy == (int)dest) return ((double)(cnt * -1)); else return ((double)(cnt)); } double get_shortest_left_right(double x, double dest, t_zappy *server) { int leftx; int rightx; int cnt; cnt = 0; rightx = (int)x; leftx = (int)x; while (leftx != (int)dest && rightx != (int)dest) { leftx -= 1; rightx += 1; if (leftx < 0) leftx = server->width - 1; if ((unsigned int)rightx >= server->width) rightx = 0; cnt += 1; } if (leftx == (int)dest) return ((double)(cnt * -1)); else return ((double)cnt); } double *get_shortest_vector(t_clientIA *client_pos, t_clientIA *client_dest, t_zappy *server) { double *result; if (!(result = malloc(sizeof(*result) * (2)))) return (NULL); result[0] = get_shortest_left_right(client_pos->x, client_dest->x, server); result[1] = get_shortest_up_down(client_pos->y, client_dest->y, server); return (result); } int get_correct_num(double angle) { angle = (360.0 + angle); if (angle > 360.0) angle -= 360.0; if ((int)angle < 45) return (1); else if ((int)angle == 45) return (2); else if ((int)angle < 135) return (3); else if ((int)angle == 135) return (4); else if ((int)angle < 225) return (5); else if ((int)angle == 225) return (6); else if ((int)angle < 315) return (7); else if ((int)angle == 315) return (8); else return (1); } double scal_prod(double *vec1, double *vec2, bool is_normalized) { if (!is_normalized) return (vec1[0] * vec2[0] + vec1[1] * vec2[1]); else return (sqrt(vec1[0] * vec1[0] + vec1[1] * vec1[1]) * sqrt(vec2[0] * vec2[0] + vec2[1] * vec2[1])); } <file_sep>NAME = zappy CC = gcc INCS = ./incs SERVER = ./server INIT = $(SERVER)/init NW = $(SERVER)/network STRUCT = $(SERVER)/struct UTILS = $(SERVER)/utils IA = $(SERVER)/clientIA GUI = $(SERVER)/clientGUI EGG = $(SERVER)/egg SPAWN = $(SERVER)/foodSpawn COMMUNICATION = $(SERVER)/communications SRC += main.c \ SRC += $(SPAWN)/foodSpawn.c SRC += $(SERVER)/schedule.c \ $(SERVER)/release.c \ $(SERVER)/signals.c \ $(SERVER)/find_func_ia.c \ $(SERVER)/find_func_gui.c \ $(SERVER)/team.c \ $(SERVER)/display_info.c \ $(SERVER)/display2.c \ SRC += $(IA)/alloc_client_ia.c \ $(IA)/move.c \ $(IA)/right.c \ $(IA)/left.c \ $(IA)/see.c \ $(IA)/take_obj.c \ $(IA)/put_obj.c \ $(IA)/expulse.c \ $(IA)/broadcast.c \ $(IA)/incantation.c \ $(IA)/fork.c \ $(IA)/connect_nbr.c \ $(IA)/case.c \ $(IA)/inventory.c \ $(IA)/map.c \ $(IA)/init_incantation_checks.c \ $(IA)/broadcast_utils.c \ $(IA)/inventory_utils.c \ $(IA)/decrement_food.c \ $(IA)/vectors.c \ $(IA)/incantation_utils.c \ $(IA)/expulse_utils.c \ $(IA)/see_utils.c \ $(IA)/see_utils2.c \ $(IA)/see_utils3.c \ $(IA)/see_utils4.c \ $(IA)/map_utils.c \ SRC += $(COMMUNICATION)/serv_to_gui.c SRC += $(COMMUNICATION)/serv_to_gui_2.c SRC += $(COMMUNICATION)/serv_to_gui_3.c SRC += $(COMMUNICATION)/serv_to_gui_4.c SRC += $(COMMUNICATION)/serv_to_gui_5.c SRC += $(COMMUNICATION)/serv_to_gui_6.c SRC += $(GUI)/alloc_client_gui.c \ $(GUI)/get_client_ia.c \ $(GUI)/msz.c \ $(GUI)/bct.c \ $(GUI)/mct.c \ $(GUI)/tna.c \ $(GUI)/ppo.c \ $(GUI)/plv.c \ $(GUI)/pin.c \ $(GUI)/sgt.c \ $(GUI)/sst.c \ SRC += $(INIT)/init_server.c \ $(INIT)/fill_option.c \ $(INIT)/func_parse.c \ $(INIT)/func_parse2.c \ SRC += $(STRUCT)/list.c \ $(STRUCT)/circular_buffer.c \ $(STRUCT)/utils_buffer.c \ $(STRUCT)/release_node.c \ $(STRUCT)/iter_list.c \ SRC += $(UTILS)/is_digit.c \ $(UTILS)/free_va_arg.c \ $(UTILS)/display_info.c \ $(UTILS)/time.c \ $(UTILS)/concatList.c \ $(UTILS)/parse_arg_int.c \ SRC += $(NW)/create_socket_tcp.c \ $(NW)/connexion.c \ $(NW)/monitor_socket.c \ $(NW)/routine_connexion.c \ $(NW)/routine_clients_ia.c \ $(NW)/routine_clients_gui.c \ $(NW)/choose_graphic_or_ia.c \ $(NW)/action_network.c \ $(NW)/choose_client.c \ $(NW)/write_ia.c \ $(NW)/write_gui.c \ SRC += $(EGG)/alloc_egg.c \ $(EGG)/is_in_list_egg.c \ $(EGG)/routine_egg.c \ OBJ = $(SRC:.c=.o) CFLAGS = -W -Wall -Wextra -I$(INCS) LDFLAGS = -lm RM = rm -f all: $(NAME) $(NAME): $(OBJ) $(CC) -o $@ $^ $(LDFLAGS) clean: $(RM) $(OBJ) fclean: clean $(RM) $(NAME) re: fclean all <file_sep>#ifndef _FUNC_GUI_H_ # define _FUNC_GUI_H_ #include <stdio.h> #include "zappy.h" typedef struct s_client_gui t_clientGUI; int bct(t_zappy *server, t_clientGUI *client, char *cmd); int mct(t_zappy *server, t_clientGUI *client, char *cmd); int msz(t_zappy *server, t_clientGUI *client, char *cmd); int pin(t_zappy *server, t_clientGUI *client, char *cmd); int plv(t_zappy *server, t_clientGUI *client, char *cmd); int ppo(t_zappy *server, t_clientGUI *client, char *cmd); int sgt(t_zappy *server, t_clientGUI *client, char *cmd); int sst(t_zappy *server, t_clientGUI *client, char *cmd); int tna(t_zappy *server, t_clientGUI *client, char *cmd); #endif <file_sep>/* ** find_func_gui.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:50:47 2014 courtu_r ** Last update Sun Jul 13 15:50:48 2014 courtu_r */ #include <string.h> #include "zappy.h" /* ** Be careful same order like in clients.h */ t_cmd_gui find_cmd_gui(const char *cmd) { static char *tab_cmd[NB_FUNC_GUI + 1] = { "msz", "bct", "mct", "tna", "ppo", "plv", "pin", "sgt", "sst" }; int i; i = -1; while (++i < NB_FUNC_GUI) if (strncmp(cmd, tab_cmd[i], strlen(tab_cmd[i])) == 0) return (i); return (-1); } <file_sep>/* ** display_info.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/utils ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 16:07:25 2014 ** Last update Sun Jul 13 16:07:58 2014 */ #include "zappy.h" const char *get_color_term(t_color col) { static char tab[NB_COLOR_TERM][15] = { "\033[01;32m", "\033[01;33m", "\033[01;31m", "\033[01;34m", "\033[01;0m" }; return (tab[col]); } <file_sep>#ifndef _EGG_H_ # define _EGG_H_ #include "team.h" typedef unsigned int uint; typedef struct s_zappy t_zappy; typedef struct s_egg { double tick; bool active; unsigned int id; unsigned int x; unsigned int y; t_team *team; t_clientIA *player; } t_egg; int hatch_egg(t_egg *, t_zappy *); t_egg *alloc_egg(uint id, t_clientIA *client); #endif <file_sep>#ifndef TEAM_HPP_ #define TEAM_HPP_ #include <SFML/Graphics.hpp> #include <list> #include <mutex> #include "Player.hpp" #include "Egg.hpp" class Team { std::list<Player *> _players; std::string _teamName; std::list<Egg *> _egg; std::mutex m_mutex; sf::Color _color; //color public: Team() {}; Team(std::string const &, sf::Color); ~Team(); std::list<Player *> &getPlayers(); std::string const &getTeamName() const; void setTeamName(std::string const &); sf::Color const &getTeamColor() const; void setTeamColor(sf::Color const &); void setNewPlayer(Player *); void setNewEgg(Egg *); unsigned int getMaxLevel() const; std::list<Egg*> &getEggs(); }; #endif <file_sep>#ifndef COLOR_HPP__ # define COLOR_HPP__ #include <SFML/Graphics.hpp> class Color { public: /* map */ static sf::Color Case; static sf::Color CaseFocus; /* pierres */ static sf::Color Nourriture; static sf::Color Linemate; static sf::Color Deraumere; static sf::Color Sibur; static sf::Color Mendiane; static sf::Color Phiras; static sf::Color Thystame; /* panelTime */ static sf::Color PanelTime; static sf::Color Time; static sf::Color PanelAU; static sf::Color PanelAD; static sf::Color PanelAU_ON; static sf::Color PanelAD_ON; /* panel teams */ static sf::Color PanelTeam; static sf::Color PanelTeamArrowOn; public: /* divers */ static sf::Color BroadcastInColor; static sf::Color BroadcastOutLineColor; }; #endif // EOF - Color.hpp<file_sep>/* ** expulse.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sat Jul 12 13:15:41 2014 courtu_r ** Last update Sun Jul 13 16:34:46 2014 courtu_r */ #include "broadcast.h" void init_begin(t_zappy *, t_clientIA *); int set_all(t_zappy *, t_clientIA *, t_node *); int call_ppo(t_zappy *, t_clientIA *); int *init_directions(int *directions) { if ((directions = malloc(sizeof(*directions) * 4)) == NULL) return (NULL); (directions)[Up] = 1; (directions)[Left] = 3; (directions)[Right] = 7; (directions)[Down] = 5; return (directions); } char *get_string(int dir) { int len; char *ans; len = get_pow(dir); if ((ans = malloc(sizeof(*ans) * (len + 2 + 14))) == NULL) return (NULL); sprintf(ans, "deplacement : %d\n", dir); return (ans); } int get_expulse_direction(t_clientIA *expulsed, t_clientIA *player, t_zappy *server) { Uint tmpx; Uint tmpy; int cnt; int dir; dir = expulsed->direction; cnt = 0; while (cnt < 4) { tmpx = correct_x(expulsed->x + expulsed->x_moves[get_left(dir)], server); tmpy = correct_y(expulsed->y + expulsed->y_moves[get_left(dir)], server); if (tmpx == player->x && tmpy == player->y) return (dir); cnt += 1; } return (dir); } char *get_ans(t_clientIA *expulsed, t_clientIA *player, t_zappy *server) { int *directions; int dir; directions = NULL; if ((directions = init_directions(directions)) == NULL) return (NULL); dir = get_expulse_direction(expulsed, player, server); printf("Player (expulsing) : x = %d\ty = %d\tdir = %d\n", player->x, player->y, player->direction); printf("Player (expulsed) : x = %d\ty = %d\tdir = %d\n", expulsed->x, expulsed->y, expulsed->direction); printf("Expulsion dir is : %d\n", dir); free(directions); return (get_string(dir)); } int expulse(t_zappy *server, t_clientIA *client, char *cmd) { t_node *node; double frequency; (void)cmd; frequency = ((double)7.0f / server->delay); client->lastAction = get_tick(frequency); node = server->map->map[correct_y(client->y, server)][correct_x(client->x, server)]->players->head; server->currentRessource = client; if (!put_in_list(server->listWrite, create_gui_ans(tograph_pex(server), client->lastAction))) return (1); if (set_all(server, client, node)) return (1); client->write = true; copy_in_buff("ok\n", client->buff_write); return (0); } <file_sep>#include <iostream> #include <string> #include "Case.hpp" #include "Player.hpp" #include "Settings.hpp" #include "Color.hpp" Case::Case(unsigned int nx, unsigned int ny): m_x(nx), m_y(ny) { int shapeSize = 25; m_shape.setSize(sf::Vector2f(shapeSize,shapeSize)); m_shape.setPosition(m_x * shapeSize + (3 * m_x) , m_y * shapeSize + (3 * m_y)); m_shape.setFillColor(Color::Case); _ressources[Nourriture] = 0; _ressources[Linemate] = 0; _ressources[Deraumere] = 0; _ressources[Sibur] = 0; _ressources[Mendiane] = 0; _ressources[Phiras] = 0; _ressources[Thystame] = 0; _incantation = false; _incLvl = 0; _incSucceed = false; } Case::~Case() { } unsigned int Case::getX() const { return m_x; } unsigned int Case::getY() const { return m_y; } sf::RectangleShape Case::getShape() const { return m_shape; } void Case::setX(unsigned int x) { m_x = x; } void Case::setY(unsigned int y) { m_y = y; } bool Case::getIncSucceed() const { return (_incSucceed); } void Case::setIncantParam(bool is, unsigned int lvl, bool suc) { _incantation = is; _incLvl = lvl; _incSucceed = suc; } bool Case::getIncantationIsSet() const { return (_incantation); } unsigned int Case::getIncLvl() const { return (_incLvl); } void Case::focusShape() { m_shape.setFillColor(Color::CaseFocus); } void Case::unFocusShape() { m_shape.setFillColor(Color::Case); } void Case::setRessources(eRessources res, unsigned int nbr) { _ressources[res] = nbr; } std::map<eRessources, unsigned int> & Case::getRessources() { return _ressources; } void Case::updateIncLevel() { if (_incLvl > Settings::RotationMaxIncantation) _incLvl = 0; else _incLvl += Settings::SpeedIncantation; } unsigned int Case::getIncRotation() const { return _incLvl; }<file_sep>#ifndef LOGIN_HPP__ # define LOGIN_HPP__ #include <tuple> #include <SFML/Graphics.hpp> class Login { public: typedef enum e_direction { SUP, SDOWN } e_direction; Login(sf::RenderWindow &); ~Login(); public: void getCredentials(std::string &, std::string &); private: sf::RenderWindow & m_window; std::string m_ip; std::string m_port; const std::vector<std::string> m_affichage = { "IP :", "Port :" }; unsigned int m_position; std::vector<sf::Vector2f> m_rect_position; std::vector< std::tuple<sf::Vector2f, sf::Vector2f, sf::Color> > m_rects; private: bool _events(std::string &, std::string &); void _updatePosition(e_direction); void _display(); void _displayUserInputs(); void _displayStrings(); void _displayBackground(); void _retrieveChar(sf::Event &); std::string & _getStringFromPosition(); void _moveCursor(sf::Event &); }; #endif // EOF - Login.hpp<file_sep>/* ** display_info.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:50:29 2014 courtu_r ** Last update Sun Jul 13 19:38:12 2014 courtu_r */ #include <sys/time.h> #include <stdlib.h> #include "zappy.h" #define LISTEN "Listening on port %d...\n" #define CONF "Configuration : Max(%d) WordX(%d) WorldY(%d) Delay(%d)\n" #define NAME_TEAM "\tName(%s) Max(%d)\n" static int print_info_team(t_zappy *server, t_node *node, t_type type, int *ret); int display_info(t_zappy *server) { printf("%s", get_color_term(SERVER)); printf(LISTEN, server->port); printf(CONF, server->nbClients, server->width, server->height, server->delay); printf("Teams :\n"); iter(server->listTeam, server, print_info_team); printf("Server is ready !!!%s\n", get_color_term(DISABLE)); return (0); } static int print_info_team(t_zappy *server, t_node *node, t_type type, int *ret) { t_team *team; (void)ret; (void)server; if (type != TEAM) return (1); team = ((t_team*)node->data); printf(NAME_TEAM, team->name, team->nb_slots_max); return (0); } void print_time_param(double time) { TIMEVAL tv; tv.tv_sec = time / 1000000.0f; while (time > 10000000000.0f) time -= 10000000000.0f; while (time > 100000000.0f) time -= 100000000.0f; while (time > 1000000.0f) time -= 1000000.0f; tv.tv_usec = time; printf("%d:%06d\n", ((int)tv.tv_sec), ((int)tv.tv_usec)); } int can_write_buffer(t_buff *buff) { char *tmp; tmp = (buff->begPtr); while (*tmp != '\n' && tmp != buff->endPtr) { tmp += 1; if (tmp > buff->buf + SIZE) tmp = buff->buf; } if (*tmp == '\n') return (1); else return (0); } void print_cmd_buffer(t_buff *buff) { char *tmp; tmp = (buff->begPtr); while (*tmp != '\n' && tmp != buff->endPtr) { printf("%c", *tmp); tmp += 1; if (tmp >= buff->buf + SIZE) tmp = buff->buf; } printf("\n"); } <file_sep> #include <stdio.h> #include "IA.hpp" bool key_inter = true; void signal_callback_handler(int) { key_inter = false; std::cout << "\rDisconnect." << std::endl; } void takeArgs(std::string & av1, std::string & av2, std::string & av3, char ** argv) { unsigned int i = 1; while (argv[i]) { if (std::string(argv[i]) == "-h") { if (argv[i + 1]) av1 = std::string(argv[i + 1]); } else if (std::string(argv[i]) == "-p") { if (argv[i + 1]) av2 = std::string(argv[i + 1]); } else if (std::string(argv[i]) == "-n") { if (argv[i + 1]) av3 = std::string(argv[i + 1]); } i += 1; } } int checkArgs(std::string & av2, std::string av3) { int i = 0; if (av2 == "") { std::cout << "Error : missing option -p." << std::endl; i = -1; } if (av3 == "") { std::cout << "Error : missing option -n." << std::endl; i = -1; } return i; } void runClient(Client & c, IA & ia) { unsigned int deb = 0; while (c.getRun() && key_inter) { if (c.canWrite() == true) { deb = 0; ia.setLvl(c.getLvl()); ia.choseCmdToSend(); } usleep(200); deb += 1; if (deb >= 70000) { c.setCanWrite(true); c.resetStat(); c.setNextCmd(Inventaire); } } c.close(); } int main(int argc, char ** argv) { std::string av1 = "127.0.0.1"; std::string av2 = ""; std::string av3 = ""; takeArgs(av1, av2, av3, argv); if (argc <= 1 || checkArgs(av2, av3) == -1) { std::cerr << "Usage: " << argv[0] << " [-h <host>] -p <port> -n <team_name>\n"; return 1; } try { char *p3 = new char[av3.length() + 1]; strcpy(p3, av3.c_str()); signal(SIGINT, signal_callback_handler); boost::asio::io_service io_service; tcp::resolver resolver(io_service); tcp::resolver::query query(av1, av2); tcp::resolver::iterator iterator = resolver.resolve(query); Client c(io_service, iterator, p3); c.setID(); IA ia(&c, av2); c.write_string(av3); c.write_string("\n"); boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service)); sleep(1); runClient(c, ia); t.detach(); delete [] p3; } catch (boost::exception & e) { std::cerr << "Stop : Boost Exception." << std::endl; return -1; } catch (std::exception & e) { std::cerr << "Exception : " << e.what() << std::endl; return -1; } catch (...) { std::cerr << "Boost Exception." << std::endl; return -1; } return 0; } <file_sep>#ifndef _UTILS_H_ # define _UTILS_H_ #include <stdbool.h> #include <stdarg.h> bool is_digit(char *); char *get_param(char *str); void *free_va_arg(int nbparam, ...); int parse_two_int(char *cmd, unsigned int *a1, unsigned int *a2); #endif <file_sep>#ifndef BROADCAST_H #define BROADCAST_H #include "zappy.h" typedef struct s_case t_case; typedef struct s_map t_map; typedef struct s_gui_answer { unsigned int tick; char *msg; }t_gui_answer; typedef struct s_broadcast { unsigned int noPlayer; char *msg; }t_broadcast; typedef struct s_ressourcePlayer { t_clientIA *clientIA; int noRessource; }t_ressourcePlayer; /* ** Result = 0 || 1 */ typedef struct s_incantation_ended { t_case *ncase; unsigned char result; }t_incantation_ended; typedef struct s_incantation_for_players { t_case *ncase; //Sur quelle case l'incantation commence t_list *listPlayer; //la liste des players qui sont sur la case t_clientIA *incanter; // T'as craque mon pauvre. Tu crois jvais faire un sort? // Jte files un t_clientIA * oui. //le premier doit etre celui quand lance l'incantation!! }t_incantation_for_players; t_gui_answer *create_gui_ans(char *, unsigned int); #endif <file_sep>/* ** release_node.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/struct ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:56:18 2014 ** Last update Sun Jul 13 15:56:19 2014 */ #include <stdlib.h> #include "utils.h" #include "zappy.h" static void free_for_ia(t_clientIA *ia); static void free_for_gui(t_clientGUI *gui); int release_node(t_node *node, t_type type) { t_clientIA *ia; t_clientGUI *gui; t_gui_answer *answer; if ((type == IA) && (ia = ((t_clientIA*)node->data))) free_for_ia(ia); else if ((type == GUI) && ((gui = ((t_clientGUI*)node->data)))) free_for_gui(gui); else if (type == PLAYER) { free(node); return (1); } else if (type == ANSWER) { if ((answer = ((t_gui_answer*)node->data))) free(answer->msg); } free_va_arg(2, node->data, node); return (0); } static void free_for_ia(t_clientIA *ia) { if (ia->buff_read) free_va_arg(2, ia->buff_read->buf, ia->buff_read); if (ia->buff_write) free_va_arg(2, ia->buff_write->buf, ia->buff_write); free_va_arg(2, ia->inventory, ia->big_write); } static void free_for_gui(t_clientGUI *gui) { release_list(gui->listWrite); if (gui->buff_read) free_va_arg(2, gui->buff_read->buf, gui->buff_read); if (gui->buff_write) free_va_arg(2, gui->buff_write->buf, gui->buff_write); } <file_sep>CC = g++ -Wall -Wextra -fstack-protector -fstack-protector-all -Wstack-protector -std=c++11 -O3 DIR_SRC = ./sources/ CXXFLAGS += -I./includes CXXFLAGS += -I$(DIR_SRC)app/ CXXFLAGS += -I$(DIR_SRC)login/ CXXFLAGS += -I$(DIR_SRC)texture_manager/ CXXFLAGS += -I$(DIR_SRC)view/ CXXFLAGS += -I$(DIR_SRC)sfmltools/ CXXFLAGS += -I$(DIR_SRC)collision/ CXXFLAGS += -I$(DIR_SRC)color/ CXXFLAGS += -I$(DIR_SRC)panel_team/ CXXFLAGS += -I$(DIR_SRC)panel_time/ CXXFLAGS += -I$(DIR_SRC)settings/ CXXFLAGS += -I$(DIR_SRC)zappy/ CXXFLAGS += -I$(DIR_SRC)zappy/map/ CXXFLAGS += -I$(DIR_SRC)zappy/map/case/ CXXFLAGS += -I$(DIR_SRC)zappy/player/ CXXFLAGS += -I$(DIR_SRC)zappy/team/ CXXFLAGS += -I$(DIR_SRC)zappy/egg/ LDFLAGS = -L /usr/local/lib/ -lsfml-graphics -lsfml-window -lsfml-system -lpthread -lsfml-audio RM = rm -f NAME = zappy_gui SRCS = $(DIR_SRC)main.cpp \ $(DIR_SRC)app/App.cpp \ $(DIR_SRC)login/Login.cpp \ $(DIR_SRC)settings/Settings.cpp \ $(DIR_SRC)texture_manager/TextureManager.cpp \ $(DIR_SRC)view/View.cpp \ $(DIR_SRC)view/ViewFPTR.cpp \ $(DIR_SRC)view/ViewFPTRCase.cpp \ $(DIR_SRC)zappy/Zappy.cpp \ $(DIR_SRC)collision/CollisionEngine.cpp \ $(DIR_SRC)color/Color.cpp \ $(DIR_SRC)zappy/map/Map.cpp \ $(DIR_SRC)zappy/map/case/Case.cpp \ $(DIR_SRC)zappy/player/Player.cpp \ $(DIR_SRC)sfmltools/SFMLMouseEvent.cpp \ $(DIR_SRC)reception/Reception.cpp \ $(DIR_SRC)reception/FileDescr.cpp \ $(DIR_SRC)reception/Socket.cpp \ $(DIR_SRC)reception/CircularBuffer.cpp \ $(DIR_SRC)reception/Treatment.cpp \ $(DIR_SRC)zappy/team/Team.cpp \ $(DIR_SRC)zappy/egg/Egg.cpp \ $(DIR_SRC)panel_team/PanelTeam.cpp \ $(DIR_SRC)panel_time/PanelTime.cpp \ OBJS = $(SRCS:.cpp=.o) %.o: %.cpp @$(CC) -c $^ -o $@ $(CXXFLAGS) @printf " \033[32m[Compilation]\033[39m %s\n" $< all: $(NAME) $(NAME): $(OBJS) @printf " \033[32m[Compilation des .o]\033[39m %s\n" @$(CC) -o $(NAME) $(OBJS) $(LDFLAGS) @printf " \033[32m[Compilation terminée avec succès]\033[39m %s\n" clean: @printf " \033[31m[Suppression des .o]\033[39m\n" @$(RM) $(OBJS) fclean: clean @printf " \033[31m[Suppression du binaire : %s]\033[39m\n" $(NAME) @$(RM) $(NAME) re: fclean all test: fclean all $(RM) $(OBJS) <file_sep>/* ** inventory.h for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ZappyTitou/map ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Mon Jun 23 14:10:36 2014 courtu_r ** Last update Sat Jul 12 15:39:47 2014 courtu_r */ #ifndef INVENTORY_H__ # define INVENTORY_H__ typedef struct s_egg t_egg; typedef struct s_client_ia t_clientIA; typedef struct s_zappy t_zappy; /*Variable defines*/ #define MAX_RESOURCES 5 #define MIN_RESOURCES 1 typedef unsigned int Uint; typedef enum resource { Food, Linemate, Deraumere, Sibur, Mendiane, Phiras, Thystame }e_resource; typedef struct s_inventory { unsigned int content[7]; }t_inventory; /*Prototypes for files using inventory.c*/ char *get_inventory(t_inventory *); t_inventory *random_init(t_inventory *inventory); t_inventory *init_inventory(t_inventory *); // If t_inventory is NULL, will be allocated. int get_length(t_inventory *); int get_pow(int); int add_resource(e_resource, Uint, t_inventory *); // Returns zero on success int del_resource(e_resource, Uint, t_inventory *); // returns 1 in case of error. int decrement_food(t_clientIA *, t_inventory *, t_zappy *, t_egg *); int get_nb_resource(e_resource, t_inventory *); void print_inventory(t_inventory *); void new_client_spawn_food(t_zappy *); void timer_spawn_food(t_zappy *); #endif /*INVENTORY*/ <file_sep>#ifndef TEXTURE_MANAGER_HPP__ # define TEXTURE_MANAGER_HPP__ #include <SFML/Graphics.hpp> #include <map> #include <vector> typedef enum e_texture { LOGIN_SCREEN = 0 , PLAYER_SPRITE , BIG_PLAYER , BIG_CASE , EGG_SMALL , EGG_SMALL_CRACK , SUN_SMALL , BACKGROUND , ARROW_UP , ARROW_DOWN , ARROW_LEFT , ARROW_RIGHT , ARROW_UP_SMALL , ARROW_DOWN_SMALL , } e_texture; class TextureManager { public: static TextureManager& Instance(); const sf::Texture & getTexture(const e_texture); const sf::Font & getFont(); private: TextureManager& operator= (const TextureManager&); TextureManager(const TextureManager&){} TextureManager(); ~TextureManager(); static TextureManager m_instance; private: std::map<e_texture, sf::Texture> m_textures; sf::Font m_font; }; const std::string ASSETS_PATH = "./assets/"; const std::map<std::string, e_texture> TEXTURES_PATH = { { ASSETS_PATH + "login_screen.png" , LOGIN_SCREEN }, { ASSETS_PATH + "sprite.png" , PLAYER_SPRITE }, { ASSETS_PATH + "big_player.png" , BIG_PLAYER }, { ASSETS_PATH + "big_case.png" , BIG_CASE }, { ASSETS_PATH + "egg.png" , EGG_SMALL }, { ASSETS_PATH + "egg_crack.png" , EGG_SMALL_CRACK }, { ASSETS_PATH + "sun.png" , SUN_SMALL }, { ASSETS_PATH + "background.png" , BACKGROUND }, { ASSETS_PATH + "arrow_up.png" , ARROW_UP }, { ASSETS_PATH + "arrow_down.png" , ARROW_DOWN }, { ASSETS_PATH + "arrow_left.png" , ARROW_LEFT }, { ASSETS_PATH + "arrow_right.png" , ARROW_RIGHT }, { ASSETS_PATH + "arrow_up_small.png" , ARROW_UP_SMALL }, { ASSETS_PATH + "arrow_down_small.png" , ARROW_DOWN_SMALL } }; #endif<file_sep>#ifndef _LIST_H_ # define _LIST_H_ #include <stdbool.h> typedef struct s_zappy t_zappy; typedef enum e_type { CONN, IA, GUI, TEAM, PLAYER, CHAR, EGG, WRITE, ANSWER } t_type; typedef struct s_node { void *data; struct s_node *next; struct s_node *prev; } t_node; typedef struct s_list { unsigned int length; t_type type; t_node *head; t_node *end; } t_list; int release_node(t_node *node, t_type type); t_list *create_list(t_type type); // Init list avec le type; t_node *rm_node(t_list *list, t_node *node); // rm node : params : list courante, node concerne. bool put_in_list(t_list *list, void *data); // list et data t_node *rm_node(t_list *list, t_node *node); int release_list(t_list *list); int iter_routine_next(t_list *list, t_zappy *s, t_node *(*p_func)(t_zappy*, t_node*, t_type, int *)); int iter(t_list *list, t_zappy *s, int (*p_func)(t_zappy *, t_node *, t_type, int *)); int iter_list_ret_next(t_list *list, int init, t_node *(*func)(t_list *l, t_node*, t_type, int *)); #endif <file_sep>/* ** alloc_egg.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/egg ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:55:10 2014 ** Last update Sun Jul 13 15:55:11 2014 */ #include <stdlib.h> #include "zappy.h" typedef unsigned int uint; t_egg *alloc_egg(uint id, t_clientIA *client) { t_egg *ret; if (client == NULL) return (NULL); if (!(ret = malloc(sizeof(*ret)))) return (NULL); ret->id = id; ret->x = client->x; ret->y = client->y; ret->team = client->team; ret->player = client; ret->active = false; ret->tick = 0.0f; return (ret); } <file_sep>/* ** serv_to_gui.c for communications in /home/titouan/Dropbox/Bomberman/blowshitup/ServerZappy/server/communications ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sun Jul 13 13:18:37 2014 <NAME> ** Last update Sun Jul 13 14:17:43 2014 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "tograph.h" #include "broadcast.h" #include "list.h" int getPlayerId(t_clientIA *player) { return (player->id); } void writeClient(char *buffer, t_node *clientIA, t_clientIA *incanter, t_list *l) { while (clientIA != NULL) { if ((((t_clientIA*)clientIA->data) != incanter)) { snprintf(buffer, SIZE_BUFF, " %d", getPlayerId(((t_clientIA*)clientIA->data))); put_in_list(l, strdup(buffer)); } clientIA = (t_node*)clientIA->next; } put_in_list(l, strdup("\n")); } /* ** currentRessource = t_incantation_for_players */ char *tograph_pic(t_zappy *z) { char buffer[SIZE_BUFF]; t_list *l; t_node *clientIA; t_clientIA *incanter; l = create_list(CHAR); clientIA = ((t_incantation_for_players*)z->currentRessource) ->listPlayer->head; incanter = ((t_incantation_for_players*)z->currentRessource)->incanter; snprintf(buffer, SIZE_BUFF, "pic %u %u %d %d", ((t_incantation_for_players*)z->currentRessource)->ncase->pos_x, ((t_incantation_for_players*)z->currentRessource)->ncase->pos_y, incanter->level, getPlayerId(incanter)); put_in_list(l, strdup(buffer)); writeClient(buffer, clientIA, incanter, l); return (concatList(l)); } /* ** currentRessource must be a s_clientIA */ char *tograph_pin(t_zappy *z) { char buffer[SIZE_BUFF]; t_clientIA *player; player = (t_clientIA*)z->currentRessource; snprintf(buffer, SIZE_BUFF, "pin %d %u %u %u %u %u %u %u %u %u\n", getPlayerId(player), player->x, player->y, player->inventory->content[0] / 126, player->inventory->content[1], player->inventory->content[2], player->inventory->content[3], player->inventory->content[4], player->inventory->content[5], player->inventory->content[6]); return (strdup(buffer)); } <file_sep>#include <iostream> #include <string> #include "SFMLMouseEvent.hpp" SFMLMouseEvent::SFMLMouseEvent(): mouseClicked(false) { } SFMLMouseEvent::~SFMLMouseEvent() { } void SFMLMouseEvent::update(sf::RenderWindow & window, sf::Event event) { mouseEvent = event; mouseClicked = false; if (event.type == sf::Event::MouseButtonPressed) { if (event.mouseButton.button == sf::Mouse::Left) { sf::Vector2i pixelPos = sf::Mouse::getPosition(window); _x = pixelPos.x; _y = pixelPos.y; mouseClicked = true; } } } bool SFMLMouseEvent::isMouseClicked() const { return mouseClicked; } int SFMLMouseEvent::getX() const { return _x; } int SFMLMouseEvent::getY() const { return _y; } void SFMLMouseEvent::reset() { mouseClicked = false; }<file_sep>#ifndef CIRCULARBUFFER_HPP_ #define CIRCULARBUFFER_HPP_ #include <string> #include <boost/circular_buffer.hpp> class CircularBuffer { boost::circular_buffer<char> _buf; public: CircularBuffer(unsigned int); ~CircularBuffer() {}; void pushString(std::string const &); bool getFirstString(std::string &); bool isEmpty() const; bool isFull() const; unsigned int sizeEmpty() const; }; #endif <file_sep> #include "Client.hpp" bool Client::inventaireChecker() const { bool (Client::*fn_ptr[7])() const; fn_ptr[0] = &Client::inventaireCheckerLvl1; fn_ptr[1] = &Client::inventaireCheckerLvl2; fn_ptr[2] = &Client::inventaireCheckerLvl3; fn_ptr[3] = &Client::inventaireCheckerLvl4; fn_ptr[4] = &Client::inventaireCheckerLvl5; fn_ptr[5] = &Client::inventaireCheckerLvl6; fn_ptr[6] = &Client::inventaireCheckerLvl7; if (this->lvl > 0 && this->lvl < 8) return (this->*fn_ptr[this->lvl - 1])(); return false; } bool Client::inventaireCheckerLvl1() const { const Inventory inv = this->getInventory(); if (inv.linemate >= 1) return true; return false; } bool Client::inventaireCheckerLvl2() const { const Inventory inv = this->getInventory(); if (inv.linemate >= 1 && inv.deraumere >= 1 && inv.sibur >= 1) return true; return false; } bool Client::inventaireCheckerLvl3() const { const Inventory inv = this->getInventory(); if (inv.linemate >= 2 && inv.phiras >= 2 && inv.sibur >= 1) return true; return false; } bool Client::inventaireCheckerLvl4() const { const Inventory inv = this->getInventory(); if (inv.linemate >= 1 && inv.deraumere >= 1 && inv.sibur >= 2 && inv.phiras >= 1) return true; return false; } bool Client::inventaireCheckerLvl5() const { const Inventory inv = this->getInventory(); if (inv.linemate >= 1 && inv.deraumere >= 2 && inv.sibur >= 1 && inv.mendiane >= 3) return true; return false; } bool Client::inventaireCheckerLvl6() const { const Inventory inv = this->getInventory(); if (inv.linemate >= 1 && inv.deraumere >= 2 && inv.sibur >= 3 && inv.phiras >= 1) return true; return false; } bool Client::inventaireCheckerLvl7() const { const Inventory inv = this->getInventory(); if (inv.linemate >= 2 && inv.deraumere >= 2 && inv.sibur >= 2 && inv.mendiane >= 2 && inv.phiras >= 2 && inv.thystame >= 1) return true; return false; } void Client::rdxForIncantation() { void (Client::*fn_ptr[7])(); fn_ptr[0] = &Client::rdxForIncantationLvl1; fn_ptr[1] = &Client::rdxForIncantationLvl2; fn_ptr[2] = &Client::rdxForIncantationLvl3; fn_ptr[3] = &Client::rdxForIncantationLvl4; fn_ptr[4] = &Client::rdxForIncantationLvl5; fn_ptr[5] = &Client::rdxForIncantationLvl6; fn_ptr[6] = &Client::rdxForIncantationLvl7; if (this->lvl > 0 && this->lvl < 8) (this->*fn_ptr[this->lvl - 1])(); } void Client::rdxForIncantationLvl1() { this->nextCmd = Voir; this->onFarm = false; } void Client::rdxForIncantationLvl2() { this->onFarm = false; if (this->lastSaw.size() > 0 && this->lastSaw[0] && this->lastSaw[0]->player >= 2) { this->waitingMore = false; this->nextCmd = Voir; } else { this->waitingMore = true; if (this->enoughFollowers() == false) this->nextCmd = RFI; else this->nextCmd = Voir; } } void Client::rdxForIncantationLvl3() { this->onFarm = false; if (this->lastSaw.size() > 0 && this->lastSaw[0] && this->lastSaw[0]->player >= 2) { this->waitingMore = false; this->nextCmd = Voir; } else { this->waitingMore = true; if (this->enoughFollowers() == false) this->nextCmd = RFI; else this->nextCmd = Voir; } } void Client::rdxForIncantationLvl4() { this->onFarm = false; if (this->lastSaw.size() > 0 && this->lastSaw[0] && this->lastSaw[0]->player >= 4) { this->waitingMore = false; this->nextCmd = Voir; } else { this->waitingMore = true; if (this->enoughFollowers() == false) this->nextCmd = RFI; else this->nextCmd = Voir; } } void Client::rdxForIncantationLvl5() { this->onFarm = false; if (this->lastSaw.size() > 0 && this->lastSaw[0] && this->lastSaw[0]->player >= 4) { this->waitingMore = false; this->nextCmd = Voir; } else { this->waitingMore = true; if (this->enoughFollowers() == false) this->nextCmd = RFI; else this->nextCmd = Voir; } } void Client::rdxForIncantationLvl6() { this->onFarm = false; if (this->lastSaw.size() > 0 && this->lastSaw[0] && this->lastSaw[0]->player >= 6) { this->waitingMore = false; this->nextCmd = Voir; } else { this->waitingMore = true; if (this->enoughFollowers() == false) this->nextCmd = RFI; else this->nextCmd = Voir; } } void Client::rdxForIncantationLvl7() { this->onFarm = false; if (this->lastSaw.size() > 0 && this->lastSaw[0] && this->lastSaw[0]->player >= 6) { this->waitingMore = false; this->nextCmd = Voir; } else { this->waitingMore = true; if (this->enoughFollowers() == false) this->nextCmd = RFI; else this->nextCmd = Voir; } } void Client::getMyNum(std::string & str) { unsigned int i = 0; while (str[i] >= '0' && str[i] <= '9') i += 1; str[i] = 0; } bool Client::enoughFollowers() const { bool (Client::*fn_ptr[7])() const; fn_ptr[0] = &Client::enFolloLvl1; fn_ptr[1] = &Client::enFolloLvl2; fn_ptr[2] = &Client::enFolloLvl3; fn_ptr[3] = &Client::enFolloLvl4; fn_ptr[4] = &Client::enFolloLvl5; fn_ptr[5] = &Client::enFolloLvl6; fn_ptr[6] = &Client::enFolloLvl7; if (this->lvl > 0 && this->lvl < 8) return (this->*fn_ptr[this->lvl - 1])(); return false; } bool Client::enFolloLvl1() const { return true; } bool Client::enFolloLvl2() const { if (this->followers.size() >= 1) return true; return false; } bool Client::enFolloLvl3() const { if (this->followers.size() >= 1) return true; return false; } bool Client::enFolloLvl4() const { if (this->followers.size() >= 3) return true; return false; } bool Client::enFolloLvl5() const { if (this->followers.size() >= 3) return true; return false; } bool Client::enFolloLvl6() const { if (this->followers.size() >= 5) return true; return false; } bool Client::enFolloLvl7() const { if (this->followers.size() >= 5) return true; return false; } <file_sep>#ifndef _TEAM_H # define _TEAM_H typedef struct s_team { char name[32]; unsigned int nb_slots_max; unsigned int length; unsigned int nbplayers; } t_team; #endif <file_sep>/* ** circular_buffer.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/struct ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:55:55 2014 ** Last update Sun Jul 13 17:50:57 2014 courtu_r */ #include <stdio.h> #include <stdlib.h> #include "zappy.h" #include "circular_buffer.h" t_buff *alloc_buff() { t_buff *buff; if ((buff = malloc(sizeof(*buff))) == NULL) { fprintf(stderr, "Malloc has failed in init_buff()\n"); return (NULL); } buff->buf = malloc(sizeof(*(buff->buf)) * (SIZE + 1)); if (!(buff->buf)) { fprintf(stderr, "Malloc has failed in init_buff()\n"); return (NULL); } bzero((buff->buf), SIZE + 1); buff->begPtr = buff->buf; buff->endPtr = buff->buf; buff->readCnt = 0; buff->writeCnt = 0; return (buff); } int write_in_buff(int fd, t_buff *buff, bool display, int id) { Uint nbreads; Uint sizeLeft; sizeLeft = check_size(buff); if ((nbreads = read(fd, (buff->endPtr), sizeLeft)) <= 0) return (nbreads); buff->writeCnt += nbreads; buff->endPtr += nbreads; if (buff->endPtr >= buff->buf + SIZE) buff->endPtr = buff->buf; if (display && can_write_buffer(buff)) { printf("%s", get_color_term(RECV)); print_time(); printf("Received message from %d: ", id); print_cmd_buffer(buff); printf("%s", get_color_term(DISABLE)); fflush(stdout); } return (nbreads); } char *try_get_cmd(t_buff *buff) { char *tmp; tmp = (buff->begPtr); while (*tmp != '\n' && tmp != buff->endPtr) { tmp += 1; if (tmp >= buff->buf + SIZE) tmp = buff->buf; } if (*tmp != '\n') return (NULL); else return (get_cmd_from_buff(buff)); } char *finish_treating(t_buff **buff, char *str, int cnt) { if (str) { str[cnt++] = '\n'; str[cnt] = 0; } (*(*buff)->begPtr) = 0; (*buff)->begPtr += 1; if ((*buff)->begPtr >= (*buff)->buf + SIZE) (*buff)->begPtr = (*buff)->buf; (*buff)->readCnt += 1; return (str); } char *get_cmd_from_buff(t_buff *buff) { char *str; Uint cnt; char *keepBeg; cnt = 0; keepBeg = buff->begPtr; str = NULL; while (*((buff)->begPtr) != '\n' && (buff->readCnt) < buff->writeCnt) { if ((str = realloc(str, sizeof(*str) * (3 + cnt))) == NULL) { fprintf(stderr, "Malloc has failed\n"); return (NULL); } str[cnt] = (*buff->begPtr); cnt += 1; buff->readCnt += 1; (buff->begPtr) += 1; if (buff->begPtr >= buff->buf + SIZE) buff->begPtr = buff->buf; } if (!check_str(buff, str, keepBeg, cnt)) return (NULL); return (finish_treating(&buff, str, cnt)); } <file_sep>#include <iostream> #include "CollisionEngine.hpp" /* pt vs pt */ bool CollisionEngine::pointVSPoint(sf::Vector2f & obj1, sf::Vector2f & obj2) { if (obj1.x == obj2.x && obj1.y == obj2.y) return true; return false; } /* pt vs rectangle shape */ bool CollisionEngine::pointVSshape( sf::RenderWindow &window, sf::RectangleShape shape, int x, int y) { sf::FloatRect boundingBox = shape.getGlobalBounds(); sf::Vector2f point; point = window.mapPixelToCoords(sf::Vector2i(x,y)); if (boundingBox.contains(point)) return true; return false; } /* pt vs sprite */ bool CollisionEngine::pointVSsprite( sf::RenderWindow &window, sf::Sprite sprite, int x, int y) { sf::FloatRect boundingBox = sprite.getGlobalBounds(); sf::Vector2f point; point = window.mapPixelToCoords(sf::Vector2i(x,y)); if (boundingBox.contains(point)) return true; return false; }<file_sep>/* ** right.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sat Jul 12 12:26:31 2014 courtu_r ** Last update Sun Jul 13 21:25:30 2014 courtu_r */ #include "zappy.h" int call_ppo(t_zappy *, t_clientIA *); int right(t_zappy *server, t_clientIA *client, char *cmd) { double frequency; (void)cmd; frequency = ((double)7.0f / server->delay); client->lastAction = get_tick(frequency); if (client->direction < Left) client->direction += 1; else client->direction = Up; copy_in_buff("ok\n", client->buff_write); client->write = true; if (call_ppo(server, client)) return (1); return (0); } <file_sep>/* ** see_utils4.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sun Jul 13 16:44:55 2014 courtu_r ** Last update Sun Jul 13 16:48:01 2014 courtu_r */ #include <string.h> #include "proto.h" #include "zappy.h" void init_int_var_left_right(int * width, int * depth, int * cnt) { (*width) = 1; (*depth) = 0; (*cnt) = 0; } char *get_up_down(t_zappy *server, char *msg, t_clientIA *player) { int width; int depth; int tmpX; int tmpY; int nbcases; int cnt; nbcases = get_nb_cases(player->level); init_int_var_left_right(&width, &depth, &cnt); init_pos_player_left_right(&tmpX, &tmpY, player); while (depth <= player->level) { while (cnt < width) { if ((msg = serialize_case(server->map->map[tmpY] [correct_x(tmpX, server)], msg, server)) == NULL) return (NULL); if (f_cor_up_down(&nbcases, &cnt, &msg) == -1) return (NULL); f2_cor_up_down(&tmpX, player, server); } looping_left_right(&cnt, &width, &depth); f3_cor_up_down(&tmpX, player, server, width); tmpY = correct_y(tmpY + (player->y_moves[player->direction]), server); } return (msg); } void cor_saw_left_right(t_clientIA * player, int * tmpY, int width, t_zappy * server) { if (player->direction == Up) (*tmpY) = correct_y(player->y + (player-> y_moves[get_right(player->direction) ] * (width / 2)), server); else (*tmpY) = correct_y(player->y + (player-> y_moves[get_left(player->direction) ] * (width / 2)), server); } void f_cor_saw_left_right(t_clientIA * player, int * tmpY, t_zappy * server) { if (player->direction == Up) (*tmpY) = correct_y((*tmpY) + player-> y_moves[get_left(player->direction)], server); else (*tmpY) = correct_y((*tmpY) + player-> y_moves[get_right(player->direction)], server); } int mid_loop_left_right(int * nbcases, int * cnt, char **msg) { (*nbcases) -= 1; (*cnt) += 1; if ((*nbcases) > 0) { if (((*msg) = realloc((*msg), sizeof(**msg) * (strlen(*msg) + 2))) == NULL) return (-1); if (((*msg) = strcat((*msg), ",")) == NULL) return (-1); } return (0); } <file_sep>#ifndef _ZAPPY_H_ # define _ZAPPY_H_ #include <stdbool.h> #include "map.h" #include "list.h" #include "team.h" #include "egg.h" #include "types.h" #include "inventory.h" #include "clients.h" #include "tograph.h" #include "func_ia.h" #include "func_gui.h" #include "routines.h" #include "circular_buffer.h" #define HOME_GUI "GRAPHIC" #define NB_FUNC_IA 12 #define NB_FUNC_GUI 9 #define UNIT_TIME 126.0f typedef struct s_client_conn t_conn; typedef enum e_cmd_client_ia t_cmd_ia; typedef enum e_cmd_client_gui t_cmd_gui; typedef struct s_zappy { int nb_players[8]; t_inventory *incantation_requirements; char *resources[9]; unsigned int nbClients; unsigned int width; unsigned int height; unsigned int port; int delay; SOCKET listen; t_list *listConn; t_list *listTeam; t_list *listIA; t_list *listGUI; t_list *listEGG; fd_set readsd; fd_set writesd; fd_set exceptsd; TIMEVAL timeval; TIMEVAL timeActu; int max_sd; t_map *map; unsigned int max_id; int (*ptr_func_ia[NB_FUNC_IA + 1])(t_zappy *s, t_clientIA *c, char *cmd); int (*ptr_func_gui[NB_FUNC_GUI + 1])(t_zappy *s, t_clientGUI *c, char *cmd); void *currentRessource; t_list *listWrite; char *writeCmd; char *writeGui; bool game; } t_zappy; void print_time(void); double get_tick(double sec); char *_concatList(t_list *l); void print_time_param(double); int schedule(t_zappy *server); int connexion(t_zappy *server); t_clientGUI *alloc_clientGUI(SOCKET sd); int init_signal(t_zappy *server); t_cmd_ia find_cmd_ia(const char *cmd); const char *get_color_term(t_color col); t_cmd_gui find_cmd_gui(const char *cmd); int display_info(t_zappy *server); bool is_writed(t_zappy *s, int index); int can_write_buffer(t_buff *buff); void set_connect_nbr(t_zappy *server); bool create_socket_TCP(t_zappy *server); void add_socket_to_monitor(t_zappy *server); int release_memory(t_zappy *server, int ret); t_clientIA *alloc_clientIA(t_team *team, SOCKET sd); int print_info(t_color color, const char *str); void do_fd_sets(t_zappy *s, t_clientGUI *client); t_clientIA *is_in_list_of_ia(t_list *list, t_team *team); t_team *is_in_list_of_team(t_list *list, const char *name); void send_buffer(t_clientIA *client, const char *buffer); t_clientIA *get_clientIA_by_index(t_list *list, unsigned int num); int choose_graphic_or_ia(t_zappy *s, t_conn *c, const char *buff); bool are_requirements_met(t_zappy *server, t_clientIA *client, bool first_check); void *free_va_arg(int, ...); t_inventory *init_inventories(t_zappy*); t_inventory *get_inventory_to_comp(int, t_zappy*); t_clientIA *is_in_list_egg(t_list *l, t_team *t, t_conn *c, t_zappy *s); void first_send_ia(t_clientIA *clientIA, t_zappy *s, t_team *team); void call_back_broadcast(t_zappy *server, t_clientIA *client); int choose_client(t_zappy *server, t_team *team, t_conn *c); int create_client_ia(t_zappy *s, t_conn* c, t_team *team); #endif <file_sep>## ## Makefile for in /home/remaud_c/Code/TPs/my_script/MyS ## ## Made by remaud_c ## Login <<EMAIL>> ## ## Started on Fri Feb 14 12:01:16 2014 remaud_c ## Last update Wed Jun 11 16:48:41 2014 courtu_r ## CC = g++ -W -Wall -std=c++0x LDFLAGS += -lboost_system -lboost_date_time -lboost_thread -lboost_serialization -lpthread -std=c++0x -W -Wall DIR = Code/ RM = rm -f NAME = clientIA SRCS = $(DIR)Client.cpp \ $(DIR)ClientChecker.cpp \ $(DIR)IA.cpp \ $(DIR)Inventory.cpp \ $(DIR)main.cpp OBJS = $(SRCS:.cpp=.o) %.o: %.cpp $(CC) -c $^ -o $@ $(CXXFLAGS) all: $(NAME) $(NAME): $(OBJS) $(CC) -o $(NAME) $(OBJS) $(LDFLAGS) clean: $(RM) $(OBJS) fclean: clean $(RM) $(NAME) re: fclean all test: fclean all $(RM) $(OBJS) <file_sep>#ifndef EXCEPT_HPP_ #define EXCEPT_HPP_ #include <stdexcept> #include <iostream> class Except : public std::exception { std::string error; public: Except(std::string const &str) { error = str; } ~Except() throw() {}; const char * what() const throw() { return (error.c_str()); } }; #endif <file_sep>#include <iostream> #include <string> #include "TextureManager.hpp" #include "Login.hpp" Login::Login(sf::RenderWindow & win) : m_window(win), m_position(0) { m_rect_position.push_back(sf::Vector2f(511,254)); m_rect_position.push_back(sf::Vector2f(512,383)); /* position, size, color */ auto matique = std::make_tuple(sf::Vector2f(511,254), sf::Vector2f(576,62), sf::Color(150, 50, 250, 0)); m_rects.push_back( matique ); matique = std::make_tuple(sf::Vector2f(512,383), sf::Vector2f(576,62), sf::Color(150, 50, 250, 0)); m_rects.push_back( matique ); matique = std::make_tuple(sf::Vector2f(707,511), sf::Vector2f(380,60), sf::Color(150,150,150,0)); m_rects.push_back( matique ); } Login::~Login() { } void Login::getCredentials(std::string & ip, std::string & port) { sf::Sprite background(TextureManager::Instance().getTexture(LOGIN_SCREEN)); while (m_window.isOpen()) { m_window.clear(); m_window.draw(background); if (!_events(ip, port)) return; _display(); } } bool Login::_events(std::string & ip, std::string & port) { sf::Event event; std::string str; sf::Text text; while (m_window.pollEvent(event)) { if (event.type == sf::Event::Closed) m_window.close(); if (m_position == 2 && event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Return) { /* try to connect to server */ ip = m_ip; port = m_port; return false; } _retrieveChar(event); _moveCursor(event); } return true; } void Login::_moveCursor(sf::Event & event) { if (event.type == sf::Event::KeyPressed) { switch (event.key.code) { case sf::Keyboard::Up: _updatePosition(SUP); break; case sf::Keyboard::Down: _updatePosition(SDOWN); break; default: break; } } } void Login::_retrieveChar(sf::Event & event) { if (event.type != sf::Event::TextEntered) return; if (event.text.unicode == 13) return; std::string & str = _getStringFromPosition(); if (m_position == 2) { return; } if (event.text.unicode < 128) { if (static_cast<char>(event.text.unicode) == '\b') { if (str.size() > 0) str.pop_back(); } else str += static_cast<char>(event.text.unicode); } } std::string & Login::_getStringFromPosition() { if (m_position == 0) return m_ip; return m_port; } void Login::_display() { _displayBackground(); _displayUserInputs(); _displayStrings(); m_window.display(); } void Login::_displayBackground() { sf::RectangleShape rectangle(sf::Vector2f(120, 50)); auto matique = m_rects[m_position]; std::get<1>(matique); rectangle.setPosition( std::get<0>(matique) ); rectangle.setSize( std::get<1>(matique) ); rectangle.setFillColor( std::get<2>(matique)); rectangle.setOutlineThickness(2); rectangle.setOutlineColor(sf::Color(250, 150, 100)); m_window.draw(rectangle); } void Login::_displayStrings() { unsigned int coefficient = 0; sf::Text text; sf::Vector2u winSize = m_window.getSize(); (void)winSize; text.setFont(TextureManager::Instance().getFont()); text.setColor(sf::Color(50,50,50)); text.setCharacterSize(45); for (auto &i : m_affichage) { text.setString(i); text.setPosition(sf::Vector2f(325,250 + coefficient * 130)); m_window.draw(text); coefficient += 1; } } void Login::_displayUserInputs() { sf::Text text; text.setFont(TextureManager::Instance().getFont()); text.setColor(sf::Color(50,50,50)); text.setCharacterSize(45); /* draw ip */ text.setString(m_ip); text.setPosition(525, 255); m_window.draw(text); /* draw port */ text.setString(m_port); text.setPosition(525, 383); m_window.draw(text); } void Login::_updatePosition(e_direction dir) { if (dir == SDOWN) { m_position += 1; if (m_position >= m_rects.size()) m_position = 0; } else { if (m_position > 0) m_position -= 1; else m_position = m_rects.size() - 1; } }<file_sep>/* ** schedule.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:50:00 2014 courtu_r ** Last update dim. juil. 13 19:14:49 2014 <NAME> */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <stdbool.h> #include <sys/time.h> #include <sys/types.h> #include "zappy.h" int schedule(t_zappy *server) { int activity; while (server->game) { server->timeval.tv_sec = 0; server->timeval.tv_usec = 5; add_socket_to_monitor(server); activity = select(server->max_sd + 1, &(server->readsd), &(server->writesd), &(server->exceptsd), &(server->timeval)); if ((activity == -1) && (errno != EINTR)) perror("Select failed. Error"); else { if (FD_ISSET(server->listen, &(server->readsd))) connexion(server); if (server->listIA->length > 0) iter_routine_next(server->listIA, server, &routine_clientIA); if (server->listGUI->length > 0) iter_routine_next(server->listGUI, server, &routine_clientGUI); if (server->listConn->length > 0) iter_routine_next(server->listConn, server, &routine_connexion); if (server->listEGG->length > 0) iter_routine_next(server->listEGG, server, &routine_egg); } } return (0); } <file_sep>#ifndef _FUNC_IA_H_ # define _FUNC_IA_H_ #include <stdio.h> #include "clients.h" #include "zappy.h" int see(t_zappy *server, t_clientIA *client, char *cmd); int left(t_zappy *server, t_clientIA *client, char *cmd); int move(t_zappy *server, t_clientIA *client, char *cmd); int _fork(t_zappy *server, t_clientIA *client, char *cmd); int right(t_zappy *server, t_clientIA *client, char *cmd); int put_obj(t_zappy *server, t_clientIA *client, char *cmd); int expulse(t_zappy *server, t_clientIA *client, char *cmd); int take_obj(t_zappy *server, t_clientIA *client, char *cmd); int broadcast(t_zappy *server, t_clientIA *client, char *cmd); int inventory(t_zappy *server, t_clientIA *client, char *cmd); int connect_nbr(t_zappy *server, t_clientIA *client, char *cmd); int incantation(t_zappy *server, t_clientIA *client, char *cmd); #endif <file_sep>#include "Reception.hpp" #include <iostream> #include <unistd.h> Reception::Reception(Socket &com, Zappy &data) : _comm(com), _buf(2048), _data(data) { } Reception::~Reception() { } void Reception::threadLaunch(Reception *recep) { recep->launch(); } void Reception::setFuncPointer() { _tabCommand[0] = &Treatment::doMsz; _tabCommand[1] = &Treatment::doBct; _tabCommand[2] = &Treatment::doTna; _tabCommand[3] = &Treatment::doPnw; _tabCommand[4] = &Treatment::doPpo; _tabCommand[5] = &Treatment::doPlv; _tabCommand[6] = &Treatment::doPin; _tabCommand[7] = &Treatment::doPex; _tabCommand[8] = &Treatment::doPbc; _tabCommand[9] = &Treatment::doPic; _tabCommand[10] = &Treatment::doPie; _tabCommand[11] = &Treatment::doPfk; _tabCommand[12] = &Treatment::doPdr; _tabCommand[13] = &Treatment::doPgt; _tabCommand[14] = &Treatment::doPdi; _tabCommand[15] = &Treatment::doEnw; _tabCommand[16] = &Treatment::doEht; _tabCommand[17] = &Treatment::doEbo; _tabCommand[18] = &Treatment::doEdi; _tabCommand[19] = &Treatment::doSgt; _tabCommand[20] = &Treatment::doSeg; _tabCommand[21] = &Treatment::doSmg; _tabCommand[22] = &Treatment::doSuc; _tabCommand[23] = &Treatment::doSbp; } void Reception::setCmdList() { _commandList.push_back("msz"); _commandList.push_back("bct"); _commandList.push_back("tna"); _commandList.push_back("pnw"); _commandList.push_back("ppo"); _commandList.push_back("plv"); _commandList.push_back("pin"); _commandList.push_back("pex"); _commandList.push_back("pbc"); _commandList.push_back("pic"); _commandList.push_back("pie"); _commandList.push_back("pfk"); _commandList.push_back("pdr"); _commandList.push_back("pgt"); _commandList.push_back("pdi"); _commandList.push_back("enw"); _commandList.push_back("eht"); _commandList.push_back("ebo"); _commandList.push_back("edi"); _commandList.push_back("sgt"); _commandList.push_back("seg"); _commandList.push_back("smg"); _commandList.push_back("suc"); _commandList.push_back("sbp"); } bool Reception::verifyData(std::string const &command) { unsigned int i = 0; while (i < _commandList.size()) { if (command.substr(0, 3) == _commandList[i]) { if ((_treat.*_tabCommand[i])(command, _data) == false) { std::cerr << _commandList[i] << " : Invalid parameter in the command receive from server" << std::endl; return (false); } else return (true); } i++; } std::cerr << "Unknown command receive from server" << std::endl; return (false); } void Reception::launch() { std::string str; std::string ret; setFuncPointer(); setCmdList(); while (42) { if (_buf.sizeEmpty() > 100) { str = _comm.readOnSocket(100); _buf.pushString(str); } if (!_buf.isEmpty()) { if (_buf.getFirstString(ret) == true) { if (ret.compare("BIENVENUE") == 0) _comm.writeOnSocket("GRAPHIC\n"); else verifyData(ret); } } usleep(10); } } <file_sep>/* ** bct.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/clientGUI ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:53:00 2014 ** Last update dim. juil. 13 16:36:07 2014 <NAME> */ #include <string.h> #include "utils.h" #include "zappy.h" #include "tograph.h" int bct(t_zappy *server, t_clientGUI *client, char *cmd) { unsigned int x; unsigned int y; char *send; if (parse_two_int(cmd, &x, &y)) { client->error = true; return (1); } if ((x >= server->width) || (y >= server->height)) client->error = true; else { server->currentRessource = ((void*)server->map->map[y][x]); send = tograph_bct(server); if (send) { copy_in_buff(send, client->buff_write); free(send); client->write = true; } } return (0); } <file_sep>/* ** serv_to_gui_5.c for communications in /home/titouan/Dropbox/Bomberman/blowshitup/ServerZappy/server/communications ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sun Jul 13 13:20:05 2014 Titouan Creach ** Last update Sun Jul 13 13:20:05 2014 Titouan Creach */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "tograph.h" #include "broadcast.h" #include "list.h" /* ** currentRessource must be a t_clientIA*) */ char *tograph_plv(t_zappy *z) { char buffer[SIZE_BUFF]; t_clientIA *player; player = (t_clientIA*)z->currentRessource; snprintf(buffer, SIZE_BUFF, "plv %d %u\n", getPlayerId(player), player->level); return strdup(buffer); } /* ** don't care about currentRessource */ char *tograph_sgt(t_zappy *z) { char buffer[SIZE_BUFF]; snprintf(buffer, SIZE_BUFF, "sgt %d\n", z->delay); return strdup(buffer); } /* ** currentRessource must point to a struct s_clientIA* */ char *tograph_ppo(t_zappy *z) { char buffer[SIZE_BUFF]; t_clientIA *player; player = (t_clientIA*)z->currentRessource; snprintf(buffer, SIZE_BUFF, "ppo %d %d %d %d\n", getPlayerId(player), player->x, player->y, player->direction + 1); return (strdup(buffer)); } /* ** currentRessource must point to a char* */ char *tograph_smg(t_zappy *z) { char buffer[SIZE_BUFF]; snprintf(buffer, SIZE_BUFF, "smg %s\n", (char*)z->currentRessource); return strdup(buffer); } /* ** currentRessource must point to the winner's team */ char *tograph_seg(t_zappy *z) { char buffer[SIZE_BUFF]; snprintf(buffer, SIZE_BUFF, "seg %s\n", ((t_team*)z->currentRessource)->name); return strdup(buffer); } <file_sep>/* ** parse_arg_int.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/utils ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 16:07:40 2014 ** Last update dim. juil. 13 16:35:41 2014 <NAME> */ #include <string.h> #include <stdlib.h> #include "zappy.h" #include "utils.h" static unsigned int len_first(char *num); static int parse_second(char *cmd, char *arg1, unsigned int *a2); int parse_two_int(char *cmd, unsigned int *a1, unsigned int *a2) { char *arg1; char *arg2; arg2 = NULL; arg1 = get_param(cmd); if (a1) { *(a1) = atoi(arg1); if ((*(a1) == 0) && arg1[0] != '0') { free(arg1); return (1); } } if (parse_second(arg2, arg1, a2)) return (1); free_va_arg(2, arg1, arg2); return (0); } static int parse_second(char *arg2, char *arg1, unsigned int *a2) { unsigned int index; index = len_first(arg1); if (a2) { if (index == strlen(arg1)) { free(arg1); return (1); } arg2 = get_param(arg1); arg1[index] = '\0'; (*a2) = atoi(arg2); if (((*a2) == 0) && arg2[0] != '0') { free_va_arg(2, arg1, arg2); return (1); } } return (0); } static unsigned int len_first(char *num) { unsigned int ret; ret = 0; while (*(num++)) { if (*(num - 1) < '0' || *(num - 1) > '9') return (ret); else ++ret; } return (ret); } <file_sep>#ifndef MAP_HPP_ # define MAP_HPP_ #include <algorithm> #include <vector> #include <mutex> #include "Case.hpp" class Map { public: Map(); Map(unsigned int, unsigned int); ~Map(); Case * atCoords(unsigned int, unsigned int); std::vector<Case *> & getVectCase(); unsigned int getLength() const; unsigned int getWidth() const; void setMap(unsigned int, unsigned int); private: std::vector<Case *> m_map; unsigned int m_length; unsigned int m_width; std::mutex m_mutex; void _initialize_clear_map(); }; #endif <file_sep>/* ** mct.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/clientGUI ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:53:34 2014 ** Last update dim. juil. 13 16:36:20 2014 <NAME> */ #include "zappy.h" int mct(t_zappy *server, t_clientGUI *client, char *cmd) { t_gui_answer *answer; (void)cmd; answer = create_gui_ans(tograph_send_map(server), 0); put_in_list(client->listWrite, answer); return (0); } <file_sep>/* ** tna.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/clientGUI ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:54:56 2014 ** Last update dim. juil. 13 16:37:12 2014 <NAME> */ #include "zappy.h" int tna(t_zappy *server, t_clientGUI *client, char *cmd) { char *send; (void)cmd; send = tograph_tna(server); if (send) { copy_in_buff(send, client->buff_write); free(send); client->write = true; } return (0); } <file_sep>/* ** serv_to_gui_2.c for communications in /home/titouan/Dropbox/Bomberman/blowshitup/ServerZappy/server/communications ** ** Made by <NAME> ** Login <<EMAIL>> ** ** Started on Sun Jul 13 13:19:37 2014 Titouan Creach ** Last update Sun Jul 13 13:19:37 2014 Titouan Creach */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "tograph.h" #include "broadcast.h" #include "list.h" /* ** Concat char* list into a single char* ** /!\ this function FREE the list */ char *concatList(t_list *l) { size_t size; char *copy_addr; char *content; struct s_node *it; size = 0; content = NULL; it = l->head; while (it != NULL) { size += strlen((char*)it->data); content = realloc(content, sizeof(char) * (size + 1)); copy_addr = content + size - strlen((char*)it->data); strcpy(copy_addr, (char*)it->data); it = it->next; } release_list(l); return (content); } char *tograph_welcome_msg(t_zappy *z) { t_list *list; t_node *clientIA; t_node *egg; list = create_list(CHAR); put_in_list(list, tograph_msz(z)); put_in_list(list, tograph_sgt(z)); put_in_list(list, tograph_send_map(z)); put_in_list(list, tograph_tna(z)); clientIA = z->listIA->head; egg = z->listEGG->head; while (clientIA != NULL) { z->currentRessource = ((t_clientIA*)clientIA->data); put_in_list(list, tograph_pnw(z)); clientIA = (t_node*)clientIA->next; } while (egg != NULL) { z->currentRessource = ((t_egg*)egg->data); put_in_list(list, tograph_enw(z)); egg = (t_node*)egg->next; } return (concatList(list)); } /* ** currentRessource == OSEF */ char *tograph_msz(t_zappy *z) { char buffer[SIZE_BUFF]; t_map *map; map = z->map; snprintf(buffer, SIZE_BUFF, "msz %u %u\n", map->width, map->height); return strdup(buffer); } /* ** Don't care about currentRessource */ char *tograph_tna(t_zappy *z) { t_list *buffList; char buffer[SIZE_BUFF]; t_node *teams; buffList = create_list(CHAR); teams = (t_node*)z->listTeam->head; while (teams != NULL) { bzero(buffer, SIZE_BUFF); snprintf(buffer, SIZE_BUFF, "tna %s\n", ((t_team*)teams->data)->name); put_in_list(buffList, strdup(buffer)); teams = (t_node*)teams->next; } return (concatList(buffList)); } /* ** Don't care about currentRessource */ char *tograph_sbp(t_zappy *z) { IGNORE(z); return (strdup("sbp\n")); } <file_sep>#include "Player.hpp" #include "Settings.hpp" #include <sstream> Player::Player(int id, unsigned int x, unsigned int y): m_x(x), m_y(y), m_id(id), m_broadCastLevel(0) { _level = 0; _ressources[Nourriture] = 0; _ressources[Linemate] = 0; _ressources[Deraumere] = 0; _ressources[Sibur] = 0; _ressources[Mendiane] = 0; _ressources[Phiras] = 0; _ressources[Thystame] = 0; _currentAction = Nothing; _broadCastMsg = ""; _incantationParam.push_back(0); _incantationParam.push_back(0); _incantationParam.push_back(0); _currentStat = Not; } Player::~Player() { } std::string const &Player::getStringAction() { if (_currentAction == Nothing) _strCurAction = "Nothing"; else if (_currentAction == Expulse) _strCurAction = "Expulse"; else if (_currentAction == Broadcast) _strCurAction = "Broadcast"; else if (_currentAction == IncantationLaunch) _strCurAction = "Launch Incantation"; else if (_currentAction == Fork) _strCurAction = "Fork"; else if (_currentAction == PutRessources) _strCurAction = "Put a ressource"; else if (_currentAction == GetRessources) _strCurAction = "Get a ressource"; return _strCurAction; } void Player::demandInventory(Socket *sock) { std::string str; std::ostringstream os; str = "pin "; os << m_id; str += os.str(); str += "\n"; sock->writeOnSocket(str); } void Player::setIncantationParam(unsigned int x, unsigned int y, unsigned int lvl) { _incantationParam[0] = x; _incantationParam[1] = y; _incantationParam[2] = lvl; } unsigned int Player::getBroadCastLevel() const { return m_broadCastLevel; } void Player::updateBroadCastLevel() { if (_currentAction != Broadcast) { m_broadCastLevel = 0; return; } if (m_broadCastLevel > Settings::SizeBroadCast) m_broadCastLevel = 0; else m_broadCastLevel += Settings::SpeedBroadcast; } std::vector<unsigned int> const &Player::getIncantationParam() const { return (_incantationParam); } eStat Player::getCurrentStat() const { return (_currentStat); } void Player::setCurrentStat(eStat st) { _currentStat = st; } void Player::setBroadCastMsg(std::string const &str) { _broadCastMsg = str; } std::string const &Player::getBroadCastMsg() const { return (_broadCastMsg); } void Player::setCurrentAction(eAction cur) { _currentAction = cur; } eAction Player::getCurrentAction() const { return (_currentAction); } void Player::setLevel(unsigned int level) { _level = level; } void Player::setOrientation(eOrientation o) { _orient = o; } eOrientation Player::getOrientation() const { return (_orient); } unsigned int Player::getLevel() const { return (_level); } void Player::setX(unsigned int x) { m_x = x; } void Player::setY(unsigned int y) { m_y = y; } unsigned int Player::getX() const { return (m_x); } unsigned int Player::getY() const { return (m_y); } int Player::getId() const { return (m_id); } void Player::setRessource(eRessources res, unsigned int nbr) { _ressources[res] = nbr; } std::map<eRessources, unsigned int> const &Player::getRessource() const { return (_ressources); } <file_sep>/* ** is_in_list_egg.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/egg ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:55:22 2014 ** Last update Sun Jul 13 15:55:23 2014 */ #include <stdlib.h> #include "zappy.h" static t_clientIA *create_ia_egg(t_egg *, t_team *, t_zappy *, int); t_clientIA *is_in_list_egg(t_list *l, t_team *t, t_conn *c, t_zappy *s) { t_node *loop; t_egg *egg; t_clientIA *client; t_gui_answer *answer; if (l->type != EGG) return (NULL); loop = l->head; while (loop) { egg = ((t_egg*)loop->data); if ((egg->active) && (egg->team == t)) { s->currentRessource = egg; answer = create_gui_ans(tograph_ebo(s), 0); put_in_list(s->listWrite, answer); client = create_ia_egg(egg, t, s, c->socket); if (client) rm_node(l, loop); return (client); } loop = loop->next; } return (NULL); } static t_clientIA *create_ia_egg(t_egg *egg, t_team *team, t_zappy *s, int sd) { t_clientIA *clientIA; if (!(clientIA = alloc_clientIA(team, sd))) return (NULL); clientIA->x = egg->x; clientIA->y = egg->y; if (!(place_player(clientIA, s->map))) { free(clientIA); return (NULL); } if (!(put_in_list(s->listIA, clientIA))) { free(clientIA); return (NULL); } if (clientIA->buff_read == NULL) if (!(clientIA->buff_read = alloc_buff())) return (free_va_arg(1, clientIA)); clientIA->decLife = get_tick(((double)UNIT_TIME * 1.0f / (double)s->delay)); ++(team->nbplayers); first_send_ia(clientIA, s, team); return (clientIA); } <file_sep>/* ** init_server.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/init ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 16:15:18 2014 ** Last update dim. juil. 13 19:50:39 2014 julien thebaud */ #include <time.h> #include <stdlib.h> #include "zappy.h" static void init_ptr_func_ia(t_zappy *server); static void init_ptr_func_gui(t_zappy *server); static int init_resource_strings(t_zappy *server); int init_server(t_zappy *server) { srand(time(NULL)); server->max_id = 0; server->map = NULL; server->writeGui = NULL; if (!(server->listConn = create_list(CONN))) return (1); if (!(server->listTeam = create_list(TEAM))) return (2); if (!(server->listIA = create_list(IA))) return (3); if (!(server->listGUI = create_list(GUI))) return (4); if (!(server->listEGG = create_list(EGG))) return (4); if (!(server->listWrite = create_list(ANSWER))) return (5); if (init_resource_strings(server)) return (6); if (!(server->incantation_requirements = init_inventories(server))) return (7); init_ptr_func_ia(server); init_ptr_func_gui(server); return (0); } static int init_resource_strings(t_zappy *server) { server->resources[Food] = "nourriture"; server->resources[Linemate] = "linemate"; server->resources[Deraumere] = "deraumere"; server->resources[Sibur] = "sibur"; server->resources[Mendiane] = "mendiane"; server->resources[Phiras] = "phiras"; server->resources[Thystame] = "thystame"; server->resources[7] = "joueur"; server->resources[8] = NULL; server->nb_players[0] = 1; server->nb_players[1] = 2; server->nb_players[2] = 2; server->nb_players[3] = 4; server->nb_players[4] = 4; server->nb_players[5] = 6; server->nb_players[6] = 6; return (0); } static void init_ptr_func_ia(t_zappy *server) { server->ptr_func_ia[MOVE] = &move; server->ptr_func_ia[RIGHT] = &right; server->ptr_func_ia[LEFT] = &left; server->ptr_func_ia[SEE] = &see; server->ptr_func_ia[INVENTORY] = &inventory; server->ptr_func_ia[TAKE_OBJ] = &take_obj; server->ptr_func_ia[PUT_OBJ] = &put_obj; server->ptr_func_ia[EXPULSE] = &expulse; server->ptr_func_ia[BROADCAST] = &broadcast; server->ptr_func_ia[INCANTATION] = &incantation; server->ptr_func_ia[FORK] = &_fork; server->ptr_func_ia[CONNECT_NBR] = &connect_nbr; } static void init_ptr_func_gui(t_zappy *server) { server->ptr_func_gui[MSZ] = &msz; server->ptr_func_gui[BCT] = &bct; server->ptr_func_gui[MCT] = &mct; server->ptr_func_gui[TNA] = &tna; server->ptr_func_gui[PPO] = &ppo; server->ptr_func_gui[PLV] = &plv; server->ptr_func_gui[PIN] = &pin; server->ptr_func_gui[SGT] = &sgt; server->ptr_func_gui[SST] = &sst; } void set_connect_nbr(t_zappy *server) { t_node *teams; teams = server->listTeam->head; while (teams) { ((t_team *)(teams->data))->nb_slots_max = server->nbClients; teams = teams->next; } } <file_sep>#include "Treatment.hpp" #include <iostream> Treatment::Treatment() { } Treatment::~Treatment() { std::cout << "Treatment DEstructionnnnn" << std::endl; } bool Treatment::getSubstr(std::string const &command, unsigned int i, std::string &res) { std::size_t pos1 = 0, pos2 = 0; for (unsigned int nb = 0; nb < i; nb++) { pos1 = command.find(" ", pos2); if (pos1 == std::string::npos) return (false); pos2 = command.find(" ", pos1 + 1); if (pos2 == std::string::npos) pos2 = command.length(); } res = command.substr(pos1, pos2 - pos1); return (true); } unsigned int Treatment::StringToUInt(std::string const &str) { unsigned int x; std::istringstream ss(str); ss >> x; return (x); } int Treatment::StringToInt(std::string const &str) { int x; std::istringstream ss(str); ss >> x; return (x); } unsigned int Treatment::generateRandomNumber(unsigned int min, unsigned int max) const { unsigned int value; static int i; if (i == 0) srand(time(NULL)); i++; while ((value = rand() % (max + 1)) < min); return (value); } bool Treatment::doMsz(std::string const &command, Zappy &data) { std::string first, second; unsigned int x, y; if (data.getIsSet() == true) return (false); if (getSubstr(command, 1, first) == false) return (false); if (getSubstr(command, 2, second) == false) return (false); x = StringToUInt(first); y = StringToUInt(second); if (x == 0 || y == 0) return (false); data.setMap(x, y); data.setIsSet(true); return (true); } bool Treatment::doBct(std::string const &command, Zappy &data) { std::string str; unsigned int x, y, val, res = 0; Case *ca; if (data.getIsSet() == false) return (false); if (getSubstr(command, 1, str) == false) return (false); x = StringToUInt(str); if (getSubstr(command, 2, str) == false) return (false); y = StringToUInt(str); if (data.getMap().getLength() < x) return (false); if (data.getMap().getWidth() < y) return (false); if ((ca = data.getMap().atCoords(x, y)) == 0) return (false); for (x = 3; x < 10; x++) { if (getSubstr(command, x, str) == false) return (false); val = StringToUInt(str); ca->setRessources(static_cast<eRessources>(res), val); res++; } return (true); } bool Treatment::doTna(std::string const &command, Zappy &data) { std::string name; unsigned int r, g, b; if (data.getIsSet() == false) return (false); if (getSubstr(command, 1, name) == false) return (false); if (data.getTeam(name) != 0) return (false); r = generateRandomNumber(0, 255); g = generateRandomNumber(0, 255); b = generateRandomNumber(0, 255); while (data.compareTeamColor(r, g, b) == true) { r = generateRandomNumber(0, 255); g = generateRandomNumber(0, 255); b = generateRandomNumber(0, 255); } sf::Color col(r, g, b); data.setNewTeam(new Team(name, col)); return (true); } bool Treatment::doPnw(std::string const &command, Zappy &data) { std::string str; int id; unsigned int x, y; Player *player = 0; if (data.getIsSet() == false) return (false); if (getSubstr(command, 1, str) == false) return (false); id = StringToInt(str); if (data.getPlayerById(id) != 0) player = data.getPlayerById(id); if (getSubstr(command, 2, str) == false) return (false); x = StringToUInt(str); if (getSubstr(command, 3, str) == false) return (false); y = StringToUInt(str); if (data.getMap().getLength() < x) return (false); if (data.getMap().getWidth() < y) return (false); if (data.getPlayerById(id) == 0) player = new Player(id, x, y); else { player->setX(x); player->setY(y); } if (getSubstr(command, 4, str) == false) return (false); player->setOrientation(static_cast<eOrientation>(StringToInt(str))); if (getSubstr(command, 5, str) == false) return (false); player->setLevel(StringToUInt(str)); if (getSubstr(command, 6, str) == false) return (false); if (data.getTeam(str) == 0) return (false); if (data.getPlayerById(id) == 0) data.getTeam(str)->setNewPlayer(player); return (true); } bool Treatment::doPpo(std::string const &command, Zappy &data) { std::string str; int id; Player *play; if (data.getIsSet() == false) return (false); if (getSubstr(command, 1, str) == false) return (false); id = StringToInt(str); if ((play = data.getPlayerById(id)) == 0) return (false); if (getSubstr(command, 2, str) == false) return (false); if (data.getMap().getLength() < StringToUInt(str)) return (false); play->setX(StringToUInt(str)); if (getSubstr(command, 3, str) == false) return (false); if (data.getMap().getWidth() < StringToUInt(str)) return (false); play->setY(StringToUInt(str)); if (getSubstr(command, 4, str) == false) return (false); play->setOrientation(static_cast<eOrientation>(StringToInt(str))); return (true); } bool Treatment::doPlv(std::string const &command, Zappy &data) { std::string str; int id; Player *play; if (data.getIsSet() == false) return (false); if (getSubstr(command, 1, str) == false) return (false); id = StringToInt(str); if ((play = data.getPlayerById(id)) == 0) return (false); if (getSubstr(command, 2, str) == false) return (false); play->setLevel(StringToUInt(str)); return (true); } bool Treatment::doPin(std::string const &command, Zappy &data) { std::string str; int id; Player *play; unsigned int val, res = 0; if (data.getIsSet() == false) return (false); if (getSubstr(command, 1, str) == false) return (false); id = StringToInt(str); if ((play = data.getPlayerById(id)) == 0) return (false); if (getSubstr(command, 2, str) == false) return (false); if (data.getMap().getLength() < StringToUInt(str)) return (false); play->setX(StringToUInt(str)); if (getSubstr(command, 3, str) == false) return (false); if (data.getMap().getWidth() < StringToUInt(str)) return (false); play->setY(StringToUInt(str)); for (unsigned int x = 3; x < 10; x++) { if (getSubstr(command, x, str) == false) return (false); val = StringToUInt(str); play->setRessource(static_cast<eRessources>(res), val); res++; } return (true); } bool Treatment::doPex(std::string const &command, Zappy &data) { std::string str; int id; Player *play; if (data.getIsSet() == false) return (false); if (getSubstr(command, 1, str) == false) return (false); id = StringToInt(str); if ((play = data.getPlayerById(id)) == 0) return (false); play->setCurrentAction(Expulse); return (true); } bool Treatment::doPbc(std::string const &command, Zappy &data) { std::string str; int id; Player *play; if (data.getIsSet() == false) return (false); if (getSubstr(command, 1, str) == false) return (false); id = StringToInt(str); if ((play = data.getPlayerById(id)) == 0) return (false); play->setCurrentAction(Broadcast); if (getSubstr(command, 2, str) == false) return (false); play->setBroadCastMsg(str); return (true); } bool Treatment::doPic(std::string const &command, Zappy &data) { std::string str; int id; unsigned int x, y, lvl, pos; Player *play; Case *ca; if (data.getIsSet() == false) return (false); if (getSubstr(command, 1, str) == false) return (false); x = StringToUInt(str); if (data.getMap().getLength() < StringToUInt(str)) return (false); if (getSubstr(command, 2, str) == false) return (false); y = StringToUInt(str); if (data.getMap().getWidth() < StringToUInt(str)) return (false); if (getSubstr(command, 3, str) == false) return (false); lvl = StringToUInt(str); if ((ca = data.getMap().atCoords(x, y)) == 0) return (false); ca->setIncantParam(true, lvl, false); pos = 4; while (getSubstr(command, pos, str) != false) { id = StringToInt(str); if ((play = data.getPlayerById(id)) == 0) return (false); if (pos == 4) play->setCurrentAction(IncantationLaunch); play->setCurrentStat(Incantation); play->setIncantationParam(x, y, lvl); pos++; } return (true); } bool Treatment::doPie(std::string const &command, Zappy &data) { std::string str; unsigned int x, y, suc; Case *ca; if (data.getIsSet() == false) return (false); if (getSubstr(command, 1, str) == false) return (false); x = StringToUInt(str); if (data.getMap().getLength() < StringToUInt(str)) return (false); if (getSubstr(command, 2, str) == false) return (false); y = StringToUInt(str); if (data.getMap().getWidth() < StringToUInt(str)) return (false); if ((ca = data.getMap().atCoords(x, y)) == 0) return (false); if (getSubstr(command, 3, str) == false) return (false); suc = StringToUInt(str); if (suc == 1) ca->setIncantParam(false, 0, true); else ca->setIncantParam(false, 0, false); data.deSetIncant(x, y); return (true); } bool Treatment::doPfk(std::string const &command, Zappy &data) { std::string str; int id; Player *play; if (data.getIsSet() == false) return (false); if (getSubstr(command, 1, str) == false) return (false); id = StringToInt(str); if ((play = data.getPlayerById(id)) == 0) return (false); play->setCurrentAction(Fork); return (true); } bool Treatment::doPdr(std::string const &command, Zappy &data) { std::string str; int id; Player *play; if (data.getIsSet() == false) return (false); if (getSubstr(command, 1, str) == false) return (false); id = StringToInt(str); if ((play = data.getPlayerById(id)) == 0) return (false); play->setCurrentAction(PutRessources); return (true); } bool Treatment::doPgt(std::string const &command, Zappy &data) { std::string str; int id; Player *play; if (data.getIsSet() == false) return (false); if (getSubstr(command, 1, str) == false) return (false); id = StringToInt(str); if ((play = data.getPlayerById(id)) == 0) return (false); play->setCurrentAction(GetRessources); return (true); } bool Treatment::doPdi(std::string const &command, Zappy &data) { std::string str; std::vector<unsigned int> param; if (data.getIsSet() == false) return (false); if (getSubstr(command, 1, str) == false) return (false); data.removePlayerById(StringToInt(str)); return (true); } bool Treatment::doEnw(std::string const &command, Zappy &data) { std::string str; int eggId, playerId; unsigned int x, y; Egg *egg; Player *play; Team *team; if (data.getIsSet() == false) return (false); if (getSubstr(command, 1, str) == false) return (false); eggId = StringToInt(str); if (data.getEggById(eggId) != 0) return (false); if (getSubstr(command, 2, str) == false) return (false); playerId = StringToInt(str); if ((play = data.getPlayerById(playerId)) == 0) return (false); if ((team = data.getTeamByPlayerId(playerId)) == 0) return (false); if (getSubstr(command, 3, str) == false) return (false); x = StringToUInt(str); if (getSubstr(command, 4, str) == false) return (false); y = StringToUInt(str); if (data.getMap().getLength() < x) return (false); if (data.getMap().getWidth() < y) return (false); egg = new Egg(eggId, x, y); team->setNewEgg(egg); if (play->getCurrentAction() == Fork) play->setCurrentAction(Nothing); return (true); } bool Treatment::doEht(std::string const &command, Zappy &data) { std::string str; Egg *egg; if (data.getIsSet() == false) return (false); if (getSubstr(command, 1, str) == false) return (false); if ((egg = data.getEggById(StringToInt(str))) == 0) return (false); egg->setStat(Eclot); return (true); } bool Treatment::doEbo(std::string const &command, Zappy &data) { std::string str; if (data.getIsSet() == false) return (false); if (getSubstr(command, 1, str) == false) return (false); if (data.getEggById(StringToInt(str)) == 0) return (false); data.removeEggById(StringToInt(str)); return (true); } bool Treatment::doEdi(std::string const &command, Zappy &data) { std::string str; if (data.getIsSet() == false) return (false); if (getSubstr(command, 1, str) == false) return (false); if (data.getEggById(StringToInt(str)) == 0) return (false); data.removeEggById(StringToInt(str)); return (true); } bool Treatment::doSgt(std::string const &command, Zappy &data) { std::string str; if (getSubstr(command, 1, str) == false) return (false); data.setTimeRef(StringToUInt(str)); return (true); } bool Treatment::doSeg(std::string const &command, Zappy &data) { std::string str; if (getSubstr(command, 1, str) == false) return (false); data.setEndGame(true); data.setWinnerTeam(str); return (true); } bool Treatment::doSmg(std::string const &command, Zappy &) { std::string str; if (getSubstr(command, 1, str) == false) return (false); std::cout << "Server Message : " << str << std::endl; return (true); } bool Treatment::doSuc(std::string const &, Zappy &) { std::cerr << "Unknown Command Send To Server From this Client" << std::endl; return (true); } bool Treatment::doSbp(std::string const &, Zappy &) { std::cerr << "Command with parameter send to server from this client" << std::endl; return (true); } <file_sep>#ifndef APP_HPP # define APP_HPP #include <thread> #include <SFML/Graphics.hpp> #include "Zappy.hpp" #include "Socket.hpp" class App { public: App(); ~App(); public: void initialize(); void run(); private: sf::RenderWindow m_window; Zappy m_zappy; std::thread *t1; Socket sock; private: void _events(); void _connexion(); }; #endif // APP_HPP<file_sep>#include "View.hpp" void View::drawNourriture(sf::CircleShape & shape, sf::Vector2f newPos) { shape.setFillColor(Color::Nourriture); shape.setPosition(newPos); m_window.draw(shape); } void View::drawLinemate(sf::CircleShape & shape, sf::Vector2f newPos) { shape.setFillColor(Color::Linemate); newPos.x += Settings::CoeffRessources; shape.setPosition(newPos); m_window.draw(shape); } void View::drawDeraumere(sf::CircleShape & shape, sf::Vector2f newPos) { shape.setFillColor(Color::Deraumere); newPos.y += Settings::CoeffRessources; shape.setPosition(newPos); m_window.draw(shape); } void View::drawSibur(sf::CircleShape & shape, sf::Vector2f newPos) { shape.setFillColor(Color::Sibur); newPos.x += Settings::CoeffRessources; newPos.y += Settings::CoeffRessources; shape.setPosition(newPos); m_window.draw(shape); } void View::drawMendiane(sf::CircleShape & shape, sf::Vector2f newPos) { shape.setFillColor(Color::Mendiane); newPos.x += Settings::CoeffRessources * 1; newPos.y += Settings::CoeffRessources * 2; shape.setPosition(newPos); m_window.draw(shape); } void View::drawPhiras(sf::CircleShape & shape, sf::Vector2f newPos) { shape.setFillColor(Color::Phiras); newPos.x += Settings::CoeffRessources * 2; shape.setPosition(newPos); m_window.draw(shape); } void View::drawThystame(sf::CircleShape & shape, sf::Vector2f newPos) { shape.setFillColor(Color::Thystame); newPos.x += Settings::CoeffRessources * 2; newPos.y += Settings::CoeffRessources * 2; shape.setPosition(newPos); m_window.draw(shape); }<file_sep>/* ** list.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/struct ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:56:10 2014 ** Last update dim. juil. 13 15:57:18 2014 <NAME> */ #include <stdlib.h> #include "list.h" t_list *create_list(t_type type) { t_list *ret; if (!(ret = malloc(sizeof(*ret)))) return (NULL); ret->type = type; ret->length = 0; ret->head = NULL; ret->end = NULL; return (ret); } /* ** put an elem at the end of the list ** all data must be allocated */ bool put_in_list(t_list *list, void *data) { t_node *elem; if ((!data) || (!list)) return (false); if (!(elem = malloc(sizeof(*elem)))) return (false); elem->data = data; elem->next = NULL; if (!(list->head)) { elem->prev = NULL; list->head = elem; list->end = elem; } else { elem->prev = list->end; list->end->next = elem; list->end = elem; } ++(list->length); return (true); } /* ** RM node and return the next elem or NULL */ t_node *rm_node(t_list *list, t_node *node) { t_node *next; if ((!list) || (!node)) return (NULL); next = node->next; if (node == list->head) list->head = next; if (node == list->end) list->end = node->prev; if (node->prev) node->prev->next = next; if (node->next) node->next->prev = node->prev; release_node(node, list->type); --(list->length); return (next); } int release_list(t_list *list) { t_node *loop; if (!(list)) return (1); loop = list->head; while (loop) loop = rm_node(list, loop); free(list); return (0); } <file_sep> #ifndef TO_GRAPH_H #define TO_GRAPH_H #include <stdbool.h> #include "broadcast.h" #define IGNORE(x) ((void)x) /* Minimal buffer is 512 */ #ifdef SIZE_BUFF #if SIZE_BUFF < 512 #undef SIZE_BUFF #define SIZE_BUFF 512 #endif #endif #ifndef SIZE_BUFF #define SIZE_BUFF 512 #endif char *tograph_msz(t_zappy *z); char *tograph_tna(t_zappy *z); char *tograph_sbp(t_zappy *z); char *tograph_suc(t_zappy *z); char *tograph_pbc(t_zappy *z); char *tograph_bct(t_zappy *z); char *tograph_send_map(t_zappy *z); char *tograph_pnw(t_zappy *z); char *tograph_pdi(t_zappy *z); char *tograph_enw(t_zappy *z); char *tograph_pex(t_zappy *z); char *tograph_pdr(t_zappy *z); char *tograph_pgt(t_zappy *z); char *tograph_plv(t_zappy *z); char *tograph_sgt(t_zappy *z); char *tograph_ppo(t_zappy *z); char *tograph_welcome_msg(t_zappy *z); char *tograph_smg(t_zappy *z); char *tograph_seg(t_zappy *z); char *tograph_pfk(t_zappy *z); char *tograph_eht(t_zappy *z); char *tograph_edi(t_zappy *z); char *tograph_ebo(t_zappy *z); char *tograph_pie(t_zappy *z); char *tograph_pic(t_zappy *z); char *tograph_pin(t_zappy *z); char *concatList(t_list *l); int getPlayerId(t_clientIA *player); #endif <file_sep>// // FileDescr.hpp for Plaza in /home/courtu_r/tests/plazza // // Made by courtu_r // Login <<EMAIL>> // // Started on Fri Apr 18 13:36:56 2014 courtu_r // Last update Fri Apr 25 15:42:38 2014 remaud_c // #ifndef FILEDESCR # define FILEDESCR #include <unistd.h> #include <fcntl.h> class FileDescr { int _fd; fd_set _rfds; struct timeval _time; public: void setTime(int sec, int usec); void setFd(int fd); void clearFd(); bool isSet(int fd) const; int setNonBlock(); }; #endif /*FILEDESCR*/ <file_sep>#include "Egg.hpp" Egg::Egg(int id, unsigned int x, unsigned int y) : _posX(x), _posY(y), _id(id) { } Egg::~Egg() { } void Egg::setX(unsigned int x) { _posX = x; } void Egg::setY(unsigned int y) { _posY = y; } unsigned int Egg::getX() const { return (_posX); } unsigned int Egg::getY() const { return (_posY); } int Egg::getId() const { return (_id); } eEggStat Egg::getStat() const { return (_stat); } void Egg::setStat(eEggStat st) { _stat = st; } <file_sep>#include <iostream> #include <sstream> #include "Zappy.hpp" Zappy::Zappy() { _mapIsSet = false; _endGame = false; _winnerTeam = ""; } Zappy::~Zappy() { std::list<Team *>::iterator it; for (it = m_team.begin(); it != m_team.end(); it++) { delete (*it); } } void Zappy::sendTimeToServer(unsigned int time, Socket &sock) { std::ostringstream ss; ss << "sst " << time << std::endl; sock.writeOnSocket(ss.str()); } bool Zappy::compareTeamColor(unsigned int r, unsigned int g, unsigned int b) const { sf::Color test(r, g, b); std::list<Team *>::const_iterator it; for (it = m_team.begin(); it != m_team.end(); it++) { if (test == (*it)->getTeamColor()) return (true); } return (false); } void Zappy::deSetIncant(unsigned int x, unsigned int y) { std::list<Team*>::iterator it; std::list<Player *>::iterator it2; std::vector<unsigned int> vec; for (it = m_team.begin(); it != m_team.end(); it++) { std::list<Player*> &li = (*it)->getPlayers(); for (it2 = li.begin(); it2 != li.end(); it2++) { vec = (*it2)->getIncantationParam(); if (vec[2] != 0 && vec[0] == x && vec[1] == y) { (*it2)->setIncantationParam(0, 0, 0); if ((*it2)->getCurrentAction() == IncantationLaunch) (*it2)->setCurrentAction(Nothing); if ((*it2)->getCurrentStat() == Incantation) (*it2)->setCurrentStat(Not); } } } } void Zappy::setEndGame(bool end) { _endGame = end; } bool Zappy::getEndGame() const { return (_endGame); } void Zappy::setWinnerTeam(std::string const &t) { _winnerTeam = t; } Team *Zappy::getTeamById(unsigned int id) { for (auto &i : m_team) { if (id == 0) return i; --id; } return NULL; } std::string const &Zappy::getWinnerTeam() const { return (_winnerTeam); } void Zappy::setTimeRef(unsigned int time) { _timeRef = time; } unsigned int Zappy::getTimeRef() const { return (_timeRef); } Map & Zappy::getMap() { return (m_map); } void Zappy::setMap(unsigned int x, unsigned int y) { m_map.setMap(x, y); } void Zappy::restartClock() { m_clock.restart(); } void Zappy::removeEggById(int id) { m_mutex.lock(); std::list<Team *>::iterator it; std::list<Egg *>::iterator it2; for (it = m_team.begin(); it != m_team.end(); it++) { std::list<Egg *> &li = (*it)->getEggs(); for (it2 = li.begin(); it2 != li.end(); it2++) { if ((*it2)->getId() == id) { li.erase(it2); m_mutex.unlock(); return ; } } } m_mutex.unlock(); } void Zappy::removePlayerById(int id) { m_mutex.lock(); std::list<Team *>::iterator it; std::list<Player *>::iterator it2; for (it = m_team.begin(); it != m_team.end(); it++) { std::list<Player *> &li = (*it)->getPlayers(); for (it2 = li.begin(); it2 != li.end(); it2++) { if ((*it2)->getId() == id) { li.erase(it2); m_mutex.unlock(); std::cout << "Player deleted" << std::endl; return ; } } } m_mutex.unlock(); } void Zappy::setNewTeam(Team *team) { m_team.push_back(team); } const std::list<Team *> & Zappy::getTeam() const { return (m_team); } Team *Zappy::getTeam(std::string const &name) const { std::list<Team*>::const_iterator it; for (it = m_team.begin(); it != m_team.end(); it++) { if ((*it)->getTeamName() == name) return (*it); } return (0); } Player *Zappy::getPlayerById(int id) const { std::list<Team *>::const_iterator it; std::list<Player *> li; std::list<Player *>::const_iterator it2; for (it = m_team.begin(); it != m_team.end(); it++) { li = (*it)->getPlayers(); for (it2 = li.begin(); it2 != li.end(); it2++) { if ((*it2)->getId() == id) return (*it2); } } return (0); } void Zappy::setIsSet(bool s) { _mapIsSet = s; } bool Zappy::getIsSet() const { return (_mapIsSet); } Egg *Zappy::getEggById(int id) const { std::list<Team *>::const_iterator it; std::list<Egg *> li; std::list<Egg *>::const_iterator it2; for (it = m_team.begin(); it != m_team.end(); it++) { li = (*it)->getEggs(); for (it2 = li.begin(); it2 != li.end(); it2++) { if ((*it2)->getId() == id) return (*it2); } } return (0); } Team *Zappy::getTeamByPlayerId(int id) const { std::list<Team *>::const_iterator it; std::list<Player *> li; std::list<Player *>::const_iterator it2; for (it = m_team.begin(); it != m_team.end(); it++) { li = (*it)->getPlayers(); for (it2 = li.begin(); it2 != li.end(); it2++) { if ((*it2)->getId() == id) return (*it); } } return (0); } void Zappy::lock() { m_mutex.lock(); } void Zappy::unlock() { m_mutex.unlock(); } <file_sep>/* ** map.c for zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy/server/clientIA ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Thu Jun 26 12:46:11 2014 courtu_r ** Last update Sun Jul 13 16:49:41 2014 courtu_r */ #include "proto.h" #include "map.h" t_map *init_map(t_map *map, Uint width, Uint height) { if (map == NULL && (map = malloc(sizeof(*map))) == NULL) return (NULL); map->width = width; map->height = height; map->map = create_map(map->width, map->height); return (map); } void free_map(t_map *map) { Uint x = 0; Uint y = 0; while (y < map->height) { while (x < map->width) { free_case(((map->map)[y][x])); x += 1; } free((map->map)[y]); y += 1; x = 0; } free((map->map)[y]); free(map->map); free(map); } t_case ***create_map(Uint width, Uint height) { t_case ***map; Uint x; Uint y; x = 0; y = 0; if ((map = malloc(sizeof(*map) * (height + 1))) == NULL) return (NULL); while (y < height) { if ((map[y] = malloc(sizeof(**map) * width)) == NULL) { free(map); return (NULL); } while (x < width) { map[y][x] = (init_case(x, y)); x += 1; } y += 1; x = 0; } map[y] = NULL; return (map); } void show_map(t_map *map) { Uint x = 0; Uint y = 0; while (y < map->height) { while (x < map->width) { print_case(((map->map)[y][x])); x += 1; } y += 1; x = 0; } } <file_sep>/* ** alloc_client_gui.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/clientGUI ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:53:09 2014 ** Last update Sun Jul 13 15:53:10 2014 */ #include <stdlib.h> #include "zappy.h" t_clientGUI *alloc_clientGUI(SOCKET sd) { t_clientGUI *ret; if (!(ret = malloc(sizeof(*ret)))) return (NULL); if (!(ret->buff_write = alloc_buff())) return (free_va_arg(1, ret)); if (!(ret->listWrite = create_list(ANSWER))) return (free_va_arg(2, ret->buff_write, ret)); ret->buff_read = NULL; ret->socket = sd; ret->error = false; ret->write = false; ret->writeConn = NULL; ret->buff = NULL; return (ret); } <file_sep>/* ** monitor_socket.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/network ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:59:23 2014 ** Last update Sun Jul 13 19:51:26 2014 courtu_r */ #include <sys/select.h> #include <string.h> #include "zappy.h" static t_gui_answer *dup_gui_answer(t_gui_answer *old); static int set_socket_ia(t_zappy *s, t_node *node, t_type t, int *ret); static int set_socket_gui(t_zappy *s, t_node *node, t_type t, int *ret); static int set_socket_conn(t_zappy *s, t_node *node, t_type t, int *ret); void add_socket_to_monitor(t_zappy *server) { int ret; t_node *loop; FD_ZERO(&(server->readsd)); FD_ZERO(&(server->writesd)); FD_ZERO(&(server->exceptsd)); FD_SET(server->listen, &(server->readsd)); server->max_sd = server->listen; ret = iter(server->listConn, server, set_socket_conn); if (server->max_sd < ret) server->max_sd = ret; ret = iter(server->listIA, server, set_socket_ia); if (server->max_sd < ret) server->max_sd = ret; ret = iter(server->listGUI, server, set_socket_gui); if (server->max_sd < ret) server->max_sd = ret; loop = server->listWrite->head; while (loop) loop = rm_node(server->listWrite, loop); } static int set_socket_conn(t_zappy *s, t_node *node, t_type t, int *ret) { t_conn *conn; if (t != CONN) return (1); conn = ((t_conn*)node->data); if ((*ret) < conn->socket) (*ret) = conn->socket; if (conn->welcome) FD_SET(conn->socket, &(s->writesd)); else if (conn->write) FD_SET(conn->socket, &(s->writesd)); FD_SET(conn->socket, &(s->readsd)); return (0); } static int set_socket_ia(t_zappy *s, t_node *node, t_type t, int *ret) { t_clientIA *client; if (t != IA) return (1); client = ((t_clientIA*)node->data); if (client->socket != -1) { if ((*ret) < client->socket) (*ret) = client->socket; if (client->call_incantation || client->broadcast || client->error || client->write || client->instant_write || client->big_write || client->incantation || client->isDead) FD_SET(client->socket, &(s->writesd)); FD_SET(client->socket, &(s->readsd)); } return (0); } static t_gui_answer *dup_gui_answer(t_gui_answer *old) { return (create_gui_ans(strdup(old->msg), old->tick)); } static int set_socket_gui(t_zappy *s, t_node *node, t_type t, int *ret) { t_clientGUI *client; t_node *loop; if (t != GUI) return (1); client = ((t_clientGUI*)node->data); if (client->socket != -1) { if ((*ret) < client->socket) (*ret) = client->socket; if (s->listWrite->length > 0) { loop = s->listWrite->head; while (loop) { put_in_list(client->listWrite, dup_gui_answer(((t_gui_answer*)loop->data))); loop = loop->next; } } do_fd_sets(s, client); } return (0); } <file_sep>#ifndef ZAPPY_HPP_ # define ZAPPY_HPP_ #include <string> #include <mutex> #include "Map.hpp" #include "Team.hpp" #include "Socket.hpp" class Zappy { public: Zappy(); ~Zappy(); Map & getMap(); void setMap(unsigned int, unsigned int); void restartClock(); void setNewTeam(Team *team); Team *getTeam(std::string const &name) const; Egg *getEggById(int) const; Team *getTeamByPlayerId(int) const; Player *getPlayerById(int) const; void removePlayerById(int); void removeEggById(int); const std::list<Team *> & getTeam() const; void setIsSet(bool); bool getIsSet() const; unsigned int getTimeRef() const; void setTimeRef(unsigned int); void setEndGame(bool); bool getEndGame() const; void setWinnerTeam(std::string const &); std::string const &getWinnerTeam() const; void lock(); void unlock(); Team *getTeamById(unsigned int); void deSetIncant(unsigned int, unsigned int); bool compareTeamColor(unsigned int, unsigned int, unsigned int) const; void sendTimeToServer(unsigned int, Socket &); private: bool _endGame; std::string _winnerTeam; Map m_map; bool _mapIsSet; unsigned int _timeRef; std::list<Team *> m_team; sf::Clock m_clock; std::mutex m_mutex; }; #endif // ZAPPY_HPP__ <file_sep>#include "FileDescr.hpp" void FileDescr::setTime(int sec, int usec) { _time.tv_sec = sec; _time.tv_usec = usec; } void FileDescr::setFd(int fd) { FD_ZERO(&(_rfds)); _fd = fd; FD_SET(_fd, &(_rfds)); } void FileDescr::clearFd() { FD_ZERO(&(_rfds)); } bool FileDescr::isSet(int fd) const { if (FD_ISSET(fd, &_rfds)) return (true); else return (false); } int FileDescr::setNonBlock() { int ret; ret = select(_fd + 1, &_rfds, NULL, NULL, &_time); if (ret == -1) return (ret); return (ret); } <file_sep>#ifndef EGG_HPP_ #define EGG_HPP_ #include <mutex> enum eEggStat { Eclot = 0, Rien, }; class Egg { unsigned int _posX; unsigned int _posY; eEggStat _stat; int _id; std::mutex m_mutex; public: Egg(int, unsigned int, unsigned int); ~Egg(); eEggStat getStat() const; void setStat(eEggStat); void setX(unsigned int); void setY(unsigned int); unsigned int getX() const; unsigned int getY() const; int getId() const; }; #endif <file_sep>/* ** plv.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/clientGUI ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:54:01 2014 ** Last update dim. juil. 13 16:36:41 2014 <NAME> */ #include "utils.h" #include "zappy.h" int plv(t_zappy *server, t_clientGUI *client, char *cmd) { char *send; unsigned int n; if (parse_two_int(cmd, &n, NULL)) { client->error = true; return (1); } server->currentRessource = ((void*)get_clientIA_by_index(server->listIA, n)); if (server->currentRessource) { send = tograph_plv(server); if (send) { copy_in_buff(send, client->buff_write); free(send); client->write = true; } } else client->error = true; return (0); } <file_sep>## preview ![Screenshot](https://github.com/AkselsLedins/academic-zappy/blob/master/screenshots/gui.png) Server (C), Client (C++ SFML), AI (C++), Mutli AI collaborative game over network, with 2D viewer of server activity (showing AI playing) ## mark : 24/20 ![Mark](https://github.com/AkselsLedins/academic-zappy/blob/master/screenshots/mark.png) More info in ./subject <file_sep>#ifndef TREATMENT_HPP_ #define TREATMENT_HPP_ #include <ctime> #include <cstdlib> #include <SFML/Graphics.hpp> #include <sstream> #include <string> #include "Zappy.hpp" class Treatment { public: Treatment(); ~Treatment(); unsigned int StringToUInt(std::string const &); unsigned int generateRandomNumber(unsigned int, unsigned int) const; int StringToInt(std::string const &); bool getSubstr(std::string const &command, unsigned int i, std::string &res); bool doMsz(std::string const &, Zappy &); bool doBct(std::string const &, Zappy &); bool doTna(std::string const &, Zappy &); bool doPnw(std::string const &, Zappy &); bool doPpo(std::string const &, Zappy &); bool doPlv(std::string const &, Zappy &); bool doPin(std::string const &, Zappy &); bool doPex(std::string const &, Zappy &); bool doPbc(std::string const &, Zappy &); bool doPic(std::string const &, Zappy &); bool doPie(std::string const &, Zappy &); bool doPfk(std::string const &, Zappy &); bool doPdr(std::string const &, Zappy &); bool doPgt(std::string const &, Zappy &); bool doPdi(std::string const &, Zappy &); bool doEnw(std::string const &, Zappy &); bool doEht(std::string const &, Zappy &); bool doEbo(std::string const &, Zappy &); bool doEdi(std::string const &, Zappy &); bool doSgt(std::string const &, Zappy &); bool doSeg(std::string const &, Zappy &); bool doSmg(std::string const &, Zappy &); bool doSuc(std::string const &, Zappy &); bool doSbp(std::string const &, Zappy &); }; #endif <file_sep>/* ** create_socket_tcp.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/network ** ** Made by ** Login <<EMAIL>> ** ** Started on Sun Jul 13 15:58:23 2014 ** Last update dim. juil. 13 21:39:50 2014 <NAME> */ #include <stdio.h> #include <netdb.h> #include <unistd.h> #include <stdbool.h> #include <sys/socket.h> #include "zappy.h" static bool perror_and_close(const char *str, int fdsock); bool create_socket_TCP(t_zappy *server) { SOCKADDR_IN serv_in; PROTOENT *pe; int sd; int opt; opt = 1; pe = getprotobyname("TCP"); if (!pe) sd = socket(AF_INET, SOCK_STREAM, 0); else sd = socket(AF_INET, SOCK_STREAM, pe->p_proto); if (sd == -1) return (perror_and_close("Socket failed. Error", -1)); if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1) return (perror_and_close("Setsockopt failed. Error", sd)); serv_in.sin_family = AF_INET; serv_in.sin_addr.s_addr = INADDR_ANY; serv_in.sin_port = htons(server->port); if (bind(sd, (SOCKADDR*)&serv_in, sizeof(serv_in)) == -1) return (perror_and_close("Bind failed. Error", sd)); if (listen(sd, SOMAXCONN) == -1) return (perror_and_close("Listen failed. Error", sd)); server->max_sd = sd; server->listen = sd; return (true); } static bool perror_and_close(const char *str, int fdsock) { if (str) perror(str); else perror(""); if (fdsock != -1) { if (close(fdsock) == -1) perror("Close failed. Error"); } return (false); } <file_sep>/* ** init_incantation_checks.c for Zappy in /home/courtu_r/BOMBERMAN/thirdvers/blowshitup/ServerZappy ** ** Made by courtu_r ** Login <<EMAIL>> ** ** Started on Tue Jul 8 13:27:56 2014 courtu_r ** Last update Sat Jul 12 13:11:50 2014 courtu_r */ #include <stdlib.h> #include "zappy.h" t_inventory *init_level_7(t_inventory *inv) { inv[6].content[0] = 0; inv[6].content[1] = 2; inv[6].content[2] = 2; inv[6].content[3] = 2; inv[6].content[4] = 2; inv[6].content[5] = 2; inv[6].content[6] = 1; return (inv); } t_inventory *init_level_4_5_6(t_inventory *inv) { inv[3].content[0] = 0; inv[3].content[1] = 1; inv[3].content[2] = 1; inv[3].content[3] = 2; inv[3].content[4] = 0; inv[3].content[5] = 1; inv[3].content[6] = 0; inv[4].content[0] = 0; inv[4].content[1] = 1; inv[4].content[2] = 2; inv[4].content[3] = 1; inv[4].content[4] = 3; inv[4].content[5] = 0; inv[4].content[6] = 0; inv[5].content[0] = 0; inv[5].content[1] = 1; inv[5].content[2] = 2; inv[5].content[3] = 3; inv[5].content[4] = 0; inv[5].content[5] = 1; inv[5].content[6] = 0; return (inv); } t_inventory *init_level_1_2_3(t_inventory *inv) { inv[0].content[0] = 0; inv[0].content[1] = 1; inv[0].content[2] = 0; inv[0].content[3] = 0; inv[0].content[4] = 0; inv[0].content[5] = 0; inv[0].content[6] = 0; inv[1].content[0] = 0; inv[1].content[1] = 1; inv[1].content[2] = 1; inv[1].content[3] = 1; inv[1].content[4] = 0; inv[1].content[5] = 0; inv[1].content[6] = 0; inv[2].content[0] = 0; inv[2].content[1] = 2; inv[2].content[2] = 0; inv[2].content[3] = 1; inv[2].content[4] = 0; inv[2].content[5] = 2; inv[2].content[6] = 0; return (inv); } t_inventory *init_inventories(t_zappy *server) { t_inventory *invent; invent = NULL; if ((invent = malloc(sizeof(*(invent)) * (7 + 1))) == NULL) return (NULL); invent = init_level_1_2_3(invent); invent = init_level_4_5_6(invent); invent = init_level_7(invent); server->incantation_requirements = invent; return (invent); } t_inventory *get_inventory_to_comp(int lvl, t_zappy *server) { if (lvl > 0 && lvl < 8) return (&(server->incantation_requirements[lvl])); else return (NULL); }
24b9174e8d641c99eb4894af5bb314e2124c4957
[ "Markdown", "C", "Makefile", "C++" ]
158
C++
AkselsLedins/academic-zappy
53025ee1549dd8ad693ca647888eb77985875547
6279936bcfe1e364c16418028a1c4aad8a5789b3
refs/heads/master
<repo_name>kingkung/CreateAndLearnTemplates<file_sep>/settings.gradle include ':app' rootProject.name = "Create And LearnTemplates"<file_sep>/app/src/main/java/us/createandlearn/tendotfive/Card.java package us.createandlearn.tendotfive; public class Card { private final String rank; private final String suit; private final double pointValue; private final int imageResId; public Card(String rank, String suit, double pointValue, int imageResId) { this.rank = rank; this.suit = suit; this.pointValue = pointValue; this.imageResId = imageResId; } public String getRank() { return rank; } public String getSuit() { return suit; } public double getPointValue() { return pointValue; } public int getImageResId() { return imageResId; } public String toString() { String strCard; strCard = " --------\n"; if(rank.equals("10")) strCard+="| " + rank + "|\n"; else strCard+="| " + rank + " |\n"; strCard+="| |\n"; strCard+="| |\n"; //strCard+="| " + suit + " |\n"; strCard+="| |\n"; strCard+="| |\n"; if(rank.equals("10")) strCard+="| " + rank + " |\n"; else strCard+="| " + rank + " |\n"; strCard+=" --------\n"; return strCard; } } <file_sep>/app/src/main/java/us/createandlearn/tendotfive/Deck.java package us.createandlearn.tendotfive; import java.util.ArrayList; import java.util.List; import us.createandlearn.R; public class Deck { private static final int NUMBER_OF_CARDS = 52; private static final String[] RANKS = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"}; private static final double[] VALUES = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, .5, .5 , .5 }; private static final String[] SUITS = {"S"}; // look up working Unicode chars private static final int[] IMAGE_RES_ID = { R.drawable.spade_ace, R.drawable.spade2, R.drawable.spade3, R.drawable.spade4, R.drawable.spade5, R.drawable.spade6, R.drawable.spade7, R.drawable.spade8, R.drawable.spade9, R.drawable.spade10, R.drawable.spade_jack, R.drawable.spade_queen, R.drawable.spade_king, }; private final List<Card> cards; public Deck() { cards = new ArrayList<>(); for(String suit : SUITS) { for(int i=0; i<RANKS.length; i++) { cards.add(new Card(RANKS[i], suit, VALUES[i], IMAGE_RES_ID[i])); } } shuffleDeck(); } public void shuffleDeck() { for(int i=0; i<cards.size(); i++) { int randPos = (int)(Math.random() * cards.size()); //swap the current card with a randomly selected card Card temp = cards.get(i); cards.set(i, cards.get(randPos)); cards.set(randPos, temp); } } public Card dealCard() { if(cards.size() == 0) return null; else { Card card = cards.remove(cards.size() - 1); return card; } } public String toString() { String result = ""; for(int i=0; i<cards.size(); i++) { result += cards.get(i).toString() + "\n"; } return result; } } <file_sep>/app/src/main/java/us/createandlearn/tendotfive/TenDotFiveGame.java package us.createandlearn.tendotfive; import java.util.ArrayList; public class TenDotFiveGame { private final Deck deck; private final ArrayList<Card> playerHand; private final ArrayList<Card> dealerHand; private double playerTotal, dealerTotal; public TenDotFiveGame() { deck = new Deck(); playerHand = new ArrayList<Card>(); dealerHand = new ArrayList<Card>(); playerTotal = dealerTotal = 0; } public void dealOpeningCards() { playerHit(); dealerHit(); } public Card getPlayerLastCard() { return playerHand.get(playerHand.size()-1); } public Card getDealerLastCard() { return dealerHand.get(dealerHand.size()-1); } /** Adds a card to player's hand * PointTotal is updated */ public Card playerHit() { Card card = deck.dealCard(); playerHand.add(card); playerTotal += card.getPointValue(); return card; } /** Adds a card to dealer's hand * PointTotal is updated */ public Card dealerHit() { Card card = deck.dealCard(); dealerHand.add(card); dealerTotal += card.getPointValue(); return card; } public boolean dealerShouldHit() { return dealerTotal <= 7; } public String getPlayerHand() { String result = "\nPlayer Hand:\n"; for(Card card : playerHand) result += "\n" + card.toString(); return result; } public String getDealerHand() { String result = "\nDealer Hand:\n"; for(Card card : dealerHand) result += "\n" + card.toString(); return result; } public double getPlayerTotal() { return playerTotal; } public double getDealerTotal() { return dealerTotal; } public boolean playerIsBusted() { return playerTotal > 10.5; } public boolean dealerIsBusted() { return dealerTotal > 10.5; } public String getWinner() { String result = ""; if(playerTotal > 10.5) result = "Player Busted!"; else if(dealerTotal > 10.5) result = "Dealer Busted!"; else if(playerTotal > dealerTotal) result = "Player wins!"; else if(playerTotal < dealerTotal) result = "Dealer wins"; else if(playerTotal == dealerTotal) result = "Tie goes to the player!"; else result = "unexpected"; return result; } }
09644d32f6c5fa09c3115895615f33528e4fa09e
[ "Java", "Gradle" ]
4
Gradle
kingkung/CreateAndLearnTemplates
0b6b45f63bdcd02c8db5c116d7331a8e90d19885
159288a7d0ec2707b8187d84e926f15021dc97f5
refs/heads/master
<repo_name>DavidLXu/cpp<file_sep>/测量时间方法.cpp #include <iostream> #include <ctime> int main() { clock_t start = clock(); //...code you want to measure time clock_t end = clock(); double elapsed_time = (double (end) - double(start)) / (CLOCKS_PER_SEC); std::cout << "Elapsed time is:" << elapsed_time << " (s)" << std::endl; } //CLOCKS_PER_SEC是标准c的time.h头函数中宏定义的一个常数,表示一秒钟内CPU运行的时钟周期数, //用于将clock()函数的结果转化为以秒为单位的量,但是这个量的具体值是与操作系统相关的。 <file_sep>/FUNCTION, LINE和FILE.cpp //cout<<__FUNCTION__<<endl;输出所在的function名称 //cout<<__LINE__<<endl;输出该行行号 //cout<<__FILE__<<endl;输出所在文件名 int myfunction() { cout<<__FUNCTION__<<endl; cout<<__LINE__<<endl; } int main() { myfunction(); cout<<__FILE__<<endl; } <file_sep>/安装第三方库.md 使用配置是vscode+mingw 在windows下,gcc的include路径是在C:\MinGW\include 把第三方的库直接扔到这里就好了
da5b7544f960c8c7381a6ece8b127861b718e17b
[ "Markdown", "C++" ]
3
C++
DavidLXu/cpp
3ec1fe7710a01526a781c036bc300f1357f50a22
07ad6477cfb928eb9fb1e9da8a84e2f1b534a466
refs/heads/master
<repo_name>XXanderWP/FiveM-RichPresence<file_sep>/README.md # FiveM-RichPresence Simple resource that uses Discord's rich presence to display street name, vehicle and more <file_sep>/RichPresence/client.lua local WaitTime = 10000 -- How often do you want to update the status (In MS) Citizen.CreateThread(function() while true do local x,y,z = table.unpack(GetEntityCoords(PlayerPedId(),true)) local StreetHash = GetStreetNameAtCoord(x, y, z) Citizen.Wait(WaitTime) if StreetHash ~= nil then StreetName = GetStreetNameFromHashKey(StreetHash) if IsPedOnFoot(PlayerPedId()) and not IsEntityInWater(PlayerPedId()) then if IsPedRunning(PlayerPedId()) or GetEntitySpeed(PlayerPedId()) > 2.0 then SetRichPresence("Running down "..StreetName) elseif not IsPedRunning(PlayerPedId()) and GetEntitySpeed(PlayerPedId()) > 1.0 and GetEntitySpeed(PlayerPedId()) < 2.0 then SetRichPresence("Walking down "..StreetName) else SetRichPresence("Standing on "..StreetName) end elseif GetVehiclePedIsUsing(PlayerPedId()) ~= nil and not IsPedInAnyHeli(PlayerPedId()) and not IsPedInAnyPlane(PlayerPedId()) and not IsPedOnFoot(PlayerPedId()) and not IsPedInAnySub(PlayerPedId()) and not IsPedInAnyBoat(PlayerPedId()) then local MPH = math.ceil(GetEntitySpeed(GetVehiclePedIsUsing(PlayerPedId())) * 2.236936) local VehName = GetLabelText(GetDisplayNameFromVehicleModel(GetEntityModel(GetVehiclePedIsUsing(PlayerPedId())))) if MPH > 50 then SetRichPresence("Speeding down "..StreetName.." In a "..VehName) elseif MPH <= 50 and MPH > 0 then SetRichPresence("Cruising down "..StreetName.." In a "..VehName) elseif MPH == 0 then SetRichPresence("Parked on "..StreetName.." In a "..VehName) end elseif IsPedInAnyHeli(PlayerPedId()) or IsPedInAnyPlane(PlayerPedId()) then local VehName = GetLabelText(GetDisplayNameFromVehicleModel(GetEntityModel(GetVehiclePedIsUsing(PlayerPedId())))) if IsEntityInAir(GetVehiclePedIsUsing(PlayerPedId())) or GetEntityHeightAboveGround(GetVehiclePedIsUsing(PlayerPedId())) > 5.0 then SetRichPresence("Flying over "..StreetName.." in a "..VehName) else SetRichPresence("Landed at "..StreetName.." in a "..VehName) end elseif IsEntityInWater(PlayerPedId()) then SetRichPresence("Swimming around") elseif IsPedInAnyBoat(PlayerPedId()) and IsEntityInWater(GetVehiclePedIsUsing(PlayerPedId())) then local VehName = GetLabelText(GetDisplayNameFromVehicleModel(GetEntityModel(GetVehiclePedIsUsing(PlayerPedId())))) SetRichPresence("Sailing around in a "..VehName) elseif IsPedInAnySub(PlayerPedId()) and IsEntityInWater(GetVehiclePedIsUsing(PlayerPedId())) then SetRichPresence("In a yellow submarine") end end end end)
49f2c762fc18489823fbbfe6f2c57296f2e7c7fe
[ "Markdown", "Lua" ]
2
Markdown
XXanderWP/FiveM-RichPresence
a07c4dde190498cd31f61e59dad9779520487394
13abe67ea78737c3cd491f92046f41869de0ca6f
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.OracleClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace DatabaseConnect { public partial class Form1 : Form { OracleConnection ConnectionToOracle; //string connectionString = "DATA SOURCE=localhost;PASSWORD=<PASSWORD>;PERSIST SECURITY INFO=True;USER ID=system"; //string connectionString = "Data Source=127.0.0.1:1521/orcl;User Id=system;Password=<PASSWORD>"; string connectionString = "Data Source=127.0.0.1:1521;User Id=HR;Password=<PASSWORD>"; public Form1() { InitializeComponent(); ConnectionToOracle = new OracleConnection(connectionString); ConnectionToOracle.Open(); } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void Form1_Load(object sender, EventArgs e) { // TODO: данная строка кода позволяет загрузить данные в таблицу "dataSet1.EMPLOYEES". При необходимости она может быть перемещена или удалена. this.eMPLOYEESTableAdapter.Fill(this.dataSet1.EMPLOYEES); } private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e) { } private void button1_Click(object sender, EventArgs e) { OracleCommand cmd = new OracleCommand(); Object returnValue; int bookID = Convert.ToInt32(textBox2.Text); //команда запроса. Не забываем, что при запросе к БД //Oracle все названия пишутся в кавычках cmd.CommandText = "SELECT \"LAST_NAME\" FROM \"EMPLOYEES\" WHERE \"EMPLOYEES\".\"EMPLOYEE_ID\" = '" + bookID + "'"; cmd.Connection = ConnectionToOracle; returnValue = cmd.ExecuteScalar(); textBox1.Text = Convert.ToString(returnValue); } private void Form1_FormClosed_1(object sender, FormClosedEventArgs e) { ConnectionToOracle.Close(); } } }
2bbcc2eb65352afcfb89809949261ac9a3ec1c04
[ "C#" ]
1
C#
Andreyshabalinn/-4-
db91286062d16a5b5d385f30983a3de8d7b780c0
bdb1a755133368d139128ff1e544c4f6f5fbcb29
refs/heads/master
<repo_name>jatinn/number_guessing_game<file_sep>/game.rs use std::io; use std::rand; fn main() { println!("Guess the number!"); let secret_number = (rand::random::<uint>() % 100u) + 1u; loop { print!("Please input your guess (1-100): "); let input = io::stdin().read_line() .ok() .expect("Failed to read line"); let input_num: Option<uint> = from_str(input.as_slice().trim()); let num = match input_num { Some(num) => num, None => { println!("Please input a number!"); continue; } }; match (num, secret_number) { (x, y) if x > y => { println!("Too big!"); } (x, y) if y > x => { println!("Too small!"); } _ => { println!("You win!"); break;} } } } <file_sep>/game.py from random import randint def main(): secret_number = randint(1, 100) correct = False print "Guess the number!" while not correct: try: guess = int(raw_input("Please input your guess (1-100): ")) except ValueError: print "Please input a number!" continue if guess < secret_number: print "Too small!" elif guess > secret_number: print "Too big!" else: print "You win!" correct = True if __name__ == '__main__': main()
98117d59afc6d9dc349717664dc1a72653cad39a
[ "Rust", "Python" ]
2
Rust
jatinn/number_guessing_game
d81b0867421725f248624aad122d8d5633db7dd1
a337a14b1f1c5fa1ab0035d9bb7de771d5ae657b
refs/heads/master
<repo_name>DanhNT99/news-web<file_sep>/public/js/event2.js function Opennew(obj){ let subnav = document.querySelector(obj.subnav), btnList = subnav.querySelectorAll(obj.rules[0]), scRightList = subnav.querySelectorAll(obj.rules[1]); scRightList[0].classList.add('open'); btnList[0].classList.add('btn-more'); btnList.forEach((btn,index) => { btn.addEventListener('click', ()=> { for(let i = 0; i < scRightList.length; i++) { scRightList[i].classList.remove('open'); } for(let i = 0; i < btnList.length; i++) { btnList[i].classList.remove('btn-more'); } btn.classList.add('btn-more'); scRightList[index].classList.add('open'); }) }); } Opennew.isBtn = function (selected){ return selected; } Opennew.isContent = (selected)=> { return selected; } // function inputChecked() { // let searchMobile = document.querySelector(".nav_seacrh-mobile"), // afterForm = document.querySelector(".search_form-layout"); // if(input.checked == false) { // console.log(afterForm.after); // } // } /* thử làm khi click vào thì tạo ra div chèn vào đó có nghia là lúc đầu chỉ có 1 div ở trong và tạo ra div khác chèn vào đó */
485b3491362bce902a811f1102102e978a05d678
[ "JavaScript" ]
1
JavaScript
DanhNT99/news-web
150bf0b1a44d90b794beaeb9d518d8b703dc1828
d6de5feda549eff48fb18a0f892e7a629aed88e9
refs/heads/master
<file_sep>// // User+CoreDataClass.swift // Task // // Created by <NAME> on 04/03/18. // Copyright © 2018 <NAME>. All rights reserved. // // import Foundation import CoreData @objc(User) public class User: NSManagedObject { } <file_sep>// // ViewController.swift // Task // // Created by <NAME> on 04/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import CoreData let dbSharedInstance = DBHandler.shared class ViewController: UIViewController { let appDelegate = UIApplication.shared.delegate as! AppDelegate let progressHUD = ProgressHUD(text: "Loading users...") @IBOutlet weak var userTableView: UITableView! fileprivate var usersArray = [User]() { didSet { DispatchQueue.main.async { self.userTableView.reloadData() self.progressHUD.hide() } } } override func viewDidLoad() { super.viewDidLoad() dbSharedInstance.delegate = self self.view.addSubview(progressHUD) progressHUD.show() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let users = dbSharedInstance.fetchUsers() { usersArray = users } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) getUsersData() } func getUsersData(){ guard let testDataUrl = URL(string: "https://jsonplaceholder.typicode.com/users") else { return } URLSession.shared.dataTask(with: testDataUrl) { (data, response , error) in guard let data = data else { return } do { let decoder = JSONDecoder() let usersData = try decoder.decode([UserModel].self, from: data) dbSharedInstance.saveOrUpdate(users: usersData) } catch let err { print("Err", err) } }.resume() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return usersArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell:UserCell = tableView.dequeueReusableCell(withIdentifier: "userCellID") as? UserCell else { return UITableViewCell() } cell.selectionStyle = .none cell.setUpCellWith(user: usersArray[indexPath.row], atIndexPath: indexPath) return cell } } extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let detailVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DetailViewID") as! DetailViewController detailVC.userDetails = usersArray[indexPath.row] self.addChildViewController(detailVC) detailVC.view.frame = self.view.bounds self.view.addSubview(detailVC.view) detailVC.didMove(toParentViewController: self) } } extension ViewController: DBHandlerDelegate{ func dbUpdated() { if let users = dbSharedInstance.fetchUsers() { usersArray = users } } } <file_sep>// // DBHandler.swift // Task // // Created by <NAME> on 04/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import Foundation import CoreData //For updating Database changes protocol DBHandlerDelegate { func dbUpdated() } class DBHandler { static let shared = DBHandler() let appDelegate = UIApplication.shared.delegate as! AppDelegate var delegate: DBHandlerDelegate? private init(){ // Get notification from Core Data whenever database is changed let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(managedObjectContextObjectsDidChange), name: NSNotification.Name.NSManagedObjectContextObjectsDidChange, object: appDelegate.persistentContainer.viewContext) } @objc func managedObjectContextObjectsDidChange(notification: NSNotification) { guard let _ = notification.userInfo else { return } delegate?.dbUpdated() } //Save or Update Database func saveOrUpdate(users: [UserModel]) { for user in users { let managedContext = appDelegate.persistentContainer.viewContext let request = NSFetchRequest<NSFetchRequestResult>(entityName: "User") let predicate = NSPredicate(format: "id == %d", user.id) request.predicate = predicate request.fetchLimit = 1 do{ // Check if User exists with same id - to avoid duplicates let count = try managedContext.count(for: request) if(count == 0){ // no matching object let userEntity = NSEntityDescription.entity(forEntityName: "User", in: managedContext)! let userManagedObject = User(entity: userEntity, insertInto: managedContext) userManagedObject.setValue(user.id, forKey: "id") userManagedObject.setValue(user.name, forKey: "name") userManagedObject.setValue(user.username, forKey: "username") userManagedObject.setValue(user.email, forKey: "email") userManagedObject.setValue(user.phone, forKey: "phone") userManagedObject.setValue(user.website, forKey: "website") } else{ // at least one matching object exists } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } appDelegate.saveContext() } } //Get Data from Database func fetchUsers() -> [User]?{ let managedContext = appDelegate.persistentContainer.viewContext let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "User") let sort = NSSortDescriptor(key: "id", ascending: true) fetchRequest.sortDescriptors = [sort] do { let users: [User] = try managedContext.fetch(fetchRequest) as! [User] return users } catch let error as NSError { print("Could not fetch. \(error), \(error.userInfo)") } return nil } } <file_sep>// // UserCell.swift // Task // // Created by <NAME> on 04/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class UserCell: UITableViewCell { @IBOutlet weak var idLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setUpCellWith(user: User, atIndexPath indexPath: IndexPath) { idLabel.text = "\(user.id)" if let name = user.name { nameLabel.text = name } } } <file_sep>// // User.swift // Task // // Created by <NAME> on 04/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation struct UserModel: Codable { var id: Int var name: String var username: String var email: String var phone: String var website: String } <file_sep>// // DetailViewController.swift // Task // // Created by <NAME> on 05/03/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import CoreData class DetailViewController: UIViewController { @IBOutlet weak var idLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var emailLabel: UILabel! @IBOutlet weak var phoneLabel: UILabel! @IBOutlet weak var websiteLabel: UILabel! @IBOutlet weak var popUpView: UIView! var userDetails: User! override func viewDidLoad() { super.viewDidLoad() let black = UIColor.black let semi = black.withAlphaComponent(0.4) self.view.backgroundColor = semi self.popUpView.layer.cornerRadius = 5.0 showAnimate() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.idLabel.text = "ID: \(userDetails.id)" self.nameLabel.text = "Name: \(String(describing: userDetails.name!))" self.usernameLabel.text = "Username: \(String(describing: userDetails.username!))" self.emailLabel.text = "Email: \(String(describing: userDetails.email!))" self.phoneLabel.text = "Phone: \(String(describing: userDetails.phone!))" self.websiteLabel.text = "Website: \(String(describing: userDetails.website!))" } func showAnimate() { self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3) self.view.alpha = 0.0 UIView.animate(withDuration: 0.25, animations: { self.view.alpha = 1.0 self.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) }) } func removeAnimate() { UIView.animate(withDuration: 0.25, animations: { self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3) self.view.alpha = 0.0 }, completion: {(finished : Bool) in if(finished) { self.view.removeFromSuperview() } }) } @IBAction func closeAction(_ sender: Any) { removeAnimate() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
82c7aa5d947f2f18e5cf9c408426930febcdf0c0
[ "Swift" ]
6
Swift
sureshvutukuru/Task
75aba1628dbcb4a63badcf8a7b2eadb43f6a0bc3
d4a73c30e5bcdcce77fdf78fa689f7119972b69e
refs/heads/master
<file_sep>package foodbook.thinmint.models.domain; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by Zachery.Sogolow on 5/9/2017. */ public class Note extends EntityBase { @SerializedName("userID") private long mUserId; @SerializedName("user") private User mUser; @SerializedName("content") private String mContent; @SerializedName("comments") private List<Comment> mComments; @SerializedName("likes") private List<Like> mLikes; public Note() { super(); } public long getUserId() { return mUserId; } public void setUserId(long userId) { this.mUserId = userId; } public User getUser() { return mUser; } public void setUser(User user) { this.mUser = user; } public String getContent() { return mContent; } public void setContent(String content) { this.mContent = content; } public List<Comment> getComments() { return mComments; } public void setComments(List<Comment> comments) { this.mComments = comments; } public List<Like> getLikes() { return mLikes; } public void setLikes(List<Like> likes) { this.mLikes = likes; } } <file_sep>package foodbook.thinmint.tasks; import android.content.Context; import android.os.AsyncTask; import foodbook.thinmint.api.Query; import foodbook.thinmint.api.WebAPIConnect; import foodbook.thinmint.api.WebAPIResult; import foodbook.thinmint.constants.Constants; import foodbook.thinmint.idsrv.Token; import foodbook.thinmint.idsrv.TokenHelper; import foodbook.thinmint.idsrv.TokenResult; /** * Created by Zachery.Sogolow on 5/9/2017. */ public class GetAsyncTask extends AsyncTask<Query, String, WebAPIResult> { private Context mContext; private AsyncCallback<WebAPIResult> mCallback; private Token mToken; public GetAsyncTask(Context context, AsyncCallback<WebAPIResult> callback, Token token) { this.mContext = context; this.mCallback = callback; this.mToken = token; } @Override protected WebAPIResult doInBackground(Query... params) { // params[0] is path WebAPIResult result = null; Query query = params[0]; WebAPIConnect connect = new WebAPIConnect(); publishProgress("Getting data..."); if (TokenHelper.isTokenExpired(mToken)) { TokenResult tokenResult = mToken.getRefreshToken(Constants.CLIENT_ID, Constants.CLIENT_SECRET); Token tempToken = TokenHelper.getTokenFromJson(tokenResult); TokenHelper.saveToken(mContext, tempToken); TokenHelper.copyToken(tempToken, mToken); } if (!TokenHelper.isTokenExpired(mToken)) { result = connect.get(query, mToken.getAccessToken()); } return result; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onPostExecute(WebAPIResult result) { mCallback.onCompleted(result); mCallback.onPostExecute(this); } @Override protected void onProgressUpdate(String... values) { super.onProgressUpdate(values); } @Override protected void onCancelled() { super.onCancelled(); } } <file_sep>package foodbook.thinmint.api; /** * Created by ZachS on 5/9/2017. */ public class PagingInfo { private long mCurrentPage; private long mPageSize; private long mTotalCount; private long mTotalPages; private String mPrevPageLink; private String mNextPageLink; public PagingInfo(long currentPage, long pageSize, long totalCount, long totalPages, String prevPageLink, String nextPageLink) { this.mCurrentPage = currentPage; this.mPageSize = pageSize; this.mTotalCount = totalCount; this.mTotalPages = totalPages; this.mPrevPageLink = prevPageLink; this.mNextPageLink = nextPageLink; } public long getCurrentPage() { return mCurrentPage; } public void setCurrentPage(long currentPage) { this.mCurrentPage = currentPage; } public long getPageSize() { return mPageSize; } public void setPageSize(long pageSize) { this.mPageSize = pageSize; } public long getTotalCount() { return mTotalCount; } public void setTotalCount(long totalCount) { this.mTotalCount = totalCount; } public long getTotalPages() { return mTotalPages; } public void setTotalPages(long totalPages) { this.mTotalPages = totalPages; } public String getPrevPageLink() { return mPrevPageLink; } public void setPrevPageLink(String prevPageLink) { this.mPrevPageLink = prevPageLink; } public String getNextPageLink() { return mNextPageLink; } public void setNextPageLink(String nextPageLink) { this.mNextPageLink = nextPageLink; } } <file_sep>package foodbook.thinmint.activities.adapters.users.list; import android.app.Activity; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import foodbook.thinmint.R; import foodbook.thinmint.activities.adapters.common.AbstractListRecyclerAdapter; import foodbook.thinmint.activities.adapters.common.AbstractListViewHolder; import foodbook.thinmint.models.domain.User; /** * Created by Zachery.Sogolow on 5/18/2017. */ public class UsersListRecyclerAdapter extends AbstractListRecyclerAdapter<User, IOnUsersListClickListener> { // Provide a suitable constructor (depends on the kind of dataset) public UsersListRecyclerAdapter(List<User> users, IOnUsersListClickListener listener, Activity activity) { super(users, listener, activity); } // Create new views (invoked by the layout manager) @Override public UsersListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view LinearLayout v = (LinearLayout) LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_user, parent, false); // set the view's size, margins, paddings and layout parameters UsersListViewHolder vh = new UsersListViewHolder(v, mListener); return vh; } // Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(AbstractListViewHolder<IOnUsersListClickListener> holder, int position) { // - get element from your dataset at this position // - replace the contents of the view with that element ((TextView) holder.mLinearLayout.findViewById(R.id.user_name)) .setText(mItems.get(position).getUsername()); ((TextView) holder.mLinearLayout.findViewById(R.id.hidden_user_id)) .setText(mItems.get(position).getSubject()); } } <file_sep>package foodbook.thinmint.activities.notes; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import foodbook.thinmint.IApiCallback; import foodbook.thinmint.IAsyncCallback; import foodbook.thinmint.R; import foodbook.thinmint.activities.common.ActivityHelper; import foodbook.thinmint.activities.common.TokenFragment; import foodbook.thinmint.activities.adapters.notes.item.IOnNoteClickListener; import foodbook.thinmint.activities.adapters.notes.item.NoteRecyclerAdapter; import foodbook.thinmint.api.WebAPIResult; import foodbook.thinmint.models.JsonHelper; import foodbook.thinmint.models.domain.Comment; import foodbook.thinmint.models.domain.EntityBase; import foodbook.thinmint.models.domain.Like; import foodbook.thinmint.models.domain.Note; import foodbook.thinmint.models.views.ListItem; import foodbook.thinmint.models.views.ListItemTypes; import foodbook.thinmint.tasks.AsyncCallback; import foodbook.thinmint.tasks.TasksHelper; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link OnNoteFragmentDataListener} interface * to handle interaction events. * Use the {@link NoteFragment#newInstance} factory method to * create an instance of this fragment. */ public class NoteFragment extends TokenFragment implements IOnNoteClickListener { private static final String ARG_NOTEID = "noteid"; private static final String ARG_COMMENTFLAG = "commentflag"; private long mNoteId; private boolean mCommentFlag; private OnNoteFragmentDataListener mListener; private RecyclerView mListView; private SwipeRefreshLayout mSwipeRefreshLayout; private NoteRecyclerAdapter mAdapter; private LinearLayoutManager mLayoutManager; private TextView mHiddenUserSubject; private AsyncCallback<WebAPIResult> mGetNoteCallback; private AsyncCallback<WebAPIResult> mDeleteNoteCallback; private AsyncCallback<WebAPIResult> mAddCommentCallback; private AsyncCallback<WebAPIResult> mLikeCallback; private AsyncCallback<WebAPIResult> mUnlikeCallback; public NoteFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param noteId Parameter 1. * @return A new instance of fragment FeedFragment. */ public static NoteFragment newInstance(long noteId, boolean commentFlag) { NoteFragment fragment = new NoteFragment(); Bundle args = new Bundle(); args.putLong(ARG_NOTEID, noteId); args.putBoolean(ARG_COMMENTFLAG, commentFlag); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mNoteId = getArguments().getLong(ARG_NOTEID); mCommentFlag = getArguments().getBoolean(ARG_COMMENTFLAG); } initToken(); initUser(); mGetNoteCallback = new AsyncCallback<>(this); mDeleteNoteCallback = new AsyncCallback<>(this); mAddCommentCallback = new AsyncCallback<>(this); mLikeCallback = new AsyncCallback<>(this); mUnlikeCallback = new AsyncCallback<>(this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View inflated = inflater.inflate(R.layout.fragment_note, container, false); mListView = (RecyclerView) inflated.findViewById(R.id.activity_main_listview); mSwipeRefreshLayout = (SwipeRefreshLayout) inflated.findViewById(R.id.activity_note_swipe_refresh_layout); mHiddenUserSubject = (TextView) inflated.findViewById(R.id.hidden_user_id); // use a linear layout manager mLayoutManager = new LinearLayoutManager(getActivity()); mListView.setLayoutManager(mLayoutManager); List<ListItem<EntityBase>> models = new ArrayList<>(); models.add(new ListItem<>(ListItemTypes.Note, null)); models.add(new ListItem<>(ListItemTypes.AddComment, null)); mAdapter = new NoteRecyclerAdapter(models, this, getActivity()); mListView.setAdapter(mAdapter); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { refreshFragment(); } }); mListener.onNoteFragmentCreated(inflated); return inflated; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnNoteFragmentDataListener) { mListener = (OnNoteFragmentDataListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnNoteFragmentDataListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onStart() { super.onStart(); refreshFragment(); } @Override public void onStop() { super.onStop(); if (mRunningTask != null) { mRunningTask.cancel(true); } } private void setLoading(boolean isLoading) { mSwipeRefreshLayout.setRefreshing(isLoading); } @Override protected void refreshFragment() { setLoading(true); mRunningTask = TasksHelper.getNote(getContext(), mGetNoteCallback, mToken, mNoteId); } private void onNoteRetrieved(Note note) { setLoading(false); mHiddenUserSubject.setText(note.getUser().getSubject()); List<ListItem<EntityBase>> models = new ArrayList<>(); models.add(new ListItem<EntityBase>(ListItemTypes.Note, note)); models.add(new ListItem<EntityBase>(ListItemTypes.AddComment, null)); for (Comment comment : note.getComments()) { models.add(new ListItem<EntityBase>(ListItemTypes.Comment, comment)); } mAdapter.swap(models); new Handler().postDelayed(new Runnable() { @Override public void run() { if (mCommentFlag) { mCommentFlag = false; EditText editText = (EditText) mListView.findViewById(R.id.comment_edit_text); editText.requestFocus(); ActivityHelper.showSoftKeyboard(getActivity()); } } }, 250); } private void onNoteDeleted(boolean success) { setLoading(false); if (success) { mListener.onNoteDeleted(mNoteId); } } private void onCommentAdded(Comment comment) { mAdapter.add(2, new ListItem<EntityBase>(ListItemTypes.Comment, comment)); refreshFragment(); } private void onLikeChanged() { refreshFragment(); } private void onCommentFailed() { setLoading(false); } public void deleteNote() { setLoading(true); TasksHelper.deleteNote(getContext(), mDeleteNoteCallback, mToken, mNoteId); } @Override public void onAddCommentClick(EditText editText) { setLoading(true); String comment = editText.getText().toString(); TasksHelper.addComment(getContext(), mAddCommentCallback, mToken, mNoteId, mUserId, comment); ActivityHelper.hideSoftKeyboard(getActivity()); } @Override public void onUserClick(View view) { TextView hiddenUserIdTextView = (TextView) view.findViewById(R.id.hidden_user_id); TextView userNameTextView = (TextView) view.findViewById(R.id.user_name); String userId = hiddenUserIdTextView.getText().toString(); String username = userNameTextView.getText().toString(); ActivityHelper.startUserActivity(getActivity(), userId, username); } @Override public void onCommentButtonClick(View view) { TextView hiddenUserIdTextView = (TextView) view.findViewById(R.id.hidden_user_id); TextView userNameTextView = (TextView) view.findViewById(R.id.user_name); String userId = hiddenUserIdTextView.getText().toString(); String username = userNameTextView.getText().toString(); EditText editText = (EditText) mListView.findViewById(R.id.comment_edit_text); editText.requestFocus(); ActivityHelper.showSoftKeyboard(getActivity()); } @Override public void onLikeButtonClick(View view) { TextView hiddenNoteIdTextView = (TextView) view.findViewById(R.id.hidden_note_id); long noteId = Long.parseLong(hiddenNoteIdTextView.getText().toString()); setLoading(true); TasksHelper.likeNote(getContext(), mLikeCallback, mToken, noteId, mUserId); } @Override public void onUnlikeButtonClick(View view) { TextView hiddenNoteIdTextView = (TextView) view.findViewById(R.id.hidden_note_id); long noteId = Long.parseLong(hiddenNoteIdTextView.getText().toString()); setLoading(true); TasksHelper.unlikeNote(getContext(), mUnlikeCallback, mToken, noteId, mUserId); } @Override public void onClick(View caller) { } @Override public void callback(IAsyncCallback cb) { super.callback(cb); if (cb.equals(mGetNoteCallback)) { Note note = JsonHelper.getNote(mGetNoteCallback.getResult().getResult()); onNoteRetrieved(note); mListener.onNoteRetrieved(note); } else if (cb.equals(mDeleteNoteCallback)) { boolean success = mDeleteNoteCallback.getResult().isSuccess(); onNoteDeleted(success); } else if (cb.equals(mAddCommentCallback)) { WebAPIResult result = mAddCommentCallback.getResult(); if (result.isSuccess()) { Comment addedComment = JsonHelper.getComment(mAddCommentCallback.getResult().getResult()); onCommentAdded(addedComment); mListener.onCommentAdded(addedComment); } else { onCommentFailed(); } } else if (cb.equals(mLikeCallback)) { WebAPIResult result = mLikeCallback.getResult(); if (result.isSuccess()) { Like addedLike = JsonHelper.getLike(mLikeCallback.getResult().getResult()); onLikeChanged(); mListener.onLikeAdded(addedLike); } } else if (cb.equals(mUnlikeCallback)) { WebAPIResult result = mUnlikeCallback.getResult(); if (result.isSuccess()) { onLikeChanged(); } } } public interface OnNoteFragmentDataListener { void onNoteFragmentCreated(View view); void onNoteRetrieved(Note note); void onNoteDeleted(long noteId); void onCommentAdded(Comment comment); void onLikeAdded(Like like); } } <file_sep>package foodbook.thinmint.tasks; import android.content.Context; import android.os.AsyncTask; import android.support.v7.widget.Toolbar; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import foodbook.thinmint.R; import foodbook.thinmint.activities.common.ActivityHelper; import foodbook.thinmint.api.Query; import foodbook.thinmint.api.WebAPIResult; import foodbook.thinmint.idsrv.Token; /** * Created by ZachS on 5/29/2017. */ public class TasksHelper { public static AsyncTask likeNote(Context context, AsyncCallback<WebAPIResult> callback, Token token, long noteId, long userId) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z", Locale.US); Map<String, Object> map = new HashMap<>(); map.put("noteid", noteId); map.put("userid", userId); map.put("datecreated", dateFormat.format(new Date(System.currentTimeMillis()))); PostAsyncTask task = new PostAsyncTask(context, callback, token, map); task.execute("api/likes"); return task; } public static AsyncTask unlikeNote(Context context, AsyncCallback<WebAPIResult> callback, Token token, long noteId, long userId) { DeleteAsyncTask task = new DeleteAsyncTask(context, callback, token); Query query = Query.builder() .setPath(String.format(Locale.US, "api/notes/%d/likes/%d", noteId, userId)) .build(); task.execute(query); return task; } public static AsyncTask getNote(Context context, AsyncCallback<WebAPIResult> callback, Token token, long noteId) { GetAsyncTask task = new GetAsyncTask(context, callback, token); String path = "api/notes/" + noteId; Query query = Query.builder() .setPath(path) .build(); task.execute(query); return task; } public static AsyncTask deleteNote(Context context, AsyncCallback<WebAPIResult> callback, Token token, long noteId) { DeleteAsyncTask task = new DeleteAsyncTask(context, callback, token); Query query = Query.builder() .setPath("api/notes/" + noteId) .build(); task.execute(query); return task; } public static AsyncTask getNotes(Context context, AsyncCallback<WebAPIResult> callback, Token token, String userSubject, int page, String filter) { String path = String.format(Locale.US, "api/users/%s/notes", userSubject); Query query = Query.builder() .setPath(path) .setSort("-datecreated") .setFilter(filter) .setPage(page) .build(); GetAsyncTask task = new GetAsyncTask(context, callback, token); task.execute(query); return task; } public static AsyncTask getNotes(Context context, AsyncCallback<WebAPIResult> callback, Token token, int page, String filter) { String path = "api/notes"; Query query = Query.builder() .setPath(path) .setSort("-datecreated") .setFilter(filter) .setPage(page) .build(); GetAsyncTask task = new GetAsyncTask(context, callback, token); task.execute(query); return task; } public static AsyncTask addComment(Context context, AsyncCallback<WebAPIResult> callback, Token token, long noteId, long userId, String comment) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z", Locale.US); Map<String, Object> map = new HashMap<>(); map.put("noteid", noteId); map.put("userid", userId); map.put("text", comment); map.put("datecreated", dateFormat.format(new Date(System.currentTimeMillis()))); PostAsyncTask task = new PostAsyncTask(context, callback, token, map); task.execute("api/comments"); return task; } public static AsyncTask getUsers(Context context, AsyncCallback<WebAPIResult> callback, Token token, int page, String filter) { Query query = Query.builder() .setPath("api/users") .setSort("username") .setFilter(filter) .setPage(page) .build(); GetAsyncTask task = new GetAsyncTask(context, callback, token); task.execute(query); return task; } } <file_sep>package foodbook.thinmint.activities.day; import android.content.Context; import android.support.annotation.Nullable; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import foodbook.thinmint.IApiCallback; import foodbook.thinmint.IAsyncCallback; import foodbook.thinmint.R; import foodbook.thinmint.activities.common.ActivityHelper; import foodbook.thinmint.activities.MainActivity; import foodbook.thinmint.activities.common.TokenFragment; import foodbook.thinmint.activities.adapters.EndlessRecyclerViewScrollListener; import foodbook.thinmint.activities.adapters.notes.list.IOnNotesListClickListener; import foodbook.thinmint.activities.common.OnNotesListInteractionListener; import foodbook.thinmint.activities.adapters.notes.list.NotesListRecyclerAdapter; import foodbook.thinmint.api.WebAPIResult; import foodbook.thinmint.models.JsonHelper; import foodbook.thinmint.models.domain.Like; import foodbook.thinmint.models.domain.Note; import foodbook.thinmint.tasks.AsyncCallback; import foodbook.thinmint.tasks.TasksHelper; public class DayFragment extends TokenFragment implements OnNotesListInteractionListener, IOnNotesListClickListener { private static final String ARG_DATE = "date"; private Date mCurrentDate; private OnDayFragmentDataListener mListener; private RecyclerView mListView; private SwipeRefreshLayout mSwipeRefreshLayout; private NotesListRecyclerAdapter mAdapter; private LinearLayoutManager mLayoutManager; private AsyncCallback<WebAPIResult> mGetNoteCallback; private AsyncCallback<WebAPIResult> mGetNotesCallback; private AsyncCallback<WebAPIResult> mLoadMoreCallback; private AsyncCallback<WebAPIResult> mLikeCallback; private AsyncCallback<WebAPIResult> mUnlikeCallback; private long mLastNoteId; private EndlessRecyclerViewScrollListener mScrollListener; public DayFragment() { } public static DayFragment newInstance(Date date) { DayFragment fragment = new DayFragment(); Bundle args = new Bundle(); args.putString(ARG_DATE, MainActivity.PARSABLE_DATE_FORMAT.format(date)); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { String dateString = getArguments().getString(ARG_DATE); try { mCurrentDate = MainActivity.PARSABLE_DATE_FORMAT.parse(dateString); } catch (ParseException pe) { mCurrentDate = new Date(System.currentTimeMillis()); } } initToken(); initUser(); mGetNoteCallback = new AsyncCallback<>(this); mGetNotesCallback = new AsyncCallback<>(this); mLoadMoreCallback = new AsyncCallback<>(this); mLikeCallback = new AsyncCallback<>(this); mUnlikeCallback = new AsyncCallback<>(this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View inflated = inflater.inflate(R.layout.fragment_day, container, false); mListView = (RecyclerView) inflated.findViewById(R.id.activity_main_listview); mSwipeRefreshLayout = (SwipeRefreshLayout) inflated.findViewById(R.id.activity_main_swipe_refresh_layout); // use a linear layout manager mLayoutManager = new LinearLayoutManager(getActivity()); mListView.setLayoutManager(mLayoutManager); mAdapter = new NotesListRecyclerAdapter(new ArrayList<Note>(), this, getActivity()); mListView.setAdapter(mAdapter); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { refreshFragment(); } }); mListener.onDayFragmentCreated(inflated); mScrollListener = new EndlessRecyclerViewScrollListener(mLayoutManager) { @Override public void onLoadMore(int page, int totalItemsCount, RecyclerView view) { Calendar calendar = Calendar.getInstance(); calendar.setTime(mCurrentDate); String rawQuery = String.format(Locale.US, "((DateCreated Ge %d-%d-%d 00:00:00 -0700) And (DateCreated Le %d-%d-%d 23:59:59 -0700))", calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH)); mRunningTask = TasksHelper.getNotes(getContext(), mLoadMoreCallback, mToken, mUserSubject, page + 1, rawQuery); } }; return inflated; } @Override public void onAttach(Context activity) { super.onAttach(activity); // This makes sure that the container activity has implemented // the callback interface. If not, it throws an exception try { mListener = (OnDayFragmentDataListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onStart() { super.onStart(); refreshFragment(); } @Override public void onStop() { super.onStop(); if (mRunningTask != null) { mRunningTask.cancel(true); } } @Override public void onLikeNoteClick(View caller) { TextView hiddenNoteIdTextView = (TextView) caller.findViewById(R.id.hidden_note_id); long noteId = Long.parseLong(hiddenNoteIdTextView.getText().toString()); setLoading(true); TasksHelper.likeNote(getContext(), mLikeCallback, mToken, noteId, mUserId); } @Override public void onUnlikeButtonClick(View view) { TextView hiddenNoteIdTextView = (TextView) view.findViewById(R.id.hidden_note_id); long noteId = Long.parseLong(hiddenNoteIdTextView.getText().toString()); mLastNoteId = noteId; setLoading(true); TasksHelper.unlikeNote(getContext(), mUnlikeCallback, mToken, noteId, mUserId); } @Override public void onNoteClick(View caller) { TextView hiddenNoteIdTextView = (TextView) caller.findViewById(R.id.hidden_note_id); String noteId = hiddenNoteIdTextView.getText().toString(); ActivityHelper.startNoteActivityForResult(getActivity(), Long.parseLong(noteId), false); } @Override public void onCommentClick(View caller) { TextView hiddenNoteIdTextView = (TextView) caller.findViewById(R.id.hidden_note_id); String noteId = hiddenNoteIdTextView.getText().toString(); ActivityHelper.startNoteActivityForResult(getActivity(), Long.parseLong(noteId), true); } @Override public void onUserClick(View caller) { TextView hiddenUserIdTextView = (TextView) caller.findViewById(R.id.hidden_user_id); TextView userNameTextView = (TextView) caller.findViewById(R.id.user_name); String userId = hiddenUserIdTextView.getText().toString(); String username = userNameTextView.getText().toString(); ActivityHelper.startUserActivity(getActivity(), userId, username); } @Override protected void refreshFragment() { setLoading(true); mScrollListener.resetState(); Calendar calendar = Calendar.getInstance(); calendar.setTime(mCurrentDate); String rawQuery = String.format(Locale.US, "((DateCreated Ge %d-%d-%d 00:00:00 -0700) And (DateCreated Le %d-%d-%d 23:59:59 -0700))", calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH)); mRunningTask = TasksHelper.getNotes(getContext(), mGetNotesCallback, mToken, mUserSubject, 1, rawQuery); } private void setLoading(boolean isLoading) { mSwipeRefreshLayout.setRefreshing(isLoading); } private void onNotesRetrieved(List<Note> notes) { mAdapter.swap(notes); setLoading(false); } private void onNoteRetrieved(Note note) { mAdapter.replace(note); setLoading(false); } private void onLoadedMore(List<Note> notes) { mAdapter.addAll(notes); } @Override public void onNoteAdded(long noteId) { refreshFragment(); } @Override public void onNoteDeleted(long noteId) { mAdapter.remove(noteId); } @Override public void onCommentAdded(long noteId) { mRunningTask = TasksHelper.getNote(getContext(), mGetNoteCallback, mToken, noteId); } @Override public void onLikeAdded(long noteId) { mRunningTask = TasksHelper.getNote(getContext(), mGetNoteCallback, mToken, noteId); } @Override public void callback(IAsyncCallback cb) { super.callback(cb); if (cb.equals(mGetNotesCallback)) { List<Note> notes = JsonHelper.getNotes(mGetNotesCallback.getResult().getResult()); onNotesRetrieved(notes); } else if (cb.equals(mLoadMoreCallback)) { List<Note> notes = JsonHelper.getNotes(mLoadMoreCallback.getResult().getResult()); onLoadedMore(notes); } else if (cb.equals(mGetNoteCallback)) { Note note = JsonHelper.getNote(mGetNoteCallback.getResult().getResult()); onNoteRetrieved(note); } else if (cb.equals(mLikeCallback)) { WebAPIResult result = mLikeCallback.getResult(); if (result.isSuccess()) { Like addedLike = JsonHelper.getLike(mLikeCallback.getResult().getResult()); onLikeAdded(addedLike.getNoteId()); } } else if (cb.equals(mUnlikeCallback)) { WebAPIResult result = mUnlikeCallback.getResult(); if (result.isSuccess()) { onLikeAdded(mLastNoteId); } } } public void setDate(Date date) { mCurrentDate = date; refreshFragment(); } public interface OnDayFragmentDataListener { void onDayFragmentCreated(View view); void selectDay(Date date); } } <file_sep>package foodbook.thinmint.activities.adapters.notes.list; import android.view.View; /** * Created by Zachery.Sogolow on 5/26/2017. */ public interface IOnNotesListClickListener { void onNoteClick(View caller); void onCommentClick(View caller); void onUserClick(View caller); void onLikeNoteClick(View caller); void onUnlikeButtonClick(View view); } <file_sep>package foodbook.thinmint.activities.adapters.users.list; import android.view.View; /** * Created by Zachery.Sogolow on 5/26/2017. */ public interface IOnUsersListClickListener { void onUserClick(View caller); } <file_sep>package foodbook.thinmint.activities; import android.content.SharedPreferences; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import foodbook.thinmint.activities.common.ActivityHelper; import foodbook.thinmint.api.Query; import foodbook.thinmint.api.WebAPIConnect; import foodbook.thinmint.api.WebAPIResult; import foodbook.thinmint.constants.Constants; import foodbook.thinmint.idsrv.Token; import foodbook.thinmint.idsrv.TokenHelper; import foodbook.thinmint.idsrv.TokenResult; import foodbook.thinmint.idsrv.UserInfo; import foodbook.thinmint.idsrv.UserInfoHelper; import foodbook.thinmint.idsrv.UserInfoResult; import foodbook.thinmint.models.JsonHelper; import foodbook.thinmint.models.domain.User; public class SplashActivity extends AppCompatActivity { private RefreshTokenAsyncTask mRefreshTask = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); if (!prefs.getString(Constants.ACCESS_TOKEN_PREFERENCE_KEY, "").equals("")) { // check if expired // refresh if necessary and store new stuff Token token = new Token(); token.setAccessToken(prefs.getString(Constants.ACCESS_TOKEN_PREFERENCE_KEY, "")); token.setRefreshToken(prefs.getString(Constants.REFRESH_TOKEN_PREFERENCE_KEY, "")); token.setExpiresIn(prefs.getString(Constants.EXPIRES_IN_PREFERENCE_KEY, "")); token.setLastRetrieved(prefs.getLong(Constants.LAST_RETRIEVED_PREFERENCE_KEY, 0)); if (TokenHelper.isTokenExpired(token)) { mRefreshTask = new RefreshTokenAsyncTask(token); mRefreshTask.execute(); } else { ActivityHelper.finishLogin(this); } } else { ActivityHelper.startLogin(this); } } private class RefreshTokenAsyncTask extends AsyncTask<String, String, TokenResult> { private Token mToken; RefreshTokenAsyncTask(Token token) { mToken = token; } @Override protected TokenResult doInBackground(String... params) { publishProgress("Getting refresh token..."); TokenResult result = mToken.getRefreshToken(Constants.CLIENT_ID, Constants.CLIENT_SECRET); if (result.isSuccess()) { Token tempToken = TokenHelper.getTokenFromJson(result); TokenHelper.saveToken(SplashActivity.this, tempToken); TokenHelper.copyToken(tempToken, mToken); UserInfoResult userInfoResult = mToken.getUserInfo(); UserInfo userInfo = UserInfoHelper.getUserInfoFromJson(userInfoResult.getUserInfoResult()); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); prefs.edit().putString(Constants.USER_SUBJECT, userInfo.getSubject()).apply(); Query query = Query.builder() .setPath("api/users/" + userInfo.getSubject()) // .setAccessToken(mToken.getAccessToken()) .build(); WebAPIResult apiResult = new WebAPIConnect().get(query, mToken.getAccessToken()); User user = JsonHelper.getUser(apiResult.getResult()); prefs.edit().putLong(Constants.USER_ID, user.getId()).apply(); prefs.edit().putString(Constants.USER_NAME, user.getUsername()).apply(); } return result; } @Override protected void onPostExecute(TokenResult result) { mRefreshTask = null; if (result.isSuccess()) { ActivityHelper.finishLogin(SplashActivity.this); } else { ActivityHelper.startLogin(SplashActivity.this); } } @Override protected void onCancelled() { mRefreshTask = null; } } } <file_sep>package foodbook.thinmint.idsrv; /** * Created by Zachery.Sogolow on 5/9/2017. */ public class UserInfoResult { private boolean mSuccess; private String mUserInfoResult; public UserInfoResult() { mSuccess = false; mUserInfoResult = ""; } public UserInfoResult(boolean success, String result) { mSuccess = success; mUserInfoResult = result; } public boolean isSuccess() { return mSuccess; } public String getUserInfoResult() { return mUserInfoResult; } public void setSuccess(boolean success) { this.mSuccess = success; } public void setUserInfoResult(String userInfoResult) { this.mUserInfoResult = userInfoResult; } } <file_sep>package foodbook.thinmint.activities.notes; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AlertDialog; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import foodbook.thinmint.R; import foodbook.thinmint.activities.common.ActivityHelper; import foodbook.thinmint.activities.common.TokenActivity; import foodbook.thinmint.activities.common.RequestCodes; import foodbook.thinmint.models.domain.Comment; import foodbook.thinmint.models.domain.Like; import foodbook.thinmint.models.domain.Note; public class NoteActivity extends TokenActivity implements NoteFragment.OnNoteFragmentDataListener { private NoteFragment mNoteFragment; private Menu mMenu; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_note); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); initToken(); initUser(); Bundle bundle = getIntent().getExtras(); long noteId = bundle.getLong("note_id"); boolean commentFlag = bundle.getBoolean("comment_flag"); setActionBarTitle("Note"); showNoteFragment(noteId, commentFlag); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.note, menu); mMenu = 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_delete) { attemptDelete(); return true; } else if (id == R.id.action_save) { return true; } else if (id == R.id.action_logout) { ActivityHelper.logout(NoteActivity.this); return true; } return super.onOptionsItemSelected(item); } private void attemptDelete() { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Delete Note") .setMessage("Are you sure you want to delete this note?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mNoteFragment.deleteNote(); } }) .setNegativeButton("Cancel", null) .show(); } private void toggleNoteActions(boolean show) { if (mMenu != null) { MenuItem delete = mMenu.findItem(R.id.action_delete); delete.setVisible(show); } } private void showNoteFragment(long noteId, boolean commentFlag) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack mNoteFragment = NoteFragment.newInstance(noteId, commentFlag); fragmentTransaction.replace(R.id.fragment_container, mNoteFragment, "Note"); // Commit the transaction fragmentTransaction.commit(); } @Override public void onNoteFragmentCreated(View view) { } @Override public void onNoteRetrieved(Note note) { if (note.getUserId() != mUserId) { toggleNoteActions(false); } else { toggleNoteActions(true); } } @Override public void onNoteDeleted(long noteId) { Intent resultIntent = new Intent(); resultIntent.putExtra(RequestCodes.NOTE_EXTRA_ACTION, RequestCodes.DELETE_NOTE_ACTION); resultIntent.putExtra(RequestCodes.NOTE_EXTRA_ID, noteId); setResult(Activity.RESULT_OK, resultIntent); finish(); } @Override public void onCommentAdded(Comment comment) { Intent resultIntent = new Intent(); resultIntent.putExtra(RequestCodes.NOTE_EXTRA_ACTION, RequestCodes.COMMENT_NOTE_ACTION); resultIntent.putExtra(RequestCodes.NOTE_EXTRA_ID, comment.getNoteId()); resultIntent.putExtra(RequestCodes.NOTE_COMMENT_EXTRA_ID, comment.getId()); setResult(Activity.RESULT_OK, resultIntent); } @Override public void onLikeAdded(Like like) { Intent resultIntent = new Intent(); resultIntent.putExtra(RequestCodes.NOTE_EXTRA_ACTION, RequestCodes.LIKE_NOTE_ACTION); resultIntent.putExtra(RequestCodes.NOTE_EXTRA_ID, like.getNoteId()); resultIntent.putExtra(RequestCodes.NOTE_LIKE_EXTRA_ID, like.getId()); setResult(Activity.RESULT_OK, resultIntent); } } <file_sep>package foodbook.thinmint.activities.day; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.app.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import foodbook.thinmint.R; import foodbook.thinmint.activities.common.ActivityHelper; import foodbook.thinmint.activities.common.TokenActivity; import foodbook.thinmint.activities.common.RequestCodes; public class DayActivity extends TokenActivity implements DayFragment.OnDayFragmentDataListener { public static final DateFormat PARSABLE_DATE_FORMAT = DateFormat.getDateInstance(); public static final DateFormat DATE_FORMAT = new SimpleDateFormat("MMM d", Locale.US); public static final DateFormat DATE_FORMAT_YEAR = new SimpleDateFormat("MMM d yyyy", Locale.US); public static final DateFormat TIME_FORMAT = new SimpleDateFormat("h:mm a", Locale.US); private Date mCurrentDate; private DayFragment mDayFragment; private View mProgressView; private View mContentView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_day); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); initToken(); initUser(); Bundle bundle = getIntent().getExtras(); String date = bundle.getString("date"); if (mCurrentDate == null) { mCurrentDate = new Date(System.currentTimeMillis()); } FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startCreateNoteActivity(); } }); mContentView = findViewById(R.id.fragment_container); mProgressView = findViewById(R.id.loading_progress); setActionBarTitle(DATE_FORMAT.format(mCurrentDate)); showDayFragment(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case RequestCodes.NOTE_REQUEST_CODE: if (resultCode == Activity.RESULT_OK) { String action = data.getStringExtra(RequestCodes.NOTE_EXTRA_ACTION); long id = data.getLongExtra(RequestCodes.NOTE_EXTRA_ID, -1); if (action.equals(RequestCodes.COMMENT_NOTE_ACTION)) { mDayFragment.onCommentAdded(id); } else if (action.equals(RequestCodes.DELETE_NOTE_ACTION)) { mDayFragment.onNoteDeleted(id); } else if (action.equals(RequestCodes.CREATE_NOTE_ACTION)) { mDayFragment.onNoteAdded(id); } else if (action.equals(RequestCodes.LIKE_NOTE_ACTION)) { mDayFragment.onLikeAdded(id); } } break; } } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.day, 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_logout) { // User chose the "Settings" item, show the app settings UI... ActivityHelper.logout(DayActivity.this); return true; } else if (id == R.id.action_go_to_today) { mCurrentDate = new Date(System.currentTimeMillis()); selectDay(mCurrentDate); return true; } else if (id == R.id.action_date) { showDatePicker(); return true; } return super.onOptionsItemSelected(item); } private void startCreateNoteActivity() { ActivityHelper.startCreateNoteActivityForResult(DayActivity.this); } private void showDayFragment() { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); mDayFragment = DayFragment.newInstance(mCurrentDate); fragmentTransaction.replace(R.id.fragment_container, mDayFragment, "DayFragment"); // Commit the transaction fragmentTransaction.commit(); } private void showDatePicker() { DatePickerFragment newFragment = new DatePickerFragment(); newFragment.setDate(mCurrentDate); newFragment.show(getSupportFragmentManager(), "datePicker"); } @Override public void onDayFragmentCreated(View view) { } @Override public void selectDay(Date date) { setActionBarTitle(DATE_FORMAT.format(date)); mDayFragment.setDate(date); mCurrentDate = date; } /** * Shows the progress UI and hides the login form. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) private void showProgress(final boolean show) { // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow // for very easy animations. If available, use these APIs to fade-in // the progress spinner. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); mContentView.setVisibility(show ? View.GONE : View.VISIBLE); mContentView.animate().setDuration(shortAnimTime).alpha( show ? 0 : 1).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mContentView.setVisibility(show ? View.GONE : View.VISIBLE); } }); mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mProgressView.animate().setDuration(shortAnimTime).alpha( show ? 1 : 0).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); } }); } else { // The ViewPropertyAnimator APIs are not available, so simply show // and hide the relevant UI components. mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mContentView.setVisibility(show ? View.GONE : View.VISIBLE); } } } <file_sep>package foodbook.thinmint.activities.adapters.notes.item; import android.view.View; import android.widget.Button; import android.widget.EditText; /** * Created by Zachery.Sogolow on 5/26/2017. */ public interface IOnNoteClickListener { void onClick(View view); void onAddCommentClick(EditText editText); void onUserClick(View view); void onCommentButtonClick(View view); void onLikeButtonClick(View view); void onUnlikeButtonClick(View view); } <file_sep>package foodbook.thinmint.models.views; /** * Created by ZachS on 5/27/2017. */ public enum ListItemTypes { Note, Comment, AddComment, User } <file_sep>package foodbook.thinmint.activities; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.app.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.MenuInflater; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import java.util.Date; import foodbook.thinmint.R; import foodbook.thinmint.activities.common.ActivityHelper; import foodbook.thinmint.activities.common.OnNotesListInteractionListener; import foodbook.thinmint.activities.common.RequestCodes; import foodbook.thinmint.activities.common.TokenActivity; import foodbook.thinmint.activities.feed.FeedFragment; import foodbook.thinmint.activities.users.UsersFragment; public class MainActivity extends TokenActivity implements NavigationView.OnNavigationItemSelectedListener, FeedFragment.OnFeedFragmentDataListener, UsersFragment.OnUsersFragmentDataListener { private static final String TAG = "MainActivity"; private FeedFragment mFeedFragment; private OnNotesListInteractionListener mCurrentFragment; private NavigationView mNavigationView; private DrawerLayout mDrawerLayout; private View mProgressView; private View mContentView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); initToken(); initUser(); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startCreateNoteActivity(); } }); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, mDrawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); mDrawerLayout.addDrawerListener(toggle); toggle.syncState(); mNavigationView = (NavigationView) findViewById(R.id.nav_view); mNavigationView.setNavigationItemSelectedListener(this); TextView userNameTextView = (TextView) mNavigationView.getHeaderView(0).findViewById(R.id.user_name); userNameTextView.setText(mUserName); getSupportFragmentManager() .addOnBackStackChangedListener(getBackStackChangedListener()); mContentView = findViewById(R.id.fragment_container); mProgressView = findViewById(R.id.loading_progress); MenuItem dailyItem = mNavigationView.getMenu().getItem(0); dailyItem.setChecked(true); onNavigationItemSelected(dailyItem); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case RequestCodes.NOTE_REQUEST_CODE: if (resultCode == Activity.RESULT_OK) { String action = data.getStringExtra(RequestCodes.NOTE_EXTRA_ACTION); long id = data.getLongExtra(RequestCodes.NOTE_EXTRA_ID, -1); if (action.equals(RequestCodes.COMMENT_NOTE_ACTION)) { mCurrentFragment.onCommentAdded(id); } else if (action.equals(RequestCodes.DELETE_NOTE_ACTION)) { mCurrentFragment.onNoteDeleted(id); } else if (action.equals(RequestCodes.CREATE_NOTE_ACTION)) { mCurrentFragment.onNoteAdded(id); } else if (action.equals(RequestCodes.LIKE_NOTE_ACTION)) { mCurrentFragment.onLikeAdded(id); } } break; } } @Override public void onBackPressed() { if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) { mDrawerLayout.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } FragmentManager fragmentManager = getSupportFragmentManager(); if (fragmentManager.getBackStackEntryCount() > 0) { fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); mCurrentFragment = mFeedFragment; } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_logout) { // User chose the "Settings" item, show the app settings UI... ActivityHelper.logout(MainActivity.this); return true; } return super.onOptionsItemSelected(item); } @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_calendar) { startDayActivity(new Date(System.currentTimeMillis())); } else if (id == R.id.nav_home) { setActionBarTitle("Feed"); showHomeFragment(); } else if (id == R.id.nav_my_stuff) { startUserActivity(mUserSubject, mUserName); } else if (id == R.id.nav_users) { setActionBarTitle("Users"); showUsersFragment(); } mDrawerLayout.closeDrawer(GravityCompat.START); return true; } // Private Helpers private FragmentManager.OnBackStackChangedListener getBackStackChangedListener() { final FragmentManager.OnBackStackChangedListener listener = new FragmentManager.OnBackStackChangedListener() { public void onBackStackChanged() { // Update your UI here. FragmentManager fragmentManager = getSupportFragmentManager(); if (fragmentManager.getBackStackEntryCount() > 0) { String fragmentTag = fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount() - 1).getName(); } else if (fragmentManager.getBackStackEntryCount() == 0) { try { FeedFragment feedFragment = (FeedFragment) fragmentManager.findFragmentByTag("FeedFragment"); if (feedFragment != null) { setActionBarTitle("Feed"); mNavigationView.getMenu().getItem(0).setChecked(true); } } catch (ClassCastException cce) { } } } }; return listener; } private void startDayActivity(Date date) { ActivityHelper.startDayActivity(MainActivity.this, date); } private void startCreateNoteActivity() { ActivityHelper.startCreateNoteActivityForResult(MainActivity.this); } private void startUserActivity(String userSubject, String username) { ActivityHelper.startUserActivity(MainActivity.this, userSubject, username); } private void showUsersFragment() { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack UsersFragment usersFragment = UsersFragment.newInstance(mUserSubject); fragmentTransaction.replace(R.id.fragment_container, usersFragment, "Users"); fragmentTransaction.addToBackStack(null); // Commit the transaction fragmentTransaction.commit(); } private void showHomeFragment() { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); mFeedFragment = FeedFragment.newInstance("Hello home fragment"); fragmentTransaction.replace(R.id.fragment_container, mFeedFragment, "FeedFragment"); fragmentManager.popBackStack(); // Commit the transaction fragmentTransaction.commit(); mCurrentFragment = mFeedFragment; } @Override public void onFeedFragmentCreated(View view) { } @Override public void onUsersFragmentCreated(View view) { } /** * Shows the progress UI and hides the login form. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) private void showProgress(final boolean show) { // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow // for very easy animations. If available, use these APIs to fade-in // the progress spinner. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); mContentView.setVisibility(show ? View.GONE : View.VISIBLE); mContentView.animate().setDuration(shortAnimTime).alpha( show ? 0 : 1).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mContentView.setVisibility(show ? View.GONE : View.VISIBLE); } }); mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mProgressView.animate().setDuration(shortAnimTime).alpha( show ? 1 : 0).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); } }); } else { // The ViewPropertyAnimator APIs are not available, so simply show // and hide the relevant UI components. mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mContentView.setVisibility(show ? View.GONE : View.VISIBLE); } } } <file_sep>package foodbook.thinmint.activities.adapters.users.item; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import foodbook.thinmint.R; import foodbook.thinmint.activities.adapters.common.AbstractItemViewHolder; import foodbook.thinmint.models.views.ListItemTypes; /** * Created by ZachS on 5/27/2017. */ public class UserViewHolder extends AbstractItemViewHolder<IOnUserClickListener> { private TextView mUserNameView; private Button mAddCommentButton; private Button mAddLikeButton; private Button mUnlikeButton; public UserViewHolder(LinearLayout v, IOnUserClickListener listener, ListItemTypes type) { super(v, listener); if (type == ListItemTypes.Note) { mAddCommentButton = (Button) mLinearLayout.findViewById(R.id.comment_button); mAddLikeButton = (Button) mLinearLayout.findViewById(R.id.like_button); mUnlikeButton = (Button) mLinearLayout.findViewById(R.id.un_like_button); mAddCommentButton.setOnClickListener(this); mAddLikeButton.setOnClickListener(this); mUnlikeButton.setOnClickListener(this); mLinearLayout.setOnClickListener(this); } else if (type == ListItemTypes.Comment) { mUserNameView = (TextView) mLinearLayout.findViewById(R.id.user_name); mUserNameView.setOnClickListener(this); } } @Override public void onClick(View v) { if (v.equals(mAddCommentButton)) { mOnClickListener.onCommentButtonClick(mLinearLayout); } else if (v.equals(mAddLikeButton)) { mOnClickListener.onLikeButtonClick(mLinearLayout); } else if (v.equals(mUnlikeButton)) { mOnClickListener.onUnlikeButtonClick(mLinearLayout); } else { mOnClickListener.onClick(mLinearLayout); } } } <file_sep>package foodbook.thinmint.activities.adapters.comments; import android.app.Activity; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import foodbook.thinmint.R; import foodbook.thinmint.activities.adapters.common.AbstractListRecyclerAdapter; import foodbook.thinmint.activities.adapters.common.AbstractListViewHolder; import foodbook.thinmint.models.domain.Comment; import foodbook.thinmint.models.domain.User; /** * Created by Zachery.Sogolow on 5/18/2017. */ public class CommentsRecyclerAdapter extends AbstractListRecyclerAdapter<Comment, IOnCommentClickListener> { // Provide a suitable constructor (depends on the kind of dataset) public CommentsRecyclerAdapter(List<Comment> comments, IOnCommentClickListener listener, Activity activity) { super(comments, listener, activity); } // Create new views (invoked by the layout manager) @Override public CommentsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view LinearLayout v = (LinearLayout) LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_comment, parent, false); // set the view's size, margins, paddings and layout parameters CommentsViewHolder vh = new CommentsViewHolder(v, mListener); return vh; } // Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(AbstractListViewHolder<IOnCommentClickListener> holder, int position) { long nowInMillis = System.currentTimeMillis(); Date dateCreated = mItems.get(position).getDateCreated(); Calendar now = Calendar.getInstance(); Calendar created = Calendar.getInstance(); now.setTime(new Date(nowInMillis)); created.setTime(dateCreated); boolean sameDay = now.get(Calendar.YEAR) == created.get(Calendar.YEAR) && now.get(Calendar.DAY_OF_YEAR) == created.get(Calendar.DAY_OF_YEAR); boolean sameYear = now.get(Calendar.YEAR) == created.get(Calendar.YEAR); DateFormat dateFormat = sameYear ? DATE_FORMAT : DATE_FORMAT_YEAR; String dateString = sameDay ? TIME_FORMAT.format(dateCreated) : dateFormat.format(dateCreated) + " at " + TIME_FORMAT.format(dateCreated); Comment comment = mItems.get(position); User user = comment.getUser(); ((TextView) holder.mLinearLayout.findViewById(R.id.user_name)) .setText(mItems.get(position).getUser().getUsername()); ((TextView) holder.mLinearLayout.findViewById(R.id.hidden_user_id)) .setText(mItems.get(position).getUser().getSubject()); ((TextView) holder.mLinearLayout.findViewById(R.id.comment_text)) .setText(mItems.get(position).getText()); ((TextView) holder.mLinearLayout.findViewById(R.id.comment_date)) .setText(dateString); } } <file_sep>package foodbook.thinmint.activities.adapters.common; import android.view.View; import android.widget.LinearLayout; /** * Created by Zachery.Sogolow on 5/26/2017. */ public abstract class AbstractItemViewHolder<T> extends AbstractListViewHolder<T> { protected AbstractItemViewHolder(LinearLayout v, T listener) { super(v, listener); } @Override public abstract void onClick(View v); } <file_sep>package foodbook.thinmint.activities.common; /** * Created by Zachery.Sogolow on 5/24/2017. */ public class RequestCodes { public static final int NOTE_REQUEST_CODE = 0; public static final int CREATE_NOTE_REQUEST_CODE = 1; public static final int DELETE_NOTE_REQUEST_CODE = 2; public static final String DELETE_NOTE_ACTION = "delete_note_action"; public static final String CREATE_NOTE_ACTION = "create_note_action"; public static final String COMMENT_NOTE_ACTION = "comment_note_action"; public static final String LIKE_NOTE_ACTION = "like_note_action"; public static final String NOTE_EXTRA_ID = "note_id"; public static final String NOTE_COMMENT_EXTRA_ID = "note_comment_id"; public static final String NOTE_LIKE_EXTRA_ID = "note_like_id"; public static final String NOTE_EXTRA_ACTION = "note_action"; public static final String CREATE_NOTE_EXTRA_ID = "created_note_id"; public static final String DELETE_NOTE_EXTRA_ID = "deleted_note_id"; } <file_sep>package foodbook.thinmint.models.domain; import com.google.gson.annotations.SerializedName; /** * Created by Zachery.Sogolow on 5/9/2017. */ public class Like extends EntityBase { @SerializedName("noteID") private long mNoteId; @SerializedName("userID") private long mUserId; @SerializedName("user") private User mUser; public Like() { super(); } public long getNoteId() { return mNoteId; } public void setNoteId(long noteId) { this.mNoteId = noteId; } public long getUserId() { return mUserId; } public void setUserId(long userId) { this.mUserId = userId; } public User getUser() { return mUser; } public void setUser(User user) { this.mUser = user; } } <file_sep>package foodbook.thinmint.idsrv; import org.json.JSONObject; /** * Created by Zachery.Sogolow on 5/8/2017. */ public class JsonManipulation { public static String getAttrFromJson(String json, String attribute){ try{ return (new JSONObject(json)).getString(attribute); } catch (Exception e){ return "{Exception: " + e.getMessage() +"}"; } } } <file_sep>package foodbook.thinmint.activities.common; import android.content.SharedPreferences; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import foodbook.thinmint.IApiCallback; import foodbook.thinmint.IAsyncCallback; import foodbook.thinmint.constants.Constants; import foodbook.thinmint.idsrv.Token; import foodbook.thinmint.idsrv.TokenHelper; /** * Created by Zachery.Sogolow on 5/10/2017. */ public abstract class TokenFragment extends Fragment implements IApiCallback { protected Token mToken; protected String mUserSubject; protected String mUserName; protected long mUserId; protected AsyncTask mRunningTask; protected void initToken() { mToken = TokenHelper.getToken(getContext()); } protected void initUser() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext()); mUserSubject = prefs.getString(Constants.USER_SUBJECT, ""); mUserName = prefs.getString(Constants.USER_NAME, ""); mUserId = prefs.getLong(Constants.USER_ID, -1); } protected abstract void refreshFragment(); @Override public void callback(IAsyncCallback cb) { mRunningTask = null; } } <file_sep>package foodbook.thinmint.tasks; import android.os.AsyncTask; import foodbook.thinmint.AbstractAsyncCallback; import foodbook.thinmint.IApiCallback; import foodbook.thinmint.api.WebAPIResult; /** * Created by Zachery.Sogolow on 5/25/2017. */ public class AsyncCallback<T> extends AbstractAsyncCallback<T> { public AsyncCallback(IApiCallback callback) { super(callback); } } <file_sep>package foodbook.thinmint.idsrv; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import foodbook.thinmint.constants.Constants; /** * Created by Zachery.Sogolow on 5/9/2017. */ public class TokenHelper { public static Token getTokenFromJson(TokenResult tokenResult) { Token token = new Token(); String json = tokenResult.getTokenResult(); String refreshToken = JsonManipulation.getAttrFromJson(json, Constants.REFRESH_TOKEN_PREFERENCE_KEY); String accessToken = JsonManipulation.getAttrFromJson(json, Constants.ACCESS_TOKEN_PREFERENCE_KEY); String expiresIn = JsonManipulation.getAttrFromJson(json, Constants.EXPIRES_IN_PREFERENCE_KEY); long lastRetrieved = tokenResult.getRetrieved(); token.setAccessToken(accessToken); token.setRefreshToken(refreshToken); token.setExpiresIn(expiresIn); token.setLastRetrieved(lastRetrieved); return token; } public static boolean isTokenExpired(Token token) { try { long now = System.currentTimeMillis(); long expiresInMs = Long.parseLong(token.getExpiresIn()) * 1000; long lastRefresh = token.getLastRetrieved(); return (lastRefresh + expiresInMs) < (now + 15000); } catch (Exception e) { return true; } } public static Token getToken(Context context) { Token token = new Token(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); token.setAccessToken(prefs.getString(Constants.ACCESS_TOKEN_PREFERENCE_KEY, "")); token.setRefreshToken(prefs.getString(Constants.REFRESH_TOKEN_PREFERENCE_KEY, "")); token.setExpiresIn(prefs.getString(Constants.EXPIRES_IN_PREFERENCE_KEY, "")); token.setLastRetrieved(prefs.getLong(Constants.LAST_RETRIEVED_PREFERENCE_KEY, 0)); return token; } public static void copyToken(Token source, Token destination) { destination.setExpiresIn(source.getExpiresIn()); destination.setLastRetrieved(source.getLastRetrieved()); destination.setAccessToken(source.getAccessToken()); destination.setRefreshToken(source.getRefreshToken()); } public static Token saveToken(Context context, Token token) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext()); prefs.edit().putString(Constants.REFRESH_TOKEN_PREFERENCE_KEY, token.getRefreshToken()).apply(); prefs.edit().putString(Constants.ACCESS_TOKEN_PREFERENCE_KEY, token.getAccessToken()).apply(); prefs.edit().putString(Constants.EXPIRES_IN_PREFERENCE_KEY, token.getExpiresIn()).apply(); prefs.edit().putLong(Constants.LAST_RETRIEVED_PREFERENCE_KEY, token.getLastRetrieved()).apply(); return token; } } <file_sep>package foodbook.thinmint.models.domain; import com.google.gson.annotations.SerializedName; import java.util.Date; /** * Created by ZachS on 5/14/2017. */ public abstract class EntityBase { @SerializedName("id") protected long mId; @SerializedName("dateCreated") protected Date mDateCreated; protected EntityBase() { } protected EntityBase(long id, Date dateCreated) { this.mId = id; this.mDateCreated = dateCreated; } public long getId() { return mId; } public void setId(long id) { this.mId = id; } public Date getDateCreated() { return mDateCreated; } public void setDateCreated(Date dateCreated) { this.mDateCreated = dateCreated; } } <file_sep>package foodbook.thinmint.idsrv; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import foodbook.thinmint.constants.Constants; /** * Created by Zachery.Sogolow on 5/8/2017. */ public class Token { private String mAccessToken; private String mRefreshToken; private String mExpiresIn; private long mLastRetrieved; public Token() { mAccessToken = ""; mRefreshToken = ""; mExpiresIn = ""; mLastRetrieved = -1; } public void setLastRetrieved(long lastRetrieved) { this.mLastRetrieved = lastRetrieved; } public void setExpiresIn(String expiresIn) { this.mExpiresIn = expiresIn; } public void setAccessToken(String accessToken) { this.mAccessToken = accessToken; } public void setRefreshToken(String refreshToken) { this.mRefreshToken = refreshToken; } public String getAccessToken() { return mAccessToken; } public String getRefreshToken() { return mRefreshToken; } public String getExpiresIn() { return mExpiresIn; } public long getLastRetrieved() { return mLastRetrieved; } public TokenResult getAccessToken(String _clientId, String _clientSecret, String _userName, String _userPassword, String _scope) { String result = ""; TokenResult tokenResult = new TokenResult(); try { String url = Constants.IdSrvToken; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //add parameters String charset = "UTF-8"; String urlParameters = "grant_type=" + URLEncoder.encode("password", charset); urlParameters += "&client_id=" + URLEncoder.encode(_clientId, charset); urlParameters += "&client_secret=" + URLEncoder.encode(_clientSecret, charset); urlParameters += "&username=" + URLEncoder.encode(_userName, charset); urlParameters += "&password=" + URLEncoder.encode(_userPassword, charset); urlParameters += "&scope=" + URLEncoder.encode(_scope, charset); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); // Get response code int responseCode = con.getResponseCode(); if (responseCode < 400) { // Response to String BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // setAccessToken((new JSONObject(response.toString())).getString("access_token")); result = response.toString(); tokenResult.setSuccess(true); } else { result = con.getResponseMessage(); tokenResult.setSuccess(false); } // Return response (token) tokenResult.setTokenResult(result); tokenResult.setRetrieved(System.currentTimeMillis()); return tokenResult; } catch (Exception e) { return new TokenResult(false, "Error: " + result + "\n\nException: " + e.getMessage()); } } public TokenResult getRefreshToken(String _clientId, String _clientSecret) { String result = ""; TokenResult tokenResult = new TokenResult(); try { String url = Constants.IdSrvToken; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //add parameters String charset = "UTF-8"; String urlParameters = "refresh_token=" + URLEncoder.encode(mRefreshToken, charset); urlParameters += "&client_id=" + URLEncoder.encode(_clientId, charset); urlParameters += "&client_secret=" + URLEncoder.encode(_clientSecret, charset); urlParameters += "&grant_type=" + URLEncoder.encode("refresh_token", charset); urlParameters += "&scope=" + URLEncoder.encode("openid profile thinmintapi offline_access", charset); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); // Get response code int responseCode = con.getResponseCode(); if (responseCode < 400) { // Response to String BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); result = response.toString(); tokenResult.setSuccess(true); tokenResult.setRetrieved(System.currentTimeMillis()); } else { result = con.getResponseMessage(); tokenResult.setSuccess(false); } tokenResult.setTokenResult(result); // Return response (token) return tokenResult; } catch (Exception e) { return new TokenResult(false, "Error: " + result + "\n\nException: " + e.getMessage()); } } public UserInfoResult getUserInfo() { String result = ""; UserInfoResult userInfo = new UserInfoResult(); try { String url = Constants.IdSrvUserInfo; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("GET"); con.setRequestProperty("Authorization", "Bearer " + mAccessToken); // Get response code int responseCode = con.getResponseCode(); if (responseCode < 400) { // Response to String BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); result = response.toString(); userInfo.setSuccess(true); } else { result = con.getResponseMessage(); userInfo.setSuccess(false); } userInfo.setUserInfoResult(result); // Return response (token) return userInfo; } catch (Exception e) { return new UserInfoResult(false, "Error: " + result + "\n\nException: " + e.getMessage()); } } }
0a56b901630969afff8e47f493996213ebfe4c9e
[ "Java" ]
27
Java
zsogolow/foodbook
a8078c5cac911de56c04d2bb0ac730927f8d1c84
eaa37e88984fc242f58b24f406dad71f56b0173f
refs/heads/main
<file_sep>/** * */ $("#btn").click(function(){ var i1 = $("#title").val() var i2 = $("#writer").val() var i3 = $("#contents").val() var ch1 = false; var ch2 = false; var ch3 = false; if (i1 !=''){ ch1 = true; } if (i2 !=''){ ch2 = true; } if (i3 !=''){ ch3 = true; } if(ch1&&ch2&&ch3){ $("#frm").submit(); }else{ alert("필수 항목 입력해주세요"); } }); <file_sep>package com.ch.s4.member.memberUser; import com.ch.s4.member.MemberDTO; public class MemberUserDTO extends MemberDTO { } <file_sep>user=user01 password=<PASSWORD> url=jdbc:oracle:thin:@localhost:1521:xe driver=oracle.jdbc.driver.OracleDriver
41972ffc702bb3749075855b0771964328507d1c
[ "JavaScript", "Java", "INI" ]
3
JavaScript
MYCHCH515/spring_4
58de5e37484e29bb2b90fc386e61dc5b76cbedc6
273b52824fd83fc14f52c0fc712650d87d8ce8d0
refs/heads/master
<repo_name>TheCelavi/dmNivoSliderBehaviorPlugin<file_sep>/lib/dmNivoSliderBehaviorForm.class.php <?php /* * @author TheCelavi */ class dmNivoSliderBehaviorForm extends dmBehaviorBaseForm { protected $effect = array( 'random' => 'Random', 'sliceDown' => 'Slice down', 'sliceDownLeft' => 'Slice down-left', 'sliceUp' => 'Slice up', 'sliceUpLeft' => 'Slice up-left', 'sliceUpDown' => 'Slice up-down', 'sliceUpDownLeft' => 'Slice up-down-left', 'fold' => 'Fold', 'fade' => 'Fade', 'slideInRight' => 'Slide in-right', 'slideInLeft' => 'Slide in-left', 'boxRandom' => 'Box random', 'boxRain' => 'Box rain', 'boxRainReverse' => 'Box rain reverse', 'boxRainGrow' => 'Box rain grow', 'boxRainGrowReverse' => 'Box rain grow reverse' ); protected $theme = array( 'default' => 'Default' ); public function configure() { $this->widgetSchema['inner_target'] = new sfWidgetFormInputText(); $this->validatorSchema['inner_target'] = new sfValidatorString(array( 'required' => false )); $this->widgetSchema['theme'] = new sfWidgetFormChoice(array( 'choices' => $this->getI18n()->translateArray($this->theme) )); $this->validatorSchema['theme'] = new sfValidatorChoice(array( 'choices' => array_keys($this->theme) )); $this->widgetSchema['effect'] = new sfWidgetFormChoice(array( 'choices' => $this->getI18n()->translateArray($this->effect) )); $this->validatorSchema['effect'] = new sfValidatorChoice(array( 'choices' => array_keys($this->effect) )); $this->widgetSchema['use_image_alt_attr'] = new sfWidgetFormInputCheckbox(); $this->validatorSchema['use_image_alt_attr'] = new sfValidatorBoolean(); $this->widgetSchema['slices'] = new sfWidgetFormInputText(); $this->validatorSchema['slices'] = new sfValidatorInteger(array( 'required' => true, 'min' => 2 )); $this->widgetSchema['boxCols'] = new sfWidgetFormInputText(); $this->validatorSchema['boxCols'] = new sfValidatorInteger(array( 'required' => true, 'min' => 2 )); $this->widgetSchema['boxRows'] = new sfWidgetFormInputText(); $this->validatorSchema['boxRows'] = new sfValidatorInteger(array( 'required' => true, 'min' => 2 )); $this->widgetSchema['animSpeed'] = new sfWidgetFormInputText(); $this->validatorSchema['animSpeed'] = new sfValidatorInteger(array( 'required' => true, 'min' => 1 )); $this->widgetSchema['pauseTime'] = new sfWidgetFormInputText(); $this->validatorSchema['pauseTime'] = new sfValidatorInteger(array( 'required' => true, 'min' => 1 )); $this->widgetSchema['randomStart'] = new sfWidgetFormInputCheckbox(); $this->validatorSchema['randomStart'] = new sfValidatorBoolean(); $this->widgetSchema['captionOpacity'] = new sfWidgetFormInputText(); $this->validatorSchema['captionOpacity'] = new sfValidatorInteger(array( 'required' => true, 'min' => 0, 'max' => 100 )); $this->widgetSchema['directionNav'] = new sfWidgetFormInputCheckbox(); $this->validatorSchema['directionNav'] = new sfValidatorBoolean(); $this->widgetSchema['directionNavHide'] = new sfWidgetFormInputCheckbox(); $this->validatorSchema['directionNavHide'] = new sfValidatorBoolean(); $this->widgetSchema['controlNav'] = new sfWidgetFormInputCheckbox(); $this->validatorSchema['controlNav'] = new sfValidatorBoolean(); $this->widgetSchema['keyboardNav'] = new sfWidgetFormInputCheckbox(); $this->validatorSchema['keyboardNav'] = new sfValidatorBoolean(); $this->widgetSchema['pauseOnHover'] = new sfWidgetFormInputCheckbox(); $this->validatorSchema['pauseOnHover'] = new sfValidatorBoolean(); $this->getWidgetSchema()->setLabels(array( 'use_image_alt_attr' => 'Use alt for caption', 'slices' => 'Number of slices', 'boxCols' => 'Box columns', 'boxRows' => 'Box rows', 'animSpeed' => 'Animation speed', 'pauseTime' => 'Pause time', 'randomStart' => 'Random start', 'captionOpacity' => 'Captions opacity', 'directionNav' => 'Use navigation', 'directionNavHide' => 'Hide navigation on mouse out', 'controlNav' => 'Navigation numbers', 'keyboardNav' => 'Keyboard navigation', 'pauseOnHover' => 'Pause on hover' )); $this->getWidgetSchema()->setHelps(array( 'use_image_alt_attr' => 'If there is no TITLE attribuute, you can use ALT attribute for image caption', 'slices' => 'Number of slices for slice animation', 'boxCols' => 'Number of box columns for box animations', 'boxCols' => 'Number of box columns for box animations', 'boxRows' => 'Number of box rows for box animations', 'animSpeed' => 'Animation speed in ms', 'pauseTime' => 'Pause time between slides in ms', 'randomStart' => 'Start with random image', 'captionOpacity' => 'Opacity of captions in percents, set 0 for no captions', 'controlNav' => 'Show navigation numbers' )); if (is_null($this->getDefault('theme'))) $this->setDefault ('theme', 'default'); if (is_null($this->getDefault('effect'))) $this->setDefault ('effect', 'random'); if (is_null($this->getDefault('use_image_alt_attr'))) $this->setDefault ('use_image_alt_attr', true); if (is_null($this->getDefault('slices'))) $this->setDefault ('slices', 15); if (is_null($this->getDefault('boxCols'))) $this->setDefault ('boxCols', 8); if (is_null($this->getDefault('boxRows'))) $this->setDefault ('boxRows', 4); if (is_null($this->getDefault('animSpeed'))) $this->setDefault ('animSpeed', 500); if (is_null($this->getDefault('pauseTime'))) $this->setDefault ('pauseTime', 3000); if (is_null($this->getDefault('randomStart'))) $this->setDefault ('randomStart', false); if (is_null($this->getDefault('captionOpacity'))) $this->setDefault ('captionOpacity', 80); if (is_null($this->getDefault('directionNav'))) $this->setDefault ('directionNav', true); if (is_null($this->getDefault('directionNavHide'))) $this->setDefault ('directionNavHide', true); if (is_null($this->getDefault('controlNav'))) $this->setDefault ('controlNav', true); if (is_null($this->getDefault('keyboardNav'))) $this->setDefault ('keyboardNav', true); if (is_null($this->getDefault('pauseOnHover'))) $this->setDefault ('pauseOnHover', true); parent::configure(); } } <file_sep>/web/js/dmNivoSliderBehavior.js (function($) { var methods = { init: function(behavior) { var $this = $(this), data = $this.data('dmNivoSliderBehavior'); if (data && behavior.dm_behavior_id != data.dm_behavior_id) { // There is attached the same, so we must report it alert('You can not attach Nivo Slider to same content'); // TODO TheCelavi - adminsitration mechanizm for this? Reporting error }; $this.data('dmNivoSliderBehavior', behavior); }, start: function(behavior) { var $this = $(this); var $copy = $this.children().clone(true, true); $this.data('dmNivoSliderBehaviorPreviousDOM', $this.children().detach()); $this.children().remove(); if (behavior.use_image_alt_attr) { $.each($('img',$copy), function(){ $(this).attr('title', $(this).attr('alt')); }); }; // Now we have to figure out what is the content // Content can be: // Case 1: $copy > DIV > A or $copy > DIV > IMG => we have to remove DIV (it is inside of widgets) // Case 2: $copy > A or $copy > IMG (this is good, just call NivoSlide if ($copy.length == $copy.filter('div').length) { $copy = $copy.find('.dm_widget_inner').children(); }; $this.append($('<div class="dmNivoSliderBehavior"></div>').append($copy)); $this.addClass('nivo-theme-' + behavior.theme); $this.find('.dmNivoSliderBehavior').nivoSlider(behavior); }, stop: function(behavior) { var $this = $(this); $this.children().remove(); $this.removeClass('nivo-theme-' + behavior.theme); $this.append($this.data('dmNivoSliderBehaviorPreviousDOM')); }, destroy: function(behavior) { var $this = $(this); $this.data('dmNivoSliderBehavior', null); $this.data('dmNivoSliderBehaviorPreviousDOM', null) } } $.fn.dmNivoSliderBehavior = function(method, behavior){ return this.each(function() { if ( methods[method] ) { return methods[ method ].apply( this, [behavior]); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, [method] ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.dmNivoSliderBehavior' ); }; }); }; $.extend($.dm.behaviors, { dmNivoSliderBehavior: { init: function(behavior) { $($.dm.behaviorsManager.getCssXPath(behavior, true) + ' ' + behavior.inner_target).dmNivoSliderBehavior('init', behavior); }, start: function(behavior) { $($.dm.behaviorsManager.getCssXPath(behavior, true) + ' ' + behavior.inner_target).dmNivoSliderBehavior('start', behavior); }, stop: function(behavior) { $($.dm.behaviorsManager.getCssXPath(behavior, true) + ' ' + behavior.inner_target).dmNivoSliderBehavior('stop', behavior); }, destroy: function(behavior) { $($.dm.behaviorsManager.getCssXPath(behavior, true) + ' ' + behavior.inner_target).dmNivoSliderBehavior('destroy', behavior); } } }); })(jQuery);
9385468b5cf52dc5fe9976080db74863f54a0022
[ "JavaScript", "PHP" ]
2
PHP
TheCelavi/dmNivoSliderBehaviorPlugin
678498ccedaaeec95a1f472fd08a5bb5460fba36
c8eeccfef022610d0d5158459ca8b027001f943f
refs/heads/master
<repo_name>chrieric/cs290-assignment5<file_sep>/QueryFunctions.php <?php session_start(); ob_start(); error_reporting(E_ALL); ini_set('display_errors',1); $failure=0; $mysqli=new mysqli('oniddb.cws.oregonstate.edu','chrieric-db','KpqdL049GgphILrs','chrieric-db'); if($mysqli->connect_errno) { echo 'Connection error' . $mysqli->connect_errno . '' . $mysqli->connect_error; } function addMovie($array) { global $mysqli; global $failure; $name=$array["name"]; $category=$array["category"]; $length=$array["length"]; if($name !=null && $category != null && ($length != null && is_numeric($length))) { /*this is where you add functionality to add the data to the table via SQL call include button creation here as well?*/ if(!($stmt=$mysqli->prepare("INSERT INTO video_store_inventory (name, category, length) VALUES (?,?,?)"))) { echo 'Prep failed: (' . $mysqli->errno . ') ' . $mysqli->error; } elseif(!($stmt->bind_param("ssi", $name, $category, $length))) { echo 'Binding failed: (' . $stmt->errno . ') ' . $stmt->error; } else if(!($stmt->execute())) { echo 'Execution failed: ' . $stmt->errno . ') ' . $stmt->error; } $stmt->close(); } else { $failure=1; if($name==null) { echo 'You failed to enter a name! <br>'; } if($category==null) { echo 'You failed to enter a category! <br>'; } if($length==null) { echo 'You failed to enter a movie length! <br>'; } if(!(is_numeric($length))) { echo 'You failed to enter a number for movie length! <br>'; } echo "Error while adding video, click <a href='front_page.php'>here</a> to return to your inventory."; } }; function deleteMovie($array) { global $mysqli; $id=$array['id']; /*this is just to inform me what should be here, change later*/ echo $id. ' goes here'; if($id!=null) { if(!($stmt=$mysqli->prepare("DELETE FROM video_store_inventory WHERE id = ?"))) { echo 'Prep failed: (' . $mysqli->errno . ') ' . $mysqli->error; } elseif(!($stmt->bind_param("i", $id))) { echo 'Binding failed: (' . $stmt->errno . ') ' . $stmt->error; } else if(!($stmt->execute())) { echo 'Execution failed: ' . $stmt->errno . ') ' . $stmt->error; } $stmt->close(); } else { echo "Name not found click <a href='front_page.php'>here</a> to return to your inventory."; } }; function deleteAll($array) { global $mysqli; if(!($stmt=$mysqli->prepare("DELETE FROM video_store_inventory"))) { echo 'Prep failed: (' . $mysqli->errno . ') ' . $mysqli->error; } else if(!($stmt->execute())) { echo 'Execution failed: ' . $stmt->errno . ') ' . $stmt->error; } $stmt->close(); }; function checkInOut($array) { global $mysqli; //gets id passed from post $id=$array['id']; //temp variable $temp_rented; $temp_f; $temp_g; //checks to deteremine if an errors if(!($stmt = $mysqli->prepare("SELECT rented FROM video_store_inventory WHERE id=?"))) { echo 'Query failed: (' . $mysqli->errno . ') ' . $mysqli->error; } elseif(!($stmt->bind_param("i", $id))) { echo 'Binding failed: (' . $stmt->errno . ') ' . $stmt->error; } else if(!($stmt->execute())) { echo 'Execution failed: ' . $stmt->errno . ') ' . $stmt->error; } //if no errors, fetches value of rented //then changes rented value from 0 to 1 or 1 to 0 else { $temp_f=$stmt->get_result(); $temp_g=$temp_f->fetch_assoc(); $temp_rented=$temp_g['rented']; if($temp_rented==0) { if(!($stmt=$mysqli->prepare("UPDATE video_store_inventory SET rented=1 WHERE id=?"))) { echo 'Prep failed: (' . $mysqli->errno . ') ' . $mysqli->error; } elseif(!($stmt->bind_param("i", $id))) { echo 'Execution failed: ' . $stmt->errno . ') ' . $stmt->error; } else if(!($stmt->execute())) { echo 'Execution failed: ' . $stmt->errno . ') ' . $stmt->error; } } elseif($temp_rented==1) { if(!($stmt=$mysqli->prepare("UPDATE video_store_inventory SET rented=0 WHERE id=?"))) { echo 'Prep failed: (' . $mysqli->errno . ') ' . $mysqli->error; } elseif(!($stmt->bind_param("i", $id))) { echo 'Execution failed: ' . $stmt->errno . ') ' . $stmt->error; } else if(!($stmt->execute())) { echo 'Execution failed: ' . $stmt->errno . ') ' . $stmt->error; } } /*else { echo 'Error, error, error!'; }*/ } $stmt->close(); }; /*original idea from http://www.phpro.org/tutorials/Dropdown-Select-With-PHP-and-MySQL.html though I modified it to better fit the nees of this assignment*/ function dropDown($id,array $options) { $drop='<select name="'.$id.'">'."\n"; $len=count($options); $drop.='<option value="Default">Default</option>'."\n"; for($i=0;$i<$len;$i++) { $drop.= '<option value="'.$options[$i].'">'.$options[$i].'</option>'."\n"; } $drop.='</select>'."\n"; return $drop; } if(isset($_POST['add_video'])) { addMovie($_POST); if($failure==0) { header("Location:front_page.php",true); } } elseif(isset($_POST['delete_movie'])) { deleteMovie($_POST); if($failure==0) { header("Location:front_page.php",true); } } elseif(isset($_POST['delete_all'])) { deleteAll($_POST); if($failure==0) { header("Location:front_page.php",true); } } elseif(isset($_POST['check_in_out'])) { checkInOut($_POST); if($failure==0) { header("Location:front_page.php",true); } } elseif(isset($_POST['dropsort'])) { $_SESSION['dropdown']=$_POST['dropdown']; if($failure==0) { header("Location:front_page.php",true); } } ?><file_sep>/front_page.php <?php ob_start(); session_start(); include 'QueryFunctions.php'; error_reporting(E_ALL); ini_set('display_errors',1); $mysqli=new mysqli('oniddb.cws.oregonstate.edu','chrieric-db','KpqdL049GgphILrs','chrieric-db'); if($mysqli->connect_errno) { echo 'Connection error ' . $mysqli->connect_errno . '' . $mysqli->connect_error; } ?> <!DOCTYPE html> <html lang='en'> <head> <title>Video Rental</title> </head> <body> <section> <form action='QueryFunctions.php' method='post'> <input type='submit' name='delete_all' value='Delete All'> </form> <form action='QueryFunctions.php' method='post'> <p>Name:<input type='text' name='name'></p> <p>Category:<input type='text' name='category'></p> <p>Length:<input type='text' name='length'></p> <input type='submit' name='add_video' value='Add Video'> </form> <?php if(!(isset($_SESSION['dropdown']))||$_SESSION['dropdown']=='Default') { if(!($stmt=$mysqli->query("SELECT id, name, category, length, rented FROM video_store_inventory"))) { echo "Query failed: (" . $mysqli->errno . ") ". $mysqli->error; } } else { $category=$_SESSION['dropdown']; if(!($stmt=$mysqli->query("SELECT id, name, category, length, rented FROM video_store_inventory WHERE category='$category'"))) { echo "Query failed: (" . $mysqli->errno . ") ". $mysqli->error; } } $_SESSION['dropdown']='Default'; ?> <table border='1'> <thead> <tr> <th>Title</th> <th>Category</th> <th>Length(In Min)</th> <th>Rented</th> <th>Check-In/Out</th> <th>Delete Movie</th> </tr> </thead> <tbody> <?php $curr_categories=array(); $row; while($row = mysqli_fetch_array($stmt)) { echo "<tr>"; echo "<td>" . $row['name'] . "</td>"; echo "<td>" . $row['category'] . "</td>"; if($row['length']==0) { echo "<td>" . "none listed" . "</td>"; } else { echo "<td>" . $row['length'] . "</td>"; } echo "<td>" . $row['rented'] . "</td>"; echo "<td>"; echo "<form action='QueryFunctions.php' method='post'>"; echo "<input type='hidden' name='id' value=\"".$row['id']."\">"; echo "<input type='submit' name='check_in_out' value='Check In/Out'>"; echo "</form>"; echo "</td>"; echo "<td>"; echo "<form action='QueryFunctions.php' method='post'>"; echo "<input type='hidden' name='id' value=\"".$row['id']."\">"; echo "<input type='submit' name='delete_movie' value='Delete'>"; echo "</form>"; echo "</td>"; echo "</tr>"; } if (!$stmt = $mysqli->query("SELECT category FROM video_store_inventory")) { echo "Query Failed!: (" . $mysqli->errno . ") ". $mysqli->error; } while($row = mysqli_fetch_array($stmt)) { if(!(in_array($row['category'], $curr_categories))) { array_push($curr_categories,$row['category']); } } echo "<form action='QueryFunctions.php' method='post'>"; echo dropDown('dropdown',$curr_categories); echo "<input type='submit' name='dropsort' value='Sort'>"; echo "</form>"; ?> </tbody> </table> </section> </body> </html>
6fe816b58363944c295a0aa558582e2e0715079b
[ "PHP" ]
2
PHP
chrieric/cs290-assignment5
5866c6e743113fa2967f8d9b37aaf3dc2dfa38ac
a62ca687e858477ef35a2c60d52fd2c901113dc0
refs/heads/master
<repo_name>liyuanlin123456/liyuanlin20190120<file_sep>/liyuanlin20190120/src/main/java/com/example/liyuanlin20190120/entity/Cart.java package com.example.liyuanlin20190120.entity; import java.util.List; public class Cart { public String msg; public String code; public List<DataBean> data; public static class DataBean{ public boolean isChecked; public List<ListBean> list; public String sellerName; public String sellerid; public static class ListBean{ public boolean isProductChecked; public String subhead; public String images; public double price; public String title; public int productNum=1; public int pos; } } } <file_sep>/liyuanlin20190120/src/main/java/com/example/liyuanlin20190120/contract/CartContract.java package com.example.liyuanlin20190120.contract; import com.example.liyuanlin20190120.net.RequestCallBack; import java.util.HashMap; public interface CartContract { //p层的方法 public abstract class CartPresenter{ public abstract void cart(HashMap<String,String> params); } //m层的方法 interface ICartModel{ void cart(HashMap<String,String> params, RequestCallBack requestCallBack); } //v层的方法 interface ICartView{ void onFailUre(String msg); void onSuccess(String result); } } <file_sep>/liyuanlin20190120/src/main/java/com/example/liyuanlin20190120/activity/LoginActivity.java package com.example.liyuanlin20190120.activity; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.Toast; import com.example.liyuanlin20190120.R; public class LoginActivity extends AppCompatActivity { private EditText name; private EditText pwd; private CheckBox checkBox; private Button btn_login; private Button btn_reg; private Button btn_qq; private SharedPreferences sharedPreferences; private SharedPreferences.Editor edit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); //获取登录页面的控件id getSupportActionBar().hide(); name = findViewById(R.id.name); pwd = findViewById(R.id.pwd); checkBox = findViewById(R.id.checkBox); btn_login = findViewById(R.id.btn_login); btn_reg = findViewById(R.id.btn_reg); btn_qq = findViewById(R.id.btn_qq); //获取sharedpreferences sharedPreferences = getSharedPreferences("user", MODE_PRIVATE); edit = sharedPreferences.edit(); //获取保存的数据 String login_namee = sharedPreferences.getString("login_name", null); String login_pwdd = sharedPreferences.getString("login_pwd", null); boolean checkboxx = sharedPreferences.getBoolean("checkbox", false); //判断是否选中 if (checkboxx){ checkBox.setChecked(checkboxx); name.setText(login_namee); pwd.setText(login_pwdd); } //获取保存的数据 final String reg_name = sharedPreferences.getString("name", null); final String reg_pwd = sharedPreferences.getString("pwd", null); //设置点击事件 btn_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name1 = name.getText().toString(); String pwd1 = pwd.getText().toString(); if (name1.equals(reg_name)) { if (pwd1.equals(reg_pwd)) { Toast.makeText(LoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show(); Intent intent = new Intent(LoginActivity.this, ShowActivity.class); startActivity(intent); } else { Toast.makeText(LoginActivity.this, "输入的密码错误", Toast.LENGTH_SHORT).show(); } }else{ Toast.makeText(LoginActivity.this,"您输入的用户名未进行注册,请先注册",Toast.LENGTH_SHORT).show(); startActivity(new Intent(LoginActivity.this,RegActivity.class)); } } }); //注册按钮的跳转 btn_reg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(LoginActivity.this,RegActivity.class)); } }); //获取checkbox的选中转态 checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked){ String login_name = name.getText().toString(); String login_pwd = pwd.getText().toString(); if (login_name!=null || login_name.equals("") || login_pwd!=null || login_pwd.equals("")){ edit.putString("login_name",login_name); edit.putString("login_pwd",login_pwd); edit.putBoolean("checkbox",true); edit.commit(); } } } }); } } <file_sep>/liyuanlin20190120/src/main/java/com/example/liyuanlin20190120/model/CartModel.java package com.example.liyuanlin20190120.model; import android.text.TextUtils; import com.example.liyuanlin20190120.api.CartApi; import com.example.liyuanlin20190120.contract.CartContract; import com.example.liyuanlin20190120.net.OkhttpCallBack; import com.example.liyuanlin20190120.net.RequestCallBack; import com.example.liyuanlin20190120.utils.OkhttpUtils; import java.util.HashMap; public class CartModel implements CartContract.ICartModel { @Override public void cart(HashMap<String, String> params, final RequestCallBack requestCallBack) { //调用okhttp方法 OkhttpUtils.getmInstance().doPost(CartApi.CART_SHOW, params, new OkhttpCallBack() { @Override public void onFailUre(String msg) { if (requestCallBack!=null){ requestCallBack.onFailUre("网络异常,请稍后再试"); } } @Override public void onSuccess(String result) { if (!TextUtils.isEmpty(result)){ requestCallBack.onSuccess(result); } } }); } } <file_sep>/settings.gradle include ':app', ':liyuanlin20190120' <file_sep>/liyuanlin20190120/src/main/java/com/example/liyuanlin20190120/view/AddMinusNum.java package com.example.liyuanlin20190120.view; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import com.example.liyuanlin20190120.R; public class AddMinusNum extends LinearLayout { private TextView minus; private EditText ed_num; private TextView add; private int num; public AddMinusNum(Context context) { this(context,null); } public AddMinusNum(Context context, AttributeSet attrs) { this(context, attrs,0); } public AddMinusNum(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); } private void init(Context context) { //获取控件 View view = LayoutInflater.from(context).inflate(R.layout.addminus, this); minus = view.findViewById(R.id.minus); ed_num = view.findViewById(R.id.ed_num); add = view.findViewById(R.id.add); //设置监听为其赋值 minus.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { num = Integer.parseInt(ed_num.getText().toString()); num--; if (num==0){ num=1; } numCallBack.getNum(num); ed_num.setText(num+""); } }); //设置监听 为其赋值 add.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { num++; numCallBack.getNum(num); ed_num.setText(num+""); } }); } public void setNum(int num) { ed_num.setText(num+""); } private NumCallBack numCallBack; public void setNumCallBack(NumCallBack numCallBack) { this.numCallBack = numCallBack; } public interface NumCallBack{ void getNum(int num); } } <file_sep>/liyuanlin20190120/src/main/java/com/example/liyuanlin20190120/net/CartUiCallBack.java package com.example.liyuanlin20190120.net; public interface CartUiCallBack { void notifyPrice(); } <file_sep>/liyuanlin20190120/src/main/java/com/example/liyuanlin20190120/fragment/FragmentCart.java package com.example.liyuanlin20190120.fragment; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import com.example.liyuanlin20190120.R; import com.example.liyuanlin20190120.adapter.CartAdapter; import com.example.liyuanlin20190120.contract.CartContract; import com.example.liyuanlin20190120.entity.Cart; import com.example.liyuanlin20190120.net.CartUiCallBack; import com.example.liyuanlin20190120.presenter.CartPresenter; import com.example.liyuanlin20190120.utils.OkhttpUtils; import com.google.gson.Gson; import java.util.List; public class FragmentCart extends Fragment implements CartContract.ICartView,CartUiCallBack { private Button qx; private RecyclerView rec; private CheckBox checkBox; private TextView price; private Button btn; private CartPresenter presenter; private CartAdapter myAdapter; private List<Cart.DataBean> data; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_cart,container,false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); //获取页面控件 qx = view.findViewById(R.id.qx); rec = view.findViewById(R.id.rec); rec.setLayoutManager(new LinearLayoutManager(getActivity())); checkBox = view.findViewById(R.id.checkBox); price = view.findViewById(R.id.price); btn = view.findViewById(R.id.btn); presenter = new CartPresenter(this); presenter.cart(null); myAdapter = new CartAdapter(getActivity(),this); rec.setAdapter(myAdapter); //设置checkbox的监听 checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { //判断他的选中转态 为集合里面的参数赋值 if (isChecked){ for (Cart.DataBean datum : data) { datum.isChecked=true; for (Cart.DataBean.ListBean listBean : datum.list) { listBean.isProductChecked=true; } } }else{ for (Cart.DataBean datum : data) { datum.isChecked=false; for (Cart.DataBean.ListBean listBean : datum.list) { listBean.isProductChecked=false; } } } myAdapter.notifyDataSetChanged(); getPrice(); } }); qx.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!data.get(0).isChecked){ for (Cart.DataBean datum : data) { datum.isChecked=true; for (Cart.DataBean.ListBean listBean : datum.list) { listBean.isProductChecked=true; } } }else{ for (Cart.DataBean datum : data) { datum.isChecked=false; for (Cart.DataBean.ListBean listBean : datum.list) { listBean.isProductChecked=false; } } } myAdapter.notifyDataSetChanged(); getPrice(); } }); } @Override public void onFailUre(String msg) { } @Override public void onSuccess(String result) { Cart cart = new Gson().fromJson(result, Cart.class); data = cart.data; myAdapter.setList(cart.data); } public void getPrice(){ //计算价钱 double pricee=0; for (Cart.DataBean datum : data) { for (Cart.DataBean.ListBean listBean : datum.list) { if (listBean.isProductChecked){ pricee+=listBean.productNum*listBean.price; } } } price.setText("¥"+pricee); } @Override public void notifyPrice() { getPrice(); } //防止内存泄漏 @Override public void onDestroy() { super.onDestroy(); OkhttpUtils.getmInstance().okHttpCancel(); presenter.onDestroy(); } }
3ebd4985bf632f864603bb435e160eb23fdd541d
[ "Java", "Gradle" ]
8
Java
liyuanlin123456/liyuanlin20190120
a6ac51676ac144f9b4838078aebe148f0ee6cc69
480255f42698bca7ba33260856bbcea7d91b48b2
refs/heads/master
<repo_name>chocozhao/kotlin<file_sep>/libraries/tools/kotlin-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/testing/internal/AggregateTestReportGradle5.kt /* * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.gradle.testing.internal import org.gradle.api.internal.CollectionCallbackActionDecorator import org.gradle.api.internal.tasks.testing.DefaultTestTaskReports import org.gradle.api.internal.tasks.testing.junit.result.* import org.gradle.api.internal.tasks.testing.report.DefaultTestReport import org.gradle.api.tasks.Internal import org.gradle.api.tasks.Nested import org.gradle.api.tasks.TaskAction import org.gradle.api.tasks.testing.AbstractTestTask import org.gradle.internal.concurrent.CompositeStoppable.stoppable import org.gradle.internal.logging.ConsoleRenderer import org.gradle.internal.operations.BuildOperationExecutor import org.gradle.internal.reflect.Instantiator import org.gradle.internal.remote.internal.inet.InetAddressFactory import org.jetbrains.kotlin.gradle.utils.injected import java.util.* import javax.inject.Inject @Suppress("UnstableApiUsage") open class AggregateTestReportGradle5 : AggregateTestReport() { @Internal val reports: DefaultTestTaskReports protected open val instantiator: Instantiator @Inject get() = injected protected open val collectionCallbackActionDecorator: CollectionCallbackActionDecorator @Inject get() = injected protected open val buildOperationExecutor: BuildOperationExecutor @Inject get() = injected protected open val inetAddressFactory: InetAddressFactory @Inject get() = injected init { @Suppress("LeakingThis") reports = instantiator.newInstance(DefaultTestTaskReports::class.java, this, collectionCallbackActionDecorator) reports.junitXml.isEnabled = true reports.html.isEnabled = true } override fun configureReportsConvention(name: String) { reports.configureConventions(project, name) } override val htmlReportUrl: String? get() = if (reports.html.isEnabled) ConsoleRenderer().asClickableFileUrl(reports.html.destination.resolve("index.html")) else null @TaskAction fun generateReport() { val resultsProvider = createAggregateProvider() try { if (resultsProvider.isHasResults) { val junitXml = reports.junitXml if (junitXml.isEnabled) { Binary2JUnitXmlReportGenerator( junitXml.destination, resultsProvider, when { junitXml.isOutputPerTestCase -> TestOutputAssociation.WITH_TESTCASE else -> TestOutputAssociation.WITH_SUITE }, buildOperationExecutor, inetAddressFactory.hostname ).generate() } val html = reports.html if (html.isEnabled) { val testReport = DefaultTestReport(buildOperationExecutor) testReport.generateReport(resultsProvider, html.destination) } } else { logger.info("{} - no binary test results found in dirs: {}.", path, testResultDirs) didWork = false } } finally { stoppable(resultsProvider).stop() } checkFailedTests() } private fun createAggregateProvider(): TestResultsProvider { val resultsProviders = LinkedList<TestResultsProvider>() try { val resultDirs = testResultDirs return if (resultDirs.size == 1) BinaryResultBackedTestResultsProvider(resultDirs.single()) else AggregateTestResultsProvider(resultDirs.mapTo(resultsProviders) { BinaryResultBackedTestResultsProvider(it) }) } catch (e: RuntimeException) { stoppable(resultsProviders).stop() throw e } } override fun overrideReporting(task: AbstractTestTask) { task.ignoreFailures = true @Suppress("UnstableApiUsage") task.reports.html.isEnabled = false @Suppress("UnstableApiUsage") task.reports.junitXml.isEnabled = false checkFailedTests = true ignoreFailures = false } }<file_sep>/libraries/tools/kotlin-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/testing/internal/AggregateTestReport.kt /* * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.gradle.testing.internal import org.gradle.api.GradleException import org.gradle.api.internal.AbstractTask import org.gradle.api.tasks.* import org.gradle.api.tasks.testing.AbstractTestTask import org.gradle.api.tasks.testing.TestDescriptor import org.gradle.api.tasks.testing.TestListener import org.gradle.api.tasks.testing.TestResult import java.io.File open class AggregateTestReport : AbstractTask() { @Internal val testTasks = mutableListOf<AbstractTestTask>() /** * Returns the set of binary test results to include in the report. */ @Suppress("MemberVisibilityCanBePrivate") val testResultDirs: Collection<File> @PathSensitive(PathSensitivity.NONE) @InputFiles @SkipWhenEmpty get() { val dirs = mutableListOf<File>() testTasks.forEach { @Suppress("UnstableApiUsage") dirs.add(it.binResultsDir) } return dirs } @Input var ignoreFailures: Boolean = false private var hasFailedTests = false private val failedTestsListener = object : TestListener { override fun beforeTest(testDescriptor: TestDescriptor) { } override fun afterSuite(suite: TestDescriptor, result: TestResult) { } override fun beforeSuite(suite: TestDescriptor) { } override fun afterTest(testDescriptor: TestDescriptor, result: TestResult) { if (result.failedTestCount > 0) { hasFailedTests = true } } } @Input var checkFailedTests: Boolean = false fun registerTestTask(task: AbstractTestTask) { testTasks.add(task) task.addTestListener(failedTestsListener) } open fun configureReportsConvention(name: String) { } @Internal protected open val htmlReportUrl: String? = null protected fun checkFailedTests() { if (checkFailedTests && hasFailedTests) { val message = StringBuilder("There were failing tests.") val reportUrl = htmlReportUrl if (reportUrl != null) { message.append(" See the report at: $reportUrl") } if (ignoreFailures) { logger.warn(message.toString()) } else { throw GradleException(message.toString()) } } } open fun overrideReporting(task: AbstractTestTask) { task.ignoreFailures = true checkFailedTests = true ignoreFailures = false } } <file_sep>/libraries/tools/kotlin-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/testing/internal/testsRegistry.kt /* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.gradle.testing.internal import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.plugins.JavaBasePlugin import org.gradle.api.tasks.testing.AbstractTestTask import org.gradle.language.base.plugins.LifecycleBasePlugin import org.jetbrains.kotlin.gradle.plugin.TaskHolder import org.jetbrains.kotlin.gradle.tasks.locateOrRegisterTask private val Project.allTestsTask: TaskHolder<AggregateTestReport> get() = getAggregatedTestTask( name = "allTests", description = "Runs the tests for all targets and create aggregated report", reportName = "all" ).also { tasks.maybeCreate(LifecycleBasePlugin.CHECK_TASK_NAME) .dependsOn(it.getTaskOrProvider()) } internal fun Project.getAggregatedTestTask(name: String, description: String, reportName: String): TaskHolder<AggregateTestReport> { return locateOrRegisterTask(name) { aggregate -> aggregate.description = description aggregate.group = JavaBasePlugin.VERIFICATION_GROUP aggregate.configureReportsConvention(reportName) aggregate.onlyIf { aggregate.testTasks.size > 1 } if (System.getProperty("idea.active") != null) { aggregate.extensions.extraProperties.set("idea.internal.test", true) } } } private fun cleanTaskName(taskName: String): String { check(taskName.isNotEmpty()) return "clean" + taskName.capitalize() } private val Project.cleanAllTestTask: Task get() { val taskName = cleanTaskName(allTestsTask.name) return tasks.findByName(taskName) ?: tasks.create(taskName, Task::class.java).also { tasks.getByName(LifecycleBasePlugin.CLEAN_TASK_NAME).dependsOn(it) } } @Suppress("UnstableApiUsage") internal fun registerTestTask(taskHolder: TaskHolder<AbstractTestTask>) { registerTestTaskInAggregate(taskHolder, taskHolder.project.allTestsTask.doGetTask()) } internal fun registerTestTaskInAggregate( taskHolder: TaskHolder<AbstractTestTask>, allTests: AggregateTestReport ) { val project = taskHolder.project project.tasks.getByName(LifecycleBasePlugin.CHECK_TASK_NAME).dependsOn(taskHolder.name) project.cleanAllTestTask.dependsOn(cleanTaskName(taskHolder.name)) allTests.dependsOn(taskHolder.name) taskHolder.configure { task -> allTests.registerTestTask(task) project.gradle.taskGraph.whenReady { if (it.hasTask(allTests)) { // when [allTestsTask] task enabled, test failure should be reported only on [allTestsTask], // not at individual target's test tasks. To do that, we need: // - disable all reporting in test tasks // - enable [checkFailedTests] on [allTestsTask] allTests.overrideReporting(task) } } ijListenTestTask(task) } }
9c8a8fc3b402772505cff701f983334bd9c9e3d6
[ "Kotlin" ]
3
Kotlin
chocozhao/kotlin
ff774f62499b69f2261eeae61da3ec1f638ddd23
8cba2e01bf364f5f454890e73e641fc27ef5f97b
refs/heads/master
<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript" charset="utf-8"></script> <script src="specimen_files/easytabs.js" type="text/javascript" charset="utf-8"></script> <link rel="stylesheet" href="specimen_files/specimen_stylesheet.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="stylesheet.css" type="text/css" charset="utf-8" /> <style type="text/css"> body{ font-family: 'AlrightSansLight'; } </style> <title>Alright Sans Light Specimen</title> <script type="text/javascript" charset="utf-8"> $(document).ready(function() { $('#container').easyTabs({defaultContent:1}); }); </script> </head> <body> <div id="container"> <div id="header"> Alright Sans Light </div> <ul class="tabs"> <li><a href="#specimen">Specimen</a></li> <li><a href="#layout">Sample Layout</a></li> <li><a href="#rendering">Windows Rendering</a></li> <li><a href="#glyphs">Glyphs &amp; Languages</a></li> <li><a href="#installing">Installing Webfonts</a></li> </ul> <div id="main_content"> <div id="specimen"> <div class="section"> <div class="grid12 firstcol"> <div class="huge">AaBb</div> </div> </div> <div class="section"> <div class="glyph_range">A&#x200B;B&#x200b;C&#x200b;D&#x200b;E&#x200b;F&#x200b;G&#x200b;H&#x200b;I&#x200b;J&#x200b;K&#x200b;L&#x200b;M&#x200b;N&#x200b;O&#x200b;P&#x200b;Q&#x200b;R&#x200b;S&#x200b;T&#x200b;U&#x200b;V&#x200b;W&#x200b;X&#x200b;Y&#x200b;Z&#x200b;a&#x200b;b&#x200b;c&#x200b;d&#x200b;e&#x200b;f&#x200b;g&#x200b;h&#x200b;i&#x200b;j&#x200b;k&#x200b;l&#x200b;m&#x200b;n&#x200b;o&#x200b;p&#x200b;q&#x200b;r&#x200b;s&#x200b;t&#x200b;u&#x200b;v&#x200b;w&#x200b;x&#x200b;y&#x200b;z&#x200b;1&#x200b;2&#x200b;3&#x200b;4&#x200b;5&#x200b;6&#x200b;7&#x200b;8&#x200b;9&#x200b;0&#x200b;&amp;&#x200b;.&#x200b;,&#x200b;?&#x200b;!&#x200b;&#64;&#x200b;(&#x200b;)&#x200b;#&#x200b;$&#x200b;%&#x200b;*&#x200b;+&#x200b;-&#x200b;=&#x200b;:&#x200b;;</div> </div> <div class="section"> <div class="grid12 firstcol"> <table class="sample_table"> <tr><td>10</td><td class="size10">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>11</td><td class="size11">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>12</td><td class="size12">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>13</td><td class="size13">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>14</td><td class="size14">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>16</td><td class="size16">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>18</td><td class="size18">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>20</td><td class="size20">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>24</td><td class="size24">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>30</td><td class="size30">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>36</td><td class="size36">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>48</td><td class="size48">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>60</td><td class="size60">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>72</td><td class="size72">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> <tr><td>90</td><td class="size90">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</td></tr> </table> </div> </div> <div class="section" id="bodycomparison"> <div id="xheight"> <div class="fontbody">&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;&#xE000;body</div><div class="arialbody">body</div><div class="verdanabody">body</div><div class="georgiabody">body</div></div> <div class="fontbody" style="z-index:1"> body<span>Alright Sans Light</span> </div> <div class="arialbody" style="z-index:1"> body<span>Arial</span> </div> <div class="verdanabody" style="z-index:1"> body<span>Verdana</span> </div> <div class="georgiabody" style="z-index:1"> body<span>Georgia</span> </div> </div> <div class="section psample psample_row1" id=""> <div class="grid2 firstcol"> <p class="size10"><span>10.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid3"> <p class="size11"><span>11.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid3"> <p class="size12"><span>12.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid4"> <p class="size13"><span>13.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="white_blend"></div> </div> <div class="section psample psample_row2" id=""> <div class="grid3 firstcol"> <p class="size14"><span>14.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid4"> <p class="size16"><span>16.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid5"> <p class="size18"><span>18.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="white_blend"></div> </div> <div class="section psample psample_row3" id=""> <div class="grid5 firstcol"> <p class="size20"><span>20.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid7"> <p class="size24"><span>24.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="white_blend"></div> </div> <div class="section psample psample_row4" id=""> <div class="grid12 firstcol"> <p class="size30"><span>30.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="white_blend"></div> </div> <div class="section psample psample_row1 fullreverse"> <div class="grid2 firstcol"> <p class="size10"><span>10.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid3"> <p class="size11"><span>11.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid3"> <p class="size12"><span>12.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid4"> <p class="size13"><span>13.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="black_blend"></div> </div> <div class="section psample psample_row2 fullreverse"> <div class="grid3 firstcol"> <p class="size14"><span>14.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid4"> <p class="size16"><span>16.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid5"> <p class="size18"><span>18.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="black_blend"></div> </div> <div class="section psample fullreverse psample_row3" id=""> <div class="grid5 firstcol"> <p class="size20"><span>20.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="grid7"> <p class="size24"><span>24.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="black_blend"></div> </div> <div class="section psample fullreverse psample_row4" id="" style="border-bottom: 20px #000 solid;"> <div class="grid12 firstcol"> <p class="size30"><span>30.</span>Aenean lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Nullam id dolor id nibh ultricies vehicula ut id elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla vitae elit libero, a pharetra augue.</p> </div> <div class="black_blend"></div> </div> </div> <div id="layout"> <div class="section"> <div class="grid12 firstcol"> <h1>Lorem Ipsum Dolor</h1> <h2>Etiam porta sem malesuada magna mollis euismod</h2> <p class="byline">By <a href="#link">Aenean Lacinia</a></p> </div> </div> <div class="section"> <div class="grid8 firstcol"> <p class="large">Donec sed odio dui. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. </p> <h3>Pellentesque ornare sem</h3> <p>Maecenas sed diam eget risus varius blandit sit amet non magna. Maecenas faucibus mollis interdum. Donec ullamcorper nulla non metus auctor fringilla. Nullam id dolor id nibh ultricies vehicula ut id elit. Nullam id dolor id nibh ultricies vehicula ut id elit. </p> <p>Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. </p> <p>Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Aenean lacinia bibendum nulla sed consectetur. </p> <p>Nullam quis risus eget urna mollis ornare vel eu leo. Nullam quis risus eget urna mollis ornare vel eu leo. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec ullamcorper nulla non metus auctor fringilla. </p> <h3>Cras mattis consectetur</h3> <p>Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Aenean lacinia bibendum nulla sed consectetur. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Cras mattis consectetur purus sit amet fermentum. </p> <p>Nullam id dolor id nibh ultricies vehicula ut id elit. Nullam quis risus eget urna mollis ornare vel eu leo. Cras mattis consectetur purus sit amet fermentum.</p> </div> <div class="grid4 sidebar"> <div class="box reverse"> <p class="last">Nullam quis risus eget urna mollis ornare vel eu leo. Donec ullamcorper nulla non metus auctor fringilla. Cras mattis consectetur purus sit amet fermentum. Sed posuere consectetur est at lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> </div> <p class="caption">Maecenas sed diam eget risus varius.</p> <p>Vestibulum id ligula porta felis euismod semper. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Vestibulum id ligula porta felis euismod semper. Sed posuere consectetur est at lobortis. Maecenas sed diam eget risus varius blandit sit amet non magna. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. </p> <p>Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Aenean lacinia bibendum nulla sed consectetur. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Aenean lacinia bibendum nulla sed consectetur. Nullam quis risus eget urna mollis ornare vel eu leo. </p> <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec ullamcorper nulla non metus auctor fringilla. Maecenas faucibus mollis interdum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. </p> </div> </div> </div> <div id="rendering"> <div class="section"> <div class="grid12 firstcol"> <h1>ClearType (GDI)</h1> <p><img src="specimen_files/alrightsans-light-cleartype.png" /></p> </div> </div> </div> <div id="glyphs"> <div class="section"> <div class="grid12 firstcol"> <h1>Language Support</h1> <p>The subset of Alright Sans Light in this kit supports the following languages:<br /> Albanian, Bosnian, Catalan, Croatian, Czech, Danish, Dutch, English, Esperanto, Estonian, Faroese, French, German, Hungarian, Icelandic, Italian, Latvian, Lithuanian, Malagasy, Maltese, Norwegian, Polish, Romanian, Serbian, Slovak, Slovenian, Spanish, Swedish, Turkish </p> <h1>Glyph Chart</h1> <p>The subset of Alright Sans Light in this kit includes all the glyphs listed below. Unicode entities are included above each glyph to help you insert individual characters into your layout.</p> <div id="glyph_chart"> <div><p>&amp;#32;</p>&#32;</div> <div><p>&amp;#33;</p>&#33;</div> <div><p>&amp;#34;</p>&#34;</div> <div><p>&amp;#35;</p>&#35;</div> <div><p>&amp;#36;</p>&#36;</div> <div><p>&amp;#37;</p>&#37;</div> <div><p>&amp;#38;</p>&#38;</div> <div><p>&amp;#39;</p>&#39;</div> <div><p>&amp;#40;</p>&#40;</div> <div><p>&amp;#41;</p>&#41;</div> <div><p>&amp;#42;</p>&#42;</div> <div><p>&amp;#43;</p>&#43;</div> <div><p>&amp;#44;</p>&#44;</div> <div><p>&amp;#45;</p>&#45;</div> <div><p>&amp;#46;</p>&#46;</div> <div><p>&amp;#47;</p>&#47;</div> <div><p>&amp;#48;</p>&#48;</div> <div><p>&amp;#49;</p>&#49;</div> <div><p>&amp;#50;</p>&#50;</div> <div><p>&amp;#51;</p>&#51;</div> <div><p>&amp;#52;</p>&#52;</div> <div><p>&amp;#53;</p>&#53;</div> <div><p>&amp;#54;</p>&#54;</div> <div><p>&amp;#55;</p>&#55;</div> <div><p>&amp;#56;</p>&#56;</div> <div><p>&amp;#57;</p>&#57;</div> <div><p>&amp;#58;</p>&#58;</div> <div><p>&amp;#59;</p>&#59;</div> <div><p>&amp;#60;</p>&#60;</div> <div><p>&amp;#61;</p>&#61;</div> <div><p>&amp;#62;</p>&#62;</div> <div><p>&amp;#63;</p>&#63;</div> <div><p>&amp;#64;</p>&#64;</div> <div><p>&amp;#65;</p>&#65;</div> <div><p>&amp;#66;</p>&#66;</div> <div><p>&amp;#67;</p>&#67;</div> <div><p>&amp;#68;</p>&#68;</div> <div><p>&amp;#69;</p>&#69;</div> <div><p>&amp;#70;</p>&#70;</div> <div><p>&amp;#71;</p>&#71;</div> <div><p>&amp;#72;</p>&#72;</div> <div><p>&amp;#73;</p>&#73;</div> <div><p>&amp;#74;</p>&#74;</div> <div><p>&amp;#75;</p>&#75;</div> <div><p>&amp;#76;</p>&#76;</div> <div><p>&amp;#77;</p>&#77;</div> <div><p>&amp;#78;</p>&#78;</div> <div><p>&amp;#79;</p>&#79;</div> <div><p>&amp;#80;</p>&#80;</div> <div><p>&amp;#81;</p>&#81;</div> <div><p>&amp;#82;</p>&#82;</div> <div><p>&amp;#83;</p>&#83;</div> <div><p>&amp;#84;</p>&#84;</div> <div><p>&amp;#85;</p>&#85;</div> <div><p>&amp;#86;</p>&#86;</div> <div><p>&amp;#87;</p>&#87;</div> <div><p>&amp;#88;</p>&#88;</div> <div><p>&amp;#89;</p>&#89;</div> <div><p>&amp;#90;</p>&#90;</div> <div><p>&amp;#91;</p>&#91;</div> <div><p>&amp;#92;</p>&#92;</div> <div><p>&amp;#93;</p>&#93;</div> <div><p>&amp;#94;</p>&#94;</div> <div><p>&amp;#95;</p>&#95;</div> <div><p>&amp;#96;</p>&#96;</div> <div><p>&amp;#97;</p>&#97;</div> <div><p>&amp;#98;</p>&#98;</div> <div><p>&amp;#99;</p>&#99;</div> <div><p>&amp;#100;</p>&#100;</div> <div><p>&amp;#101;</p>&#101;</div> <div><p>&amp;#102;</p>&#102;</div> <div><p>&amp;#103;</p>&#103;</div> <div><p>&amp;#104;</p>&#104;</div> <div><p>&amp;#105;</p>&#105;</div> <div><p>&amp;#106;</p>&#106;</div> <div><p>&amp;#107;</p>&#107;</div> <div><p>&amp;#108;</p>&#108;</div> <div><p>&amp;#109;</p>&#109;</div> <div><p>&amp;#110;</p>&#110;</div> <div><p>&amp;#111;</p>&#111;</div> <div><p>&amp;#112;</p>&#112;</div> <div><p>&amp;#113;</p>&#113;</div> <div><p>&amp;#114;</p>&#114;</div> <div><p>&amp;#115;</p>&#115;</div> <div><p>&amp;#116;</p>&#116;</div> <div><p>&amp;#117;</p>&#117;</div> <div><p>&amp;#118;</p>&#118;</div> <div><p>&amp;#119;</p>&#119;</div> <div><p>&amp;#120;</p>&#120;</div> <div><p>&amp;#121;</p>&#121;</div> <div><p>&amp;#122;</p>&#122;</div> <div><p>&amp;#123;</p>&#123;</div> <div><p>&amp;#124;</p>&#124;</div> <div><p>&amp;#125;</p>&#125;</div> <div><p>&amp;#126;</p>&#126;</div> <div><p>&amp;#160;</p>&#160;</div> <div><p>&amp;#161;</p>&#161;</div> <div><p>&amp;#162;</p>&#162;</div> <div><p>&amp;#163;</p>&#163;</div> <div><p>&amp;#164;</p>&#164;</div> <div><p>&amp;#165;</p>&#165;</div> <div><p>&amp;#166;</p>&#166;</div> <div><p>&amp;#167;</p>&#167;</div> <div><p>&amp;#168;</p>&#168;</div> <div><p>&amp;#169;</p>&#169;</div> <div><p>&amp;#170;</p>&#170;</div> <div><p>&amp;#171;</p>&#171;</div> <div><p>&amp;#172;</p>&#172;</div> <div><p>&amp;#174;</p>&#174;</div> <div><p>&amp;#175;</p>&#175;</div> <div><p>&amp;#176;</p>&#176;</div> <div><p>&amp;#177;</p>&#177;</div> <div><p>&amp;#178;</p>&#178;</div> <div><p>&amp;#179;</p>&#179;</div> <div><p>&amp;#180;</p>&#180;</div> <div><p>&amp;#181;</p>&#181;</div> <div><p>&amp;#182;</p>&#182;</div> <div><p>&amp;#183;</p>&#183;</div> <div><p>&amp;#184;</p>&#184;</div> <div><p>&amp;#185;</p>&#185;</div> <div><p>&amp;#186;</p>&#186;</div> <div><p>&amp;#187;</p>&#187;</div> <div><p>&amp;#188;</p>&#188;</div> <div><p>&amp;#189;</p>&#189;</div> <div><p>&amp;#190;</p>&#190;</div> <div><p>&amp;#191;</p>&#191;</div> <div><p>&amp;#192;</p>&#192;</div> <div><p>&amp;#193;</p>&#193;</div> <div><p>&amp;#194;</p>&#194;</div> <div><p>&amp;#195;</p>&#195;</div> <div><p>&amp;#196;</p>&#196;</div> <div><p>&amp;#197;</p>&#197;</div> <div><p>&amp;#198;</p>&#198;</div> <div><p>&amp;#199;</p>&#199;</div> <div><p>&amp;#200;</p>&#200;</div> <div><p>&amp;#201;</p>&#201;</div> <div><p>&amp;#202;</p>&#202;</div> <div><p>&amp;#203;</p>&#203;</div> <div><p>&amp;#204;</p>&#204;</div> <div><p>&amp;#205;</p>&#205;</div> <div><p>&amp;#206;</p>&#206;</div> <div><p>&amp;#207;</p>&#207;</div> <div><p>&amp;#208;</p>&#208;</div> <div><p>&amp;#209;</p>&#209;</div> <div><p>&amp;#210;</p>&#210;</div> <div><p>&amp;#211;</p>&#211;</div> <div><p>&amp;#212;</p>&#212;</div> <div><p>&amp;#213;</p>&#213;</div> <div><p>&amp;#214;</p>&#214;</div> <div><p>&amp;#215;</p>&#215;</div> <div><p>&amp;#216;</p>&#216;</div> <div><p>&amp;#217;</p>&#217;</div> <div><p>&amp;#218;</p>&#218;</div> <div><p>&amp;#219;</p>&#219;</div> <div><p>&amp;#220;</p>&#220;</div> <div><p>&amp;#221;</p>&#221;</div> <div><p>&amp;#222;</p>&#222;</div> <div><p>&amp;#223;</p>&#223;</div> <div><p>&amp;#224;</p>&#224;</div> <div><p>&amp;#225;</p>&#225;</div> <div><p>&amp;#226;</p>&#226;</div> <div><p>&amp;#227;</p>&#227;</div> <div><p>&amp;#228;</p>&#228;</div> <div><p>&amp;#229;</p>&#229;</div> <div><p>&amp;#230;</p>&#230;</div> <div><p>&amp;#231;</p>&#231;</div> <div><p>&amp;#232;</p>&#232;</div> <div><p>&amp;#233;</p>&#233;</div> <div><p>&amp;#234;</p>&#234;</div> <div><p>&amp;#235;</p>&#235;</div> <div><p>&amp;#236;</p>&#236;</div> <div><p>&amp;#237;</p>&#237;</div> <div><p>&amp;#238;</p>&#238;</div> <div><p>&amp;#239;</p>&#239;</div> <div><p>&amp;#240;</p>&#240;</div> <div><p>&amp;#241;</p>&#241;</div> <div><p>&amp;#242;</p>&#242;</div> <div><p>&amp;#243;</p>&#243;</div> <div><p>&amp;#244;</p>&#244;</div> <div><p>&amp;#245;</p>&#245;</div> <div><p>&amp;#246;</p>&#246;</div> <div><p>&amp;#247;</p>&#247;</div> <div><p>&amp;#248;</p>&#248;</div> <div><p>&amp;#249;</p>&#249;</div> <div><p>&amp;#250;</p>&#250;</div> <div><p>&amp;#251;</p>&#251;</div> <div><p>&amp;#252;</p>&#252;</div> <div><p>&amp;#253;</p>&#253;</div> <div><p>&amp;#254;</p>&#254;</div> <div><p>&amp;#255;</p>&#255;</div> <div><p>&amp;#256;</p>&#256;</div> <div><p>&amp;#257;</p>&#257;</div> <div><p>&amp;#258;</p>&#258;</div> <div><p>&amp;#259;</p>&#259;</div> <div><p>&amp;#260;</p>&#260;</div> <div><p>&amp;#261;</p>&#261;</div> <div><p>&amp;#262;</p>&#262;</div> <div><p>&amp;#263;</p>&#263;</div> <div><p>&amp;#264;</p>&#264;</div> <div><p>&amp;#265;</p>&#265;</div> <div><p>&amp;#266;</p>&#266;</div> <div><p>&amp;#267;</p>&#267;</div> <div><p>&amp;#268;</p>&#268;</div> <div><p>&amp;#269;</p>&#269;</div> <div><p>&amp;#270;</p>&#270;</div> <div><p>&amp;#271;</p>&#271;</div> <div><p>&amp;#272;</p>&#272;</div> <div><p>&amp;#273;</p>&#273;</div> <div><p>&amp;#274;</p>&#274;</div> <div><p>&amp;#275;</p>&#275;</div> <div><p>&amp;#276;</p>&#276;</div> <div><p>&amp;#277;</p>&#277;</div> <div><p>&amp;#278;</p>&#278;</div> <div><p>&amp;#279;</p>&#279;</div> <div><p>&amp;#280;</p>&#280;</div> <div><p>&amp;#281;</p>&#281;</div> <div><p>&amp;#282;</p>&#282;</div> <div><p>&amp;#283;</p>&#283;</div> <div><p>&amp;#284;</p>&#284;</div> <div><p>&amp;#285;</p>&#285;</div> <div><p>&amp;#286;</p>&#286;</div> <div><p>&amp;#287;</p>&#287;</div> <div><p>&amp;#288;</p>&#288;</div> <div><p>&amp;#289;</p>&#289;</div> <div><p>&amp;#290;</p>&#290;</div> <div><p>&amp;#291;</p>&#291;</div> <div><p>&amp;#292;</p>&#292;</div> <div><p>&amp;#293;</p>&#293;</div> <div><p>&amp;#294;</p>&#294;</div> <div><p>&amp;#295;</p>&#295;</div> <div><p>&amp;#296;</p>&#296;</div> <div><p>&amp;#297;</p>&#297;</div> <div><p>&amp;#298;</p>&#298;</div> <div><p>&amp;#299;</p>&#299;</div> <div><p>&amp;#300;</p>&#300;</div> <div><p>&amp;#301;</p>&#301;</div> <div><p>&amp;#302;</p>&#302;</div> <div><p>&amp;#303;</p>&#303;</div> <div><p>&amp;#304;</p>&#304;</div> <div><p>&amp;#305;</p>&#305;</div> <div><p>&amp;#308;</p>&#308;</div> <div><p>&amp;#309;</p>&#309;</div> <div><p>&amp;#310;</p>&#310;</div> <div><p>&amp;#311;</p>&#311;</div> <div><p>&amp;#312;</p>&#312;</div> <div><p>&amp;#313;</p>&#313;</div> <div><p>&amp;#314;</p>&#314;</div> <div><p>&amp;#315;</p>&#315;</div> <div><p>&amp;#316;</p>&#316;</div> <div><p>&amp;#317;</p>&#317;</div> <div><p>&amp;#318;</p>&#318;</div> <div><p>&amp;#319;</p>&#319;</div> <div><p>&amp;#320;</p>&#320;</div> <div><p>&amp;#321;</p>&#321;</div> <div><p>&amp;#322;</p>&#322;</div> <div><p>&amp;#323;</p>&#323;</div> <div><p>&amp;#324;</p>&#324;</div> <div><p>&amp;#325;</p>&#325;</div> <div><p>&amp;#326;</p>&#326;</div> <div><p>&amp;#327;</p>&#327;</div> <div><p>&amp;#328;</p>&#328;</div> <div><p>&amp;#330;</p>&#330;</div> <div><p>&amp;#331;</p>&#331;</div> <div><p>&amp;#332;</p>&#332;</div> <div><p>&amp;#333;</p>&#333;</div> <div><p>&amp;#334;</p>&#334;</div> <div><p>&amp;#335;</p>&#335;</div> <div><p>&amp;#336;</p>&#336;</div> <div><p>&amp;#337;</p>&#337;</div> <div><p>&amp;#338;</p>&#338;</div> <div><p>&amp;#339;</p>&#339;</div> <div><p>&amp;#340;</p>&#340;</div> <div><p>&amp;#341;</p>&#341;</div> <div><p>&amp;#342;</p>&#342;</div> <div><p>&amp;#343;</p>&#343;</div> <div><p>&amp;#344;</p>&#344;</div> <div><p>&amp;#345;</p>&#345;</div> <div><p>&amp;#346;</p>&#346;</div> <div><p>&amp;#347;</p>&#347;</div> <div><p>&amp;#348;</p>&#348;</div> <div><p>&amp;#349;</p>&#349;</div> <div><p>&amp;#350;</p>&#350;</div> <div><p>&amp;#351;</p>&#351;</div> <div><p>&amp;#352;</p>&#352;</div> <div><p>&amp;#353;</p>&#353;</div> <div><p>&amp;#354;</p>&#354;</div> <div><p>&amp;#355;</p>&#355;</div> <div><p>&amp;#356;</p>&#356;</div> <div><p>&amp;#357;</p>&#357;</div> <div><p>&amp;#358;</p>&#358;</div> <div><p>&amp;#359;</p>&#359;</div> <div><p>&amp;#360;</p>&#360;</div> <div><p>&amp;#361;</p>&#361;</div> <div><p>&amp;#362;</p>&#362;</div> <div><p>&amp;#363;</p>&#363;</div> <div><p>&amp;#364;</p>&#364;</div> <div><p>&amp;#365;</p>&#365;</div> <div><p>&amp;#366;</p>&#366;</div> <div><p>&amp;#367;</p>&#367;</div> <div><p>&amp;#368;</p>&#368;</div> <div><p>&amp;#369;</p>&#369;</div> <div><p>&amp;#370;</p>&#370;</div> <div><p>&amp;#371;</p>&#371;</div> <div><p>&amp;#372;</p>&#372;</div> <div><p>&amp;#373;</p>&#373;</div> <div><p>&amp;#374;</p>&#374;</div> <div><p>&amp;#375;</p>&#375;</div> <div><p>&amp;#376;</p>&#376;</div> <div><p>&amp;#377;</p>&#377;</div> <div><p>&amp;#378;</p>&#378;</div> <div><p>&amp;#379;</p>&#379;</div> <div><p>&amp;#380;</p>&#380;</div> <div><p>&amp;#381;</p>&#381;</div> <div><p>&amp;#382;</p>&#382;</div> <div><p>&amp;#399;</p>&#399;</div> <div><p>&amp;#402;</p>&#402;</div> <div><p>&amp;#408;</p>&#408;</div> <div><p>&amp;#409;</p>&#409;</div> <div><p>&amp;#415;</p>&#415;</div> <div><p>&amp;#439;</p>&#439;</div> <div><p>&amp;#461;</p>&#461;</div> <div><p>&amp;#462;</p>&#462;</div> <div><p>&amp;#463;</p>&#463;</div> <div><p>&amp;#464;</p>&#464;</div> <div><p>&amp;#465;</p>&#465;</div> <div><p>&amp;#466;</p>&#466;</div> <div><p>&amp;#467;</p>&#467;</div> <div><p>&amp;#468;</p>&#468;</div> <div><p>&amp;#478;</p>&#478;</div> <div><p>&amp;#479;</p>&#479;</div> <div><p>&amp;#482;</p>&#482;</div> <div><p>&amp;#483;</p>&#483;</div> <div><p>&amp;#484;</p>&#484;</div> <div><p>&amp;#485;</p>&#485;</div> <div><p>&amp;#486;</p>&#486;</div> <div><p>&amp;#487;</p>&#487;</div> <div><p>&amp;#488;</p>&#488;</div> <div><p>&amp;#489;</p>&#489;</div> <div><p>&amp;#490;</p>&#490;</div> <div><p>&amp;#491;</p>&#491;</div> <div><p>&amp;#492;</p>&#492;</div> <div><p>&amp;#493;</p>&#493;</div> <div><p>&amp;#494;</p>&#494;</div> <div><p>&amp;#495;</p>&#495;</div> <div><p>&amp;#496;</p>&#496;</div> <div><p>&amp;#500;</p>&#500;</div> <div><p>&amp;#501;</p>&#501;</div> <div><p>&amp;#506;</p>&#506;</div> <div><p>&amp;#507;</p>&#507;</div> <div><p>&amp;#508;</p>&#508;</div> <div><p>&amp;#509;</p>&#509;</div> <div><p>&amp;#510;</p>&#510;</div> <div><p>&amp;#511;</p>&#511;</div> <div><p>&amp;#512;</p>&#512;</div> <div><p>&amp;#513;</p>&#513;</div> <div><p>&amp;#514;</p>&#514;</div> <div><p>&amp;#515;</p>&#515;</div> <div><p>&amp;#516;</p>&#516;</div> <div><p>&amp;#517;</p>&#517;</div> <div><p>&amp;#518;</p>&#518;</div> <div><p>&amp;#519;</p>&#519;</div> <div><p>&amp;#520;</p>&#520;</div> <div><p>&amp;#521;</p>&#521;</div> <div><p>&amp;#522;</p>&#522;</div> <div><p>&amp;#523;</p>&#523;</div> <div><p>&amp;#524;</p>&#524;</div> <div><p>&amp;#525;</p>&#525;</div> <div><p>&amp;#526;</p>&#526;</div> <div><p>&amp;#527;</p>&#527;</div> <div><p>&amp;#528;</p>&#528;</div> <div><p>&amp;#529;</p>&#529;</div> <div><p>&amp;#530;</p>&#530;</div> <div><p>&amp;#531;</p>&#531;</div> <div><p>&amp;#532;</p>&#532;</div> <div><p>&amp;#533;</p>&#533;</div> <div><p>&amp;#534;</p>&#534;</div> <div><p>&amp;#535;</p>&#535;</div> <div><p>&amp;#536;</p>&#536;</div> <div><p>&amp;#537;</p>&#537;</div> <div><p>&amp;#538;</p>&#538;</div> <div><p>&amp;#539;</p>&#539;</div> <div><p>&amp;#542;</p>&#542;</div> <div><p>&amp;#543;</p>&#543;</div> <div><p>&amp;#550;</p>&#550;</div> <div><p>&amp;#551;</p>&#551;</div> <div><p>&amp;#556;</p>&#556;</div> <div><p>&amp;#557;</p>&#557;</div> <div><p>&amp;#558;</p>&#558;</div> <div><p>&amp;#559;</p>&#559;</div> <div><p>&amp;#560;</p>&#560;</div> <div><p>&amp;#561;</p>&#561;</div> <div><p>&amp;#567;</p>&#567;</div> <div><p>&amp;#601;</p>&#601;</div> <div><p>&amp;#629;</p>&#629;</div> <div><p>&amp;#658;</p>&#658;</div> <div><p>&amp;#710;</p>&#710;</div> <div><p>&amp;#711;</p>&#711;</div> <div><p>&amp;#728;</p>&#728;</div> <div><p>&amp;#729;</p>&#729;</div> <div><p>&amp;#730;</p>&#730;</div> <div><p>&amp;#731;</p>&#731;</div> <div><p>&amp;#732;</p>&#732;</div> <div><p>&amp;#733;</p>&#733;</div> <div><p>&amp;#783;</p>&#783;</div> <div><p>&amp;#785;</p>&#785;</div> <div><p>&amp;#787;</p>&#787;</div> <div><p>&amp;#803;</p>&#803;</div> <div><p>&amp;#809;</p>&#809;</div> <div><p>&amp;#960;</p>&#960;</div> <div><p>&amp;#7692;</p>&#7692;</div> <div><p>&amp;#7693;</p>&#7693;</div> <div><p>&amp;#7696;</p>&#7696;</div> <div><p>&amp;#7697;</p>&#7697;</div> <div><p>&amp;#7716;</p>&#7716;</div> <div><p>&amp;#7717;</p>&#7717;</div> <div><p>&amp;#7734;</p>&#7734;</div> <div><p>&amp;#7735;</p>&#7735;</div> <div><p>&amp;#7736;</p>&#7736;</div> <div><p>&amp;#7737;</p>&#7737;</div> <div><p>&amp;#7746;</p>&#7746;</div> <div><p>&amp;#7747;</p>&#7747;</div> <div><p>&amp;#7748;</p>&#7748;</div> <div><p>&amp;#7749;</p>&#7749;</div> <div><p>&amp;#7750;</p>&#7750;</div> <div><p>&amp;#7751;</p>&#7751;</div> <div><p>&amp;#7770;</p>&#7770;</div> <div><p>&amp;#7771;</p>&#7771;</div> <div><p>&amp;#7772;</p>&#7772;</div> <div><p>&amp;#7773;</p>&#7773;</div> <div><p>&amp;#7778;</p>&#7778;</div> <div><p>&amp;#7779;</p>&#7779;</div> <div><p>&amp;#7788;</p>&#7788;</div> <div><p>&amp;#7789;</p>&#7789;</div> <div><p>&amp;#7808;</p>&#7808;</div> <div><p>&amp;#7809;</p>&#7809;</div> <div><p>&amp;#7810;</p>&#7810;</div> <div><p>&amp;#7811;</p>&#7811;</div> <div><p>&amp;#7812;</p>&#7812;</div> <div><p>&amp;#7813;</p>&#7813;</div> <div><p>&amp;#7830;</p>&#7830;</div> <div><p>&amp;#7838;</p>&#7838;</div> <div><p>&amp;#7882;</p>&#7882;</div> <div><p>&amp;#7883;</p>&#7883;</div> <div><p>&amp;#7884;</p>&#7884;</div> <div><p>&amp;#7885;</p>&#7885;</div> <div><p>&amp;#7908;</p>&#7908;</div> <div><p>&amp;#7909;</p>&#7909;</div> <div><p>&amp;#7922;</p>&#7922;</div> <div><p>&amp;#7923;</p>&#7923;</div> <div><p>&amp;#7928;</p>&#7928;</div> <div><p>&amp;#7929;</p>&#7929;</div> <div><p>&amp;#8194;</p>&#8194;</div> <div><p>&amp;#8195;</p>&#8195;</div> <div><p>&amp;#8196;</p>&#8196;</div> <div><p>&amp;#8197;</p>&#8197;</div> <div><p>&amp;#8198;</p>&#8198;</div> <div><p>&amp;#8199;</p>&#8199;</div> <div><p>&amp;#8200;</p>&#8200;</div> <div><p>&amp;#8201;</p>&#8201;</div> <div><p>&amp;#8202;</p>&#8202;</div> <div><p>&amp;#8203;</p>&#8203;</div> <div><p>&amp;#8211;</p>&#8211;</div> <div><p>&amp;#8212;</p>&#8212;</div> <div><p>&amp;#8216;</p>&#8216;</div> <div><p>&amp;#8217;</p>&#8217;</div> <div><p>&amp;#8218;</p>&#8218;</div> <div><p>&amp;#8220;</p>&#8220;</div> <div><p>&amp;#8221;</p>&#8221;</div> <div><p>&amp;#8222;</p>&#8222;</div> <div><p>&amp;#8224;</p>&#8224;</div> <div><p>&amp;#8225;</p>&#8225;</div> <div><p>&amp;#8226;</p>&#8226;</div> <div><p>&amp;#8230;</p>&#8230;</div> <div><p>&amp;#8240;</p>&#8240;</div> <div><p>&amp;#8249;</p>&#8249;</div> <div><p>&amp;#8250;</p>&#8250;</div> <div><p>&amp;#8253;</p>&#8253;</div> <div><p>&amp;#8260;</p>&#8260;</div> <div><p>&amp;#8304;</p>&#8304;</div> <div><p>&amp;#8308;</p>&#8308;</div> <div><p>&amp;#8309;</p>&#8309;</div> <div><p>&amp;#8310;</p>&#8310;</div> <div><p>&amp;#8311;</p>&#8311;</div> <div><p>&amp;#8312;</p>&#8312;</div> <div><p>&amp;#8313;</p>&#8313;</div> <div><p>&amp;#8314;</p>&#8314;</div> <div><p>&amp;#8315;</p>&#8315;</div> <div><p>&amp;#8316;</p>&#8316;</div> <div><p>&amp;#8317;</p>&#8317;</div> <div><p>&amp;#8318;</p>&#8318;</div> <div><p>&amp;#8319;</p>&#8319;</div> <div><p>&amp;#8320;</p>&#8320;</div> <div><p>&amp;#8321;</p>&#8321;</div> <div><p>&amp;#8322;</p>&#8322;</div> <div><p>&amp;#8323;</p>&#8323;</div> <div><p>&amp;#8324;</p>&#8324;</div> <div><p>&amp;#8325;</p>&#8325;</div> <div><p>&amp;#8326;</p>&#8326;</div> <div><p>&amp;#8327;</p>&#8327;</div> <div><p>&amp;#8328;</p>&#8328;</div> <div><p>&amp;#8329;</p>&#8329;</div> <div><p>&amp;#8333;</p>&#8333;</div> <div><p>&amp;#8334;</p>&#8334;</div> <div><p>&amp;#8353;</p>&#8353;</div> <div><p>&amp;#8364;</p>&#8364;</div> <div><p>&amp;#8467;</p>&#8467;</div> <div><p>&amp;#8470;</p>&#8470;</div> <div><p>&amp;#8480;</p>&#8480;</div> <div><p>&amp;#8482;</p>&#8482;</div> <div><p>&amp;#8486;</p>&#8486;</div> <div><p>&amp;#8494;</p>&#8494;</div> <div><p>&amp;#8592;</p>&#8592;</div> <div><p>&amp;#8593;</p>&#8593;</div> <div><p>&amp;#8594;</p>&#8594;</div> <div><p>&amp;#8595;</p>&#8595;</div> <div><p>&amp;#8598;</p>&#8598;</div> <div><p>&amp;#8599;</p>&#8599;</div> <div><p>&amp;#8600;</p>&#8600;</div> <div><p>&amp;#8601;</p>&#8601;</div> <div><p>&amp;#8706;</p>&#8706;</div> <div><p>&amp;#8710;</p>&#8710;</div> <div><p>&amp;#8719;</p>&#8719;</div> <div><p>&amp;#8721;</p>&#8721;</div> <div><p>&amp;#8722;</p>&#8722;</div> <div><p>&amp;#8730;</p>&#8730;</div> <div><p>&amp;#8734;</p>&#8734;</div> <div><p>&amp;#8747;</p>&#8747;</div> <div><p>&amp;#8776;</p>&#8776;</div> <div><p>&amp;#8800;</p>&#8800;</div> <div><p>&amp;#8804;</p>&#8804;</div> <div><p>&amp;#8805;</p>&#8805;</div> <div><p>&amp;#9632;</p>&#9632;</div> <div><p>&amp;#9633;</p>&#9633;</div> <div><p>&amp;#9635;</p>&#9635;</div> <div><p>&amp;#9650;</p>&#9650;</div> <div><p>&amp;#9654;</p>&#9654;</div> <div><p>&amp;#9660;</p>&#9660;</div> <div><p>&amp;#9664;</p>&#9664;</div> <div><p>&amp;#9673;</p>&#9673;</div> <div><p>&amp;#9674;</p>&#9674;</div> <div><p>&amp;#9675;</p>&#9675;</div> <div><p>&amp;#9677;</p>&#9677;</div> <div><p>&amp;#9678;</p>&#9678;</div> <div><p>&amp;#9679;</p>&#9679;</div> <div><p>&amp;#9698;</p>&#9698;</div> <div><p>&amp;#9699;</p>&#9699;</div> <div><p>&amp;#9700;</p>&#9700;</div> <div><p>&amp;#9701;</p>&#9701;</div> <div><p>&amp;#9733;</p>&#9733;</div> <div><p>&amp;#9760;</p>&#9760;</div> <div><p>&amp;#11800;</p>&#11800;</div> <div><p>&amp;#12296;</p>&#12296;</div> <div><p>&amp;#12297;</p>&#12297;</div> <div><p>&amp;#57344;</p>&#57344;</div> <div><p>&amp;#57348;</p>&#57348;</div> <div><p>&amp;#57349;</p>&#57349;</div> <div><p>&amp;#57353;</p>&#57353;</div> <div><p>&amp;#57356;</p>&#57356;</div> <div><p>&amp;#57357;</p>&#57357;</div> <div><p>&amp;#57358;</p>&#57358;</div> <div><p>&amp;#57359;</p>&#57359;</div> <div><p>&amp;#57360;</p>&#57360;</div> <div><p>&amp;#57361;</p>&#57361;</div> <div><p>&amp;#57362;</p>&#57362;</div> <div><p>&amp;#57363;</p>&#57363;</div> <div><p>&amp;#57364;</p>&#57364;</div> <div><p>&amp;#57365;</p>&#57365;</div> <div><p>&amp;#57367;</p>&#57367;</div> <div><p>&amp;#57371;</p>&#57371;</div> <div><p>&amp;#57372;</p>&#57372;</div> <div><p>&amp;#57374;</p>&#57374;</div> <div><p>&amp;#57376;</p>&#57376;</div> <div><p>&amp;#57378;</p>&#57378;</div> <div><p>&amp;#57379;</p>&#57379;</div> <div><p>&amp;#57384;</p>&#57384;</div> <div><p>&amp;#57385;</p>&#57385;</div> <div><p>&amp;#57392;</p>&#57392;</div> <div><p>&amp;#57393;</p>&#57393;</div> <div><p>&amp;#57394;</p>&#57394;</div> <div><p>&amp;#57395;</p>&#57395;</div> <div><p>&amp;#57396;</p>&#57396;</div> <div><p>&amp;#57397;</p>&#57397;</div> <div><p>&amp;#57398;</p>&#57398;</div> <div><p>&amp;#57399;</p>&#57399;</div> <div><p>&amp;#57400;</p>&#57400;</div> <div><p>&amp;#57401;</p>&#57401;</div> <div><p>&amp;#57403;</p>&#57403;</div> <div><p>&amp;#57407;</p>&#57407;</div> <div><p>&amp;#57408;</p>&#57408;</div> <div><p>&amp;#57410;</p>&#57410;</div> <div><p>&amp;#57412;</p>&#57412;</div> <div><p>&amp;#57415;</p>&#57415;</div> <div><p>&amp;#57440;</p>&#57440;</div> <div><p>&amp;#57452;</p>&#57452;</div> <div><p>&amp;#57453;</p>&#57453;</div> <div><p>&amp;#57454;</p>&#57454;</div> <div><p>&amp;#57455;</p>&#57455;</div> <div><p>&amp;#57456;</p>&#57456;</div> <div><p>&amp;#57457;</p>&#57457;</div> <div><p>&amp;#57458;</p>&#57458;</div> <div><p>&amp;#57459;</p>&#57459;</div> <div><p>&amp;#57460;</p>&#57460;</div> <div><p>&amp;#57461;</p>&#57461;</div> <div><p>&amp;#57462;</p>&#57462;</div> <div><p>&amp;#57463;</p>&#57463;</div> <div><p>&amp;#57464;</p>&#57464;</div> <div><p>&amp;#57465;</p>&#57465;</div> <div><p>&amp;#57466;</p>&#57466;</div> <div><p>&amp;#57467;</p>&#57467;</div> <div><p>&amp;#57468;</p>&#57468;</div> <div><p>&amp;#57469;</p>&#57469;</div> <div><p>&amp;#57470;</p>&#57470;</div> <div><p>&amp;#57471;</p>&#57471;</div> <div><p>&amp;#57472;</p>&#57472;</div> <div><p>&amp;#57473;</p>&#57473;</div> <div><p>&amp;#57474;</p>&#57474;</div> <div><p>&amp;#57475;</p>&#57475;</div> <div><p>&amp;#57476;</p>&#57476;</div> <div><p>&amp;#57477;</p>&#57477;</div> <div><p>&amp;#57478;</p>&#57478;</div> <div><p>&amp;#57479;</p>&#57479;</div> <div><p>&amp;#57480;</p>&#57480;</div> <div><p>&amp;#57481;</p>&#57481;</div> <div><p>&amp;#57482;</p>&#57482;</div> <div><p>&amp;#57483;</p>&#57483;</div> <div><p>&amp;#57484;</p>&#57484;</div> <div><p>&amp;#57485;</p>&#57485;</div> <div><p>&amp;#57486;</p>&#57486;</div> <div><p>&amp;#57487;</p>&#57487;</div> <div><p>&amp;#57488;</p>&#57488;</div> <div><p>&amp;#57489;</p>&#57489;</div> <div><p>&amp;#57490;</p>&#57490;</div> <div><p>&amp;#57491;</p>&#57491;</div> <div><p>&amp;#57492;</p>&#57492;</div> <div><p>&amp;#57493;</p>&#57493;</div> <div><p>&amp;#57494;</p>&#57494;</div> <div><p>&amp;#57495;</p>&#57495;</div> <div><p>&amp;#57496;</p>&#57496;</div> <div><p>&amp;#57497;</p>&#57497;</div> <div><p>&amp;#57498;</p>&#57498;</div> <div><p>&amp;#57499;</p>&#57499;</div> <div><p>&amp;#57500;</p>&#57500;</div> <div><p>&amp;#57501;</p>&#57501;</div> <div><p>&amp;#57502;</p>&#57502;</div> <div><p>&amp;#57503;</p>&#57503;</div> <div><p>&amp;#57504;</p>&#57504;</div> <div><p>&amp;#57505;</p>&#57505;</div> <div><p>&amp;#57506;</p>&#57506;</div> <div><p>&amp;#57507;</p>&#57507;</div> <div><p>&amp;#57508;</p>&#57508;</div> <div><p>&amp;#57509;</p>&#57509;</div> <div><p>&amp;#57510;</p>&#57510;</div> <div><p>&amp;#57511;</p>&#57511;</div> <div><p>&amp;#57512;</p>&#57512;</div> <div><p>&amp;#57513;</p>&#57513;</div> <div><p>&amp;#57514;</p>&#57514;</div> <div><p>&amp;#57515;</p>&#57515;</div> <div><p>&amp;#57516;</p>&#57516;</div> <div><p>&amp;#57517;</p>&#57517;</div> <div><p>&amp;#57518;</p>&#57518;</div> <div><p>&amp;#57519;</p>&#57519;</div> <div><p>&amp;#57520;</p>&#57520;</div> <div><p>&amp;#57522;</p>&#57522;</div> <div><p>&amp;#57523;</p>&#57523;</div> <div><p>&amp;#57524;</p>&#57524;</div> <div><p>&amp;#57526;</p>&#57526;</div> <div><p>&amp;#57527;</p>&#57527;</div> <div><p>&amp;#57528;</p>&#57528;</div> <div><p>&amp;#57529;</p>&#57529;</div> <div><p>&amp;#57530;</p>&#57530;</div> <div><p>&amp;#57531;</p>&#57531;</div> <div><p>&amp;#57532;</p>&#57532;</div> <div><p>&amp;#57533;</p>&#57533;</div> <div><p>&amp;#57534;</p>&#57534;</div> <div><p>&amp;#57535;</p>&#57535;</div> <div><p>&amp;#57536;</p>&#57536;</div> <div><p>&amp;#57537;</p>&#57537;</div> <div><p>&amp;#57538;</p>&#57538;</div> <div><p>&amp;#57539;</p>&#57539;</div> <div><p>&amp;#57540;</p>&#57540;</div> <div><p>&amp;#57541;</p>&#57541;</div> <div><p>&amp;#57542;</p>&#57542;</div> <div><p>&amp;#57543;</p>&#57543;</div> <div><p>&amp;#57544;</p>&#57544;</div> <div><p>&amp;#57545;</p>&#57545;</div> <div><p>&amp;#57546;</p>&#57546;</div> <div><p>&amp;#57547;</p>&#57547;</div> <div><p>&amp;#57548;</p>&#57548;</div> <div><p>&amp;#57549;</p>&#57549;</div> <div><p>&amp;#57550;</p>&#57550;</div> <div><p>&amp;#57551;</p>&#57551;</div> <div><p>&amp;#57552;</p>&#57552;</div> <div><p>&amp;#57553;</p>&#57553;</div> <div><p>&amp;#57554;</p>&#57554;</div> <div><p>&amp;#57555;</p>&#57555;</div> <div><p>&amp;#57556;</p>&#57556;</div> <div><p>&amp;#57557;</p>&#57557;</div> <div><p>&amp;#57558;</p>&#57558;</div> <div><p>&amp;#57559;</p>&#57559;</div> <div><p>&amp;#57560;</p>&#57560;</div> <div><p>&amp;#57561;</p>&#57561;</div> <div><p>&amp;#57562;</p>&#57562;</div> <div><p>&amp;#57563;</p>&#57563;</div> <div><p>&amp;#57564;</p>&#57564;</div> <div><p>&amp;#57565;</p>&#57565;</div> <div><p>&amp;#57566;</p>&#57566;</div> <div><p>&amp;#57567;</p>&#57567;</div> <div><p>&amp;#57568;</p>&#57568;</div> <div><p>&amp;#57569;</p>&#57569;</div> <div><p>&amp;#57570;</p>&#57570;</div> <div><p>&amp;#57571;</p>&#57571;</div> <div><p>&amp;#57572;</p>&#57572;</div> <div><p>&amp;#57573;</p>&#57573;</div> <div><p>&amp;#57574;</p>&#57574;</div> <div><p>&amp;#57575;</p>&#57575;</div> <div><p>&amp;#57576;</p>&#57576;</div> <div><p>&amp;#57577;</p>&#57577;</div> <div><p>&amp;#57578;</p>&#57578;</div> <div><p>&amp;#57579;</p>&#57579;</div> <div><p>&amp;#57580;</p>&#57580;</div> <div><p>&amp;#57581;</p>&#57581;</div> <div><p>&amp;#57582;</p>&#57582;</div> <div><p>&amp;#57583;</p>&#57583;</div> <div><p>&amp;#57584;</p>&#57584;</div> <div><p>&amp;#57585;</p>&#57585;</div> <div><p>&amp;#57586;</p>&#57586;</div> <div><p>&amp;#57587;</p>&#57587;</div> <div><p>&amp;#57588;</p>&#57588;</div> <div><p>&amp;#57589;</p>&#57589;</div> <div><p>&amp;#57590;</p>&#57590;</div> <div><p>&amp;#57591;</p>&#57591;</div> <div><p>&amp;#57592;</p>&#57592;</div> <div><p>&amp;#57593;</p>&#57593;</div> <div><p>&amp;#57594;</p>&#57594;</div> <div><p>&amp;#57595;</p>&#57595;</div> <div><p>&amp;#57596;</p>&#57596;</div> <div><p>&amp;#57597;</p>&#57597;</div> <div><p>&amp;#57598;</p>&#57598;</div> <div><p>&amp;#57599;</p>&#57599;</div> <div><p>&amp;#57600;</p>&#57600;</div> <div><p>&amp;#57601;</p>&#57601;</div> <div><p>&amp;#57602;</p>&#57602;</div> <div><p>&amp;#57603;</p>&#57603;</div> <div><p>&amp;#57604;</p>&#57604;</div> <div><p>&amp;#57605;</p>&#57605;</div> <div><p>&amp;#57606;</p>&#57606;</div> <div><p>&amp;#57607;</p>&#57607;</div> <div><p>&amp;#57608;</p>&#57608;</div> <div><p>&amp;#57609;</p>&#57609;</div> <div><p>&amp;#57610;</p>&#57610;</div> <div><p>&amp;#57611;</p>&#57611;</div> <div><p>&amp;#57612;</p>&#57612;</div> <div><p>&amp;#57613;</p>&#57613;</div> <div><p>&amp;#57614;</p>&#57614;</div> <div><p>&amp;#57615;</p>&#57615;</div> <div><p>&amp;#57616;</p>&#57616;</div> <div><p>&amp;#57617;</p>&#57617;</div> <div><p>&amp;#57618;</p>&#57618;</div> <div><p>&amp;#57619;</p>&#57619;</div> <div><p>&amp;#57620;</p>&#57620;</div> <div><p>&amp;#57621;</p>&#57621;</div> <div><p>&amp;#57622;</p>&#57622;</div> <div><p>&amp;#57623;</p>&#57623;</div> <div><p>&amp;#57624;</p>&#57624;</div> <div><p>&amp;#57625;</p>&#57625;</div> <div><p>&amp;#57626;</p>&#57626;</div> <div><p>&amp;#57627;</p>&#57627;</div> <div><p>&amp;#57628;</p>&#57628;</div> <div><p>&amp;#57629;</p>&#57629;</div> <div><p>&amp;#57630;</p>&#57630;</div> <div><p>&amp;#57631;</p>&#57631;</div> <div><p>&amp;#57632;</p>&#57632;</div> <div><p>&amp;#57633;</p>&#57633;</div> <div><p>&amp;#57634;</p>&#57634;</div> <div><p>&amp;#57635;</p>&#57635;</div> <div><p>&amp;#57636;</p>&#57636;</div> <div><p>&amp;#57637;</p>&#57637;</div> <div><p>&amp;#57638;</p>&#57638;</div> <div><p>&amp;#57639;</p>&#57639;</div> <div><p>&amp;#57640;</p>&#57640;</div> <div><p>&amp;#57641;</p>&#57641;</div> <div><p>&amp;#57642;</p>&#57642;</div> <div><p>&amp;#57645;</p>&#57645;</div> <div><p>&amp;#57646;</p>&#57646;</div> <div><p>&amp;#57647;</p>&#57647;</div> <div><p>&amp;#57649;</p>&#57649;</div> <div><p>&amp;#57650;</p>&#57650;</div> <div><p>&amp;#57651;</p>&#57651;</div> <div><p>&amp;#57652;</p>&#57652;</div> <div><p>&amp;#57653;</p>&#57653;</div> <div><p>&amp;#57702;</p>&#57702;</div> <div><p>&amp;#57712;</p>&#57712;</div> <div><p>&amp;#57714;</p>&#57714;</div> <div><p>&amp;#57719;</p>&#57719;</div> <div><p>&amp;#57742;</p>&#57742;</div> <div><p>&amp;#57743;</p>&#57743;</div> <div><p>&amp;#57748;</p>&#57748;</div> <div><p>&amp;#57778;</p>&#57778;</div> <div><p>&amp;#57779;</p>&#57779;</div> <div><p>&amp;#57780;</p>&#57780;</div> <div><p>&amp;#57781;</p>&#57781;</div> <div><p>&amp;#57782;</p>&#57782;</div> <div><p>&amp;#57783;</p>&#57783;</div> <div><p>&amp;#57784;</p>&#57784;</div> <div><p>&amp;#57785;</p>&#57785;</div> <div><p>&amp;#57786;</p>&#57786;</div> <div><p>&amp;#57787;</p>&#57787;</div> <div><p>&amp;#57818;</p>&#57818;</div> <div><p>&amp;#57819;</p>&#57819;</div> <div><p>&amp;#57820;</p>&#57820;</div> <div><p>&amp;#57821;</p>&#57821;</div> <div><p>&amp;#57822;</p>&#57822;</div> <div><p>&amp;#57823;</p>&#57823;</div> <div><p>&amp;#57824;</p>&#57824;</div> <div><p>&amp;#57825;</p>&#57825;</div> <div><p>&amp;#57826;</p>&#57826;</div> <div><p>&amp;#57827;</p>&#57827;</div> <div><p>&amp;#57863;</p>&#57863;</div> <div><p>&amp;#57864;</p>&#57864;</div> <div><p>&amp;#57871;</p>&#57871;</div> <div><p>&amp;#57872;</p>&#57872;</div> <div><p>&amp;#57873;</p>&#57873;</div> <div><p>&amp;#57874;</p>&#57874;</div> <div><p>&amp;#57875;</p>&#57875;</div> <div><p>&amp;#57876;</p>&#57876;</div> <div><p>&amp;#57877;</p>&#57877;</div> <div><p>&amp;#59665;</p>&#59665;</div> <div><p>&amp;#59666;</p>&#59666;</div> <div><p>&amp;#59667;</p>&#59667;</div> <div><p>&amp;#59668;</p>&#59668;</div> <div><p>&amp;#59669;</p>&#59669;</div> <div><p>&amp;#59670;</p>&#59670;</div> <div><p>&amp;#59671;</p>&#59671;</div> <div><p>&amp;#59672;</p>&#59672;</div> <div><p>&amp;#59673;</p>&#59673;</div> <div><p>&amp;#59680;</p>&#59680;</div> <div><p>&amp;#59681;</p>&#59681;</div> <div><p>&amp;#59682;</p>&#59682;</div> <div><p>&amp;#59683;</p>&#59683;</div> <div><p>&amp;#59684;</p>&#59684;</div> <div><p>&amp;#59685;</p>&#59685;</div> <div><p>&amp;#59686;</p>&#59686;</div> <div><p>&amp;#59687;</p>&#59687;</div> <div><p>&amp;#59688;</p>&#59688;</div> <div><p>&amp;#59689;</p>&#59689;</div> <div><p>&amp;#59696;</p>&#59696;</div> <div><p>&amp;#59697;</p>&#59697;</div> <div><p>&amp;#59698;</p>&#59698;</div> <div><p>&amp;#59699;</p>&#59699;</div> <div><p>&amp;#59700;</p>&#59700;</div> <div><p>&amp;#59701;</p>&#59701;</div> <div><p>&amp;#59702;</p>&#59702;</div> <div><p>&amp;#59703;</p>&#59703;</div> <div><p>&amp;#59704;</p>&#59704;</div> <div><p>&amp;#59705;</p>&#59705;</div> <div><p>&amp;#59712;</p>&#59712;</div> <div><p>&amp;#59713;</p>&#59713;</div> <div><p>&amp;#59714;</p>&#59714;</div> <div><p>&amp;#59716;</p>&#59716;</div> <div><p>&amp;#59717;</p>&#59717;</div> <div><p>&amp;#59718;</p>&#59718;</div> <div><p>&amp;#59719;</p>&#59719;</div> <div><p>&amp;#59720;</p>&#59720;</div> <div><p>&amp;#59721;</p>&#59721;</div> <div><p>&amp;#59728;</p>&#59728;</div> <div><p>&amp;#59729;</p>&#59729;</div> <div><p>&amp;#59730;</p>&#59730;</div> <div><p>&amp;#59732;</p>&#59732;</div> <div><p>&amp;#59733;</p>&#59733;</div> <div><p>&amp;#59734;</p>&#59734;</div> <div><p>&amp;#59735;</p>&#59735;</div> <div><p>&amp;#59736;</p>&#59736;</div> <div><p>&amp;#59737;</p>&#59737;</div> <div><p>&amp;#59745;</p>&#59745;</div> <div><p>&amp;#59746;</p>&#59746;</div> <div><p>&amp;#59747;</p>&#59747;</div> <div><p>&amp;#59748;</p>&#59748;</div> <div><p>&amp;#59749;</p>&#59749;</div> <div><p>&amp;#59750;</p>&#59750;</div> <div><p>&amp;#59751;</p>&#59751;</div> <div><p>&amp;#59752;</p>&#59752;</div> <div><p>&amp;#59753;</p>&#59753;</div> <div><p>&amp;#59761;</p>&#59761;</div> <div><p>&amp;#59763;</p>&#59763;</div> <div><p>&amp;#59765;</p>&#59765;</div> <div><p>&amp;#59766;</p>&#59766;</div> <div><p>&amp;#59767;</p>&#59767;</div> <div><p>&amp;#59768;</p>&#59768;</div> <div><p>&amp;#59769;</p>&#59769;</div> <div><p>&amp;#59779;</p>&#59779;</div> <div><p>&amp;#59780;</p>&#59780;</div> <div><p>&amp;#59781;</p>&#59781;</div> <div><p>&amp;#59782;</p>&#59782;</div> <div><p>&amp;#59783;</p>&#59783;</div> <div><p>&amp;#59784;</p>&#59784;</div> <div><p>&amp;#59785;</p>&#59785;</div> <div><p>&amp;#59792;</p>&#59792;</div> <div><p>&amp;#59793;</p>&#59793;</div> <div><p>&amp;#59794;</p>&#59794;</div> <div><p>&amp;#59795;</p>&#59795;</div> <div><p>&amp;#59796;</p>&#59796;</div> <div><p>&amp;#59797;</p>&#59797;</div> <div><p>&amp;#59798;</p>&#59798;</div> <div><p>&amp;#59801;</p>&#59801;</div> <div><p>&amp;#61421;</p>&#61421;</div> <div><p>&amp;#61422;</p>&#61422;</div> <div><p>&amp;#61425;</p>&#61425;</div> <div><p>&amp;#61426;</p>&#61426;</div> <div><p>&amp;#61427;</p>&#61427;</div> <div><p>&amp;#61429;</p>&#61429;</div> <div><p>&amp;#61431;</p>&#61431;</div> <div><p>&amp;#61696;</p>&#61696;</div> <div><p>&amp;#61697;</p>&#61697;</div> <div><p>&amp;#61698;</p>&#61698;</div> <div><p>&amp;#61699;</p>&#61699;</div> <div><p>&amp;#61700;</p>&#61700;</div> <div><p>&amp;#61701;</p>&#61701;</div> <div><p>&amp;#61702;</p>&#61702;</div> <div><p>&amp;#61703;</p>&#61703;</div> <div><p>&amp;#61704;</p>&#61704;</div> <div><p>&amp;#61705;</p>&#61705;</div> <div><p>&amp;#61712;</p>&#61712;</div> <div><p>&amp;#61713;</p>&#61713;</div> <div><p>&amp;#61714;</p>&#61714;</div> <div><p>&amp;#61715;</p>&#61715;</div> <div><p>&amp;#61716;</p>&#61716;</div> <div><p>&amp;#61717;</p>&#61717;</div> <div><p>&amp;#61718;</p>&#61718;</div> <div><p>&amp;#61719;</p>&#61719;</div> <div><p>&amp;#61720;</p>&#61720;</div> <div><p>&amp;#61721;</p>&#61721;</div> <div><p>&amp;#61728;</p>&#61728;</div> <div><p>&amp;#61729;</p>&#61729;</div> <div><p>&amp;#61730;</p>&#61730;</div> <div><p>&amp;#61731;</p>&#61731;</div> <div><p>&amp;#61732;</p>&#61732;</div> <div><p>&amp;#61733;</p>&#61733;</div> <div><p>&amp;#61734;</p>&#61734;</div> <div><p>&amp;#61735;</p>&#61735;</div> <div><p>&amp;#61736;</p>&#61736;</div> <div><p>&amp;#61737;</p>&#61737;</div> <div><p>&amp;#61744;</p>&#61744;</div> <div><p>&amp;#61745;</p>&#61745;</div> <div><p>&amp;#61746;</p>&#61746;</div> <div><p>&amp;#61747;</p>&#61747;</div> <div><p>&amp;#61748;</p>&#61748;</div> <div><p>&amp;#61749;</p>&#61749;</div> <div><p>&amp;#61750;</p>&#61750;</div> <div><p>&amp;#61751;</p>&#61751;</div> <div><p>&amp;#61752;</p>&#61752;</div> <div><p>&amp;#61753;</p>&#61753;</div> <div><p>&amp;#63020;</p>&#63020;</div> <div><p>&amp;#63021;</p>&#63021;</div> <div><p>&amp;#63025;</p>&#63025;</div> <div><p>&amp;#63026;</p>&#63026;</div> <div><p>&amp;#63027;</p>&#63027;</div> <div><p>&amp;#63031;</p>&#63031;</div> <div><p>&amp;#63033;</p>&#63033;</div> <div><p>&amp;#63034;</p>&#63034;</div> <div><p>&amp;#63035;</p>&#63035;</div> <div><p>&amp;#63036;</p>&#63036;</div> <div><p>&amp;#63037;</p>&#63037;</div> <div><p>&amp;#63038;</p>&#63038;</div> <div><p>&amp;#63039;</p>&#63039;</div> <div><p>&amp;#63040;</p>&#63040;</div> <div><p>&amp;#63041;</p>&#63041;</div> <div><p>&amp;#63061;</p>&#63061;</div> <div><p>&amp;#63062;</p>&#63062;</div> <div><p>&amp;#63063;</p>&#63063;</div> <div><p>&amp;#63064;</p>&#63064;</div> <div><p>&amp;#63065;</p>&#63065;</div> <div><p>&amp;#63066;</p>&#63066;</div> <div><p>&amp;#63067;</p>&#63067;</div> <div><p>&amp;#63068;</p>&#63068;</div> <div><p>&amp;#63069;</p>&#63069;</div> <div><p>&amp;#63070;</p>&#63070;</div> <div><p>&amp;#63071;</p>&#63071;</div> <div><p>&amp;#63072;</p>&#63072;</div> <div><p>&amp;#63073;</p>&#63073;</div> <div><p>&amp;#63074;</p>&#63074;</div> <div><p>&amp;#63075;</p>&#63075;</div> <div><p>&amp;#63076;</p>&#63076;</div> <div><p>&amp;#63077;</p>&#63077;</div> <div><p>&amp;#63078;</p>&#63078;</div> <div><p>&amp;#63079;</p>&#63079;</div> <div><p>&amp;#63080;</p>&#63080;</div> <div><p>&amp;#63081;</p>&#63081;</div> <div><p>&amp;#63082;</p>&#63082;</div> <div><p>&amp;#63083;</p>&#63083;</div> <div><p>&amp;#63084;</p>&#63084;</div> <div><p>&amp;#63150;</p>&#63150;</div> <div><p>&amp;#63151;</p>&#63151;</div> <div><p>&amp;#63152;</p>&#63152;</div> <div><p>&amp;#63153;</p>&#63153;</div> <div><p>&amp;#63154;</p>&#63154;</div> <div><p>&amp;#63155;</p>&#63155;</div> <div><p>&amp;#63156;</p>&#63156;</div> <div><p>&amp;#63157;</p>&#63157;</div> <div><p>&amp;#63158;</p>&#63158;</div> <div><p>&amp;#63159;</p>&#63159;</div> <div><p>&amp;#63160;</p>&#63160;</div> <div><p>&amp;#63161;</p>&#63161;</div> <div><p>&amp;#63162;</p>&#63162;</div> <div><p>&amp;#63163;</p>&#63163;</div> <div><p>&amp;#63164;</p>&#63164;</div> <div><p>&amp;#63165;</p>&#63165;</div> <div><p>&amp;#63171;</p>&#63171;</div> <div><p>&amp;#63177;</p>&#63177;</div> <div><p>&amp;#63178;</p>&#63178;</div> <div><p>&amp;#63179;</p>&#63179;</div> <div><p>&amp;#63182;</p>&#63182;</div> <div><p>&amp;#63183;</p>&#63183;</div> <div><p>&amp;#63184;</p>&#63184;</div> <div><p>&amp;#63196;</p>&#63196;</div> <div><p>&amp;#63201;</p>&#63201;</div> <div><p>&amp;#63202;</p>&#63202;</div> <div><p>&amp;#63207;</p>&#63207;</div> <div><p>&amp;#63208;</p>&#63208;</div> <div><p>&amp;#63210;</p>&#63210;</div> <div><p>&amp;#63211;</p>&#63211;</div> <div><p>&amp;#63212;</p>&#63212;</div> <div><p>&amp;#63213;</p>&#63213;</div> <div><p>&amp;#63214;</p>&#63214;</div> <div><p>&amp;#63215;</p>&#63215;</div> <div><p>&amp;#63217;</p>&#63217;</div> <div><p>&amp;#63218;</p>&#63218;</div> <div><p>&amp;#63219;</p>&#63219;</div> <div><p>&amp;#63270;</p>&#63270;</div> <div><p>&amp;#63393;</p>&#63393;</div> <div><p>&amp;#63423;</p>&#63423;</div> <div><p>&amp;#64256;</p>&#64256;</div> <div><p>&amp;#64257;</p>&#64257;</div> <div><p>&amp;#64258;</p>&#64258;</div> <div><p>&amp;#64259;</p>&#64259;</div> <div><p>&amp;#64260;</p>&#64260;</div> <div><p>&amp;#64262;</p>&#64262;</div> </div> </div> </div> </div> <div id="specs"> </div> <div id="installing"> <div class="section"> <div class="grid7 firstcol"> <h1>Installing Webfonts</h1> <p>Webfonts are supported by all major browser platforms but not all in the same way. There are currently four different font formats that must be included in order to target all browsers. This includes TTF, WOFF, EOT and SVG.</p> <h2>1. Upload your webfonts</h2> <p>You must upload your webfont kit to your website. They should be in or near the same directory as your CSS files.</p> <h2>2. Include the webfont stylesheet</h2> <p>A special CSS @font-face declaration helps the various browsers select the appropriate font it needs without causing you a bunch of headaches. Learn more about this syntax by reading the <a href="http://www.fontspring.com/blog/further-hardening-of-the-bulletproof-syntax">Fontspring blog post</a> about it. The code for it is as follows:</p> <code> @font-face{ font-family: 'MyWebFont'; src: url('WebFont.eot'); src: url('WebFont.eot?#iefix') format('embedded-opentype'), url('WebFont.woff') format('woff'), url('WebFont.ttf') format('truetype'), url('WebFont.svg#webfont') format('svg'); } </code> <p>We've already gone ahead and generated the code for you. All you have to do is link to the stylesheet in your HTML, like this:</p> <code>&lt;link rel=&quot;stylesheet&quot; href=&quot;stylesheet.css&quot; type=&quot;text/css&quot; charset=&quot;utf-8&quot; /&gt;</code> <h2>3. Modify your own stylesheet</h2> <p>To take advantage of your new fonts, you must tell your stylesheet to use them. Look at the original @font-face declaration above and find the property called "font-family." The name linked there will be what you use to reference the font. Prepend that webfont name to the font stack in the "font-family" property, inside the selector you want to change. For example:</p> <code>p { font-family: 'WebFont', Arial, sans-serif; }</code> <h2>4. Test</h2> <p>Getting webfonts to work cross-browser <em>can</em> be tricky. Use the information in the sidebar to help you if you find that fonts aren't loading in a particular browser.</p> </div> <div class="grid5 sidebar"> <div class="box"> <h2>Troubleshooting<br />Font-Face Problems</h2> <p>Having trouble getting your webfonts to load in your new website? Here are some tips to sort out what might be the problem.</p> <h3>Fonts not showing in any browser</h3> <p>This sounds like you need to work on the plumbing. You either did not upload the fonts to the correct directory, or you did not link the fonts properly in the CSS. If you've confirmed that all this is correct and you still have a problem, take a look at your .htaccess file and see if requests are getting intercepted.</p> <h3>Fonts not loading in iPhone or iPad</h3> <p>The most common problem here is that you are serving the fonts from an IIS server. IIS refuses to serve files that have unknown MIME types. If that is the case, you must set the MIME type for SVG to "image/svg+xml" in the server settings. Follow these instructions from Microsoft if you need help.</p> <h3>Fonts not loading in Firefox</h3> <p>The primary reason for this failure? You are still using a version Firefox older than 3.5. So upgrade already! If that isn't it, then you are very likely serving fonts from a different domain. Firefox requires that all font assets be served from the same domain. Lastly it is possible that you need to add WOFF to your list of MIME types (if you are serving via IIS.)</p> <h3>Fonts not loading in IE</h3> <p>Are you looking at Internet Explorer on an actual Windows machine or are you cheating by using a service like Adobe BrowserLab? Many of these screenshot services do not render @font-face for IE. Best to test it on a real machine.</p> <h3>Fonts not loading in IE9</h3> <p>IE9, like Firefox, requires that fonts be served from the same domain as the website. Make sure that is the case.</p> </div> </div> </div> </div> </div> <div id="footer"> <p>&copy;2010-2011 Font Squirrel. All rights reserved.</p> </div> </div> </body> </html> <file_sep>module Bourbon end require_relative "bourbon/sass_extensions" <file_sep>module Bourbon::SassExtensions::Functions end require_relative "functions/compact" module Sass::Script::Functions include Bourbon::SassExtensions::Functions::Compact end # Wierd that this has to be re-included to pick up sub-modules. Ruby bug? class Sass::Script::Functions::EvaluationContext include Sass::Script::Functions end <file_sep>module Bourbon::SassExtensions end require_relative "sass_extensions/functions"
42cfdad46a86483e7b1e2a6bcf542ad0185636d6
[ "Ruby", "HTML" ]
4
HTML
frechg/Analytics-Dashboard
df9a39582d0fd4373310753968c669a42af7c104
7d2f6e1b88a8903e00e26e2f34a723185c7cfb77
refs/heads/main
<repo_name>Shengyuan-Lu/Parstagram<file_sep>/README.md # Parstagram Parstagram is an Instagram clone with a custom Parse backend that allows a user to post photos and view a global photos feed. ## Part 1 User Stories The following functionality is completed: - [X] User sees app icon in home screen and styled launch screen. - [X] User can sign up to create a new account. - [X] User can log in. - [X] User can take a photo, add a caption, and post it to the server. - [X] User can view the last 20 posts. ### Video Walkthrough Here's a walkthrough of implemented user stories: <img src="https://i.imgur.com/iCs3gAU.gif" width=750 /> ## Part 2 User Stories The following functionality is completed: - [x] User stays logged in across restarts. - [x] User can log out. - [x] User can view comments on a post. - [x] User can add a new comment. ### Video Walkthrough Here's a walkthrough of implemented user stories: <img src="https://i.imgur.com/SSAHMBn.gif" width=750 /> <file_sep>/Parstagram/View Controllers/LoginViewController.swift // // LoginViewController.swift // Parstagram // // Created by <NAME> on 2/7/21. // import UIKit import Parse class LoginViewController: UIViewController { @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var passwordField: UITextField! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) usernameField.text?.removeAll() passwordField.text?.removeAll() } @IBAction func loginButtonTapped(_ sender: UIButton) { let username = usernameField.text ?? "" let password = passwordField.text ?? "" PFUser.logInWithUsername(inBackground: username, password: password) { (user, error) in if user != nil { self.performSegue(withIdentifier: "toFeedScreen", sender: nil) } else { print("ERROR: Invlid username or password") } } } @IBAction func onTap(_ sender: Any) { view.endEditing(true) } @IBAction func signupButtonTapped(_ sender: Any) { let user = PFUser() user.username = usernameField.text ?? "" user.password = <PASSWORD>Field.text ?? "" user.signUpInBackground { (success, error) in if success { self.performSegue(withIdentifier: "toFeedScreen", sender: nil) } else { print("ERROR: \(error?.localizedDescription ?? "Unknown Error")") } } } }
37fe2929367ef88092b99faf27ecc1289afcbcea
[ "Markdown", "Swift" ]
2
Markdown
Shengyuan-Lu/Parstagram
1fcea67690070376457f71d332508c1eba3fbb4e
747d9ef6dad5220b48360d2eb2ade53b13dab9f3
refs/heads/master
<file_sep># react-tutorial 学习react, 做点笔记<file_sep>import React, {Component} from 'react'; import { render } from 'react-dom'; import Game from './Game'; render( <Game />, document.getElementById('root') );
adf4f263b5936f7c81a607bc58cf2c4379b640cb
[ "Markdown", "JavaScript" ]
2
Markdown
bluewaitor/react-tutorial
d5c4ec5e1d01f35c76ab940951c9b12f17887574
a579f92f45bc7669f2954f30cd08e31ac7dc1c44
refs/heads/master
<file_sep>## # Bash utilities : rename it as .bash_profile on your user's root folder ## # fonction md : mkdir + cd md() { mkdir -p -- "$1" && cd -P -- "$1" } # Set Proxy function setproxy() { export PROXY=http://10.154.61.3:3128 export {http,https,ftp}_proxy=$PROXY export {HTTP,HTTPS,FTP}_PROXY=$PROXY # git git config --global http.proxy $PROXY git config --global https.proxy $PROXY # npm npm config set proxy $PROXY # gradle if [ -f ~/.gradle/gradle.archive.properties ]; then mv ~/.gradle/gradle.archive.properties ~/.gradle/gradle.properties fi } # Set Proxy (configuration à l'identique des smartphones) function setproxysmart() { export PROXY=http://10.156.242.218:8080 export {http,https,ftp}_proxy=$PROXY export {HTTP,HTTPS,FTP}_PROXY=$PROXY # git git config --global http.proxy $PROXY git config --global https.proxy $PROXY # npm npm config set proxy $PROXY # utile éventuellement quand on est en mode setproxysmart pour ne pas toujours passer par le proxy d'IA export no_proxy="localhost,127.0.0.1,10.75.204.14" } # Unset Proxy function unsetproxy() { unset {http,https,ftp}_proxy unset {HTTP,HTTPS,FTP}_PROXY unset {ALL,_}PROXY unset PROXY unset no_proxy # git git config --global --unset http.proxy git config --global --unset https.proxy # npm npm config delete proxy # gradle if [ -f ~/.gradle/gradle.properties ]; then mv ~/.gradle/gradle.properties ~/.gradle/gradle.archive.properties fi } function showproxy() { echo "Affichage des paramètres proxy du poste de développement" echo "--------------------------------------------------------" env | grep PROXY env | grep proxy echo "git http.proxy :" $(git config --global --get http.proxy) echo "git https.proxy :" $(git config --global --get https.proxy) echo "npm proxy :" $(npm config get proxy) if [ -f ~/.gradle/gradle.properties ]; then echo "gradle proxy" echo "------------" cat ~/.gradle/gradle.properties else echo "gradle proxy (pas de fichier gradle.properties trouvé)" fi } # Ouvrir dans XCode le fichier avec l'extension xcworkspace function openxcw() { FILE=$(find ./platforms/ios -name "*.xcworkspace") echo "Ouverture de $FILE" open $FILE } export JAVA_HOME=$(/usr/libexec/java_home) export ANDROID_HOME="/Users/pomauguet/Library/Android/sdk" export ANDROID_SDK_ROOT=$ANDROID_HOME export PATH=${PATH}:${ANDROID_HOME}/platform-tools:${ANDROID_HOME}/tools/bin export PATH=${PATH}:/Users/pomauguet/scripts # ajout couleurs au shell export PS1="\[\033[36m\]\u\[\033[m\]@\[\033[32m\]\h:\[\033[33;1m\]\w\[\033[m\]\$ " export CLICOLOR=1 export LSCOLORS=ExFxBxDxCxegedabagacad export LAB="/Users/pomauguet/lab" # alias alias ls='ls -GFh' alias ll="ls -al" alias ..="cd .." alias ...=".. && .."
f98661254efe3a9bc7ba4f5ec15f7de1ef4badb3
[ "Shell" ]
1
Shell
pom421/bash-utilities
9bf94aab92066593fda138521740744ce302b1f4
107eb52161043d85bd665cef36a56f413f679916
refs/heads/master
<file_sep> def process_and_count(filename): with open(filename, "r") as f: content = f.readlines() count = 0 length = 0 for item in content: r, s, o, _ = item.strip().split('\t') length += len(o.split(" ")) count += 1 return length / count filename = "gpt2-test.txt" print(process_and_count(filename)) filename = "test_epoch10000.txt" print(process_and_count(filename)) filename = "test_conceptnet_model_checkpoint-10000.txt" print(process_and_count(filename)) filename = "test_conceptnet_model_pretrain_full_15epoch.txt" print(process_and_count(filename)) import os import sys import pickle import argparse sys.path.append(os.getcwd()) import src.data.conceptnet as cdata combine_into_words = {j:i for i, j in cdata.split_into_words.items()} parser = argparse.ArgumentParser() parser.add_argument("--gens_name", type=str, default="results/gens/conceptnet-generation/iteration-500-100000/transformer/rel_language-trainsize_100-devversion_12-maxe1_10-maxe2_15/model_transformer-nL_12-nH_12-hSize_768-edpt_0.1-adpt_0.1-rdpt_0.1-odpt_0.1-pt_gpt-afn_gelu-init_pt-vSize_40545/exp_generation-seed_123-l2_0.01-vl2_T-lrsched_warmup_linear-lrwarm_0.002-clip_1-loss_nll-b2_0.999-b1_0.9-e_1e-08/bs_1-smax_40-sample_greedy-numseq_1-gs_full-es_full/1e-05_adam_64_15500/test.txt") parser.add_argument("--training_set_file", type=str, default="data/concepnet/train100k.txt") args = parser.parse_args() gens = [i.split("\t")[:3] for i in open(args.gens_name, "r").read().split("\n") if i] training_gens = [i.split("\t")[:3] for i in open(args.training_set_file, "r").read().split("\n") if i] evaluation_rels = set([tuple([j.strip() for j in i]) for i in gens]) evaluation_e2s = set([i[2].strip() for i in gens]) train_rels = set([tuple([j.strip() for j in i]) for i in training_gens]) train_e2s = set([i[2].strip() for i in training_gens]) for item in evaluation_rels: if item not in train_rels: print(item[1],item[0], item[2], int(item[1] in train_e2s),int(item[2] in train_e2s)) print("% new o: {}".format(len([i for i in evaluation_e2s if i not in train_e2s]) / len(evaluation_rels))) print("% new sro: {}".format(len([i for i in evaluation_rels if i not in train_rels]) / len(evaluation_rels))) <file_sep> ## Language model training Modified from [HuggingFace's implementation](https://github.com/huggingface/transformers/tree/master/examples/language-modeling). <file_sep># GPT2-commonsense ## Requirements To install requirements (make sure conda is installed) ```setup bash dependencies.bash ``` ## ConceptNet Experiments: ### Training: To use the default setting: ``` cd language-modeling/ bash train_script.py ``` The model parameters will be saved in `./language-modeling/model_conceptnet/pytorch_model.bin` To use customized training setting, please run: ``` python run_language_modeling.py --output_dir=<model_name> --model_type=gpt2 --model_name_or_path=<"gpt2" or path_to_pretrained_model> --do_train --train_data_file=train100k_processed.txt --do_eval --eval_data_file=test_processed.txt --line_by_line --learning_rate 1e-5 --num_train_epochs=5 --overwrite_output_dir --save_steps 5000 --evaluate_during_training ``` ### Generation: To use the defaut generation setting: ``` cd language-modeling/ bash generation_script.bash ``` The generation results will be saved in `./language-modeling/results/test_model_conceptnet.txt` To use customized generation setting, please run: ``` python generation_script.py --model_type gpt2 --model_name_or_path <path_to_saved_model> --length 100 --stop_token "<EOS>" --k 1 --num_return_sequences 1 --test_dir test_prompt.txt --output_dir results/<name_of_generation_file> ``` ## Evaluation First we need to preprocess the raw GPT-2 generation: ``` python evaluate/preprocess.py --gens_name /path/to/generations_file/ ``` Then, we get the raw Conceptnet data: ``` bash get_conceptnet_data.sh ``` To run the classifier from Li et al., 2016 on your generated tuples to evaluate correctness, first download the pretrained model from: ``` wget https://ttic.uchicago.edu/~kgimpel/comsense_resources/ckbc-demo.tar.gz tar -xvzf ckbc-demo.tar.gz ``` then run the following code on the the generations file ``` python2.7 evaluate/classify_conceptnet_generations.py --gens_name /path/to/generations_file/ ``` To get the novelty metrics `N/T sro` and `N/T o`: ``` python evaluate/compare.py --training_set_file data/conceptnet/train100k.txt --gens_name /path/to/generations_file/ ``` ### Results Comparing to [COMeT](https://github.com/atcbosselut/comet-commonsense) | Method \ Metrics | PPL | AVG Score | N/T sro | N/T o | |--------| -------- | -------- | -------- | ------- | |COMeT | 4.32 | 95.25 | 59.25 | 3.75 | |GPT-2 | **1.83** | 72.87 | 53.90 | **8.18**| |GPT-2-pretrain| 4.40|73.64|**88.75**|**16.6**| <file_sep>import pickle import argparse result_dir = "/Users/fischer/UCSD/XPTLab/GPT2-commonsense/language-modeling/results/" rel_map = {'hasproperty': 'HasProperty', 'capableof': 'CapableOf', 'haspainintensity': 'HasPainIntensity', 'causesdesire': 'CausesDesire', 'notdesires': 'NotDesires', 'symbolof': 'SymbolOf', 'usedfor': 'UsedFor', 'atlocation': 'AtLocation', 'hasfirstsubevent': 'HasFirstSubevent', 'causes': 'Causes', 'locatednear': 'LocatedNear', 'motivatedbygoal': 'MotivatedByGoal', 'locationofaction': 'LocationofAction', 'hassubevent': 'HasSubevent', 'relatedto': 'RelatedTo', 'madeof': 'MadeOf', 'partof': 'PartOf', 'createdby': 'CreatedBy', 'desireof': 'DesireOf', 'inheritsfrom': 'InheritsFrom', 'notisa': 'NotIsA', 'desires': 'Desires', 'nothasproperty': 'NotHasProperty', 'hasa': 'HasA', 'notcapableof': 'NotCapableOf', 'haslastsubevent': 'HasLastSubevent', 'definedas': 'DefinedAs', 'instanceof': 'InstanceOf', 'nothasa': 'NotHasA', 'hasprerequisite': 'HasPrerequisite', 'receivesaction': 'ReceivesAction', 'haspaincharacter': 'HasPainCharacter', 'notmadeof': 'NotMadeOf', 'isa': 'IsA', 'haveprerequisite':'HasPrerequisite'} parser = argparse.ArgumentParser() parser.add_argument("--gens_name", type=str, default="../language-modeling/results/test_conceptnet_model.txt") args = parser.parse_args() with open(args.gens_name, "r") as f: raw_text = f.readlines() output = [] with open(args.gens_name, "w") as f: for i, item in enumerate(raw_text): split_item = item.split(" <MASK> ") s,o = split_item[0], split_item[-1].strip() r = split_item[-2].strip().replace("<MASK> ", "").replace(" ", "") if r not in rel_map.keys(): print(item) continue f.write(rel_map[r] + "\t" + s + "\t" + o + "\t" + "1" + "\n" ) <file_sep>conda install pytorch torchvision cudatoolkit=10.2 -c pytorch pip install tensorboard cd ../transformers pip install .
a6206a68a033f26a509478f91d86233d31bc6b90
[ "Markdown", "Python", "Shell" ]
5
Python
Fischer19/GPT2-commonsense
fd7f8b38526c67cf93c086ce95d31daa1e42378b
989c3346283a09218e9726729c5796227dee2407
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ParseText { public partial class frmMain : Form { string _pathToFile = string.Empty; public frmMain() { InitializeComponent(); } private void cmdSelectFile_Click(object sender, EventArgs e) { dlgFilePicker.ShowDialog(this); if (dlgFilePicker.CheckFileExists) { _pathToFile = dlgFilePicker.FileName; txtFileName.Text = System.IO.Path.GetFileNameWithoutExtension(_pathToFile); cmdParseFile.Enabled = true; } else { cmdParseFile.Enabled = false; MessageBox.Show(this, "File not Found.", "Error"); } } } }
526925df487e038760617fcf50b6c2c5b76ae818
[ "C#" ]
1
C#
rosco-y/ParseText
f738eb214f65f2989dad44ba57c7e99eb2d6ef47
f10765754b940af7a082d14995b527aa168337ed
refs/heads/master
<file_sep>from django.db import models # Create your models here. class Product(models.Model): asin = models.CharField(max_length=255, primary_key=True) product_id = models.IntegerField(null=True) title = models.TextField(null=True) product_type_name = models.TextField(null=True) brand = models.TextField(null=True) color = models.TextField(null=True) formatted_price = models.TextField(null=True) small_image_url = models.TextField(null=True) medium_image_url = models.TextField(null=True) large_image_url = models.TextField(null=True) <file_sep>from django.shortcuts import render, redirect from . import models from ml import model def redirect_view(request): return redirect('/pageno=1') def homepage(request, pageno='1'): page_size = 15 start_index = page_size * pageno end_index = start_index + page_size pagination_start = pageno if pageno < 9 else pageno - 7 pagination_end = pageno + 7; products = models.Product.objects.all()[start_index:end_index] product_count = models.Product.objects.all().count() return render(request, "index.html", {"products": products, "currentpage": pageno, "endpage": pagination_end -1 , "startpage": pagination_start, "currentpage": pageno, "pages": list(range(pagination_start, pagination_end))}) def productpage(request, id): product = models.Product.objects.get(pk=id) suggestions_ids = model.bag_of_words(product.product_id, 6) suggestions_bow = models.Product.objects.filter(product_id__in=suggestions_ids[1:]) suggestions_ids = model.avg_w2v_model(product.product_id, 6) suggestions_w2v = models.Product.objects.filter(product_id__in=suggestions_ids[1:]) print(suggestions_w2v) return render(request, "product.html", {"product": product, "suggestions_bow": suggestions_bow, "suggestions_w2v": suggestions_w2v}) <file_sep>import pandas as pd from sklearn.metrics import pairwise_distances import numpy as np import pickle import os def bag_of_words(doc_id, num_results): dir_path = os.path.dirname(os.path.realpath(__file__)) data = pd.read_csv(dir_path + "\\data.csv") with open(dir_path + '\\title_features.pickle', 'rb') as file: title_features = pickle.load(file) pairwise_dist = pairwise_distances(title_features, title_features[doc_id]) indices = np.argsort(pairwise_dist.flatten())[0:num_results] return indices def avg_w2v_model(doc_id, num_results): dir_path = os.path.dirname(os.path.realpath(__file__)) data = pd.read_csv(dir_path + "\\data.csv") with open(dir_path + '\\arr.npy', 'rb') as file: w2v_title = np.load(file) pairwise_dist = pairwise_distances(w2v_title, w2v_title[doc_id].reshape(1, -1)) indices = np.argsort(pairwise_dist.flatten())[0:num_results] df_indices = list(data.index[indices]) return df_indices
c8be348e1431439dc7deda719a785d1b7286693d
[ "Python" ]
3
Python
Kedar0572/product-recommandation
a6062346b7d1cdfa3c56b730d91ff8c3d9d73151
38265c7c4929e717fc525511b68ca85589882255
refs/heads/master
<file_sep><!doctype html> <html lang='en'> <head> <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet"> <link rel='stylesheet' href="{{url_for('static',filename='styling.css')}}"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <title>Lounge</title> <body> <div class="header"> <a href="/"><img src="/static/logo.jpg" alt="Lounge Logo"></a> <ul> <li><a href="/">Home</a></li> <li><a href="/messages">Messages</a></li> <li><a href="/approved">Events</a></li> <li><a href="/donate">Donate</a></li> <li><a href="/feedback">Feedback</a></li> </ul> </div> <!--display all flashed messages--> {% with messages = get_flashed_messages() %} {% if messages %} <div id="messages"> {% for message in messages %} <p>{{ message }}</p> {% endfor %} </div> {% endif %} {% endwith %} {% block content %} <h1>Welcome!</h1> <html> <body> <p>Log in! <form action="/setUID/" method="POST"> <input type="text" name="uid" placeholder="username"> </form> </p> <p>Check out our pages! <a href="/">Home</a> <a href="/createAccount/">Create a profile</a> <a href="/approved/">Events</a> <a href="/messages/">Messages</a> </p> </body> Lounge is a Whiptail database where current members and alumnae of the Wellesley ultimate frisbee team can more easily connect for fundraising, networking, and socializing. {% endblock %} </html> <file_sep>import sys import MySQLdb # ================================================================ ''' Search for members in the database by name, nickname, classyear and industry ''' def search (curs, search_items): '''Searches for profiles by name, nickname and class year''' # adds nickname to the query if name is in there if "name" in search_items[0]: items = [search_items[1][0]] +list(search_items[1]) name = ['(name like %s or nickname like %s)'] compares =' and '.join(name+[ ' {col} like %s '.format(col=c) \ for c in search_items[0][1:]]) else: items = search_items[1] compares = ' and '.join([ ' {col} like %s '.format(col=c) \ for c in search_items[0]]) #sees if an industry is in the query if "iname" in compares: curs.execute('''select user.username, user.name, user.nickname, user.classyear from user inner join industry on username=pid where ''' + compares, items) else: curs.execute('''select username, name, nickname, classyear from user where ''' + compares, items) return curs.fetchall() <file_sep># <NAME> import sys import MySQLdb # ================================================================ # return the connection to MySQLdb for particular user def getConn(db): conn = MySQLdb.connect(host='localhost', user='rianntang', passwd='', db=db) conn.autocommit(True) return conn def getEvents(conn, approved): curs = conn.cursor(MySQLdb.cursors.DictCursor) curs.execute('''select * from events where approved = %s order by edate asc''', (approved,)) return curs.fetchall() def checkEvent(conn, name, date): curs = conn.cursor(MySQLdb.cursors.DictCursor) curs.execute('''select count(*) as count from events where ename = %s and edate = %s''', (name, date,)) row = curs.fetchone() return row['count'] > 0 def submitEvent(conn, name, city, state, country, desc, date): curs = conn.cursor(MySQLdb.cursors.DictCursor) curs.execute('''insert into events(ename, city, state, country, description, edate, approved) values(%s, %s, %s, %s, %s, %s, 0)''', (name, city, state, country, desc, date,)) def approveEvent(conn, name, date): curs = conn.cursor(MySQLdb.cursors.DictCursor) curs.execute('''update events set approved = 1 where ename = %s and edate = %s''', (name, date,)) def deleteEvent(conn, name, date): curs = conn.cursor(MySQLdb.cursors.DictCursor) curs.execute('''delete from events where ename = %s and edate = %s''', (name, date,)) # ================================================================ if __name__ == '__main__': conn = getConn('wmdb') <file_sep># <NAME> import sys import MySQLdb # ================================================================ def getFamily(curs, searchterm): names_dict = findFamily(curs, searchterm) names = [name['name'] for name in names_dict] wildcard = tuple(names) curs.execute('''select family.name, user.name as uname, user.classyear from family inner join user on family.predecessor = user.username or family.member = user.username having family.name in %s order by user.classyear''', (wildcard,)) return curs.fetchall() # need to inner join to search user name instead of username def findFamily(curs, name): key = '%' + name + '%' # format the wildcard for sql search curs.execute('''select family.name, user.name from family inner join user on family.predecessor = user.username or family.member = user.username where user.name like %s''', (key,)) return curs.fetchall()<file_sep># <NAME> import sys import MySQLdb # ================================================================ def checkPerson(curs, uname): curs.execute('''select * from user where username=%s''', (uname,)) return curs.fetchone def getSecurityPrefs(curs, uname): """Returns the security preferences of given user""" curs.execute('''select sprefs from user where username=%s''', (uname, )) return curs.fetchone() def getBasicInfo(curs, uname): """Return the name, nickname and classyear of given user""" curs.execute('''select username, name, nickname, classyear from user where username=%s''', (uname, )) return curs.fetchone() def getIndustry(curs, uname): """Return the industry type of the given user""" curs.execute('''select iname from industry where pid=%s''', (uname, )) return curs.fetchone() def getTeam(curs, uname): """Return the team name, type, city, state and country of given user""" curs.execute('''select tname, nearestcity, state, country from team where pid=%s''', (uname, )) return curs.fetchone() def getContactInfo(curs, uname): """Return the email and phone number of given user""" curs.execute('''select email, phnum from user where username=%s''', (uname, )) return curs.fetchone() def getYear(curs, uname): """Return the classyear of given user""" curs.execute('''select classyear from user where username=%s''', (uname, )) return curs.fetchone() def getOverlap(curs, uname1, uname2): """Return 1 if there is an overlap in time at Wellesley, 0 if not""" olap = 0 year1 = int(getYear(curs, uname1)['classyear']) year2 = int(getYear(curs, uname2)['classyear']) if abs(year1-year2) < 4: olap = 1 return olap<file_sep>import sys import MySQLdb def findUser(curs, username): curs.execute('''select username from user where username = %s''', [username,]) return curs.fetchone() def insertUser(curs, email, username, password, sprefs): curs.execute('''insert into user(email, username, password, user_type, sprefs) values (%s, %s, %s, "regular", %s)''', [email, username, password, sprefs,]) def updateUser(curs, username, name, nickname, phnum, classyear): curs.execute('''update user set name=%s, nickname=%s, phnum=%s, classyear=%s where username=%s''', [name, nickname, phnum, classyear, username,]) def getPassword(curs, username): curs.execute('select * from user where username = %s', [username,]) return curs.fetchone() def insertIndustry(curs, username, industry): return curs.execute('''insert into industry(pid, iname) values (%s, %s)''', [username, industry,]) def insertFamily(curs, username, family, pred): return curs.execute('''insert into family(member, name, predecessor) values (%s, %s, %s)''', [username, family, pred,]) def insertTeam(curs, username, team, ttype, ncity, state, country): return curs.execute('''insert into team(pid, tname, `type`, nearestcity, state, country) values (%s, %s, %s, %s, %s, %s)''', [username, team, ttype, ncity, state, country,]) <file_sep>use c9; insert into user(name,nickname,classyear,username,password,user_type,sprefs) values ("person","person",2017,"person","pass","regular","overlap");<file_sep># <NAME> import sys import MySQLdb def submitFeedback(curs, uname, date, subject, message): """Insert a new feedback into the feedback table""" curs.execute('''insert into feedback (subject, message, edate, pid) values (%s, %s, %s, %s)''', (subject, message, date, uname,)) def viewFeedback(curs): """Return all feedback""" curs.execute('''select * from feedback''') return curs.fetchall()<file_sep>use lounge_db; insert into events(ename,city,state,country,description,edate,approved,pid) values ("Lobster Pot","Wellesley","ME","US","tourney","2019-10-28",1,"tdeshong"), ("Reunion","San Francisco","CA","US","get-together","2019-01-03",1,"rtang"), ("Spikeball","Wellesley","MA","US","games","2018-12-04",1,"ltso"), ("Reunion","Chicago","IL","US","get-together","2019-09-18",0,"rtang"), ("High Tide","Raleigh","NC","US","tourney","2019-04-08",0,"ltso"); <file_sep># <NAME> import sys import MySQLdb # ================================================================ def getEvent(curs, name, date): '''returns the event matching the unique name and date given''' curs.execute('''select * from events where ename = %s and edate = %s''', (name, date,)) return curs.fetchone() def getEvents(curs, approved): '''returns all upcoming events that are or are not approved''' curs.execute('''select * from events where approved = %s and edate >= current_timestamp() order by edate asc''', (approved,)) return curs.fetchall() def getPastEvents(curs, approved): '''returns all past events that are (1) or are not approved (0)''' curs.execute('''select * from events where approved = %s and edate < current_timestamp() order by edate asc''', (approved,)) return curs.fetchall() def checkEvent(curs, name, date): '''returns true if event with same name and date already exists''' curs.execute('''select count(*) as count from events where ename = %s and edate = %s''', (name, date,)) row = curs.fetchone() return row['count'] > 0 def checkRSVP(curs, uname, name, date): '''returns true if given user has rsvpd to given event''' curs.execute('''select count(*) as count from rsvps where uname=%s and ename = %s and edate = %s''', (uname, name, date,)) row = curs.fetchone() return row['count'] > 0 def submitEvent(curs, name, city, state, country, desc, date, uname): '''inserts event with all accompanying data into the events table''' curs.execute('''insert into events(ename, city, state, country, description, edate, approved, pid) values(%s, %s, %s, %s, %s, %s, 0, %s) ''', (name, city, state, country, desc, date, uname,)) def approveEvent(curs, name, date): '''set event with given name and date as approved -- for admins''' curs.execute('''update events set approved = 1 where ename = %s and edate = %s''', (name, date,)) def deleteEvent(curs, name, date): '''delete event with given name and date -- for admins''' curs.execute('''delete from events where ename = %s and edate = %s''', (name, date,)) def updateRSVP(curs, name, date, uname): '''update rsvps for the event with the given name and date for the user''' curs.execute('''insert into rsvps(uname, ename, edate) values(%s, %s, %s)''', (uname, name, date,)) curs.execute('''update events set rsvps = rsvps + 1 where ename = %s and edate = %s''', (name, date,)) # need to inner join on rsvps def getRSVP(curs, name, date): '''return number of rsvps for the event with the given name and date''' curs.execute('''select rsvps from events where ename = %s and edate = %s''', (name, date,)) return curs.fetchone() def getPeople(curs, name, date): '''return people who have rsvpd to the event with the given name and date''' curs.execute('''select name, username from user inner join rsvps on user.username = rsvps.uname where ename = %s and edate = %s''', (name, date,)) return curs.fetchall() # ================================================================ <file_sep>import sys import MySQLdb def getConn(db): conn = MySQLdb.connect(host='localhost', user='ltso', passwd='', db=db) conn.autocommit(True) return conn def findUser(conn, username): curs = conn.cursor(MySQLdb.cursors.DictCursor) curs.execute('''select * from user where username = %s''', [username,]) return curs.fetchone() def getUserType(conn, username): curs = conn.cursor(MySQLdb.cursors.DictCursor) curs.execute('''select user_type from user where username = %s''', [username,]) return curs.fetchone() def insertUser(conn, name, email, username, password, nickname, phnum, classyear, sprefs): curs = conn.cursor(MySQLdb.cursors.DictCursor) return curs.execute('''insert into user(name, email, username, password, nickname, phnum, classyear, user_type, sprefs) values (%s, %s, %s, %s, %s, %s, %s, "regular", %s)''', [name, email, username, password, nickname, phnum, classyear, sprefs,]) def insertIndustry(conn, username, industry): curs = conn.cursor(MySQLdb.cursors.DictCursor) return curs.execute('''insert into industry(pid, iname) values (%s, %s)''', [username, industry,]) def insertFamily(conn, username, family, pred): curs = conn.cursor(MySQLdb.cursors.DictCursor) return curs.execute('''insert into family(memeber, name, predecessor) values (%s, %s, %s)''', [username, family, pred,]) def insertTeam(conn, username, team, ttype, ncity, state, country): curs = conn.cursor(MySQLdb.cursors.DictCursor) return curs.execute('''insert into team(pid, tname, `type`, nearestcity, state, country) values (%s, %s, %s, %s, %s, %s)''', [username, team, ttype, ncity, state, country,]) <file_sep># <NAME> import sys import MySQLdb import cs304auth def getConn(): conn = MySQLdb.connect(host='localhost', user='rianntang', passwd='', db='c9') curs = conn.cursor(MySQLdb.cursors.DictCursor) conn.autocommit(True) return curs<file_sep># Welcome to Lounge! Lounge is a Whiptail database where current members and alumnae of the Wellesley ultimate frisbee team can more easily connect for fundraising, networking, and socializing. -- <NAME> <NAME> <NAME> <file_sep>from flask import (Flask, url_for, flash, render_template, request, redirect, session, jsonify) import events, messages, login, donations, feedback app = Flask(__name__) app.secret_key = "notverysecret" @app.route('/') def index(): return render_template('index.html') @app.route('/createAccount/', methods=['GET', 'POST']) def logins(): if request.method == 'GET': return render_template('userinfo.html') if request.method == 'POST': error = False email = '' uname = '' pwd1 = '' pwd2 = '' name = '' nname = '' year = '' phnum = '' sprefs = '' industry = '' fname = '' ances = '' team = '' ttype = '' ncity= '' state = '' country = '' try: email = request.form.get("email") uname = request.form.get("username") pwd1 = request.form.get("<PASSWORD>1") pwd2 = request.form.get("<PASSWORD>") name = request.form.get("name") nname = request.form.get("nickname") year = request.form.get("year") phnum = request.form.get("phnum") sprefs = request.form.get("sprefs") industry = request.form.get("ind") fname = request.form.get("fname") ances = request.form.get("ancestor") team = request.form.get("team") ttype = request.form.get("t") ncity = request.form.get("tcity") state = request.form.get("tstate") country = request.form.get("tcountry") except: flash("Access to missing form inputs") error = True if uname == '': error = True flash("Missing input: Username is missing") if pwd1 == '' or pwd2 == '': error = True flash("Missing input: One or both of the password fields are incomplete") if pwd1 != pwd2: error = True flash("Passwords do not match") if email == '' or "@" not in email: error = True flash("Invalid email address") if name == '': error = True flash("Missing input: Name is missing") if not year.isdigit(): error = True flash("Invalid class year") if sprefs == '': error = True flash("Missing input: Security preferences missing") if not error: conn = login.getConn("c9") if login.findUser(conn, uname) is None: flash("{} created an account".format(uname)) login.insertUser(conn, name, email, uname, pwd1, nname, phnum, year, sprefs) if industry != '': login.insertIndustry(conn, uname, industry) if fname != '': login.insertFamily(conn, uname, fname, ances) if team != '': login.insertTeam(conn, uname, team, ttype, ncity, state, country) return redirect(url_for('index')) else: flash("Username already exists") # username not in database return redirect(request.referrer) else: return redirect(request.referrer) # Sets the user of the session @app.route('/setUID/', methods=['POST']) def setUID(): uid = request.form.get('uid') session['uid'] = uid conn = login.getConn("c9") session['utype'] = login.getUserType(conn, uid) return redirect(request.referrer) @app.route('/approved/') def viewApproved(): if session['uid'] == '': flash("Need to log in") return redirect(request.referrer) else: conn = events.getConn('c9') all_events = events.getEvents(conn, 1) return render_template('events.html', events=all_events) @app.route('/submitted/') def viewSubmitted(): if session['uid'] == '': flash("Need to log in") return redirect(request.referrer) else: if session['utype']['user_type'] == 'regular': flash('Not accessible for regular users') return redirect(url_for('viewApproved')) else: conn = events.getConn('c9') all_events = events.getEvents(conn, 0) return render_template('events.html', events=all_events, approve = "yes") @app.route('/submitEvent/', methods=['POST']) def submitEvent(): if session['uid'] == '': flash("Need to log in") return redirect(request.referrer) else: error = False name = '' city = '' state = '' country = '' description = '' date = '' try: name = request.form.get('name') city = request.form.get('city') state = request.form.get('state') country = request.form.get('country') desc = request.form.get('desc') date = request.form.get('date') except: flash("Access to missing form inputs") error = True if name == '': flash("Missing input: Event's name is missing") error = True checkdate = "".join(request.form.get('date').split("-")) if not checkdate or not checkdate.isdigit(): error = True if not checkdate: flash("Missing input: Event's date is missing") else: flash("Date is not numeric") if not error: conn = events.getConn('c9') if events.checkEvent(conn, name, date): flash("Event {} at {} exists".format(name, date)) else: events.submitEvent(conn, name, city, state, country, desc, date) flash("Event {} submitted for approval by admins".format(name)) return redirect(url_for('viewApproved')) @app.route('/approveDeleteEvent/', methods=['POST']) def approveDeleteEvent(): conn = events.getConn('c9') name = request.form.get('name') date = request.form.get('date') if request.form.get('submit') == 'Approve!': events.approveEvent(conn, name, date) flash("Event {} approved".format(name)) return redirect(url_for('viewApproved')) if request.form.get('submit') == 'Delete!': print(name, date) events.deleteEvent(conn, name, date) flash("Event {} deleted".format(name)) return redirect(url_for('viewSubmitted')) # Main page for messaging feature @app.route('/messages/') def messaging(): if session['uid'] == '': # Not logged in yet flash("Need to log in") return render_template('index.html') # Go to a temporary login else: uid = session['uid'] curs = messages.cursor('c9') allMsgs = messages.getMessageHistory(curs, uid) # Get people user has messaged/received messages from allK = list(allMsgs.keys()) mPreview=[] # Empty list to store a preview of messages with each person num=[] # For navigating for all the inputs in html page for i in range(0,len(allK)): mPreview.append(messages.getLastM(curs,uid, allK[i])) for i in range(0,len(allMsgs)): num.append(i) return render_template('messages.html', num=num, msgs=allMsgs, mKeys=allK, mPrev=mPreview) # Sends new message @app.route('/sendMsg/', methods=['POST']) def sendMsg(): curs = messages.cursor('c9') uid = session['uid'] receiver = request.form.get('receiver') content = request.form.get('message') messages.sendMessage(curs, uid, receiver, content) return redirect(request.referrer) # Sends new message with Ajax @app.route('/sendMsgAjax/', methods=['POST']) def sendMsgAjax(): curs = messages.cursor('c9') uid = session['uid'] receiver = request.form.get('receiver') content = request.form.get('message') messages.sendMessage(curs, uid, receiver, content) return jsonify(uid) #Could even return text # For showing messages with an individual person @app.route('/personMs/') def messagePerson(): uid = session['uid'] person = request.args.get('person') curs=messages.cursor('c9') msgs = messages.getMessages(curs, uid, person) return jsonify(msgs) # Main page for donations, showing HTML form to submit donations @app.route('/donate/') def makeDonation(): if session['uid'] == '': flash("Need to log in") return redirect(request.referrer) else: return render_template('donations.html') @app.route('/submitDonation/', methods=['POST']) def submitDonation(): if session['uid'] == '': flash("Need to log in") return redirect(request.referrer) else: error = False uname = request.form.get('username') item = request.form.get('item') description = request.form.get('description') # Check to see all inputs have been filled out if uname == '': flash("Missing input: Please input your name") error = True if item == None: flash("Missing input: Please choose an item type") error = True if description == '': flash("Missing input: Please describe your item") error = True if not error: curs = donations.cursor('c9') donations.submitDonation(curs, uname, item, description) name=donations.getName(curs,uname) name=name['name'] return render_template('donationSuccess.html', name = name) return render_template('donations.html') # An admin only page for viewing donations @app.route('/viewDonations/') def viewDonations(): if session['uid'] == '': flash("Need to log in") return redirect(request.referrer) else: # Make sure user is an admin if session['utype']['user_type'] == 'regular': flash('Not accessible for regular users') return redirect(url_for('makeDonation')) else: curs = donations.cursor('c9') oldDonations = donations.getOldDonations(curs) newDonations = donations.getNewDonations(curs) return render_template('viewDonations.html', oldDonations=oldDonations, newDonations=newDonations) # Method to mark donations as read/unread @app.route('/markDonation/', methods=['POST']) def markSeen(): curs = messages.cursor('c9') uid = session['uid'] did = request.form.get('did') seen = 0; if request.form.get('submit') == "Mark as read": seen = 1; donations.mark(curs, did, seen) return redirect(url_for('viewDonations')) # Main page for feedback, showing HTML form to submit feedback @app.route('/feedback/') def giveFeedback(): if session['uid'] == '': flash("Need to log in") return redirect(request.referrer) else: return render_template('feedback.html') @app.route('/submitFeedback/', methods=['POST']) def submitFeedback(): if session['uid'] == '': flash("Need to log in") return redirect(request.referrer) else: error = False uname = request.form.get('username') date = request.form.get('date') subject = request.form.get('subject') message = request.form.get('message') if message == '': flash("Missing input: Message is required") error = True if date != '': checkdate = "".join(request.form.get('date').split("-")) if not checkdate.isdigit(): error = True flash("Date is not numeric") if not error: curs = feedback.cursor('c9') feedback.submitFeedback(curs, uname, date, subject, message) flash("Thanks for the feedback! Our admins will be in touch soon to follow up if necessary.") return render_template('feedback.html') @app.route('/viewFeedback/') def viewFeedback(): if session['uid'] == '': flash("Need to log in") return redirect(request.referrer) else: # Make sure user is an admin if session['utype']['user_type'] == 'regular': flash('Not accessible for regular users') return redirect(url_for('makeDonation')) else: curs = feedback.cursor('c9') fback = feedback.viewFeedback(curs) return render_template('viewFeedback.html', feedback=fback) if __name__ == '__main__': app.debug = True app.run('0.0.0.0',8080)<file_sep>use lounge_db; delete from donation; insert into donation (pid, item, description) values ("ltso", "cleats", "Lightly used, size 7"), ("rtang", "uniform", "Size M top, size S shorts"), ("tdeshong", "other", "Size S running shorts");<file_sep># <NAME> import sys import MySQLdb def getSenderHist(curs, user): """Return the name of people user has messaged.""" curs.execute('''select receiver from messages where sender=%s''', (user,)) return curs.fetchall() def getReceiveHist(curs,user): """Return the name of people user has recieved messages from.""" curs.execute('''select sender from messages where receiver=%s''', (user,)) return curs.fetchall() def getName(curs, user): """Return the name of the given user.""" curs.execute('''select name from user where username=%s''', (user,)) return curs.fetchone() def getMessageHistory(curs, user): """Return all messages user has sent and recieved messages from""" sendHist = getSenderHist(curs, user) receiveHist=getReceiveHist(curs, user) allMs = sendHist+receiveHist distinctMs = [] for i in range (0, len(allMs)): if allMs[i].has_key('receiver'): if allMs[i]['receiver'] not in distinctMs: distinctMs.append(allMs[i]['receiver']) if allMs[i].has_key('sender'): if allMs[i]['sender'] not in distinctMs: distinctMs.append(allMs[i]['sender']) mHist = {} for i in range (0,len(distinctMs)): name = getName(curs, distinctMs[i]) mHist[distinctMs[i]] = name['name'] return mHist def getLastM(curs, user1, user2): """Return most recent message between two given users""" curs.execute('''select message from messages where (sender=%s and receiver=%s) or (sender=%s and receiver=%s) order by mid desc limit 1''',(user1,user2,user2,user1,)) return curs.fetchone() def getMessages(curs, user1, user2): """Return all messages between two given users""" curs.execute('''select message, sender from messages where (sender=%s and receiver=%s) or (sender=%s and receiver=%s)''',(user1, user2, user2, user1,)) return curs.fetchall() def sendMessage(curs, sender, receiver, msg): "Insert messages into messages table" curs.execute('''insert into messages (sender, receiver, message) values (%s,%s,%s)''', (sender, receiver, msg,)) <file_sep>import sys import MySQLdb def findUser(curs, username): curs.execute('''select username from user where username = %s''', [username,]) return curs.fetchone() def insertUser(curs, email, username, password, sprefs): curs.execute('''insert into user(email, username, password, user_type, sprefs) values (%s, %s, %s, "regular", %s)''', [email, username, password, sprefs,]) def updateUser(curs, username, name, nickname, phnum, classyear): curs.execute('''update user set name=%s, nickname=%s, phnum=%s, classyear=%s where username=%s''', [name, nickname, phnum, classyear, username,]) def getPassword(curs, username): curs.execute('select * from user where username = %s', [username,]) return curs.fetchone() def insertIndustry(curs, username, industry): return curs.execute('''insert into industry(pid, iname) values (%s, %s) on duplicate key update iname=%s''', [username, industry, industry,]) def insertFamily(curs, username, family, pred): return curs.execute('''insert into family(member, name, predecessor) values (%s, %s, %s) on duplicate key update name=%s, predecessor=%s''', [username, family, pred, family, pred,]) def insertTeam(curs, username, team, ttype, ncity, state, country): return curs.execute('''insert into team(pid, tname, `type`, nearestcity, state, country) values (%s, %s, %s, %s, %s, %s) on duplicate key update tname=%s, `type`=%s, nearestcity=%s, state=%s, country=%s''', [username, team, ttype, ncity, state, country, team, ttype, ncity, state, country,]) def insertPic(curs, username, filename): '''Insert user and their picture into picfile table''' curs.execute('''insert into picfile(pic, filename) values (%s, %s)''', [username, filename,]) <file_sep># <NAME> import sys import MySQLdb # ================================================================ def getUserFamily(curs, uid): '''returns family name a given person is a part of''' curs.execute('''select family.name, user.name as pred from family inner join user on family.predecessor = user.username where family.member = %s''', (uid,)) return curs.fetchone() def getFamily(curs, names_dict): '''returns all given family names and members with their given name''' names = [name['name'] for name in names_dict] wildcard = tuple(names) curs.execute('''select family.name, user.name as uname, user.classyear from family inner join user on family.predecessor = user.username or family.member = user.username having family.name in %s order by user.classyear''', (wildcard,)) return curs.fetchall() def findFamily(curs, searchterm): '''returns all families with a member that matches the searchterm''' key = '%' + searchterm + '%' # format the wildcard for sql search curs.execute('''select family.name, user.name from family inner join user on family.predecessor = user.username or family.member = user.username where user.name like %s''', (key,)) return curs.fetchall()<file_sep>use c9; delete from messages; insert into messages (sender, receiver, message) values ("ltso", "tdeshong", "Hey Tam!"), ("tdeshong", "ltso", "Lauren, what's up?"), ("ltso", "tdeshong", "You going to the tournament this weekend?"), ("tdeshong", "ltso", "Not sure yet. I have a lot of work due Monday...Hbu?"), ("ltso", "tdeshong", "I think so! You should come!"), ("tdeshong", "ltso", "eh, we'll see"), ("rtang", "ltso", "Going to Target. Want anything?"), ("ltso", "rtang", "Goldfish please"), ("rtang", "ltso", "Ok, will do!"), ("rtang", "ltso", "Actually, have another space in the car. Wanna come?"), ("ltso", "rtang", "ok"), ("rtang", "ltso", "Meet you in gray lot at 6"), ("rtang", "tdeshong", "knock knock"), ("tdeshong", "rtang", "who's there?"), ("rtang", "tdeshong", "interupting cow"), ("tdeshong", "rtang", "interupting cow who?"), ("rtang", "tdeshong", "moooooo"), ("rtang", "tdeshong", "wait...realizing this joke doesn't work over text..."), ("tdeshong", "rtang", "...omg riann");<file_sep># <NAME> import sys import MySQLdb # ================================================================ ''' Search for members in the database by name, nickname, classyear and industry ''' def search (curs, search_items): # addes nickname to the query if name is in there if "name" in search_items[0]: items = [search_items[1][0]] +list(search_items[1]) name = ['(name like %s or nickname like %s)'] compares =' and '.join(name+[ ' {col} like %s '.format(col=c) \ for c in search_items[0][1:]]) else: items = search_items[1] compares = ' and '.join([ ' {col} like %s '.format(col=c) \ for c in search_items[0]]) #sees if an industry is in the query if "iname" in compares: curs.execute('''select user.name, user.nickname, user.classyear from user inner join industry on username=pid where ''' + compares, items) else: curs.execute('''select name, nickname, classyear from user where ''' + compares, items) return curs.fetchall() # compares = ' and '.join([ ' {col} like %s '.format(col=c) for c in search_items[0] ]) # if "iname" in compares: # curs.execute('''select user.name, user.nickname, user.classyear # from user inner join industry on username=pid # where ''' + compares, search_items[1]) # else: # curs.execute('''select name, nickname, classyear # from user where ''' + compares, search_items[1]) # return curs.fetchall() # def preference(curs, username): # curs.execute('''select * from user where name = %s''', # [username]) # return curs.fetchone() <file_sep># <NAME> import sys import MySQLdb import cs304auth def getConn(): conn = MySQLdb.connect(host='localhost', user='ltso', passwd='', db='lounge_db') curs = conn.cursor(MySQLdb.cursors.DictCursor) conn.autocommit(True) return curs<file_sep># <NAME> import sys import MySQLdb def getConn(db): conn = MySQLdb.connect(host='localhost', user='ltso', passwd='', db=db) conn.autocommit(True) # Necessary to alter the wmdb database return conn def cursor(db, rowType='dictionary'): conn = getConn(db) '''Returns a list of rows, either as dictionaries (the default) or tuples''' if rowType == 'tuple': curs = conn.cursor() elif rowType == 'dictionary': # results as Dictionaries curs = conn.cursor(MySQLdb.cursors.DictCursor) return curs # Helper function to get messages sent by given user def getSenderHist(curs, user): curs.execute('''select receiver from messages where sender=%s''', (user,)) return curs.fetchall() # Helper function to get messages received by given user def getReceiveHist(curs,user): curs.execute('''select sender from messages where receiver=%s''', (user,)) return curs.fetchall() # Helper function get the name of a user given their username def getName(curs, user): curs.execute('''select name from user where username=%s''', (user,)) return curs.fetchone() # Function to get all messages sent and received by given user def getMessageHistory(curs, user): sendHist = getSenderHist(curs, user) receiveHist=getReceiveHist(curs, user) allMs = sendHist+receiveHist distinctMs = [] for i in range (0, len(allMs)): if allMs[i].has_key('receiver'): if allMs[i]['receiver'] not in distinctMs: distinctMs.append(allMs[i]['receiver']) if allMs[i].has_key('sender'): if allMs[i]['sender'] not in distinctMs: distinctMs.append(allMs[i]['sender']) mHist = {} for i in range (0,len(distinctMs)): name = getName(curs, distinctMs[i]) mHist[distinctMs[i]] = name['name'] return mHist # Function to get the most recently message between two users def getLastM(curs, user1, user2): curs.execute('''select message from messages where (sender=%s and receiver=%s) or (sender=%s and receiver=%s) order by mid desc limit 1''',(user1,user2,user2,user1,)) return curs.fetchone() # Function to get all messages between two users def getMessages(curs, user1, user2): curs.execute('''select message, sender from messages where (sender=%s and receiver=%s) or (sender=%s and receiver=%s)''',(user1, user2, user2, user1,)) return curs.fetchall() # Function to input a new message into the messages table def sendMessage(curs, sender, receiver, msg): curs.execute('''insert into messages (sender, receiver, message) values (%s,%s,%s)''', (sender, receiver, msg,)) <file_sep>from flask import (Flask, url_for, flash, render_template, request, redirect, session, jsonify, make_response, send_from_directory, Response) from datetime import date, datetime from threading import Thread, Lock import events, messages, family, login, donations, feedback, conn, profiles, search from werkzeug import secure_filename import bcrypt import imghdr import MySQLdb import sys, os app = Flask(__name__) app.secret_key = "notverysecret" app.config['TRAP_BAD_REQUEST_ERRORS'] = True app.config['UPLOADS'] = 'uploads' lock = Lock() @app.route('/') def index(): '''return template with appropriate login display''' if session.get('uid') == None or session.get('uid') == '': return render_template('notLI.html') else: return render_template('LI.html') @app.route('/admin/') def adminBoard(): '''return admin page viewable only to admin users''' if session.get('uid') == None: flash("Need to log in") return redirect(request.referrer) if session.get('utype') == 'regular': flash('Need admin privileges') return redirect(request.referrer) else: return render_template('admin.html') @app.route('/account/', methods=['GET', 'POST']) def account(): '''return template to create a new account''' return render_template('userinfo.html') @app.route('/createAccount/', methods=['GET', 'POST']) def newAccount(): '''create a new account and insert user into database''' if request.method == 'GET': return redirect(url_for('account')) if request.method == 'POST': error = False email = request.form.get("email", '') uname = request.form.get("username", '') pwd1 = request.form.get("password1", '') pwd2 = request.form.get("password2", '') sprefs = request.form.get("sprefs", '') if uname == '': error = True flash("Missing input: Username is missing") if pwd1 == '' or pwd2 == '': error = True flash("Missing input: One or both of the password fields are incomplete") if pwd1 != pwd2: error = True flash("Passwords do not match") if "@" not in email: error = True flash("Invalid email address") if sprefs == '': error = True flash("Missing input: Security preferences missing") if error: return redirect(request.referrer) curs = conn.getConn() hashed = bcrypt.hashpw(pwd1.encode('utf-8'), bcrypt.gensalt()) # salt password for security if login.findUser(curs, uname) is not None: flash('That username is taken') return redirect(url_for('index')) login.insertUser(curs, email, uname, hashed, sprefs) login.insertPic(curs, uname, 'default.jpg') flash('Thanks for creating in account. Try logging in now!') return redirect(url_for('index')) @app.route('/login/', methods=['POST']) def loginuser(): '''log in a user and set their status as a user''' try: username = request.form.get('uid') passwd = request.form.get('pwd') curs = conn.getConn() row = login.getPassword(curs, username) if row is None: # Same response as wrong password, so no information about what went wrong flash('login incorrect. Try again or join') hashed = row['password'] utype = row['user_type'] # strings always come out of the database as unicode objects if bcrypt.hashpw(passwd.encode('utf-8'),hashed.encode('utf-8')) == hashed: flash('successfully logged in as '+ username) session['uid'] = username session['logged_in'] = True session['utype'] = utype return redirect(url_for('completeProfile')) else: flash('login incorrect. Try again or join') return redirect(url_for('index')) except Exception as err: flash('form submission error '+ str(err)) return redirect( url_for('index') ) @app.route('/logout/', methods=['POST']) def logout(): '''logout a user and set the session appropriately''' try: if session.get('uid') == None: flash('you are not logged in. Please login or join') return redirect( url_for('index') ) else: uid = session['uid'] session.pop('uid') session.pop('logged_in') flash('{} is logged out'.format(uid)) return redirect(url_for('index')) except Exception as err: flash('some kind of error '+str(err)) return redirect( url_for('index')) @app.route('/completeProfile/', methods=['GET', 'POST']) def completeProfile(): '''return template to complete a user's profile''' if session.get('uid') == None: flash("Need to log in") return redirect( url_for('index')) else: curs = conn.getConn() uid = session.get('uid') basic = profiles.getBasicInfo(curs, uid) contact = profiles.getContactInfo(curs, uid) industry = profiles.getIndustry(curs, uid) fam = family.getUserFamily(curs, uid) team = profiles.getTeam(curs, uid) picture = profiles.getPic(curs,uid) return render_template('moreinfo.html', b=basic, c=contact, i=industry, f=fam, t=team, p=picture) @app.route('/updateProfile/', methods=['POST']) def updateProfile(): '''update profile for filled in items and picture''' if session.get('uid') == None: flash("Need to log in") return redirect( url_for('index')) else: uname = session.get('uid') name = request.form.get("name") nname = request.form.get("nickname") year = request.form.get("year") phnum = request.form.get("phnum") industry = request.form.get("ind", '') fname = request.form.get("fname") ances = request.form.get("predecessor") team = request.form.get("team") ttype = request.form.get("t", '') ncity = request.form.get("tcity") state = request.form.get("tstate") country = request.form.get("tcountry") error = False print(year) print(type(year)) print(year != 'None') if year != 'None' and not year.isdigit(): error = True flash("Invalid class year") curs = conn.getConn() try: f = request.files['pic'] mime_type = imghdr.what(f.stream) if mime_type.lower() not in ['jpeg','gif','png']: raise Exception('Not a JPEG, GIF or PNG: {}'.format(mime_type)) filename = secure_filename('{}.{}'.format(uname,mime_type)) pathname = os.path.join(app.config['UPLOADS'],filename) f.save(pathname) curs.execute('''update picfile set filename=%s where pic=%s''', [filename, uname]) except ZeroDivisionError as err: flash('Upload failed {why}'.format(why=err)) return redirect(request.referrer) if not error: login.updateUser(curs, uname, name, nname, phnum, year) login.insertIndustry(curs, uname, industry) login.insertFamily(curs, uname, fname, ances) login.insertTeam(curs, uname, team, ttype, ncity, state, country) flash('Updated profile!') flash('Upload successful') return redirect(url_for('getProfile', username=uname)) else: return redirect(request.referrer) @app.route('/approved/') def viewApproved(): '''display past and upcoming approved (1) events''' if session.get('uid') == None: flash("Need to log in") return redirect(url_for('index')) else: curs = conn.getConn() up_events = events.getEvents(curs, 1) up_id = [event['ename'].replace(' ', '') for event in up_events] up = [(up_events[i], up_id[i]) for i in range(len(up_events))] past_events = events.getPastEvents(curs, 1) past_id = [event['ename'].replace(' ', '') for event in past_events] past = [(past_events[i], past_id[i]) for i in range(len(past_events))] return render_template('events.html', up=up, past=past) @app.route('/events/<eid>', methods=['GET']) def listEvent(eid): '''display more info on a specific event''' curs = conn.getConn() new_id = eid.split('_') name = new_id[0] date = new_id[1] event = events.getEvent(curs, name, date) past = False approved = False rsvp=False if event in events.getPastEvents(curs, 1): past = True if event in events.getEvents(curs, 1): approved = True if events.checkRSVP(curs, session.get('uid'), name, date): rsvp=True return render_template('event.html', event = event, past=past, approved=approved, rsvp=rsvp) @app.route('/moreEvent/', methods=['POST']) def moreEvent(): '''redirect user to single event card with more info''' name = request.form.get('name') date = request.form.get('date') eid = str(name) + '_' + str(date) return redirect(url_for('listEvent', eid=eid)) @app.route('/submitted/') def viewSubmitted(): '''view past and upcoming submitted (0) events''' if session.get('uid') == None: flash("Need to log in") return redirect(url_for('index')) else: if session.get('utype') == 'regular': flash('Not accessible for regular users') return redirect(url_for('viewApproved')) else: curs = conn.getConn() up_events = events.getEvents(curs, 0) up_id = [event['ename'].replace(' ', '') for event in up_events] up = [(up_events[i], up_id[i]) for i in range(len(up_events))] past_events = events.getPastEvents(curs, 0) past_id = [event['ename'].replace(' ', '') for event in past_events] past = [(past_events[i], past_id[i]) for i in range(len(past_events))] return render_template('events.html', up=up, past=past) @app.route('/createEvent/', methods=['GET', 'POST']) def createEvent(): '''return template to create an event''' return render_template('createEvent.html') @app.route('/submitEvent/', methods=['POST']) def submitEvent(): '''submit an event to be approved by admins''' if session.get('uid') == None: flash("Need to log in") return redirect(url_for('index')) else: error = False name = request.form.get('name') city = request.form.get('city') state = request.form.get('state') country = request.form.get('country') desc = request.form.get('desc') date = request.form.get('date') if name == '': flash("Missing input: Event's name is missing") error = True try: datetime.strptime(date, '%Y-%m-%d') except: error = True flash("Incorrect data format, should be YYYY-MM-DD") if not error: curs = conn.getConn() lock.acquire() if events.checkEvent(curs, name, date): flash("Event {} at {} exists".format(name, date)) else: events.submitEvent(curs, name, city, state, country, desc, date, session['uid']) flash("Event {} submitted for approval by admins".format(name)) lock.release() return redirect(url_for('createEvent')) @app.route('/approveDeleteEvent/', methods=['POST']) def approveDeleteEvent(): '''approve or delete an event by an admin only''' curs = conn.getConn() name = request.form.get('name') date = request.form.get('date') if request.form.get('submit') == 'Approve!': events.approveEvent(curs, name, date) flash("Event {} approved".format(name)) return redirect(url_for('viewApproved')) if request.form.get('submit') == 'Delete!': print(name, date) events.deleteEvent(curs, name, date) flash("Event {} deleted".format(name)) return redirect(url_for('viewSubmitted')) @app.route('/rsvpEvent/', methods=['POST']) def rsvpEvent(): '''update rsvps on page through flask''' curs = conn.getConn() name = request.form.get('name') date = request.form.get('date') events.updateRSVP(curs, name, date, session['uid']) return redirect(request.referrer) @app.route('/rsvpEventAjax/', methods=['POST']) def rsvpEventAjax(): '''update rsvps on page through ajax''' curs = conn.getConn() name = request.form.get('name') eid = name.replace(' ', '') date = request.form.get('date') events.updateRSVP(curs, name, date, session['uid']) rsvp = events.getRSVP(curs, name, date) return jsonify({'rsvp': rsvp['rsvps'], 'name': name, 'date': date, 'eid': eid}) @app.route('/findRSVPsAjax/', methods=['POST']) def findRSVPsAjax(): '''list rsvps on page through ajax''' curs = conn.getConn() name = request.form.get('name') date = request.form.get('date') rsvps = events.getPeople(curs, name, date) unames = [rsvp['username'] for rsvp in rsvps] str_rsvps = [rsvp['name'] for rsvp in rsvps] return jsonify({'rsvps': str_rsvps, 'unames':unames}) @app.route('/messages/') def messaging(): """Returns html page with necessary data to populate messaging page.""" if session.get('uid') == None: flash("Need to log in") return redirect(url_for('index')) else: uid = session['uid'] curs = conn.getConn() allMsgs = messages.getMessageHistory(curs, uid) # Get people user has messaged/received messages from allK = list(allMsgs.keys()) mPreview = [messages.getLastM(curs,uid, allK[i]) for i in range(0,len(allK))] num = [i for i in range(0,len(allMsgs))] return render_template('messages.html', num=num, msgs=allMsgs, mKeys=allK, mPrev=mPreview) @app.route('/sendMsg/', methods=['POST']) def sendMsg(): """Sends a new message by inserting into the messaging table""" curs = conn.getConn() uid = session['uid'] receiver = request.form.get('receiver') content = request.form.get('message') messages.sendMessage(curs, uid, receiver, content) return redirect(request.referrer) # Sends new message with Ajax @app.route('/sendMsgAjax/', methods=['POST']) def sendMsgAjax(): """Sends a message using Ajax updating""" curs = conn.getConn() uid = session['uid'] receiver = request.form.get('receiver') content = request.form.get('message') messages.sendMessage(curs, uid, receiver, content) return jsonify(uid) #Could even return text @app.route('/personMs/') def messagePerson(): """Returns all messages with a specific person""" uid = session['uid'] person = request.args.get('person') curs = conn.getConn() msgs = messages.getMessages(curs, uid, person) return jsonify(msgs) @app.route('/donate/') def makeDonation(): """Returns html page populated with donation form""" if session.get('uid') == None: flash("Need to log in") return redirect(url_for('index')) else: return render_template('donations.html') @app.route('/submitDonation/', methods=['POST']) def submitDonation(): """Submits donation by inserting the data into the donation table""" if session.get('uid') == None: flash("Need to log in") return redirect( url_for('index')) else: error = False uname = request.form.get('username') item = request.form.get('item') description = request.form.get('description') # Check to see all inputs have been filled out if uname == '': flash("Missing input: Please input your name") error = True if item == None: flash("Missing input: Please choose an item type") error = True if description == '': flash("Missing input: Please describe your item") error = True if not error: curs = conn.getConn() donations.submitDonation(curs, uname, item, description) name=donations.getName(curs,uname) name=name['name'] return render_template('donationSuccess.html', name = name) return render_template('donations.html') @app.route('/viewDonations/') def viewDonations(): """Returns html page populated with data of all submitted donations""" if session.get('uid') == None: flash("Need to log in") return redirect(url_for('index')) else: if session.get('utype') == 'regular': # Make sure user is an admin flash('Not accessible for regular users') return redirect(url_for('makeDonation')) else: curs = conn.getConn() oldDonations = donations.getOldDonations(curs) newDonations = donations.getNewDonations(curs) return render_template('viewDonations.html', oldDonations=oldDonations, newDonations=newDonations) @app.route('/markDonation/', methods=['POST']) def markSeen(): """Mark all messages as seen or unseen by updating the seen column of the donation table.""" curs = conn.getConn() uid = session['uid'] did = request.form.get('did') seen = 0; if request.form.get('submit') == "Mark as read": seen = 1; donations.mark(curs, did, seen) return redirect(url_for('viewDonations')) @app.route('/feedback/') def giveFeedback(): """Return html page with feedback form""" if session.get('uid') == None: flash("Need to log in") return redirect(url_for('index')) else: return render_template('feedback.html') @app.route('/submitFeedback/', methods=['POST']) def submitFeedback(): """Submit feedback by inserting feedback data into feedback table.""" error = False uname = request.form.get('username') date = request.form.get('date') subject = request.form.get('subject') message = request.form.get('message') if message == '': flash("Missing input: Message is required") error = True if date != '': checkdate = "".join(request.form.get('date').split("-")) if not checkdate.isdigit(): error = True flash("Date is not numeric") if uname == "": # PID in table must be specified or assigned NULL uname = None if not error: curs = conn.getConn() feedback.submitFeedback(curs, uname, date, subject, message) flash("Thanks for the feedback! Our admins will be in touch soon to follow up if necessary.") return render_template('feedback.html') @app.route('/viewFeedback/') def viewFeedback(): """Return all submitted feedback in html page""" if session.get('uid') == None: flash("Need to log in") return redirect(url_for('index')) else: if session.get('utype') == 'regular': # Make sure user is an admin flash('Not accessible for regular users') return redirect(url_for('makeDonation')) else: curs = conn.getConn() fback = feedback.viewFeedback(curs) return render_template('viewFeedback.html', feedback=fback) @app.route('/familySearch/', methods=['POST']) def redirect_url(): searchterm = request.form.get('searchterm') # take in searched search term return redirect(url_for('getFamily', searchterm=searchterm)) # redirect to movie page with movies matching search @app.route('/family/', defaults={'searchterm':''}) # defaults to showing all families @app.route('/family/<searchterm>/', methods=['GET']) def getFamily(searchterm): if session.get('uid') == None:# Not logged in yet flash("Need to log in") return redirect(url_for('index')) else: curs = conn.getConn() names_dict = family.findFamily(curs, searchterm) if len(names_dict) == 0: flash('No names match this search') return redirect(request.referrer) else: families = family.getFamily(curs, names_dict) names_all = [fam['name'] for fam in families] names = list(set(names_all)) return render_template('family.html', families=families, names=names) @app.route('/profile/<username>/', methods=['GET']) def getProfile(username): """Retrieves the profile of the given user and ensures security preferences are respected""" currentU = session.get('uid') if currentU == None: flash("Need to log in") return redirect(url_for('index')) if currentU == username: # Check if viewing own profile isSelf = 1; curs = conn.getConn() #Get all the user's info basic = profiles.getBasicInfo(curs, username) industry = profiles.getIndustry(curs, username) team = profiles.getTeam(curs, username) contact = profiles.getContactInfo(curs, username) pic = profiles.getPic(curs, username) try: # If viewing own profile isSelf permiss=1 return render_template('profile.html', basic=basic, industry=industry, team=team, contact=contact, permiss=permiss, isSelf=isSelf, pic = url_for('pic',name=username)) except NameError: #Check user's security preferences and whether person viewing profiles matches prefs prefs = profiles.getSecurityPrefs(curs, username)['sprefs'] if session.get('utype') == 'admin': #Admins can always view all info permiss = 1 elif prefs == "all": permiss = 1 elif prefs == "class": if profiles.getYear(curs, username) == profiles.getYear(curs, currentU): permiss = 1 elif prefs == "overlap": if profiles.getOverlap(curs, username, currentU) == 1: permiss = 1 try: # Determine how much to show on html page permiss return render_template('profile.html', basic=basic, industry=industry, team=team, contact=contact, permiss=permiss, pic = url_for('pic',name=username)) except NameError: npermiss = 1 return render_template('profile.html', basic=basic, industry=industry, team=team, contact=contact, npermiss=npermiss, pic = url_for('pic',name=username)) @app.route("/search/", methods=["GET", "POST"]) def searchPerson(): if session.get('uid') == None:# Not logged in yet flash("Need to log in") return redirect(url_for('index')) if request.method == 'GET': return render_template('search.html') else: name = request.form.get("name") year= request.form.get("year") indust = request.form.get("Industry") if all([name=="", year=="", indust==""]): flash("enter something to filter your search by") return render_template('search.html') searchItems = [] if name!="": searchItems.append(["name", "%"+name+"%"]) if year !="" and year.isdigit(): searchItems.append(["classyear","%"+year+"%" ]) if indust !="": searchItems.append(["iname","%"+indust+"%" ]) transpose = zip(*searchItems) curs = conn.getConn() table = search.search(curs, transpose) return render_template('search.html', table=table) @app.route('/pics/<name>') def pic(name): curs = conn.getConn() numrows = curs.execute('select filename from picfile where pic=%s ', [name]) row = curs.fetchone() val = send_from_directory(app.config['UPLOADS'],row['filename']) print(val) return val if __name__ == '__main__': app.debug = True app.run('0.0.0.0',8080)<file_sep>use lounge_db; delete from feedback; insert into feedback (pid, subject, message, edate) values ("ltso", NULL, "Riann did so well with the CSS!!!!!!!! :D", NULL), ("rtang", "practice", "Just wanted to let captains know that practice was great!", "2018-12-10"), (NULL, NULL, "I wish the team was more transparent about how profits are spent", NULL);<file_sep># <NAME> import sys import MySQLdb def submitDonation(curs, uname, item, description): """Insert a new donation into the donation table""" curs.execute('''insert into donation (pid, item, description) values (%s, %s, %s)''', (uname, item, description,)) def getName(curs, uname): """Return the name of given user""" curs.execute('''select name from user where username=%s''',( uname,)) return curs.fetchone() def getOldDonations(curs): """Return all donations marked as read""" curs.execute('''select * from donation where seen=1''') return curs.fetchall() def getNewDonations(curs): """"Return all donations marked as unread""" curs.execute('''select * from donation where seen=0''') return curs.fetchall() def mark(curs, did, seen): """Mark donations as either read or unread Arguments: Seen -- A boolean represented as a bit set to either 0 or 1 """ curs.execute('''update donation set seen=%s where did =%s''', (seen, did,)) <file_sep>import os, re import MySQLdb def file_contents(filename): with open(filename,'r') as f: return f.read() def getpass(filename='~/mysql-passwd'): '''returns the contents of the given file as a string. You can store your MySQL password in there, separate from your source code''' return file_contents(os.path.expanduser(filename)) # ========================================================================================== # Reading a file formatted like ~/.my.cnf def read_cnf_core(cnf_file=None): '''Read a file formatted like ~/.my.cnf file; defaulting to that file. Return a dictionary with the necessary information to connect to a database. This function is an internal function. Consider using read_cnf(), which caches the results.''' if cnf_file is None: cnf_file = os.path.expanduser('~/.my.cnf') else: cnf_file = os.path.expanduser(cnf_file) cnf = file_contents(cnf_file) credentials = {} # the key is the name used in the CNF file; # the value is the name used in the MySQLdb.connect() function mapping = {'host':'host', 'user':'user', 'password':'<PASSWORD>', 'database':'db'} for key in ('host', 'user', 'password', 'database' ): cred_key = mapping[key] # using \w* permits empty passwords and such # this regex is not perfect. It doesn't allow embedded spaces, for example. regex = r"\b{k}\s*=\s*[\'\"]?(\w*)[\'\"]?".format(k=key) # print 'regex',regex p = re.compile(regex) m = p.search(cnf) if m: credentials[ cred_key ] = m.group(1) elif key == 'host' or key == 'database': credentials[ cred_key ] = 'not specified in ' + cnf_file else: raise Exception('Could not find key {k} in {f}' .format(k=key,f=cnf_file)) checkDSN(credentials) return credentials def checkDSN(dsn): '''Raises a comprehensible error message if the DSN is missing some necessary info''' for key in ('host', 'user', 'passwd', 'db' ): if not key in dsn: raise KeyError('''DSN lacks necessary '{k}' key'''.format(k=key)) return True CNF = None def read_cnf(cnf_file="~/.my.cnf"): global CNF if CNF is not None: return CNF CNF = read_cnf_core(cnf_file) return CNF # ========================================================================================== def mysqlConnectC9(db=None): CNF = {'host': 'localhost', 'user': 'ubuntu', 'passwd':''} if db is not None: CNF['db'] = db conn = MySQLdb.connect(**CNF) conn.autocommit(True) return conn def mysqlConnectPasswd(db=None,filename="~/mysql-passwd"): passwd = file_contents(filename) CNF = {'host': 'localhost', 'user': 'ubuntu', 'passwd':<PASSWORD>} if db is not None: CNF['db'] = db conn = MySQLdb.connect(**CNF) conn.autocommit(True) return conn def mysqlConnectCNF(db=None,filename="~/.my.cnf"): CNF = read_cnf(filename) if db is not None: CNF['db'] = db conn = MySQLdb.connect(**CNF) conn.autocommit(True) return conn # ========================================================================================== if __name__ == '__main__': print 'starting test code, demonstrating how to use the CNF version' import sys if len(sys.argv) < 2: print('''Usage: {cmd} cnf_file test dbconn by giving the name of a cnf_file on the command line''' .format(cmd=sys.argv[0])) sys.exit(1) cnf_file = sys.argv[1] c = mysqlConnectCNF(db='wmdb',filename=cnf_file) print('successfully connected') curs = c.cursor(MySQLdb.cursors.DictCursor) # results as Dictionaries curs.execute('select user() as user, database() as db') row = curs.fetchone() print('connected to {db} as {user}' .format(db=row['db'],user=row['user'])) curs.execute('select nm,name,birthdate from person limit 3') print('first three people') for row in curs.fetchall(): print row curs.execute('select nm,name,birthdate from person where name like %s', ['%george%']) print('names like george') for row in curs.fetchall(): print row <file_sep>use lounge_db; drop table if exists picfile; drop table if exists family; drop table if exists donation; drop table if exists feedback; drop table if exists rsvps; drop table if exists events; drop table if exists messages; drop table if exists team; drop table if exists location; drop table if exists industry; drop table if exists user; create table user( name varchar(50), nickname varchar(30), email varchar(60) not NULL, phnum varchar(10), classyear varchar(4), username varchar(20) not NULL, password varchar(100) not NULL, user_type enum("regular","admin") default "regular", sprefs enum("all", "class", "overlap", "admin") not NULL, primary key(username) ) ENGINE = InnoDB; create table location( pid varchar(20) not NULL, city varchar(50), nearestcity varchar(50), state varchar(2), country varchar(60), primary key(pid), foreign key (pid) references user(username) on delete restrict on update cascade ) ENGINE = InnoDB; create table team( tname varchar(50) default '', `type` enum("Club", "League", "College"), nearestcity varchar(50), state varchar(2), country varchar(60), pid varchar(20) not NULL, primary key(tname, pid), foreign key (pid) references user(username) on delete restrict on update cascade ) ENGINE = InnoDB; create table industry( pid varchar(20) not NULL, iname enum("Government and Law", "Technology and Engineering", "Consulting and Finance", "Physical and Life Sciences", "Education and Nonprofit", "Health Professions", "") default "", primary key(iname, pid), foreign key (pid) references user(username) on delete restrict on update cascade ) ENGINE = InnoDB; create table messages( mid int auto_increment, sender varchar(20) not NULL, receiver varchar(20) not NULL, message varchar(140), receipt bit not NULL default 0, primary key(mid, sender, receiver), foreign key (sender) references user(username) on delete restrict on update cascade, foreign key (receiver) references user(username) on delete restrict on update cascade ) ENGINE = InnoDB; create table events( ename varchar(50) not NULL, city varchar(50), state varchar(2), country varchar(60), description varchar(140), edate date not NULL, approved bit, rsvps int default 0, pid varchar(20) not NULL, primary key(ename,edate), foreign key (pid) references user(username) on delete restrict on update cascade ) ENGINE = InnoDB; create table rsvps( uname varchar(20) not NULL, ename varchar(50), edate date, primary key(uname, ename, edate) ) ENGINE = InnoDB; create table feedback( fid int auto_increment, subject varchar(50), message varchar(140), edate date, pid varchar(20), primary key(fid), foreign key (pid) references user(username) on delete restrict on update cascade ) ENGINE = InnoDB; create table donation( did int auto_increment, pid varchar(20) not NULL, item enum("cleats", "uniform", "other"), description varchar(140), seen bit not NULL default 0, primary key(did), foreign key (pid) references user(username) on delete restrict on update cascade ) ENGINE = InnoDB; create table family( name varchar(30) default "", predecessor varchar(20), member varchar(20), primary key(name, member), foreign key (member) references user(username) on delete restrict on update cascade ) ENGINE = InnoDB; create table picfile ( pic varchar(20) primary key, filename varchar(50), foreign key (pic) references user(username) on delete cascade on update cascade ) ENGINE = InnoDB;
205ec4212255afeb02d35630c5722abb936c41d0
[ "Markdown", "SQL", "Python", "HTML" ]
27
HTML
cs304-fa18/semester-project-lounge
32726ffcf10b10bf60dbb2ff259d63a4fb599cf4
74c1d3037f8d7f06265e02dfa65d4985aece69bd
refs/heads/master
<repo_name>GelionPraim999/https-github.com-GelionPraim999--Functions-Arrays<file_sep>/Functions/main.cpp #include<iostream> #include<Windows.h> using namespace std; int Add(int a, int b); // Прототип функции int Sub(int a, int b); int Mul(int a, int b); double Div(int a, int b); void main() { setlocale(LC_ALL, "ru"); int a, b; cout << "Введите два числа : "; cin >> a >> b; int c = Add(a, b); cout << c << endl; cout << Sub(a, b) << endl; cout << Mul(a, b) << endl; cout << Div(a, b) << endl; } int Add(int a, int b)// Реализация {// Addition - Сложение int c = a + b; return c; } int Sub(int a, int b) {// Subtraction- Вычитание return a - b; } int Mul(int a, int b) {// Multiplication return a * b; } double Div(int a, int b) {// Division - Деление return (double) a / b; } <file_sep>/Arrays/main.cpp #include<iostream> using namespace std; void FillRand(int arr[], const unsigned int n);// Заполняет массив случайными числами void Print(int arr[], const unsigned int n); void ReversePrint(int arr[], const unsigned int n);//Выводит массив в обратном направлении int Sum (int arr[], const unsigned int n, int sum = 0); // Возвращает сумму элемента double Avg (int arr[],const unsigned int n); //Возвращает среднее арифмитическое массива int minValueIn (int arr[], const unsigned int n, int min);// Возвращает минимальное значение массива int maxValueIn (int arr[], const unsigned int n, int max); //Возвращает максимальное значение массива void Sort(int arr[], const unsigned int n);// Сортирует массив в порядке возрастания void main() { setlocale(LC_ALL, ""); const unsigned int n = 5; int arr[n]; int min = 0; int max = 0; FillRand(arr, n); cout << "Исходный массив: \t\t "; Print(arr, n); cout << "Вывод массива в обратном направлении: \t"; ReversePrint(arr, n); cout << "Сумма элементов массива : " << Sum (arr,n)<< endl; cout << "Среднее арефметическое элементов массива :\t" << Avg (arr, n)<< endl; cout << "Минимальное значение массива : \t " << minValueIn(arr, n, min)<< endl; cout << "Максимальное значение массива : \t" << maxValueIn(arr, n, max)<< endl; cout << "Массив в порядке возрастания :\t"; Sort(arr, n); } void FillRand(int arr[], const unsigned int n) { for (int i = 0; i < n; i++) { arr[i] = rand(); } } void Print(int arr[], const unsigned int n) { for (int i = 0; i < n; i++) { cout << arr[i] << "\t"; } cout << endl; } void ReversePrint(int arr[], const unsigned int n) { for (int i = n - 1; i >= 0; --i) { cout << arr[i] << " \t"; } cout << endl; } int Sum(int arr[], const unsigned int n, int sum ) { for (int i = 0; i < n; i++) { sum += arr[i]; } return sum; } double Avg(int arr[], const unsigned int n) { return (double)Sum(arr, n) / n; } int minValueIn(int arr[], const unsigned int n, int min) { min = arr[0]; for (int i = 0; i < n; i++) { if (min > arr[i]) min = arr[i]; } return min ; } int maxValueIn(int arr[], const unsigned int n, int max) { max = arr[0]; for (int i = 0; i < n; i++) { if (max < arr[i]) max = arr[i]; } return max; } void Sort(int arr[], const unsigned int n) { for (int i = 0; i < n; i++) { for (int j = n-1; j > i; j--) { if (arr[j] < arr[ j- 1]) { int temp = arr[j]; arr[j] = arr[j - 1]; arr[j - 1 ] = temp; } } } for (int i = 0; i < n; i++) { cout << arr[i] << "\t"; } cout << endl; }
716d4ab0379fe6bc3a846e4422cfe61724aa198f
[ "C++" ]
2
C++
GelionPraim999/https-github.com-GelionPraim999--Functions-Arrays
ddfa48bb814bf9276509cb6f29de35a37deff221
cc2b49b3198a7bb3b00c99acdc7a4335c87286a8
refs/heads/main
<repo_name>SWI-MIN/TESTTRYTRY<file_sep>/CODE/lab11-1 learning board 211208/Nu-LB-NUC140_BSP3.00.004_v1.2/SampleCode/Nu-LB-NUC140/Timer/main.c // // TMR_LED : change LED on/off by Timer1 interrupt // #include <stdio.h> #include "NUC100Series.h" #include "MCU_init.h" #include "SYS_init.h" #include <math.h> #include <string.h> #include "LCD.h" uint8_t ledState = 0; uint32_t keyin = 0; uint32_t i = 5; uint32_t j = 0; uint32_t x, y, z; char Text[16]; uint32_t u32ADCvalue; void Init_ADC(void) { } void TMR1_IRQHandler(void) { } void Init_Timer1(void) { } int main(void) { SYS_Init(); init_LCD(); clear_LCD(); PD14 = 0; Init_Timer1(); Init_ADC(); while(1) { if(keyin == 1) { } else if(keyin == 2) { } else if(keyin == 3) { } } }<file_sep>/CODE/lab9-1 learning board 211124/Library/NuMakerLib/Include/MLX90614.h #include "NUC100Series.h" #define MLX90614_I2CADDR 0x5A // RAM #define MLX90614_RAWIR1 0x04 #define MLX90614_RAWIR2 0x05 #define MLX90614_TA 0x06 #define MLX90614_TOBJ1 0x07 #define MLX90614_TOBJ2 0x08 // EEPROM #define MLX90614_TOMAX 0x20 #define MLX90614_TOMIN 0x21 #define MLX90614_PWMCTRL 0x22 #define MLX90614_TARANGE 0x23 #define MLX90614_EMISS 0x24 #define MLX90614_CONFIG 0x25 #define MLX90614_ADDR 0x0E #define MLX90614_ID1 0x3C #define MLX90614_ID2 0x3D #define MLX90614_ID3 0x3E #define MLX90614_ID4 0x3F extern float MLX90614_readObjectTempC(void); extern float MLX90614_readAmbientTempC(void); extern float MLX90614_readObjectTempF(void); extern float MLX90614_readAmbientTempF(void); extern uint16_t MLX90614_readID(uint8_t id); float readTemp(uint8_t reg); uint16_t read16(uint8_t reg); <file_sep>/CODE/lab9-1 learning board 211124/Library/Nu-LB-NUC140/Include/EEPROM.h // Global variables typedef void (*I2C_FUNC)(uint32_t u32Status); static I2C_FUNC s_I2C1HandlerFn = NULL; void I2C_MasterRx(uint32_t u32Status); void I2C_MasterTx(uint32_t u32Status); void Close_EEPROM(void); void Init_EEPROM(void); void EEPROM_Write(uint16_t addr, uint8_t data); uint8_t EEPROM_Read(uint16_t addr); <file_sep>/CODE/lab9-1 learning board 211124/Library/Nu-LB-NUC140/Source/W25Q16CV.c #include "stdio.h" #include "string.h" #include "NUC100Series.h" #include "SYS.h" #include "SPI.h" #include "W25Q16CV.h" void init_W25Q16(void) { SPI_Open(W25Q16_SPI_PORT, SPI_MASTER, SPI_MODE_0, 8, 500000); SPI_DisableAutoSS(W25Q16_SPI_PORT); SPI_SET_MSB_FIRST(W25Q16_SPI_PORT); } // Command void W25Q16_Command(uint8_t command) { SPI_SET_SS0_LOW(W25Q16_SPI_PORT); SPI_WRITE_TX0(W25Q16_SPI_PORT, command); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_SET_SS0_HIGH(W25Q16_SPI_PORT); } // Write Enable void W25Q16_WriteEnable(void) { W25Q16_Command(W25Q16_WRITE_ENABLE); } // Write Enable for Volatile Status Register void W25Q16_WriteEnableForVolatileStatusRegister(void) { W25Q16_Command(W25Q16_WRITE_ENABLE_FOR_VOLATILE_STATUS_REGISTER ); } // Write Disable void W25Q16_WriteDisable(void) { W25Q16_Command(W25Q16_WRITE_DISABLE ); } // Read Status Register 1 uint8_t W25Q16_ReadStatusRegister1(void) { uint32_t tmp; SPI_SET_SS0_LOW(W25Q16_SPI_PORT); SPI_WRITE_TX0(W25Q16_SPI_PORT, W25Q16_READ_STATUS_REGISTER1 ); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); tmp =W25Q16_SPI_PORT->RX[0]; SPI_SET_SS0_HIGH(W25Q16_SPI_PORT); return tmp; } // Read Status Register 2 uint8_t W25Q16_ReadStatusRegister2(void) { uint32_t tmp; SPI_SET_SS0_LOW(W25Q16_SPI_PORT); SPI_WRITE_TX0(W25Q16_SPI_PORT, W25Q16_READ_STATUS_REGISTER2 ); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); tmp = W25Q16_SPI_PORT->RX[0]; SPI_SET_SS0_HIGH(W25Q16_SPI_PORT); return tmp; } // Write Status Register void W25Q16_WriteStatusRegister(uint16_t u16data) { SPI_SET_SS0_LOW(W25Q16_SPI_PORT); SPI_WRITE_TX0(W25Q16_SPI_PORT, W25Q16_WRITE_STATUS_REGISTER ); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, u16data &0x00FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, u16data>>8); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_SET_SS0_HIGH(W25Q16_SPI_PORT); } // Page Program void W25Q16_PageProgram(uint32_t u24addr, uint8_t *data) { uint32_t i; SPI_SET_SS0_LOW(W25Q16_SPI_PORT); SPI_WRITE_TX0(W25Q16_SPI_PORT, W25Q16_PAGE_PROGRAM ); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, (u24addr>>16)&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, (u24addr>>8)&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, u24addr&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); for (i=0; i<strlen(data); i++) { SPI_WRITE_TX0(W25Q16_SPI_PORT, data[i]); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); } SPI_SET_SS0_HIGH(W25Q16_SPI_PORT); } // Sector Erase void W25Q16_SectorErase(uint32_t u24addr) { SPI_SET_SS0_LOW(W25Q16_SPI_PORT); SPI_WRITE_TX0(W25Q16_SPI_PORT, W25Q16_SECTOR_ERASE ); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, (u24addr>>16)&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, (u24addr>>8)&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, u24addr&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_SET_SS0_HIGH(W25Q16_SPI_PORT); } // Block Erase 32KB void W25Q16_BlockErase32KB(uint32_t u24addr) { SPI_SET_SS0_LOW(W25Q16_SPI_PORT); SPI_WRITE_TX0(W25Q16_SPI_PORT, W25Q16_BLOCK_ERASE_32KB ); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, (u24addr>>16)&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, (u24addr>>8)&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, u24addr&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_SET_SS0_HIGH(W25Q16_SPI_PORT); } // Block Erase 64KB void W25Q16_BlockErase64KB(uint32_t u24addr) { SPI_SET_SS0_LOW(W25Q16_SPI_PORT); SPI_WRITE_TX0(W25Q16_SPI_PORT, W25Q16_BLOCK_ERASE_64KB ); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, (u24addr>>16)&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, (u24addr>>8)&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, u24addr&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_SET_SS0_HIGH(W25Q16_SPI_PORT); } // Chip Erase void W25Q16_ChipErase(void) { W25Q16_Command(W25Q16_CHIP_ERASE); } // Erase Suspend void W25Q16_EraseSuspend(void) { W25Q16_Command(W25Q16_ERASE_SUSPEND); } // Erase Resume void W25Q16_EraseResume(void) { W25Q16_Command(W25Q16_ERASE_RESUME); } // Erase Resume void W25Q16_PowerDown(void) { W25Q16_Command(W25Q16_POWER_DOWN); } // Continuouse Read Mode Reset void W25Q16_ContinuouseReadModeReset(void) { SPI_SET_SS0_LOW(W25Q16_SPI_PORT); SPI_WRITE_TX0(W25Q16_SPI_PORT, W25Q16_CONTINUOUS_READ_MODE_RESET); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_SET_SS0_HIGH(W25Q16_SPI_PORT); } // Read Data uint8_t W25Q16_ReadData(uint32_t u24addr) { uint32_t tmp; SPI_SET_SS0_LOW(W25Q16_SPI_PORT); SPI_WRITE_TX0(W25Q16_SPI_PORT, W25Q16_READ_DATA ); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, (u24addr>>16)&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, (u24addr>>8)&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, u24addr&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); tmp = W25Q16_SPI_PORT->RX[0]; SPI_SET_SS0_HIGH(W25Q16_SPI_PORT); return tmp; } // Release Power Down / Device ID uint8_t W25Q16_ReleasePowerDown_DeviceID(void) { uint32_t tmp; SPI_SET_SS0_LOW(W25Q16_SPI_PORT); SPI_WRITE_TX0(W25Q16_SPI_PORT, W25Q16_RELEASE_PWRDN_DEVICE_ID ); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); tmp = W25Q16_SPI_PORT->RX[0]; SPI_SET_SS0_HIGH(W25Q16_SPI_PORT); return tmp; } // Read Manufacturer & Device ID uint16_t W25Q16_ReadManufacturerDeviceID(void) { uint32_t mf, id; SPI_SET_SS0_LOW(W25Q16_SPI_PORT); SPI_WRITE_TX0(W25Q16_SPI_PORT, W25Q16_MANUFACTURER_DEVICE_ID ); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0x00); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); mf = W25Q16_SPI_PORT->RX[0]; SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); id = W25Q16_SPI_PORT->RX[0]; SPI_SET_SS0_HIGH(W25Q16_SPI_PORT); return ((mf<<8)&0x0000FF00) | (id&0x00000000FF); } // Read JEDEC ID uint32_t W25Q16_ReadJEDECID(void) { uint32_t mf, tmp[2]; SPI_SET_SS0_LOW(W25Q16_SPI_PORT); SPI_WRITE_TX0(W25Q16_SPI_PORT, W25Q16_READ_JEDEC_ID ); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); mf = W25Q16_SPI_PORT->RX[0]; SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); tmp[1] = W25Q16_SPI_PORT->RX[0]; SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); tmp[0] = W25Q16_SPI_PORT->RX[0]; SPI_SET_SS0_HIGH(W25Q16_SPI_PORT); return ((mf<<16)&0x00FF0000) | ((tmp[1]<<8) & 0x0000FF00) | (tmp[0] & 0x000000FF); } // Read Unique ID uint8_t W25Q16_ReadUniqueID(void) { uint32_t id; SPI_SET_SS0_LOW(W25Q16_SPI_PORT); SPI_WRITE_TX0(W25Q16_SPI_PORT, W25Q16_READ_UNIQUE_ID ); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); id = W25Q16_SPI_PORT->RX[0]; SPI_SET_SS0_HIGH(W25Q16_SPI_PORT); return id; } // Read SFDP Register uint8_t W25Q16_ReadSFDPRegister(uint8_t addr) { uint32_t data; SPI_SET_SS0_LOW(W25Q16_SPI_PORT); SPI_WRITE_TX0(W25Q16_SPI_PORT, W25Q16_READ_SFDP_REGISTER ); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0x00); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0x00); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, addr); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); data = W25Q16_SPI_PORT->RX[0]; SPI_SET_SS0_HIGH(W25Q16_SPI_PORT); return data; } // Erase Security Registers void W25Q16_EraseSecurityRegisters(uint32_t u24addr) { SPI_SET_SS0_LOW(W25Q16_SPI_PORT); SPI_WRITE_TX0(W25Q16_SPI_PORT, W25Q16_ERASE_SECURITY_REGISTERS ); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, (u24addr>>16)&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, (u24addr>>8)&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, u24addr&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_SET_SS0_HIGH(W25Q16_SPI_PORT); } // Erase Security Registers void W25Q16_ProgramSecurityRegiters(uint32_t u24addr, uint8_t data) { SPI_SET_SS0_LOW(W25Q16_SPI_PORT); SPI_WRITE_TX0(W25Q16_SPI_PORT, W25Q16_PROGRAM_SECURITY_REGISTERS ); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, (u24addr>>16)&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, (u24addr>>8)&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, u24addr&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, data); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, data); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_SET_SS0_HIGH(W25Q16_SPI_PORT); } uint8_t W25Q16_ReadSecurityRegisters(uint32_t u24addr) { uint32_t data; SPI_SET_SS0_LOW(W25Q16_SPI_PORT); SPI_WRITE_TX0(W25Q16_SPI_PORT, W25Q16_READ_SECURITY_REGISTERS ); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, (u24addr>>16)&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, (u24addr>>8)&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, u24addr&0x000000FF); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); SPI_WRITE_TX0(W25Q16_SPI_PORT, 0xff); SPI_TRIGGER(W25Q16_SPI_PORT); while(SPI_IS_BUSY(W25Q16_SPI_PORT)); data = W25Q16_SPI_PORT->RX[0] & 0x000000FF; SPI_SET_SS0_HIGH(W25Q16_SPI_PORT); return data; } <file_sep>/CODE/lab9-1 learning board 211124/Library/NuMakerLib/Source/HMC5883L.c /* HMC5883L.cpp - Class file for the HMC5883L Triple Axis Digital Compass Arduino Library. Version: 1.1.0 (c) 2014 <NAME> www.jarzebski.pl This program is free software: you can redistribute it and/or modify it under the terms of the version 3 GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "HMC5883L.h" static uint8_t devAddr; float mgPerDigit; VecInt16 v; int xOffset, yOffset; bool HMC5883L_begin(void) { devAddr= HMC5883L_DEFAULT_ADDRESS; HMC5883L_setRange(HMC5883L_RANGE_1_3GA); HMC5883L_setMeasurementMode(HMC5883L_CONTINOUS); HMC5883L_setDataRate(HMC5883L_DATARATE_15HZ); HMC5883L_setSamples(HMC5883L_SAMPLES_1); mgPerDigit = 0.92f; return true; } VecInt16 HMC5883L_readRaw(void) { uint8_t data[2]; I2Cdev_readBytes(devAddr, HMC5883L_REG_OUT_X_H, 2, data); v.X = (data[0]<<8 | data[1]) - xOffset; I2Cdev_readBytes(devAddr, HMC5883L_REG_OUT_Y_H, 2, data); v.Y = (data[0]<<8 | data[1])- yOffset; I2Cdev_readBytes(devAddr, HMC5883L_REG_OUT_Z_H, 2, data); v.Z = (data[0]<<8 | data[1]); return v; } VecInt16 HMC5883L_readNormalize(void) { uint8_t data[2]; I2Cdev_readBytes(devAddr, HMC5883L_REG_OUT_X_H, 2, data); v.X = ((float)(data[0]<<8 | data[1]) - xOffset) * mgPerDigit; I2Cdev_readBytes(devAddr, HMC5883L_REG_OUT_Y_H, 2, data); v.Y = ((float)(data[0]<<8 | data[1]) - yOffset) * mgPerDigit; I2Cdev_readBytes(devAddr, HMC5883L_REG_OUT_Z_H, 2, data); v.Z = (float)(data[0]<<8 | data[1]) * mgPerDigit; return v; } void HMC5883L_setOffset(int xo, int yo) { xOffset = xo; yOffset = yo; } void HMC5883L_setRange(hmc5883l_range_t range) { switch(range) { case HMC5883L_RANGE_0_88GA: mgPerDigit = 0.073f; break; case HMC5883L_RANGE_1_3GA: mgPerDigit = 0.92f; break; case HMC5883L_RANGE_1_9GA: mgPerDigit = 1.22f; break; case HMC5883L_RANGE_2_5GA: mgPerDigit = 1.52f; break; case HMC5883L_RANGE_4GA: mgPerDigit = 2.27f; break; case HMC5883L_RANGE_4_7GA: mgPerDigit = 2.56f; break; case HMC5883L_RANGE_5_6GA: mgPerDigit = 3.03f; break; case HMC5883L_RANGE_8_1GA: mgPerDigit = 4.35f; break; default: break; } I2Cdev_writeByte(devAddr, HMC5883L_REG_CONFIG_B, range << 5); } hmc5883l_range_t HMC5883L_getRange(void) { uint8_t value; I2Cdev_readByte(devAddr,HMC5883L_REG_CONFIG_B, &value); return (hmc5883l_range_t)(value >> 5); } void HMC5883L_setMeasurementMode(hmc5883l_mode_t mode) { uint8_t value; I2Cdev_readByte(devAddr, HMC5883L_REG_MODE, &value); value &= 0xFC;//0b11111100; value |= mode; I2Cdev_writeByte(devAddr, HMC5883L_REG_MODE, value); } hmc5883l_mode_t HMC5883L_getMeasurementMode(void) { uint8_t value; I2Cdev_readByte(devAddr, HMC5883L_REG_MODE, &value); value &= 0x03; //0b00000011; return (hmc5883l_mode_t)value; } void HMC5883L_setDataRate(hmc5883l_dataRate_t dataRate) { uint8_t value; I2Cdev_readByte(devAddr, HMC5883L_REG_CONFIG_A, &value); value &= 0xE3;//0b11100011; value |= (dataRate << 2); I2Cdev_writeByte(devAddr, HMC5883L_REG_CONFIG_A, value); } hmc5883l_dataRate_t HMC5883L_getDataRate(void) { uint8_t value; I2Cdev_readByte(devAddr, HMC5883L_REG_CONFIG_A, &value); value &= 0x1C;//0b00011100; value >>= 2; return (hmc5883l_dataRate_t)value; } void HMC5883L_setSamples(hmc5883l_samples_t samples) { uint8_t value; I2Cdev_readByte(devAddr, HMC5883L_REG_CONFIG_A, &value); value &= 0x9F;//0b10011111; value |= (samples << 5); I2Cdev_writeByte(devAddr, HMC5883L_REG_CONFIG_A, value); } hmc5883l_samples_t HMC5883L_getSamples(void) { uint8_t value; I2Cdev_readByte(devAddr, HMC5883L_REG_CONFIG_A, &value); value &= 0xc0; //0b01100000; value >>= 5; return (hmc5883l_samples_t)value; } <file_sep>/CODE/lab9-1 learning board 211124/Library/NuMakerLib/Source/BMP085.c // // BMP085 Driver: Digital Pressure Sensor // // Interface: I2C (slave address = 0xEE) // pin1: Gnd (Ground) // pin2: EOC (End of Conversion) // pin3: Vdda (Analog Power Supply) // pin4: Vddd (Digital Power Supply) // pin5: NC (No Connection) // pin6: SCL (I2C Clock Input) // pin7: SDA (I2C Data) // pin8: XCLR (Master Clear Input, low-active) #include <stdio.h> #include <stdint.h> #include <math.h> #include "NUC100Series.h" #include "I2Cdev.h" #include "BMP085.h" const float p0 = 101325; // Pressure at sea level (Pa) short ac1, ac2, ac3; unsigned short ac4, ac5, ac6; short b1, b2, mb, mc, md; long x1, x2, x3, b3, b5, b6; unsigned long b4, b7; int16_t OSS =0; // over-sampling setting long p; int16_t BMP085_readword(uint8_t regAddr) { uint8_t data[2]; I2Cdev_readBytes(BMP085_devAddr, regAddr, 2, data); return data[0]<<8 | data[1]; } void BMP085_Calibration(void) { ac1=BMP085_readword(0xAA); ac2=BMP085_readword(0xAC); ac3=BMP085_readword(0xAE); ac4=BMP085_readword(0xB0); ac5=BMP085_readword(0xB2); ac6=BMP085_readword(0xB4); b1 =BMP085_readword(0xB6); b2 =BMP085_readword(0xB8); mb =BMP085_readword(0xBA); mc =BMP085_readword(0xBC); md =BMP085_readword(0xBE); } uint16_t BMP085_ReadUT(void) { uint8_t msb[1], lsb[1]; I2Cdev_writeByte(BMP085_devAddr, BMP085_CR, 0x2E); CLK_SysTickDelay(4500); I2Cdev_readByte(BMP085_devAddr, BMP085_MSB, msb); I2Cdev_readByte(BMP085_devAddr, BMP085_LSB, lsb); return ((msb[0]<<8) | lsb[0]); } uint32_t BMP085_ReadUP(void) { uint8_t msb[1], lsb[1], xsb[1]; uint8_t data; data=0x34+(OSS<<6); I2Cdev_writeByte(BMP085_devAddr, BMP085_CR, data); CLK_SysTickDelay(4500); I2Cdev_readByte(BMP085_devAddr, BMP085_MSB, msb); I2Cdev_readByte(BMP085_devAddr, BMP085_LSB, lsb); I2Cdev_readByte(BMP085_devAddr, BMP085_XSB, xsb); return( ( ((unsigned long)msb[0]<<16) + ((unsigned long)lsb[0]<<8) + (unsigned long)xsb[0] )>> (8-OSS)); } short BMP085_GetTemperature(uint16_t ut) { x1 = (((long)ut - (long)ac6)*(long)ac5)>>15; x2 = ((long)mc <<11)/(x1 + md); b5 = x1 + x2; return ((b5 + 8)>>4); } long BMP085_GetPressure(uint32_t up) { b6 = b5 - 4000; // Calculate B3 x1 = ((b2 * (b6 * b6))>>12)>>11; x2 = (ac2 * b6)>>11; x3 = x1 + x2; b3 = (((((long)ac1)*4 + x3)<<OSS) + 2)>>2; // Calculate B4 x1 = (ac3 * b6)>>13; x2 = (b1 * ((b6 * b6)>>12))>>16; x3 = ((x1 + x2) + 2)>>2; b4 = (ac4 * (unsigned long)(x3 + 32768))>>15; b7 = ((unsigned long)(up - b3) * (50000>>OSS)); if (b7 < 0x80000000) p = (b7<<1)/b4; else p = (b7/b4)<<1; x1 = (p>>8) * (p>>8); x1 = (x1 * 3038)>>16; x2 = (-7357 * p)>>16; p += (x1 + x2 + 3791)>>4; return p; } <file_sep>/CODE/lab9-1 learning board 211124/Library/Nu-LB-NUC140/Include/I2CDev.h #ifndef _I2CAPI_H #define _I2CAPI_H #include "NVT_I2C.h" int8_t I2Cdev_readBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t *data); int8_t I2Cdev_readByte(uint8_t devAddr, uint8_t regAddr, uint8_t *data); int8_t I2Cdev_readBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t *data); int8_t I2Cdev_readBit(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t *data); int8_t I2Cdev_readWords(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint16_t *data); bool I2Cdev_writeBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t* data); bool I2Cdev_writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t data); bool I2Cdev_writeBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t data); bool I2Cdev_writeBit(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t data); bool I2Cdev_writeWord(uint8_t devAddr, uint8_t regAddr, uint16_t data); #endif <file_sep>/CODE/lab9-1 learning board 211124/Library/NuMakerLib/Include/HMC5883L.h /* HMC5883L.h - Header file for the HMC5883L Triple Axis Digital Compass Arduino Library. Version: 1.1.0 (c) 2014 <NAME> www.jarzebski.pl This program is free software: you can redistribute it and/or modify it under the terms of the version 3 GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef HMC5883L_h #define HMC5883L_h #include "I2Cdev.h" #include <stdbool.h> #define HMC5883L_DEFAULT_ADDRESS 0x1E #define HMC5883L_REG_CONFIG_A 0x00 #define HMC5883L_REG_CONFIG_B 0x01 #define HMC5883L_REG_MODE 0x02 #define HMC5883L_REG_OUT_X_H 0x03 #define HMC5883L_REG_OUT_X_L 0x04 #define HMC5883L_REG_OUT_Z_H 0x05 #define HMC5883L_REG_OUT_Z_L 0x06 #define HMC5883L_REG_OUT_Y_H 0x07 #define HMC5883L_REG_OUT_Y_L 0x08 #define HMC5883L_REG_STATUS 0x09 #define HMC5883L_REG_IDENT_A 0x0A #define HMC5883L_REG_IDENT_B 0x0B #define HMC5883L_REG_IDENT_C 0x0C typedef enum { HMC5883L_SAMPLES_8 = 3,//0b11, HMC5883L_SAMPLES_4 = 2,//0b10, HMC5883L_SAMPLES_2 = 1,//0b01, HMC5883L_SAMPLES_1 = 0 //0b00 } hmc5883l_samples_t; typedef enum { HMC5883L_DATARATE_75HZ = 6,//0b110, HMC5883L_DATARATE_30HZ = 5,//0b101, HMC5883L_DATARATE_15HZ = 4,//0b100, HMC5883L_DATARATE_7_5HZ = 3,//0b011, HMC5883L_DATARATE_3HZ = 2,//0b010, HMC5883L_DATARATE_1_5HZ = 1,//0b001, HMC5883L_DATARATE_0_75_HZ = 0 //0b000 } hmc5883l_dataRate_t; typedef enum { HMC5883L_RANGE_8_1GA = 7,//0b111, HMC5883L_RANGE_5_6GA = 6,//0b110, HMC5883L_RANGE_4_7GA = 5,//0b101, HMC5883L_RANGE_4GA = 4,//0b100, HMC5883L_RANGE_2_5GA = 3,//0b011, HMC5883L_RANGE_1_9GA = 2,//0b010, HMC5883L_RANGE_1_3GA = 1,//0b001, HMC5883L_RANGE_0_88GA = 0 //0b000 } hmc5883l_range_t; typedef enum { HMC5883L_IDLE = 2,//0b10, HMC5883L_SINGLE = 1,//0b01, HMC5883L_CONTINOUS = 0 //0b00 } hmc5883l_mode_t; typedef struct { int16_t X; int16_t Y; int16_t Z; }VecInt16; bool HMC5883L_begin(void); VecInt16 HMC5883L_readRaw(void); VecInt16 HMC5883L_readNormalize(void); void HMC5883L_setOffset(int xo, int yo); void HMC5883L_setRange(hmc5883l_range_t range); hmc5883l_range_t HMC5883L_getRange(void); void HMC5883L_setMeasurementMode(hmc5883l_mode_t mode); hmc5883l_mode_t HMC5883L_getMeasurementMode(void); void HMC5883L_setDataRate(hmc5883l_dataRate_t dataRate); hmc5883l_dataRate_t HMC5883L_getDataRate(void); void HMC5883L_setSamples(hmc5883l_samples_t samples); hmc5883l_samples_t HMC5883L_getSamples(void); #endif <file_sep>/CODE/lab9-1 learning board 211124/Library/NuMakerLib/Include/Def.h #ifndef DEF_H_ #define DEF_H_ #include <stdbool.h> #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif #ifndef false #define false 0 #endif #ifndef true #define true 1 #endif #ifndef bool #define bool unsigned char #endif #endif //DEF_H_ <file_sep>/CODE/lab11-1 learning board 211208/Nu-LB-NUC140_BSP3.00.004_v1.2/SampleCode/Nu-LB-NUC140/Timer/MCU_init.h //Define Clock source #define MCU_CLOCK_SOURCE #define MCU_CLOCK_SOURCE_HXT // HXT, LXT, HIRC, LIRC #define MCU_CLOCK_FREQUENCY 50000000 //Hz //Define MCU Interfaces // LCD using SPI3 #define MCU_INTERFACE_SPI3 #define SPI3_CLOCK_SOURCE_HCLK // HCLK, PLL #define PIN_SPI3_SS0_PD8 #define PIN_SPI3_SCLK_PD9 #define PIN_SPI3_MISO0_PD10 #define PIN_SPI3_MOSI0_PD11 #define MCU_INTERFACE_UART0 #define UART_CLOCK_SOURCE_HXT // HXT, LXT, PLL, HIRC #define UART_CLOCK_DIVIDER 3 #define PIN_UART0_RX_PB0 #define PIN_UART0_TX_PB1 #define MCU_INTERFACE_TMR1 #define TMR1_CLOCK_SOURCE_HXT // HXT, LXT, HCLK, EXT, LIRC, HIRC #define TMR1_CLOCK_DIVIDER 1 #define TMR1_OPERATING_MODE TIMER_PERIODIC_MODE // ONESHOT, PERIODIC, TOGGLE, CONTINUOUS #define TMR1_OPERATING_FREQ 1 //Hz //Define Clock source #define MCU_CLOCK_SOURCE #define MCU_CLOCK_SOURCE_HXT // HXT, LXT, HIRC, LIRC #define MCU_CLOCK_FREQUENCY 50000000 //Hz //Define MCU Interfaces #define MCU_INTERFACE_TMR2 #define TMR2_CLOCK_SOURCE_HXT // HXT, LXT, HCLK, EXT, LIRC, HIRC #define TMR2_CLOCK_DIVIDER 12 #define TMR2_OPERATING_MODE TIMER_CONTINUOUS_MODE // ONESHOT, PERIODIC, TOGGLE, CONTINUOUS #define TMR2_OPERATING_FREQ 1000000 //Hz #define TMR2_EVENT_DETECTION TIMER_COUNTER_FALLING_EDGE // FALLING, RISING #define TMR2_CAPTURE_MODE TIMER_CAPTURE_FREE_COUNTING_MODE // FREE_COUNTING, COUNTER_RESET #define TMR2_CAPTURE_EDGE TIMER_CAPTURE_FALLING_AND_RISING_EDGE // FALLING, RISING, FALLING_AND_RISING #define PIN_TC2_PB2 // TC0_PB15, TC1_PE5, TC2_PB2, TC3_PB3 #define MCU_INTERFACE_SPI3 #define SPI3_CLOCK_SOURCE_HCLK // HCLK, PLL #define PIN_SPI3_SS0_PD8 #define PIN_SPI3_SCLK_PD9 #define PIN_SPI3_MISO0_PD10 #define PIN_SPI3_MOSI0_PD11 #define MCU_INTERFACE_ADC #define ADC_CLOCK_SOURCE_HXT // HXT, LXT, PLL, HIRC, HCLK #define ADC_CLOCK_DIVIDER 1 #define PIN_ADC7_PA7 #define ADC_CHANNEL_MASK ADC_CH_0_MASK | ADC_CH_1_MASK | ADC_CH_7_MASK #define ADC_INPUT_MODE ADC_INPUT_MODE_SINGLE_END // SINGLE_END, DIFFERENTIAL #define ADC_OPERATION_MODE ADC_OPERATION_MODE_CONTINUOUS // SINGLE, SINGLE_CYCLE, CONTINUOUS<file_sep>/CODE/lab9-1 learning board 211124/Library/NuMakerLib/Include/MPU9250.h #ifndef _MPU9250_H_ #define _MPU9250_H_ // Include the Invensense MPU9250 driver and DMP keys: #include <stdbool.h> #include "NUC100Series.h" #include "inv_mpu.h" #include "inv_mpu_dmp_motion_driver.h" // Optimally, these defines would be passed as compiler options, but Arduino // doesn't give us a great way to do that. #define MPU9250 #define AK8963_SECONDARY #define COMPASS_ENABLED enum mpu9250_register { MPU9250_SELF_TEST_X_GYRO = 0x00, MPU9250_SELF_TEST_Y_GYRO = 0x01, MPU9250_SELF_TEST_Z_GYRO = 0x02, MPU9250_SELF_TEST_X_ACCEL = 0x0D, MPU9250_SELF_TEST_Y_ACCEL = 0x0E, MPU9250_SELF_TEST_Z_ACCEL = 0x0F, MPU9250_XG_OFFSET_H = 0x13, MPU9250_XG_OFFSET_L = 0x14, MPU9250_YG_OFFSET_H = 0x15, MPU9250_YG_OFFSET_L = 0x16, MPU9250_ZG_OFFSET_H = 0x17, MPU9250_ZG_OFFSET_L = 0x18, MPU9250_SMPLRT_DIV = 0x19, MPU9250_CONFIG = 0x1A, MPU9250_GYRO_CONFIG = 0x1B, MPU9250_ACCEL_CONFIG = 0x1C, MPU9250_ACCEL_CONFIG_2 = 0x1D, MPU9250_LP_ACCEL_ODR = 0x1E, MPU9250_WOM_THR = 0x1F, MPU9250_FIFO_EN = 0x23, MPU9250_I2C_MST_CTRL = 0x24, MPU9250_I2C_SLV0_ADDR = 0x25, MPU9250_I2C_SLV0_REG = 0x26, MPU9250_I2C_SLV0_CTRL = 0x27, MPU9250_I2C_SLV1_ADDR = 0x28, MPU9250_I2C_SLV1_REG = 0x29, MPU9250_I2C_SLV1_CTRL = 0x2A, MPU9250_I2C_SLV2_ADDR = 0x2B, MPU9250_I2C_SLV2_REG = 0x2C, MPU9250_I2C_SLV2_CTRL = 0x2D, MPU9250_I2C_SLV3_ADDR = 0x2E, MPU9250_I2C_SLV3_REG = 0x2F, MPU9250_I2C_SLV3_CTRL = 0x30, MPU9250_I2C_SLV4_ADDR = 0x31, MPU9250_I2C_SLV4_REG = 0x32, MPU9250_I2C_SLV4_DO = 0x33, MPU9250_I2C_SLV4_CTRL = 0x34, MPU9250_I2C_SLV4_DI = 0x35, MPU9250_I2C_MST_STATUS = 0x36, MPU9250_INT_PIN_CFG = 0x37, MPU9250_INT_ENABLE = 0x38, MPU9250_INT_STATUS = 0x3A, MPU9250_ACCEL_XOUT_H = 0x3B, MPU9250_ACCEL_XOUT_L = 0x3C, MPU9250_ACCEL_YOUT_H = 0x3D, MPU9250_ACCEL_YOUT_L = 0x3E, MPU9250_ACCEL_ZOUT_H = 0x3F, MPU9250_ACCEL_ZOUT_L = 0x40, MPU9250_TEMP_OUT_H = 0x41, MPU9250_TEMP_OUT_L = 0x42, MPU9250_GYRO_XOUT_H = 0x43, MPU9250_GYRO_XOUT_L = 0x44, MPU9250_GYRO_YOUT_H = 0x45, MPU9250_GYRO_YOUT_L = 0x46, MPU9250_GYRO_ZOUT_H = 0x47, MPU9250_GYRO_ZOUT_L = 0x48, MPU9250_EXT_SENS_DATA_00 = 0x49, MPU9250_EXT_SENS_DATA_01 = 0x4A, MPU9250_EXT_SENS_DATA_02 = 0x4B, MPU9250_EXT_SENS_DATA_03 = 0x4C, MPU9250_EXT_SENS_DATA_04 = 0x4D, MPU9250_EXT_SENS_DATA_05 = 0x4E, MPU9250_EXT_SENS_DATA_06 = 0x4F, MPU9250_EXT_SENS_DATA_07 = 0x50, MPU9250_EXT_SENS_DATA_08 = 0x51, MPU9250_EXT_SENS_DATA_09 = 0x52, MPU9250_EXT_SENS_DATA_10 = 0x53, MPU9250_EXT_SENS_DATA_11 = 0x54, MPU9250_EXT_SENS_DATA_12 = 0x55, MPU9250_EXT_SENS_DATA_13 = 0x56, MPU9250_EXT_SENS_DATA_14 = 0x57, MPU9250_EXT_SENS_DATA_15 = 0x58, MPU9250_EXT_SENS_DATA_16 = 0x59, MPU9250_EXT_SENS_DATA_17 = 0x5A, MPU9250_EXT_SENS_DATA_18 = 0x5B, MPU9250_EXT_SENS_DATA_19 = 0x5C, MPU9250_EXT_SENS_DATA_20 = 0x5D, MPU9250_EXT_SENS_DATA_21 = 0x5E, MPU9250_EXT_SENS_DATA_22 = 0x5F, MPU9250_EXT_SENS_DATA_23 = 0x60, MPU9250_I2C_SLV0_DO = 0x63, MPU9250_I2C_SLV1_DO = 0x64, MPU9250_I2C_SLV2_DO = 0x65, MPU9250_I2C_SLV3_DO = 0x66, MPU9250_I2C_MST_DELAY_CTRL =0x67, MPU9250_SIGNAL_PATH_RESET = 0x68, MPU9250_MOT_DETECT_CTRL = 0x69, MPU9250_USER_CTRL = 0x6A, MPU9250_PWR_MGMT_1 = 0x6B, MPU9250_PWR_MGMT_2 = 0x6C, MPU9250_FIFO_COUNTH = 0x72, MPU9250_FIFO_COUNTL = 0x73, MPU9250_FIFO_R_W = 0x74, MPU9250_WHO_AM_I = 0x75, MPU9250_XA_OFFSET_H = 0x77, MPU9250_XA_OFFSET_L = 0x78, MPU9250_YA_OFFSET_H = 0x7A, MPU9250_YA_OFFSET_L = 0x7B, MPU9250_ZA_OFFSET_H = 0x7D, MPU9250_ZA_OFFSET_L = 0x7E }; enum interrupt_status_bits { INT_STATUS_RAW_DATA_RDY_INT = 0, INT_STATUS_FSYNC_INT = 3, INT_STATUS_FIFO_OVERFLOW_INT = 4, INT_STATUS_WOM_INT = 6, }; enum gyro_config_bits { GYRO_CONFIG_FCHOICE_B = 0, GYRO_CONFIG_GYRO_FS_SEL = 3, GYRO_CONFIG_ZGYRO_CTEN = 5, GYRO_CONFIG_YGYRO_CTEN = 6, GYRO_CONFIG_XGYRO_CTEN = 7, }; #define MPU9250_GYRO_FS_SEL_MASK 0x3 #define MPU9250_GYRO_FCHOICE_MASK 0x3 enum accel_config_bit { ACCEL_CONFIG_ACCEL_FS_SEL = 3, ACCEL_CONFIG_AZ_ST_EN = 5, ACCEL_CONFIG_AY_ST_EN = 6, ACCEL_CONFIG_AX_ST_EN = 7, }; #define MPU9250_ACCEL_FS_SEL_MASK 0x3 enum accel_config_2_bits { ACCEL_CONFIG_2_A_DLPFCFG = 0, ACCEL_CONFIG_2_ACCEL_FCHOICE_B = 3, }; enum pwr_mgmt_1_bits { PWR_MGMT_1_CLKSEL = 0, PWR_MGMT_1_PD_PTAT = 3, PWR_MGMT_1_GYRO_STANDBY = 4, PWR_MGMT_1_CYCLE = 5, PWR_MGMT_1_SLEEP = 6, PWR_MGMT_1_H_RESET = 7 }; enum pwr_mgmt_2_bits { PWR_MGMT_2_DISABLE_ZG = 0, PWR_MGMT_2_DISABLE_YG = 1, PWR_MGMT_2_DISABLE_XG = 2, PWR_MGMT_2_DISABLE_ZA = 3, PWR_MGMT_2_DISABLE_YA = 4, PWR_MGMT_2_DISABLE_XA = 5, }; enum int_enable_bits { INT_ENABLE_RAW_RDY_EN = 0, INT_ENABLE_FSYNC_INT_EN = 3, INT_ENABLE_FIFO_OVERFLOW_EN = 4, INT_ENABLE_WOM_EN = 6, }; enum int_pin_cfg_bits { INT_PIN_CFG_BYPASS_EN = 1, INT_PIN_CFG_FSYNC_INT_MODE_EN = 2, INT_PIN_CFG_ACTL_FSYNC = 3, INT_PIN_CFG_INT_ANYRD_2CLEAR = 4, INT_PIN_CFG_LATCH_INT_EN = 5, INT_PIN_CFG_OPEN = 6, INT_PIN_CFG_ACTL = 7, }; #define INT_PIN_CFG_INT_MASK 0xF0 #define MPU9250_WHO_AM_I_RESULT 0x71 enum ak8963_register { AK8963_WIA = 0x0, AK8963_INFO = 0x1, AK8963_ST1 = 0x2, AK8963_HXL = 0x3, AK8963_HXH = 0x4, AK8963_HYL = 0x5, AK8963_HYH = 0x6, AK8963_HZL = 0x7, AK8963_HZH = 0x8, AK8963_ST2 = 0x9, AK8963_CNTL = 0xA, AK8963_RSV = 0xB, AK8963_ASTC = 0xC, AK8963_TS1 = 0xD, AK8963_TS2 = 0xE, AK8963_I2CDIS = 0xF, AK8963_ASAX = 0x10, AK8963_ASAY = 0x11, AK8963_ASAZ = 0x12, }; #define MAG_CTRL_OP_MODE_MASK 0xF #define AK8963_ST1_DRDY_BIT 0 #define AK8963_WHO_AM_I_RESULT 0x48 typedef int inv_error_t; #define INV_SUCCESS 0 #define INV_ERROR 0x20 enum t_axisOrder { X_AXIS, // 0 Y_AXIS, // 1 Z_AXIS // 2 }; // Define's passed to update(), to request a specific sensor (or multiple): #define UPDATE_ACCEL (1<<1) #define UPDATE_GYRO (1<<2) #define UPDATE_COMPASS (1<<3) #define UPDATE_TEMP (1<<4) #define INT_ACTIVE_HIGH 0 #define INT_ACTIVE_LOW 1 #define INT_LATCHED 1 #define INT_50US_PULSE 0 #define MAX_DMP_SAMPLE_RATE 200 // Maximum sample rate for the DMP FIFO (200Hz) #define FIFO_BUFFER_SIZE 512 // Max FIFO buffer size #define ORIENT_PORTRAIT 0 #define ORIENT_LANDSCAPE 1 #define ORIENT_REVERSE_PORTRAIT 2 #define ORIENT_REVERSE_LANDSCAPE 3 typedef struct{ int ax, ay, az; int gx, gy, gz; int mx, my, mz; long qw, qx, qy, qz; long temperature; unsigned long time; float pitch, roll, yaw; float heading; }VectorIMU; extern VectorIMU imu; // begin(void) -- Verifies communication with the MPU-9250 and the AK8963, // and initializes them to the default state: // All sensors enabled // Gyro FSR: +/- 2000 dps // Accel FSR: +/- 2g // LPF: 42 Hz // FIFO: 50 Hz, disabled // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_begin(void); // setSensors(unsigned char) -- Turn on or off MPU-9250 sensors. Any of the // following defines can be combined: INV_XYZ_GYRO, INV_XYZ_ACCEL, // INV_XYZ_COMPASS, INV_X_GYRO, INV_Y_GYRO, or INV_Z_GYRO // Input: Combination of enabled sensors. Unless specified a sensor will be // disabled. // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_setSensors(unsigned char sensors); // setGyroFSR(unsigned short) -- Sets the full-scale range of the gyroscope // Input: Gyro DPS - 250, 500, 1000, or 2000 // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_setGyroFSR(unsigned short fsr); // getGyroFSR -- Returns the current gyroscope FSR // Output: Current Gyro DPS - 250, 500, 1000, or 2000 unsigned short MPU9250_getGyroFSR(void); // getGyroSens -- Returns current gyroscope sensitivity. The FSR divided by // the resolution of the sensor (signed 16-bit). // Output: Currently set gyroscope sensitivity (e.g. 131, 65.5, 32.8, 16.4) float MPU9250_getGyroSens(void); // setAccelFSR(unsigned short) -- Sets the FSR of the accelerometer // // Input: Accel g range - 2, 4, 8, or 16 // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_setAccelFSR(unsigned char fsr); // getAccelFSR -- Returns the current accelerometer FSR // Output: Current Accel g - 2, 4, 8, or 16 unsigned char MPU9250_getAccelFSR(void); // getAccelSens -- Returns current accelerometer sensitivity. The FSR // divided by the resolution of the sensor (signed 16-bit). // Output: Currently set accel sensitivity (e.g. 16384, 8192, 4096, 2048) float MPU9250_getAccelSens(void); // getMagFSR -- Returns the current magnetometer FSR // Output: Current mag uT range - +/-1450 uT unsigned short MPU9250_getMagFSR(void); // getMagSens -- Returns current magnetometer sensitivity. The FSR // divided by the resolution of the sensor (signed 16-bit). // Output: Currently set mag sensitivity (e.g. 0.15) float MPU9250_getMagSens(void); // setLPF -- Sets the digital low-pass filter of the accel and gyro. // Can be any of the following: 188, 98, 42, 20, 10, 5 (value in Hz) // Input: 188, 98, 42, 20, 10, or 5 (defaults to 5 if incorrectly set) // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_setLPF(unsigned short lpf); // getLPF -- Returns the set value of the LPF. // // Output: 5, 10, 20, 42, 98, or 188 if set. 0 if the LPF is disabled. unsigned short MPU9250_getLPF(void); // setSampleRate -- Set the gyroscope and accelerometer sample rate to a // value between 4Hz and 1000Hz (1kHz). // The library will make an attempt to get as close as possible to the // requested sample rate. // Input: Value between 4 and 1000, indicating the desired sample rate // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_setSampleRate(unsigned short rate); // getSampleRate -- Get the currently set sample rate. // May differ slightly from what was set in setSampleRate. // Output: set sample rate of the accel/gyro. A value between 4-1000. unsigned short MPU9250_getSampleRate(void); // setCompassSampleRate -- Set the magnetometer sample rate to a value // between 1Hz and 100 Hz. // The library will make an attempt to get as close as possible to the // requested sample rate. // Input: Value between 1 and 100, indicating the desired sample rate // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_setCompassSampleRate(unsigned short rate); // getCompassSampleRate -- Get the currently set magnetometer sample rate. // May differ slightly from what was set in setCompassSampleRate. // // Output: set sample rate of the magnetometer. A value between 1-100 unsigned short MPU9250_getCompassSampleRate(void); // dataReady -- checks to see if new accel/gyro data is available. // (New magnetometer data cannot be checked, as the library runs that sensor // in single-conversion mode.) // Output: true if new accel/gyro data is available bool MPU9250_dataReady(void); // update -- Reads latest data from the MPU-9250's data registers. // Sensors to be updated can be set using the [sensors] parameter. // [sensors] can be any combination of UPDATE_ACCEL, UPDATE_GYRO, // UPDATE_COMPASS, and UPDATE_TEMP. // Output: INV_SUCCESS (0) on success, otherwise error // Note: after a successful update the public sensor variables // (e.g. ax, ay, az, gx, gy, gz) will be updated with new data //Usage: MPU9250_update( UPDATE_ACCEL | UPDATE_GYRO | UPDATE_COMPASS); inv_error_t MPU9250_update(unsigned char sensors); // updateAccel, updateGyro, updateCompass, and updateTemperature are // called by the update() public method. They read from their respective // sensor and update the class variable (e.g. ax, ay, az) // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_updateAccel(void); inv_error_t MPU9250_updateGyro(void); inv_error_t MPU9250_updateCompass(void); inv_error_t MPU9250_updateTemperature(void); // configureFifo(unsigned char) -- Initialize the FIFO, set it to read from // a select set of sensors. // Any of the following defines can be combined for the [sensors] parameter: // INV_XYZ_GYRO, INV_XYZ_ACCEL, INV_X_GYRO, INV_Y_GYRO, or INV_Z_GYRO // Input: Combination of sensors to be read into FIFO // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t configureFifo(unsigned char sensors); // getFifoConfig -- Returns the sensors configured to be read into the FIFO // Output: combination of INV_XYZ_GYRO, INV_XYZ_ACCEL, INV_Y_GYRO, // INV_X_GYRO, or INV_Z_GYRO unsigned char MPU9250_getFifoConfig(void); // fifoAvailable -- Returns the number of bytes currently filled in the FIFO // Outputs: Number of bytes filled in the FIFO (up to 512) unsigned short MPU9250_fifoAvailable(void); // updateFifo -- Reads from the top of the FIFO, and stores the new data // in ax, ay, az, gx, gy, or gz (depending on how the FIFO is configured). // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_updateFifo(void); // resetFifo -- Resets the FIFO's read/write pointers // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_resetFifo(void); // enableInterrupt -- Configure the MPU-9250's interrupt output to indicate // when new data is ready. // Input: 0 to disable, >=1 to enable // Output: INV_SUCCESS (0) on success, otherwise error // Usage: inv_error_t MPU9250_enableInterrupt(1); inv_error_t MPU9250_enableInterrupt(unsigned char enable); // setIntLevel -- Configure the MPU-9250's interrupt to be either active- // high or active-low. // Input: 0 for active-high, 1 for active-low // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_setIntLevel(unsigned char active_low); // setIntLatched -- Configure the MPU-9250's interrupt to latch or operate // as a 50us pulse. // Input: 0 for // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_setIntLatched(unsigned char enable); // getIntStatus -- Reads the MPU-9250's INT_STATUS register, which can // indicate what (if anything) caused an interrupt (e.g. FIFO overflow or // or data read). // Output: contents of the INT_STATUS register short MPU9250_getIntStatus(void); // dmpBegin -- Initialize the DMP, enable one or more features, and set the FIFO's sample rate // features can be any one of // DMP_FEATURE_TAP -- Tap detection // DMP_FEATURE_ANDROID_ORIENT -- Orientation (portrait/landscape) detection // DMP_FEATURE_LP_QUAT -- Accelerometer, low-power quaternion calculation // DMP_FEATURE_PEDOMETER -- Pedometer (always enabled) // DMP_FEATURE_6X_LP_QUAT -- 6-axis (accel/gyro) quaternion calculation // DMP_FEATURE_GYRO_CAL -- Gyroscope calibration (0's out after 8 seconds of no motion) // DMP_FEATURE_SEND_RAW_ACCEL -- Send raw accelerometer values to FIFO // DMP_FEATURE_SEND_RAW_GYRO -- Send raw gyroscope values to FIFO // DMP_FEATURE_SEND_CAL_GYRO -- Send calibrated gyroscop values to FIFO // fifoRate can be anywhere between 4 and 200Hz. // Input: OR'd list of features and requested FIFO sampling rate // Output: INV_SUCCESS (0) on success, otherwise error // Usage: MPU9250_dmpBegin(0, MAX_DMP_SAMPLE_RATE); inv_error_t MPU9250_dmpBegin(unsigned short features, unsigned short fifoRate); // dmpLoad -- Loads the DMP with 3062-byte image memory. Must be called to begin DMP. // This function is called by the dmpBegin function. // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_dmpLoad(void); // dmpGetFifoRate -- Returns the sample rate of the FIFO // Output: Set sample rate, in Hz, of the FIFO unsigned short MPU9250_dmpGetFifoRate(void); // dmpSetFiFoRate -- Sets the rate of the FIFO. // Input: Requested sample rate in Hz (range: 4-200) // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_dmpSetFifoRate(unsigned short rate); // dmpUpdateFifo -- Reads from the top of the FIFO and fills accelerometer, gyroscope, // quaternion, and time public variables (depending on how the DMP is configured). // Should be called whenever an MPU interrupt is detected // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_dmpUpdateFifo(void); // dmpEnableFeatures -- Enable one, or multiple DMP features. // Input: An OR'd list of features (see dmpBegin) // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_dmpEnableFeatures(unsigned short mask); // dmpGetEnabledFeatures -- Returns the OR'd list of enabled DMP features // // Output: OR'd list of DMP feature's (see dmpBegin for list) unsigned short MPU9250_dmpGetEnabledFeatures(void); // dmpSetTap -- Enable tap detection and configure threshold, tap time, and minimum tap count. // Inputs: x/y/zThresh - accelerometer threshold on each axis. Range: 0 to 1600. 0 disables tap // detection on that axis. Units are mg/ms. // taps - minimum number of taps to create a tap event (Range: 1-4) // tapTime - Minimum number of milliseconds between separate taps // tapMulti - Maximum number of milliseconds combined taps // Output: INV_SUCCESS (0) on success, otherwise error // Usage: MPU9250_dmpSetTap(250, 250, 250, 1, 100, 500); inv_error_t MPU9250_dmpSetTap(unsigned short xThresh, unsigned short yThresh, unsigned short zThresh, unsigned char taps, unsigned short tapTime, unsigned short tapMulti); // tapAvailable -- Returns true if a new tap is available // Output: True if new tap data is available. Cleared on getTapDir or getTapCount. bool MPU9250_tapAvailable(void); // getTapDir -- Returns the tap direction. // Output: One of the following: TAP_X_UP, TAP_X_DOWN, TAP_Y_UP, TAP_Y_DOWN, TAP_Z_UP, // or TAP_Z_DOWN unsigned char MPU9250_getTapDir(void); // getTapCount -- Returns the number of taps in the sensed direction // Output: Value between 1-8 indicating successive number of taps sensed. unsigned char MPU9250_getTapCount(void); // dmpSetOrientation -- Set orientation matrix, used for orientation sensing. // Use defaultOrientation matrix as an example input. // Input: Gyro and accel orientation in body frame (9-byte array) // Output: INV_SUCCESS (0) on success, otherwise error // UsagE: MPU9250_dmpSetOrientation(defaultOrientation); inv_error_t MPU9250_dmpSetOrientation(const signed char * orientationMatrix); // dmpGetOrientation -- Get the orientation, if any. // Output: If an orientation is detected, one of ORIENT_LANDSCAPE, ORIENT_PORTRAIT, // ORIENT_REVERSE_LANDSCAPE, or ORIENT_REVERSE_PORTRAIT. unsigned char MPU9250_MPU9250_dmpGetOrientation(void); // dmpEnable3Quat -- Enable 3-axis quaternion calculation // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_dmpEnable3Quat(void); // dmpEnable6Quat -- Enable 6-axis quaternion calculation // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_dmpEnable6Quat(void); // dmpGetPedometerSteps -- Get number of steps in pedometer register // Output: Number of steps sensed unsigned long MPU9250_dmpGetPedometerSteps(void); // dmpSetPedometerSteps -- Set number of steps to a value // Input: Desired number of steps to begin incrementing from // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t dmpSetPedometerSteps(unsigned long steps); // dmpGetPedometerTime -- Get number of milliseconds ellapsed over stepping // Output: Number of milliseconds where steps were detected unsigned long MPU9250_dmpGetPedometerTime(void); // dmpSetPedometerTime -- Set number time to begin incrementing step time counter from // Input: Desired number of milliseconds // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_dmpSetPedometerTime(unsigned long time); // dmpSetInterruptMode -- // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_dmpSetInterruptMode(unsigned char mode); // dmpSetGyroBias -- // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_dmpSetGyroBias(long * bias); // dmpSetAccelBias -- // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_dmpSetAccelBias(long * bias); // lowPowerAccel -- // Output: INV_SUCCESS (0) on success, otherwise error inv_error_t MPU9250_lowPowerAccel(unsigned short rate); // calcAccel -- Convert 16-bit signed acceleration value to g's float MPU9250_calcAccel(int axis); // calcGyro -- Convert 16-bit signed gyroscope value to degree's per second float MPU9250_calcGyro(int axis); // calcMag -- Convert 16-bit signed magnetometer value to microtesla (uT) float MPU9250_calcMag(int axis); // calcQuat -- Convert Q30-format quaternion to a vector between +/- 1 float MPU9250_calcQuat(long axis); // computeEulerAngles -- Compute euler angles based on most recently read qw, qx, qy, and qz // Input: boolean indicating whether angle results are presented in degrees or radians // Output: class variables roll, pitch, and yaw will be updated on exit. // Usage: MPU9250_computeEulerAngles(true); void MPU9250_computeEulerAngles(bool degrees); // computeCompassHeading -- Compute heading based on most recently read mx, my, and mz values // Output: class variable heading will be updated on exit float MPU9250_computeCompassHeading(void); // selfTest -- Run gyro and accel self-test. // Output: Returns bit mask, 1 indicates success. A 0x7 is success on all sensors. // Bit pos 0: gyro // Bit pos 1: accel // Bit pos 2: mag // Usage: MPU9250_selfTest(0); int MPU9250_selfTest(unsigned char debug); // Convert a QN-format number to a float float qToFloat(long number, unsigned char q); unsigned short orientation_row_2_scale(const signed char *row); #endif // _MPU9250_H_ <file_sep>/CODE/lab9-1 learning board 211124/Library/NuMakerLib/Source/MPU9250.c #include <Stdbool.h> #include <math.h> #include "MPU9250.h" #include "inv_mpu.h" #define PI 3.14159265359 float _mSense = 6.665f; // Constant - 4915 / 32760 float _aSense = 0.0f; // Updated after accel FSR is set float _gSense = 0.0f; // Updated after gyro FSR is set static unsigned char orientation; static unsigned char tap_count; static unsigned char tap_direction; static bool _tap_available; static void orient_cb(unsigned char orient); static void tap_cb(unsigned char direction, unsigned char count); VectorIMU imu; const signed char defaultOrientation[9] = { 1, 0, 0, 0, 1, 0, 0, 0, 1 }; inv_error_t MPU9250_begin(void) { inv_error_t result; struct int_param_s int_param; result = mpu_init(&int_param); if (result) return result; mpu_set_bypass(1); // Place all slaves (including compass) on primary bus MPU9250_setSensors(INV_XYZ_GYRO | INV_XYZ_ACCEL | INV_XYZ_COMPASS); _gSense = MPU9250_getGyroSens(); _aSense = MPU9250_getAccelSens(); return result; } inv_error_t MPU9250_enableInterrupt(unsigned char enable) { return 0; } inv_error_t MPU9250_setIntLevel(unsigned char active_low) { return mpu_set_int_level(active_low); } inv_error_t MPU9250_setIntLatched(unsigned char enable) { return mpu_set_int_latched(enable); } short MPU9250_getIntStatus(void) { short status; if (mpu_get_int_status(&status) == INV_SUCCESS) { return status; } return 0; } // Accelerometer Low-Power Mode. Rate options: // 1.25 (1), 2.5 (2), 5, 10, 20, 40, // 80, 160, 320, or 640 Hz // Disables compass and gyro inv_error_t MPU9250_lowPowerAccel(unsigned short rate) { return mpu_lp_accel_mode(rate); } inv_error_t MPU9250_setGyroFSR(unsigned short fsr) { inv_error_t err; err = mpu_set_gyro_fsr(fsr); if (err == INV_SUCCESS) { _gSense = MPU9250_getGyroSens(); } return err; } inv_error_t MPU9250_setAccelFSR(unsigned char fsr) { inv_error_t err; err = mpu_set_accel_fsr(fsr); if (err == INV_SUCCESS) { _aSense = MPU9250_getAccelSens(); } return err; } unsigned short MPU9250_getGyroFSR(void) { unsigned short tmp; if (mpu_get_gyro_fsr(&tmp) == INV_SUCCESS) { return tmp; } return 0; } unsigned char MPU9250_getAccelFSR(void) { unsigned char tmp; if (mpu_get_accel_fsr(&tmp) == INV_SUCCESS) { return tmp; } return 0; } unsigned short MPU9250_getMagFSR(void) { unsigned short tmp; if (mpu_get_compass_fsr(&tmp) == INV_SUCCESS) { return tmp; } return 0; } inv_error_t MPU9250_setLPF(unsigned short lpf) { return mpu_set_lpf(lpf); } unsigned short MPU9250_getLPF(void) { unsigned short tmp; if (mpu_get_lpf(&tmp) == INV_SUCCESS) { return tmp; } return 0; } inv_error_t MPU9250_setSampleRate(unsigned short rate) { return mpu_set_sample_rate(rate); } unsigned short MPU9250_getSampleRate(void) { unsigned short tmp; if (mpu_get_sample_rate(&tmp) == INV_SUCCESS) { return tmp; } return 0; } inv_error_t MPU9250_setCompassSampleRate(unsigned short rate) { return mpu_set_compass_sample_rate(rate); } unsigned short MPU9250_getCompassSampleRate(void) { unsigned short tmp; if (mpu_get_compass_sample_rate(&tmp) == INV_SUCCESS) { return tmp; } return 0; } float MPU9250_getGyroSens(void) { float sens; if (mpu_get_gyro_sens(&sens) == INV_SUCCESS) { return sens; } return 0; } float MPU9250_getAccelSens(void) { unsigned short sens; if (mpu_get_accel_sens(&sens) == INV_SUCCESS) { return (float)sens; } return 0; } float MPU9250_getMagSens(void) { return 0.15; // Static, 4915/32760 } unsigned char MPU9250_getFifoConfig(void) { unsigned char sensors; if (mpu_get_fifo_config(&sensors) == INV_SUCCESS) { return sensors; } return 0; } inv_error_t MPU9250_configureFifo(unsigned char sensors) { return mpu_configure_fifo(sensors); } inv_error_t MPU9250_resetFifo(void) { return mpu_reset_fifo(); } unsigned short MPU9250_fifoAvailable(void) { unsigned char fifoH, fifoL; if (mpu_read_reg(MPU9250_FIFO_COUNTH, &fifoH) != INV_SUCCESS) return 0; if (mpu_read_reg(MPU9250_FIFO_COUNTL, &fifoL) != INV_SUCCESS) return 0; return (fifoH << 8 ) | fifoL; } inv_error_t MPU9250_updateFifo(void) { short gyro[3], accel[3]; unsigned long timestamp; unsigned char sensors, more; if (mpu_read_fifo(gyro, accel, &timestamp, &sensors, &more) != INV_SUCCESS) return INV_ERROR; if (sensors & INV_XYZ_ACCEL) { imu.ax = accel[X_AXIS]; imu.ay = accel[Y_AXIS]; imu.az = accel[Z_AXIS]; } if (sensors & INV_X_GYRO) imu.gx = gyro[X_AXIS]; if (sensors & INV_Y_GYRO) imu.gy = gyro[Y_AXIS]; if (sensors & INV_Z_GYRO) imu.gz = gyro[Z_AXIS]; imu.time = timestamp; return INV_SUCCESS; } inv_error_t MPU9250_setSensors(unsigned char sensors) { return mpu_set_sensors(sensors); } bool MPU9250_dataReady(void) { unsigned char intStatusReg; if (mpu_read_reg(MPU9250_INT_STATUS, &intStatusReg) == INV_SUCCESS) { return (intStatusReg & (1<<INT_STATUS_RAW_DATA_RDY_INT)); } return false; } inv_error_t MPU9250_update(unsigned char sensors) { inv_error_t aErr = INV_SUCCESS; inv_error_t gErr = INV_SUCCESS; inv_error_t mErr = INV_SUCCESS; inv_error_t tErr = INV_SUCCESS; if (sensors & UPDATE_ACCEL) aErr = MPU9250_updateAccel(); if (sensors & UPDATE_GYRO) gErr = MPU9250_updateGyro(); if (sensors & UPDATE_COMPASS) mErr = MPU9250_updateCompass(); if (sensors & UPDATE_TEMP) tErr = MPU9250_updateTemperature(); return aErr | gErr | mErr | tErr; } int MPU9250_updateAccel(void) { short data[3]; if (mpu_get_accel_reg(data, &imu.time)) { return INV_ERROR; } imu.ax = data[X_AXIS]; imu.ay = data[Y_AXIS]; imu.az = data[Z_AXIS]; return INV_SUCCESS; } int MPU9250_updateGyro(void) { short data[3]; if (mpu_get_gyro_reg(data, &imu.time)) { return INV_ERROR; } imu.gx = data[X_AXIS]; imu.gy = data[Y_AXIS]; imu.gz = data[Z_AXIS]; return INV_SUCCESS; } int MPU9250_updateCompass(void) { short data[3]; if (mpu_get_compass_reg(data, &imu.time)) { return INV_ERROR; } imu.mx = data[X_AXIS]; imu.my = data[Y_AXIS]; imu.mz = data[Z_AXIS]; return INV_SUCCESS; } inv_error_t MPU9250_updateTemperature(void) { return mpu_get_temperature(&imu.temperature, &imu.time); } int MPU9250_selfTest(unsigned char debug) { long gyro[3], accel[3]; return mpu_run_self_test(gyro, accel); } inv_error_t MPU9250_dmpBegin(unsigned short features, unsigned short fifoRate) { unsigned short feat = features; unsigned short rate = fifoRate; if (MPU9250_dmpLoad() != INV_SUCCESS) return INV_ERROR; // 3-axis and 6-axis LP quat are mutually exclusive. // If both are selected, default to 3-axis if (feat & DMP_FEATURE_LP_QUAT) { feat &= ~(DMP_FEATURE_6X_LP_QUAT); dmp_enable_lp_quat(1); } else if (feat & DMP_FEATURE_6X_LP_QUAT) dmp_enable_6x_lp_quat(1); if (feat & DMP_FEATURE_GYRO_CAL) dmp_enable_gyro_cal(1); if (MPU9250_dmpEnableFeatures(feat) != INV_SUCCESS) return INV_ERROR; if (rate>200) rate=200; if (MPU9250_dmpSetFifoRate(rate) != INV_SUCCESS) return INV_ERROR; return mpu_set_dmp_state(1); } inv_error_t MPU9250_dmpLoad(void) { return dmp_load_motion_driver_firmware(); } unsigned short MPU9250_dmpGetFifoRate(void) { unsigned short rate; if (dmp_get_fifo_rate(&rate) == INV_SUCCESS) return rate; return 0; } inv_error_t MPU9250_dmpSetFifoRate(unsigned short rate) { if (rate > MAX_DMP_SAMPLE_RATE) rate = MAX_DMP_SAMPLE_RATE; return dmp_set_fifo_rate(rate); } inv_error_t MPU9250_dmpUpdateFifo(void) { short gyro[3]; short accel[3]; long quat[4]; unsigned long timestamp; short sensors; unsigned char more; if (dmp_read_fifo(gyro, accel, quat, &timestamp, &sensors, &more) != INV_SUCCESS) { return INV_ERROR; } if (sensors & INV_XYZ_ACCEL) { imu.ax = accel[X_AXIS]; imu.ay = accel[Y_AXIS]; imu.az = accel[Z_AXIS]; } if (sensors & INV_X_GYRO) imu.gx = gyro[X_AXIS]; if (sensors & INV_Y_GYRO) imu.gy = gyro[Y_AXIS]; if (sensors & INV_Z_GYRO) imu.gz = gyro[Z_AXIS]; if (sensors & INV_WXYZ_QUAT) { imu.qw = quat[0]; imu.qx = quat[1]; imu.qy = quat[2]; imu.qz = quat[3]; } imu.time = timestamp; return INV_SUCCESS; } inv_error_t MPU9250_dmpEnableFeatures(unsigned short mask) { unsigned short enMask = 0; enMask |= mask; // Combat known issue where fifo sample rate is incorrect // unless tap is enabled in the DMP. enMask |= DMP_FEATURE_TAP; return dmp_enable_feature(enMask); } unsigned short MPU9250_dmpGetEnabledFeatures(void) { unsigned short mask; if (dmp_get_enabled_features(&mask) == INV_SUCCESS) return mask; return 0; } inv_error_t MPU9250_dmpSetTap( unsigned short xThresh, unsigned short yThresh, unsigned short zThresh, unsigned char taps, unsigned short tapTime, unsigned short tapMulti) { unsigned char axes = 0; if (xThresh > 0) { axes |= TAP_X; if (xThresh>1600) xThresh=1600; if (dmp_set_tap_thresh(1<<X_AXIS, xThresh) != INV_SUCCESS) return INV_ERROR; } if (yThresh > 0) { axes |= TAP_Y; if (yThresh>1600) yThresh=1600; if (dmp_set_tap_thresh(1<<Y_AXIS, yThresh) != INV_SUCCESS) return INV_ERROR; } if (zThresh > 0) { axes |= TAP_Z; if (zThresh>1600) zThresh=1600; if (dmp_set_tap_thresh(1<<Z_AXIS, zThresh) != INV_SUCCESS) return INV_ERROR; } if (dmp_set_tap_axes(axes) != INV_SUCCESS) return INV_ERROR; if (dmp_set_tap_count(taps) != INV_SUCCESS) return INV_ERROR; if (dmp_set_tap_time(tapTime) != INV_SUCCESS) return INV_ERROR; if (dmp_set_tap_time_multi(tapMulti) != INV_SUCCESS) return INV_ERROR; dmp_register_tap_cb(tap_cb); return INV_SUCCESS; } unsigned char MPU9250_getTapDir(void) { _tap_available = false; return tap_direction; } unsigned char MPU9250_getTapCount(void) { _tap_available = false; return tap_count; } bool MPU9250_tapAvailable(void) { return _tap_available; } inv_error_t MPU9250_dmpSetOrientation(const signed char * orientationMatrix) { unsigned short scalar; scalar = orientation_row_2_scale(orientationMatrix); scalar |= orientation_row_2_scale(orientationMatrix + 3) << 3; scalar |= orientation_row_2_scale(orientationMatrix + 6) << 6; dmp_register_android_orient_cb(orient_cb); return dmp_set_orientation(scalar); } unsigned char MPU9250_dmpGetOrientation(void) { return orientation; } inv_error_t MPU9250_dmpEnable3Quat(void) { unsigned short dmpFeatures; // 3-axis and 6-axis quat are mutually exclusive dmpFeatures = MPU9250_dmpGetEnabledFeatures(); dmpFeatures &= ~(DMP_FEATURE_6X_LP_QUAT); dmpFeatures |= DMP_FEATURE_LP_QUAT; if (MPU9250_dmpEnableFeatures(dmpFeatures) != INV_SUCCESS) return INV_ERROR; return dmp_enable_lp_quat(1); } unsigned long MPU9250_dmpGetPedometerSteps(void) { unsigned long steps; if (dmp_get_pedometer_step_count(&steps) == INV_SUCCESS) { return steps; } return 0; } inv_error_t MPU9250_dmpSetPedometerSteps(unsigned long steps) { return dmp_set_pedometer_step_count(steps); } unsigned long MPU9250_dmpGetPedometerTime(void) { unsigned long walkTime; if (dmp_get_pedometer_walk_time(&walkTime) == INV_SUCCESS) { return walkTime; } return 0; } inv_error_t MPU9250_dmpSetPedometerTime(unsigned long time) { return dmp_set_pedometer_walk_time(time); } float MPU9250_calcAccel(int axis) { return (float) axis / (float) _aSense; } float MPU9250_calcGyro(int axis) { return (float) axis / (float) _gSense; } float MPU9250_calcMag(int axis) { return (float) axis / (float) _mSense; } float MPU9250_calcQuat(long axis) { return qToFloat(axis, 30); } float qToFloat(long number, unsigned char q) { int i; unsigned long mask = 0; for (i=0; i<q; i++) { mask |= (1<<i); } return (number >> q) + ((number & mask) / (float) (2<<(q-1))); } void MPU9250_computeEulerAngles(bool degrees) { float dqw = qToFloat(imu.qw, 30); float dqx = qToFloat(imu.qx, 30); float dqy = qToFloat(imu.qy, 30); float dqz = qToFloat(imu.qz, 30); float ysqr = dqy * dqy; float t0 = -2.0f * (ysqr + dqz * dqz) + 1.0f; float t1 = +2.0f * (dqx * dqy - dqw * dqz); float t2 = -2.0f * (dqx * dqz + dqw * dqy); float t3 = +2.0f * (dqy * dqz - dqw * dqx); float t4 = -2.0f * (dqx * dqx + ysqr) + 1.0f; // Keep t2 within range of asin (-1, 1) t2 = t2 > 1.0f ? 1.0f : t2; t2 = t2 < -1.0f ? -1.0f : t2; imu.pitch = asin(t2) * 2; imu.roll = atan2(t3, t4); imu.yaw = atan2(t1, t0); if (degrees) { imu.pitch *= (180.0 / PI); imu.roll *= (180.0 / PI); imu.yaw *= (180.0 / PI); if (imu.pitch < 0) imu.pitch = 360.0 + imu.pitch; if (imu.roll < 0) imu.roll = 360.0 + imu.roll; if (imu.yaw < 0) imu.yaw = 360.0 + imu.yaw; } } float MPU9250_computeCompassHeading(void) { if (imu.my == 0) imu.heading = (imu.mx < 0) ? PI : 0; else imu.heading = atan2(imu.mx, imu.my); if (imu.heading > PI) imu.heading -= (2 * PI); else if (imu.heading < -PI) imu.heading += (2 * PI); else if (imu.heading < 0) imu.heading += 2 * PI; imu.heading*= 180.0 / PI; return imu.heading; } unsigned short orientation_row_2_scale(const signed char *row) { unsigned short b; if (row[0] > 0) b = 0; else if (row[0] < 0) b = 4; else if (row[1] > 0) b = 1; else if (row[1] < 0) b = 5; else if (row[2] > 0) b = 2; else if (row[2] < 0) b = 6; else b = 7; // error return b; } static void tap_cb(unsigned char direction, unsigned char count) { _tap_available = true; tap_count = count; tap_direction = direction; } static void orient_cb(unsigned char orient) { orientation = orient; } <file_sep>/CODE/lab4-1 learning board 211013/Nu-LB-NUC140_BSP3.00.004_v1.2/SampleCode/Nu-LB-NUC140/GPIO_7seg_keypad/TEST.txt // // GPIO_7seg_keypad : 3x3 keypad inpt and display on 7-segment LEDs // #include <stdio.h> #include <stdlib.h> #include "NUC100Series.h" #include "MCU_init.h" #include "SYS_init.h" #include "Seven_Segment.h" #include "Scankey.h" uint8_t SEG[10] = {0x82, 0xEE, 0x07, 0x46, 0x6A, 0x52, 0x12, 0xE6, 0x02, 0x62}; int pc_Open = 1; int pc_Close = 0; int pe_Open = 0; int pe_Close = 1; /* PC = 1 is OPEN,PE = 0 is OPEN void Test_7_segment(uint16_t value){ PC4 = 0; // right to left 0 PC5 = 0; // 1 PC6 = 0; // 2 PC7 = 0; // 3 PE0 = 1; // bottom right PE1 = 1; // dot PE2 = 1; // upper left PE3 = 1; // upper PE4 = 1; // upper right PE5 = 1; // bottom PE6 = 1; // bottom left PE7 = 1; // center CLK_SysTickDelay(50000); } */ // display an integer on four 7-segment LEDs void Q1_Show(uint16_t value){ PC4=1; uint8_t temp; temp=SEG[value]; for(int i=0;i<8;i++){ if((temp&0x01)==0x01){ switch(i){ case 0: PE0=1; break; case 1: PE1=1; break; case 2: PE2=1; break; case 3: PE3=1; break; case 4: PE4=1; break; case 5: PE5=1; break; case 6: PE6=1; break; case 7: PE7=1; break; } }else{ switch(i) { case 0: PE0=0; break; case 1: PE1=0; break; case 2: PE2=0; break; case 3: PE3=0; break; case 4: PE4=0; break; case 5: PE5=0; break; case 6: PE6=0; break; case 7: PE7=0; break; } } temp=temp>>1; } } int Q2_find_pc(int *pc){ for(int i=0; i<4; i++){ if(pc[i] == 1){ return i; } } } int Q2_find_pe(int *pe){ for(int i=0; i<8; i++){ if(pe[i] == 0){ return i; } } } void Q2_Show(int pcc, int pee){ switch(pcc){ case 0: PC4=1; break; case 1: PC5=1; break; case 2: PC6=1; break; case 3: PC7=1; break; } switch(pee){ case 0: PE0=0; break; case 1: PE1=0; break; case 2: PE2=0; break; case 3: PE3=0; break; case 4: PE4=0; break; case 5: PE5=0; break; case 6: PE6=0; break; case 7: PE7=0; break; } } void Q2_Close(void){ PC4 = 0; // right to left 0 PC5 = 0; // 1 PC6 = 0; // 2 PC7 = 0; // 3 PE0 = 1; // bottom right PE1 = 1; // dot PE2 = 1; // upper left PE3 = 1; // upper PE4 = 1; // upper right PE5 = 1; // bottom PE6 = 1; // bottom left PE7 = 1; // center CLK_SysTickDelay(5000); } void Q2_Change_PC_PE(int *pc, int *pe, uint16_t value){ int pcc = Q2_find_pc(pc); int pee = Q2_find_pe(pe); if(value==2){ if(pee == 4){ pe[4]=pe_Close;pe[3]=pe_Open; }else if(pee == 0){ pe[0]=pe_Close;pe[4]=pe_Open; }else if(pee == 3){ pe[3]=pe_Close;pe[5]=pe_Open; }else if(pee == 7){ pe[7]=pe_Close;pe[3]=pe_Open; }else if(pee == 5){ pe[5]=pe_Close;pe[7]=pe_Open; }else if(pee == 2){ pe[2]=pe_Close;pe[3]=pe_Open; }else if(pee == 6){ pe[6]=pe_Close;pe[2]=pe_Open; } } else if(value==8){ if(pee == 4){ pe[4]=pe_Close;pe[0]=pe_Open; }else if(pee == 0){ pe[0]=pe_Close;pe[5]=pe_Open; }else if(pee == 3){ pe[3]=pe_Close;pe[7]=pe_Open; }else if(pee == 7){ pe[7]=pe_Close;pe[5]=pe_Open; }else if(pee == 5){ pe[5]=pe_Close;pe[3]=pe_Open; }else if(pee == 2){ pe[2]=pe_Close;pe[6]=pe_Open; }else if(pee == 6){ pe[6]=pe_Close;pe[5]=pe_Open; } } else if(value==6){ if(pee == 4){ if(pcc == 0){ pc[0]=pc_Close;pc[3]=pc_Open; pe[4]=pc_Close;pe[2]=pe_Open; }else if(pcc == 1){ pc[1]=pc_Close;pc[0]=pc_Open; pe[4]=pe_Close;pe[2]=pe_Open; }else if(pcc == 2){ pc[2]=pc_Close;pc[1]=pc_Open; pe[4]=pe_Close;pe[2]=pe_Open; }else if(pcc == 3){ pc[3]=pc_Close;pc[2]=pc_Open; pe[4]=pe_Close;pe[2]=pe_Open; } }else if(pee == 0){ if(pcc == 0){ pc[0]=pc_Close;pc[3]=pc_Open; pe[0]=pe_Close;pe[6]=pe_Open; }else if(pcc == 1){ pc[1]=pc_Close;pc[0]=pc_Open; pe[0]=pe_Close;pe[6]=pe_Open; }else if(pcc == 2){ pc[2]=pc_Close;pc[1]=pc_Open; pe[0]=pe_Close;pe[6]=pe_Open; }else if(pcc == 3){ pc[3]=pc_Close;pc[2]=pc_Open; pe[0]=pe_Close;pe[6]=pe_Open; } }else if(pee == 3){ pe[3]=pe_Close;pe[4]=pe_Open; }else if(pee == 7){ if(pcc == 0){ pc[0]=pc_Close;pc[3]=pc_Open; }else if(pcc == 1){ pc[1]=pc_Close;pc[0]=pc_Open; }else if(pcc == 2){ pc[2]=pc_Close;pc[1]=pc_Open; }else if(pcc == 3){ pc[3]=pc_Close;pc[2]=pc_Open; } }else if(pee == 5){ pe[5]=pe_Close;pe[0]=pe_Open; }else if(pee == 2){ pe[2]=pe_Close;pe[3]=pe_Open; }else if(pee == 6){ pe[6]=pe_Close;pe[5]=pe_Open; } } else if(value==4){ if(pee == 4){ pe[4]=pe_Close;pe[3]=pe_Open; }else if(pee == 0){ pe[0]=pe_Close;pe[5]=pe_Open; }else if(pee == 3){ pe[3]=pe_Close;pe[2]=pe_Open; }else if(pee == 7){ if(pcc == 0){ pc[0]=pc_Close;pc[1]=pc_Open; }else if(pcc == 1){ pc[1]=pc_Close;pc[2]=pc_Open; }else if(pcc == 2){ pc[2]=pc_Close;pc[3]=pc_Open; }else if(pcc == 3){ pc[3]=pc_Close;pc[0]=pc_Open; } }else if(pee == 5){ pe[5]=pe_Close;pe[6]=pe_Open; }else if(pee == 2){ if(pcc == 0){ pc[0]=pc_Close;pc[1]=pc_Open; pe[2]=pe_Close;pe[4]=pe_Open; }else if(pcc == 1){ pc[1]=pc_Close;pc[2]=pc_Open; pe[2]=pe_Close;pe[4]=pe_Open; }else if(pcc == 2){ pc[2]=pc_Close;pc[3]=pc_Open; pe[2]=pe_Close;pe[4]=pe_Open; }else if(pcc == 3){ pc[3]=pc_Close;pc[0]=pc_Open; pe[2]=pe_Close;pe[4]=pe_Open; } }else if(pee == 6){ if(pcc == 0){ pc[0]=pc_Close;pc[1]=pc_Open; pe[6]=pe_Close;pe[0]=pe_Open; }else if(pcc == 1){ pc[1]=pc_Close;pc[2]=pc_Open; pe[6]=pe_Close;pe[0]=pe_Open; }else if(pcc == 2){ pc[2]=pc_Close;pc[3]=pc_Open; pe[6]=pe_Close;pe[0]=pe_Open; }else if(pcc == 3){ pc[3]=pc_Close;pc[0]=pc_Open; pe[6]=pe_Close;pe[0]=pe_Open; } } } } int main(void){ SYS_Init(); OpenSevenSegment(); CloseSevenSegment(); OpenKeyPad(); uint16_t i; int question = 2; if(question == 1){ while(1){ i = ScanKey(); Q1_Show(i); } } else if(question == 2){ int pc[4] = {1, 0, 0, 0}; int pe[8] = {1, 1, 1, 1, 0, 1, 1, 1}; while(1){ i = ScanKey(); if(i==2 || i == 4 || i == 6 || i == 8){ Q2_Close(); Q2_Change_PC_PE(pc, pe, i); CLK_SysTickDelay(1000000); } int pcc = Q2_find_pc(pc); int pee = Q2_find_pe(pe); Q2_Show(pcc, pee); } } } <file_sep>/CODE/lab8-1 learning board 211117/Nu-LB-NUC140_BSP3.00.004_v1.2/SampleCode/Nu-LB-NUC140/UART0_RX/MCU_init.h //Define Clock source #define MCU_CLOCK_SOURCE #define MCU_CLOCK_SOURCE_HXT // HXT, LXT, HIRC, LIRC #define MCU_CLOCK_FREQUENCY 50000000 //Hz //Define MCU Interfaces // LCD using SPI3 #define MCU_INTERFACE_SPI3 #define SPI3_CLOCK_SOURCE_HCLK // HCLK, PLL #define PIN_SPI3_SS0_PD8 #define PIN_SPI3_SCLK_PD9 #define PIN_SPI3_MISO0_PD10 #define PIN_SPI3_MOSI0_PD11 #define MCU_INTERFACE_UART0 #define UART_CLOCK_SOURCE_HXT // HXT, LXT, PLL, HIRC #define UART_CLOCK_DIVIDER 3 #define PIN_UART0_RX_PB0 #define PIN_UART0_TX_PB1 <file_sep>/CODE/lab9-1 learning board 211124/Library/NuMakerLib/Include/typedefs.h typedef struct { int x; int y; int z; } tAxisB; typedef struct { int x; int y; int z; } tAxis; typedef struct { float x; float y; float z; } tAxisF; typedef struct { int Heading; int Roll; int Pitch; } eAxis; typedef struct { tAxis accel; tAxis gyro; tAxis mag; eAxis euler; short temp; float gdt; //gyro sample time (sec) } tSensor; <file_sep>/CODE/lab3-2 learning board 211006/lab3-2 learning board 211006/Nu-LB-NUC140_BSP3.00.004_v1.2/Library/Nu-LB-NUC140/Include/SYS_init.h // // For NUC140 // #ifndef __SYS_init_H__ #define __SYS_init_H__ #ifdef MCU_CLOCK_SOURCE_HXT #define MCU_CLOCK_SOURCE_MASK_HXT CLK_PWRCON_XTL12M_EN_Msk #define CLK_CLKSTATUS_STB_MASK_HXT CLK_CLKSTATUS_XTL12M_STB_Msk #else #define MCU_CLOCK_SOURCE_MASK_HXT 0 #define CLK_CLKSTATUS_STB_MASK_HXT 0 #endif #ifdef MCU_CLOCK_SOURCE_LXT #define MCU_CLOCK_SOURCE_MASK_LXT CLK_PWRCON_XTL32K_EN_Msk #define CLK_CLKSTATUS_STB_MASK_LXT CLK_CLKSTATUS_IRC10K_STB_Msk #else #define MCU_CLOCK_SOURCE_MASK_LXT 0 #define CLK_CLKSTATUS_STB_MASK_LXT 0 #endif #ifdef MCU_CLOCK_SOURCE_HIRC #define MCU_CLOCK_SOURCE_MASK_HIRC CLK_PWRCON_IRC22M_EN_Msk #define CLK_CLKSTATUS_STB_MASK_HIRC CLK_CLKSTATUS_IRC22M_STB_Msk #else #define MCU_CLOCK_SOURCE_MASK_HIRC 0 #define CLK_CLKSTATUS_STB_MASK_HIRC 0 #endif #ifdef MCU_CLOCK_SOURCE_LIRC #define MCU_CLOCK_SOURCE_MASK_LIRC CLK_PWRCON_IRC10K_EN_Msk #define CLK_CLKSTATUS_STB_MASK_LIRC CLK_CLKSTATUS_IRC10K_STB_Msk #else #define MCU_CLOCK_SOURCE_MASK_LIRC 0 #define CLK_CLKSTATUS_STB_MASK_LIRC 0 #endif #ifdef MCU_CLOCK_SOURCE #define MCU_CLOCK_SOURCE_MASK (MCU_CLOCK_SOURCE_MASK_HXT | MCU_CLOCK_SOURCE_MASK_LXT | MCU_CLOCK_SOURCE_MASK_HIRC | MCU_CLOCK_SOURCE_MASK_LIRC) #define MCU_CLOCK_STABLE_MASK (CLK_CLKSTATUS_STB_MASK_HXT | CLK_CLKSTATUS_STB_MASK_LXT | CLK_CLKSTATUS_STB_MASK_HIRC | CLK_CLKSTATUS_STB_MASK_LIRC) #endif // For CLK.h compatible to Nano BSP #define CLK_HCLK_CLK_DIVIDER(x) ((x)-1) /*!< CLKDIV Setting for HCLK clock divider. It could be 1~16 */ #define CLK_USB_CLK_DIVIDER(x) (((x)-1) << CLK_CLKDIV_USB_N_Pos) /*!< CLKDIV Setting for USB clock divider. It could be 1~16 */ #define CLK_UART_CLK_DIVIDER(x) (((x)-1) << CLK_CLKDIV_UART_N_Pos) /*!< CLKDIV Setting for UART clock divider. It could be 1~16 */ #define CLK_ADC_CLK_DIVIDER(x) (((x)-1) << CLK_CLKDIV_ADC_N_Pos) /*!< CLKDIV Setting for ADC clock divider. It could be 1~256 */ #define CLK_SC0_CLK_DIVIDER(x) (((x)-1) << CLK_CLKDIV1_SC0_N_Pos) /*!< CLKDIV1 Setting for SC0 clock divider. It could be 1~256*/ #define CLK_SC1_CLK_DIVIDER(x) (((x)-1) << CLK_CLKDIV1_SC1_N_Pos) /*!< CLKDIV1 Setting for SC1 clock divider. It could be 1~256*/ #define CLK_SC2_CLK_DIVIDER(x) (((x)-1) << CLK_CLKDIV1_SC2_N_Pos) /*!< CLKDIV1 Setting for SC2 clock divider. It could be 1~256*/ // For GPIO.h compatible to Nano BSP #define GPIO_MODE_INPUT 0x0UL /*!< Input Mode */ #define GPIO_MODE_OUTPUT 0x1UL /*!< Output Mode */ #define GPIO_MODE_OPEN_DRAIN 0x2UL /*!< Open-Drain Mode */ #define GPIO_MODE_QUASI 0x3UL /*!< Quasi-bidirectional Mode */ // For ADC.h compatbile to Nano BSP #define ADC_CH_0_MASK (1UL << 0) /*!< ADC channel 0 mask */ #define ADC_CH_1_MASK (1UL << 1) /*!< ADC channel 1 mask */ #define ADC_CH_2_MASK (1UL << 2) /*!< ADC channel 2 mask */ #define ADC_CH_3_MASK (1UL << 3) /*!< ADC channel 3 mask */ #define ADC_CH_4_MASK (1UL << 4) /*!< ADC channel 4 mask */ #define ADC_CH_5_MASK (1UL << 5) /*!< ADC channel 5 mask */ #define ADC_CH_6_MASK (1UL << 6) /*!< ADC channel 6 mask */ #define ADC_CH_7_MASK (1UL << 7) /*!< ADC channel 7 mask */ #define ADC_OPERATION_MODE_SINGLE (0UL<<ADC_ADCR_ADMD_Pos) /*!< Single mode */ #define ADC_OPERATION_MODE_SINGLE_CYCLE (2UL<<ADC_ADCR_ADMD_Pos) /*!< Single cycle scan mode */ #define ADC_OPERATION_MODE_CONTINUOUS (3UL<<ADC_ADCR_ADMD_Pos) /*!< Continuous scan mode */ #define ADC_INPUT_MODE_SINGLE_END (0UL<<ADC_ADCR_DIFFEN_Pos) /*!< Single end input mode */ #define ADC_INPUT_MODE_DIFFERENTIAL (1UL<<ADC_ADCR_DIFFEN_Pos) /*!< Differential input type */ // For PWM.h compatible to Nano BSP #define PWM0_IRQn PWMA_IRQn #define PWM1_IRQn PWMB_IRQn #define PWM_CH_0_MASK (1UL) /*!< PWM channel 0 mask \hideinitializer */ #define PWM_CH_1_MASK (2UL) /*!< PWM channel 1 mask \hideinitializer */ #define PWM_CH_2_MASK (4UL) /*!< PWM channel 2 mask \hideinitializer */ #define PWM_CH_3_MASK (8UL) /*!< PWM channel 3 mask \hideinitializer */ // For I2C.h compatible to Nano BSP #define I2C_STA_SI 0x28UL /*!< I2CON setting for I2C control bits. It would set STA and SI bits */ #define I2C_STA_SI_AA 0x2CUL /*!< I2CON setting for I2C control bits. It would set STA, SI and AA bits */ #define I2C_STO_SI 0x18UL /*!< I2CON setting for I2C control bits. It would set STO and SI bits */ #define I2C_STO_SI_AA 0x1CUL /*!< I2CON setting for I2C control bits. It would set STO, SI and AA bits */ #define I2C_SI 0x08UL /*!< I2CON setting for I2C control bits. It would set SI bit */ #define I2C_SI_AA 0x0CUL /*!< I2CON setting for I2C control bits. It would set SI and AA bits */ #define I2C_STA 0x20UL /*!< I2CON setting for I2C control bits. It would set STA bit */ #define I2C_STO 0x10UL /*!< I2CON setting for I2C control bits. It would set STO bit */ #define I2C_AA 0x04UL /*!< I2CON setting for I2C control bits. It would set AA bit */ // For RTC.h #define CLK_CLKSEL2_RTC_SEL_10K_LXT (0x0UL<<CLK_CLKSEL2_RTC_SEL_10K_Pos) /*!< Setting WWDT clock source as external X'tal 32.768KHz */ #define CLK_CLKSEL2_RTC_SEL_10K_LIRC (0x1UL<<CLK_CLKSEL2_RTC_SEL_10K_Pos) /*!< Setting WWDT clock source as internal 10KHz RC clock */ // For SYS.h compatible to Nano BSP #define SYS_PA_L_MFP_PA0_MFP_GPIO 0x00000000UL /*!< GPA_MFP PA.0 setting for GPIO */ #define SYS_PA_L_MFP_PA0_MFP_ADC_CH0 (1UL<<0) /*!< GPA_MFP PA.0 setting for ADC0 */ #define SYS_PA_L_MFP_PA0_MFP_SC0_PWR (1UL<<0) /*!< GPA_MFP PA.0 setting for SC0_PWR */ #define SYS_PA_L_MFP_PA0_MFP_Msk (1UL<<0) /*!< GPA_MFP PA.0 mask */ #define SYS_PA_L_MFP_PA1_MFP_GPIO 0x00000000UL /*!< GPA_MFP PA.1 setting for GPIO */ #define SYS_PA_L_MFP_PA1_MFP_ADC_CH1 (1UL<<1) /*!< GPA_MFP PA.1 setting for ADC1 */ #define SYS_PA_L_MFP_PA1_MFP_SC0_RST (1UL<<1) /*!< GPA_MFP PA.1 setting for SC0_RST */ #define SYS_PA_L_MFP_PA1_MFP_EBI_AD12 (1UL<<1) /*!< GPA_MFP PA.1 setting for EBI_AD12 */ #define SYS_PA_L_MFP_PA1_MFP_Msk (1UL<<1) /*!< GPA_MFP PA.1 mask */ #define SYS_PA_L_MFP_PA2_MFP_GPIO 0x00000000UL /*!< GPA_MFP PA.2 setting for GPIO */ #define SYS_PA_L_MFP_PA2_MFP_ADC_CH2 (1UL<<2) /*!< GPA_MFP PA.2 setting for ADC2 */ #define SYS_PA_L_MFP_PA2_MFP_SC0_CLK (1UL<<2) /*!< GPA_MFP PA.2 setting for SC0_CLK */ #define SYS_PA_L_MFP_PA2_MFP_EBI_AD11 (1UL<<2) /*!< GPA_MFP PA.2 setting for EBI_AD11 */ #define SYS_PA_L_MFP_PA2_MFP_Msk (1UL<<2) /*!< GPA_MFP PA.2 mask */ #define SYS_PA_L_MFP_PA3_MFP_GPIO 0x00000000UL /*!< GPA_MFP PA.3 setting for GPIO */ #define SYS_PA_L_MFP_PA3_MFP_ADC_CH3 (1UL<<3) /*!< GPA_MFP PA.3 setting for ADC3 */ #define SYS_PA_L_MFP_PA3_MFP_SC0_DAT (1UL<<3) /*!< GPA_MFP PA.3 setting for SC0_DAT */ #define SYS_PA_L_MFP_PA3_MFP_EBI_AD10 (1UL<<3) /*!< GPA_MFP PA.3 setting for EBI_AD10 */ #define SYS_PA_L_MFP_PA3_MFP_Msk (1UL<<3) /*!< GPA_MFP PA.3 mask */ #define SYS_PA_L_MFP_PA4_MFP_GPIO 0x00000000UL /*!< GPA_MFP PA.4 setting for GPIO */ #define SYS_PA_L_MFP_PA4_MFP_ADC_CH4 (1UL<<4) /*!< GPA_MFP PA.4 setting for ADC4 */ #define SYS_PA_L_MFP_PA4_MFP_SC1_PWR (1UL<<4) /*!< GPA_MFP PA.4 setting for SC1_PWR */ #define SYS_PA_L_MFP_PA4_MFP_EBI_AD9 (1UL<<4) /*!< GPA_MFP PA.4 setting for EBI_AD9 */ #define SYS_PA_L_MFP_PA4_MFP_Msk (1UL<<4) /*!< GPA_MFP PA.4 mask */ #define SYS_PA_L_MFP_PA5_MFP_GPIO 0x00000000UL /*!< GPA_MFP PA.5 setting for GPIO */ #define SYS_PA_L_MFP_PA5_MFP_ADC_CH5 (1UL<<5) /*!< GPA_MFP PA.5 setting for ADC5 */ #define SYS_PA_L_MFP_PA5_MFP_SC1_RST (1UL<<5) /*!< GPA_MFP PA.5 setting for SC1_RST */ #define SYS_PA_L_MFP_PA5_MFP_EBI_AD8 (1UL<<5) /*!< GPA_MFP PA.5 setting for EBI_AD8 */ #define SYS_PA_L_MFP_PA5_MFP_Msk (1UL<<5) /*!< GPA_MFP PA.5 mask */ #define SYS_PA_L_MFP_PA6_MFP_GPIO 0x00000000UL /*!< GPA_MFP PA.6 setting for GPIO */ #define SYS_PA_L_MFP_PA6_MFP_ADC_CH6 (1UL<<6) /*!< GPA_MFP PA.6 setting for ADC6 */ #define SYS_PA_L_MFP_PA6_MFP_SC1_CLK (1UL<<6) /*!< GPA_MFP PA.6 setting for SC1_CLK */ #define SYS_PA_L_MFP_PA6_MFP_EBI_AD7 (1UL<<6) /*!< GPA_MFP PA.6 setting for AD7 */ #define SYS_PA_L_MFP_PA6_MFP_Msk (1UL<<6) /*!< GPA_MFP PA.6 mask */ #define SYS_PA_L_MFP_PA7_MFP_GPIO 0x00000000UL /*!< GPA_MFP PA.7 setting for GPIO */ #define SYS_PA_L_MFP_PA7_MFP_ADC_CH7 (1UL<<7) /*!< GPA_MFP PA.7 setting for ADC7 */ #define SYS_PA_L_MFP_PA7_MFP_SPI2_SS1 (1UL<<7) /*!< GPA_MFP PA.7 setting for SPI2_SS1 */ #define SYS_PA_L_MFP_PA7_MFP_SC1_DAT (1UL<<7) /*!< GPA_MFP PA.7 setting for SC1_DAT */ #define SYS_PA_L_MFP_PA7_MFP_EBI_AD6 (1UL<<7) /*!< GPA_MFP PA.7 setting for EBI_AD6 */ #define SYS_PA_L_MFP_PA7_MFP_Msk (1UL<<7) /*!< GPA_MFP PA.7 mask */ #define SYS_PA_H_MFP_PA8_MFP_GPIO 0x00000000UL /*!< GPA_MFP PA.8 setting for GPIO */ #define SYS_PA_H_MFP_PA8_MFP_I2C0_SDA (1UL<<8) /*!< GPA_MFP PA.8 setting for I2C0_SDA */ #define SYS_PA_H_MFP_PA8_MFP_Msk (1UL<<8) /*!< GPA_MFP PA.8 mask */ #define SYS_PA_H_MFP_PA9_MFP_GPIO 0x00000000UL /*!< GPA_MFP PA.9 setting for GPIO */ #define SYS_PA_H_MFP_PA9_MFP_I2C0_SCL (1UL<<9) /*!< GPA_MFP PA.9 setting for I2C0_SCL */ #define SYS_PA_H_MFP_PA9_MFP_Msk (1UL<<9) /*!< GPA_MFP PA.9 mask */ #define SYS_PA_H_MFP_PA10_MFP_GPIO 0x00000000UL /*!< GPA_MFP PA.10 setting for GPIO */ #define SYS_PA_H_MFP_PA10_MFP_I2C1_SDA (1UL<<10) /*!< GPA_MFP PA.10 setting for I2C1_SDA */ #define SYS_PA_H_MFP_PA10_MFP_EBI_nWR (1UL<<10) /*!< GPA_MFP PA.10 setting for EBI_nWR */ #define SYS_PA_H_MFP_PA10_MFP_Msk (1UL<<10) /*!< GPA_MFP PA.10 mask */ #define SYS_PA_H_MFP_PA11_MFP_GPIO 0x00000000UL /*!< GPA_MFP PA.11 setting for GPIO */ #define SYS_PA_H_MFP_PA11_MFP_I2C1_SCL (1UL<<11) /*!< GPA_MFP PA.11 setting for I2C1_SCL */ #define SYS_PA_H_MFP_PA11_MFP_EBI_nRD (1UL<<11) /*!< GPA_MFP PA.11 setting for EBI_nRD */ #define SYS_PA_H_MFP_PA11_MFP_Msk (1UL<<11) /*!< GPA_MFP PA.11 mask */ #define SYS_PA_H_MFP_PA12_MFP_GPIO 0x00000000UL /*!< GPA_MFP PA.12 setting for GPIO */ #define SYS_PA_H_MFP_PA12_MFP_PWM_CH0 (1UL<<12) /*!< GPA_MFP PA.12 setting for PWM0 */ #define SYS_PA_H_MFP_PA12_SC2_DAT (1UL<<12) /*!< GPA_MFP PA.12 setting for SC2_DAT */ #define SYS_PA_H_MFP_PA12_EBI_AD13 (1UL<<12) /*!< GPA_MFP PA.12 setting for EBI_AD13 */ #define SYS_PA_H_MFP_PA12_MFP_Msk (1UL<<12) /*!< GPA_MFP PA.12 mask */ #define SYS_PA_H_MFP_PA13_MFP_GPIO 0x00000000UL /*!< GPA_MFP PA.13 setting for GPIO */ #define SYS_PA_H_MFP_PA13_MFP_PWM_CH1 (1UL<<13) /*!< GPA_MFP PA.13 setting for PWM1 */ #define SYS_PA_H_MFP_PA13_MFP_SC2_CLK (1UL<<13) /*!< GPA_MFP PA.13 setting for SC2_CLK */ #define SYS_PA_H_MFP_PA13_MFP_EBI_AD14 (1UL<<13) /*!< GPA_MFP PA.13 setting for EBI_AD14 */ #define SYS_PA_H_MFP_PA13_MFP_Msk (1UL<<13) /*!< GPA_MFP PA.13 mask */ #define SYS_PA_H_MFP_PA14_MFP_GPIO 0x00000000UL /*!< GPA_MFP PA.14 setting for GPIO */ #define SYS_PA_H_MFP_PA14_MFP_PWM_CH2 (1UL<<14) /*!< GPA_MFP PA.14 setting for PWM2 */ #define SYS_PA_H_MFP_PA14_MFP_SC2_RST (1UL<<14) /*!< GPA_MFP PA.14 setting for SC2_RST */ #define SYS_PA_H_MFP_PA14_MFP_EBI_AD15 (1UL<<14) /*!< GPA_MFP PA.14 setting for EBI_AD15 */ #define SYS_PA_H_MFP_PA14_MFP_Msk (1UL<<14) /*!< GPA_MFP PA.14 mask */ #define SYS_PA_H_MFP_PA15_MFP_GPIO 0x00000000UL /*!< GPA_MFP PA.15 setting for GPIO */ #define SYS_PA_H_MFP_PA15_MFP_PWM_CH3 (1UL<<15) /*!< GPA_MFP PA.15 setting for PWM3 */ #define SYS_PA_H_MFP_PA15_MFP_I2S_MCLK (1UL<<15) /*!< GPA_MFP PA.15 setting for I2S_MCLK */ #define SYS_PA_H_MFP_PA15_MFP_SC2_PWR (1UL<<15) /*!< GPA_MFP PA.15 setting for SC2_PWR */ #define SYS_PA_H_MFP_PA15_MFP_Msk (1UL<<15) /*!< GPA_MFP PA.15 mask */ #define SYS_PB_L_MFP_PB0_MFP_GPIO 0x00000000UL /*!< GPB_MFP PB.0 setting for GPIO */ #define SYS_PB_L_MFP_PB0_MFP_UART0_RX (1UL<<0) /*!< GPB_MFP PB.0 setting for UART0_RXD */ #define SYS_PB_L_MFP_PB0_MFP_Msk (1UL<<0) /*!< GPB_MFP PB.0 mask */ #define SYS_PB_L_MFP_PB1_MFP_GPIO 0x00000000UL /*!< GPB_MFP PB.1 setting for GPIO */ #define SYS_PB_L_MFP_PB1_MFP_UART0_TX (1UL<<1) /*!< GPB_MFP PB.1 setting for UART0_TXD */ #define SYS_PB_L_MFP_PB1_MFP_Msk (1UL<<1) /*!< GPB_MFP PB.1 mask */ #define SYS_PB_L_MFP_PB2_MFP_GPIO 0x00000000UL /*!< GPB_MFP PB.2 setting for GPIO */ #define SYS_PB_L_MFP_PB2_MFP_UART0_nRTS (1UL<<2) /*!< GPB_MFP PB.2 setting for UART0_nRTS */ #define SYS_PB_L_MFP_PB2_MFP_EBI_nWRL (1UL<<2) /*!< GPB_MFP PB.2 setting for EBI_nWRL */ #define SYS_PB_L_MFP_PB2_MFP_TC2 (1UL<<2) /*!< GPB_MFP PB.2 setting for TC2 */ #define SYS_PB_L_MFP_PB2_MFP_TM2_EXT (1UL<<2) /*!< GPB_MFP PB.2 setting for TM2_EXT */ #define SYS_PB_L_MFP_PB2_MFP_Msk (1UL<<2) /*!< GPB_MFP PB.2 mask */ #define SYS_PB_L_MFP_PB3_MFP_GPIO 0x00000000UL /*!< GPB_MFP PB.3 setting for GPIO */ #define SYS_PB_L_MFP_PB3_MFP_ART0_nCTS (1UL<<3) /*!< GPB_MFP PB.3 setting for UART0_nCTS */ #define SYS_PB_L_MFP_PB3_MFP_TC3 (1UL<<3) /*!< GPB_MFP PB.3 setting for TC3 */ #define SYS_PB_L_MFP_PB3_MFP_T3EX (1UL<<3) /*!< GPB_MFP PB.3 setting for T3EX */ #define SYS_PB_L_MFP_PB3_MFP_TM3_EXT (1UL<<3) /*!< GPB_MFP PB.3 setting for TM3_EXT */ #define SYS_PB_L_MFP_PB3_MFP_SC2_CD (1UL<<3) /*!< GPB_MFP PB.3 setting for SC2_CD */ #define SYS_PB_L_MFP_PB3_MFP_EBI_nWRH (1UL<<3) /*!< GPB_MFP PB.3 setting for EBI_nWRH */ #define SYS_PB_L_MFP_PB3_MFP_Msk (1UL<<3) /*!< GPB_MFP PB.3 mask */ #define SYS_PB_L_MFP_PB4_MFP_GPIO 0x00000000UL /*!< GPB_MFP PB.4 setting for GPIO */ #define SYS_PB_L_MFP_PB4_MFP_UART1_RX (1UL<<4) /*!< GPA_MFP PB.4 setting for UART1_RXD */ #define SYS_PB_L_MFP_PB4_MFP_Msk (1UL<<4) /*!< GPA_MFP PB.4 mask */ #define SYS_PB_L_MFP_PB5_MFP_GPIO 0x00000000UL /*!< GPB_MFP PB.5 setting for GPIO */ #define SYS_PB_L_MFP_PB5_MFP_UART1_TX (1UL<<5) /*!< GPA_MFP PB.5 setting for UART1_RXD */ #define SYS_PB_L_MFP_PB5_MFP_Msk (1UL<<5) /*!< GPA_MFP PB.5 mask */ #define SYS_PB_L_MFP_PB6_MFP_GPIO 0x00000000UL /*!< GPB_MFP PB.6 setting for GPIO */ #define SYS_PB_L_MFP_PB6_MFP_UART1_nRTS (1UL<<6) /*!< GPB_MFP PB.6 setting for UART1_nRTS */ #define SYS_PB_L_MFP_PB6_MFP_EBI_ALE (1UL<<6) /*!< GPB_MFP PB.6 setting for EBI_ALE */ #define SYS_PB_L_MFP_PB6_MFP_Msk (1UL<<6) /*!< GPB_MFP PB.6 mask */ #define SYS_PB_L_MFP_PB7_MFP_GPIO 0x00000000UL /*!< GPB_MFP PB.7 setting for GPIO */ #define SYS_PB_L_MFP_PB7_MFP_UART1_nCTS (1UL<<7) /*!< GPB_MFP PB.7 setting for UART1_nCTS */ #define SYS_PB_L_MFP_PB7_MFP_EBI_nCS (1UL<<7) /*!< GPB_MFP PB.7 setting for EBI_nCS */ #define SYS_PB_L_MFP_PB7_MFP_Msk (1UL<<7) /*!< GPB_MFP PB.7 mask */ #define SYS_PB_H_MFP_PB8_MFP_GPIO 0x00000000UL /*!< GPB_MFP PB.8 setting for GPIO */ #define SYS_PB_H_MFP_PB8_MFP_TM0 (1UL<<8) /*!< GPA_MFP PB.8 setting for TM0 */ #define SYS_PB_H_MFP_PB8_MFP_Msk (1UL<<8) /*!< GPB_MFP PB.8 mask */ #define SYS_PB_H_MFP_PB9_MFP_GPIO 0x00000000UL /*!< GPB_MFP PB.9 setting for GPIO */ #define SYS_PB_H_MFP_PB9_MFP_TM1 (1UL<<9) /*!< GPB_MFP PB.9 setting for TM1 */ #define SYS_PB_H_MFP_PB9_MFP_SPI1_SS1 (1UL<<9) /*!< GPB_MFP PB.9 setting for SPI1_SS1 */ #define SYS_PB_H_MFP_PB9_MFP_Msk (1UL<<9) /*!< GPB_MFP PB.9 mask */ #define SYS_PB_H_MFP_PB10_MFP_GPIO 0x00000000UL /*!< GPB_MFP PB.10 setting for GPIO */ #define SYS_PB_H_MFP_PB10_MFP_TM2 (1UL<<10) /*!< GPB_MFP PB.10 setting for TM2 */ #define SYS_PB_H_MFP_PB10_MFP_SPI0_SS1 (1UL<<10) /*!< GPB_MFP PB.10 setting for SPI0_SS1 */ #define SYS_PB_H_MFP_PB10_MFP_Msk (1UL<<10) /*!< GPB_MFP PB.10 mask */ #define SYS_PB_H_MFP_PB11_MFP_GPIO 0x00000000UL /*!< GPB_MFP PB.11 setting for GPIO */ #define SYS_PB_H_MFP_PB11_MFP_TM3 (1UL<<11) /*!< GPB_MFP PB.11 setting for TM3 */ #define SYS_PB_H_MFP_PB11_MFP_PWM_CH4 (1UL<<11) /*!< GPB_MFP PB.11 setting for PWM4 */ #define SYS_PB_H_MFP_PB11_MFP_Msk (1UL<<11) /*!< GPB_MFP PB.11 mask */ #define SYS_PB_H_MFP_PB12_MFP_GPIO 0x00000000UL /*!< GPB_MFP PB.12 setting for GPIO */ #define SYS_PB_H_MFP_PB12_MFP_ACMP0_O (1UL<<12) /*!< GPB_MFP PB.12 setting for ACMP0_O */ #define SYS_PB_H_MFP_PB12_MFP_CLKO (1UL<<12) /*!< GPB_MFP PB.12 setting for CLKO */ #define SYS_PB_H_MFP_PB12_MFP_EBI_AD0 (1UL<<12) /*!< GPB_MFP PB.12 setting for AD0 */ #define SYS_PB_H_MFP_PB12_MFP_Msk (1UL<<12) /*!< GPB_MFP PB.12 mask */ #define SYS_PB_H_MFP_PB13_MFP_GPIO 0x00000000UL /*!< GPB_MFP PB.13 setting for GPIO */ #define SYS_PB_H_MFP_PB13_MFP_ACMP1_O (1UL<<13) /*!< GPB_MFP PB.13 setting for ACMP1_O */ #define SYS_PB_H_MFP_PB13_MFP_EBI_AD1 (1UL<<13) /*!< GPB_MFP PB.13 setting for EBI_AD1 */ #define SYS_PB_H_MFP_PB13_MFP_Msk (1UL<<13) /*!< GPB_MFP PB.13 mask */ #define SYS_PB_H_MFP_PB14_MFP_GPIO 0x00000000UL /*!< GPB_MFP PB.14 setting for GPIO */ #define SYS_PB_H_MFP_PB14_MFP_EINT0 (1UL<<14) /*!< GPB_MFP PB.14 setting for INT0 */ #define SYS_PB_H_MFP_PB14_MFP_SPI3_SS1 (1UL<<14) /*!< GPB_MFP PB.14 setting for SPI3_SS1 */ #define SYS_PB_H_MFP_PB14_MFP_Msk (1UL<<14) /*!< GPB_MFP PB.14 mask */ #define SYS_PB_H_MFP_PB15_MFP_GPIO 0x00000000UL /*!< GPB_MFP PB.15 setting for GPIO */ #define SYS_PB_H_MFP_PB15_MFP_EINT1 (1UL<<15) /*!< GPB_MFP PB.15 setting for INT1 */ #define SYS_PB_H_MFP_PB15_MFP_TC0 (1UL<<15) /*!< GPB_MFP PB.15 setting for TC0 */ #define SYS_PB_H_MFP_PB15_MFP_TM0_EXT (1UL<<15) /*!< GPB_MFP PB.15 setting for TM0_EXT */ #define SYS_PB_H_MFP_PB15_MFP_Msk (1UL<<15) /*!< GPB_MFP PB.15 mask */ #define SYS_PC_L_MFP_PC0_MFP_GPIO 0x00000000UL /*!< GPC_MFP PC.0 setting for GPIO */ #define SYS_PC_L_MFP_PC0_MFP_SPI0_SS0 (1UL<<0) /*!< GPC_MFP PC.0 setting for SPI0_SS0 */ #define SYS_PC_L_MFP_PC0_MFP_I2S_LRCLK (1UL<<0) /*!< GPC_MFP PC.0 setting for I2S_LRCLK */ #define SYS_PC_L_MFP_PC0_MFP_I2S_LRCK (1UL<<0) /*!< GPC_MFP PC.0 setting for I2S_LRCK */ #define SYS_PC_L_MFP_PC0_MFP_Msk (1UL<<0) /*!< GPC_MFP PC.0 mask */ #define SYS_PC_L_MFP_PC1_MFP_GPIO 0x00000000UL /*!< GPC_MFP PC.1 setting for GPIO */ #define SYS_PC_L_MFP_PC1_MFP_SPI0_CLK (1UL<<1) /*!< GPC_MFP PC.1 setting for SPI0_CLK */ #define SYS_PC_L_MFP_PC1_MFP_I2S_BCLK (1UL<<1) /*!< GPC_MFP PC.1 setting for I2S_BCLK */ #define SYS_PC_L_MFP_PC1_MFP_Msk (1UL<<1) /*!< GPC_MFP PC.1 mask */ #define SYS_PC_L_MFP_PC2_MFP_GPIO 0x00000000UL /*!< GPC_MFP PC.2 setting for GPIO */ #define SYS_PC_L_MFP_PC2_MFP_SPI0_MISO0 (1UL<<2) /*!< GPC_MFP PC.2 setting for SPI0_MISO0 */ #define SYS_PC_L_MFP_PC2_MFP_I2S_DI (1UL<<2) /*!< GPC_MFP PC.2 setting for I2S_DI */ #define SYS_PC_L_MFP_PC2_MFP_Msk (1UL<<2) /*!< GPC_MFP PC.2 mask */ #define SYS_PC_L_MFP_PC3_MFP_GPIO 0x00000000UL /*!< GPC_MFP PC.3 setting for GPIO */ #define SYS_PC_L_MFP_PC3_MFP_SPI0_MOSI0 (1UL<<3) /*!< GPC_MFP PC.3 setting for SPI0_MOSI0 */ #define SYS_PC_L_MFP_PC3_MFP_I2S_DO (1UL<<3) /*!< GPC_MFP PC.3 setting for I2S_DO */ #define SYS_PC_L_MFP_PC3_MFP_Msk (1UL<<3) /*!< GPC_MFP PC.3 mask */ #define SYS_PC_L_MFP_PC4_MFP_GPIO 0x00000000UL /*!< GPC_MFP PC.4 setting for GPIO */ #define SYS_PC_L_MFP_PC4_MFP_SPI0_MISO1 (1UL<<4) /*!< GPC_MFP PC.4 setting for SPI0_MISO1 */ #define SYS_PC_L_MFP_PC4_MFP_Msk (1UL<<4) /*!< GPC_MFP PC.4 mask */ #define SYS_PC_L_MFP_PC5_MFP_GPIO 0x00000000UL /*!< GPC_MFP PC.5 setting for GPIO */ #define SYS_PC_L_MFP_PC5_MFP_SPI0_MOSI1 (1UL<<5) /*!< GPC_MFP PC.5 setting for SPI0_MOSI1 */ #define SYS_PC_L_MFP_PC5_MFP_Msk (1UL<<5) /*!< GPC_MFP PC.5 mask */ #define SYS_PC_L_MFP_PC6_MFP_GPIO 0x00000000UL /*!< GPC_MFP PC.6 setting for GPIO */ #define SYS_PC_L_MFP_PC6_MFP_ACMP0_P (1UL<<6) /*!< GPC_MFP PC.6 setting for ACMP0_P */ #define SYS_PC_L_MFP_PC6_MFP_SC0_CD (1UL<<6) /*!< GPC_MFP PC.6 setting for SC0_CD */ #define SYS_PC_L_MFP_PC6_MFP_EBI_AD4 (1UL<<6) /*!< GPC_MFP PC.6 setting for EBI_AD4 */ #define SYS_PC_L_MFP_PC6_MFP_Msk (1UL<<6) /*!< GPC_MFP PC.6 mask */ #define SYS_PC_L_MFP_PC7_MFP_GPIO 0x00000000UL /*!< GPC_MFP PC.7 setting for GPIO */ #define SYS_PC_L_MFP_PC7_MFP_ACMP0_N (1UL<<7) /*!< GPC_MFP PC.7 setting for ACMP0_N */ #define SYS_PC_L_MFP_PC7_MFP_SC1_CD (1UL<<7) /*!< GPC_MFP PC.7 setting for SC1_CD */ #define SYS_PC_L_MFP_PC7_MFP_EBI_AD5 (1UL<<7) /*!< GPC_MFP PC.7 setting for EBI_AD5 */ #define SYS_PC_L_MFP_PC7_MFP_Msk (1UL<<7) /*!< GPC_MFP PC.7 mask */ #define SYS_PC_H_MFP_PC8_MFP_GPIO 0x00000000UL /*!< GPC_MFP PC.8 setting for GPIO */ #define SYS_PC_H_MFP_PC8_MFP_SPI1_SS0 (1UL<<8) /*!< GPC_MFP PC.8 setting for SPI1_SS0 */ #define SYS_PC_H_MFP_PC8_MFP_EBI_MCLK (1UL<<8) /*!< GPC_MFP PC.8 setting for EBI_MCLK */ #define SYS_PC_H_MFP_PC8_MFP_Msk (1UL<<8) /*!< GPC_MFP PC.8 mask */ #define SYS_PC_H_MFP_PC9_MFP_GPIO 0x00000000UL /*!< GPC_MFP PC.9 setting for GPIO */ #define SYS_PC_H_MFP_PC9_MFP_SPI1_CLK (1UL<<9) /*!< GPC_MFP PC.9 setting for SPI1_CLK */ #define SYS_PC_H_MFP_PC9_MFP_Msk (1UL<<9) /*!< GPC_MFP PC.9 mask */ #define SYS_PC_H_MFP_PC10_MFP_GPIO 0x00000000UL /*!< GPC_MFP PC.10 setting for GPIO */ #define SYS_PC_H_MFP_PC10_MFP_SPI1_MISO0 (1UL<<10) /*!< GPC_MFP PC.10 setting for SPI1_MISO0 */ #define SYS_PC_H_MFP_PC10_MFP_Msk (1UL<<10) /*!< GPC_MFP PC.10 mask */ #define SYS_PC_H_MFP_PC11_MFP_GPIO 0x00000000UL /*!< GPC_MFP PC.11 setting for GPIO */ #define SYS_PC_H_MFP_PC11_MFP_SPI1_MOSI0 (1UL<<11) /*!< GPC_MFP PC.11 setting for SPI1_MOSI0 */ #define SYS_PC_H_MFP_PC11_MFP_Msk (1UL<<11) /*!< GPC_MFP PC.11 mask */ #define SYS_PC_H_MFP_PC12_MFP_GPIO 0x00000000UL /*!< GPC_MFP PC.12 setting for GPIO */ #define SYS_PC_H_MFP_PC12_MFP_SPI1_MISO1 (1UL<<12) /*!< GPC_MFP PC.12 setting for SPI1_MISO1 */ #define SYS_PC_H_MFP_PC12_MFP_Msk (1UL<<12) /*!< GPC_MFP PC.12 mask */ #define SYS_PC_H_MFP_PC13_MFP_GPIO 0x00000000UL /*!< GPC_MFP PC.13 setting for GPIO */ #define SYS_PC_H_MFP_PC13_MFP_SPI1_MOSI0 (1UL<<13) /*!< GPC_MFP PC.13 setting for SPI1_MOSI1 */ #define SYS_PC_H_MFP_PC13_MFP_Msk (1UL<<13) /*!< GPC_MFP PC.13 mask */ #define SYS_PC_H_MFP_PC14_MFP_GPIO 0x00000000UL /*!< GPC_MFP PC.14 setting for GPIO */ #define SYS_PC_H_MFP_PC14_MFP_ACMP1_P (1UL<<14) /*!< GPC_MFP PC.14 setting for ACMP1_P */ #define SYS_PC_H_MFP_PC14_MFP_EBI_AD2 (1UL<<14) /*!< GPC_MFP PC.14 setting for EBI_AD2 */ #define SYS_PC_H_MFP_PC14_MFP_Msk (1UL<<14) /*!< GPC_MFP PC.14 mask */ #define SYS_PC_H_MFP_PC15_MFP_GPIO 0x00000000UL /*!< GPC_MFP PC.15 setting for GPIO */ #define SYS_PC_H_MFP_PC15_MFP_ACMP1_N (1UL<<15) /*!< GPC_MFP PC.15 setting for ACMP1_N */ #define SYS_PC_H_MFP_PC15_MFP_EBI_AD3 (1UL<<15) /*!< GPC_MFP PC.15 setting for EBI_AD3 */ #define SYS_PC_H_MFP_PC15_MFP_Msk (1UL<<15) /*!< GPC_MFP PC.15 mask */ #define SYS_PD_L_MFP_PD0_MFP_GPIO 0x00000000UL /*!< GPD_MFP PD.0 setting for GPIO */ #define SYS_PD_L_MFP_PD0_MFP_SPI2_SS0 (1UL<<0) /*!< GPD_MFP PD.0 setting for SPI2_SS0 */ #define SYS_PD_L_MFP_PD0_MFP_Msk (1UL<<0) /*!< GPD_MFP PD.0 mask */ #define SYS_PD_L_MFP_PD1_MFP_GPIO 0x00000000UL /*!< GPD_MFP PD.1 setting for GPIO */ #define SYS_PD_L_MFP_PD1_MFP_SPI2_CLK (1UL<<1) /*!< GPD_MFP PD.1 setting for SPI2_CLK */ #define SYS_PD_L_MFP_PD1_MFP_Msk (1UL<<1) /*!< GPD_MFP PD.1 mask */ #define SYS_PD_L_MFP_PD2_MFP_GPIO 0x00000000UL /*!< GPD_MFP PD.2 setting for GPIO */ #define SYS_PD_L_MFP_PD2_MFP_SPI2_MISO0 (1UL<<2) /*!< GPD_MFP PD.2 setting for SPI2_MISO0 */ #define SYS_PD_L_MFP_PD2_MFP_Msk (1UL<<2) /*!< GPD_MFP PD.2 mask */ #define SYS_PD_L_MFP_PD3_MFP_GPIO 0x00000000UL /*!< GPD_MFP PD.3 setting for GPIO */ #define SYS_PD_L_MFP_PD3_MFP_SPI2_MOSI0 (1UL<<3) /*!< GPD_MFP PD.3 setting for SPI2_MOSI0 */ #define SYS_PD_L_MFP_PD3_MFP_Msk (1UL<<3) /*!< GPD_MFP PD.3 mask */ #define SYS_PD_L_MFP_PD4_MFP_GPIO 0x00000000UL /*!< GPD_MFP PD.4 setting for GPIO */ #define SYS_PD_L_MFP_PD4_MFP_SPI2_MISO1 (1UL<<4) /*!< GPD_MFP PD.4 setting for SPI2_MISO1 */ #define SYS_PD_L_MFP_PD4_MFP_Msk (1UL<<4) /*!< GPD_MFP PD.4 mask */ #define SYS_PD_L_MFP_PD5_MFP_GPIO 0x00000000UL /*!< GPD_MFP PD.5 setting for GPIO */ #define SYS_PD_L_MFP_PD5_MFP_SPI2_MOSI1 (1UL<<5) /*!< GPD_MFP PD.5 setting for SPI2_MOSI1 */ #define SYS_PD_L_MFP_PD5_MFP_Msk (1UL<<5) /*!< GPD_MFP PD.5 mask */ #define SYS_PD_L_MFP_PD6_MFP_GPIO 0x00000000UL /*!< GPD_MFP PD.6 setting for GPIO */ #define SYS_PD_L_MFP_PD6_MFP_CAN0_RX (1UL<<6) /*!< GPD_MFP PD.5 setting for SPI2_MOSI1 */ #define SYS_PD_L_MFP_PD6_MFP_Msk (1UL<<6) /*!< GPD_MFP PD.6 mask */ #define SYS_PD_L_MFP_PD7_MFP_GPIO 0x00000000UL /*!< GPD_MFP PD.7 setting for GPIO */ #define SYS_PD_L_MFP_PD7_MFP_CAN0_TX (1UL<<7) /*!< GPD_MFP PD.5 setting for SPI2_MOSI1 */ #define SYS_PD_L_MFP_PD7_MFP_Msk (1UL<<7) /*!< GPD_MFP PD.7 mask */ #define SYS_PD_H_MFP_PD8_MFP_GPIO 0x00000000UL /*!< GPD_MFP PD.8 setting for GPIO */ #define SYS_PD_H_MFP_PD8_MFP_SPI3_SS0 (1UL<<8) /*!< GPD_MFP PD.8 setting for SPI3_SS0 */ #define SYS_PD_H_MFP_PD8_MFP_Msk (1UL<<8) /*!< GPD_MFP PD.8 mask */ #define SYS_PD_H_MFP_PD9_MFP_GPIO 0x00000000UL /*!< GPD_MFP PD.9 setting for GPIO */ #define SYS_PD_H_MFP_PD9_MFP_SPI3_CLK (1UL<<9) /*!< GPD_MFP PD.9 setting for SPI3_CLK */ #define SYS_PD_H_MFP_PD9_MFP_Msk (1UL<<9) /*!< GPD_MFP PD.9 mask */ #define SYS_PD_H_MFP_PD10_MFP_GPIO 0x00000000UL /*!< GPD_MFP PD.10 setting for GPIO */ #define SYS_PD_H_MFP_PD10_MFP_SPI3_MISO0 (1UL<<10) /*!< GPD_MFP PD.10 setting for SPI3_MISO0 */ #define SYS_PD_H_MFP_PD10_MFP_Msk (1UL<<10) /*!< GPD_MFP PD.10 mask */ #define SYS_PD_H_MFP_PD11_MFP_GPIO 0x00000000UL /*!< GPD_MFP PD.11 setting for GPIO */ #define SYS_PD_H_MFP_PD11_MFP_SPI3_MOSI0 (1UL<<11) /*!< GPD_MFP PD.11 setting for SPI3_MOSI0 */ #define SYS_PD_H_MFP_PD11_MFP_Msk (1UL<<11) /*!< GPD_MFP PD.11 mask */ #define SYS_PD_H_MFP_PD12_MFP_GPIO 0x00000000UL /*!< GPD_MFP PD.12 setting for GPIO */ #define SYS_PD_H_MFP_PD12_MFP_SPI3_MISO1 (1UL<<12) /*!< GPD_MFP PD.12 setting for SPI3_MISO1 */ #define SYS_PD_H_MFP_PD12_MFP_Msk (1UL<<12) /*!< GPD_MFP PD.12 mask */ #define SYS_PD_H_MFP_PD13_MFP_GPIO 0x00000000UL /*!< GPD_MFP PD.13 setting for GPIO */ #define SYS_PD_H_MFP_PD13_MFP_SPI3_MOSI1 (1UL<<13) /*!< GPD_MFP PD.13 setting for SPI3_MOSI1 */ #define SYS_PD_H_MFP_PD13_MFP_Msk (1UL<<13) /*!< GPD_MFP PD.13 mask */ #define SYS_PD_H_MFP_PD14_MFP_GPIO 0x00000000UL /*!< GPD_MFP PD.14 setting for GPIO */ #define SYS_PD_H_MFP_PD14_MFP_UART2_RX (1UL<<14) /*!< GPD_MFP PD.14 setting for UART2_RXD */ #define SYS_PD_H_MFP_PD14_MFP_Msk (1UL<<14) /*!< GPD_MFP PD.14 mask */ #define SYS_PD_H_MFP_PD15_MFP_GPIO 0x00000000UL /*!< GPD_MFP PD.15 setting for GPIO */ #define SYS_PD_H_MFP_PD15_MFP_UART2_TX (1UL<<15) /*!< GPD_MFP PD.15 setting for UART2_TXD */ #define SYS_PD_H_MFP_PD15_MFP_Msk (1UL<<15) /*!< GPD_MFP PD.15 mask */ #define SYS_PE_L_MFP_PE0_MFP_GPIO 0x00000000UL /*!< GPD_MFP PE.0 setting for GPIO */ #define SYS_PE_L_MFP_PE0_MFP_PWM_CH6 (1UL<<0) /*!< GPE_MFP PE.0 setting for PWM6 */ #define SYS_PE_L_MFP_PE0_MFP_Msk (1UL<<0) /*!< GPD_MFP PE.0 mask */ #define SYS_PE_L_MFP_PE1_MFP_GPIO 0x00000000UL /*!< GPD_MFP PE.1 setting for GPIO */ #define SYS_PE_L_MFP_PE1_MFP_PWM_CH7 (1UL<<1) /*!< GPE_MFP PE.1 setting for PWM7 */ #define SYS_PE_L_MFP_PE1_MFP_Msk (1UL<<1) /*!< GPD_MFP PE.1 mask */ #define SYS_PE_L_MFP_PE2_MFP_GPIO 0x00000000UL /*!< GPD_MFP PE.2 setting for GPIO */ #define SYS_PE_L_MFP_PE2_MFP_Msk (1UL<<2) /*!< GPD_MFP PE.2 mask */ #define SYS_PE_L_MFP_PE3_MFP_GPIO 0x00000000UL /*!< GPD_MFP PE.3 setting for GPIO */ #define SYS_PE_L_MFP_PE3_MFP_Msk (1UL<<3) /*!< GPD_MFP PE.3 mask */ #define SYS_PE_L_MFP_PE4_MFP_GPIO 0x00000000UL /*!< GPD_MFP PE.4 setting for GPIO */ #define SYS_PE_L_MFP_PE4_MFP_Msk (1UL<<4) /*!< GPD_MFP PE.4 mask */ #define SYS_PE_L_MFP_PE5_MFP_GPIO 0x00000000UL /*!< GPD_MFP PE.5 setting for GPIO */ #define SYS_PE_L_MFP_PE5_MFP_PWM_CH5 (1UL<<5) /*!< GPE_MFP PE.5 setting for PWM5 */ #define SYS_PE_L_MFP_PE5_MFP_TC1 (1UL<<5) /*!< GPE_MFP PE.5 setting for TC1 */ #define SYS_PE_L_MFP_PE5_MFP_TM1_EXT (1UL<<5) /*!< GPE_MFP PE.5 setting for TM1_EXT */ #define SYS_PE_L_MFP_PE5_MFP_Msk (1UL<<5) /*!< GPD_MFP PE.5 mask */ #define SYS_PF_L_MFP_PF0_MFP_GPIO 0x00000000UL /*!< GPD_MFP PF.0 setting for GPIO */ #define SYS_PF_L_MFP_PF0_MFP_XT1_OUT (1UL<<0) /*!< GPF_MFP PF.0 setting for XT1_OUT */ #define SYS_PF_L_MFP_PF0_MFP_Msk (1UL<<0) /*!< GPD_MFP PF.0 mask */ #define SYS_PF_L_MFP_PF1_MFP_GPIO 0x00000000UL /*!< GPD_MFP PF.1 setting for GPIO */ #define SYS_PF_L_MFP_PF1_MFP_XT1_IN (1UL<<1) /*!< GPF_MFP PF.1 setting for XT1_IN */ #define SYS_PF_L_MFP_PF1_MFP_Msk (1UL<<1) /*!< GPD_MFP PF.1 mask */ #define SYS_PF_L_MFP_PF2_MFP_GPIO 0x00000000UL /*!< GPD_MFP PF.2 setting for GPIO */ #define SYS_PF_L_MFP_PF2_MFP_PS2_DAT (1UL<<2) /*!< GPF_MFP PF.2 setting for PS2_DAT */ #define SYS_PF_L_MFP_PF2_MFP_Msk (1UL<<2) /*!< GPD_MFP PF.2 mask */ #define SYS_PF_L_MFP_PF3_MFP_GPIO 0x00000000UL /*!< GPD_MFP PF.3 setting for GPIO */ #define SYS_PF_L_MFP_PF3_MFP_PS2_CLK (1UL<<3) /*!< GPF_MFP PF.3 setting for PS2_CLK */ #define SYS_PF_L_MFP_PF3_MFP_Msk (1UL<<3) /*!< GPD_MFP PF.3 mask */ extern void SYS_Init(void); #endif <file_sep>/CODE/lab9-1 learning board 211124/Library/NuMakerLib/Source/MLX90614.c #include "NUC100Series.h" #include "I2C.h" #include "MLX90614.h" #define I2C_PORT I2C0 #define I2C_ADDR MLX90614_I2CADDR float MLX90614_readObjectTempF(void) { return (readTemp(MLX90614_TOBJ1) * 9 / 5) + 32; } float MLX90614_readAmbientTempF(void) { return (readTemp(MLX90614_TA) * 9 / 5) + 32; } float MLX90614_readObjectTempC(void) { return readTemp(MLX90614_TOBJ1); } float MLX90614_readAmbientTempC(void) { return readTemp(MLX90614_TA); } uint16_t MLX90614_readID(uint8_t id) { uint16_t devID; if (id==1) devID = read16(MLX90614_ID1); if (id==2) devID = read16(MLX90614_ID2); if (id==3) devID = read16(MLX90614_ID3); if (id==4) devID = read16(MLX90614_ID4); return devID; } float readTemp(uint8_t reg) { float temp; temp = read16(reg); temp *= .02; temp -= 273.15; return temp; } uint16_t read16(uint8_t regAddr) { uint16_t ret; uint8_t data[3]; uint8_t length = 3; uint8_t pec; uint8_t i; I2C_SET_CONTROL_REG(I2C_PORT, I2C_I2CON_STA); //start I2C_WAIT_READY(I2C_PORT); I2C_SET_DATA(I2C_PORT, I2C_ADDR<<1); //send slave address+W I2C_SET_CONTROL_REG(I2C_PORT, I2C_I2CON_SI); I2C_WAIT_READY(I2C_PORT); I2C_SET_DATA(I2C_PORT, regAddr); //send index I2C_SET_CONTROL_REG(I2C_PORT, I2C_I2CON_SI); I2C_WAIT_READY(I2C_PORT); I2C_SET_CONTROL_REG(I2C_PORT, I2C_I2CON_STA_SI);//Repeated Start I2C_WAIT_READY(I2C_PORT); I2C_SET_DATA(I2C_PORT, I2C_ADDR<<1 | 0x01); //send slave address+R I2C_SET_CONTROL_REG(I2C_PORT, I2C_I2CON_SI); I2C_WAIT_READY(I2C_PORT); for (i=0; i<length; i++) { I2C_SET_CONTROL_REG(I2C_PORT, I2C_I2CON_SI_AA);// send Acknowledge I2C_WAIT_READY(I2C_PORT); data[i] = I2C_GET_DATA(I2C_PORT); //read data } I2C_STOP(I2C_PORT); ret = data[0] | data[1]<<8; pec = data[2]; // PEC (Packet Error Code) return ret; } <file_sep>/CODE/lab9-1 learning board 211124/Library/NuMakerLib/Source/rfid.c #include "rfid.h" #include "LCD.h" uint8_t buff[MAXRLEN]; tag_stat find_tag(uint16_t *cardType) { tag_stat status; status=PcdRequest(PICC_REQIDL,buff); if (status==TAG_OK) { *cardType = buff[0]<<8 | buff[1]; } return status; } tag_stat select_tag_sn(uint8_t * sn, uint8_t * len){ if (PcdAnticoll(PICC_ANTICOLL1,buff)!=TAG_OK) {return TAG_ERR;} if (PcdSelect(PICC_ANTICOLL1,buff)!=TAG_OK) {return TAG_ERR;} if (buff[0]==0x88) { memcpy(sn,&buff[1],3); if (PcdAnticoll(PICC_ANTICOLL2,buff)!=TAG_OK) { return TAG_ERR;} if (PcdSelect(PICC_ANTICOLL2,buff)!=TAG_OK) {return TAG_ERR;} if (buff[0]==0x88) { memcpy(sn+3,&buff[1],3); if (PcdAnticoll(PICC_ANTICOLL3,buff)!=TAG_OK) { return TAG_ERR;} if (PcdSelect(PICC_ANTICOLL3,buff)!=TAG_OK) {return TAG_ERR;} memcpy(sn+6,buff,4); *len=10; }else{ memcpy(sn+3,buff,4); *len=7; } }else{ memcpy(sn,&buff[0],4); *len=4; } return TAG_OK; } tag_stat read_tag_str(uint8_t addr, char * str) { tag_stat tmp; char text1[16], text2[16]; uint8_t i; uint8_t buff[MAXRLEN]; tmp=PcdRead(addr,buff); if (tmp==TAG_OK) { for (i=0;i<8;i++) { sprintf(text1,"%2x",(char)buff[i]); *text1+=2; } for (i=8;i<16;i++) { sprintf(text2,"%2x",(char)buff[i]); *text2+=2; } }else if (tmp==TAG_ERRCRC){ sprintf(text1,"CRC Error"); print_Line(3, text1); }else{ sprintf(text1,"Unknown error"); print_Line(3, text1); } return tmp; } <file_sep>/CODE/lab9-1 learning board 211124/Library/NuMakerLib/Include/LM75A.h // // LM75A : Temperature Sensor // #define LM75A_devAddr 0x4F // 0x48~4F set by pin A2,A1,A0 // LM75A Internal Registers #define LM75A_TEMP 0x00 // read only #define LM75A_CONF 0x01 // R/W #define LM75A_THYST 0x02 // R/W #define LM75A_TOS 0x03 // R/W extern void Init_LM75A(void); extern uint8_t LM75A_ReadConfig(void); extern uint16_t LM75A_ReadTemp(void); <file_sep>/CODE/lab10-1 learning board 211201/Nu-LB-NUC140_BSP3.00.004_v1.2/SampleCode/Nu-LB-NUC140/Timer/main.c // // TMR_LED : change LED on/off by Timer1 interrupt // #include <stdio.h> #include "NUC100Series.h" #include "MCU_init.h" #include "SYS_init.h" #include <math.h> #include <string.h> #include "LCD.h" uint8_t ledState = 0; uint32_t keyin = 0; uint32_t i = 5; uint32_t j = 0; void TMR1_IRQHandler(void) { PC14 = ~PC14; TIMER_ClearIntFlag(TIMER1); // Clear Timer1 time-out interrupt flag } void Init_Timer1(void) { TIMER_Open(TIMER1, TMR1_OPERATING_MODE, 5); TIMER_EnableInt(TIMER1); NVIC_EnableIRQ(TMR1_IRQn); TIMER_Start(TIMER1); } int main(void) { SYS_Init(); init_LCD(); clear_LCD(); PD14 = 0; print_Line(0, "timer"); Init_Timer1(); while(1) { } }<file_sep>/CODE/lab9-1 learning board 211124/SampleCode/Nu-LB-NUC140/VR/main.c // // TMR_Capture_SR04 : usi[ng Timer Capture to read Ultrasound Ranger SR-04 // // EVB : Nu-LB-NUC140 (need to manually switch RSTCAPSEL) // MCU : NUC140VE3CN // Sensor: SR-04 // SR-04 connection // Trig connected to PB8 // Echo connected to TC2/PB2 (TC0_PB15, TC1_PE5, TC2_PB2, TC3_PB3) #include <stdio.h> #include "NUC100Series.h" #include "MCU_init.h" #include "SYS_init.h" #include "LCD.h" char Text[16]; void Init_ADC(void) { ADC_Open(ADC, ADC_INPUT_MODE, ADC_OPERATION_MODE, ADC_CHANNEL_MASK); ADC_POWER_ON(ADC); } int32_t main (void) { uint32_t x, y, z; SYS_Init(); Init_ADC(); init_LCD(); clear_LCD(); PD14 = 0; print_Line(0, "VR"); while(1) { ADC_START_CONV(ADC); x = ADC_GET_CONVERSION_DATA(ADC, 0); sprintf(Text,"T = %5d", x); print_Line(1, Text); y = ADC_GET_CONVERSION_DATA(ADC, 1); sprintf(Text,"T = %5d", y); print_Line(2, Text); z = PB0; sprintf(Text,"T = %5d", z); print_Line(3, Text); } }<file_sep>/CODE/lab9-1 learning board 211124/Library/NuMakerLib/Source/ADXL345.c // // ADXL345 : Analog Device 3-axis accelerometer // // Interface: I2C/SPI (CS Hi/Lo) // pin1: Gnd to Vss (NUC123 pin15) // pin2: Vcc to Vdd // pin3: CS to Vdd // pin4: INT1-- N.C. // pin5: INT2-- N.C. // pin6: SDO to Gnd (ALT_Address =0) // pin7: SDA to SDA // pin8: SCL to SCL #include <stdio.h> #include <NUC100Series.h> #include "I2Cdev.h" #include "ADXL345.h" void ADXL345_Init(void) { I2Cdev_writeByte(ADXL345_devAddr, ADXL345_DATA_FORMAT,0x0B); I2Cdev_writeByte(ADXL345_devAddr, ADXL345_BW_RATE,0x0F); I2Cdev_writeByte(ADXL345_devAddr, ADXL345_POWER_CTL,0x08); I2Cdev_writeByte(ADXL345_devAddr, ADXL345_INT_ENABLE,0x80); I2Cdev_writeByte(ADXL345_devAddr, ADXL345_OFSX,0x00); I2Cdev_writeByte(ADXL345_devAddr, ADXL345_OFSY,0x00); I2Cdev_writeByte(ADXL345_devAddr, ADXL345_OFSZ,0x05); } uint16_t ADXL345_ReadAccelX(void) { uint8_t LoByte, HiByte; I2Cdev_readByte(ADXL345_devAddr, ADXL345_DATAX0, LoByte); I2Cdev_readByte(ADXL345_devAddr, ADXL345_DATAX1, HiByte); return((HiByte<<8)|LoByte); } uint16_t ADXL345_ReadAccelY(void) { uint8_t LoByte, HiByte; I2Cdev_readByte(ADXL345_devAddr, ADXL345_DATAY0, LoByte); I2Cdev_readByte(ADXL345_devAddr, ADXL345_DATAY1, HiByte); return((HiByte<<8)|LoByte); } uint16_t ADXL345_ReadAccelZ(void) { uint8_t LoByte, HiByte; I2Cdev_readByte(ADXL345_devAddr, ADXL345_DATAZ0, LoByte); I2Cdev_readByte(ADXL345_devAddr, ADXL345_DATAZ1, HiByte); return((HiByte<<8)|LoByte); } <file_sep>/CODE/lab9-1 learning board 211124/Library/Nu-LB-NUC140/Source/I2Cdev.c #include <stdio.h> #include <stdbool.h> #include "NVT_I2C.h" #include "NUC100Series.h" int8_t I2Cdev_readBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t *data) { uint8_t ErrorFlag; NVT_SetDeviceAddress(devAddr); ErrorFlag = NVT_ReadByteContinue_addr8(regAddr,data, length); #ifdef I2CDEV_SERIAL_DEBUG Serial.print(". Done ("); Serial.print(count, DEC); Serial.println(" read)."); #endif if(ErrorFlag) return 0; else return 1; } int8_t I2Cdev_readByte(uint8_t devAddr, uint8_t regAddr, uint8_t *data) { NVT_SetDeviceAddress(devAddr); NVT_ReadByteContinue_addr8(regAddr, data, 1); return 1; } int8_t I2Cdev_readBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t *data) { uint8_t count, b; if ((count = I2Cdev_readByte(devAddr, regAddr, &b)) != 0) { uint8_t mask = ((1 << length) - 1) << (bitStart - length + 1); b &= mask; b >>= (bitStart - length + 1); *data = b; } return count; } int8_t I2Cdev_readBit(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t *data) { uint8_t b; uint8_t count = I2Cdev_readByte(devAddr, regAddr, &b); *data = b & (1 << bitNum); return count; } int8_t I2Cdev_readWords(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint16_t *data) { return 0; } int8_t I2Cdev_readWord(uint8_t devAddr, uint8_t regAddr, uint16_t *data) { return I2Cdev_readWords(devAddr, regAddr, 1, data); } int8_t I2Cdev_readBitW(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint16_t *data) { uint16_t b = 0; uint8_t count = I2Cdev_readWord(devAddr, regAddr, &b); *data = b & (1 << bitNum); return count; } int8_t I2Cdev_readBitsW(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint16_t *data) { uint8_t count; uint16_t w; if ((count = I2Cdev_readWord(devAddr, regAddr, &w)) != 0) { uint16_t mask = ((1 << length) - 1) << (bitStart - length + 1); w &= mask; w >>= (bitStart - length + 1); *data = w; } return count; } bool I2Cdev_writeBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t* data) { NVT_SetDeviceAddress(devAddr); NVT_WriteByteContinue_addr8(regAddr,data, length); return 1; } bool I2Cdev_writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t data) { return I2Cdev_writeBytes(devAddr, regAddr, 1, &data); } bool I2Cdev_writeBit(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t data) { uint8_t b; I2Cdev_readByte(devAddr, regAddr, &b); b = (data != 0) ? (b | (1 << bitNum)) : (b & ~(1 << bitNum)); return I2Cdev_writeByte(devAddr, regAddr, b); } bool I2Cdev_writeBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t data) { uint8_t b; uint8_t mask; if (I2Cdev_readByte(devAddr, regAddr, &b) != 0) { mask = ((1 << length) - 1) << (bitStart - length + 1); data <<= (bitStart - length + 1); data &= mask; b &= ~(mask); b |= data; return I2Cdev_writeByte(devAddr, regAddr, b); } else { return false; } } bool I2Cdev_writeWords(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint16_t* data) { return false; } bool I2Cdev_writeWord(uint8_t devAddr, uint8_t regAddr, uint16_t data) { return I2Cdev_writeWords(devAddr, regAddr, 1, &data); } bool I2Cdev_writeBitW(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint16_t data) { uint16_t w; I2Cdev_readWord(devAddr, regAddr, &w); w = (data != 0) ? (w | (1 << bitNum)) : (w & ~(1 << bitNum)); return I2Cdev_writeWord(devAddr, regAddr, w); } bool I2Cdev_writeBitsW(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint16_t data) { return false; } <file_sep>/CODE/lab9-1 learning board 211124/Library/NuMakerLib/Source/RC522.c #include <string.h> #include <stdio.h> #include "NUC100Series.h" #include "SPI.h" #include "RC522.h" void initRC522(void) { PcdReset(); PcdAntennaOn(); } //------------------------------------------------------------------ //Function : Find Card //Parameter: req_code[IN] = sensing method // 0x52 = look for all cards that match 14443A standard // 0x26 = look for non-sleep card // pTagType[OUT]:card type // 0x4400 = Mifare_UltraLight // 0x0400 = Mifare_One(S50) // 0x0200 = Mifare_One(S70) // 0x0800 = Mifare_Pro(X) // 0x4403 = Mifare_DESFire //Return: TAG_OK if succeed //------------------------------------------------------------------ char PcdRequest(uint8_t req_code,uint8_t *pTagType) { char status; uint8_t unLen; uint8_t ucComMF522Buf[MAXRLEN]; WriteRawRC(BitFramingReg,0x07); ucComMF522Buf[0] = req_code; status = PcdComMF522(PCD_TRANSCEIVE,ucComMF522Buf,1,ucComMF522Buf,&unLen); if ((status == TAG_OK) && (unLen == 0x10)) { *pTagType = ucComMF522Buf[0]; *(pTagType+1) = ucComMF522Buf[1]; } else if (status == TAG_COLLISION) { // printf("ATQA %02x%02x\n",ucComMF522Buf[0],ucComMF522Buf[1]); } else if (status!=TAG_NOTAG) { status = TAG_ERR; } return status; } //------------------------------------------------------------------ //Function : Avoid Collision //Parameter: pSnr[OUT] = card serial number (4 bytes) //Return : TAG_OK if succeed //------------------------------------------------------------------ char PcdAnticoll(uint8_t cascade, uint8_t *pSnr) { char status; uint8_t i,snr_check=0; uint8_t unLen; uint8_t ucComMF522Buf[MAXRLEN]; uint8_t pass=32; uint8_t collbits=0; i=0; WriteRawRC(BitFramingReg,0x00); do { ucComMF522Buf[0] = cascade; ucComMF522Buf[1] = 0x20+collbits; // WriteRawRC(0x0e,0); status = PcdComMF522(PCD_TRANSCEIVE,ucComMF522Buf,2+i,ucComMF522Buf,&unLen); if (status == TAG_COLLISION) { collbits=ReadRawRC(CollReg)&0x1f; if (collbits==0) collbits=32; i=(collbits-1)/8 +1; // printf ("--- %02x %02x %02x %02x %d\n",ucComMF522Buf[0],ucComMF522Buf[1],ucComMF522Buf[2],ucComMF522Buf[3],unLen); ucComMF522Buf[i-1]|=(1<<((collbits-1)%8)); ucComMF522Buf[5]=ucComMF522Buf[3]; ucComMF522Buf[4]=ucComMF522Buf[2]; ucComMF522Buf[3]=ucComMF522Buf[1]; ucComMF522Buf[2]=ucComMF522Buf[0]; WriteRawRC(BitFramingReg,(collbits % 8)); // printf (" %d %d %02x %d\n",collbits,i,ucComMF522Buf[i+1],collbits % 8); } } while (((--pass)>0)&&(status==TAG_COLLISION)); if (status == TAG_OK) { for (i=0; i<4; i++) { *(pSnr+i) = ucComMF522Buf[i]; snr_check ^= ucComMF522Buf[i]; } if (snr_check != ucComMF522Buf[i]) { status = TAG_ERR; } } return status; } //------------------------------------------------------------------ //Function : Select Card //Parameter: pSnr[IN] = card serial number (4 bytes) //Return : TAG_OK if succeed //------------------------------------------------------------------ char PcdSelect(uint8_t cascade, uint8_t *pSnr) { char status; uint8_t i; uint8_t unLen; uint8_t ucComMF522Buf[MAXRLEN]; ucComMF522Buf[0] = cascade; ucComMF522Buf[1] = 0x70; ucComMF522Buf[6] = 0; for (i=0; i<4; i++) { ucComMF522Buf[i+2] = *(pSnr+i); ucComMF522Buf[6] ^= *(pSnr+i); } CalulateCRC(ucComMF522Buf,7,&ucComMF522Buf[7]); ClearBitMask(Status2Reg,0x08); status = PcdComMF522(PCD_TRANSCEIVE,ucComMF522Buf,9,ucComMF522Buf,&unLen); if ((status == TAG_OK) && (unLen == 0x18)) { status = TAG_OK; } else { status = TAG_ERR; } return status; } //------------------------------------------------------------------ //Function : verify card password //Parameter: auth_mode[IN] = password authentication mode // 0x60 = authentication key A // 0x61 = authentication key B // addr[IN] = block address // pKey[IN] = password // pSnr[IN] = card serial number (4 bytes) //Return : TAG_OK if succeed //------------------------------------------------------------------ char PcdAuthState(uint8_t auth_mode,uint8_t addr,uint8_t *pKey,uint8_t *pSnr) { char status; uint8_t unLen; uint8_t ucComMF522Buf[MAXRLEN]; ucComMF522Buf[0] = auth_mode; ucComMF522Buf[1] = addr; memcpy(&ucComMF522Buf[2], pKey, 6); memcpy(&ucComMF522Buf[8], pSnr, 4); status = PcdComMF522(PCD_AUTHENT,ucComMF522Buf,12,ucComMF522Buf,&unLen); if ((status != TAG_OK) || (!(ReadRawRC(Status2Reg) & 0x08))) { status = TAG_ERR; } return status; } //------------------------------------------------------------------ //Function : read data from M1 card //Parameter: addr[IN] = block address // pData[OUT] = read data (16 bytes) //Return : TAG_OK if succeed //------------------------------------------------------------------ char PcdRead(uint8_t addr,uint8_t *p ) { char status; uint8_t unLen; uint8_t i,ucComMF522Buf[MAXRLEN]; uint8_t CRC_buff[2]; memset(ucComMF522Buf,0,sizeof(ucComMF522Buf)); ucComMF522Buf[0] = PICC_READ; ucComMF522Buf[1] = addr; CalulateCRC(ucComMF522Buf,2,&ucComMF522Buf[2]); status = PcdComMF522(PCD_TRANSCEIVE,ucComMF522Buf,4,ucComMF522Buf,&unLen); CalulateCRC(ucComMF522Buf,16,CRC_buff); if ((status == TAG_OK) && (unLen == 0x90)) { if ((CRC_buff[0]!=ucComMF522Buf[16])||(CRC_buff[1]!=ucComMF522Buf[17])) { status = TAG_ERRCRC; } for (i=0; i<16; i++) { *(p +i) = ucComMF522Buf[i]; } } else { status = TAG_ERR; } return status; } //------------------------------------------------------------------ //Function : read 1 block from M1 card //Parameter: addr[IN] = block address // pData[OUT] = read data (16 bytes) //Return : TAG_OK if succeed //------------------------------------------------------------------ char Read_Block(unsigned char Block,unsigned char *Buf) { char result; result = PcdAuthState(0x60,Block,Password,UID); if(result!=TAG_OK) return result; result = PcdRead(Block, Buf); if(result!=TAG_OK) return result; if(Block!=0x00&&des_on) { // Des_Decrypt((char *)Buf ,KK,(char *)Buf ); // Des_Decrypt((char *)&Buf[8],KK,(char *)&Buf[8]); } return 1; } //------------------------------------------------------------------ //Function : write data to M1 card //Parameter: addr[IN] = block address // pData[OUT] = write data (16 bytes) //Return : TAG_OK if succeed //------------------------------------------------------------------ char PcdWrite(uint8_t addr,uint8_t *p ) { char status; uint8_t unLen; uint8_t i,ucComMF522Buf[MAXRLEN]; ucComMF522Buf[0] = PICC_WRITE; ucComMF522Buf[1] = addr; CalulateCRC(ucComMF522Buf,2,&ucComMF522Buf[2]); status = PcdComMF522(PCD_TRANSCEIVE,ucComMF522Buf,4,ucComMF522Buf,&unLen); if ((status != TAG_OK) || (unLen != 4) || ((ucComMF522Buf[0] & 0x0F) != 0x0A)) { status = TAG_ERR; } if (status == TAG_OK) { for (i=0; i<16; i++) { ucComMF522Buf[i] = *(p +i); } CalulateCRC(ucComMF522Buf,16,&ucComMF522Buf[16]); status = PcdComMF522(PCD_TRANSCEIVE,ucComMF522Buf,18,ucComMF522Buf,&unLen); if ((status != TAG_OK) || (unLen != 4) || ((ucComMF522Buf[0] & 0x0F) != 0x0A)) { status = TAG_ERR; } } return status; } //------------------------------------------------------------------ //Function : write 1 block from M1 card //Parameter: addr[IN] = block address // pData[OUT] = write data (16 bytes) //Return : TAG_OK if succeed //------------------------------------------------------------------ char Write_Block(unsigned char Block) { char result; if(des_on) { // Des_Encrypt((char *)RF_Buffer ,KK, // (char *)RF_Buffer );// for debug // Des_Encrypt((char *)&RF_Buffer[8],KK, // (char *)&RF_Buffer[8] );// for debug } result = PcdAuthState(0x60,Block,Password,UID) ; if(result!=TAG_OK) return result; result = PcdWrite(Block,RF_Buffer); return result; } //------------------------------------------------------------------ //Function : Deduction & Charge //Parameter: dd_mode[IN] = command // 0xC0 = Deduction // 0xC1 = Charge // addr[IN] = Wallet Address // pValue[IN]:4 bytes increment/decduction value (LSB first) //Return : TAG_OK if succeed //------------------------------------------------------------------ char PcdValue(unsigned char dd_mode,unsigned char addr,unsigned char *pValue) { char status; unsigned char unLen; unsigned char i,ucComMF522Buf[MAXRLEN]; ucComMF522Buf[0] = dd_mode; ucComMF522Buf[1] = addr; CalulateCRC(ucComMF522Buf,2,&ucComMF522Buf[2]); status = PcdComMF522(PCD_TRANSCEIVE,ucComMF522Buf,4,ucComMF522Buf,&unLen); if ((status != TAG_OK) || (unLen != 4) || ((ucComMF522Buf[0] & 0x0F) != 0x0A)) { status = TAG_ERR; } if (status == TAG_OK) { for (i=0; i<16; i++) { ucComMF522Buf[i] = *(pValue+i); } CalulateCRC(ucComMF522Buf,4,&ucComMF522Buf[4]); unLen = 0; status = PcdComMF522(PCD_TRANSCEIVE,ucComMF522Buf,6,ucComMF522Buf,&unLen); if (status != TAG_ERR) { status = TAG_OK; } } if (status == TAG_OK) { ucComMF522Buf[0] = PICC_TRANSFER; ucComMF522Buf[1] = addr; CalulateCRC(ucComMF522Buf,2,&ucComMF522Buf[2]); status = PcdComMF522(PCD_TRANSCEIVE,ucComMF522Buf,4,ucComMF522Buf,&unLen); if ((status != TAG_OK) || (unLen != 4) || ((ucComMF522Buf[0] & 0x0F) != 0x0A)) { status = TAG_ERR; } } return status; } char PcdBakValue(unsigned char sourceaddr, unsigned char goaladdr) { char status; unsigned char unLen; unsigned char ucComMF522Buf[MAXRLEN]; ucComMF522Buf[0] = PICC_RESTORE; ucComMF522Buf[1] = sourceaddr; CalulateCRC(ucComMF522Buf,2,&ucComMF522Buf[2]); status = PcdComMF522(PCD_TRANSCEIVE,ucComMF522Buf,4,ucComMF522Buf,&unLen); if ((status != TAG_OK) || (unLen != 4) || ((ucComMF522Buf[0] & 0x0F) != 0x0A)) { status = TAG_ERR; } if (status == TAG_OK) { ucComMF522Buf[0] = 0; ucComMF522Buf[1] = 0; ucComMF522Buf[2] = 0; ucComMF522Buf[3] = 0; CalulateCRC(ucComMF522Buf,4,&ucComMF522Buf[4]); status = PcdComMF522(PCD_TRANSCEIVE,ucComMF522Buf,6,ucComMF522Buf,&unLen); if (status != TAG_ERR) { status = TAG_OK; } } if (status != TAG_OK) { return TAG_ERR; } ucComMF522Buf[0] = PICC_TRANSFER; ucComMF522Buf[1] = goaladdr; CalulateCRC(ucComMF522Buf,2,&ucComMF522Buf[2]); status = PcdComMF522(PCD_TRANSCEIVE,ucComMF522Buf,4,ucComMF522Buf,&unLen); if ((status != TAG_OK) || (unLen != 4) || ((ucComMF522Buf[0] & 0x0F) != 0x0A)) { status = TAG_ERR; } return status; } char PcdHalt(void) { uint8_t status; uint8_t unLen; uint8_t ucComMF522Buf[MAXRLEN]; ucComMF522Buf[0] = PICC_HALT; ucComMF522Buf[1] = 0; CalulateCRC(ucComMF522Buf,2,&ucComMF522Buf[2]); status = PcdComMF522(PCD_TRANSCEIVE,ucComMF522Buf,4,ucComMF522Buf,&unLen); return status; } //------------------------------------------------------------------ // MF522 CRC16 //------------------------------------------------------------------ void CalulateCRC(uint8_t *pIn ,uint8_t len,uint8_t *pOut ) { uint8_t i,n; ClearBitMask(DivIrqReg,0x04); WriteRawRC(CommandReg,PCD_IDLE); SetBitMask(FIFOLevelReg,0x80); for (i=0; i<len; i++) { WriteRawRC(FIFODataReg, *(pIn +i)); } WriteRawRC(CommandReg, PCD_CALCCRC); i = 0xFF; do { n = ReadRawRC(DivIrqReg); i--; } while ((i!=0) && !(n&0x04)); pOut [0] = ReadRawRC(CRCResultRegL); pOut [1] = ReadRawRC(CRCResultRegM); } char PcdReset(void) { WriteRawRC(CommandReg,PCD_RESETPHASE); CLK_SysTickDelay(10000); ClearBitMask(TxControlReg,0x03); CLK_SysTickDelay(10000); SetBitMask(TxControlReg,0x03); WriteRawRC(TModeReg,0x8D); WriteRawRC(TPrescalerReg,0x3E); WriteRawRC(TReloadRegL,30); WriteRawRC(TReloadRegH,0); WriteRawRC(TxASKReg,0x40); WriteRawRC(ModeReg,0x3D); //6363 // WriteRawRC(DivlEnReg,0x90); WriteRawRC(RxThresholdReg,0x84); WriteRawRC(RFCfgReg,0x68); WriteRawRC(GsNReg,0xff); WriteRawRC(CWGsCfgReg,0x2f); // WriteRawRC(ModWidthReg,0x2f); return TAG_OK; } /* char M500PcdConfigISOType(uint8_t type) { if (type == 'A') { ClearBitMask(Status2Reg,0x08); WriteRawRC(ModeReg,0x3D); WriteRawRC(RxSelReg,0x86); WriteRawRC(RFCfgReg,0x7F); WriteRawRC(TReloadRegL,30); WriteRawRC(TReloadRegH,0); WriteRawRC(TModeReg,0x8D); WriteRawRC(TPrescalerReg,0x3E); PcdAntennaOn(); } else{ return 1; } return TAG_OK; } */ uint8_t ReadRawRC(uint8_t Address) { uint8_t result; SPI_SET_SS0_LOW(RC522_SPI_PORT); SPI_WRITE_TX0(RC522_SPI_PORT, (Address<<1) | 0x80); // bit7 = 1 : Read SPI_TRIGGER(RC522_SPI_PORT); while(SPI_IS_BUSY(RC522_SPI_PORT)); SPI_WRITE_TX0(RC522_SPI_PORT, 0xff); SPI_TRIGGER(RC522_SPI_PORT); while(SPI_IS_BUSY(RC522_SPI_PORT)); result = RC522_SPI_PORT->RX[0]; SPI_SET_SS0_HIGH(RC522_SPI_PORT); return result; } void WriteRawRC(uint8_t Address, uint8_t Data) { SPI_SET_SS0_LOW(RC522_SPI_PORT); SPI_WRITE_TX0(RC522_SPI_PORT, (Address<<1) & 0x7F); // bit7 = 0 : Write SPI_TRIGGER(RC522_SPI_PORT); while(SPI_IS_BUSY(RC522_SPI_PORT)); SPI_WRITE_TX0(RC522_SPI_PORT, Data); SPI_TRIGGER(RC522_SPI_PORT); while(SPI_IS_BUSY(RC522_SPI_PORT)); SPI_SET_SS0_HIGH(RC522_SPI_PORT); } void SetBitMask(uint8_t reg,uint8_t mask) { char tmp = 0x0; tmp = ReadRawRC(reg); WriteRawRC(reg,tmp | mask); // set bit mask } void ClearBitMask(uint8_t reg,uint8_t mask) { char tmp = 0x0; tmp = ReadRawRC(reg); WriteRawRC(reg, tmp & ~mask); // clear bit mask } char PcdComMF522(uint8_t Command, uint8_t *pIn , uint8_t InLenByte, uint8_t *pOut , uint8_t *pOutLenBit) { char status = TAG_ERR; uint8_t irqEn = 0x00; uint8_t waitFor = 0x00; uint8_t lastBits; uint8_t n; uint32_t i; uint8_t PcdErr; // printf("CMD %02x\n",pIn[0]); switch (Command) { case PCD_AUTHENT: irqEn = 0x12; waitFor = 0x10; break; case PCD_TRANSCEIVE: irqEn = 0x77; waitFor = 0x30; break; default: break; } WriteRawRC(ComIEnReg,irqEn|0x80); // WriteRawRC(ComIEnReg,irqEn); ClearBitMask(ComIrqReg,0x80); SetBitMask(FIFOLevelReg,0x80); WriteRawRC(CommandReg,PCD_IDLE); for (i=0; i<InLenByte; i++) { WriteRawRC(FIFODataReg, pIn [i]); } WriteRawRC(CommandReg, Command); if (Command == PCD_TRANSCEIVE) { SetBitMask(BitFramingReg,0x80); } //i = 600;//���ʱ��Ƶ�ʵ������M1�����ȴ�ʱ��25ms i = 150; do { CLK_SysTickDelay(200); n = ReadRawRC(ComIrqReg); i--; } while ((i!=0) && (!(n&0x01)) && (!(n&waitFor))); ClearBitMask(BitFramingReg,0x80); if (i!=0) { PcdErr=ReadRawRC(ErrorReg); if (!(PcdErr & 0x11)) { status = TAG_OK; if (n & irqEn & 0x01) {status = TAG_NOTAG;} if (Command == PCD_TRANSCEIVE) { n = ReadRawRC(FIFOLevelReg); lastBits = ReadRawRC(ControlReg) & 0x07; if (lastBits) {*pOutLenBit = (n-1)*8 + lastBits;} else {*pOutLenBit = n*8;} if (n == 0) {n = 1;} if (n > MAXRLEN) {n = MAXRLEN;} for (i=0; i<n; i++) { pOut [i] = ReadRawRC(FIFODataReg); //printf (".%02X ",pOut[i]); } } } else { //printf (stderr,"Err %02x\n",PcdErr); status = TAG_ERR;} if (PcdErr&0x08) { status = TAG_COLLISION; } } // SetBitMask(ControlReg,0x80); // stop timer now // WriteRawRC(CommandReg,PCD_IDLE); ??????? // printf ("PCD Err %02x\n",PcdErr); return status; } void PcdAntennaOn(void) { uint8_t i; i = ReadRawRC(TxControlReg); if (!(i & 0x03)) { SetBitMask(TxControlReg, 0x03); } } void PcdAntennaOff(void) { ClearBitMask(TxControlReg, 0x03); } <file_sep>/CODE/lab8-1 learning board 211117/Nu-LB-NUC140_BSP3.00.004_v1.2/SampleCode/Nu-LB-NUC140/UART0_RX/main.c // // UART0_RX : UART0 RX recieve and display Text // // Board : Nu-LB-NUC140 // MCU : NUC140VE3CN (LQFP100) // UART0 : baudrate=115200, databit=8, stopbit=1, paritybit=0, flowcontrol=None #include <stdio.h> #include <math.h> #include <string.h> #include "NUC100Series.h" #include "MCU_init.h" #include "SYS_init.h" #include "LCD.h" void Init_UART(void) { UART_Open(UART0, 9600); // set UART0 baud rate } int32_t main() { char TX_Buffer[16]; char RX_Buffer[16]; uint32_t keyin = 0; SYS_Init(); init_LCD(); clear_LCD(); Init_UART(); PD14 = 0; print_Line(0, "test TX and RX:"); sprintf(TX_Buffer, "TX123"); while(1) { keyin = ScanKey(); if(keyin == 1) { print_Line(1, "send!!!"); UART_Write(UART0, TX_Buffer, 5); CLK_SysTickDelay(1000000); break; } } while(1) { UART_Read(UART0, RX_Buffer, 5); print_Line(2, RX_Buffer); CLK_SysTickDelay(1000000); } } <file_sep>/CODE/lab5-1 learning board 211020/Nu-LB-NUC140_BSP3.00.004_v1.2/SampleCode/Nu-LB-NUC140/GPIO_7seg_keypad/main.c // // GPIO_7seg_keypad : 3x3 keypad inpt and display on 7-segment LEDs // #include <stdio.h> #include "NUC100Series.h" #include "MCU_init.h" #include "SYS_init.h" #include "Seven_Segment.h" #include "Scankey.h" #include "LCD.h" // display an integer on four 7-segment LEDs int main(void) { uint16_t i; SYS_Init(); init_LCD(); clear_LCD(); OpenSevenSegment(); OpenKeyPad(); PD14 = 0; while(1) { i = ScanKey(); Display_7seg(i); print_Line(0, "Nu-LB-NUC140"); print_Line(1, "1 3 5 7 9 "); } } <file_sep>/CODE/lab9-1 learning board 211124/Library/Nu-LB-NUC140/Source/NVT_I2C.c #include <stdio.h> #include "NUC100Series.h" #include "NVT_I2C.h" #define I2C_PORT I2C0 #define BUSERROR 1 #define ARBITLOSS 2 #define TIMEOUT 4 #define I2CFUNC TIMEOUT #define DEBUG_PRINT printf /*---------------------------------------------------------------------------------------------------------*/ /* Global variables */ /*---------------------------------------------------------------------------------------------------------*/ uint8_t Device_W_Addr; uint8_t Device_R_Addr; uint8_t ReadFlag; uint8_t Tx_Data0[MAX_I2C_DATA_LEN]; uint8_t Rx_Data0[MAX_I2C_DATA_LEN]; uint8_t DataLen0; uint8_t RxLen0; uint8_t ContinueLen; volatile uint8_t EndFlag0 = 0; volatile uint8_t ErrorFlag = 0; uint8_t Addr1[3] = {0}; uint8_t DataLen1; uint8_t Slave_Buff1[32] = {0}; uint16_t Slave_Buff_Addr1; //extern void DelayUsec(unsigned int usec); //extern void DelayMsec(unsigned int usec); typedef void (*I2C_FUNC)(uint32_t u32Status); static volatile I2C_FUNC s_I2C0HandlerFn = NULL; static volatile I2C_FUNC s_I2C1HandlerFn = NULL; void DelayUsec(uint32_t us) { CLK_SysTickDelay(us); } void DelayMsec(uint32_t ms) { CLK_SysTickDelay(ms * 1000); } void I2CX_IRQHandler(uint8_t id) { uint32_t u32Status; u32Status = I2C_GET_STATUS(I2C_PORT); if(I2C_GET_TIMEOUT_FLAG(I2C_PORT)) { ErrorFlag = 1; /* Clear I2C0 Timeout Flag */ I2C_ClearTimeoutFlag(I2C_PORT); } else { switch (u32Status) { case 0x38:{/* Arbitration loss */ I2C_SET_CONTROL_REG(I2C_PORT, I2C_CTL_STO_SI); I2C_SET_CONTROL_REG(I2C_PORT, I2C_CTL_STA); //printf("I2C Arbitration loss\n"); break;} case 0x00: /* Bus error */ case 0x30: case 0xF8: case 0x48: { I2C_SET_CONTROL_REG(I2C_PORT, I2C_CTL_STO_SI); //I2C_SET_CONTROL_REG(I2C_PORT, I2C_CTL_SI); I2C_SET_CONTROL_REG(I2C_PORT, I2C_CTL_STA); //printf("I2C bus error\n"); break;} default: { if(id==0) { if(s_I2C0HandlerFn != NULL) s_I2C0HandlerFn(u32Status); } else if(id==1) { if(s_I2C1HandlerFn != NULL) s_I2C1HandlerFn(u32Status); } } } } } void I2C0_IRQHandler(void) { I2CX_IRQHandler(0); } void I2C1_IRQHandler(void) { I2CX_IRQHandler(1); } /*---------------------------------------------------------------------------------------------------------*/ /* I2C (Master) Rx Callback Function */ /*---------------------------------------------------------------------------------------------------------*/ void I2C_Callback_Rx(uint32_t status) { if (status == 0x08) /* START has been transmitted and prepare SLA+W */ { I2C_SetData(I2C_PORT, Device_W_Addr<<1); I2C_Ctrl(I2C_PORT, 0, 0, 1, 0); } else if (status == 0x18) /* SLA+W has been transmitted and ACK has been received */ { I2C_SetData(I2C_PORT, Tx_Data0[DataLen0++]); I2C_Ctrl(I2C_PORT, 0, 0, 1, 0); } else if (status == 0x20) /* SLA+W has been transmitted and NACK has been received */ { I2C_Ctrl(I2C_PORT, 0, 1, 1, 0); } else if (status == 0x28) /* DATA has been transmitted and ACK has been received */ { if (DataLen0 != 2) { I2C_SetData(I2C_PORT, Tx_Data0[DataLen0++]); I2C_Ctrl(I2C_PORT, 0, 0, 1, 0); } else { I2C_Ctrl(I2C_PORT, 1, 0, 1, 0); EndFlag0 = 1; } } else if (status == 0x10) /* Repeat START has been transmitted and prepare SLA+R */ { I2C_SetData(I2C_PORT, Device_W_Addr<<1 | 0x01); I2C_Ctrl(I2C_PORT, 0, 0, 1, 0); } else if (status == 0x40) /* SLA+R has been transmitted and ACK has been received */ { I2C_Ctrl(I2C_PORT, 0, 0, 1, 0); } else if (status == 0x58) /* DATA has been received and NACK has been returned */ { Rx_Data0[0] = I2C_GetData(I2C_PORT); I2C_Ctrl(I2C_PORT, 0, 1, 1, 0); EndFlag0 = 1; } else { DEBUG_PRINT("Status 0x%x is NOT processed\n", status); } } void I2C_Callback_Rx_Continue(uint32_t status) { if (status == 0x08) /* START has been transmitted and prepare SLA+W */ { I2C_SetData(I2C_PORT, Device_W_Addr<<1|ReadFlag); I2C_Ctrl(I2C_PORT, 0, 0, 1, 0); } else if (status == 0x18) /* SLA+W has been transmitted and ACK has been received */ { I2C_SetData(I2C_PORT, Tx_Data0[DataLen0++]); I2C_Ctrl(I2C_PORT, 0, 0, 1, 0); } else if (status == 0x20) /* SLA+W has been transmitted and NACK has been received */ { I2C_Ctrl(I2C_PORT, 0, 1, 1, 0); } else if (status == 0x28) /* DATA has been transmitted and ACK has been received */ { I2C_Ctrl(I2C_PORT, 1, 0, 1, 0); } else if (status == 0x10) /* Repeat START has been transmitted and prepare SLA+R */ { I2C_SetData(I2C_PORT, Device_W_Addr<<1 | 0x01); I2C_Ctrl(I2C_PORT, 0, 0, 1, 0); } else if (status == 0x40) /* SLA+R has been transmitted and ACK has been received */ { if(ContinueLen>1) I2C_Ctrl(I2C_PORT, 0, 0, 1, 1); else I2C_Ctrl(I2C_PORT, 0, 0, 1, 0); } else if (status == 0x58) /* DATA has been received and NACK has been returned */ { Rx_Data0[RxLen0++] = I2C_GetData(I2C_PORT); I2C_Ctrl(I2C_PORT, 0, 1, 1, 0); EndFlag0 = 1; } else if (status == 0x50) /* DATA has been received and ACK has been returned */ { Rx_Data0[RxLen0++] = I2C_GetData(I2C_PORT); if(RxLen0<(ContinueLen-1)) I2C_Ctrl(I2C_PORT, 0, 0, 1, 1); else I2C_Ctrl(I2C_PORT, 0, 0, 1, 0); } else { DEBUG_PRINT("Status 0x%x is NOT processed\n", status); } } /*---------------------------------------------------------------------------------------------------------*/ /* I2C (Master) Tx Callback Function */ /*---------------------------------------------------------------------------------------------------------*/ void I2C_Callback_Tx(uint32_t status) { if (status == 0x08) /* START has been transmitted */ { I2C_SetData(I2C_PORT, Device_W_Addr<<1); I2C_Ctrl(I2C_PORT, 0, 0, 1, 0); } else if (status == 0x18) /* SLA+W has been transmitted and ACK has been received */ { I2C_SetData(I2C_PORT, Tx_Data0[DataLen0++]); I2C_Ctrl(I2C_PORT, 0, 0, 1, 0); } else if (status == 0x20) /* SLA+W has been transmitted and NACK has been received */ { I2C_Ctrl(I2C_PORT, 1, 1, 1, 0); } else if (status == 0x28) /* DATA has been transmitted and ACK has been received */ { if (DataLen0 != 3) { I2C_SetData(I2C_PORT, Tx_Data0[DataLen0++]); I2C_Ctrl(I2C_PORT, 0, 0, 1, 0); } else { I2C_Ctrl(I2C_PORT, 0, 1, 1, 0); EndFlag0 = 1; } } else { DEBUG_PRINT("Status 0x%x is NOT processed\n", status); } } void I2C_Callback_Tx_Continue(uint32_t status) { if (status == 0x08) /* START has been transmitted */ { I2C_SetData(I2C_PORT, Device_W_Addr<<1); I2C_Ctrl(I2C_PORT, 0, 0, 1, 0); } else if (status == 0x18) /* SLA+W has been transmitted and ACK has been received */ { I2C_SetData(I2C_PORT, Tx_Data0[DataLen0++]); I2C_Ctrl(I2C_PORT, 0, 0, 1, 0); } else if (status == 0x20) /* SLA+W has been transmitted and NACK has been received */ { I2C_Ctrl(I2C_PORT, 1, 1, 1, 0); } else if (status == 0x28) /* DATA has been transmitted and ACK has been received */ { if (DataLen0 != ContinueLen) { I2C_SetData(I2C_PORT, Tx_Data0[DataLen0++]); I2C_Ctrl(I2C_PORT, 0, 0, 1, 0); } else { I2C_Ctrl(I2C_PORT, 0, 1, 1, 0); EndFlag0 = 1; } } else { DEBUG_PRINT("Status 0x%x is NOT processed\n", status); } } void ResetPort() { I2C_Open(I2C_PORT, 400000); I2C_EnableTimeout(I2C_PORT, 1); I2C_EnableInt(I2C_PORT); DelayMsec(4); ErrorFlag = 0; I2C_ClearTimeoutFlag(I2C_PORT); } void WaitEndFlag0(uint16_t timeout) { if(timeout) I2C_EnableTimeout(I2C_PORT, (uint8_t) timeout); while (EndFlag0 == 0) { if(ErrorFlag) { break; } }; I2C_DisableTimeout(I2C_PORT); } void NVT_WriteByte(uint16_t address,uint8_t data) { Tx_Data0[0]=address>>8; Tx_Data0[1]=(address&0xff); Tx_Data0[2] = data; DataLen0 = 0; EndFlag0 = 0; s_I2C0HandlerFn = (I2C_FUNC)I2C_Callback_Tx; s_I2C1HandlerFn = (I2C_FUNC)I2C_Callback_Tx; while(I2C_PORT->I2CON & I2C_I2CON_STO_Msk); I2C_Ctrl(I2C_PORT, 1, 0, 0, 0); WaitEndFlag0(0); } void NVT_WriteByteContinue(uint16_t address,uint8_t* data, uint8_t len) { uint8_t i; uint8_t check_sum=0; Tx_Data0[0]=address>>8; Tx_Data0[1]=(address&0xff); for(i=0;i<len;i++) Tx_Data0[2+i]=data[i]; DataLen0 = 0; EndFlag0 = 0; ContinueLen=len+2; s_I2C0HandlerFn = (I2C_FUNC)I2C_Callback_Tx_Continue; s_I2C1HandlerFn = (I2C_FUNC)I2C_Callback_Tx_Continue; while(I2C_PORT->I2CON & I2C_I2CON_STO_Msk); I2C_Ctrl(I2C_PORT, 1, 0, 0, 0); WaitEndFlag0(0); for(i=0;i<len;i++) { if((address+i)<0x80ff) check_sum+=Tx_Data0[2+i]; } check_sum=(check_sum^0xff)+1; } void NVT_WriteMultiBytes(uint16_t address,uint8_t* data, uint8_t len) { uint16_t i=0; uint8_t check_sum=0; for (i = 0; i < len; i++) { NVT_WriteByte(address+i,data[i]) ; check_sum+=data[i]; } check_sum=(check_sum^0xff)+1; } void NVT_ReadByte(uint16_t address, uint8_t *data) { Tx_Data0[0]=address>>8; Tx_Data0[1]=(address&0xff); DataLen0 = 0; EndFlag0 = 0; s_I2C0HandlerFn = (I2C_FUNC)I2C_Callback_Rx; s_I2C1HandlerFn = (I2C_FUNC)I2C_Callback_Rx; I2C_Ctrl(I2C_PORT, 1, 0, 0, 0); while (EndFlag0 == 0); *data=Rx_Data0[0]; } void NVT_ReadMultiBytes(uint16_t address,uint8_t* data, uint8_t len) { uint16_t i=0; uint8_t check_sum=0; for (i = 0; i < len; i++) { NVT_ReadByte(address+i,&data[i]); check_sum+=data[i]; } check_sum=(check_sum^0xff)+1; } void NVT_ReadByteContinue(uint16_t address,uint8_t* data, uint8_t len) { uint8_t i; for(i=0;i<len;i++) { RxLen0 = 0; DataLen0 = 0; EndFlag0 = 0; ReadFlag=0; ContinueLen=2; Tx_Data0[0]=address>>8; Tx_Data0[1]=(address&0xff); s_I2C0HandlerFn = (I2C_FUNC)I2C_Callback_Rx_Continue; s_I2C1HandlerFn = (I2C_FUNC)I2C_Callback_Rx_Continue; I2C_Ctrl(I2C_PORT, 1, 0, 0, 0); WaitEndFlag0(0); ContinueLen=1; ReadFlag=1; EndFlag0 = 0; I2C_Ctrl(I2C_PORT, 1, 0, 0, 0); WaitEndFlag0(0); data[i]=Rx_Data0[0]; address++; } } uint8_t NVT_WriteByteContinue_addr8(uint8_t address,uint8_t* data, uint8_t len) { uint8_t i; Tx_Data0[0]=address; for(i=0;i<len;i++) Tx_Data0[1+i]=data[i]; DataLen0 = 0; EndFlag0 = 0; ErrorFlag = 0; ContinueLen=len+1; s_I2C0HandlerFn = (I2C_FUNC)I2C_Callback_Tx_Continue; s_I2C1HandlerFn = (I2C_FUNC)I2C_Callback_Tx_Continue; while(I2C_PORT->I2CON & I2C_I2CON_STO_Msk); I2C_Ctrl(I2C_PORT, 1, 0, 0, 0); WaitEndFlag0(1); return ErrorFlag; } uint8_t NVT_ReadByteContinue_addr8(uint8_t address,uint8_t* data, uint8_t len) { uint8_t i; RxLen0 = 0; DataLen0 = 0; EndFlag0 = 0; ReadFlag = 0; ErrorFlag = 0; ContinueLen = len; Tx_Data0[0] = address; s_I2C0HandlerFn = (I2C_FUNC)I2C_Callback_Rx_Continue; s_I2C1HandlerFn = (I2C_FUNC)I2C_Callback_Rx_Continue; while(I2C_PORT->I2CON & I2C_I2CON_STO_Msk); I2C_Ctrl(I2C_PORT, 1, 0, 0, 0); WaitEndFlag0(0); for(i = 0; i<len; i++) data[i]=Rx_Data0[i]; return ErrorFlag; } void NVT_I2C_Init(uint32_t u32BusFreq) { I2C_Open(I2C_PORT, u32BusFreq); //u32data = I2C_GetClockFreq(I2C_PORT); //printf("I2C clock: %d Hz\n", u32data); /* Enable I2C interrupt and set corresponding NVIC bit */ I2C_EnableInt(I2C_PORT); if(I2C_PORT==I2C0) NVIC_EnableIRQ(I2C0_IRQn); if(I2C_PORT==I2C1) NVIC_EnableIRQ(I2C1_IRQn); } void NVT_SetDeviceAddress(uint8_t devAddr) { Device_W_Addr=devAddr; Device_R_Addr=devAddr+1; } <file_sep>/CODE/lab7-0 learning board 211110/Nu-LB-NUC140_BSP3.00.004_v1.2/Library/NuMakerLib/Source/HMC5883.c // // HMC5883 Driver: E-compass // // Interface: I2C // pin1: Vcc to Vcc (+5V) // pin2: Gnd to Gnd // pin3: SCL to I2C0_SCL/GPA9 // pin4: SDA to I2C0_SDA/GPA8 // pin5: DRDY N.C. #include <stdio.h> #include <stdint.h> #include <string.h> #include "NUC100Series.h" #include "I2Cdev.h" #include "HMC5883.h" #include "sensor.h" hmc5883MagRegisters_t hmc5883_reg; static float _hmc5883_Gauss_LSB_XY = 1100.0F; // Varies with gain static float _hmc5883_Gauss_LSB_Z = 980.0F; // Varies with gain void HMC5883_write(uint8_t reg, uint8_t value) { I2C_WriteBytes(HMC5883_I2C_PORT, HMC5883_I2C_SLA, reg, value, 1); } uint8_t HMC5883_read(uint8_t reg) { uint8_t data[1]; I2C_readBytes(HMC5883_I2C_PORT, HMC5883_I2C_SLA, reg, 1, data); return data; } void init_HMC5883(void) { HMC5883_write(HMC5883_MAG_MR_REG_M, 0x00); CLK_SysTickDelay(20000); // wait for 20ms setMagGain(HMC5883_MAGGAIN_1_3); } void setMagGain(uint8_t gain) { HMC5883_write(HMC5883_MAG_CRB_REG_M, gain); switch(gain) { case HMC5883_MAGGAIN_1_3: _hmc5883_Gauss_LSB_XY = 1100; _hmc5883_Gauss_LSB_Z = 980; break; case HMC5883_MAGGAIN_1_9: _hmc5883_Gauss_LSB_XY = 855; _hmc5883_Gauss_LSB_Z = 760; break; case HMC5883_MAGGAIN_2_5: _hmc5883_Gauss_LSB_XY = 670; _hmc5883_Gauss_LSB_Z = 600; break; case HMC5883_MAGGAIN_4_0: _hmc5883_Gauss_LSB_XY = 450; _hmc5883_Gauss_LSB_Z = 400; break; case HMC5883_MAGGAIN_4_7: _hmc5883_Gauss_LSB_XY = 400; _hmc5883_Gauss_LSB_Z = 255; break; case HMC5883_MAGGAIN_5_6: _hmc5883_Gauss_LSB_XY = 330; _hmc5883_Gauss_LSB_Z = 295; break; case HMC5883_MAGGAIN_8_1: _hmc5883_Gauss_LSB_XY = 230; _hmc5883_Gauss_LSB_Z = 205; break; } } bool HMC5883_getEvent(sensors_event_t *event) { memset(event, 0, sizeof(sensors_event_t)); /* Read new data */ read(); event->version = sizeof(sensors_event_t); event->sensor_id = _sensorID; event->type = SENSOR_TYPE_MAGNETIC_FIELD; event->timestamp = 0; event->magnetic.x = _magData.x / _hmc5883_Gauss_LSB_XY * SENSORS_GAUSS_TO_MICROTESLA; event->magnetic.y = _magData.y / _hmc5883_Gauss_LSB_XY * SENSORS_GAUSS_TO_MICROTESLA; event->magnetic.z = _magData.z / _hmc5883_Gauss_LSB_Z * SENSORS_GAUSS_TO_MICROTESLA; return true; } void HMC5883_getSensor(sensor_t *sensor) { /* Clear the sensor_t object */ memset(sensor, 0, sizeof(sensor_t)); /* Insert the sensor name in the fixed length char array */ strncpy (sensor->name, "HMC5883", sizeof(sensor->name) - 1); sensor->name[sizeof(sensor->name)- 1] = 0; sensor->version = 1; sensor->sensor_id = _sensorID; sensor->type = SENSOR_TYPE_MAGNETIC_FIELD; sensor->min_delay = 0; sensor->max_value = 800; // 8 gauss == 800 microTesla sensor->min_value = -800; // -8 gauss == -800 microTesla sensor->resolution = 0.2; // 2 milligauss == 0.2 microTesla } <file_sep>/CODE/lab9-1 learning board 211124/Library/Nu-LB-NUC140/Include/NVT_I2C.h #ifndef _DRVI2C_NVT_H #define _DRVI2C_NVT_H #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif #ifndef false #define false 0 #endif #ifndef true #define true 1 #endif #ifndef bool #define bool unsigned char #endif #include <stdint.h> #define MAX_I2C_DATA_LEN 200 #define I2C_CTL_STA_SI 0x28UL /*!< I2CON setting for I2C control bits. It would set STA and SI bits */ #define I2C_CTL_STA_SI_AA 0x2CUL /*!< I2CON setting for I2C control bits. It would set STA, SI and AA bits */ #define I2C_CTL_STO_SI 0x18UL /*!< I2CON setting for I2C control bits. It would set STO and SI bits */ #define I2C_CTL_STO_SI_AA 0x1CUL /*!< I2CON setting for I2C control bits. It would set STO, SI and AA bits */ #define I2C_CTL_SI 0x08UL /*!< I2CON setting for I2C control bits. It would set SI bit */ #define I2C_CTL_SI_AA 0x0CUL /*!< I2CON setting for I2C control bits. It would set SI and AA bits */ #define I2C_CTL_STA 0x20UL /*!< I2CON setting for I2C control bits. It would set STA bit */ #define I2C_CTL_STO 0x10UL /*!< I2CON setting for I2C control bits. It would set STO bit */ #define I2C_CTL_AA 0x04UL /*!< I2CON setting for I2C control bits. It would set AA bit */ #define I2C_CTL_STA_STO_SI 0x38UL void NVT_I2C_Init(uint32_t u32BusClock); uint8_t NVT_WriteByteContinue_addr8(uint8_t address,uint8_t* data, uint8_t len); uint8_t NVT_ReadByteContinue_addr8(uint8_t address,uint8_t* data, uint8_t len); void NVT_SetDeviceAddress(uint8_t devAddr); #endif <file_sep>/CODE/lab11-1 learning board 211208/Nu-LB-NUC140_BSP3.00.004_v1.2/Library/NuMakerLib/Include/HMC5883.h #ifndef __HMC5883_H__ #define __HMC5883_H__ #define HMC5883_I2C_SLA 0x3C #define HMC5883_I2C_PORT I2C1 // REGISTERS typedef enum { HMC5883_MAG_CRA_REG_M = 0x00, HMC5883_MAG_CRB_REG_M = 0x01, HMC5883_MAG_MR_REG_M = 0x02, HMC5883_MAG_OUT_X_H_M = 0x03, HMC5883_MAG_OUT_X_L_M = 0x04, HMC5883_MAG_OUT_Z_H_M = 0x05, HMC5883_MAG_OUT_Z_L_M = 0x06, HMC5883_MAG_OUT_Y_H_M = 0x07, HMC5883_MAG_OUT_Y_L_M = 0x08, HMC5883_MAG_SR_REG_Mg = 0x09, HMC5883_MAG_IRA_REG_M = 0x0A, HMC5883_MAG_IRB_REG_M = 0x0B, HMC5883_MAG_IRC_REG_M = 0x0C, HMC5883_MAG_TEMP_OUT_H_M = 0x31, HMC5883_MAG_TEMP_OUT_L_M = 0x32 } hmc5883MagRegisters_t; // MAGNETOMETER GAIN SETTINGS typedef enum { HMC5883_MAGGAIN_1_3 = 0x20, // +/- 1.3 HMC5883_MAGGAIN_1_9 = 0x40, // +/- 1.9 HMC5883_MAGGAIN_2_5 = 0x60, // +/- 2.5 HMC5883_MAGGAIN_4_0 = 0x80, // +/- 4.0 HMC5883_MAGGAIN_4_7 = 0xA0, // +/- 4.7 HMC5883_MAGGAIN_5_6 = 0xC0, // +/- 5.6 HMC5883_MAGGAIN_8_1 = 0xE0 // +/- 8.1 } hmc5883MagGain; // INTERNAL MAGNETOMETER DATA TYPE typedef struct hmc5883MagData_s { float x; float y; float z; float orientation; } hmc5883MagData; // CHIP ID #define HMC5883_ID (0b11010100) // sensor driver for the magnetometer extern void init_HMC5883(void); extern void HMC5883_setMagGain(hmc5883MagGain gain); extern bool HMC5883_getEvent(sensors_event_t*); extern void HMC5883_getSensor(sensor_t*); void HMC5883MagGain(uint8_t _magGain); void HMC5883MagData(uint8_t _magData); // Last read magnetometer data will be available here int32_t _sensorID; void HMC5883_write(uint8_t reg, uint8_t value); uint8_t HMC5883_read(uint8_t reg); #endif <file_sep>/CODE/lab9-1 learning board 211124/Library/NuMakerLib/Source/HTU21D.c // // HTU21D Driver: Digital Relative Humidity Sensor with Temperature Output // // Interface: I2C (slave address = 0x80) // pin1: Gnd to GND // pin2: Vdd to 3.3V // pin3: SDA (I2C Data) // pin4: SCL (I2C Clock) #include <stdio.h> #include <stdint.h> #include "NUC100Series.h" #include "I2Cdev.h" #include "HTU21D.h" // Bit7 Bit0 RH Temp // 0 0 12bits 14bits // 0 1 8 bits 12bits // 1 0 10bits 13bits // 1 1 11bits 11bits bool HTU21DF_begin(void) { uint8_t tmp; I2Cdev_readByte(HTU21DF_I2CADDR, HTU21DF_READREG, &tmp); return (tmp==0x02); // after reset should be 0x2 } void HTU21DF_reset(void) { I2Cdev_writeByte(HTU21DF_I2CADDR, HTU21DF_RESET, 0x00); CLK_SysTickDelay(15000); // Delay 15ms } uint8_t HTU21DF_ReadHumid(void) { uint8_t data[1]; I2Cdev_readByte(HTU21DF_I2CADDR, HTU21DF_READHUM, data); // trigger Temperature Hold master return data[0]; } uint16_t HTU21DF_ReadTemp(void) { uint8_t data[2]; I2Cdev_readBytes(HTU21DF_I2CADDR, HTU21DF_READTEMP, 2, data); // trigger Temperature Hold master return((data[0]<<4) + (data[1]>>4)); } float HTU21DF_Humidity(void) { uint8_t sRH = HTU21DF_ReadHumid(); //8-bit float Humid = -6 + ((125 * sRH)/256); return (Humid); } float HTU21DF_Temperature(void) { uint16_t sTemp = HTU21DF_ReadTemp(); //12-bit float Temp = -46.85 + ((175.72 * sTemp)/4096); return(Temp); } <file_sep>/CODE/lab10-1 learning board 211201/Nu-LB-NUC140_BSP3.00.004_v1.2/Library/Nu-LB-NUC140/Include/I2Cdev.h #define I2C_STA_SI 0x28UL /*!< I2CON setting for I2C control bits. It would set STA and SI bits */ #define I2C_STA_SI_AA 0x2CUL /*!< I2CON setting for I2C control bits. It would set STA, SI and AA bits */ #define I2C_STO_SI 0x18UL /*!< I2CON setting for I2C control bits. It would set STO and SI bits */ #define I2C_STO_SI_AA 0x1CUL /*!< I2CON setting for I2C control bits. It would set STO, SI and AA bits */ #define I2C_SI 0x08UL /*!< I2CON setting for I2C control bits. It would set SI bit */ #define I2C_SI_AA 0x0CUL /*!< I2CON setting for I2C control bits. It would set SI and AA bits */ #define I2C_STA 0x20UL /*!< I2CON setting for I2C control bits. It would set STA bit */ #define I2C_STO 0x10UL /*!< I2CON setting for I2C control bits. It would set STO bit */ #define I2C_AA 0x04UL /*!< I2CON setting for I2C control bits. It would set AA bit */ extern void I2C_readBytes(I2C_T *i2c, uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t *data); extern void I2C_writeBytes(I2C_T *i2c, uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t *data); <file_sep>/CODE/lab4-1 learning board 211013/Nu-LB-NUC140_BSP3.00.004_v1.2/Library/Nu-LB-NUC140/Source/Seven_Segment.c #include <stdio.h> #include "NUC100Series.h" #include "GPIO.h" #include "SYS.h" #include "Seven_Segment.h" #define SEG_N0 0x82 #define SEG_N1 0xEE #define SEG_N2 0x07 #define SEG_N3 0x46 #define SEG_N4 0x6A #define SEG_N5 0x52 #define SEG_N6 0x12 #define SEG_N7 0xE6 #define SEG_N8 0x02 #define SEG_N9 0x62 #define SEG_N10 0x22 #define SEG_N11 0x1A #define SEG_N12 0x93 #define SEG_N13 0x0E #define SEG_N14 0x13 #define SEG_N15 0x33 uint8_t SEG_BUF[16]={SEG_N0, SEG_N1, SEG_N2, SEG_N3, SEG_N4, SEG_N5, SEG_N6, SEG_N7, SEG_N8, SEG_N9, SEG_N10, SEG_N11, SEG_N12, SEG_N13, SEG_N14, SEG_N15}; void OpenSevenSegment(void) { GPIO_SetMode(PC, BIT4, GPIO_PMD_OUTPUT); GPIO_SetMode(PC, BIT5, GPIO_PMD_OUTPUT); GPIO_SetMode(PC, BIT6, GPIO_PMD_OUTPUT); GPIO_SetMode(PC, BIT7, GPIO_PMD_OUTPUT); PC4=0; PC5=0; PC6=0; PC7=0; GPIO_SetMode(PE, BIT0, GPIO_PMD_QUASI); GPIO_SetMode(PE, BIT1, GPIO_PMD_QUASI); GPIO_SetMode(PE, BIT2, GPIO_PMD_QUASI); GPIO_SetMode(PE, BIT3, GPIO_PMD_QUASI); GPIO_SetMode(PE, BIT4, GPIO_PMD_QUASI); GPIO_SetMode(PE, BIT5, GPIO_PMD_QUASI); GPIO_SetMode(PE, BIT6, GPIO_PMD_QUASI); GPIO_SetMode(PE, BIT7, GPIO_PMD_QUASI); PE0=1; PE1=1; PE2=1; PE3=1; PE4=1; PE5=1; PE6=1; PE7=1; } void CloseSevenSegment(void) { PC4=0; PC5=0; PC6=0; PC7=0; } <file_sep>/CODE/lab3-2 learning board 211006/lab3-2 learning board 211006/Nu-LB-NUC140_BSP3.00.004_v1.2/SampleCode/Nu-LB-NUC140/GPIO_7seg/main.c // // GPIO_7seg : counting from 0 to 9999 and display on 7-segment LEDs // #include <stdio.h> #include <stdlib.h> #include "NUC100Series.h" #include "MCU_init.h" #include "SYS_init.h" #include "Seven_Segment.h" void LED_binary(int num){ PC12 = 1; PC13 = 1; PC14 = 1; PC15 = 1; //CLK_SysTickDelay(5000); if(num>=8) { num-=8; PC12 = 0; } if(num>=4) { num-=4; PC13 = 0; } if(num>=2) { num-=2; PC14 = 0; } if(num>=1) { num-=1; PC15 = 0; } } void SevenSegment_0to9999(int num){ while(num<10000){ ShowSevenSegment(0,num%10); CLK_SysTickDelay(5000); CloseSevenSegment(); ShowSevenSegment(1,num/10%10); CLK_SysTickDelay(5000); CloseSevenSegment(); ShowSevenSegment(2,num/100%10); CLK_SysTickDelay(5000); CloseSevenSegment(); ShowSevenSegment(3,num/1000); CLK_SysTickDelay(5000); CloseSevenSegment(); num++; if(num == 10000){ num = 0; CloseSevenSegment(); } } } int main(void){ SYS_Init(); OpenSevenSegment(); CloseSevenSegment(); //uint8_t a = 0;// just leave it int i = 0; int j = 0; int question = 0; if(question == 1){ i = 0; j = 0; while(1){ // delay us, 1000000us == 1s LED_binary(j); ShowSevenSegment(i,j); CLK_SysTickDelay(1000000); if(j == 9){ j = 0; } else{ j++; } } } else if(question == 2){ j = 0; SevenSegment_0to9999(j); } } <file_sep>/CODE/lab9-1 learning board 211124/Library/Nu-LB-NUC140/Source/EEPROM.c // // I2C_EEPROM : using I2C1 to access EEPROM // // EVB : Nu-LB-NUC140 // MCU : NUC140VE3CN (LQFP100) // EEPROM : 24LC64 // I2C1@400KHz (2.5~5.5V) #include <stdio.h> #include "NUC100Series.h" #include "MCU_init.h" #include "EEPROM.h" volatile uint8_t g_u8DeviceAddr; volatile uint8_t g_au8TxData[3]; volatile uint8_t g_u8RxData; volatile uint8_t g_u8DataLen; volatile uint8_t g_u8EndFlag = 0; /*---------------------------------------------------------------------------------------------------------*/ /* I2C Rx Callback Function */ /*---------------------------------------------------------------------------------------------------------*/ void I2C_MasterRx(uint32_t u32Status) { if(u32Status == 0x08) // START has been transmitted and prepare SLA+W { I2C_SET_DATA(I2C1, (g_u8DeviceAddr << 1)); // Write SLA+W to Register I2CDAT I2C_SET_CONTROL_REG(I2C1, I2C_I2CON_SI); } else if(u32Status == 0x18) // SLA+W has been transmitted and ACK has been received { I2C_SET_DATA(I2C1, g_au8TxData[g_u8DataLen++]); I2C_SET_CONTROL_REG(I2C1, I2C_I2CON_SI); } else if(u32Status == 0x20) // SLA+W has been transmitted and NACK has been received { I2C_STOP(I2C1); I2C_START(I2C1); } else if(u32Status == 0x28) // DATA has been transmitted and ACK has been received { if(g_u8DataLen != 2) { I2C_SET_DATA(I2C1, g_au8TxData[g_u8DataLen++]); I2C_SET_CONTROL_REG(I2C1, I2C_I2CON_SI); } else { I2C_SET_CONTROL_REG(I2C1, I2C_I2CON_STA_SI); } } else if(u32Status == 0x10) // Repeat START has been transmitted and prepare SLA+R { I2C_SET_DATA(I2C1, ((g_u8DeviceAddr << 1) | 0x01)); // Write SLA+R to Register I2CDAT I2C_SET_CONTROL_REG(I2C1, I2C_I2CON_SI); } else if(u32Status == 0x40) // SLA+R has been transmitted and ACK has been received { I2C_SET_CONTROL_REG(I2C1, I2C_I2CON_SI); } else if(u32Status == 0x58) // DATA has been received and NACK has been returned { g_u8RxData = (unsigned char) I2C_GET_DATA(I2C1); I2C_SET_CONTROL_REG(I2C1, I2C_I2CON_STO_SI); g_u8EndFlag = 1; } else { // printf("Status 0x%x is NOT processed\n", u32Status); } } /*---------------------------------------------------------------------------------------------------------*/ /* I2C Tx Callback Function */ /*---------------------------------------------------------------------------------------------------------*/ void I2C_MasterTx(uint32_t u32Status) { if(u32Status == 0x08) // START has been transmitted { I2C_SET_DATA(I2C1, g_u8DeviceAddr << 1); // Write SLA+W to Register I2CDAT I2C_SET_CONTROL_REG(I2C1, I2C_I2CON_SI); } else if(u32Status == 0x18) // SLA+W has been transmitted and ACK has been received { I2C_SET_DATA(I2C1, g_au8TxData[g_u8DataLen++]); I2C_SET_CONTROL_REG(I2C1, I2C_I2CON_SI); } else if(u32Status == 0x20) // SLA+W has been transmitted and NACK has been received { I2C_STOP(I2C1); I2C_START(I2C1); } else if(u32Status == 0x28) // DATA has been transmitted and ACK has been received { if(g_u8DataLen != 3) { I2C_SET_DATA(I2C1, g_au8TxData[g_u8DataLen++]); I2C_SET_CONTROL_REG(I2C1, I2C_I2CON_SI); } else { I2C_SET_CONTROL_REG(I2C1, I2C_I2CON_STO_SI); g_u8EndFlag = 1; } } else { // printf("Status 0x%x is NOT processed\n", u32Status); } } void Close_EEPROM(void) { I2C_DisableInt(I2C1); // Disable I2C1 interrupt generation NVIC_DisableIRQ(I2C1_IRQn); // Disable NVIC I2C1 interrupt input I2C_Close(I2C1); // Disable I2C1 control module CLK_DisableModuleClock(I2C1_MODULE); // Disable I2C module clock } void Init_EEPROM(void) { I2C_Open(I2C1, I2C1_CLOCK_FREQUENCY); I2C_EnableInt(I2C1); // Enable I2C1 interrupt generation NVIC_EnableIRQ(I2C1_IRQn); // Enable NVIC I2C1 interrupt input } void EEPROM_Write(uint16_t addr, uint8_t data) { g_u8DeviceAddr = 0x50; // 24LC64 device address = 0xA0 g_au8TxData[0] = (uint8_t)((addr & 0xFF00) >> 8); g_au8TxData[1] = (uint8_t)(addr & 0x00FF); g_au8TxData[2] = data; g_u8DataLen = 0; g_u8EndFlag = 0; s_I2C1HandlerFn = (I2C_FUNC)I2C_MasterTx; // I2C function to write data to slave I2C_SET_CONTROL_REG(I2C1, I2C_I2CON_STA); // I2C as master sends START signal while(g_u8EndFlag == 0); // Wait I2C Tx Finish g_u8EndFlag = 0; } uint8_t EEPROM_Read(uint16_t addr) { s_I2C1HandlerFn = (I2C_FUNC)I2C_MasterRx; // I2C function to read data from slave g_u8DataLen = 0; g_u8DeviceAddr = 0x50; g_au8TxData[0] = (uint8_t)((addr & 0xFF00) >> 8); g_au8TxData[1] = (uint8_t)(addr & 0x00FF); I2C_SET_CONTROL_REG(I2C1, I2C_I2CON_STA); while(g_u8EndFlag == 0);// Wait I2C Rx Finish g_u8EndFlag = 0; return g_u8RxData; } <file_sep>/CODE/lab9-1 learning board 211124/Library/Nu-LB-NUC140/Include/W25Q16CV.h #include "NUC100Series.h" #define W25Q16_SPI_PORT SPI2 #define W25Q16_WRITE_ENABLE 0x06 #define W25Q16_WRITE_ENABLE_FOR_VOLATILE_STATUS_REGISTER 0x50 #define W25Q16_WRITE_DISABLE 0x04 #define W25Q16_READ_STATUS_REGISTER1 0x05 #define W25Q16_READ_STATUS_REGISTER2 0x35 #define W25Q16_WRITE_STATUS_REGISTER 0x01 #define W25Q16_PAGE_PROGRAM 0x02 #define W25Q16_QUAD_PAGE_PROGRAM 0x32 #define W25Q16_SECTOR_ERASE 0x20 #define W25Q16_BLOCK_ERASE_32KB 0x52 #define W25Q16_BLOCK_ERASE_64KB 0xD8 #define W25Q16_CHIP_ERASE 0x60 // or 0xC7 #define W25Q16_ERASE_SUSPEND 0x75 #define W25Q16_ERASE_RESUME 0x7A #define W25Q16_POWER_DOWN 0xB9 #define W25Q16_CONTINUOUS_READ_MODE_RESET 0xFF #define W25Q16_READ_DATA 0x03 #define W25Q16_FAST_READ 0x0B #define W25Q16_FAST_READ_DUAL_OUTPUT 0x3B #define W25Q16_FAST_READ_QUAD_OUTPUT 0x6B #define W25Q16_FAST_READ_DUAL_IO 0xBB #define W25Q16_FAST_READ_QUAD_IO 0xEB #define W25Q16_WORD_READ_QUAD_IO 0xE7 #define W25Q16_QCTAL_WORD_READ_QUAD_IO 0xE3 #define W25Q16_SET_BURST_W_WRAP 0x77 #define W25Q16_RELEASE_PWRDN_DEVICE_ID 0xAB #define W25Q16_MANUFACTURER_DEVICE_ID 0x90 #define W25Q16_MANUFACTURER_DEVICE_ID_DUAL_IO 0x92 #define W25Q16_MANUFACTURER_DEVICE_ID_QUAD_IO 0x94 #define W25Q16_READ_JEDEC_ID 0x9F #define W25Q16_READ_UNIQUE_ID 0x4B #define W25Q16_READ_SFDP_REGISTER 0x5A #define W25Q16_ERASE_SECURITY_REGISTERS 0x44 #define W25Q16_PROGRAM_SECURITY_REGISTERS 0x42 #define W25Q16_READ_SECURITY_REGISTERS 0x48 #define W25Q16_ENABLE_RESET 0x66 #define W25Q16_RESET 0x99 extern void init_W25Q16(void); void W25Q16_Command(uint8_t command); extern void W25Q16_WriteEnable(void); extern void W25Q16_WriteEnableForVolatileStatusRegister(void); extern void W25Q16_WriteDisable(void); extern uint8_t W25Q16_ReadStatusRegister1(void); extern uint8_t W25Q16_ReadStatusRegister2(void); extern void W25Q16_WriteStatusRegister(uint16_t u16data); extern void W25Q16_PageProgram(uint32_t u24addr, uint8_t *data); extern void W25Q16_SectorErase(uint32_t u24addr); extern void W25Q16_BlockErase32KB(uint32_t u24addr); extern void W25Q16_BlockErase64KB(uint32_t u24addr); extern void W25Q16_ChipErase(void); extern void W25Q16_EraseSuspend(void); extern void W25Q16_EraseResume(void); extern void W25Q16_PowerDown(void); extern void W25Q16_ContinuouseReadModeReset(void); extern uint8_t W25Q16_ReadData(uint32_t u24addr); extern uint8_t W25Q16_ReleasePowerDown_DeviceID(void); extern uint16_t W25Q16_ReadManufacturerDeviceID(void); extern uint32_t W25Q16_ReadJEDECID(void); extern uint8_t W25Q16_ReadUniqueID(void); extern uint8_t W25Q16_ReadSFDPRegister(uint8_t addr); extern void W25Q16_EraseSecurityRegisters(uint32_t u24addr); extern void W25Q16_ProgramSecurityRegiters(uint32_t u24addr, uint8_t data); extern uint8_t W25Q16_ReadSecurityRegisters(uint32_t u24addr); <file_sep>/CODE/lab9-1 learning board 211124/Library/NuMakerLib/Include/HTU21D.h // // HTU21D : Digital Relative Humidity Sensor with Temperature Output // #include "NVT_I2C.h" /** Default I2C address for the HTU21D. */ #define HTU21DF_I2CADDR (0x40) /** Read temperature register. */ #define HTU21DF_READTEMP (0xE3) /** Read humidity register. */ #define HTU21DF_READHUM (0xE5) /** Write register command. */ #define HTU21DF_WRITEREG (0xE6) /** Read register command. */ #define HTU21DF_READREG (0xE7) /** Reset command. */ #define HTU21DF_RESET (0xFE) extern bool HTU21DF_begin(void); extern void HTU21DF_reset(void); extern uint8_t HTU21DF_ReadHumid(void); extern uint16_t HTU21DF_ReadTemp(void); extern float HTU21DF_Humidity(void); extern float HTU21DF_Temperature(void);
61336fd2b320c6ff501ef0d1860f0a9694d905ef
[ "C" ]
37
C
SWI-MIN/TESTTRYTRY
a0998d546b7dcefd945acd6a82ae3c9d2d07a786
edbb6a6e7c1ecb8517d7ebe3a27fea943e6c2e57
refs/heads/master
<file_sep>#!/usr/bin/python import pysvn import pdb passwd = "<PASSWORD>" #this is not correct; just making this private. def login(realm, username, may_save): return True, username, passwd, False def update(): client = pysvn.Client() client.update("../../features/bounds_dump") if __name__ == "__main__": update() <file_sep>''' Created on Aug 8, 2012 @author: random ''' import operator import re def _annotate(text, tuples): ends = [] newText = ""; curr = 0; for point in tuples: if len(ends) > 0: while (ends[0][0] <= point[0]): end = ends.pop(0) newText += text[curr:end[0]] + "[\\" + end[1] + "]" curr = end[0] if len(ends) < 1: break newText += text[curr:point[0]] + "[" + point[2] + "]" curr = point[0] ends.append((point[1], point[2])) for end in ends: end = ends.pop(0) newText += text[curr:end[0]] + "[\\" + end[1] + "]" curr = end[0] newText += text[curr:] return newText def annotate(text, tuples): start = first = operator.itemgetter(0) end = second = operator.itemgetter(1) tag = operator.itemgetter(2) ordered = [] start_tuples = sorted(tuples, key=start) for _tuple in start_tuples: ordered.append( (start(_tuple), '[{}]'.format(tag(_tuple))) ) end_tuples = sorted(tuples, key=end) for _tuple in end_tuples: ordered.append( (end(_tuple), '[/{}]'.format(tag(_tuple))) ) ordered = sorted(ordered, key=start) text2 = '' ordered.reverse() _abc = 0 last = 0 regex = re.compile(r'\s+', re.MULTILINE) text = regex.sub(' ', text) while len(ordered) > 0: _pop = ordered.pop() if last != first(_pop): last = first(_pop) text2 += text[_abc:last] _abc = last text2 += second(_pop) if last < len(text): text2 += text[last:] return text2 if __name__ == '__main__': test = "This is a test" tuples = [(0, 4, "this"), (5, 7, "is"), (8, 14, "done") ] ann = annotate(test, tuples) print ann <file_sep>#!/usr/bin/python import json import os import operator import sys import pdb import cgi #pdb.set_trace() import svnUpdate from collections import Counter sys.path.append('..') sys.path.append('/var/projects/persuasion/code') sys.path.append('/var/projects/utilities/nlp') from collections import defaultdict try: from discussion import Dataset, data_root_dir except Exception, e: from grab_data.discussion import Dataset, data_root_dir import annotate boundsFile = "bounds_dump" DELETE_QUOTE = False def generate_posts(): dataset = Dataset('convinceme',annotation_list=['topic']) directory = "{}/convinceme/output_by_thread".format(data_root_dir) vals = [] for thread in tuples.keys(): for post in tuples[thread].keys(): ed = Counter([x[-1] for x in tuples[thread][post] if x[-1] != "none"]) vals.append((thread, post, ed)) return write(vals) def write(vals): vOut = "" for v in vals: vOut += """ <div class="post"><a href="getSpans.py?thread=%s&post=%s" target="_BLANK">%s %s %s</a></div>""" % (v[0], v[1], v[0], v[1], ' | '.join(sorted(v[2].keys()))) r = """Content-Type: text/html; charset=utf-8 <html> <head> <style type="text/css"> #author {color: red;} #side {color: green;} #text {margin: 5px; border: 1px dotted red;} #post {width: 400px;} span {border: 1px dotted black;} .none {background-color: gray} </style> </head> <body> %s </body> </html>""" % (vOut) return r def loadTuples(): global tuples svnUpdate.update() fin = open(boundsFile, "r") tuples = json.load(fin) if __name__ == '__main__': loadTuples() print generate_posts() <file_sep># -*- coding: utf-8 -*- import re import string import nltk.tokenize newline_replacements = (re.compile(r'[\x0A\x0C\x0D]'), '\x0A') punctuation = re.compile('^['+re.escape(string.punctuation)+']+$') spaces_re = re.compile(r'\s+', re.UNICODE | re.DOTALL) legal_tokens = [spaces_re, #whitespace re.compile(r"[a-zA-Z]+$", re.UNICODE), #words re.compile(r"[a-zA-Z]+([ʼ’ʻ`'\-]\w+)*$", re.UNICODE), #words and word-like things re.compile(r"\$?\d+((\.|,)\d+)*$", re.UNICODE), #basic numbers, ipv4 addresses, etc re.compile(r'\d{1,2}/\d{1,2}(/\d{2,4})?$', re.UNICODE), #date re.compile(r'\d+(\.\d+)?[%°]$', re.UNICODE), #80% or 80° re.compile(r'\d+\'s$', re.UNICODE), #80's re.compile(r'\d*(1st|2nd|3rd|[04-9]th)$', re.UNICODE | re.IGNORECASE), #80th, 1st, 81st, etc re.compile(r'(#|0x|\\x)?[a-fA-F0-9]+$'), #hex re.compile(r'[!?]+$'), #!?! re.compile('(['+re.escape(string.punctuation)+'])\\1+$'), #same punctuation character repeated ....... && ******* re.compile(r'[}>\]<]?[:;=8BxX][\'`]?[oc\-]?[*XxO03DPpb)[\]}|/\\(]$'), #Western emoticons - see: http://en.wikipedia.org/wiki/List_of_emoticons re.compile(r'[(=]?[\-~^T0oOxX\'<>.,\'][_\-.][\-~^T0oOxX\'<>.,\'][)=]?$'), #Eastern emoticons re.compile(r'<[/\\]?3+$'), #heart <3 re.compile(r'\(( ?[.oO] ?)(\)\(|Y)\1\)$'), #boobs re.compile(r"[a-zA-Z]+\*+[a-zA-Z]*$", re.UNICODE), #w***s re.compile(r'[@#$%^&*]+$', re.UNICODE), # @$%# symbols re.compile(r'&[a-zA-Z]+;$', re.UNICODE), #html escapes re.compile(r'&#\d+;$', re.UNICODE), #html escapes re.compile(r'(https?://|www\.).*$', re.UNICODE | re.IGNORECASE), # urls re.compile(r'.*\.(edu|com|org|gov)/?$', re.UNICODE | re.IGNORECASE), # more urls and emails re.compile(r'\x00+$', re.UNICODE) # null characters ] #given english text, returns a list of tokens or a list of lists of tokens if told to break_into_sentences def tokenize(text, break_into_sentences = False, leave_whitespace=False): token_spans = list() previous_end = 0 for iter in spaces_re.finditer(text): if iter.start()!=0: token_spans.append((previous_end, iter.start())) token_spans.append((iter.start(),iter.end())) previous_end = iter.end() if previous_end != len(text): token_spans.append((previous_end, len(text))) tokens = [text[start:end] for (start,end) in token_spans] tokens = reduce(lambda x, y: x+y, map(tokenize_word, tokens), []) if break_into_sentences: tokens = tokens_to_sentences(tokens) if not leave_whitespace: tokens = remove_whitespace_tokens(tokens, break_into_sentences) return tokens #greedily splits into largest possible tokens def tokenize_word(word): if is_legal_token(word): return [word] tokens = list() for i in range(len(word),0,-1): if is_legal_token(word[:i]): tokens.append(word[:i]) tokens.extend(tokenize_word(word[i:])) break if is_legal_token(word[len(word)-i:]): tokens.extend(tokenize_word(word[:len(word)-i])) tokens.append(word[len(word)-i:]) break return tokens def is_legal_token(token): if len(token) == 1: return True for regex in legal_tokens: if regex.match(token): return True return False def sentences(text): return nltk.tokenize.sent_tokenize(text) #nltk's is actually pretty good, albeit unpredictable #TODO - once people upgrade nltk, use nltk's span option for sent tokenizing... def tokens_to_sentences(tokens): sentences = list() sentence_buffer = list() for token in tokens: if len(token) == 0 or '\n' in token or token[-1] in ['.','?',':','!',';'] or '\0' in token: sentence_buffer.append(token) sentences.append(sentence_buffer) sentence_buffer = list() else: sentence_buffer.append(token) if len(sentence_buffer) > 0: sentences.append(sentence_buffer) return sentences #Note: catches all that start with whitespace def remove_whitespace_tokens(tokens, sentences = False): if sentences: for i in range(len(tokens)): tokens[i] = remove_whitespace_tokens(tokens[i]) # tokens[i] is a sentence return tokens return [token for token in tokens if not spaces_re.match(token)] #borrowed from nltk w/ modifications clean_html_regexes = [(re.compile(r"(?is)<(script|style).*?>.*?(</\1>)"), ""), (re.compile(r"(?s)<!--(.*?)-->[\n]?", re.DOTALL), ""), (re.compile(r'(?i)<(b|h)r */? *>'), '\n'), (re.compile(r'(?s)<.*?>'), '')] def clean_html(text): for regex, sub in clean_html_regexes: text = regex.sub(sub, text) text = replace_html_escapes(text) text = text.replace(' ',' ').replace(' ',' ') return text #see: http://www.theukwebdesigncompany.com/articles/entity-escape-characters.php #and: http://www.fileformat.info/info/unicode/char/201d/index.htm # ('&amp;','&') purposely left out - replace on own html_escapes = [('&nbsp;',' '), ('&quot;','"'), ('&lt;','<'), ('&gt;','>')] html_escapes_regexes = [(re.compile(r'&(l|r)dquo;', re.IGNORECASE), '"'), (re.compile(r'&(l|r)squo;', re.IGNORECASE), "'"), (re.compile(r'&acute;', re.IGNORECASE), "'")] lossy_html_escape_regexes = [(re.compile(r'&(A|E|I|O|U|a|e|i|o|u|N|n|Y|y)(grave|acute|circ|tilde|uml|ring);'), r'\1')] def replace_html_escapes(text, replace_amp = False, use_lossy_escapes = True): for original, sub in html_escapes: text = text.replace(original, sub) for regex, sub in html_escapes_regexes: text = regex.sub(sub, text) if use_lossy_escapes: for regex, sub in lossy_html_escape_regexes: text = regex.sub(sub, text) if replace_amp: text = text.replace('&amp;','&') return text #one or both of text and term can also be lists of tokens, this speeds things up immensely def is_text_initial(term, text, start_within=5, ignore_case=True): if type(term) != type(list()): if ignore_case: term = term.lower() term_tokens = tokenize(term) else: term_tokens = [token.lower() for token in term] if ignore_case else term if type(text) != type(list()): if ignore_case: text = text.lower() text_tokens = tokenize(text) else: text_tokens = [token.lower() for token in text] if ignore_case else text spacey_text = ' '+(' '.join(text_tokens[:start_within-1+len(term_tokens)]))+' ' spacey_term = ' '+(' '.join(term_tokens))+' ' return spacey_term in spacey_text <file_sep>#!/usr/bin/env python ## example / intended use: # # from post import Post # p = Post.from_json('foo.json') # print p.tree.to_string() # p.tree.to_graphviz('foo') # creates "foo.dot", "foo.png" import re import json import sys import pdb sys.path.append("../../utilities_external") sys.path.append("../utilities_external") sys.path.append("../") from nlp import feature_extractor from nlp import word_category_counter import mpqa.mpqa as mpqa from collections import Counter import pdb def toDict(l): voc = set(l) inds = range(len(voc)) outDict = dict(zip(voc, inds)) return outDict def toLists(l): voc = set(l) return [[x] for x in voc] class Post: # it is easier to use Post.from_json to create a Post instance # buildfeats: [] for build zero features, None for build all features def __init__(self, occurrences, deps, tree, sentstarts, sentends, postid, buildfeats=[], occMapping={}): self.occurrences = occurrences self.postid = postid self.dependencies = deps self.tree = tree self.sentstarts = sentstarts self.sentends = sentends self.text = ''.join([ o.before + o.text for o in occurrences ]) # note that default behavior of build_features is to build a bunch of features, # but here in the constructor of Post, it is called in such a way as to build NO features by default self.build_features(buildfeats) self.features = dict() self.occMapping = occMapping def __repr__(self): return self.text def sentencesDB(self, site): starts = self.sentstarts ends = self.sentends lims = zip(starts, ends) sents = [] i = 0 for bounds in lims: try: sent = (i, self.text[bounds[0]: bounds[1]], bounds[0], bounds[1], self.tree.to_string(self.tree.roots[i]), self.postid, site) i += 1 except: pdb.set_trace() sents.append(sent) return (toDict(sents), ["id", "text", "start", "end", "constituencyParse", "containingPost", "site"]) def vocabDB(self): vocab = toDict([(x.text) for x in self.occurrences]) return (vocab, ["word"]) def posDB(self): POSvocab = toDict([(x.pos) for x in self.occurrences]) return (POSvocab, ["pos"]) def posWordsDB(self, vocabMap, POSMap): try: POSWords = toDict([(x.text, x.pos) for x in self.occurrences]) except: pdb.set_trace() return (POSWords, ["word", "pos"]) def occurrencesDB(self, POSWordMap, vocabMap, POSMap, site): occs = [] for i in range(len(self.occurrences)): try: occ = self.occurrences[i] sent=occ.getSent(self.sentstarts) o = (i, POSWordMap[(occ.text, occ.pos)], occ.text, occ.pos, occ.start, occ.end, self.postid, sent, site) except: pdb.set_trace() occs.append(o) return (toDict(occs), ["id", "POSword", "word", "pos", "start", "end", "containingPost", "sentence", "site"]) def depRelsDB(self): depRels = toDict([(x.relation) for x in self.dependencies]) return (depRels, ["relation"]) def depsDB(self, POSWordMap, vocabMap, POSMap, occMap, depRelMap, site): deps = [] for i in range(len(self.dependencies)): dep = self.dependencies[i] relation = dep.relation gov_occ = self.occurrences[dep.gov_index] gov_v = vocabMap[gov_occ.text] gov_pos = POSMap[gov_occ.pos] gov_item = POSWordMap[(gov_occ.text, gov_occ.pos)] gov_ind = dep.gov_index dep_occ = self.occurrences[dep.dep_index] dep_v = vocabMap[dep_occ.text] dep_pos = POSMap[dep_occ.pos] dep_item = POSWordMap[(dep_occ.text, dep_occ.pos)] dep_ind = dep.dep_index deps.append((i, relation, gov_ind, gov_occ.text, dep_ind, dep_occ.text, self.postid, site)) return (toDict(deps), ["id", "relation", "head", "headword", "tail", "tailword", "post", "site"]) @staticmethod def from_stanford_nlp(pos_dicts=None, garbage=None, deps_dicts=None, post_id=0, buildfeats=False): #if postId != None: # post_id = postId # ultimate goal: create a Post object # we can generate 3 of 5 parameters from the start try: occurrences = map(Occurrence, reduce(lambda x,y: x+y, pos_dicts)) except TypeError, e: # Something with one of the posts (empty post?) is causing this to fail reduce and it's ruining my life. return None occurrenceStarts = [o.start for o in occurrences] sent_starts = [ p[ 0][u'CharacterOffsetBegin'] for p in pos_dicts ] sent_ends = [ p[-1][u'CharacterOffsetEnd'] for p in pos_dicts ] # walk through trees, re-indexing to make indices continue over sentence boundaries last_index = 0 # params to create Tree roots = [] parent = {} children = {} descendants = {} label = {} dependencies = [] terminal = {} text = {} occMapping = {} for postnum in range(len(garbage)): tree = garbage[postnum] # parameters to Tree's constructor root_index = tree[u'index'] + last_index roots.append(root_index) # recursive walk, accumulating indices def walk(node, max_index): index = node[u'index'] + last_index if node[u'index'] > max_index: max_index = node[u'index'] if node[u'parent'] is not None: parent[index] = node[u'parent'] + last_index children[index] = map(lambda c: c[u'index'] + last_index, node[u'children']) descendants[index] = map(lambda d: d + last_index, node[u'dominates']) if node[u'token'] is None: # if non-terminal label[index] = node[u'label'] text[index] = None terminal[index] = False else: label[index] = node[u'token'][u'PartOfSpeech'] try: text[index] = node[u'token'][u'OriginalText'] except KeyError: text[index] = node[u'token'][u'Current'] terminal[index] = True # pdb.set_trace() occMapping[index] = occurrenceStarts.index(node[u'token'][u'CharacterOffsetBegin']) for child in node[u'children']: max_index = walk(child, max_index) return max_index max_index = walk(tree, 0) # bump up dependancy dict indices, too for i in range(len(deps_dicts[postnum])): dependencies.append( Dependency( deps_dicts[postnum][i][u'relation'], occMapping[deps_dicts[postnum][i][u'governor_index'] + last_index], occMapping[deps_dicts[postnum][i][u'dependent_index'] + last_index] ) ) last_index += max_index tree = Tree(roots, parent, children, descendants, label, terminal, text, occMapping) return Post(occurrences, dependencies, tree, sent_starts, sent_ends, post_id, buildfeats, occMapping) @staticmethod def from_json(json_name, buildfeats=False, postId=0): #pos_dicts was previously called occdicts [pos_dicts, garbage, deps_dicts, post_id] = json.load(open(json_name)) #if postId != None: # post_id = postId # ultimate goal: create a Post object # we can generate 3 of 5 parameters from the start try: occurrences = map(Occurrence, reduce(lambda x,y: x+y, pos_dicts)) except TypeError, e: # Something with one of the posts (empty post?) is causing this to fail reduce and it's ruining my life. return None occurrenceStarts = [o.start for o in occurrences] sent_starts = [ p[ 0][u'CharacterOffsetBegin'] for p in pos_dicts ] sent_ends = [ p[-1][u'CharacterOffsetEnd'] for p in pos_dicts ] # walk through trees, re-indexing to make indices continue over sentence boundaries last_index = 0 # params to create Tree roots = [] parent = {} children = {} descendants = {} label = {} dependencies = [] terminal = {} text = {} occMapping = {} for postnum in range(len(garbage)): tree = garbage[postnum] # parameters to Tree's constructor root_index = tree[u'index'] + last_index roots.append(root_index) # recursive walk, accumulating indices def walk(node, max_index): index = node[u'index'] + last_index if node[u'index'] > max_index: max_index = node[u'index'] if node[u'parent'] is not None: parent[index] = node[u'parent'] + last_index children[index] = map(lambda c: c[u'index'] + last_index, node[u'children']) descendants[index] = map(lambda d: d + last_index, node[u'dominates']) if node[u'token'] is None: # if non-terminal label[index] = node[u'label'] text[index] = None terminal[index] = False else: label[index] = node[u'token'][u'PartOfSpeech'] try: text[index] = node[u'token'][u'OriginalText'] except KeyError: text[index] = node[u'token'][u'Current'] terminal[index] = True # pdb.set_trace() occMapping[index] = occurrenceStarts.index(node[u'token'][u'CharacterOffsetBegin']) for child in node[u'children']: max_index = walk(child, max_index) return max_index max_index = walk(tree, 0) # bump up dependancy dict indices, too for i in range(len(deps_dicts[postnum])): dependencies.append( Dependency( deps_dicts[postnum][i][u'relation'], occMapping[deps_dicts[postnum][i][u'governor_index'] + last_index], occMapping[deps_dicts[postnum][i][u'dependent_index'] + last_index] ) ) last_index += max_index tree = Tree(roots, parent, children, descendants, label, terminal, text, occMapping) return Post(occurrences, dependencies, tree, sent_starts, sent_ends, post_id, buildfeats, occMapping) def to_string(self, *args): return self.tree.to_string(*args) def to_graphviz(self, *args): return self.tree.to_graphviz(*args) def to_json(self, json_name): f_json = open(json_name, 'w') json_top = [] json_top.append(map(lambda o: o.to_json(), self.occurrences)) json_top.append(map(lambda d: d.to_json(), self.dependencies)) json_top.append(self.tree.to_json()) json_top.append((self.sentstarts, self.sentends)) json_top.append(self.features) json.dump(json_top, f_json) f_json.close() def to_feat_json(self, boundary=None): minIndex = self.occurrences[0].start maxIndex = self.occurrences[-1].end json_top = {} if boundary == None: boundary = (minIndex, maxIndex, "none") json_top["bounds"] = boundary try: json_top["text"] = self.text[boundary[0]:boundary[1]] except: pdb.set_trace() json_top["features"] = self.features return json_top @staticmethod def from_own_json(json_name): f_json = open(json_name) [occ, deps, tree, (sstart, send), features] = json.load(f_json) f_json.close() occ = map(Occurrence.from_own_json, occ) deps = map(Dependency.from_own_json, deps) tree = Tree.from_own_json(tree) post = Post(occ, deps, tree, sstart, send) post.features = features return post def getIndex(self, lst, func, vals=None): #gets the first index that meets a certain criterion; used to bound occurrences and sentences for i,v in enumerate(lst): if func(v, vals): return i return None def build_features(self, feats=None, start=None, end=None): # default: None -> use default features minIndex = self.occurrences[0].start maxIndex = self.occurrences[-1].end if start is None: start = minIndex if end is None: end = maxIndex assert minIndex <= start <= maxIndex, "Start index is beyond bounds." assert minIndex <= end <= maxIndex, "End index is beyond bounds." assert start <= end, "Start index is greater than end index." startInd = self.getIndex(self.occurrences, lambda x,y: x.start>=y, start) endInd = self.getIndex(self.occurrences, lambda x,y: x.end>y, end) if endInd is None: endInd = len(self.occurrences)-1 occurrences = self.occurrences[startInd:endInd] text = self.text[start:end] tokens = [o.text for o in occurrences] feature_dependencies_in = [d for d in self.dependencies if startInd <= d.gov_index < endInd and startInd <= d.dep_index < endInd] feature_dependencies_boundary = [d for d in self.dependencies if startInd <= d.gov_index < endInd != startInd <= d.dep_index < endInd] # MPQA &c if feats is None: self.features = dict() # start fresh # default features feats = ['unigram', 'initialism', 'lengths', 'punctuation', 'quotes', 'liwc', 'dep'] for feat in feats: if feat.endswith('gram'): n = measure_to_int(feat) feature_extractor.get_ngrams(self.features, tokens, n=n) elif feat.endswith('alism'): feature_extractor.get_initialisms(self.features, tokens, use_lowercase=True, finalism=(feat == 'finalism')) elif feat.startswith('lengths'): sentences = [] numSents = len(self.sentstarts) for i in range(numSents): if self.sentstarts[i] > end: break sStart = self.sentstarts[i] sEnd = self.sentends[i] if self.sentends[i] > start and self.sentstarts[i] < start: sStart = start elif self.sentends[i] > end and self.sentstarts[i] < end: sEnd = end sentences.append(self.text[sStart:sEnd]) words = tokens feature_extractor.get_basic_lengths(self.features, text, sentences, words) elif feat.startswith('punct'): feature_extractor.get_repeated_punct(self.features, text) elif feat.startswith('quot'): feature_extractor.get_quoted_terms(self.features, text) elif feat.lower() == 'liwc': text_scores = Counter() text_scores['Word Count'] = len(occurrences) for o in occurrences: text_scores.update(o.liwc) text_scores = word_category_counter.normalize(text_scores) for category, score in text_scores.items(): self.features['LIWC:'+category] = score elif feat.lower() == 'dep': dep_scores = Counter() #pdb.set_trace() for d in feature_dependencies_in: dep_string = "%s(%s,%s)" % (d.relation, self.occurrences[d.gov_index].lemma, self.occurrences[d.dep_index].lemma) dep_scores[dep_string] += 1 for dep, score in dep_scores.items(): self.features['dep:'+ dep] = score # feature vector building stuff _measuredict = {'uni': 1, 'bi': 2, 'tri': 3} rx_measure = re.compile(r'(\w+)gram') def measure_to_int(s): m = rx_measure.match(s) if m is not None: m = m.group(1) if m in _measuredict: return _measuredict[m] return int(m) class Occurrence: def __init__(self, postdict): self.text = postdict.get(u'OriginalText',postdict.get(u'Current', '')) self.lemma = postdict.get(u'Lemma') self.pos = postdict.get(u'PartOfSpeech',None) self.start = postdict.get(u'CharacterOffsetBegin',None) self.end = postdict.get(u'CharacterOffsetEnd',None) self.before = postdict.get(u'Before', u'') self.after = postdict.get(u'After', u'') self._liwc = None # lazy evaluation via @property self.mpqa = mpqa.lookup(self.text, self.pos) def __repr__(self): return ' '.join([str(x) for x in [self.text, self.pos, self.start, self.end]]) @property def liwc(self): if self._liwc is None: self._liwc = dict(word_category_counter.score_word(self.text)) return self._liwc def getSent(self,sentStarts): s = 0 try: while self.start >= sentStarts[s]: s += 1 return s-1 except IndexError: return len(sentStarts)-1 def to_json(self): return { u'text': self.text, u'pos': self.pos, u'start': self.start, u'end': self.end, u'before': self.before, u'after': self.after, u'liwc': self._liwc, u'mpqa': self.mpqa, } @staticmethod def from_own_json(occmap, truncate=None): o = Occurrence({}) o.text = occmap[u'text'] o.pos = occmap[u'pos'] o.start = occmap[u'start'] o.end = occmap[u'end'] o.before = occmap[u'before'] o.after = occmap[u'after'] o._liwc = occmap[u'liwc'] o.mpqa = occmap[u'mpqa'] if truncate != None: if len(o.text) > truncate: o.text = o.text[:truncate] return o class Dependency: def __init__(self, relation, gov_index, dep_index): self.relation = relation self.gov_index = gov_index self.dep_index = dep_index def __repr__(self): return ' '.join([str(x) for x in [self.gov_index, self.relation, self.dep_index]]) def to_json(self): return { u'relation': self.relation, u'gov_index': self.gov_index, u'dep_index': self.dep_index, } @staticmethod def from_own_json(depmap): return Dependency(depmap[u'relation'], depmap[u'gov_index'], depmap[u'dep_index']) class Tree: def __init__(self, roots, parent, children, descendants, label, terminal, text, occMapping): self.roots = roots self.parent = parent self.children = children self.descendants = descendants self.label = label self.terminal = terminal self.text = text self.occMapping = occMapping def to_graphviz(self, outname, root=None): def nodename(node): s = self.label[node] if self.terminal[node]: s += r' \"%s\"' % self.text[node].replace('"', r'\"') s += ' (%d)' % node return s if root is None: nodes = self.roots[:] elif hasattr(root, '__iter__'): nodes = root else: nodes = [root] outname = str(outname) f_out = open(outname+'.dot', 'w') print >>f_out, 'digraph G {' while len(nodes) > 0: parent = nodes.pop() children = self.children[parent] pname = nodename(parent) if len(children) == 0: print >>f_out, ' "%s";' % pname else: for child in children: cname = nodename(child) print >>f_out, ' "%s" -> "%s";' % (pname, cname) nodes.extend(children) print >>f_out, '}' f_out.close() from os import system return system('dot -T png -o %s.png %s.dot' % (outname, outname)) def sentenceTrees(self): trees = [] for root in self.roots: trees.append(self.to_string(root)) return trees def sentenceTree(self, sentInd): if sentInd >= len(self.roots): return None else: return self.to_string(self.roots[sentInd]) def to_string(self, root=None): # possible to make tail-recursive? danger of stack overflow... :[ def to_string_aux(node): if self.terminal[node]: if self.label[node] in ['-LRB-', '-RRB-']: txt = "'%s'" % self.text[node] else: txt = "%s" % self.text[node] return r'( %s_%d %s )' % (self.label[node], node, txt) else: s = '( %s_%d' % (self.label[node], node) for child in self.children[node]: s += ' %s' % (to_string_aux(child)) s += ' )' return s if root is None: nodes = self.roots elif hasattr(root, '__iter__'): nodes = root else: nodes = [root] return ' '.join(map(to_string_aux, nodes)) def __repr__(self): return self.to_string() def to_json(self): return { u'roots': self.roots, u'parent': self.parent, u'children': self.children, u'descendants': self.descendants, u'label': self.label, u'terminal': self.terminal, u'text': self.text, u'occMapping': self.occMapping } @staticmethod def from_own_json(treemap): for ugh in [u'parent', u'children', u'descendants', u'label', u'terminal', u'text', u'occMapping']: tmpdict = {} for k,v in treemap[ugh].iteritems(): tmpdict[int(k)] = v treemap[ugh] = tmpdict return Tree(treemap[u'roots'], treemap[u'parent'], treemap[u'children'], treemap[u'descendants'], treemap[u'label'], treemap[u'terminal'], treemap[u'text'], treemap[u'occMapping']) #def same(first, second): # if type(first) != type(second): # print "type(first) != type(second); %s != %s" % (str(type(first)), str(type(second))) # return False # if isinstance(first, dict): # for k,v in first.iteritems(): # if not second.has_key(k): # print "key %s in first, but not in second" % repr(k) # return False # if not same(v, second[k]): # print "first[k] != second[k]; first[%s] != second[%s]; %s != %s" % (repr(k), repr(k), repr(v), repr(second[k])) # return False # elif hasattr(first, '__iter__'): # if len(first) != len(second): # print "iterables of different lengths (%d and %d)" % (len(first), len(second)) # return False # for i in range(len(first)): # if not same(first[i], second[i]): # print "first[i] != second[i]; first[%d] != second[%i]; %s != %s" % (i, i, repr(first[i]), repr(second[i])) # return False # elif isinstance(first, Occurrence) or isinstance(first, Dependency) or isinstance(first, Tree) or isinstance(first, Post): # for field in first.__dict__.keys(): # if not same(first.__dict__[field], second.__dict__[field]): # print "field %s is not the same" % field # return False # else: # if first != second: # print "first != second; %s != %s" % (repr(first), repr(second)) # return False # return True # #if __name__ == '__main__': # import sys # if len(sys.argv) < 2: name = "jsons/10004.json" # else: name = sys.argv[1] # post1 = Post.from_json(name) # post1.to_json('post1.json') # post2 = Post.from_own_json('post1.json') # print name, same(post1, post2) # vim:set textwidth=0: <file_sep>''' Created on Jul 19, 2012 ListTree class fully functional. Build a new list of ListTrees by calling the function build_ListTrees on a list of semantic dependencies. Each dependency graph will be turned into its own tree. @author: random ''' import mpqa.mpqa as mpqa from nlp.word_category_counter import score_word class Node: ''' Node class for ListTree Nodes are connected in governor-relation manner and in linear first-last sentence order each node contains info about that word nxt = next, prev = previous, gov = governor, deps = list of dependents everything else is information about the word ''' def __init__(self, word, index, pos, rel=None, lemma=None, start=None, end=None): ''' constructor ''' self.next_tree = None self.gov = None self.deps = None self.prev = None self.nxt = None self.dist = None self.start = start self.end = end self.mpqa = mpqa.lookup(word, pos) self.liwc = score_word(word) self.pos = pos self.word = word self.index = index self.rel = rel self.lemma = lemma def __repr__(self): ##Prints in the format ##index: word, pos, rel, lemma ##gov: ##deps: ##mpqa: ##liwc ##prev: ##nxt: to_return = str(self.index) + ": " + self.word + ", " + self.pos + ", " + str(self.rel) + ", " if self.lemma != None: to_return += str(self.lemma) to_return += "\ngov: " if self.gov != None: to_return += self.gov.word to_return += "\ndeps: " if self.deps != None: for node in self.deps: to_return += node.word + " " to_return += "\nrange: " if self.end != None: to_return += str(self.start) to_return += ", " if self.start != None: to_return += str(self.end) to_return += "\nprev: " if self.prev != None: to_return += self.prev.word to_return += "\n" to_return += "nxt: " if self.nxt != None: to_return += self.nxt.word return to_return def get_descendents(self, dist, notStart=True): if self.dist <= dist and notStart: return deps = [] if self.deps != None: deps.extend(self.deps) for dep in self.deps: des = dep.get_descendents(self.dist) if des != None: for node in des: if node not in deps: node.commitment = True deps.append(node) return deps def top_ends(self): curr = self.gov found = [] while (curr != None): if curr in found: return False found.append(curr) curr = curr.gov return True def build_dist(self, dist): ##Only call this on the root node, otherwise you will fuck ##everything up. Seriously. I'm not joking. Don't do it. if self.dist != None: return self.dist = dist dist += 1 if self.deps != None: for dep in self.deps: dep.build_dist(dist) class ListTree: ''' start = first node in sentence order root = root node, top of the dependency tree end = last node in sentence order, useful for some things ''' def __init__(self): ''' Constructor, does nothing other than instantiate ''' self.start = None self.root = None self.end = None def __repr__(self): ##Prints each word/node in sequential order according to the ##node string function to_return = "" trees = "" curr = self.start while (curr != None): to_return += str(curr.word) + " " trees += "\n" + str(curr) curr = curr.nxt ##to_return += trees return to_return def add_node(self, edge): ##Creates two nodes out of the edge nodeA = Node(edge['governor'], edge['governor_index'], edge['governor_pos']) nodeB = Node(edge['dependent'], edge['dependent_index'], edge['dependent_pos'], edge['relation']) curr = self.start if curr == None: ##If no nodes already in the ListTree, start at start nodeA.deps = [nodeB] nodeB.gov = nodeA nodeB.rel = edge['relation'] if nodeA.index <= nodeB.index: self.start = nodeA self.end = nodeB nodeA.nxt = nodeB nodeB.prev = nodeA else: self.start = nodeB self.end = nodeA nodeB.nxt = nodeA nodeA.prev = nodeB else: ##Otherwise, go through each node starting at start and find the ##right place to insert the node prev = None correctA = None while(curr != None and curr.index <= nodeA.index): if curr.index == nodeA.index: correctA = curr break prev = curr curr = curr.nxt ##Insert the node if correctA == None: nodeA.nxt = curr nodeA.prev = prev if prev != None: prev.nxt = nodeA if curr != None: curr.prev = nodeA if self.start == nodeA.nxt: self.start = nodeA if self.end == nodeA.prev: self.end = nodeA ##Do the same for the other node curr = self.start prev = None correctB = None while(curr != None and curr.index <= nodeB.index): if curr.index == nodeB.index: correctB = curr break prev = curr curr = curr.nxt if correctB == None: nodeB.nxt = curr nodeB.prev = prev if prev != None: prev.nxt = nodeB if curr != None: curr.prev = nodeB if self.start == nodeB.nxt: self.start = nodeB if self.end == nodeB.prev: self.end = nodeB ##Check to see if any node was already there ##Change the appropriate fields if either was already there if correctA != None: if correctB != None: if correctA.deps == None: correctA.deps = [correctB] else: if correctB not in correctA.deps: correctA.deps.append(correctB) correctB.gov = correctA correctB.rel = edge['relation'] else: nodeB.gov = correctA nodeB.rel = edge['relation'] if correctA.deps == None: correctA.deps = [nodeB] else: correctA.deps.append(nodeB) else: if correctB != None: correctB.gov = nodeA correctB.rel = edge['relation'] nodeA.deps = [correctB] else: nodeB.gov = nodeA nodeB.rel = edge['relation'] nodeA.deps = [nodeB] def add_node_pos(self, pos, index): ##Creates two nodes out of the edge text = '' try: text = pos['OriginalText'] except Exception, e: text = pos['Text'] nodeA = Node(text, index, pos['PartOfSpeech'], lemma = pos['Lemma'], start = pos['CharacterOffsetBegin'], end = pos['CharacterOffsetEnd']) curr = self.start if curr == None: ##If no nodes already in the ListTree, start at start self.start = nodeA self.end = nodeA else: ##Otherwise, go through each node starting at start and find the ##right place to insert the node prev = None correctA = None while(curr != None and curr.index <= nodeA.index): if curr.index == nodeA.index: curr.lemma = pos['Lemma'] break prev = curr curr = curr.nxt ##Insert the node if correctA == None: nodeA.nxt = curr nodeA.prev = prev if prev != None: prev.nxt = nodeA if curr != None: curr.prev = nodeA if self.start == nodeA.nxt: self.start = nodeA if self.end == nodeA.prev: self.end = nodeA def fixRoot(self): ##ListTree must already have a start or this won't work if self.start.index != 0: curr = self.start if self.start.gov == None: while curr.gov == None: curr = curr.nxt prev = None if curr.top_ends(): while curr != None: prev = curr curr = curr.gov else: found = [] while curr != None: if curr.gov != None: if "VB" in curr.pos and "VB" not in curr.gov.pos: break if curr in found: break found.append(curr) prev = curr curr = curr.gov if curr == None: curr = prev if self.end.pos == '.': self.root = self.end self.end.deps = [curr] curr.gov = self.end else: temp = Node('SentEndDummy', 0, 'DMY', 'DMY') temp.deps = [curr] curr.gov = temp self.root = temp elif self.start.pos != '.': ##If the root/zero node isn't punctuation, remove it ##and replace it with a dummy node so traversal functions ##will be simpler temp = Node('SentEndDummy', 0, 'DMY', 'DMY') temp.deps = self.start.deps for dep in self.start.deps: dep.gov = temp self.start.deps = None self.start.gov = None self.start = self.start.nxt self.start.prev.prev = None self.start.prev.nxt = None self.start.prev = None self.root = temp else: ##If the root/zer0 node is punctuation, keep it, move it ##to the back of the sentence list and set it as the root if self.start.word == self.end.word: temp = self.start self.start = self.start.nxt self.start.prev = None self.end.prev.nxt = temp temp.prev = self.end.prev temp.nxt = None self.end = temp self.root = temp else: temp = self.start self.start = self.start.nxt self.start.prev = None self.end.nxt = temp temp.prev = self.end temp.nxt = None self.end = temp self.root = temp def search_and_descend(self, word): curr = self.start to_return = [] while curr != None: if curr.word == word: deps = curr.get_descendents(curr.dist, False) if deps != None: for dep in deps: if dep not in to_return: dep.commitment = True to_return.append(dep) curr = curr.nxt return to_return def dists(self): self.root.build_dist(0) def get_quotes(self): to_return = [] curr = self.start while ( curr != None): if curr.lemma == "``": found = [] curr = curr.nxt while curr != None: if curr.lemma == "''": to_return.extend(found) found = [] break curr.commitment = True found.append(curr) if curr.nxt == None: curr = curr.next_tree else: curr = curr.nxt elif curr.lemma == "`": found = [] curr = curr.nxt while curr != None: if curr.lemma == "'": to_return.extend(found) found = [] break curr.commitment = True found.append(curr) if curr.nxt == None: curr = curr.next_tree else: curr = curr.nxt if curr != None: if curr.nxt == None: curr = curr.next_tree else: curr = curr.nxt return to_return def get_question(self): to_return = None if self.root != None: if self.root.word == "?": to_return = self.root.get_descendents(self.root.dist, False) to_return.append(self.root) if to_return != None: for node in to_return: node.commitment = True return to_return def get_nodes(self, word, strip=False): ##get a list of nodes governed by word nodes = self.search_and_descend(word) subj = None for node in nodes: ##look for the first subj, then move it out of the list if node.rel == "nsubj" and node.gov.word == word: subj = node nodes.remove(node) break if strip: ##strip possibility because i think there might be issues with spurious ##words getting saved for node in nodes: if node.rel == "mark" or node.rel == "complm": nodes.remove(node) return(subj, nodes) def get_adv(self, adv): ##takes in an adverb, finds it in the dependency, pulls out everything ##the verb governing it governs verb = None curr = self.start to_return = [] while (curr != None): if curr.word.lower() == adv: nodes = curr.gov.get_descendents(curr.gov.dist, False) verb = curr.gov curr.commitment = True to_return.append((verb, nodes)) curr = curr.nxt return to_return def get_cond(self): antecedent = None resultant = None if self.start != None: curr = self.start while curr != None: if curr.word.lower() == 'if': ''' print self print curr print "\n\n" now = self.start while now != None: print now now = now.nxt ''' if curr.rel != "dep": if curr.gov != None and curr.gov.gov != None: if not (curr.gov.pos == "." or curr.gov.gov.pos == "." or curr.gov.rel == "parataxis" or curr.gov.gov.rel == "parataxis" or curr.gov.gov.pos == "DMY"): if not (len(curr.gov.deps) <= 1): antecedent = curr.gov.get_descendents(curr.gov.dist, False) antecedent.append(curr.gov) resultant = [node for node in curr.gov.gov.get_descendents(curr.gov.gov.dist, False) if node not in antecedent] resultant.append(curr.gov.gov) for node in resultant: node.commitment = True for node in antecedent: node.commitment = True break curr = curr.nxt if antecedent != None: for node in antecedent: if node.nxt != None: if node.nxt.pos == '.': antecedent.append(node.nxt) if resultant != None: for node in resultant: if node.nxt != None: if node.nxt.pos == '.': resultant.append(node.nxt) return (antecedent, resultant) def get_neg(self): verbs = [] all_none = [] curr = self.start while curr != None: if curr.rel == 'neg': if "VB" in curr.gov.pos: verbs.append(curr.gov) all_none.extend(curr.gov.get_descendents(curr.dist, notStart = False)) curr = curr.nxt return (verbs, all_none) def build_ListTrees(deps, poses): ##Build a list of ListTrees from a list of deps ##Each dependency graph becomes its own tree listTree_list = [] for num in range(len(deps)): ##For each dep(and pos in the future), build a ListTree ##and append it to the list dep = deps[num] pos = poses[num] if len(dep) < 1: continue if len(pos) < 1: continue tree = ListTree() for curr in range(len(pos)): tree.add_node_pos(pos[curr], curr+1) for edge in dep: tree.add_node(edge) tree.fixRoot() if tree.root != None: tree.dists() listTree_list.append(tree) num = 0 while (num+1 < len(listTree_list)): listTree_list[num].end.next_tree = listTree_list[num+1].start num += 1 return listTree_list if __name__ == '__main__': import json curr_file = "/home/random/workspace/Persuasion/data/convinceme/output_by_thread/1736/21585.json" j = json.load(open(curr_file)) pos = j[0] deps = j[2] trees = build_ListTrees(deps, pos) for tree in trees: print tree quotes = trees[0].get_quotes() print print print quotes print print<file_sep>from nlp import stanford_nlp def get_roots(dependencies, word): """gather all the nodes that meet the requirement""" subroots = set() visited = set() try: possible = [dependency['dependent_index'] for dependency in dependencies if dependency['governor'].startswith(word)] subroots.update(possible) except Exception, e: print 'Exception:{}'.format(e) def _roots(dependencies, word): """recursive helper function for gathering the nodes""" for dependency in dependencies: if dependency['dependent_index'] in visited: continue visited.add(dependency['dependent_index']) if dependency['governor'].startswith(word): if not dependency['dependent_index'] in subroots: subroots.add(dependency['dependent_index']) subroots.update(_roots(dependencies, word=dependency['dependent'])) return subroots return _roots(dependencies, word) def match(dependencies, word): roots = get_roots(dependencies, word) deps = [] for dependency in dependencies: if dependency['dependent_index'] in roots: deps.append(dependency) #currently stores the whole node so that it's more robust return deps def get_nodes(word, tree, strip=False): ##get a list of nodes governed by word nodes = tree.search_and_descend(word) subj = None for node in nodes: ##look for the first subj, then move it out of the list if node.rel == "nsubj" and node.gov.word == word: subj = node nodes.remove(node) break if strip: ##strip possibility because i think there might be issues with spurious ##words getting saved for node in nodes: if node.rel == "mark" or node.rel == "complm": nodes.remove(node) return(subj, nodes) def label(deps, tag): return ["{}_{}".format(tag, dep['dependent']) for dep in deps] ##this function might be pointless now, but we should keep it just in case if __name__ == '__main__': ##testing shit, can be deleted tag = "agree" sentence = 'I agree with Bob about how ugly Steve is.' print sentence pos,meta,dependency = stanford_nlp.get_parses(sentence) nodes = get_nodes(dependency[0], tag) print label(nodes[1], tag) print nodes[0] sentence = 'I am not sure if Steve agrees with Bob.' print sentence pos,meta,dependency = stanford_nlp.get_parses(sentence) nodes = get_nodes(dependency[0], tag) print label(nodes[1], tag) print nodes[0] sentence = 'I agree that people are stupid. You agree they are nice.' print sentence pos,meta,dependency = stanford_nlp.get_parses(sentence) for sent in dependency: nodes = get_nodes(sent, tag) print label(nodes[1], tag) print nodes[0] tag = "admit" sentence = 'I admit that I like cookies.' print sentence pos,meta,dependency = stanford_nlp.get_parses(sentence) nodes = get_nodes(dependency[0], tag) print label(nodes[1], tag) print nodes[0] sentence = 'I admit that I like cookies' print sentence pos,meta,dependency = stanford_nlp.get_parses(sentence) nodes = get_nodes(dependency[0], tag) print label(nodes[1], tag) print nodes[0] #additionally you can pass the dep tree from the jsons into the get_children_dependency(dep_tree, 'search_word') <file_sep>''' Created on Jul 6, 2012 @author: random ''' from nlp import boundary import listTree import sisters def load_words(): ##Function that loads four sets of verbs to check the sisters of ##List of the files to load from to_load = ["regardless_commit.txt", "first_commit.txt", "second_commit.txt", "regardless_oppose.txt"] words = [] for name in to_load: ##Open each file, load the words from that file curr_file = open(name, 'r') curr_list = [] while (True): token = curr_file.readline() if token == "": break token = token.rstrip("\n") if token != "": curr_list.append(token) words.append(curr_list) return words ##Both get_commit and get_oppose return a list of tuples ##Each tuple goes (context word, [list of nodes that are complements of context word]) ##First, second, oppose, commit are all lists of words ##Dep is a single dependency graph, pos is a single pos list for a sentence def get_oppose(first, second, oppose, tree): to_return = [] ##Go through each set of verbs and pull out its dependents ##Keep those lists that are opposed for word in first: ##Finds nodes that are complements of first-person commit nodes = sisters.get_nodes(word, tree) if (nodes[0] != None): if nodes[0].word.lower() == 'you': to_return.append((word, nodes[1])) for word in second: ##Of second person commmit nodes = sisters.get_nodes(word, tree) if (nodes[0] != None): if nodes[0].word.lower() == 'i': to_return.append((word, nodes[1])) for word in oppose: ##Of either oppose nodes = sisters.get_nodes(word, tree) if (nodes[0] != None): if nodes[0].word.lower() == 'you' or nodes[0].word.lower() == 'i': to_return.append((word, nodes[1])) return to_return def get_commit(commit, first, second, tree): ##Go through each set of verbs and pull out its dependents ##Keep those lists that are committed ##Exactly like get_oppose, just swapped you and i and changed to commit regardless to_return = [] for word in first: nodes = sisters.get_nodes(word, tree) if (nodes[0] != None): if nodes[0].word.lower() == 'i': to_return.append((word, nodes[1])) for word in second: nodes = sisters.get_nodes(word, tree) if (nodes[0] != None): if nodes[0].word.lower() == 'you': to_return.append((word, nodes[1])) for word in commit: nodes = sisters.get_nodes(word, tree) if (nodes[0] != None): if nodes[0].word.lower() == 'you' or nodes[0].word.lower() == 'i': to_return.append((word, nodes[1])) return to_return def update_feat_vect(tree, word_lists): ##Load word lists regardless_commit, first_commit, second_commit, regardless_oppose = word_lists ##Get oppose words and nodes oppose = get_oppose(first_commit, second_commit, regardless_oppose, tree) ##Get commit words and nodes commit = get_commit(regardless_commit, first_commit, second_commit, tree) ##Return tuple consisting of (commit tuples, oppose tuples) return (commit, oppose) ##The final data structure goes ( [ (commit word, [commit nodes]) ...], [ (oppose word, [oppose nodes]) ] ) def update(name, node, vect): ''' vect[name+"unigram: "+node.word.lower()] += 1 if node.liwc != None: for key in dict(node.liwc): vect[name+"LIWC: "+key] += 1 ''' if node.deps != None: for curr in node.deps: dep_string = "pos_genDep: %s(%s,%s)" % (curr.rel, node.pos, curr.lemma) dep_string = name + dep_string vect[dep_string] += 1 ''' if node.mpqa != None: pass ##this needs to be filled with the appropriate mpqa feature stuff ''' def build_ranges(nodes, name, is_quote=False): starts = [node for node in nodes] quote_types = ["'", "''", "`", "``"] to_return = [] found_nodes = [] start = None prev = None for node in nodes: if start == None: #if there's no node starting the range, use this one start = node else: #if there is a start node, it's either prev or connected to prev #via function words. take prev and see if it connects to node via #a series of function words or directly curr = prev if curr.nxt != node: if curr.nxt != None: curr = curr.nxt #make a list to add function words to to_extend = [] while curr.gov == None and curr.deps == None: if is_quote and (curr.lemma in quote_types): break #add the function word to_extend.append(curr) #go to the next word if curr.nxt != None: curr = curr.nxt else: if curr.next_tree != None: curr = curr.next_tree else: break if curr != node: #if it didn't find a connection between prev and node, #store the old range and start a new one to_return.append((start.start, prev.end, name)) start = node else: #if it did find a range, extend nodes with the function words found_nodes.extend(to_extend) else: to_return.append((start.start, curr.end, name)) start = node #change prev prev = node if prev != None: if start == None: start = prev to_return.append((start.start, prev.end, name)) starts.extend([node for node in found_nodes]) return (to_return, starts, found_nodes) def feat_vect(deps, pos, vect): trees = listTree.build_ListTrees(deps, pos) nones = [] tuples = [] quotes = [] questions = [] antecedents = [] consequents = [] neg_verbs = [] neg_all = [] commit_starts = [] for num in range(len(trees)): tree = trees[num] ''' verbs, all_neg = tree.get_neg() if verbs: neg_verbs.extend(verbs) verbs = sorted(list(set(verbs)), key=lambda node: node.start) ranged = build_ranges(verbs, 'neg_verbs') tuples.extend(ranged[0]) commit_starts.extend(ranged[1]) neg_verbs.extend(ranged[2]) if all_neg: neg_all.extend(all_neg) all_neg = sorted(list(set(all_neg)), key=lambda node: node.start) ranged = build_ranges(all_neg, 'neg_all') tuples.extend(ranged[0]) commit_starts.extend(ranged[1]) neg_all.extend(ranged[2]) ''' question = tree.get_question() if question != None: questions.extend(question) question = sorted(list(set(question)), key=lambda node: node.start) ranged = build_ranges(question, 'question') tuples.extend(ranged[0]) commit_starts.extend(ranged[1]) questions.extend(ranged[2]) for node in question: node.commitment = True condit = tree.get_cond() if condit[0] != None and condit[1] != None: ant, cons = condit antecedents.extend(ant) ant = sorted(list(set(ant)), key=lambda node: node.start) ranged = build_ranges(ant, 'antecedent') tuples.extend(ranged[0]) commit_starts.extend(ranged[1]) antecedents.extend(ranged[2]) for node in ant: node.commitment = True consequents.extend(cons) cons = sorted(list(set(cons)), key=lambda node: node.start) ranged = build_ranges(cons, 'consequent') tuples.extend(ranged[0]) commit_starts.extend(ranged[1]) antecedents.extend(ranged[2]) for node in cons: node.commitment = True if len(trees) > 0: quotes = trees[0].get_quotes() if len(quotes) > 0: quotes= sorted(list(set(quotes)), key=lambda node: node.start) ranged = build_ranges(quotes, 'quote', is_quote=True) tuples.extend(ranged[0]) commit_starts.extend(ranged[1]) quotes.extend(ranged[2]) for node in quotes: node.commitment = True for tree in trees: curr = tree.start while curr != None: nones.append(curr) curr = curr.nxt commits = quotes + questions + antecedents + consequents + neg_all + neg_verbs nones = [node for node in nones if node not in commits] nones = sorted(list(set(nones)), key=lambda node: node.start) ranged = build_ranges(nones, 'none') tuples.extend(ranged[0]) nones.extend(ranged[2]) name = "NONE_" for node in nones: update(name, node, vect) name = "QUOTE_" for node in quotes: update(name, node, vect) name = "QUESTION_" for node in questions: update(name, node, vect) name = "ANTECEDENT_" for node in antecedents: update(name, node, vect) name = "CONSEQUENT_" for node in consequents: update(name, node, vect) ''' name = "NEG_VERBS_" for node in neg_verbs: update(name, node, vect) name = "NEG_ALL_" for node in neg_all: update(name, node, vect) ''' return tuples if __name__ == '__main__': import json curr_file = "/home/random/workspace/Persuasion/data/convinceme/output_by_thread/1736/21585.json" j = json.load(open(curr_file)) pos = j[0] deps = j[2] trees = listTree.build_ListTrees(deps, pos) for tree in trees: print tree quotes = trees[0].get_quotes() print print print quotes print print vect = {} tuples = feat_vect(deps, pos, vect) if len(vect) > 0: print vect for tup in tuples: print tup <file_sep>import re import os import itertools import csv from collections import Counter from parser import tokenize class Generic: pass simple_re = re.compile('.') def get_ngrams(feature_vector, words, n=1, prefix='uni_', style='binary'): unigrams = ['-nil-' for i in range(n-1)]+words+['-nil-' for i in range(n-1)] n_grams = list() for i in range(len(unigrams)-n+1): n_grams.append(' '.join(unigrams[i:i+n])) word_counts = Counter(n_grams) total_words = sum(word_counts.values())#len(n_grams) for word, count in word_counts.items(): if type == 'binary': feature_vector[prefix + word] = True elif type == 'float': feature_vector[prefix + word] = count / float(total_words) else: feature_vector[prefix + word] = count def ngrams_from_text(text, feature_vector, prefix, n=1, style='float'): sentences = tokenize(text, break_into_sentences=True) words_flat = flatten(sentences) get_ngrams(feature_vector=feature_vector, n=n, prefix=prefix, words=words_flat, style=style) def maybe_convert(old, func = int): if isinstance(old, list): return [maybe_convert(elem, func) for elem in old] try: return func(old) except: return old #returns a list of dicts indexed by the header (first line) in the csv file def csv_to_dicts(filename, delimiter=None): if delimiter: csv_obj = csv.reader(open(filename),delimiter=delimiter) else: csv_obj = csv.reader(open(filename)) csv_list = list(csv_obj) result_dicts = list() headings = csv_list.pop(0) for row in csv_list: row_dict = dict() for i in range(len(headings)): try: row_dict[headings[i]] = row[i] except: row_dict[headings[i]] = None result_dicts.append(row_dict) return result_dicts #@param csv_file: an opened file object e.g.: csv_file = open("bar.csv") #@param dicts: an iterable (list) of dicts which contain your data. Index => Column. #@param output_list_header: a list of column headers to use - lets you select only some from the dict, and lets you pick the order if sorting is false. If left as None, selects keys the first row in dicts def dicts_to_csv(csv_file, dicts, include_header=True, delimiter=',', sort_by_heading=False, output_list_header=None, missing_entry_value=None): if output_list_header == None: output_list_header = dicts[0].keys() if sort_by_heading: output_list_header = sorted(output_list_header) output_list = list() if include_header: output_list.append(output_list_header) for dict_obj in dicts: output_list.append(list()) for column_label in output_list_header: if column_label in dict_obj: output_list[-1].append(dict_obj[column_label]) else: output_list[-1].append(missing_entry_value) writer = csv.writer(csv_file,delimiter=delimiter) for row in output_list: writer.writerow(row) psutil_process_info = None def setup_memory_management(): import psutil psutil_process_info = psutil.Process(os.getpgid(0)) def running_out_of_memory(): return (psutil_process_info.get_memory_percent() > 75.0) # Flatten one level of nesting def flatten(listOfLists): return list(itertools.chain.from_iterable(listOfLists)) def powerset(iterable): s = list(iterable) return itertools.chain.from_iterable(itertools.combinations(s, r) for r in range(len(s)+1)) def escape_filename(filename): return filename.replace('\\','_b_slash_').replace('/','_f_slash_')[:255] #from wikipedia def computeKappa(mat): """ Computes the Kappa value @param n Number of rating per subjects (number of human raters) @param mat Matrix[subjects][categories] @return The Kappa value """ n = checkEachLineCount(mat) # PRE : every line count must be equal to n N = len(mat) k = len(mat[0]) # Computing p[] p = [0.0] * k for j in xrange(k): p[j] = 0.0 for i in xrange(N): p[j] += mat[i][j] p[j] /= N*n # Computing P[] P = [0.0] * N for i in xrange(N): P[i] = 0.0 for j in xrange(k): P[i] += mat[i][j] * mat[i][j] P[i] = (P[i] - n) / (n * (n - 1)) # Computing Pbar Pbar = sum(P) / N # Computing PbarE PbarE = 0.0 for pj in p: PbarE += pj * pj kappa = (Pbar - PbarE) / (1 - PbarE) return kappa #used for computing kappa def checkEachLineCount(mat): """ Assert that each line has a constant number of ratings @param mat The matrix checked @return The number of ratings @throws AssertionError If lines contain different number of ratings """ n = sum(mat[0]) assert all(sum(line) == n for line in mat[1:]), "Line count != %d (n value)." % n return n <file_sep>''' Created on Jun 26, 2012 @author: random ''' import sisters from nlp import stanford_nlp def get_quotes(sent): open_quotes = [] close_quotes = [] ##build a set of opening and closing quotes for pos in sent: if pos['PartOfSpeech'] == "\'\'": close_quotes.append(int(pos['BeginIndex'])) elif pos['PartOfSpeech'] == "``": open_quotes.append(int(pos['BeginIndex'])) return (open_quotes, close_quotes) def quote_nodes(sents, deps): nodes = [] for i in range(len(deps)): dep = deps[i] sent = sents[i] indices = [] quotes = get_quotes(sent) #assumes that the number of closing quotes is less than the number of opening #loops for length of opening and closing quotes, appending each node between them for num in range(len(quotes[1])): for curr in range(quotes[0][num]+1, quotes[1][num]): indices.append(int(sent[curr]['TokenBegin'])) print indices for edge in dep: if edge['dependent_index'] in indices: nodes.append(edge) return nodes def get_question(sent): ##just looks to see if there's a question mark, and returns the whole ##sentence's dependency parse if there is for node in sent: if node['governor'] == "?": return sent return None def question_nodes(sents): ##goes through a set of dependencies and builds a full set of nodes ##from question sentences. might be pointless. nodes = [] for sent in sents: question = get_question(sent) if question != None: nodes.extend(question) return nodes def get_negs(sent): ##looks for a negation node, then gets all nodes governed by its governor ##which is, presumably, the main verb or the negated verb verb = None for node in sent: if node['relation'] == "neg": nodes = sisters.get_nodes(sent, node['governor'])[1] verb = node['governor'] return (verb, nodes) def negation_nodes(sents): ##builds a list of negated verbs and nodes by iterating ##over a list of dependencies nodes = [] verbs = [] for sent in sents: negs = get_negs(sent) nodes.extend(negs[1]) verbs.append(negs[0]) nodes = [node for node in nodes if node['relation'] != "neg"] #the verbs and the nodes need to be treated differently, nodes are nodes, verbs are strings return (verbs, nodes) if __name__ == '__main__': tag = "?" sentence = '"Life threatening condition that is always physically harmful"? What a giant load of steamy BS.' print sentence pos,meta,dependency = stanford_nlp.get_parses(sentence) nodes = question_nodes(dependency) print sisters.label(nodes, tag) tag = "quote" sentence = '"Life threatening condition that is always physically harmful"? What a giant load of steamy BS.' print sentence pos,meta,dependency = stanford_nlp.get_parses(sentence) words = quote_nodes(pos, dependency) print sisters.label(words, tag) tag = "quote" sentence = "John said 'I like cookies.'" print sentence pos,meta,dependency = stanford_nlp.get_parses(sentence) words = quote_nodes(pos, dependency) print sisters.label(words, tag) <file_sep>#!/usr/bin/env python import json import os import operator import sys import re import random from collections import defaultdict, Counter try: from discussion import Dataset, data_root_dir except Exception, e: from grab_data.discussion import Dataset, data_root_dir from file_formatting import arff_writer from nlp.text_obj import TextObj from nlp.feature_extractor import get_features_by_type, get_dependency_features from nlp.boundary import Boundaries from grab_data.convinceme_extras import get_topic_side sys.path.append('..') from get_features import feat_vect from annotate import annotate from utils import ngrams_from_text DELETE_QUOTE = False rand = [] def merrrr(text, boundaries): return ["{}:{}".format(bound[2].upper(), re.sub(r'\r', '', text)[bound[0]:bound[1]]) for bound in boundaries] def uni_from_boundaries(text, boundaries, features): bounds = [(bound[2].upper(), re.sub(r'\r', '', text)[bound[0]:bound[1]]) for bound in boundaries] for bound in bounds: ngrams_from_text(bound[1], features, prefix=bound[0]+"_uni_caps_", n=1, style='float') ngrams_from_text(bound[1].lower(), features, prefix=bound[0]+"_uni_lower_", n=1, style='float') class Bounds(object): def __init__(self, output='bounds_dump'): self._dict = defaultdict(lambda: defaultdict(list)) self._output = output def add(self, discussion_id, post_id, text, tuples): boundaries = Boundaries() boundaries.initializeFromTuples(tuples) try: boundaries.walk(0, max(tuples, key=operator.itemgetter(1))) self._dict[discussion_id][post_id] = boundaries.partitions rand.append([text, merrrr(text, tuples), tuples, discussion_id, post_id]) except ValueError, e: pass def dump(self): print 'Dumping Boundaries to {}.'.format(self._output) json.dump(self._dict, open(self._output, 'wb')) class Commitment(object): def __init__(self, topic, features=['unigram', 'LIWC', 'pos_dep']): self.topic = topic self.feature_vectors = [] self.classification_feature = 'commitment' self.features = features self.bounds = Bounds() self.dir = re.sub(r'\s+', '_', topic) def generate_features(self): dataset = Dataset('convinceme',annotation_list=['topic','dependencies','used_in_wassa2011', 'side']) directory = "{}/convinceme/output_by_thread".format(data_root_dir) for discussion in dataset.get_discussions(annotation_label='topic'): if self.topic != discussion.annotations['topic']: continue for post in discussion.get_posts(): feature_vector = defaultdict(int) post.discussion_id = discussion.id post.topic_side = get_topic_side(discussion, post.side) post.key = str((discussion.id,post.id)) feature_vector[self.classification_feature] = post.topic_side try: json_file = "{}/{}/{}.json".format(directory, discussion.id, post.id) pos, parsetree, dep, ident = json.load(open(json_file, 'r')) result = sorted(feat_vect(dep, pos, feature_vector), key=operator.itemgetter(0)) try: text = TextObj(post.text.decode('utf-8', 'replace')) except Exception, e: continue self.bounds.add(discussion_id=discussion.id, post_id=post.id, text=text.text, tuples=result) uni_from_boundaries(text.text, result, feature_vector) dependency_list = None if 'dependencies' not in post.annotations else post.annotations['dependencies'] if 'unigram' in self.features: ngrams_from_text(text.text.lower(), feature_vector, prefix="uni_lower_", n=1, style='float') ngrams_from_text(text.text, feature_vector, prefix="uni_caps_", n=1, style='float') feats = set(self.features).difference(set(['unigram'])) get_features_by_type(feature_vector=feature_vector, features=feats, text_obj=text, dependency_list=dependency_list) if None == dependency_list: continue if 'dependencies' in self.features: get_dependency_features(feature_vector, dependency_list, generalization='opinion') if DELETE_QUOTE: unigrams = map(lambda x: x[8:], filter(lambda x: x.startswith('unigram:'), feature_vector.keys())) for unigram in unigrams: key = 'quote: {}'.format(unigram) if key in feature_vector: del feature_vector[key] self.feature_vectors.append(feature_vector) except IOError, e: # XXX TODO : we don't have all the parses saved apparently so this sometimes fails. pass self.bounds.dump() def generate_arffs(self, output_dir='arffs_output'): if not self.feature_vectors: return types = set() output_dir = "{}/{}".format(output_dir, self.dir) minimum_inst = max(2, int(0.01 * len(self.feature_vectors))) arff_writer.write("{}/all.arff".format(output_dir), self.feature_vectors, classification_feature=self.classification_feature, write_many=False, minimum_instance_counts_for_features=minimum_inst) regex = re.compile(r'(.*)_uni_(.*)$') commitment = ['NONE', 'CONSEQUENT'] non_commitment = ['ANTECEDENT', 'QUOTE', 'QUESTION'] collapsed_dicts = [] for vector in self.feature_vectors: _modified = dict() for key, value in vector.iteritems(): result = regex.match(key) if result: types.add(result.group(1)) if result.group(1) in commitment: _modified['commitment: {}'.format(result.group(2))] = value elif result.group(1) in non_commitment: _modified['non_commitment: {}'.format(result.group(2))] = value _modified[key] = vector[key] collapsed_dicts.append(_modified) arff_writer.write("{}/all_collapsed.arff".format(output_dir), collapsed_dicts, classification_feature=self.classification_feature, write_many=False, minimum_instance_counts_for_features=minimum_inst) def main(self): self.generate_features() self.generate_arffs() if __name__ == '__main__': for topic in ['death penalty', 'gay marriage', 'existence of god', 'evolution']: commitment = Commitment(topic=topic, features=['unigram']) commitment.main() fd = open('dump_random_'+re.sub(' ', '_', topic), 'wb') for line in random.sample(rand, 10): text, annots, raw, discussion, post = line fd.write("Discussion:{}, Post:{}\n".format(discussion, post)) fd.write("TEXT:{}\n".format(text)) for annotation in annots: fd.write("{}\n".format(annotation)) fd.write("RAW:{}\n\n".format(raw)) #fd.write("ANNOTS:{}\n\n".format(annots)) fd.close() <file_sep> import re, sys from os.path import basename import json from collections import defaultdict, Counter import operator import nltk.stem try: from discussion import Dataset, data_root_dir except Exception, e: from grab_data.discussion import Dataset, data_root_dir from nlp.text_obj import TextObj from nlp import post from nlp.boundary import Boundaries from grab_data.convinceme_extras import get_topic_side from file_formatting import arff_writer from nlp.extract_contexts import _featlists from machine_learning import weka_interface from progress_reporter.progress_reporter import ProgressReporter RUN_FOURFORUMS = False RUN_CONVINCEME = True POSTS_KEY = 'POSTS' class CommitmentCounter(object): def __init__(self, label='side'): self.label = label self.freq = defaultdict(int) self.by_topic = defaultdict(lambda: defaultdict(int)) self.by_side = defaultdict(lambda: defaultdict(lambda: defaultdict(int))) self.stemmer = nltk.stem.PorterStemmer() self.feature_vectors_by_topic = defaultdict(lambda: list()) self.collapsed_vectors = defaultdict(lambda: list()) self.commitment_vectors = defaultdict(lambda: list()) self.feature_vectors = list() self.environments_topic = defaultdict(lambda: Counter()) def write(self, vectors, topic, featureset): minimum_inst = max(2, int(0.01 * len(vectors))) output_dir = 'arffs' arff_writer.write("{directory}/{topic}/{featureset}.arff".format(directory=output_dir,topic=topic,featureset=featureset), self.feature_vectors_by_topic[topic], classification_feature=self.label, write_many=False, minimum_instance_counts_for_features=minimum_inst) def start(self): dataset = Dataset('convinceme',annotation_list=['side', 'topic','dependencies','used_in_wassa2011'])#'topic','dependencies']) for discussion in dataset.get_discussions(annotation_label='topic'): topic = discussion.annotations['topic'] for post in discussion.get_posts(): post.discussion_id = discussion.id post.topic_side = get_topic_side(discussion, post.side) post.key = str((discussion.id,post.id)) result = self.extract(post, topic) if result: self.feature_vectors_by_topic[topic].append(result['all']) self.collapsed_vectors[topic].append(result['collapsed']) self.commitment_vectors[topic].append(result['commitment']) for topic in self.feature_vectors_by_topic.keys(): print '{topic} has {length} elements.'.format(**{'topic': topic, 'length': len(self.feature_vectors_by_topic[topic])}) _feats = {'all': self.feature_vectors_by_topic, 'commitment': self.commitment_vectors, 'collapsed': self.collapsed_vectors,} fd = open('results', 'w') print 'Experimental Results:' fd.write('Experimental Results:\n') for topic in ['evolution','gay marriage', 'existence of god', 'abortion']: for featureset, vectors in _feats.iteritems(): self.write(vectors=vectors, topic=topic, featureset=featureset) classifiers = ['weka.classifiers.functions.SMO']#'weka.classifiers.bayes.NaiveBayes'] arff_folder = 'arffs/{topic}/'.format(topic=topic) arffs = ['all.arff', 'collapsed.arff', 'commitment.arff'] print '**RESULTS: {topic}'.format(topic=topic) fd.write('**RESULTS: {topic}\n'.format(topic=topic)) for arff in arffs: results = defaultdict(dict) #run->classifier->featureset->results for classifier_name in classifiers: run_results = weka_interface.cross_validate(arff_folder, [arff], classifier_name=classifier_name, classification_feature=self.label, n=10) right = sum([1 for entry in run_results.values() if entry['right?']]) run_accuracy = right / float(len(run_results)) print '\t{arff}: accuracy - {accuracy}'.format(arff=arff, accuracy=run_accuracy) fd.write('\t{arff}: accuracy - {accuracy}\n'.format(arff=arff, accuracy=run_accuracy)) fd.close() def extract(self, post, topic, features=[]): if len(features) == 0: features = _featlists.keys() else: features = filter(lambda x: x in _featlists, features) spans = [] # span := [ span-id, [ start, stop, { "category": (major, minor), "environment_indicators": [ (word, occurrence_id) ] } ] ] for featpair in features: (word_pairs, phrase_pairs) = _featlists[featpair] occ_i = 0 for word, rx in word_pairs: position = 0 for sentence in re.split(r'\.!?', post.text): match = rx.match(post.text) if match: spans.append( [ "%s-%s" % (str(post.id), len(spans)+1), [ position + match.start(), position + match.end(), { "category": featpair, "environment_indicators": [ (word, str(occ_i)) ] } ] ] ) position += len(sentence) occ_i += 1 occ_i = 0 for phrase, rx in phrase_pairs: for m in rx.finditer(post.text): spans.append( [ "%s-%s" % (str(post.id), len(spans)+1), [ m.start(), m.end(), { "category": featpair, "environment_indicators": [ (m.group(0), -1) ] } ] ] ) occ_i += 1 self.by_topic[topic][POSTS_KEY] += 1 environments = set() for span in set([d[1][2]['category'] for d in spans]): self.freq[span] += 1 self.by_topic[topic][span] += 1 self.by_side[topic][post.topic_side][span] += 1 environments.add(span[0]) #XXX TODO need to make sure that the environments we are checking for are in the top three as far as probabiltiy goes self.environments_topic[topic].update([len(environments)]) if len(environments) < 2: return #print 'throwing post away. discussion: {discussion} id: {id}'.format(**{'discussion': topic, 'id': post.id}) tuples = [] for span in spans: start, stop, name = span[1][0], span[1][1], '-'.join(span[1][2]['category']) tuples.append((start,stop,name)) b = Boundaries() b.initializeFromTuples(tuples) if len(b.boundaries) == 0: return b.walk(1, max(tuples, key=operator.itemgetter(1))) #print 'boundaries:{boundary.boundaries}\nparititions:{boundary.partitions}'.format(boundary=b) fv_all = defaultdict(int) fv_collapsed = defaultdict(int) fv_commitment = defaultdict(int) tokens = 0 for partition in b.partitions[:-1]: unigrams = map(lambda unigram: self.stemmer.stem(unigram.lower()), re.split(r'\W', post.text[partition[0]:partition[1]])) tokens += len(unigrams) for _label in set(partition[2].split()): for unigram in unigrams: fv_commitment['{}:{}'.format(_label, unigram)] += 1 if _label == 'none': fv_collapsed['commitment:{unigram}'.format(unigram=unigram)] += 1 else: fv_collapsed['non_commitment:{unigram}'.format(unigram=unigram)] += 1 for unigram in unigrams: fv_all['unigram_{unigram}'.format(unigram=unigram)] += 1 for key in fv_all.keys(): fv_all[key] /= float(tokens) for key in fv_commitment.keys(): fv_commitment[key] /= float(tokens) for key in fv_collapsed.keys(): fv_collapsed[key] /= float(tokens) fv_all[self.label] = post.topic_side fv_commitment[self.label] = post.topic_side fv_collapsed[self.label] = post.topic_side return {'all': fv_all, 'collapsed': fv_collapsed, 'commitment': fv_commitment} def start_(self): dataset = Dataset('fourforums',annotation_list=['qr_dependencies', 'topic'])#'topic','dependencies']) for discussion in dataset.get_discussions(annotation_label='mechanical_turk'): if 'qr_meta' not in discussion.annotations['mechanical_turk']: continue topic = discussion.annotations['topic'] for post in discussion.get_posts(): result = self.extract_(post, topic) if result: self.feature_vectors.append(result) def extract_(self, post, topic, features=[]): if len(features) == 0: features = _featlists.keys() else: features = filter(lambda x: x in _featlists, features) spans = [] # span := [ span-id, [ start, stop, { "category": (major, minor), "environment_indicators": [ (word, occurrence_id) ] } ] ] for featpair in features: (word_pairs, phrase_pairs) = _featlists[featpair] occ_i = 0 for word, rx in word_pairs: position = 0 for sentence in re.split(r'\.!?', post.text): match = rx.match(post.text) if match: spans.append( [ "%s-%s" % (str(post.id), len(spans)+1), [ position + match.start(), position + match.end(), { "category": featpair, "environment_indicators": [ (word, str(occ_i)) ] } ] ] ) position += len(sentence) occ_i += 1 occ_i = 0 for phrase, rx in phrase_pairs: for m in rx.finditer(post.text): spans.append( [ "%s-%s" % (str(post.id), len(spans)+1), [ m.start(), m.end(), { "category": featpair, "environment_indicators": [ (m.group(0), -1) ] } ] ] ) occ_i += 1 for span in set([d[1][2]['category'] for d in spans]): self.freq[span] += 1 self.by_topic[topic][span] += 1 if len(self.by_topic[topic].keys()) < 2: return #self.by_side[topic][post.topic_side][span] += 1 tuples = [] for span in spans: start, stop, name = span[1][0], span[1][1], '-'.join(span[1][2]['category']) tuples.append((start,stop,name)) b = Boundaries() b.initializeFromTuples(tuples) if len(b.boundaries) == 0: return self.by_topic[topic][POSTS_KEY] += 1 b.walk(1, max(tuples, key=operator.itemgetter(1))) feature_vector = defaultdict(int) for partition in b.partitions[:-1]: unigrams = map(lambda unigram: self.stemmer.stem(unigram.lower()), re.split(r'\W', post.text[partition[0]:partition[1]])) for unigram in unigrams: feature_vector['{}:{}'.format(partition[2], unigram)] += 1 return feature_vector if __name__ == '__main__': from reportlab.lib import colors from reportlab.lib.pagesizes import letter from reportlab.platypus import SimpleDocTemplate, Table, TableStyle if RUN_FOURFORUMS: doc = SimpleDocTemplate("simple_table4.pdf", pagesize=letter) fourforums = CommitmentCounter() fourforums.start_() OUTPUT = 'output4.out' fd = open(OUTPUT, 'w') data = [] for topic in fourforums.by_topic: items = list(fourforums.by_topic[topic].iteritems()) total = fourforums.by_topic[topic][POSTS_KEY] if total == 0: continue fd.write('{} {}\n'.format(topic, total)) header = [topic, total, ''] data.append(header) for ((key), value) in sorted(items, key=operator.itemgetter(1), reverse=True): if key == POSTS_KEY: continue percent = 100 * value / float(total) fd.write('\t{}\t\t{}\t{}\n'.format(key, value, str(percent)[:4])) if percent > 1: datum = ['', '.'.join(key)[:12], str(percent)[:4]] data.append(datum) data.append(['', '', '']) table = Table(data) table.setStyle(TableStyle([ ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ])) doc.build([table]) fd.close() if RUN_CONVINCEME: ## CONVINCEME doc = SimpleDocTemplate("simple_table.pdf", pagesize=letter) cc = CommitmentCounter() cc.start() items = list(cc.freq.iteritems()) for ((key), value) in sorted(items, key=operator.itemgetter(1), reverse=True): print key, value OUTPUT = 'output.out' fd = open(OUTPUT, 'w') SIDE_OUTPUT = 'side_output.out' fd_side = open(SIDE_OUTPUT, 'w') data = [] for topic in cc.by_topic: items = list(cc.by_topic[topic].iteritems()) total = cc.by_topic[topic][POSTS_KEY] if total == 0: continue fd.write('{} {}\n'.format(topic, total)) side_a, side_b = cc.by_side[topic].keys() fd_side.write('{}({}):\n\t\t{}:\t{}:\n'.format(topic, total, side_a, side_b)) header = [topic, total, '', ''] sides = ['', '', side_a, side_b] data.append(header) data.append(sides) for ((key), value) in sorted(items, key=operator.itemgetter(1), reverse=True): if key == POSTS_KEY: continue fd.write('\t{}\t\t{}\t{}\n'.format(key, value, str(100 * value / float(total))[:4])) side_a_score = 100 * cc.by_side[topic][side_a][key]/ float(total) side_b_score = 100 * cc.by_side[topic][side_b][key]/ float(total) difference = abs(side_a_score - side_b_score) fd_side.write('\t{}:\t{}\t{}\t(diff:{})\n'.format(key, str(side_a_score)[:4], str(side_b_score)[:4], str(difference)[:4])) if side_a_score > 1 and side_b_score > 1: datum = ['', '.'.join(key)[:12], str(side_a_score)[:4], str(side_b_score)[:4]] data.append(datum) data.append(['', '', '', '']) table = Table(data) table.setStyle(TableStyle([ ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ])) doc.build([table]) fd.close() fd_side.close() del fd fd = open('counts', 'w') for topic in cc.environments_topic.keys(): fd.write("***{}\n{}\n".format(topic, cc.environments_topic[topic])) fd.close() <file_sep>#!/usr/bin/python import json import os import operator import sys import pdb import cgi #pdb.set_trace() import svnUpdate sys.path.append('..') sys.path.append('/var/projects/persuasion/code') sys.path.append('/var/projects/utilities/nlp') from collections import defaultdict try: from discussion_with_posts import Dataset, data_root_dir except Exception, e: from grab_data.discussion_with_posts import Dataset, data_root_dir import annotate boundsFile = "bounds_dump" DELETE_QUOTE = False def generate_features(thread, postNum): dataset = Dataset('convinceme',annotation_list=['topic']) directory = "{}/convinceme/output_by_thread".format(data_root_dir) topic = dataset.discussion_annotations[int(thread)]['topic'] discussion = dataset.load_discussion(thread) post = discussion.posts[int(postNum)] try: post.loadPostStruct({"site": "/convinceme", "thread": int(thread)}) text = post.pst.text except: text = post.text.replace('\r', '') try: parent = discussion.posts[int(post.parent_id)] parentText = parent.text parentAuthor = parent.author parentSide = parent.side parentId = "<a href=\"?thread=%s&post=%s\">[see post]</a>" % (thread, post.parent_id) except: parentText = "No parent" parentAuthor = parentSide = parentId = "" author = post.author side = post.side try: tups = tuples[thread][postNum][:-1] #lose the last one because of an odd spurious bound except KeyError: tups = [] for tup in tups: tup[-1] = tup[-1].replace(' ', '_') try: annotatedText = annotate.annotate(text, tups) return produceHTML(author, side, tups, parentId, parentText, parentAuthor, parentSide, annotatedText) except: pdb.set_trace() return "" def produceHTML(author, side, tups, parentId, parentText, parentAuthor, parentSide, annotatedText): colors = ["#1f77b4", "#aec7e8", "#ff7f0e", "#ffbb78", "#2ca02c", "#98df8a", "#d62728", "#ff9896", "#9467bd", "#c5b0d5", "#8c564b", "#c49c94", "#e377c2", "#f7b6d2", "#c7c7c7", "#bcbd22", "#dbdb8d", "#17becf", "#9edae5"] items = defaultdict(list) for x in tups: if x[-1] == "none": continue else: items[x[-1]].append("%d-%d" % (x[0], x[1])) for l in items.values(): l.reverse() colorMap = dict(zip(items.keys(), colors)) colorMap["none"] = "#7f7f7f" colorStyle = "" colorLegend = "" out = colorMap.items() out.sort(key=lambda x:x[0]) for env,col in out: colorStyle += ".%s {background-color: %s}\n" % (env, col) colorLegend += """\t\t<div class="legend %s">%s<br/> %s</div>\n""" % (env, env, '<br/>'.join(items[env])) return """Content-Type: text/html; charset=utf-8 <html> <head> <style type="text/css"> .author {color: red;} .side {color: green;} #text {margin: 5px; border: 1px dotted red; overflow: auto; height: 500px;} #parentText {border: 1px dotted red; overflow: auto; height: 300px;} #parentPost {float: left; width: 300px; margin-left: 50px;} #post {width: 500px; float: left;} span {border: 1px dotted black;} .back {color: gray; border: 1px dotted gray; font-size: x-small;} #legend {margin-left: 50px; width: 200px; text-align: center; float: left;} %s </style> </head> <body> <div id="post"> <a href="getAllPosts.py"><span class="back">&lt;- back to list</span></a> <div class="author">%s</div> <div class="side">%s</div> <div id="text">%s</div> </div> <div id="legend"> %s </div> <div id="parentPost"> <div class="author">%s %s</div> <div class="side">%s</div> <div id="parentText">%s</div> </div> </body> </html>""" % (colorStyle, author, side, annotatedText, colorLegend, parentAuthor, parentId, parentSide, parentText) def loadTuples(): global tuples svnUpdate.update() fin = open(boundsFile, "r") tuples = json.load(fin) if __name__ == '__main__': loadTuples() try: form = cgi.FieldStorage() thread = form.getvalue('thread') post = form.getvalue('post') except: thread = "1448" post = "12544" if not thread: thread = "1448" post = "42560" print generate_features(thread, post) <file_sep>#!/usr/bin/env python import json import xml.etree.ElementTree as ElementTree from collections import defaultdict TOKEN = 'token' SPAN = 'span' def extract(dumpfile='dump.json'): keywords = defaultdict(lambda: defaultdict(list)) for filename in ['abstracts.xml', 'full_papers.xml']: tree = ElementTree.parse(filename) root = tree.getroot() for child in root.iter('cue'): try: _type = child.attrib['type'] keyword = child.text.lower() if ' ' in keyword: slot = keywords[_type][SPAN] if keyword not in slot: slot.append(keyword) else: slot = keywords[_type][TOKEN] if keyword not in slot: slot.append(keyword) except KeyError, e: continue with open(dumpfile, 'wb') as f: json.dump(keywords, f) def main(): extract(dumpfile='spec_neg_keywords.json') if __name__ == '__main__': main() <file_sep>import operator import re import pdb test = """Yes I have seen a dog cover it's own $hit before. You know that thing they do when they tear up the ground with their hind legs after they relieve themselves...that's covering it up. As for the general topic at hand, dogs are better than cats becuase they actually care about their pack, which includes their owners. Cat's will love whomever feeds them/plays with them/picks up after them. Dogs have an attachment greater than their present dillema. What cat has ever fought for something other than itself or its young? Lions and Siberian Tigers included. Dogs do it all the time out of loyalty to the pack.""" def annotate(text, tuples): start = first = operator.itemgetter(0) end = second = operator.itemgetter(1) tag = operator.itemgetter(2) tuples.sort(key=start) tuples.reverse() for t in tuples: tagStr = tag(t).replace(' ', '_') s = '<span class="%s" title="%s">' % (tagStr, tagStr) e = '</span>' text = text[:start(t)] + s + text[start(t):end(t)] + e+ text[end(t):] return text if __name__ == '__main__': tuples = [[452, 476, u'question'], [476, 491, u'none'], [491, 496, u'question'], [496, 512, u'none'], [512, 521, u'question']] ann = annotate(test, tuples) print ann <file_sep>import sisters from nlp import stanford_nlp def get_adv(sent, adv): ##takes in an adverb, finds it in the dependency, pulls out everything ##it governs verb = None for node in sent: if node['dependent'] == adv: nodes = sisters.get_nodes(sent, node['governor'])[1] verb = node['governor'] return (verb, nodes) def get_adv_nodes(sents, adv): ##does get_adv for a set of dependencies, builds a verb and node list nodes = [] verbs = [] for sent in sents: advs = get_adv(sent, adv) nodes.extend(advs[1]) verbs.append(advs[0]) nodes = [node for node in nodes if node['dependent'] != adv] #the verbs and the nodes need to be treated differently, nodes are nodes, verbs are strings return (verbs, nodes) def get_idiom(sent, gov_dep): ##takes a tuple/list consisting of a two-part idiom, the first one should ##be the word that governs the other. this could maybe be changed so it ##could be a list of any size nodes = None for node in sent: ##finds two nodes with the appropriate relation, pulls everything they ##govern, and returns that list if node['dependent'].lower() == gov_dep[1] and node['governor'].lower() == gov_dep[0]: nodes = sisters.get_nodes(sent, node['governor'])[1] return [node for node in nodes if node['dependent'].lower() not in gov_dep] def idiom_nodes(sents, gov_dep): ##does get_idioms for all dependencies in a listS nodes = [] for sent in sents: idioms = get_idiom(sent, gov_dep) nodes.extend(idioms) return nodes if __name__ == '__main__': tag = "really" sentence = "I really like cookies." print sentence pos,meta,dependency = stanford_nlp.get_parses(sentence) nodes = get_adv_nodes(dependency, tag) labels = sisters.label(nodes[1], tag) for verb in nodes[0]: labels.append("really_" + verb) print labels tag = "would_say" sentence = "I would say cookies are delicious." print sentence pos,meta,dependency = stanford_nlp.get_parses(sentence) nodes = idiom_nodes(dependency, ["say", "would"]) labels = sisters.label(nodes, tag) print labels tag = "it_appears" sentence = "It appears cookies are delicious." print sentence pos,meta,dependency = stanford_nlp.get_parses(sentence) nodes = idiom_nodes(dependency, ["appears", "it"]) labels = sisters.label(nodes, tag) print labels
7155131ad55f8b6c653355a194ab9834174a9ce9
[ "Python" ]
16
Python
shsanders/Commitment_features
300136ce90ed5adcc4ea02f1d74be2abaef568f6
546604744460264b91d1cda9d49f4e53111d25bf
refs/heads/master
<repo_name>Gezele14/MemoryManagement<file_sep>/src/app/Cpu.java package APP; import java.util.concurrent.Semaphore; public class Cpu extends Thread{ //Atributos private boolean L2Miss; public boolean powerON; private boolean isFromL2 = false; private boolean BusWr = false; private static Semaphore mutex = new Semaphore(1); private String id = ""; private Core core0; private Core core1; private String memDir = ""; private String Data = ""; private String reqId = ""; private String[] L2Row; private String[][] L2={{"Bloque", "Estado","Dueño", "Dir, Memoria", "Dato"}, {"0","","","","",""}, {"1","","","","",""}, {"2","","","","",""}, {"3","","","","",""}}; //Constructor public Cpu(String msg, String _id, boolean _powerON){ super(msg); this.id = _id; this.powerON = _powerON; this.core0 = new Core("Core0", this.id, "0"); this.core1 = new Core("Core1", this.id, "1"); this.core0.setPowerON(this.powerON); this.core1.setPowerON(this.powerON); } private void l1MisssManager(){ if(core0.isL1Miss()){ this.core0.setCoreState("Buscando el dato de "+id+","+core0.getCoreId()+" en L2"); this.core0.newLog(this.core0.getCoreState()); this.memDir = core0.getMemDir(); if(!this.memDirCheck(this.memDir)){ this.core0.setCoreState("El dato de "+id+","+core0.getCoreId()+" no está en L2"); this.core0.newLog(this.core0.getCoreState()); this.L2Miss = true; this.reqId = core0.getCoreId(); this.core0.setCoreState("Buscando el dato de "+id+","+core0.getCoreId()+" en la otra L2"); this.core0.newLog(this.core0.getCoreState()); while(this.L2Miss){ try{ Thread.sleep(1000); }catch(Exception e){ System.out.println(e.getMessage()); } } if(this.isFromL2){ this.core0.setCoreState("Dato de "+id+","+core0.getCoreId()+" traido desde la otra L2"); this.core0.newLog(this.core0.getCoreState()); this.core0.setData(this.getL2Data(this.memDir)); }else{ this.core0.setCoreState("Dato de "+id+","+core0.getCoreId()+" traido desde la memoria"); this.core0.newLog(this.core0.getCoreState()); try{ Thread.sleep(500); }catch(Exception e){ System.out.println(e.getMessage()); } this.core0.setCoreState("Escribiendo el dato de "+id+","+core0.getCoreId()+" en L2"); this.core0.newLog(this.core0.getCoreState()); this.writeL2(this.L2Row); this.core0.setData(this.getL2Data(this.memDir)); } }else{ this.core0.setData(this.getL2Data(this.memDir)); } this.core0.setL1Miss(false); }else if(core1.isL1Miss()){ this.core1.setCoreState("Buscando el dato de "+id+","+core0.getCoreId()+" en L2"); this.core1.newLog(this.core0.getCoreState()); this.memDir = core1.getMemDir(); if(!this.memDirCheck(this.memDir)){ this.core0.setCoreState("El dato de "+id+","+core0.getCoreId()+" no está en L2"); this.core0.newLog(this.core0.getCoreState()); this.L2Miss = true; this.reqId = core1.getCoreId(); this.core1.setCoreState("Buscando el dato de "+id+","+core0.getCoreId()+" en la otra L2"); this.core1.newLog(this.core0.getCoreState()); while(this.L2Miss){ try{ Thread.sleep(1000); }catch(Exception e){ System.out.println(e.getMessage()); } } if(this.isFromL2){ this.core1.setCoreState("Dato de "+id+","+core0.getCoreId()+" traido desde la otra L2"); this.core1.newLog(this.core0.getCoreState()); this.core1.setData(this.getL2Data(this.memDir)); }else{ this.core1.setCoreState("Dato de "+id+","+core0.getCoreId()+" traido desde la memoria"); this.core1.newLog(this.core0.getCoreState()); try{ Thread.sleep(500); }catch(Exception e){ System.out.println(e.getMessage()); } this.core1.setCoreState("Escribiendo el dato de "+id+","+core0.getCoreId()+" en L2"); this.core1.newLog(this.core0.getCoreState()); this.writeL2(this.L2Row); this.core1.setData(this.getL2Data(this.memDir)); } }else{ this.core1.setData(this.getL2Data(this.memDir)); } this.core1.setL1Miss(false); } } private void busWrManager(){ if(this.core0.isBusWr()){ this.core0.setCoreState("Escribiendo el dato de "+id+","+core0.getCoreId()+" en L2"); this.core0.newLog(this.core0.getCoreState()); this.writeCache(core0.getMemDir(), core0.getData(), core0.getCoreId()); core1.invalidCache(core0.getMemDir()); this.memDir = core0.getMemDir(); this.Data = core0.getData(); this.BusWr = true; this.core0.setCoreState("Escribiendo el dato de "+id+","+core0.getCoreId()+" en Memoria"); this.core0.newLog(this.core0.getCoreState()); while(this.BusWr){ try{ Thread.sleep(1000); }catch(Exception e){ System.out.println(e.getMessage()); } } this.core0.setBusWr(false); }else if(this.core1.isBusWr()){ this.core1.setCoreState("Escribiendo el dato de "+id+","+core0.getCoreId()+" en L2"); this.core1.newLog(this.core0.getCoreState()); this.writeCache(core1.getMemDir(), core1.getData(), core1.getCoreId()); core0.invalidCache(core1.getMemDir()); this.memDir = core1.getMemDir(); this.Data = core1.getData(); this.BusWr = true; this.core1.setCoreState("Escribiendo el dato de "+id+","+core0.getCoreId()+" en memoria"); this.core1.newLog(this.core0.getCoreState()); while(this.BusWr){ try{ Thread.sleep(1000); }catch(Exception e){ System.out.println(e.getMessage()); } } this.core1.setBusWr(false); } } private void writeCache(String dir, String Data, String coreId){ String bloque = Integer.toString(Integer.parseInt(dir,2)%4); for (int i = 1; i < this.L2.length; i++) { if(bloque.equals(this.L2[i][0])){ this.L2[i][1] = "DM"; this.L2[i][2] = this.id+","+coreId; this.L2[i][3] = dir; this.L2[i][4] = Data; break; } } } private void writeL2(String[] row){ for (int i = 1; i < this.L2.length; i++) { if(row[0].equals(L2[i][0])){ this.L2[i] = row; } } } public void invalidCache(String dir){ for (int i = 1; i < this.L2.length; i++) { if(dir.equals(this.L2[i][3])){ this.L2[i][1] = "DI"; break; } } this.core0.invalidCache(dir); this.core1.invalidCache(dir); } public String getDataDir(String dir){ String Temp = ""; for (int i = 1; i < L2.length; i++) { if(dir.equals(this.L2[i][3])){ Temp = this.L2[i][4]; } } return Temp; } public String[] getRow(String memdir) { for (int i = 1; i < L2.length; i++) { if(memdir.equals(this.L2[i][3])){ this.L2Row = this.L2[i]; } } return this.L2Row; } private String getL2Data(String dir){ for (int i = 1; i < this.L2.length; i++) { if(dir.equals(this.L2[i][3])){ this.Data = this.L2[i][4]; return Data; } } return this.Data; } public boolean memDirCheck(String dir){ for (int i = 1; i < this.L2.length; i++) { if(dir.equals(this.L2[i][3]) && !this.L2[i][1].equals("DI")){ this.Data = this.L2[i][4]; return true; } } return false; } public void setL2Value(int pos, String dir, String value){ for (int i = 1; i < this.L2.length; i++) { if(dir.equals(this.L2[i][3])){ this.L2[i][pos] += value; break; } } } public String getL2Value(int pos, String dir){ String value = ""; for (int i = 1; i < this.L2.length; i++) { if(dir.equals(this.L2[i][3])){ value = this.L2[i][pos]; } } return value; } //Metodos public void run(){ this.core0.start(); this.core1.start(); while(this.powerON){ try { mutex.acquire(); } catch (Exception e) { System.out.println(e.getMessage()); } this.busWrManager(); this.l1MisssManager(); mutex.release(); } } public Core getCore0() { return core0; } public Core getCore1() { return core1; } public boolean isL2Miss() { return L2Miss; } public void setL2Miss(boolean l2Miss) { L2Miss = l2Miss; } public boolean isPowerON() { return powerON; } public void setPowerON(boolean powerON) { this.powerON = powerON; } public String getMemDir() { return memDir; } public void setMemDir(String memDir) { this.memDir = memDir; } public String[][] getL2() { return L2; } public void setL2(String[][] l2) { L2 = l2; } public String getData() { return Data; } public void setData(String data) { Data = data; } public String getCpuId(){ return this.id; } public String[] getL2Row() { return L2Row; } public void setL2Row(String[] l2Row) { L2Row = l2Row; } public String getReqId() { return reqId; } public boolean isFromL2() { return isFromL2; } public void setFromL2(boolean isFromL2) { this.isFromL2 = isFromL2; } public boolean isBusWr() { return BusWr; } public void setBusWr(boolean busWr) { BusWr = busWr; } }<file_sep>/src/app/App.java package APP; import GUI.Main; import javafx.application.Application; public class App{ public static void main(final String[] args) throws Exception { Application.launch(Main.class, args); } }
e54fe855b5b5ed40848f4b0916e341a9778fbeec
[ "Java" ]
2
Java
Gezele14/MemoryManagement
e0fc3684a32eb4d797202245df9453d9e9b16213
19ae2ac96a8aa1610ac9f149738021bbf2666085
refs/heads/main
<file_sep>const cache = {} export default function useData(key, fetcher) { if (!cache[key]) { let data let promise cache[key] = () => { if (data !== undefined) return data if (!promise) promise = fetcher().then((r) => (data = r)) throw promise } } return cache[key]() }<file_sep>import { match } from "path-to-regexp" const useRouter = pattern => async ({ req }) => { const fn = match(pattern, { decode: decodeURIComponent }); const result = fn(req.url) console.log('result', result) if (result === false) return { props: { initialRouter: { route: req.url } } } return { props: { initialRouter: result } } } export default useRouter
44b27b253bec3176da7b8f1ae9f1e45a75b7f654
[ "TypeScript" ]
2
TypeScript
revskill10/rsc-demo
40e8084b8ad424238625fb1f79bc6a3cbae1fe04
79325085f3033e793d7607629748799a28627672
refs/heads/master
<file_sep>//##########################blink // var five = require("johnny-five"); // var board = new five.Board(); // board.on("ready", function() { // var led = new five.Led(13); // this.repl.inject({ // led: led // }); // led.blink(); // }); //####################blink timer // var five = require("johnny-five"); // var board = new five.Board(); // board.on("ready", function() { // var led = new five.Led(13); // led.blink(500); // }); //##################blink pulse // var five = require("johnny-five"); // var board = new five.Board(); // board.on("ready", function() { // var led = new five.Led(11); // led.pulse(); // this.wait(10000, function() { // led.stop().off(); // }); // }); //#################pulse animation // var five = require("johnny-five"); // var board = new five.Board(); // board.on("ready", function() { // var led = new five.Led(11); // led.pulse({ // easing: "linear", // duration: 3000, // cuePoints: [0, 0.2, 0.4, 0.6, 0.8, 1], // keyFrames: [0, 10, 0, 50, 0, 255], // onstop: function() { // console.log("Animation stopped"); // } // }); // this.wait(12000, function() { // led.stop().off(); // }); // }); //##################led fedin // var five = require("johnny-five"); // var board = new five.Board(); // board.on("ready", function() { // var led = new five.Led(11); // led.fadeIn(); // this.wait(5000, function() { // led.fadeOut(); // }); // }); //##################led demo sequence // var five = require("johnny-five"); // var board = new five.Board(); // var led; // var loop = true; // var demoSequence = [{ // method: "pulse", // args: [1000], // duration: 5000 // }, { // method: "strobe", // args: [500], // duration: 3000 // }, { // method: "fadeIn", // args: [ // 2000, // function() { // console.log("fadeIn complete!"); // } // ], // duration: 2500 // }, { // method: "fadeOut", // args: [ // 5000, // function() { // console.log("fadeOut complete!"); // } // ], // duration: 5500 // }, { // method: "brightness", // args: [10], // duration: 3000 // }, { // method: "off" // }]; // // Execute a method in the demo sequence // function execute(step) { // // Grab everything we need for this step // var method = demoSequence[step].method; // var args = demoSequence[step].args; // var duration = demoSequence[step].duration || 3000; // // Just print out what we're executing // console.log("led." + method + "(" + (args ? args.join() : "") + ")"); // // Make the actual call to the LED // five.Led.prototype[method].apply(led, args); // // Increment the step // step++; // // If we're at the end, start over (loop==true) or exit // if (step === demoSequence.length) { // if (loop) { // step = 0; // } else { // // We're done! // process.exit(0); // } // } // // Recursively call the next step after specified duration // board.wait(duration, function() { // execute(step); // }); // } // board.on("ready", function() { // // Defaults to pin 11 (must be PWM) // led = new five.Led(process.argv[2] || 11); // // Kick off the first step // execute(0); // }); //##################led array var five = require("johnny-five"); var board = new five.Board(); board.on("ready", function() { var array = new five.Leds([3, 5, 6]); array.pulse(); });
38d8a71675dd7b4536579455b6e66f4592d4d08d
[ "JavaScript" ]
1
JavaScript
BaliJS/Iot
64413d3cd6b9b51b42a966cc819adb12c09fd6c5
0e5a0e5e4e9a5eb6b32fd40d871349513328208d
refs/heads/master
<file_sep>name = input('請問你的名字是:') h=input(name+',請輸入你的身高:') w=input('請輸入你的體重:') print(name,'你的身高是',h,',你的體重是',w)<file_sep>c = input('請輸入攝氏(C)溫度 :') c = float(c) f = c * 9 / 5 + 32 print('華氏(F)溫度為 : ', f) print('ok')
00d2da380885af2d669896b0ce4bc667ff0dfc8a
[ "Python" ]
2
Python
chlin61/c_to_f
e374511d2b42a9f9e2e32b5ab43e5ed03e57101c
bf07acb0c2297689fc92216704e028e0de4120cd
refs/heads/master
<file_sep>#include <stdio.h> int main() { int m1, m2, minMultiple; printf("Enter two positive integers: "); scanf("%d %d", &m1, &m2); minMultiple = (m1>m2) ? m1 : m2; while(1) { if( minMultiple%m1==0 && minMultiple%m2==0 ) { printf("The LCM of %d and %d is %d.", m1, m2,minMultiple); break; } ++minMultiple; } return 0; }
19eacad8fe59e9ffa5f34df91b13c17fd46423fd
[ "C" ]
1
C
sgandt/gpkumar
594f3c77a9ac1a9fa213f7e2404eb95215348af8
ed0b04a14febbadadbcb4eb2ae0630b6ae14097a
refs/heads/master
<file_sep>import java.util.Arrays; /** * 选择性排序 * 时间复杂度 n(n+1)/2 =O(n^2) */ public class SelectiveSort { public static void main(String[] args) { int[] arr = {3,1,4,23,9,0,12,29,5,2,6,8,14}; for(int i=0;i<arr.length;i++){ int tmp = arr[i]; int min_index = i; for(int j=i;j<arr.length;j++){ if(tmp>arr[j]){ tmp = arr[j]; min_index = j; } } arr[min_index] = arr[i]; arr[i] = tmp; } System.out.println("SelectiveSort:"+Arrays.toString(arr)); } } <file_sep># LearningAlgorithm 算法学习 冒泡排序 BubbleSort 选择排序 SelectiveSort 插入排序 InsertionSort <file_sep>import java.util.Arrays; /** * 插入排序 * n(n-1)/2 = O(n^2) */ public class InsertionSort { public static void main(String[] args) { int[] arr = {3,12,1,9,2,39,0,8,6,13,15,4}; for(int i=0;i<arr.length;i++){ for(int j=0; j<i+1;j++){ if(arr[i] < arr[j] ){ int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } } } System.out.println("InsertionSort:"+ Arrays.toString(arr)); } }
714a4b5089a6e5294162e41b3efe9b7b8c5863ef
[ "Markdown", "Java" ]
3
Java
awarmisland/LearningAlgorithm
530a14249e6e83485e6ea5e658f4e208be30857e
5bf7b80c0bccfb0c12c304a97e410a4ddb6477de
refs/heads/master
<file_sep>rootProject.name = 'Boggle' <file_sep>rootProject.name = 'BurrowsWheeler' <file_sep>import edu.princeton.cs.algs4.FlowEdge; import edu.princeton.cs.algs4.FlowNetwork; import edu.princeton.cs.algs4.FordFulkerson; import edu.princeton.cs.algs4.In; import java.util.*; /** * Created by <NAME> on 11/12/17. */ public class BaseballElimination { private final String[] teams; private final Map<String, Integer> teamId; private final Map<String, List<String>> R; private final int[] w; private final int[] l; private final int[] r; private final int[][] g; public BaseballElimination(String filename) { In in = new In(filename); int n = in.readInt(); teams = new String[n]; teamId = new HashMap<>(); R = new HashMap<>(); w = new int[n]; l = new int[n]; r = new int[n]; g = new int[n][n]; for (int i = 0; i < n; i++) { if (!in.hasNextLine()) { throw new IllegalArgumentException("invalid input"); } teams[i] = in.readString(); teamId.put(teams[i], i); w[i] = in.readInt(); l[i] = in.readInt(); r[i] = in.readInt(); for (int j = 0; j < n; j++) { g[i][j] = in.readInt(); } } } public int numberOfTeams() { return teams.length; } public Iterable<String> teams() { return Arrays.asList(teams); } public int wins(String team) { checkTeam(team); return w[teamId.get(team)]; } public int losses(String team) { checkTeam(team); return l[teamId.get(team)]; } public int remaining(String team) { checkTeam(team); return r[teamId.get(team)]; } public int against(String team1, String team2) { checkTeam(team1); checkTeam(team2); return g[teamId.get(team1)][teamId.get(team2)]; } public boolean isEliminated(String team) { checkTeam(team); if (!R.containsKey(team)) { R.put(team, eliminate(team)); } return R.get(team).size() != 0; } public Iterable<String> certificateOfElimination(String team) { checkTeam(team); if (!R.containsKey(team)) { R.put(team, eliminate(team)); } return R.get(team); } private List<String> eliminate(String team) { // trivial int x = teamId.get(team); for (int i = 0; i < teams.length; i++) { if (x == i) continue; if (w[x] + r[x] < w[i]) { return Collections.singletonList(teams[i]); } } // nontrivial // s: 0 // i-j: 1 -- (n-2)! // i: (n-2)!+1 -- (n-2)!+(n-1) int n = teams.length; if (n <= 2) return Collections.emptyList(); int sum = sum(n - 2); int t = sum + n - 1 + 1; FlowNetwork fn = new FlowNetwork(1 + t); int[] teamVIdx = new int[n]; for (int i = 0; i < n; i++) { if (i != x) { int idx = i <= x ? i : i - 1; teamVIdx[i] = sum + idx + 1; fn.addEdge(new FlowEdge(teamVIdx[i], t, w[x] + r[x] - w[i])); } } int idx = 1; for (int i = 0; i < n - 1; i++) { if (i == x) continue; for (int j = i + 1; j < n; j++) { if (j == x) continue; fn.addEdge(new FlowEdge(0, idx, g[i][j])); fn.addEdge(new FlowEdge(idx, teamVIdx[i], Double.POSITIVE_INFINITY)); fn.addEdge(new FlowEdge(idx, teamVIdx[j], Double.POSITIVE_INFINITY)); idx++; } } FordFulkerson ff = new FordFulkerson(fn, 0, t); idx = 1; Set<String> retR = new HashSet<>(); for (int i = 0; i < n - 1; i++) { if (i == x) continue; for (int j = i + 1; j < n; j++) { if (j == x) continue; if (ff.inCut(idx)) { retR.add(teams[i]); retR.add(teams[j]); } idx++; } } return new ArrayList<>(retR); } private void checkTeam(String t) { if (t == null || !teamId.containsKey(t)) throw new IllegalArgumentException("invalid team input"); } private int sum(int n) { return (1 + n) * n / 2; } } <file_sep># AlgorithmII Assignments for [Algorithms Part II](https://www.coursera.org/learn/algorithms-part2/) <file_sep>rootProject.name = 'Seam' <file_sep>import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.util.Arrays; import java.util.HashSet; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * Created by <NAME> on 11/12/17. */ public class TrivialBaseballEliminationTest { BaseballElimination division; @BeforeClass public static void init() { System.out.println("Testing trivial BaseballElimination..."); } @Before public void initBaseballElimination() { division = new BaseballElimination("src/test/resources/teams4.txt"); } @Test public void evaluateTeams() { assertEquals("should have 4 teams", division.numberOfTeams(), 4); assertEquals("should match team names", division.teams(), Arrays.asList("Atlanta", "Philadelphia", "New_York", "Montreal")); } @Test public void evaluateEliminated() { assertFalse("Atlanta should not be eliminated", division.isEliminated("Atlanta")); assertTrue("Philadelphia should be eliminated", division.isEliminated("Philadelphia")); assertFalse("New_York should not be eliminated", division.isEliminated("New_York")); assertTrue("Montreal should be eliminated", division.isEliminated("Montreal")); } @Test public void evaluateCertificate() { HashSet<String> s = new HashSet<String>(); for (String str : division.certificateOfElimination("Philadelphia")) { s.add(str); } assertEquals("Philadelphia is eliminated by the subset R = { Atlanta New_York }", s, new HashSet<>(Arrays.asList("Atlanta", "New_York"))); assertEquals("Montreal is eliminated by the subset R = { Atlanta }", division.certificateOfElimination("Montreal"), Arrays.asList("Atlanta")); } } <file_sep>rootProject.name = 'BaseballElimination' <file_sep>import edu.princeton.cs.algs4.Picture; import java.util.Arrays; import java.util.HashMap; import java.util.Stack; /** * Created by <NAME> on 11/5/17. */ public class SeamCarver { private Element[][] pic; private int w; private int h; // create a seam carver object based on the given picture public SeamCarver(Picture picture) { if (picture == null) { throw new IllegalArgumentException("picture is null!"); } w = picture.width(); h = picture.height(); pic = new Element[w][h]; for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { pic[i][j] = new Element(picture.get(i, j)); } } for (int i = 1; i < w - 1; i++) { for (int j = 1; j < h - 1; j++) { calculate(i, j); } } } // current picture public Picture picture() { Picture picture; picture = new Picture(w, h); for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { picture.set(i, j, pic[i][j].getColor()); } } return picture; } // width of current picture public int width() { return w; } // height of current picture public int height() { return h; } // energy of pixel at column x and row y public double energy(int x, int y) { if (x < 0 || x >= w || y < 0 || y >= h) { throw new IllegalArgumentException("row and col illegal!"); } if (x == 0 || x == w - 1 || y == 0 || y == h - 1) { return 1000; } return pic[x][y].getEnergy(); } // sequence of indices for horizontal seam public int[] findHorizontalSeam() { if (h <= 2) { int[] ret = new int[w]; Arrays.fill(ret, 0); return ret; } HashMap<Integer, Double> idxSum = new HashMap<>(); HashMap<Integer, Stack<Integer>> idxPath = new HashMap<>(); for (int i = 1; i < h - 1; i++) { idxPath.put(i, new Stack<>()); idxSum.put(i, 0.0); } double defaultSum = 1000000 * w; for (int i = w - 1; i > 0; i--) { HashMap<Integer, Stack<Integer>> newPaths = new HashMap<>(); HashMap<Integer, Double> newSums = new HashMap<>(); for (int j = 1; j < h - 1; j++) { int minIdx = j; double minE2 = idxSum.get(j); if (idxSum.getOrDefault(j - 1, defaultSum) < minE2) { minE2 = idxSum.getOrDefault(j - 1, defaultSum); minIdx = j - 1; } if (idxSum.getOrDefault(j + 1, defaultSum) < minE2) { minE2 = idxSum.getOrDefault(j + 1, defaultSum); minIdx = j + 1; } newSums.put(j, pic[i][j].getEnergy() + minE2); Stack<Integer> newPath = (Stack<Integer>) idxPath.get(minIdx).clone(); newPath.push(j); newPaths.put(j, newPath); } idxPath = newPaths; idxSum = newSums; } int minIdx = 1; for (int i = 2; i < h; i++) { if (idxSum.getOrDefault(i, defaultSum) < idxSum.get(minIdx)) { minIdx = i; } } Stack<Integer> path = idxPath.get(minIdx); path.push(minIdx); int[] pathArray = new int[path.size()]; int i = 0; while (!path.empty()) { pathArray[i++] = path.pop(); } return pathArray; } // sequence of indices for vertical seam public int[] findVerticalSeam() { if (w <= 2) { int[] ret = new int[h]; Arrays.fill(ret, 0); return ret; } HashMap<Integer, Double> idxSum = new HashMap<>(); HashMap<Integer, Stack<Integer>> idxPath = new HashMap<>(); for (int i = 1; i < w - 1; i++) { idxPath.put(i, new Stack<>()); idxSum.put(i, 0.0); } double defaultSum = 1000000 * h; for (int j = h - 1; j > 0; j--) { HashMap<Integer, Stack<Integer>> newPaths = new HashMap<>(); HashMap<Integer, Double> newSums = new HashMap<>(); for (int i = 1; i < w - 1; i++) { int minIdx = i; double minE2 = idxSum.get(i); if (idxSum.getOrDefault(i - 1, defaultSum) < minE2) { minE2 = idxSum.getOrDefault(i - 1, defaultSum); minIdx = i - 1; } if (idxSum.getOrDefault(i + 1, defaultSum) < minE2) { minE2 = idxSum.getOrDefault(i + 1, defaultSum); minIdx = i + 1; } newSums.put(i, pic[i][j].getEnergy() + minE2); Stack<Integer> newPath = (Stack<Integer>) idxPath.get(minIdx).clone(); newPath.push(i); newPaths.put(i, newPath); } idxPath = newPaths; idxSum = newSums; } int minIdx = 1; for (int i = 2; i < w; i++) { if (idxSum.getOrDefault(i, defaultSum) < idxSum.get(minIdx)) { minIdx = i; } } Stack<Integer> path = idxPath.get(minIdx); path.push(minIdx); int[] pathArray = new int[path.size()]; int i = 0; while (!path.empty()) { pathArray[i++] = path.pop(); } return pathArray; } // remove horizontal seam from current picture public void removeHorizontalSeam(int[] seam) { if (seam == null) throw new IllegalArgumentException("seam is null"); if (seam.length != w) throw new IllegalArgumentException("seam wrong length"); if (h <= 1) throw new IllegalArgumentException("image height " + h + " invalid"); int prev = seam[0]; for (int i = 0; i < w; i++) { int s = seam[i]; if (s < 0 || s >= h || Math.abs(s - prev) > 1) { throw new IllegalArgumentException("invalid seam"); } prev = s; if (s < h - 1) { System.arraycopy(pic[i], s + 1, pic[i], s, h - s - 1); } } h--; for (int i = 1; i < w - 1; i++) { int s = seam[i]; if (s > 1) calculate(i, s - 1); if (s < h - 2) calculate(i, s + 1); if (s > 0 && s < h - 1) calculate(i, s); } } // remove vertical seam from current picture public void removeVerticalSeam(int[] seam) { if (seam == null) throw new IllegalArgumentException("seam is null"); if (seam.length != h) throw new IllegalArgumentException("seam wrong length"); if (w <= 1) throw new IllegalArgumentException("image width " + w + " invalid"); int prev = seam[0]; for (int j = 0; j < h; j++) { int s = seam[j]; if (s < 0 || s >= w || Math.abs(s - prev) > 1) { throw new IllegalArgumentException("invalid seam"); } prev = s; for (int i = s + 1; i < w; i++) { pic[i - 1][j] = pic[i][j]; } } w--; for (int j = 1; j < h - 1; j++) { int s = seam[j]; if (s > 1) calculate(s - 1, j); if (s < w - 2) calculate(s + 1, j); if (s > 0 && s < w - 1) calculate(s, j); } } private void calculate(int i, int j) { pic[i][j].calculateEnergy2( pic[i + 1][j].getColor(), pic[i - 1][j].getColor(), pic[i][j + 1].getColor(), pic[i][j - 1].getColor()); } } <file_sep>rootProject.name = 'WordNet' <file_sep>import edu.princeton.cs.algs4.Digraph; import edu.princeton.cs.algs4.In; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; /** * Created by <NAME> on 10/29/17. */ public class SAPTest { private SAP sap; @Rule public ExpectedException thrown = ExpectedException.none(); @BeforeClass public static void init() { System.out.println("Testing SAP..."); } @Before public void initializeSAP() { In in = new In("src/test/resources/wordnet/digraph1.txt"); Digraph G = new Digraph(in); sap = new SAP(G); } @Test public void evaluateLength() { assertEquals("3, 11 should have length 4", 4, sap.length(3, 11)); assertEquals("9, 12 should have length 3", 3, sap.length(9, 12)); assertEquals("7, 2 should have length 4", 4, sap.length(7, 2)); } @Test public void shoudlThrow() { thrown.expect(IllegalArgumentException.class); List<Integer> v = Arrays.asList(-1, 2, 7); List<Integer> w = Arrays.asList(1, 4, 6, 10, 11); sap.length(v, w); } @Test public void evaluateAncestor() { assertEquals("3, 11 should have ancestor 1", 1, sap.ancestor(3, 11)); assertEquals("9, 12 should have ancestor 5", 5, sap.ancestor(9, 12)); assertEquals("7, 2 should have ancestor 0", 0, sap.ancestor(7, 2)); } } <file_sep>import edu.princeton.cs.algs4.BreadthFirstDirectedPaths; import edu.princeton.cs.algs4.Digraph; /** * Created by <NAME> on 10/28/17. */ public class SAP { private final Digraph digraph; // constructor takes a digraph (not necessarily a DAG) public SAP(Digraph G) { if (G == null) { throw new IllegalArgumentException("Digraph input is null."); } digraph = new Digraph(G); } // length of shortest ancestral path between v and w; -1 if no such path public int length(int v, int w) { BreadthFirstDirectedPaths bfsv = new BreadthFirstDirectedPaths(digraph, v); BreadthFirstDirectedPaths bfsw = new BreadthFirstDirectedPaths(digraph, w); return findLength(bfsv, bfsw); } // a common ancestor of v and w that participates in a shortest ancestral path; -1 if no such path public int ancestor(int v, int w) { BreadthFirstDirectedPaths bfsv = new BreadthFirstDirectedPaths(digraph, v); BreadthFirstDirectedPaths bfsw = new BreadthFirstDirectedPaths(digraph, w); return findAncestor(bfsv, bfsw); } // length of shortest ancestral path between any vertex in v and any vertex in w; -1 if no such path public int length(Iterable<Integer> v, Iterable<Integer> w) { BreadthFirstDirectedPaths bfsv = new BreadthFirstDirectedPaths(digraph, v); BreadthFirstDirectedPaths bfsw = new BreadthFirstDirectedPaths(digraph, w); return findLength(bfsv, bfsw); } // a common ancestor that participates in shortest ancestral path; -1 if no such path public int ancestor(Iterable<Integer> v, Iterable<Integer> w) { BreadthFirstDirectedPaths bfsv = new BreadthFirstDirectedPaths(digraph, v); BreadthFirstDirectedPaths bfsw = new BreadthFirstDirectedPaths(digraph, w); return findAncestor(bfsv, bfsw); } private int findLength(BreadthFirstDirectedPaths bfsv, BreadthFirstDirectedPaths bfsw) { int shortest = Integer.MAX_VALUE; for (int i = 0; i < digraph.V(); i++) { int vd = bfsv.distTo(i); if (vd >= shortest) continue; int wd = bfsw.distTo(i); if (wd >= shortest) continue; shortest = Math.min(shortest, vd + wd); } return shortest == Integer.MAX_VALUE ? -1 : shortest; } private int findAncestor(BreadthFirstDirectedPaths bfsv, BreadthFirstDirectedPaths bfsw) { int shortest = Integer.MAX_VALUE; int ancestor = -1; for (int i = 0; i < digraph.V(); i++) { int vd = bfsv.distTo(i); if (vd >= shortest) continue; int wd = bfsw.distTo(i); if (wd >= shortest) continue; if (vd + wd < shortest) { shortest = vd + wd; ancestor = i; } } return ancestor; } } <file_sep>import java.util.Arrays; /** * Created by <NAME> on 10/28/17. */ public class Outcast { private final WordNet wordNet; public Outcast(WordNet net) { wordNet = net; } public String outcast(String[] nouns) { int maxDist = Integer.MIN_VALUE; int maxIdx = -1; for (int i = 0; i < nouns.length; i++) { if (!wordNet.isNoun(nouns[i])) { throw new IllegalArgumentException("input noun invalid."); } } for (int i = 0; i < nouns.length; i++) { String noun = nouns[i]; int dist = Arrays.stream(nouns).mapToInt(n -> wordNet.distance(n, noun)).sum(); if (dist > maxDist) { maxDist = dist; maxIdx = i; } } return nouns[maxIdx]; } }
b3dd6a6626e3e6d22a4c463bb7e8afd1e9a5dbed
[ "Markdown", "Java", "Gradle" ]
12
Gradle
xg-wang/AlgorithmII
4b48b713611525093abcc4a1855647e2786813ad
1d8180c626e312cfd0044bb3a19c9add7b118573
refs/heads/master
<repo_name>kaizenyatesh/orderapi<file_sep>/src/tests/Feature/IntegrationTest.php <?php namespace Tests\Unit; use Tests\TestCase; use Illuminate\Foundation\Testing\RefreshDatabase; class IntegrationTest extends TestCase { use RefreshDatabase; /** * A basic API tests. * * @return void */ /** * Function to test if orders are listed as expected. * @return void */ public function test_orders_can_be_listed() { echo "\n ### Test : Testing Order List end-point. \n "; $this->createOrder(); $response = $this->get('orders?page=1&limit=20')->assertStatus(200); echo "\n Test successful : Orders listed as expected. \n "; } // Testing Validation of Longitude of Location Co-Ordinates// /** * Function to test if origin has only one element. * @return void */ public function test_origin_has_only_one_elements() { echo "\n ### Test : Testing if origin location has less than 2 co-ordinates. \n "; $data = [ 'error' => 'The origin must have at least 2 items.' ]; $response = $this->post('orders', $this->originHasOnlyOneElement())->assertStatus(422)->assertJson($data); echo "\n Test successful : If origin location has less than 2 co-ordinates, it gives a suitalbe error message - The origin must have at least 2 items. \n "; } /** * Function to test if origin has more than 2 element. * @return void */ public function test_origin_has_more_than_two_elements() { echo "\n ### Test : Testing if origin location has more than 2 co-ordinates. \n "; $data = [ 'error' => 'The origin may not have more than 2 items.' ]; $response = $this->post('orders', $this->originHasMoreThanTwoElement())->assertStatus(422)->assertJson($data); echo "\n Test successful : If origin location has more than 2 co-ordinates, it gives a suitalbe error message - The origin may not have more than 2 items. \n "; } /** * Function to test if origin is an array. * @return void */ public function test_origin_is_not_an_array() { echo "\n ### Test : Testing if origin co-ordinates in request is an array. \n "; $data = [ 'error' => 'The origin must be an array.' ]; $response = $this->post('orders', $this->originIsNotAnArray())->assertStatus(422)->assertJson($data); echo "\n Test successful : If origin co-ordiantes in request is not an array, it gives a suitalbe error message - The origin must be an array. \n "; } /** * Function to test if origin don't have a valid latitude. * @return void */ public function test_origin_dont_have_valid_latitude() { echo "\n ### Test : Testing if origin co-ordinates in request has valid latitude. \n "; $data = [ 'error' => 'The origin.0 format is invalid.' ]; $response = $this->post('orders', $this->originDontHaveValidLatitude())->assertStatus(422)->assertJson($data); echo "\n Test successful : If origin co-ordinates in request has invalid latitude, it gives a suitalbe error message - The origin.0 format is invalid. \n "; } /** * Function to test if origin don't have a valid longitude. * @return void */ public function test_origin_dont_have_valid_longitude() { echo "\n ### Test :Testing if origin co-ordinates in request has valid longitude. \n "; $data = [ 'error' => 'The origin.1 format is invalid.' ]; $response = $this->post('orders', $this->originDontHaveValidLongitude())->assertStatus(422)->assertJson($data); echo "\n Test successful : If origin co-ordinates in request has invalid longitude, it gives a suitalbe error message- The origin.1 format is invalid. \n "; } // Testing Validation of Longitude of Location Co-Ordinates// /** * Function to test if destination has only one element. * @return void */ public function test_destination_has_only_one_elements() { echo "\n ### Test : Testing if destination co-ordinates in request has less than 2 co-ordinates. \n "; $data = [ 'error' => 'The destination must have at least 2 items.' ]; $response = $this->post('orders', $this->destinationHasOnlyOneElement())->assertStatus(422)->assertJson($data); echo "\n Test successful : If destination co-ordinates in request has less than 2 co-ordinates, it gives a suitalbe error message - The destination must have at least 2 items. \n "; } /** * Function to test if destination has more than two elements. * @return void */ public function test_destination_has_more_than_two_elements() { echo "\n ### Test : Testing if destination co-ordinates in request has more than 2 co-ordinates. \n "; $data = [ 'error' => 'The destination may not have more than 2 items.' ]; $response = $this->post('orders', $this->destinationHasMoreThanTwoElement())->assertStatus(422)->assertJson($data); echo "\n Test successful : If destination co-ordinates in request has more than 2 co-ordinates, it gives a suitalbe error message - The destination may not have more than 2 items. \n "; } /** * Function to test if destination is not an array. * @return void */ public function test_destination_is_not_an_array() { echo "\n ### Test : Testing if destination co-ordinates in request is an array. \n "; $data = [ 'error' => 'The destination must be an array.' ]; $response = $this->post('orders', $this->destinationIsNotAnArray())->assertStatus(422)->assertJson($data); echo "\n Test successful : If destination co-ordiantes in request is not an array, it gives a suitalbe error message - The destination must be an array. \n "; } /** * Function to test if destination don't have valid latitude. * @return void */ public function test_destination_dont_have_valid_latitude() { echo "\n ### Test : Testing if destination co-ordinates in request has valid latitude. \n "; $data = [ 'error' => 'The destination.0 format is invalid.' ]; $response = $this->post('orders', $this->destinationDontHaveValidLatitude())->assertStatus(422)->assertJson($data); echo "\n Test successful : If destination co-ordinates in request has invalid latitude, it gives a suitalbe error message - The destination.0 format is invalid. \n "; } /** * Function to test if destination don't have valid longitude. * @return void */ public function test_destination_dont_have_valid_longitude() { echo "\n ### Test : Testing if destination co-ordinates in request has valid longitude. \n "; $data = [ 'error' => 'The destination.1 format is invalid.' ]; $response = $this->post('orders', $this->destinationDontHaveValidLongitude())->assertStatus(422)->assertJson($data); echo "\n Test successful : If destination co-ordinates in request has invalid longitude, it gives a suitalbe error message - The destination.1 format is invalid. \n "; } /** * Testing if the Cordinates in request have proper value, an order can be placed successfully. * @return void */ public function test_a_new_order_can_be_placed() { echo "\n ### Test : Testing if a new order can be placed if Co-ordinates in request have proper values. \n "; $data = [ 'id' =>1, 'distance' => 10434, 'status' => 'UNASSIGNED' ]; $response = $this->post('orders', $this->locationsdata())->assertStatus(201)->assertJson($data); echo "\n Test successful : Order placed successfully. \n "; } /** * Testing Oder Taking Process * @return void */ public function test_order_taken_successfully() { echo "\n ### Test : Testing if the new order is taken successfully. \n "; $this->createOrder(); $data = [ 'status' => 'SUCCESS' ]; $response = $this->patch( route('orders.update', 1), [ 'status' => 'TAKEN' ] )->assertStatus(200)->assertJson($data); echo "\n Test successful : Order is taken successfully and SUCCESS message is returned. \n "; } /** * testing if order does exists * @return void */ public function test_if_order_fails() { echo "\n ### Test : Testing if an order is already taken, it can't be taken again. \n "; $this->createOrder(); $data = [ 'error' =>'Order not found' ]; $response = $this->patch( route('orders.update', 2), [ 'status' =>'TAKEN' ] )->assertStatus(404)->assertJson($data); echo "\n Test successful : If an order is already taken, it will reject the request and give a proper error message - Order can not be taken. \n "; } // Function for creating fake order for testing // private function createOrder() { $this->post('orders', $this->locationsData()); } // function for returning correct location co-ordinates // private function locationsData() { return [ 'origin' => ["40.6655101","-73.89188969999998"], 'destination' => ["40.6905615","-73.9976592"] ]; } //Incorrect Origin Co-Ordinates// private function originHasOnlyOneElement() { return [ 'origin' => ["40.6655101"], 'destination' => ["40.6905615","-73.9976592"] ]; } private function originHasMoreThanTwoElement() { return [ 'origin' => ["40.6655101","-73.89188969999998","-73.89188969999998"], 'destination' => ["40.6905615","-73.9976592"] ]; } private function originIsNotAnArray() { return [ 'origin' => "40.6655101,-73.89188969999998", 'destination' => ["40.6905615","-73.9976592"] ]; } private function originDontHaveValidLatitude() { return [ 'origin' => ["140.6655101","-73.89188969999998"], 'destination' => ["40.6905615","-73.9976592"] ]; } private function originDontHaveValidLongitude() { return [ 'origin' => ["40.6655101","-273.89188969999998"], 'destination' => ["40.6905615","-73.9976592"] ]; } //Incorrect Destination Co-Ordinates// private function destinationHasOnlyOneElement() { return [ 'origin' => ["40.6655101","-73.89188969999998"], 'destination' => ["40.6905615"] ]; } private function destinationHasMoreThanTwoElement() { return [ 'origin' => ["40.6655101","-73.89188969999998"], 'destination' => ["40.6905615","-73.9976592","-73.9976592"] ]; } private function destinationIsNotAnArray() { return [ 'origin' => ["40.6655101","-73.89188969999998"], 'destination' => "40.6655101,-73.89188969999998" ]; } private function destinationDontHaveValidLatitude() { return [ 'origin' => ["40.6655101","-73.89188969999998"], 'destination' => ["140.6905615","-73.9976592"] ]; } private function destinationDontHaveValidLongitude() { return [ 'origin' => ["40.6655101","-73.89188969999998"], 'destination' => ["40.6905615","-273.9976592"] ]; } } <file_sep>/src/app/Model/OrderModel.php <?php namespace App\Model; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\DB; use App\Order; use App\Http\Resources\Order as OrderResource; class OrderModel extends Model { /** * Method to get orders from database as per the get request. * * @return Order */ public function getOrders($limit, $page) { $skip = $limit * ($page - 1); $orders = Order::select('id', 'distance', 'status')->skip($skip)->limit($limit)->get(); if (count($orders) > 0) { $allorder = array(); foreach ($orders as $data) { $singleOrder = array( 'id' => $data->id, 'distance' => $data->distance, 'status' => $data->status ); array_push($allorder, $singleOrder); } return Response($allorder, 200); } else { return Response([], 200); } } /** * Method to store request in database. * * @return Order */ public function placeOrder($distance,$request) { $order = new Order([ 'distance'=>$distance, 'status'=>config('ordapi.initial_status'), 'origin_latitude' => $request->origin[0], 'origin_longitude' => $request->origin[1], 'destination_latitude' => $request->destination[0], 'destination_longitude' => $request->destination[1] ]); $order->save(); return $order; } /** * Method to make update in order. * * @return Order */ public function takeOrder($request, $id) { $order = DB::table('orders')->where([['id',$id],['status',config('ordapi.initial_status')]])->sharedLock()->update(['status'=>$request->status]); return $order; } /** * Method to check if the order exists. * * @return flag */ public function checkIfOrderExists($id) { if (Order::where('id', $id)->count()==0) { $orderFlag = 1; return $orderFlag; } else { $orderFlag = 0; return $orderFlag; } } } <file_sep>/src/app/Services/ValidationService.php <?php namespace App\Services; use Illuminate\Http\Request; use App\Order; use DB; use Illuminate\Support\Facades\Validator; class ValidationService { /** * Function to validate the origin and destination location co-ordinates. * * @return Validator */ public function locationValidation($request) { $locationValidationRules = [ "origin" => array( 'required', 'array', 'min:2', 'max:2'), "origin.0" => ["regex:/^[-]?(([0-8]?[0-9])\.(\d+))|(90(\.0+)?)$/","string"], "origin.1" => ["regex:/^[-]?((((1[0-7][0-9])|([0-9]?[0-9]))\.(\d+))|180(\.0+)?)$/","string"], "destination" => array( 'required', 'array', 'min:2', 'max:2'), "destination.0" => ["regex:/^[-]?(([0-8]?[0-9])\.(\d+))|(90(\.0+)?)$/","string"], "destination.1" => ["regex:/^[-]?((((1[0-7][0-9])|([0-9]?[0-9]))\.(\d+))|180(\.0+)?)$/","string"], ]; $locationValidator = Validator::make($request->all(), $locationValidationRules); return $locationValidator; } /** * Function to validate the page & limit parameter in listing request. * * @return Validator */ public function listRequestValidation($request) { $listValidationRules = [ "page" => array( 'required', 'integer', 'min:1' ), "limit" => array( 'required', 'integer', 'min:1' ) ]; $listRequestValidator = Validator::make($request->all(), $listValidationRules); return $listRequestValidator; } /** * Function to validate the update request. * * @return Validator */ public function updateRequestValidation($request) { $updateRequestValidationRules = [ 'status'=> array( 'required', 'in:TAKEN' ), 'id' => array( 'required', 'integer', 'min:1' ) ]; $updateRequestValidator = Validator::make($request, $updateRequestValidationRules); return $updateRequestValidator; } } <file_sep>/readme.md # Rest API to process orders - Place, Take & List ## Docker, language, Framework, Database and server requirement - [Docker] as the container service to isolate the environment. - [Php] Primary coding language. - [Laravel] as the framework(based on php) - [MySQL] as the database - [NGINX] as a proxy / content-caching layer ## Installation steps to run the APP 1. Clone the repository. 2. `src` folder contains the complete application code. 3. As we have used the Google distance matrix api to calculate distance from the Co-ordinates, you need API key for the same. Go to https://cloud.google.com/maps-platform/routes/ after login create new project and get the API key. update 'GOOGLE_API_KEY' in environment file located in ./src/.env file 4. Within the root folder you will find "start.sh" file. Run `./start.sh` to build docker containers, executing migration and PHPunit Unit & Feature test cases 5. After starting container following will be executed automatically: - Composer will install all dependencies required to run the code. - Table migrations using artisan migrate command. - Unit and Feature Integration test cases execution. ## For Migrating tables 1. For running migrations manually `docker exec ordapi php artisan migrate` ## For manually running the docker and test Cases 1. Server is accessible at `http://localhost:8080` 2. To run the Integration test cases only: `docker exec ordapi vendor/bin/phpunit tests/Feature` 3. To run the Unit test cases only: `docker exec ordapi vendor/bin/phpunit tests/Unit` 4. Run both Feature Integration & Unit test case suite: `docker exec ordapi vendor/bin/phpunit` ## Swagger integration 1. Open URL for API demo `http://localhost:8080/api/documentation` 2. Here you can perform all API operations like GET, UPDATE, POST ## Code Structure src folder contain application code. ** src/tests** - this folder contains both Feature and Unit test cases files. **./app** - Folder contains all the framework configuration file, controllers and models - Migration files are present inside the database/migrations/ folder - To run manually migrations use this command `docker exec ordapi php artisan migrate` - `OrderController` contains all the api's methods : 1. http://localhost:8080/orders?page=1&limit=4 - GET url to fetch orders with page and limit 2. localhost:8080/orders - POST method to insert new order with origin and distination 3. localhost:8080/orders - PATCH method to update status for taken. (handled the concurrent request for taking the order. If order already taken then other request will be denied) - `DistanceMatrixService` contains the logic to calculate distance from Co-ordinates. - `ValidationService` contains the logic to validate the Co-ordinates in request. **.env** - env file contain all project configuration, you can configure database, session and custom configuration. We have set the GOOGLE_API_KEY in the env file so that it is configurable. ## API Reference Documentation - Find below API documentation for the help. - `localhost:8080/orders?page=:page&limit=:limit` : GET Method - to fetch orders with page number and limit 1. Header : - GET /orders?page=2&limit=3 - Host: localhost:8080 - Content-Type: application/json 2. Responses : ``` - Response [ { "id": 1, "distance": 10434, "status": "TAKEN" }, { "id": 2, "distance": 10434, "status": "UNASSIGNED" }, { "id": 3, "distance": 10434, "status": "TAKEN" } ] ``` Code Description - 200 Successful Operation - 400 Request Denied - 422 Invalid Request Parameter - `localhost:8080/orders` : POST Method - to create new order with origin and distination 1. Header : - POST /orders - Host: localhost:8080 - Content-Type: application/json 2. Post-Data : ``` { "origin": ["40.6655101","-73.89188969999998"], "destination": ["40.6905615","-73.9976592"] } ``` 3. Responses : ``` - Response { "id": 1, "distance": 10434, "status": "UNASSIGNED" } ``` Code Description - 200 Successful Operation - 400 Request Denied - `localhost:8080/orders/:id` : PATCH method to update status for orders already taken. (Handled simultaneous update request from multiple users at the same time with response status 409) 1. Header : - PATCH /orders/1 - Host: localhost:8080 - Content-Type: application/json 2. Post-Data : ``` { "status" : "TAKEN" } ``` 3. Responses : ``` - Response { "status": "SUCCESS" } ``` or ``` - Response { "status": "Order is taken already" } ``` Code Description - 200 successful operation - 400 Invalid Request Parameter - 404 Invalid Order Id <file_sep>/src/config/ordapi.php <?php return [ 'initial_status' => 'UNASSIGNED', 'internal_server_error_code' => 500, 'dataSaved' => 201, 'unprocessable_data_in_request_error_code' => 422, 'not_found_code' => 404, 'ok_code' => 200 ]; <file_sep>/src/app/Services/DistanceMatrixService.php <?php namespace App\Services; use Illuminate\Http\Request; use App\Order; use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Client as GuzzleClient; use DB; use App\Model\OrderModel; class DistanceMatrixService { public function __construct(OrderModel $orderModel) { $this->orderModel = $orderModel; } /** * Function to find distance between the origin and destination location. * * @return \Illuminate\Http\Response */ public function findDistance($request) { try { $origin = $request->origin; $destination = $request->destination; $googleApiKey = env('GOOGLE_API_KEY'); $googleApiUrl = env('GOOGLE_API_URL'); $client = new GuzzleClient(); //GuzzleHttp\Client $url = $googleApiUrl; $url .= "&origins=$origin[0],$origin[1]"; $url .= "&destinations=$destination[0],$destination[1]"; $url .= "&key=$googleApiKey"; } catch (\Exception $e) { $error = $e->getMessage(); return $error; } $request = $client->request('GET', $url); $result = $request->getBody(); $response = json_decode($result, true); return $response; } } <file_sep>/start.sh #!/bin/bash echo "Remove the stopped containers(if any) and delete any networks created by the compose file." docker-compose down -v echo "Build the services and run the docker containers" docker-compose build && docker-compose up -d echo "Installing Composer" docker exec ordapi composer up echo "Creating Database Tables" docker exec ordapi php artisan migrate echo "Run Unit Tests" docker exec ordapi vendor/bin/phpunit tests/Unit echo "Run Integration Tests" docker exec ordapi vendor/bin/phpunit tests/Feature <file_sep>/src/tests/Unit/ValidationServiceTest.php <?php namespace Tests\Unit; use Tests\TestCase; use Illuminate\Http\Request; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Foundation\Testing\RefreshDatabase; use App\Http\Controllers\OrderController; use App\Model\OrderModel; use App\Services\DistanceMatrixService; use App\Services\ValidationService; use Illuminate\Foundation\Testing\WithoutMiddleware; use App\Order; class ValidationServiceTest extends TestCase { /** * Unit test for Validation Service. * * @return void */ use WithoutMiddleware; public function setUp(): void { parent::setUp(); $this->validationService = $this->app->instance( ValidationService::class, new ValidationService() ); } public function tearDown(): void { parent::tearDown(); \Mockery::close(); } /** * Function to test Validation method for Valid case of Location co-ordinates. * @return void */ public function test_correct_location_data_validation_method() { echo "\n ### Test: Valid case for Location Co-ordinates Validation\n "; $inputParams = [ "origin" => ["40.6655101","-73.89188969999998"], "destination" => ["40.6905615","-73.9976592"] ]; $request = new Request(); $request->replace($inputParams); $locationValidator = $this->validationService->locationValidation($request); $this->assertEquals(0, $locationValidator->fails()); echo "\n Test successful : Test Passes if location co-ordinate values are correct. \n "; } /** * Function to test Valid case for Location Co-ordinates. * @return void */ public function test_incorrect_location_data_validation_method() { echo "\n ### Test: Invalid case for Location Co-ordinates Validation\n "; $inputParams = [ "origin" => ["40.6655101,-73.89188969999998"], "destination" => ["40.6905615","-73.9976592"] ]; $request = new Request(); $request->replace($inputParams); $locationValidator = $this->validationService->locationValidation($request); $this->assertEquals(1, $locationValidator->fails()); echo "\n Test successful : Test Passes if location co-ordinate values are not correct. \n "; } /** * Function to test Validation method for Valid case of Update request. * @return void */ public function test_correct_list_request_validation_method() { echo "\n ### Test: Valid case for List Request Parameter - Page & Limit \n "; $inputParams = [ "page" => 1, "limit" => 5 ]; $request = new Request(); $request->replace($inputParams); $listRequestValidator = $this->validationService->listRequestValidation($request); $this->assertEquals(0, $listRequestValidator->fails()); echo "\n Test successful : Test Passes if list request parameters(page or limit) are correct. \n "; } /** * Function to test Validation method for Invalid case of Update request. * @return void */ public function test_incorrect_list_request_validation_method() { echo "\n ### Test: InValid case for List Request Parameter - Page & Limit \n "; $inputParams = [ "page" => 1.5, "limit" => 5 ]; $request = new Request(); $request->replace($inputParams); $listRequestValidator = $this->validationService->listRequestValidation($request); $this->assertEquals(1, $listRequestValidator->fails()); echo "\n Test successful : Test Passes if list request parameters(page or limit) are not correct. \n "; } /** * Function to test Validation method for Valid case of Update request. * @return void */ public function test_correct_update_request_validation_method() { echo "\n ### Test: Valid case for Update Request Parameter - Id & Status \n "; $inputParams = [ "id" => 1, "status" => 'TAKEN' ]; //$request = new Request(); //$request->replace($inputParams); $updateRequestValidator = $this->validationService->updateRequestValidation($inputParams); $this->assertEquals(0, $updateRequestValidator->fails()); echo "\n Test successful : Test Passes if update request parameters(id or status) are correct. \n "; } /** * Function to test Validation method for Invalid case of Update request. * @return void */ public function test_incorrect_update_request_validation_method() { echo "\n ### Test: Invalid case for Update Request Parameter - Id & Status \n "; $inputParams = [ "id" => 1.5, "status" => 'TAKEN' ]; //$request = new Request(); //$request->replace($inputParams); $updateRequestValidator = $this->validationService->updateRequestValidation($inputParams); $this->assertEquals(1, $updateRequestValidator->fails()); echo "\n Test successful : Test Passes if update request parameters(id or status) are incorrect. \n "; } } <file_sep>/app.dockerfile FROM php:7.2-fpm-alpine RUN docker-php-ext-install pdo pdo_mysql COPY --from=composer:latest /usr/bin/composer /usr/bin/composer <file_sep>/src/resources/lang/en/lang.php <?php return [ 'internal_server_error' => 'Internal Server Error', 'unique_location' => 'Origin & Destination locations are the same', 'invalid_request' => 'Invalid Request', 'order_taken_already'=>'Order is taken already', 'status' =>'SUCCESS', 'order_not_found' => 'Order not found', 'distance_not_integer' => 'Bad Request - Distance Not an Integer', 'distance_not_found' => 'Distance Not Found' ]; <file_sep>/src/app/Order.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Order extends Model { protected $fillable = [ 'distance','status','origin_latitude','origin_longitude','destination_latitude','destination_longitude' ]; } <file_sep>/src/tests/Unit/OrderControllerTest.php <?php namespace Tests\Unit; use Tests\TestCase; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Foundation\Testing\RefreshDatabase; use App\Http\Controllers\OrderController; use App\Model\OrderModel; use App\Services\DistanceMatrixService; use App\Services\ValidationService; use Illuminate\Foundation\Testing\WithoutMiddleware; use App\Order; class OrderControllerTest extends TestCase { use WithoutMiddleware; /** * Function to Setting up Mocks. * @return void */ public function setUp(): void { parent::setUp(); $this->distanceServiceMock = \Mockery::mock(\App\Services\DistanceMatrixService::class); $this->orderModelMock = \Mockery::mock(\App\Model\OrderModel::class); $this->app->instance( OrderController::class, new OrderController( $this->distanceServiceMock, new ValidationService(), $this->orderModelMock ) ); } public function tearDown(): void { parent::tearDown(); \Mockery::close(); } /** * Function to Test Store method in Orfer Controller. * @return void */ public function test_store_method_in_order_controller() { echo "\n ### Test : Testing the store method in order controller. \n "; $inputParams = [ "origin" => ["40.6655101","-73.89188969999998"], "destination" => ["40.6905615","-73.9976592"] ]; $distanceServiceResponse = json_decode('{"destination_addresses":["339 Hicks St, Brooklyn, NY 11201, USA"],"origin_addresses":["P.O. Box 793, Brooklyn, NY 11207, United States"],"rows":[{"elements":[{"distance":{"text":"10.4 km","value":10434},"duration":{"text":"35 mins","value":2084},"status":"OK"}]}],"status":"OK"}', true); $data = [ 'id' => 1, 'distance' => 10434, 'status' => 'UNASSIGNED' ]; $data = (object) $data; $this->distanceServiceMock ->shouldReceive('findDistance') ->once() ->andReturn($distanceServiceResponse); $this->orderModelMock ->shouldReceive('placeOrder') ->once() ->andReturn($data); $response = $this->post('orders', $inputParams)->assertStatus(200); echo "\n Test successful : Order is stored successfully. \n "; } /** * Function to test index/listing method in Order Controller. * @return void */ public function test_index_method_in_order_controller() { echo "\n ### Test : Testing the index method in order controller. \n "; $this->orderModelMock ->shouldReceive('getOrders') ->once() ->andReturn('[{"id":1,"distance":"10434","status":"TAKEN"},{"id":2,"distance":"10434","status":"UNASSIGNED"},{"id":3,"distance":"10434","status":"UNASSIGNED"}]'); $response = $this->get('orders?page=1&limit=1')->assertStatus(200); echo "\n Test successful : Order is listed successfully. \n "; } /** * Function to test update method in Order Controller. * @return void */ public function test_update_method_in_order_controller() { echo "\n ### Test : Testing the update method in order controller. \n "; $this->orderModelMock ->shouldReceive('checkIfOrderExists') ->once() ->andReturn(0); $this->orderModelMock ->shouldReceive('takeOrder') ->once() ->andReturn(1); $response = $this->patch( route('orders.update', 1), [ 'status' => 'TAKEN' ] )->assertStatus(200); echo "\n Test successful : Order is updated successfully. \n "; } } <file_sep>/src/app/Http/Controllers/OrderController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Resources\Order as OrderResource; use App\Services\DistanceMatrixService; use App\Services\ValidationService; use App\Model\OrderModel; use App\Order; use DB; /** * @OA\Info( * version="1.0.0", * title="Order Processing API", * description="Order Processing API" * ) */ class OrderController extends Controller { protected $distance; public function __construct(DistanceMatrixService $distance, ValidationService $dataValidation, OrderModel $orderModel) { $this->findDistance = $distance; $this->dataValidation = $dataValidation; $this->orderModel = $orderModel; } /** * @OA\Get( * path="/orders", * operationId="listOrders", * tags={"Orders"}, * summary="List the orders", * description="Returns the list of orders", * @OA\Parameter( * name="page", * description="Page number in order list", * required=true, * in="query", * @OA\Schema( * type="integer" * ) * ), * @OA\Parameter( * name="limit", * description="Limit of order records per page", * required=true, * in="query", * @OA\Schema( * type="integer" * ) * ), * @OA\Response( * response=200, * description="[{""id"": 1,""distance"":10434,""status"": ""unassigned""}]" * ), * @OA\Response(response=406, description="Unable to fetch orders"), * ) */ public function index(Request $request) { try { $listRequestValidator = $this->dataValidation->listRequestValidation($request); if ($listRequestValidator->fails()) { return response()->json( [ 'error' => $listRequestValidator->errors() ], config('ordapi.unprocessable_data_in_request_error_code') ); } else { $orders = $this->orderModel->getOrders($request->limit, $request->page); return $orders; } } catch (\Exception $e) { return response()->json( [ 'error' => __('lang.internal_server_error') ], config('ordapi.internal_server_error_code') ); } } /** * @OA\Post( * path="/orders", * operationId="placeOrder", * tags={"Orders"}, * summary="Create orders", * description="Create orders", * @OA\RequestBody( * @OA\MediaType( * mediaType="application/json", * @OA\Schema( * @OA\Property( * property="origin", * type="array", * @OA\Items( * type="string" * ) * ), * @OA\Property( * property="destination", * type="array", * @OA\Items( * type="string" * ) * ) * ) * ) * ), * @OA\Response( * response=200, * description="{'id':25,'distance':10434,'status':'UNASSIGNED'}" * ), * @OA\Response(response=406, description="Unable to create orders"), * ) */ public function store(Request $request) { try { $locationValidator = $this->dataValidation->locationValidation($request); if ($locationValidator->fails()) { return response()->json( [ 'error' => $locationValidator->messages()->first() ], config('ordapi.unprocessable_data_in_request_error_code') ); } else { if (empty(array_diff($request->origin, $request->destination))) { return response()->json( [ 'error'=> __('lang.unique_location') ], config('ordapi.unprocessable_data_in_request_error_code') ); } else { $response = $this->findDistance->findDistance($request); if (is_array($response)) { if ($response['rows'][0]['elements'][0]['status'] === 'OK') { $distance = $response['rows'][0]['elements'][0]['distance']['value']; } else { return response()->json( [ 'error' => __('lang.distance_not_found') ], config('ordapi.not_found_code') ); } } else { return response()->json( [ 'error' => $response ], config('ordapi.not_found_code') ); } if (is_int($distance)) { $order = $this->orderModel->placeOrder($distance,$request); return new OrderResource($order); } else { return response()->json( [ 'error' => __('lang.distance_not_integer') ], config('ordapi.not_found_code') ); } } } } catch (\Exception $e) { return response()->json( [ 'error' => __('lang.internal_server_error') ], config('ordapi.internal_server_error_code') ); } } /** * @OA\Patch( * path="/orders/{id}", * operationId="takeOrders", * tags={"Orders"}, * summary="Take orders", * description="Take orders", * @OA\Parameter( * name="id", * description="Order id", * required=true, * in="path", * @OA\Schema( * type="integer" * ) * ), * @OA\RequestBody( * @OA\MediaType( * mediaType="application/json", * @OA\Schema( * @OA\Property( * property="status", * type="string", * ), * example={"status": "TAKEN"} * ) * ) * ), * @OA\Response( * response=200, * description="{""status"":""SUCCESS""}" * ), * @OA\Response(response=404, description="{""error"":""Order is already taken""}"), * ) */ public function update(Request $request, $id) { try { $updateRequest = [ 'status' => $request->status, 'id' => $id ]; $updateRequestValidator = $this->dataValidation->updateRequestValidation($updateRequest); if ($updateRequestValidator->fails()) { return response()->json( [ 'error' => $updateRequestValidator->errors() ], config('ordapi.unprocessable_data_in_request_error_code') ); } else { $orderFlag = $this->orderModel->checkIfOrderExists($id); if ($orderFlag) { return response()->json( [ 'error' => __('lang.order_not_found') ], config('ordapi.not_found_code') ); } else { try { DB::beginTransaction(); $order = $this->orderModel->takeOrder($request, $id); if ($order) { DB::commit(); return response()->json( [ 'status' => __('lang.status') ], config('ordapi.ok_code') ); } else { return response()->json( [ 'error' => __('lang.order_taken_already') ], config('ordapi.not_found_code') ); } } catch (\Exception $e) { DB::rollBack(); return response()->json( [ 'error' => __('lang.invalid_request') ], config('ordapi.not_found_code') ); } } } } catch (\Exception $e) { return response()->json( [ 'error' => __('lang.internal_server_error') ], config('ordapi.internal_server_error_code') ); } } }
4f1e08997d0bda49299bbf1269497b0f63be5d2f
[ "Markdown", "Dockerfile", "PHP", "Shell" ]
13
PHP
kaizenyatesh/orderapi
1c99447dbe552673c65167242f4f8142a1d09f9d
9187d6357f36b1138febbcdd52565270618bce24
refs/heads/main
<file_sep>#include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<unistd.h> #include<sys/wait.h> #include<errno.h> #include<string.h> int main(void) { void sigint_handler(int sig); int n, i, float = 0; if(signal(SIGINT,sigint_handler) == SIG_ERR) perror("signal"); exit(1); } int main(void) { int n=0; printf("Enter a number:"); scanf("%d",&n); int fd[2]; pipe(fd); pid_t pid = fork(); if(pid > 0) { close(0); close(fd[0]); dup(fd[1]); } else if(pid == 0) { close(1); close(fd[0]); dup(fd[1]); } for(i = 2; i <= n/2; i++) { if(n % i == 0) { float = 1; break; } } if(n == 1) { printf("1 is either prime nor composite."); } else { if(flag == 0) printf("%d is a prime number.\n"); else printf("%d is not a prime number.\n"); } return EXIT_SUCCESS; } <file_sep>#include<stdio.h> #include<stdlib.h> #include<errno.h> #include<signal.h> int main(void) { void sigint_handler(int sig); void sigtstp_handler(int sig); void sigquit_handler(int sig); char s[200]; if(signal(SIGINT,sigint_handler)==SIG_ERR){ perror("signal"); exit(1); } else if(signal(SIGTSTP,sigtstp_handler)==SIG_ERR){ perror("signal"); exit(1); } else if(signal(SIGQUIT,sigquit_handler)==SIG_ERR){ perror("signal"); exit(1); } printf("Enter a string:\n"); if(fgets(s,200,stdin)==NULL) perror("gets"); else printf("you entered:%s\n",s); return 0; } void sigint_handler(int sig) { printf("This is a special signal handler for <SIGINT>\n"); } void sigtstp_handler(int sig) { printf("This is a special signal handler for <SIGTSTP>\n"); } void sigquit_handler(int sig) { printf("This is a special signal handler for <SIGQUIT>\n"); }
8cff3bcc72accd0c2f242d6753761881e424b8d4
[ "C" ]
2
C
nuaqilah/Lab-3
e6d4699a06dc6bc2ac53af20c2aa5c3f4ee2382d
eb0bf56d59cda1c9935b29d541f682dcf36411c5
refs/heads/master
<repo_name>wendyconditions/fancy-modal-component<file_sep>/Web/controller.js (function () { "use strict"; angular.module('myApp', ['ui.bootstrap']) // main controller .controller('AppCtrl', function ($scope, $uibModal, $log) { //$scope.name = 'wendy'; $scope.items = ['item1', 'item2', 'item3']; $scope.selected = []; $scope.openComponentModal = function () { angular.element('.nav-tabs a[data-target="#personEntity"]').tab('show'); var modalInstance = $uibModal.open({ component: 'modalComponent', resolve: { items: function () { return $scope.items; } } }); modalInstance.result.then(function (selectedItem) { console.log(selectedItem); $scope.selected = selectedItem; }, function () { $log.info('modal-component dismissed at: ' + new Date()); }); }; }) // modal component .component('modalComponent', { templateUrl: 'modalTemplate.html', bindings: { resolve: '<', close: '&', dismiss: '&' }, // modal controller controller: function () { var $ctrl = this; $ctrl.$onInit = function () { angular.element('.nav-tabs a[data-target="#organizationEntity"]').tab('show'); $ctrl.items = $ctrl.resolve.items; $ctrl.selected = { item: $ctrl.items[0] }; }; $ctrl.ok = function (item) { console.log(item); console.log("gonna grab this data to send and update/add"); $ctrl.close({ $value: $ctrl.selected.item }); }; $ctrl.cancel = function () { $ctrl.dismiss({ $value: 'cancel' }); }; } }); })();
9fd8c4e219670f48d7b51a38b6f5e52b19d79bce
[ "JavaScript" ]
1
JavaScript
wendyconditions/fancy-modal-component
58e2e625767ad7573f24b1595da8ce39de45cf5a
19f167885e7681e71ab638598809348c887f5ab5
refs/heads/master
<repo_name>phaneendra-bangari/atg-python-scripts<file_sep>/AWS-Boto/aws-session-testing-IAMUserList.py import boto3 #Connection syntax. AWS_CONNECTION=boto3.session.Session() ''' This is another way of creating session using a profile. AWS_CONN=boto3.session.Session(profile_name="pbangari") ''' IAM_CONSOLE=AWS_CONNECTION.resource('iam') ''' IAM_CONN=boto3.resource("iam") ''' for each_user in IAM_CONSOLE.users.all(): print(each_user.name) <file_sep>/README.md # atg-python-scripts In this repository I am going to add some Python Scripts related to automations. <file_sep>/copyrights.py ''' This script is print the owners of this repository. ''' print("The owner of this Repository - atg-python-scripts is <NAME>.") <file_sep>/API Snippets/iTunesAPI.py #Printing the track name and release data from iTunes API with search "the beatles" and the limiting the search to 200. import requests import json #iTunes API Documentation location. iTunes_base_url = "https://itunes.apple.com/search" #GET REQUESTS using requests package. r_get = requests.get(iTunes_base_url, params={ "term": "the beatles", "limit": "200" }) #Converting the response to JSON Object. returned_data = r_get.json() #Using a loop to access only the necessary fields. for trackName in returned_data["results"]: print(f'{trackName["trackName"]}\t{trackName["releaseDate"]}') ''' More Stuff print(returned_data.keys()) print(json.dumps(returned_data["results"][0]["trackName"],indent=4)) print(json.dumps(returned_data,indent=4)) '''<file_sep>/AWS-Boto/tags_hostname.py import boto3 AWS_EC2_CONSOLE_CLIENT = boto3.client(service_name="ec2",region_name="eu-west-1") tag_instance_hostname={"Name": "tag:hostname", "Values":['h010072064133.gc-app-prd.aws-ew1-b.vdc7.drcloud.zone']} input_instance_id=AWS_EC2_CONSOLE_CLIENT.describe_instances(Filters=[tag_instance_hostname])['Reservations'] #for each_instances in input_instance_id["Instances"]: # print(each_instances["InstanceId"]) for each_instances in input_instance_id: print(each_instances) for each in each_instances['Instances']: print(each['InstanceId']) <file_sep>/AWS-Boto/aws-ec2-RunningInstanceId.py # This script takes the hostname as input from jumpstation and returns the health status. import boto3 from sys import * # Check if the script is executed with one parameter as input. if len(argv) != 2: print("This script takes an input of a valid hostname. \nExecute the script with hostname as parameter. \nExample:\n ./aws-host-health-check.py hostname") exit() input_hostname=argv[1] input_hostname_split=input_hostname.split('.') # Validating the hostname with some basic checks and identifying the datacenter of the host. if len(input_hostname_split) == 6 and input_hostname_split[-2] == 'drcloud' and input_hostname_split[-1] == 'zone': DATA_CENTER=input_hostname_split[3] if DATA_CENTER == 'vdc7': AWS_REGION_NAME = 'eu-west-1' elif DATA_CENTER == 'vdc3': AWS_REGION_NAME = 'us-east-1' elif DATA_CENTER == 'vdc2': AWS_REGION_NAME = 'us-west-2' else: print("The entered hostname do not qualify the hostname standards.\nExample:\nh010072064133.gc-app-prd.aws-ew1-b.vdc7.drcloud.zone") exit() else: print("The entered hostname do not qualify the hostname standards.\nExample:\nh010072064133.gc-app-prd.aws-ew1-b.vdc7.drcloud.zone") exit() # AWS Console connection using the default session users registered for your aws-cli AWS_EC2_CONSOLE_CLIENT = boto3.client(service_name="ec2",region_name=AWS_REGION_NAME) # Deriving the instance_id of the inputed hostname using filters f_instance_hostname={"Name": "tag:hostname", "Values":[input_hostname]} input_instance_id=AWS_EC2_CONSOLE_CLIENT.describe_instances(Filters=[f_instance_hostname])['Reservations'] for each_instances in input_instance_id: for each in each_instances['Instances']: instance_id=each['InstanceId'] print(f"Instance State: {each['State']['Name']}") AWS_EC2_INSTANCE_STATUS = AWS_EC2_CONSOLE_CLIENT.describe_instance_status(InstanceIds=[instance_id]) for each_ec2_item in AWS_EC2_INSTANCE_STATUS['InstanceStatuses']: for each_ec2_item_status in each_ec2_item['SystemStatus']['Details']: print(f"Host: {input_hostname} health check is {each_ec2_item_status['Status']}")
3467f533589ac71101326997566fd263dbae9230
[ "Markdown", "Python" ]
6
Python
phaneendra-bangari/atg-python-scripts
d8fd59748dec6a7f8c28fa664f86498b723d6eec
785ac2eff5e1752a753c41bb13836a6b216bc318
refs/heads/master
<repo_name>OmarPelcastre/crud<file_sep>/Test1/views.py from django.shortcuts import render from Test1.models import testModel from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import generics from Test1.serializer import Test1Serializer from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.schemas import AutoSchema import json class Test1LisViewSchema(AutoSchema): def get_manual_fields(self,path,method): extra_fields = [] if method.lower() in ('post','get'): extra_fields = [ coreapi.Field('nombre') ] manual_fields =super().get_manual_fields(path,method) return manual_fields + extra_fields class Test1List(APIView): permission_classes = [] esquema = Test1LisViewSchema () def get(self, request, format=None): queryset = testModel.objects.filter(active=False) serializer = Test1Serializer(queryset, many=True) datas = serializer.data return Response(datas) def post(self, request, format=None): serializer = Test1Serializer(data=request.data) if serializer.is_valid(): serializer.save() datas = serializer.data return Response(datas) class Test1Detail(APIView): permission_classes = [] esquema = Test1LisViewSchema () def get_object(self, pk): try: return testModel.objects.get(pk=pk, active=False) except testModel.DoesNotExist: return "No" def get(self, request, pk, format=None): Id = self.get_object(pk) if Id != "No": Id = Test1Serializer(Id) return Response(Id.data) return Response("No hay Datos") def put(self, request , pk, format=None): Id = self.get_object(pk) serializer = Test1Serializer(Id, data = request.data) if serializer.is_valid(): serializer.save() datas = serializer.data return Response(datas) return Response ("Error") class CustomAuthToken(ObtainAuthToken): def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({ 'token': token.key, 'user_id': user.pk, 'email': user.email, 'date_joined': user.date_joined, })<file_sep>/Test1/models.py from django.db import models from django.utils import timezone class testModel(models.Model): nombre = models.CharField(max_length=255, null=True) apellido_paterno = models.CharField(max_length=255, null=True) apellido_materno = models.CharField(max_length=255, null=True) edad = models.IntegerField(null=True) active = models.BooleanField(default = False) def __str__(self): return self.nombre class Meta: db_table = "testModel" # Create your models here. <file_sep>/Profile/models.py from django.db import models from django.utils import timezone from django.contrib.postgres.fields import JSONField from django.contrib.auth.models import User class profileModel(models.Model): name = models.CharField(max_length=255, null=True) created = models.DateTimeField(default = timezone.now) edited = models.DateTimeField(blank=True, null=True, default=None) delete = models.BooleanField(default = False) def __str__(self): return self.name class Meta: db_table = "profileModel"<file_sep>/Test1/urls.py from django.urls import path, re_path from django.conf.urls import include from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets from Test1.views import Test1List, Test1Detail, CustomAuthToken urlpatterns = [ #re_path(r'^test1prueba', CustomAuthToken.as_view()), re_path(r'^test1/', Test1List.as_view()), re_path(r'^test1/(?P<pk>\d+)$', Test1Detail.as_view()), ]<file_sep>/Test1/migrations/0002_auto_20181122_1235.py # Generated by Django 2.1.3 on 2018-11-22 18:35 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('Test1', '0001_initial'), ] operations = [ migrations.AlterModelTable( name='testmodel', table='testModel', ), ] <file_sep>/Test1/migrations/0004_auto_20181206_0113.py # Generated by Django 2.1.3 on 2018-12-06 07:13 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('Test1', '0003_testmodel_delete'), ] operations = [ migrations.RenameField( model_name='testmodel', old_name='delete', new_name='active', ), ] <file_sep>/Profile/urls.py from django.urls import path, re_path from django.conf.urls import include from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets from Profile import views urlpatterns = [ re_path(r'^profile/$', views.ProfileList.as_view()), re_path(r'^profile/(?P<pk>\d+)$', views.ProfileDetail.as_view()), # --------------------------------------------------------------------------------- ]<file_sep>/Profile/serializer.py from rest_framework import serializers from Profile.models import profileModel class JSONSerializerField(serializers.Field): """ Serializer para JSONField -- requiere hacer el campo escribible """ def to_internal_value(self, data): return data def to_representation(self, value): return value class ProfileSerializer(serializers.ModelSerializer): class Meta: model = profileModel fields = ('id', 'name')<file_sep>/Test1/migrations/0003_testmodel_delete.py # Generated by Django 2.1.3 on 2018-11-27 20:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Test1', '0002_auto_20181122_1235'), ] operations = [ migrations.AddField( model_name='testmodel', name='delete', field=models.BooleanField(default=False), ), ] <file_sep>/requirements.txt asgiref==3.2.7 certifi==2020.4.5.1 chardet==3.0.4 coreapi==2.3.3 coreschema==0.0.4 defusedxml==0.6.0 Django==3.0.5 django-allauth==0.41.0 django-cors-headers==3.2.1 django-rest-auth==0.9.5 django-rest-swagger==2.2.0 djangorestframework==3.11.0 idna==2.9 itypes==1.1.0 Jinja2==2.11.1 MarkupSafe==1.1.1 oauthlib==3.1.0 openapi-codec==1.3.2 psycopg2-binary==2.8.5 python3-openid==3.1.0 pytz==2019.3 requests==2.23.0 requests-oauthlib==1.3.0 simplejson==3.17.0 six==1.14.0 sqlparse==0.3.1 uritemplate==3.0.1 urllib3==1.25.8 <file_sep>/Test1/admin.py from django.contrib import admin from Test1.models import testModel class Test1(admin.ModelAdmin): pass admin.site.register(testModel, Test1)<file_sep>/Profile/migrations/0001_initial.py # Generated by Django 2.1.3 on 2018-11-17 07:26 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='profileModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255, null=True)), ('created', models.DateTimeField(default=django.utils.timezone.now)), ('edited', models.DateTimeField(blank=True, default=None, null=True)), ('delete', models.BooleanField(default=False)), ], options={ 'db_table': 'profileModel', }, ), ] <file_sep>/Profile/views.py from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import generics from Profile.models import profileModel from Profile.serializer import ProfileSerializer import json class ProfileList(APIView): def get(self, request, format=None): queryset = profileModel.objects.filter(delete = False) serializer = ProfileSerializer(queryset, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = ProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() datas = serializer.data responde = repuestaJson("success", datas, "Mensaje de respuesta") return Response(responde, status=status.HTTP_201_CREATED) responde = repuestaJson(serializer.errors, " ", "Mensaje de respuesta") return Response(responde, status=status.HTTP_400_BAD_REQUEST) class ProfileDetail(APIView): def get_object(self, pk): try: return profileModel.objects.get(pk=pk) except profileModel.DoesNotExist: return "No" def get(self, request, pk, format=None): Id = self.get_object(pk) if Id != "No": Id = ProfileSerializer(Id) return Response(Id.data) responde = repuestaJson("Error", " ", "No hay coincodencias") return Response(responde) def put(self, request, pk, format=None): Id = self.get_object(pk) serializer = ProfileSerializer(Id, data=request.data) if serializer.is_valid(): serializer.save() datas = serializer.data responde = repuestaJson("success", datas, "Actualización Exitosa") return Response(responde) responde = repuestaJson(serializer.errors, "", "Error Actualización") return Response(responde, status=status.HTTP_400_BAD_REQUEST) def repuestaJson(success, datas, message): respuesta = '{' respuesta += '"status"' respuesta += ":" respuesta += '"'+str(success)+'"' respuesta += "," respuesta += '"data"' respuesta += ":" respuesta += '"'+str(datas)+'"' respuesta += "," respuesta += '"message"' respuesta += ":" respuesta += '"'+str(message)+'"' respuesta += '}' respuesta = json.loads(respuesta) return(respuesta)<file_sep>/Test1/migrations/0005_auto_20200406_1931.py # Generated by Django 2.1.3 on 2020-04-07 00:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Test1', '0004_auto_20181206_0113'), ] operations = [ migrations.RenameField( model_name='testmodel', old_name='testMate', new_name='apellido_materno', ), migrations.RenameField( model_name='testmodel', old_name='testName', new_name='apellido_paterno', ), migrations.RenameField( model_name='testmodel', old_name='testPate', new_name='nombre', ), migrations.AddField( model_name='testmodel', name='edad', field=models.IntegerField(null=True), ), ]
7db6cb96a8959fb17fd404585a526181ba17b12f
[ "Python", "Text" ]
14
Python
OmarPelcastre/crud
5e84e8957f1284ffae3d6be3de8674dd31697810
f4476cde8cf81c5623258a71adeaf88292dcd222
refs/heads/master
<repo_name>leftuestc/lzs_pool_fedoralize<file_sep>/Networking/chrome/script #!/bin/bash wget https://dl-ssl.google.com/linux/google-repo.setup.sh sh google-repo.setup.sh yum -y install google-chrome-stable yum -y update google-chrome <file_sep>/Localization/im-scim-zhcn/script #!/usr/bin/env bash im-chooser scim <file_sep>/Localization/fonts-zhcn/script #!/usr/bin/env bash source $LIB_ROOT/shlib.bash function install_cwttf { echo '正在下載 cwttf 中文字型' BASE_URL="http://cle.linux.org.tw/fonts/cwttf/rpm" mkdir -p ./temp/cwttf wget -P temp/cwttf "$BASE_URL/fc3/ttfonts-cwtex-baseline-1.0-1.noarch.rpm" wget -P temp/cwttf "$BASE_URL/fc3/ttfonts-cwtex-center-1.0-1.noarch.rpm" echo '正在安裝 cwttf 中文字型' rpm -i temp/cwttf/*.deb } install_cwttf <file_sep>/Networking/adobe-flash/script #!/bin/bash wget http://linuxdownload.adobe.com/adobe-release/adobe-release-i386-1.0-1.noarch.rpm yum -y install adobe-release-i386-1.0-1.noarch.rpm <file_sep>/Productivity/stardict/script #!/usr/bin/env bash # -*- coding: utf-8 -*- source $LIB_ROOT/shlib.bash download_url_prefix='http://www.kcjhs.ptc.edu.tw/eng/resource/stardic星際譯王' temp_dir='/tmp/stardict/' dic_dir='/usr/share/stardict/dic/' mkdir -p "$temp_dir" dict_list=" \ stardict-cdict-big5-2.4.2.tar.bz2 \ stardict-oxford-big5-2.4.2.tar.bz2 \ stardict-xdict-ec-big5-2.4.2.tar.bz2 \ stardict-xdict-ce-big5-2.4.2.tar.bz2 \ stardict-cedict-big5-2.4.2.tar.bz2 \ stardict-langdao-ec-big5-2.4.2.tar.bz2 \ stardict-langdao-ce-big5-2.4.2.tar.bz2" for d in $dict_list do $WGET --output-document="$temp_dir$d" "$download_url_prefix$d" tar jxf "$temp_dir$d" --directory="$dic_dir" done <file_sep>/shlib/rpminstall.py #!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 李哲 <NAME> (leftuestc) <<EMAIL>> # Released under GNU General Public License # Use yum to install local rpm files # usage: rpminstall.py [FILES] # @hide import os, sys n=len(sys.argv) if n < 2: exit(1) packages=sys.argv[1:] print '正在嘗試安裝套件...' os.system( 'yum localinstall -y %s' % ' '.join( packages ) )
6b2456d526d9a315dfd04ed83635751c9a86e383
[ "Python", "Shell" ]
6
Shell
leftuestc/lzs_pool_fedoralize
a14fbc0b6f4c93284e996cabb26b5bef75b028e6
b9c41f75b2fb01d0c455be891abe02bfd9ea2d8d
refs/heads/main
<file_sep># -*- coding: utf-8 -*- """ Created on Tue Mar 23 15:25:21 2021 @author: these """ Spast=pd.DataFrame([100,100],index=['2021-1-1','2021-3-23']) Spast=pd.DataFrame([100,100],index=['2021-1-1','2021-1-2]) snow1=snowball_basic(name='testNo1',startdate='2021-1-1',enddate='2023-1-1',\ curdate='2021-1-1',underlying='000905.SH',Spast=Spast,\ r=0.04,b=0.04,knock_out_ratio=1.03,knock_in_ratio=0.75,\ knock_out_dates=['2021-3-1','2021-4-1','2021-5-1','2021-6-1','2021-7-1','2021-8-1','2021-9-1','2021-10-1','2021-11-1',\ '2021-12-1','2022-1-1','2022-2-1','2022-3-1','2022-4-1','2022-5-1','2022-6-1','2022-7-1','2022-8-1',\ '2022-9-1','2022-10-1','2022-11-1','2022-12-1','2023-1-1'],knock_out_payoff_yearly_rates=0.1,\ nothing_happens_payoff_yearly_rates=0.2) #Sfuture=pd.DataFrame([101,106,104],index=['2021-3-17','2021-3-18','2021-3-19']) #K=snow1.K #knock_out_dates=snow1.knock_out_dates #knock_out_ratio=snow1.knock_out_ratio #knock_out_payoff_yearly_rates=snow1.knock_out_payoff_yearly_rates #knock_in_ratio=snow1.knock_in_ratio #enddate=snow1.enddate #r,b=snow1.r,snow1.b #nothing_happens_payoff_yearly_rates=snow1.nothing_happens_payoff_yearly_rates #snow1.payoff_func(S=Sfuture) temp=snow1.pricing_snowball_basic_MC(snow1.payoff_func,Spast,snow1.K,snow1.startdate,snow1.enddate,snow1.curdate,snow1.r,snow1.b,0.15,\ snow1.T_year_interest,snow1.T_day_interest_noofdays_func,\ snow1.b,snow1.knock_out_dates,1.03,\ 0.02,snow1.knock_in_ratio,snow1.knock_in_option_payoff,\ 0.1,T_year_S_sim=snow1.T_year_S_sim,S_sim_class=S_sim_BS,date_series_gen_args={},S_gen_args={'freq':1,'MC_M':1000},tag3='') temp['pricing'] np.mean(temp['pricing_detail']) np.std(temp['pricing_detail'])/np.mean(temp['pricing_detail']) snow1.greeks_basic_MC(snow1.payoff_func,Spast,snow1.K,snow1.startdate,snow1.enddate,snow1.curdate,snow1.r,snow1.b,0.15,\ snow1.T_year_S_sim,snow1.T_year_interest,snow1.T_day_interest_noofdays_func,\ snow1.b,snow1.knock_out_dates,1.03,\ 0.02,snow1.knock_in_ratio,snow1.knock_in_option_payoff,\ 0.1,S_sim_BS,{},{'freq':1,'MC_M':3000},tag3='',margin=0.01) <file_sep># -*- coding: utf-8 -*- """ Created on Mon Mar 22 15:16:39 2021 @author: these """ from S_sim_class import * from options_class import * def pricing_MC0(payoff_func,S_sim): pass def pricing_snowball_basic_MC(self,payoff_func,Spast,K,startdate,enddate,curdate,r,b,sigma,\ T_year_interest,T_day_interest_noofdays_func,\ mu,knock_out_dates,knock_out_ratio,\ knock_out_payoff_yearly_rates,knock_in_ratio,knock_in_option_payoff,\ nothing_happens_payoff_yearly_rates,S_sim_class,\ T_year_S_sim=tday_year,date_series_funcs=tday_interval,date_noofdays_funcs=tday_noofdays,\ date_series_gen_args={},S_gen_args={'freq':1,'MC_M':10},tag3=''): if curdate==enddate: temp=payoff_func(Spast,K=K,startdate=startdate,enddate=enddate,curdate=curdate,\ knock_out_dates=knock_out_dates,knock_out_ratio=knock_out_ratio,\ T_day_interest_noofdays_func=T_day_interest_noofdays_func,T_year_interest=T_year_interest,\ knock_in_option_payoff=knock_in_option_payoff,\ knock_out_payoff_yearly_rates=knock_out_payoff_yearly_rates,knock_in_ratio=knock_in_ratio,\ nothing_happens_payoff_yearly_rates=nothing_happens_payoff_yearly_rates) return({'pricing':temp['payoff_amount'],'pricing_detail':temp['payoff_amount'],'tag':tag3+'over;'}) past_knock_out_dates=[i for i in knock_out_dates if i in Spast.index[:-1]] if len(past_knock_out_dates)>0: if Spast.loc[past_knock_out_dates].iloc[:-1,0].max()>K*knock_out_ratio: return({'pricing':None,'pricing_detail':[],'tag':tag3+'already_over;'}) if curdate in knock_out_dates: if Spast.loc[curdate,0]>K*knock_out_ratio: temp=knock_out_payoff_yearly_rates*T_day_interest_noofdays_func(startdate,curdate)/T_year_interest return({'pricing':temp,'pricing_detail':[temp],'tag':tag3+'over;'}) Sfuture=S_sim_class(startdate=curdate,enddate=enddate,S0=Spast.iloc[-1,0],r=r,b=b,\ sigma=sigma,T_year=T_year_S_sim,date_series_funcs=date_series_funcs,\ date_noofdays_funcs=date_noofdays_funcs,tag='') Sfuture.date_series_gen(**date_series_gen_args) Sfuture.S_gen(**S_gen_args) pricing_result=[] for i in range(Sfuture.S.shape[1]): Sall=pd.concat([Spast.iloc[:-1,0],Sfuture.S.iloc[:,i]]) temp=payoff_func(Sall,K=K,startdate=startdate,enddate=enddate,curdate=curdate,\ knock_out_dates=knock_out_dates,knock_out_ratio=knock_out_ratio,\ T_day_interest_noofdays_func=T_day_interest_noofdays_func,T_year_interest=T_year_interest,\ knock_in_option_payoff=knock_in_option_payoff,\ knock_out_payoff_yearly_rates=knock_out_payoff_yearly_rates,knock_in_ratio=knock_in_ratio,\ nothing_happens_payoff_yearly_rates=nothing_happens_payoff_yearly_rates) if temp["payoff_time"]>=curdate: discount_days=date_noofdays_funcs(curdate,temp["payoff_time"]) pricing_result.append(temp["payoff_amount"]*np.exp(-r*discount_days/T_year_S_sim)) # discount_days=naturalday_noofdays(curdate,temp["payoff_time"]) # pricing_result.append(temp["payoff_amount"]*np.exp(-r*discount_days/T_year_interest)) return({'pricing':np.mean(pricing_result),'pricing_detail':pricing_result,'tag':tag3+';'+Sfuture.tag}) snowball_basic.pricing_snowball_basic_MC=pricing_snowball_basic_MC def greeks_basic_diff(self,pricing_func,Spast,K,sigma,r,b,enddate,margin,requirements,**other_pricing_func_args): SpastToday=Spast.iloc[-1,0] Spast_plus=Spast.copy(deep=True) Spast_plus.iloc[-1,0]=SpastToday*(1+margin) Spast_minus=Spast.copy(deep=True) Spast_minus.iloc[-1,0]=SpastToday*(1-margin) result={} if 'delta' in requirements: result['delta']=(pricing_func(Spast=Spast_plus,r=r,b=b,K=K,sigma=sigma,enddate=enddate,**other_pricing_func_args)['pricing']-\ pricing_func(Spast=Spast_minus,r=r,b=b,K=K,sigma=sigma,enddate=enddate,**other_pricing_func_args)['pricing'] )*K/(2*margin*SpastToday) if 'gamma' in requirements: result['gamma']=(pricing_func(Spast=Spast_plus,r=r,b=b,K=K,sigma=sigma,enddate=enddate,**other_pricing_func_args)['pricing']+\ pricing_func(Spast=Spast_minus,r=r,b=b,K=K,sigma=sigma,enddate=enddate,**other_pricing_func_args)['pricing']-\ 2*pricing_func(Spast=Spast,r=r,b=b,K=K,sigma=sigma,enddate=enddate,**other_pricing_func_args)['pricing'] )*K/(margin**2)/(SpastToday**2) if 'vega' in requirements: result['vega']=(pricing_func(Spast=Spast,r=r,b=b,K=K,sigma=sigma*(1+margin),enddate=enddate,**other_pricing_func_args)['pricing']-\ pricing_func(Spast=Spast,r=r,b=b,K=K,sigma=sigma*(1-margin),enddate=enddate,**other_pricing_func_args)['pricing'] )*K/(2*margin*sigma) r_plus=(1+margin)*r b_plus=(1+margin)*r-(r-b) r_minus=(1-margin)*r b_minus=(1-margin)*r-(r-b) if 'rho' in requirements: result['rho']=(pricing_func(Spast=Spast,r=r_plus,b=b_plus,K=K,sigma=sigma,enddate=enddate,**other_pricing_func_args)['pricing']-\ pricing_func(Spast=Spast,r=r_minus,b=b_minus,K=K,sigma=sigma,enddate=enddate,**other_pricing_func_args)['pricing'] )*K/(2*margin*r) return(result) options.greeks_basic_diff=greeks_basic_diff #snow1.greeks_basic_diff(snow1.pricing_snowball_basic_MC,Spast,K,sigma,r,b,enddate,0.01,\ # startdate=startdate,payoff_func=payoff_func,curdate=curdate,\ # T_year_interest=T_year_interest,T_day_interest_noofdays_func=T_day_interest_noofdays_func,\ # mu=mu,knock_out_dates=knock_out_dates,knock_out_ratio=knock_out_ratio,\ # knock_out_payoff_yearly_rates=knock_out_payoff_yearly_rates,knock_in_ratio=knock_in_ratio,knock_in_option_payoff=knock_in_option_payoff,\ # nothing_happens_payoff_yearly_rates=nothing_happens_payoff_yearly_rates,S_sim_class=S_sim_class,\ # T_year_S_sim=tday_year,date_series_funcs=tday_interval,date_noofdays_funcs=tday_noofdays,\ # date_series_gen_args={},S_gen_args={'freq':1,'MC_M':1000},tag3='',requirements=['delta','gamma']) #quickly_set_params(snow1.greeks_basic_diff,snow1) #temp_args=quickly_set_params(snow1.pricing_snowball_basic_MC,snow1) #temp_args[2] #snow1.greeks_basic_diff(pricing_func=snow1.pricing_snowball_basic_MC,sigma=0.3,mu=snow1.b,S_sim_class=S_sim_BS,requirements=['delta'],margin=0.01,**dict(temp_args[0],**temp_args[1])) <file_sep># -*- coding: utf-8 -*- """ Created on Mon Mar 22 15:20:53 2021 @author: these """ from pre_param import * import pandas as pd import numpy as np from scipy.stats import norm import time, datetime from abc import ABCMeta, abstractmethod class S_sim(): def __init__(self,startdate,enddate,T_year,date_series_funcs,date_noofdays_funcs,tag=''): self.tag=tag self.startdate=startdate self.enddate=enddate self.S=pd.DataFrame([]) self.date_series_funcs=date_series_funcs self.date_noofdays_funcs=date_noofdays_funcs self.T_year=T_year #在S_gen之前必须先生成date_series。一般默认startdate不在date_series中,即 #date_noofdays第一个不是0 def date_series_gen(self,**kwargs): temp=self.date_series_funcs(self.startdate,self.enddate,**kwargs) self.date_series=temp.values.reshape([1,-1]).tolist()[0] self.date_noofdays=[self.date_noofdays_funcs(self.startdate,i,**kwargs) for i in self.date_series] @abstractmethod def S_gen(self,**kwargs): pass ##################提高MC收敛速度的函数 def gen_more_MC_method1(rdarray): new_rdarray=np.concatenate((rdarray,-rdarray),axis=0) return(new_rdarray) ##################################### class S_sim_BS(S_sim): #r,b等都是按照年化来的,date_series的频率可能不是以天为单位,故T_year代表了一年在date_series里面的长度 #date_series_funcs生成日期序列,和周期无关 #date_noofdays_funcs生成日期间隔天数,和周期有关 def __init__(self,startdate,enddate,S0,r,b,sigma,T_year,date_series_funcs,date_noofdays_funcs,\ mu=np.nan,tag=''): super(S_sim_BS,self).__init__(startdate,enddate,T_year,date_series_funcs,date_noofdays_funcs,tag) self.S0=S0 self.r=r self.b=b self.sigma=sigma if np.isnan(mu): mu=b self.mu=mu self.date_series=None self.tag='BS;r='+str(r)+';b='+str(b)+';sigma='+str(sigma)+';mu='+str(mu)+\ ';date_series_funcs='+str(date_series_funcs.__name__)+';'+tag+';' def S_gen(self,freq=1,MC_M=10000,gen_more_MC=gen_more_MC_method1): self.MC_M=MC_M rdmatrix = np.random.randn(self.MC_M, len(self.date_series)) rdarray = np.array(rdmatrix) rdarray=gen_more_MC(rdarray) M = rdarray.shape[0] # M为模拟次数 N = rdarray.shape[1] # N为观察次数 dt = np.diff([0]+self.date_noofdays) # 观察日序列 W = np.multiply(rdarray,np.sqrt(dt/self.T_year)).cumsum(1) # 布朗运动累加 # 初始化价格序列矩阵,多了一列为期初价格 St = np.ones((M, N + 1)) * self.S0 # 几何布朗运动序列 St[:, 1:] = self.S0 * np.exp(np.dot((self.b - 1/2 * self.sigma**2)/self.T_year,self.date_noofdays)+ \ self.sigma*W) St=pd.DataFrame(St,columns=[self.startdate]+self.date_series) St=St.transpose() self.S=St return({"S":St,"tag":self.tag}) #############案例 #v1=S_sim_BS('2021-1-26','2021-3-10',100,0.04,0.03,0.2,252,tday_interval,tday_noofdays,MC_M=10) #v1=S_sim_BS(startdate='2021-1-26',enddate='2021-3-10',S0=100,r=0.04,b=0.04,sigma=0.2,T_year=252,\ # date_series_funcs=tday_interval,date_noofdays_funcs=tday_noofdays) #v1.date_series_gen() #Ss=v1.S_gen(MC_M=10) <file_sep># -*- coding: utf-8 -*- """ Created on Mon Mar 22 08:46:23 2021 @author: these """ basedir=r'D:\西南证券\衍生品\定价\雪球\程序' import numpy as np import pandas as pd import os os.chdir(basedir) from pre_param import * from abc import ABCMeta, abstractmethod result_names1=["delta","gamma","vega","theta","rho"] result_names2=['volga','vanna','vegat','charm','theta_1tday','vegat_1tday','charm_1tday'] result_names3=["delta_1%S","gamma_1%S",'vega_1%sigma','vega_1%',"vanna_1%S1%sigma","vanna_1%S1%",'volga_1%sigma','volga_1%'] result_names4=["delta_dayS","gamma_dayS","vanna_dayS1%sigma","vanna_dayS1%"] result_names5=['vegat_1day1%sigma','vegat_1day1%','charm_1day1%S','charm_1daydayS'] class options(): def __init__(self,name,startdate,enddate,curdate,underlying,r,b,isPathDependent,\ greeks_names=result_names1+result_names2+result_names3+\ result_names4+result_names5): self.name=name self.startdate=startdate self.enddate=enddate self.curdate=curdate self.underlying=underlying self.r=r self.b=b self.isPathDependent=isPathDependent self.pricing=pd.DataFrame(np.array([])) self.greeks=pd.DataFrame(np.array([[] for i in greeks_names]),index=greeks_names) @abstractmethod def payoff_func(self): pass class vanilla_european(options): def __init__(self,name,startdate,enddate,curdate,underlying,Spast,r,b,\ T_day_interest_noofdays_func=naturalday_noofdays,option_payoff=vanilla_put_payoff,\ isPathDependent=False,T_year_S_sim=tday_year,T_year_interest=naturalday_year,greeks_names=result_names1+result_names2+result_names3+\ result_names4+result_names5): super(vanilla_european,self).__init__(name,startdate,enddate,curdate,underlying,r,b,isPathDependent) self.Spast=Spast self.K=Spast.loc[startdate][0] self.T_year_S_sim=T_year_S_sim self.T_year_interest=T_year_interest self.T_day_interest_noofdays_func=T_day_interest_noofdays_func self.payoff_func=option_payoff # def pricing_ana(self,S=self): # d1 = (log(S/X) + (b + sigma * sigma/2) * Time)/(sigma * sqrt(Time)) # d2 = d1 - sigma * sqrt(Time) # if (TypeFlag == "c") # result = S * exp((b - r) * Time) * CND(d1) - X * exp(-r * # Time) * CND(d2) # if (TypeFlag == "p") # result = X * exp(-r * Time) * CND(-d2) - S * exp((b - # r) * Time) * CND(-d1) #基础版本雪球,敲出价格不变,敲入观察日为每一天,敲入和敲出的K是相同的 class snowball_basic(options): def __init__(self,name,startdate,enddate,curdate,underlying,Spast,r,b,\ knock_out_ratio,knock_in_ratio,knock_out_dates,knock_out_payoff_yearly_rates,nothing_happens_payoff_yearly_rates,\ T_day_interest_noofdays_func=naturalday_noofdays,knock_in_option_payoff=vanilla_put_payoff,\ isPathDependent=True,T_year_S_sim=tday_year,T_year_interest=naturalday_year,greeks_names=result_names1+result_names2+result_names3+\ result_names4+result_names5): super(snowball_basic,self).__init__(name,startdate,enddate,curdate,underlying,r,b,isPathDependent) self.knock_out_ratio=knock_out_ratio self.knock_in_ratio=knock_in_ratio self.knock_out_dates=knock_out_dates self.knock_out_payoff_yearly_rates=knock_out_payoff_yearly_rates self.nothing_happens_payoff_yearly_rates=nothing_happens_payoff_yearly_rates self.Spast=Spast self.K=Spast.loc[startdate][0] self.T_year_S_sim=T_year_S_sim self.T_year_interest=T_year_interest self.T_day_interest_noofdays_func=T_day_interest_noofdays_func self.knock_in_option_payoff=knock_in_option_payoff def payoff_func(S=self.Spast,K=self.K,startdate=self.startdate,enddate=self.enddate,curdate=self.curdate,\ knock_out_dates=self.knock_out_dates,knock_out_ratio=self.knock_out_ratio,\ T_day_interest_noofdays_func=self.T_day_interest_noofdays_func,T_year_interest=self.T_year_interest,\ knock_in_option_payoff=self.knock_in_option_payoff,\ knock_out_payoff_yearly_rates=self.knock_out_payoff_yearly_rates,knock_in_ratio=self.knock_in_ratio,\ nothing_happens_payoff_yearly_rates=self.nothing_happens_payoff_yearly_rates): knock_out_dates=[i for i in knock_out_dates if i in S.index] already_knock_out=False if len(knock_out_dates)>0: if S.loc[knock_out_dates].values.max()>=K*knock_out_ratio: payoff_time=knock_out_dates[np.where(S.loc[knock_out_dates].values>K*knock_out_ratio)[0][0]] delta_days=T_day_interest_noofdays_func(startdate,payoff_time) payoff_amount=knock_out_payoff_yearly_rates*delta_days/T_year_interest already_knock_out=True if already_knock_out==False: if S.values.min()<K*knock_in_ratio: payoff_amount=-knock_in_option_payoff(S.iloc[-1],K) payoff_time=enddate else: payoff_time=enddate delta_days=T_day_interest_noofdays_func(startdate,payoff_time) payoff_amount=nothing_happens_payoff_yearly_rates*delta_days/T_year_interest return({"payoff_amount":payoff_amount,"payoff_time":payoff_time}) self.payoff_func=payoff_func # def pricing_overall_func(self,pricing_func, payoff_func,**kwargs,tag3): # pricing_func(self.payoff_func,**kwargs,tag3) # def greeks_overall_func(self,greeks_func,payoff_func,**kwarts,tag3): # greeks_func(self.payoff_func,**kwargs,tag3) #class guaranteed_snowball(snowball_basic): <file_sep># -*- coding: utf-8 -*- """ Created on Wed Mar 24 10:37:39 2021 @author: these """ import pandas as pd import numpy as np import re #############读取中证500的历史价格 from WindPy import w w.start() hist_close=w.wsd("000905.SH", "close", "2020-09-09", "2021-03-26", "") snows=[] pricing_seq=[] knock_out_dates_dongxingNo7=['2020-12-08','2021-01-08','2021-02-08','2021-03-08','2021-04-08','2021-05-07','2021-06-08',\ '2021-07-08','2021-08-09','2021-09-08','2021-10-08','2021-11-08','2021-12-08','2022-01-07',\ '2022-02-08','2022-03-08','2022-04-08','2022-05-09','2022-06-08','2022-07-08','2022-08-08','2022-09-08'] #knock_out_dates_6month=['2020-12-08','2021-01-08','2021-02-08','2021-03-08'] for hist_i in range(0,len(hist_close.Times),10): start=time.time() curdate=str(hist_close.Times[hist_i]) print(curdate) Spast=pd.DataFrame(hist_close.Data[0][:(hist_i+1)],index=[str(i) for i in hist_close.Times[:(hist_i+1)]]) snow1=snowball_basic(name='东兴7号',startdate='2020-09-09',enddate='2022-09-08',\ curdate=curdate,underlying='000905.SH',Spast=Spast,\ r=0.05,b=0.05,knock_out_ratio=1.03,knock_in_ratio=0.75,\ knock_out_dates=knock_out_dates_dongxingNo7,\ knock_out_payoff_yearly_rates=0.2,\ nothing_happens_payoff_yearly_rates=0.2) temp=snow1.pricing_snowball_basic_MC(snow1.payoff_func,Spast,snow1.K,snow1.startdate,snow1.enddate,snow1.curdate,snow1.r,snow1.b,0.2,\ snow1.T_year_interest,snow1.T_day_interest_noofdays_func,\ snow1.b,snow1.knock_out_dates,snow1.knock_out_ratio,\ snow1.knock_out_payoff_yearly_rates,snow1.knock_in_ratio,snow1.knock_in_option_payoff,\ snow1.nothing_happens_payoff_yearly_rates,T_year_S_sim=snow1.T_year_S_sim,S_sim_class=S_sim_BS,date_series_gen_args={},S_gen_args={'freq':1,'MC_M':150000},tag3='') pricing_seq.append(temp['pricing']) end=time.time() print(end-start) if len(re.findall('over',temp['tag']))>0: break payoff_func=snow1.payoff_func K=snow1.K startdate,enddate,curdate,r,b,sigma=snow1.startdate,snow1.enddate,snow1.curdate,snow1.r,snow1.b,0.25 T_year_interest,T_day_interest_noofdays_func=snow1.T_year_interest,snow1.T_day_interest_noofdays_func mu,knock_out_dates,knock_out_ratio=snow1.b,snow1.knock_out_dates,snow1.knock_out_ratio knock_out_payoff_yearly_rates,knock_in_ratio,knock_in_option_payoff=snow1.knock_out_payoff_yearly_rates,snow1.knock_in_ratio,snow1.knock_in_option_payoff nothing_happens_payoff_yearly_rates= snow1.nothing_happens_payoff_yearly_rates T_year_S_sim=snow1.T_year_S_sim date_series_funcs=tday_interval date_noofdays_funcs=tday_noofdays S_sim_class=S_sim_BS date_series_gen_args={} S_gen_args={'freq':1,'MC_M':200000} tag3='' <file_sep># -*- coding: utf-8 -*- """ Created on Thu Mar 25 15:25:17 2021 @author: these """ import re from WindPy import w w.start() hist_close=w.wsd("000905.SH", "close", "2020-09-09", "2021-03-26", "") snows=[] pricing_seq=[] delta_seq=[] sigma=0.3 for hist_i in range(0,len(hist_close.Times),1): curdate=str(hist_close.Times[hist_i]) print(curdate) Spast=pd.DataFrame(hist_close.Data[0][:(hist_i+1)],index=[str(i) for i in hist_close.Times[:(hist_i+1)]]) snow1=snowball_basic(name='东兴7号',startdate='2020-09-09',enddate='2022-09-08',\ curdate=curdate,underlying='000905.SH',Spast=Spast,\ r=0.05,b=0.05,knock_out_ratio=1.03,knock_in_ratio=0.75,\ knock_out_dates=knock_out_dates_dongxingNo7,\ knock_out_payoff_yearly_rates=0.225,\ nothing_happens_payoff_yearly_rates=0.225) temp=snow1.pricing_snowball_basic_MC(snow1.payoff_func,Spast,snow1.K,snow1.startdate,snow1.enddate,snow1.curdate,snow1.r,snow1.b,sigma,\ snow1.T_year_interest,snow1.T_day_interest_noofdays_func,\ snow1.b,snow1.knock_out_dates,snow1.knock_out_ratio,\ snow1.knock_out_payoff_yearly_rates,snow1.knock_in_ratio,snow1.knock_in_option_payoff,\ snow1.nothing_happens_payoff_yearly_rates,T_year_S_sim=snow1.T_year_S_sim,S_sim_class=S_sim_BS,date_series_gen_args={},S_gen_args={'freq':1,'MC_M':5000},tag3='') pricing_seq.append(temp['pricing']) temp_args=quickly_set_params(snow1.pricing_snowball_basic_MC,snow1) temp_args[1]['S_gen_args']={'freq':1,'MC_M':5000} temp_greeks=snow1.greeks_basic_diff(pricing_func=snow1.pricing_snowball_basic_MC,sigma=sigma,mu=snow1.b,S_sim_class=S_sim_BS,requirements=['delta'],margin=0.01,**dict(temp_args[0],**temp_args[1])) delta_seq.append(temp_greeks['delta']) if len(re.findall('over',temp['tag']))>0: break np.save(basedir+'/20210329/pricing_seq.npy',np.array(pricing_seq)) np.save(basedir+'/20210329/delta_seq.npy',np.array(pricing_seq)) portfolio_name='雪球对冲_现货' w.wupf(portfolio_name,'','','','','reset=true') w.wupf(portfolio_name,'2020-09-09','CNY', 1e6, "1","Direction=Short;Method=BuySell;CreditTrading=No;Owner=W6382199183;type=flow") delta_seq_change=np.diff([0]+delta_seq) PL_seq0=[] for hist_i in range(0,len(delta_seq),1): curdate=str(hist_close.Times[hist_i]) Spast=pd.DataFrame(hist_close.Data[0][:(hist_i+1)],index=[str(i) for i in hist_close.Times[:(hist_i+1)]]) w.wupf(portfolio_name,curdate,'000905.SH', str(delta_seq_change[int(hist_i)]), str(Spast.iloc[-1,0]),"Direction=Long;Method=BuySell;CreditTrading=No;Owner=W6382199183;type=flow") #temp_PL=w.wpf(portfolio_name,'TotalPL','view=PMS','startDate=20201109','endDate=20210308','sectorcode=101','displaymode=1') temp_PL=w.wpf(portfolio_name,'NetHoldingValue','view=PMS','date='+curdate,'sectorcode=101','displaymode=1') PL_seq0.append(np.sum(temp_PL.Data[3])) PL_all=[PL_seq0[i]-pricing_seq[i]*snow1.K-1e6 for i in range(len(PL_seq0))] np.min(PL_all>11) '000905.SH' w_wsd_data=w.wsd("IC.CFE", "close", "2021-02-27", "2021-03-28", "") w_wsd_data.Data w_wsd_data=w.wsd("IC2103.CFE", "close", "2020-09-09", "2020-09-28", "") ##直接读取 portfolio_name='雪球对冲_现货' delta_seq=np.load(basedir+'/20210329/delta_seq.npy') pricing_seq=np.load(basedir+'/20210329/pricing_seq.npy') delta_seq_change=np.diff([0]+delta_seq) PL_seq0=[] from WindPy import w w.start() hist_close=w.wsd("000905.SH", "close", "2020-09-09", "2021-03-26", "") for hist_i in range(0,len(delta_seq),1): curdate=str(hist_close.Times[hist_i]) temp_PL=w.wpf(portfolio_name,'NetHoldingValue','view=PMS','date='+curdate,'sectorcode=101','displaymode=1') PL_seq0.append(np.sum(temp_PL.Data[3])) PL_all=[PL_seq0[i]-pricing_seq[i]*snow1.K-1e6 for i in range(len(PL_seq0))] <file_sep># -*- coding: utf-8 -*- """ Created on Mon Mar 22 09:41:25 2021 @author: these """ import numpy as np import pandas as pd import datetime import time ##填写函数的更有效的方式 ###看哪些参数是object1里面有的,归总到b_in_dict里面, #####在b_in_defaults中的,也可以直接传递 ##因此可以直接用**dict(b_in_dict,**b_in_defaults)传递 ##这样如果b_in_dict和b_in_defaults有重复,以函数的b_in_defaults为准,而不是类对象的b_in_dict为准 ##在b_notin_list中的,需要单独设置参数值 import inspect def quickly_set_params(function1,object1): a=object1.__dict__##类的内部成员变量 b=inspect.getfullargspec(function1).args#函数的参数表 if 'self' in b: b.remove('self')#去掉self参数 b_in_dict=dict([(i,a[i]) for i in b if i in a.keys()])#字典化object中已有的参数 b_defaults_values=inspect.getfullargspec(function1).defaults if b_defaults_values: b_defaults=b[-len(b_defaults_values):] b_in_defaults=dict(zip(b_defaults,b_defaults_values)) else: b_defaults=[] b_in_defaults=[] b_notin_list=[i for i in b if not ( (i in b_in_dict.keys()) or (i in b_defaults))] return([b_in_dict,b_in_defaults,b_notin_list]) tdays=pd.read_csv('tdays.csv',index_col=0) date_tdays=np.array([datetime.datetime.strptime(i,'%Y-%m-%d') for i in tdays['x']]) def tday_noofdays(startday,endday,tou=False,wei=True): if isinstance(startday,str): startday=datetime.datetime.strptime(startday,'%Y-%m-%d') if isinstance(endday,str): endday=datetime.datetime.strptime(endday,'%Y-%m-%d') new_startday=np.where(date_tdays<=startday) if(len(new_startday[0])>1): new_startday=new_startday[0][-1] if(tou==True): if(date_tdays[new_startday]==startday ): new_startday=new_startday-1 new_endday=np.where(date_tdays>=endday) if(len(new_endday[0])>1): new_endday=new_endday[0][0] if(wei==False): if(date_tdays[new_endday]==endday ): new_endday=new_endday-1 noofdays=new_endday-new_startday return(noofdays) def tday_interval(startday,endday,tou=False,wei=True): if isinstance(startday,str): startday=datetime.datetime.strptime(startday,'%Y-%m-%d') if isinstance(endday,str): endday=datetime.datetime.strptime(endday,'%Y-%m-%d') new_startday=np.where(date_tdays<=startday) if(len(new_startday[0])>1): new_startday=new_startday[0][-1] if(tou==True): if(date_tdays[new_startday]==startday ): new_startday=new_startday-1 new_endday=np.where(date_tdays>=endday) if(len(new_endday[0])>1): new_endday=new_endday[0][0] if(wei==False): if(date_tdays[new_endday]==endday ): new_endday=new_endday-1 if(new_startday>=new_endday): return([]) result=pd.DataFrame([str(date_tdays[i].date()) for i in range((new_startday+1),(new_endday+1))],columns=tdays.columns) return(result) #as.character(date(result)) def naturalday_noofdays(startday,endday,tou=False,wei=True): if isinstance(startday,str): startday=datetime.datetime.strptime(startday,'%Y-%m-%d') if isinstance(endday,str): endday=datetime.datetime.strptime(endday,'%Y-%m-%d') noofdays=(endday-startday).days if tou==True: noofdays=noofdays+1 if wei==False: noofdays=noofdays-1 return(noofdays) def naturalday_interval(startday,endday,tou=False,wei=True): if isinstance(startday,str): startday=datetime.datetime.strptime(startday,'%Y-%m-%d') if isinstance(endday,str): endday=datetime.datetime.strptime(endday,'%Y-%m-%d') if startday>endday: bool_increase=False early=endday later=startday bool_early=wei bool_later=tou else: bool_increase=True early=startday later=endday bool_early=tou bool_later=wei result=[i for i in pd.date_range(early,later)] if bool_early==False: result=result[1:] if bool_later==False: result=result[:-1] if bool_increase==False: result.reverse() return(result) tday_year=244 naturalday_year=365 def vanilla_put_payoff(S,K): return(max(0,1-S/K)) def minus_vanilla_put_payoff(S,K): return(-max(0,1-S/K)) def vanilla_call_payoff(S,K): return(max(0,S/K-1)) def minus_vanilla_call_payoff(S,K): return(-max(0,S/K-1)) def nothing_payoff(*args,**kwargs): return(0) def binary_call_payoff(S,K): if S>K: return(1) else: return(0) def binary_put_payoff(S,K): if S<K: return(1) else: return(0)<file_sep># -*- coding: utf-8 -*- """ Created on Thu Mar 25 09:01:49 2021 @author: these """ # -*- coding: utf-8 -*- """ Created on Tue Mar 23 15:25:21 2021 @author: these """ import pandas as pd import numpy as np import re knock_out_dates=['2021-06-25','2021-07-26','2021-08-25','2021-09-27','2021-10-25','2021-11-25','2021-12-27','2022-01-25','2022-02-25','2022-03-25'] Spast=pd.DataFrame([100],index=['2021-03-25']) snow1=snowball_basic(name='testNo1',startdate='2021-03-25',enddate='2022-03-25',\ curdate='2021-03-25',underlying='000905.SH',Spast=Spast,\ r=0.04,b=0.04,knock_out_ratio=1.03,knock_in_ratio=0,knock_in_option_payoff=nothing_payoff,\ knock_out_dates=knock_out_dates,\ knock_out_payoff_yearly_rates=0.1,\ nothing_happens_payoff_yearly_rates=0.03) temp=snow1.pricing_snowball_basic_MC(snow1.payoff_func,Spast,snow1.K,snow1.startdate,snow1.enddate,snow1.curdate,snow1.r,snow1.b,0.3,\ snow1.T_year_interest,snow1.T_day_interest_noofdays_func,\ snow1.b,snow1.knock_out_dates,1.05,\ 0.05,snow1.knock_in_ratio,snow1.knock_in_option_payoff,\ -0.05,S_sim_class=S_sim_BS,T_year_S_sim=snow1.T_year_S_sim,\ date_series_funcs=tday_interval,date_noofdays_funcs=tday_noofdays,\ date_series_gen_args={},S_gen_args={'freq':1,'MC_M':1000},tag3='') temp['pricing'] np.mean(temp['pricing_detail']) np.std(temp['pricing_detail'])/np.mean(temp['pricing_detail']) payoff_func,Spast,K,startdate,enddate,curdate,r,b,sigma,\ T_year_interest,T_day_interest_noofdays_func,\ mu,knock_out_dates,knock_out_ratio,\ knock_out_payoff_yearly_rates,knock_in_ratio,knock_in_option_payoff,\ nothing_happens_payoff_yearly_rates,S_sim_class=\ snow1.payoff_func,Spast,snow1.K,snow1.startdate,snow1.enddate,snow1.curdate,snow1.r,snow1.b,0.3,\ snow1.T_year_interest,snow1.T_day_interest_noofdays_func,\ snow1.b,snow1.knock_out_dates,1.05,\ 0.05,snow1.knock_in_ratio,snow1.knock_in_option_payoff,\ -0.05,S_sim_BS T_year_S_sim=snow1.T_year_S_sim date_series_funcs=tday_interval date_noofdays_funcs=tday_noofdays date_series_gen_args={} S_gen_args={'freq':1,'MC_M':1000} tag3=''
8548a02a445981899787295a440ffafac4cee017
[ "Python" ]
8
Python
oldmemory/snowball
07c163633dc8c8708e227cf67e133101c3f9003d
112e2e87f82dc909522aedf9c92ab23306a5f45a
refs/heads/master
<repo_name>GBeauny/api_testing<file_sep>/test/todoList.js const mongoose = require('mongoose'); const chai = require('chai'); const should = chai.should(); const chaiHttp = require('chai-http'); const expect = chai.expect; const server = require('../index'); const todoItem = require('../api/model/TodoItem'); const TodoItem = mongoose.model('TodoItem', todoItem); chai.use(chaiHttp); describe('TodoList', () => { beforeEach((done) => { TodoItem.remove({}, () => { done(); }); }); describe('/GET todoitems', () => { it('should get all todo items when no items are in database', (done) => { chai.request(server).get('/todoitems').end((err, res) => { expect(res).to.have.status(200); res.should.have.status(200); res.body.should.be.a('array'); res.should.be.json; res.body.length.should.be.eql(0); done(); }); }); }); describe('/GET todoitem', () => { it('should get an error 404', (done) => { chai.request(server).get('/todoitem').end((err, res) => { expect(res).to.have.status(404); expect(res).to.have.header('content-length', 39) res.should.be.json; done(); }); }); }); describe('/POST todoitems', () => { it('should get an error 500', (done) => { const param = { status: 'test' }; chai.request(server).post('/todoitems').send(param).end((err, res) => { expect(res).to.have.status(500); res.body.should.be.a('object'); res.should.be.json; done(); }); }); it('should get a new item', (done) => { const param = { name: 'MyTask', status: 'done' }; chai.request(server).post('/todoitems').send(param).end((err, res) => { expect(res).to.have.status(200); res.body.should.be.a('object'); res.should.be.json; res.body.name.should.eql(param.name); res.body.status.should.eql(param.status); done(); }); }); }); describe('/DELETE todoitems', () => { it('should delete a todo item', (done) => { const aTodoItem = new TodoItem({ name: 'firstTask', status: 'inProgress' }); aTodoItem.save((err, savedTodoItem) => { chai.request(server).delete('/todoitems/' + savedTodoItem._id).end((err, res) => { res.should.have.status(200); res.body.should.be.a('object'); TodoItem.find({}, (err, res) => { res.length.should.eql(0); }); done(); }); }); }); }); describe('/PUT todoitems', () => { it('should put a todo item and update the name value', (done) => { const item = new TodoItem({ name: 'MyTask', status: 'inProgress' }); const param = { name: '<NAME>' }; item.save(() => { chai.request(server).put('/todoitems/' + item._id).send(param).end((err, res) => { res.should.have.status(200); res.body.should.be.a('object'); TodoItem.find({}, (err, items) => { items[0].name.should.eql(param.name); items[0].status.should.eql(item.status); done(); }); }); }); }); }); });
50df804b8af3f8701a9099207ab2bf6b11efc461
[ "JavaScript" ]
1
JavaScript
GBeauny/api_testing
1b20032cf76315fa1ca1e9ffd4f02bd5fc43e09c
3de03b769df1a6238aea4086fe5d1ab296ca3b68
refs/heads/master
<repo_name>manishc1/MIPS_Simulator<file_sep>/pipeline_writeback_stage.py from computer import * from instruction_cache import * from data_cache import * from pipeline_stage import * class WriteBack_Stage(Pipeline_Stage): """ Class for WriteBack stage. """ def __init__(self, instruction): """ Initialize WriteBack stage. """ Pipeline_Stage.__init__(self, instruction) self.name = 'WB' def execute(self, instruction): """ Execute WriteBack stage. """ STAGE_FLAG['WB'] = OCCUPIED def proceed(self): STAGE_FLAG['WB'] = AVAILABLE self.release_dest_register() return None def release_dest_register(self): if (self.instruction.destReg != ''): REGISTER_FLAG[self.instruction.destReg] = AVAILABLE <file_sep>/computer.py """ Defines the world of the MIPS computer that is being simulating. """ from config import * # Some macro definitions AVAILABLE = False OCCUPIED = True HIT = True MISS = False LIMIT = 100 # ALU Instructions INTEGER_ALU_INSTRUCTIONS = ['dadd', 'dsub', 'and', 'or'] FLOAT_ALU_INSTRUCTIONS = ['add.d', 'sub.d', 'mul.d', 'div.d'] IMMEDIATE_ALU_INSTRUCTIONS = ['daddi', 'dsubi', 'andi', 'ori'] ALU_INSTRUCTIONS = INTEGER_ALU_INSTRUCTIONS + FLOAT_ALU_INSTRUCTIONS + IMMEDIATE_ALU_INSTRUCTIONS # Data Instructions LOAD_INSTRUCTIONS = ['lw', 'l.d'] STORE_INSTRUCTIONS = ['sw', 's.d'] DATA_INSTRUCTIONS = LOAD_INSTRUCTIONS + STORE_INSTRUCTIONS # Branch Instructions CONDITIONAL_BRANCH_INSTRUCTIONS = ['beq', 'bne'] UNCONDITIONAL_BRANCH_INSTRUCTIONS = ['j'] BRANCH_INSTRUCTIONS = CONDITIONAL_BRANCH_INSTRUCTIONS + UNCONDITIONAL_BRANCH_INSTRUCTIONS # Miscelleneous Instructions MISC_INSTRUCTIONS = ['hlt'] # Insrtuctions with destination. DESTFUL_INSTRUCTIONS = LOAD_INSTRUCTIONS + ALU_INSTRUCTIONS # Hazards HAZARDS = ['RAW', 'WAR', 'WAW', 'Struct'] # Stages STAGES = ['IF', 'ID', 'EX', 'WB'] # Floating Point functional units FP_UNITS = ['FP_ADD', 'FP_MUL', 'FP_DIV'] # Some computer constants DATA_MEMORY_BASE_ADDRESS = 256 WORD_SIZE = 4 # Cache constants CACHE_BLOCK_SIZE = 4 NUMBER_OF_CACHE_BLOCKS = 4 NUMBER_OF_CACHE_SETS = 2 # State of the computer and program DATA = {} INSTRUCTIONS = [] LABEL = {} REGISTERS = {'PC': 0, 'CLEAN': False} REGISTER_FLAG = {} STAGE_FLAG = { 'IF': AVAILABLE, 'ID': AVAILABLE, 'IU': AVAILABLE, 'MEM': AVAILABLE, 'FP_ADD': AVAILABLE, 'FP_MUL': AVAILABLE, 'FP_DIV': AVAILABLE, 'WB': AVAILABLE, 'IBUS': AVAILABLE, 'DBUS': AVAILABLE } # Formatting constants INSTRUCTION_LEFT_JUSTIFY = 30 <file_sep>/pipeline_stage.py """ Execution details for all the pipeline stages. """ from computer import * from instruction_cache import * from data_cache import * class Pipeline_Stage(): """ Parent class for the pipeline stages. """ def __init__(self, instruction): """ Initialize the pipeline stage. """ self.instruction = instruction self.hazards = {} for hazard in HAZARDS: self.hazards[hazard] = False <file_sep>/pipeline_decode_stage.py from computer import * from instruction_cache import * from data_cache import * from pipeline_stage import * from pipeline_execute_stage import * class Decode_Stage(Pipeline_Stage): """ Class for instruction decode stage. """ def __init__(self, instruction): """ Initialize the instruction decode stage. """ Pipeline_Stage.__init__(self, instruction) self.name = 'ID' def execute(self, instruction): """ Execute the instruction decode stage. """ STAGE_FLAG[self.name] = OCCUPIED def proceed(self): """ Proceed in the instruction decode stage. """ exec_functional_unit = self.instruction.determine_exec_functional_unit() self.discover_hazards(exec_functional_unit) if ((exec_functional_unit == 'NO_UNIT') and (not self.check_hazard(exec_functional_unit))): self.perform_branch_instruction() STAGE_FLAG[self.name] = AVAILABLE return None if (not self.check_hazard(exec_functional_unit)): STAGE_FLAG[self.name] = AVAILABLE return self.select_execution_stage(exec_functional_unit) return self def discover_hazards(self, exec_functional_unit): """ Discover the hazards in the instruction decode stage. """ if (not self.check_hazard(exec_functional_unit)): return self.hazards['Struct'] = False if ((exec_functional_unit != 'NO_UNIT') and (STAGE_FLAG[exec_functional_unit] == OCCUPIED)): self.hazards['Struct'] = True self.hazards['RAW'] = False for register in self.instruction.srcRegs: if (REGISTER_FLAG[register] == OCCUPIED): self.hazards['RAW'] = True self.hazards['WAW'] = False if ((self.instruction.destReg != '') and (REGISTER_FLAG[self.instruction.destReg] == OCCUPIED)): self.hazards['WAW'] = True def check_hazard(self, exec_functional_unit): """ Check is there is a hazardous situation. """ for register in self.instruction.srcRegs: if (REGISTER_FLAG[register] == OCCUPIED): return True if ((self.instruction.destReg != '') and (REGISTER_FLAG[self.instruction.destReg] == OCCUPIED)): return True if ((exec_functional_unit != 'NO_UNIT') and (STAGE_FLAG[exec_functional_unit] == OCCUPIED)): return True return False def perform_branch_instruction(self): """ Update the program counter from the branch instruction. """ if (self.instruction.name == 'j'): REGISTERS['PC'] = self.instruction.imm / WORD_SIZE REGISTERS['CLEAN'] = True return if ((self.instruction.name == 'beq') and (REGISTERS[self.instruction.srcRegs[0]] == REGISTERS[self.instruction.srcRegs[1]])): REGISTERS['PC'] = self.instruction.imm / WORD_SIZE REGISTERS['CLEAN'] = True return if ((self.instruction.name == 'bne') and (REGISTERS[self.instruction.srcRegs[0]] != REGISTERS[self.instruction.srcRegs[1]])): REGISTERS['PC'] = self.instruction.imm / WORD_SIZE REGISTERS['CLEAN'] = True def select_execution_stage(self, exec_functional_unit): """ Select the instruction execution stage. """ if (exec_functional_unit == 'FP_ADD'): return FP_Adder_Stage(self.instruction) elif (exec_functional_unit == 'FP_MUL'): return FP_Multiplier_Stage(self.instruction) elif (exec_functional_unit == 'FP_DIV'): return FP_Divider_Stage(self.instruction) else: return Execute_Stage(self.instruction) <file_sep>/instruction_organizer.py """ Organizes the Active Instruction Container Queue. """ from collections import deque from computer import * from instruction_container import * import operator class Instruction_Organizer(): """ Class to organize the instruction container queue. """ @classmethod def organize(self, old_instruction_containers): """ Organize instructions in WB - EX - ID - IF manner. """ new_instruction_containers = deque([]) for i in range(len(old_instruction_containers)): ic = old_instruction_containers.pop() if ic.current_pipeline_stage.name == 'WB': new_instruction_containers.appendleft(ic) else: old_instruction_containers.appendleft(ic) exe_instruction_containers = deque([]) for i in range(len(old_instruction_containers)): ic = old_instruction_containers.pop() if ic.current_pipeline_stage.name == 'EX': exe_instruction_containers.appendleft(ic) else: old_instruction_containers.appendleft(ic) new_instruction_containers = self.write_back_organize(new_instruction_containers, exe_instruction_containers) for i in range(len(old_instruction_containers)): ic = old_instruction_containers.pop() if ic.current_pipeline_stage.name == 'ID': new_instruction_containers.appendleft(ic) else: old_instruction_containers.appendleft(ic) for i in range(len(old_instruction_containers)): ic = old_instruction_containers.pop() if ic.current_pipeline_stage.name == 'IF': new_instruction_containers.appendleft(ic) else: old_instruction_containers.appendleft(ic) return new_instruction_containers @classmethod def write_back_organize(self, new_instruction_containers, exe_instruction_containers): """ Organize the instruction containers in execution stage. """ exec_priority = {} counter = LIMIT for i in range(len(exe_instruction_containers)): exec_ic = exe_instruction_containers.pop() functional_unit = exec_ic.instruction.determine_exec_functional_unit() is_fp_flag = False for fu in FP_UNITS: if (functional_unit == fu): if (FP_CONFIG[fu]['PIPELINED']): exec_priority[exec_ic] = counter + FP_CONFIG[fu]['CYCLES'] else: exec_priority[exec_ic] = counter + FP_CONFIG[fu]['CYCLES'] + LIMIT is_fp_flag = True break if (not is_fp_flag): exec_priority[exec_ic] = counter counter -= 1 sorted_ic = sorted(exec_priority.iteritems(), key=operator.itemgetter(1), reverse=True) for ic in sorted_ic: new_instruction_containers.appendleft(ic[0]) return new_instruction_containers <file_sep>/printer.py """ Class that provides functionality to print to the files. """ from computer import * from data_cache import * from instruction_cache import * from utils import * class Printer(): """ Class for printing to the file. """ @classmethod def print_output(self, fileName, output): """ Print the final output. """ result = sorted(output, key=lambda o: o.cycles[STAGES[0]]) result[len(result) - 1].cycles[STAGES[1]] = 0 string = 'instruction'.ljust(INSTRUCTION_LEFT_JUSTIFY) for stage in STAGES: string += '\t' + stage + '\t' for hazard in HAZARDS: string += '\t' + hazard + '\t' string += '\n' for i in range(len(result)): string += str(result[i]) + '\n' string += '\nTotal number of requests to instruction cache ' + str(Instruction_Cache.requests) string += '\nTotal number of instruction cache hit ' + str(Instruction_Cache.hits) string += '\nTotal number of requests to data cache ' + str(Data_Cache.requests) string += '\nTotal number of data cache hit ' + str(Data_Cache.hits) writeString(fileName, string) #print string <file_sep>/instruction_cache.py """ Details of the instruction cache. """ from computer import * from memory_cache_block import * class Instruction_Cache(): """ Class for the instruction cache. """ cache_block = [] requests = 0 hits = 0 def __init__(self): """ Initialize the instruction cache. """ for id in range(NUMBER_OF_CACHE_BLOCKS): Instruction_Cache.cache_block.append(Cache_Block(id, CACHE_BLOCK_SIZE)) @classmethod def read(self, location): """ Read instruction at location. """ Instruction_Cache.requests += 1 tag = location >> 6 block_id = (location >> NUMBER_OF_CACHE_BLOCKS) % CACHE_BLOCK_SIZE if ((Instruction_Cache.cache_block[block_id].valid_bit == True) and (Instruction_Cache.cache_block[block_id].tag == tag)): Instruction_Cache.hits += 1 return HIT, ACCESS_TIME['ICACHE'] else: Instruction_Cache.cache_block[block_id].tag = tag Instruction_Cache.cache_block[block_id].valid_bit = True return MISS, 2 * (ACCESS_TIME['MEMORY'] + ACCESS_TIME['ICACHE']) <file_sep>/simulator-1.py #! /usr/bin/python from collections import deque import re import sys DATA_BASE_ADDRESS = 100 INST_BASE_ADDRESS = 0 INSTRUCTION_SEGMENT_BASE = 0 INTEGER_EXEC_CYCLES = 1 REG_FILE_SIZE = 32 WORD_SIZE = 4 # Utility Funtions def readLines(fileName): f = open(fileName, 'r') lines = [line for line in f] f.close() return lines def bitsToVal(bits): val = 0 pos = 2**31 for i in range(len(bits)): if bits[i] == '1': val += pos pos /= 2 return val # ----- class InstructionMemory(): def __init__(self, instFile, baseAddress): self.baseAddress = baseAddress self.instructionSize = WORD_SIZE self.instructions = {} self.labels = {} self.parseInstructions(instFile) def __repr__(self): instructions = "" for counter in sorted(self.instructions.keys()): instructions = instructions + str(counter) + " : " + str(self.instructions[counter]) + "\n" labels = "" for label in self.labels.keys(): labels = labels + label + " : " + str(self.labels[label]) + "\n" return "\n* InstructionMemory *\nBase Address: %s\nInstructions:\n%sLabels:\n%s" % (self.baseAddress, instructions, self.labels) def parseInstructions(self, instFile): counter = self.baseAddress lines = readLines(instFile) for line in lines: pattern = re.compile('[,\s\n]+') instruction = pattern.split(line.strip()) if (instruction[0][-1] == ':'): # This is a label instruction self.labels[instruction[0][0:-1].lower()] = counter for i in range(len(instruction)): instruction[i] = instruction[i].lower() self.instructions[counter] = instruction counter += self.instructionSize def readInstAt(self, addr): if (self.instructions.has_key(addr)): return self.instructions[addr] return None class DataMemory(): def __init__(self, dataFile, baseAddress): self.baseAddress = baseAddress self.dataSize = WORD_SIZE self.data = {} self.parseData(dataFile) def __repr__(self): data = "" for counter in sorted(self.data.keys()): data = data + str(counter) + " : " + str(self.data[counter]) + "\n" return "\n* DataMemory *\nBase Address: %s\nData: \n%s" % (self.baseAddress, data) def parseData(self, dataFile): counter = self.baseAddress lines = readLines(dataFile) for line in lines: self.data[counter] = bitsToVal(line) counter += self.dataSize class Memory(): def __init__(self, instFile, dataFile): self.instMem = InstructionMemory(instFile, INST_BASE_ADDRESS) self.dataMem = DataMemory(dataFile, DATA_BASE_ADDRESS) def __repr__(self): return "\n* Memory *\n%s\n%s" % (self.instMem, self.dataMem) def readInstAt(self, addr): return self.instMem.readInstAt(addr) class Instruction(object): def __init__(self, name): self.name = name self.raw = False self.war = False self.waw = False self.struct = False self.entryCycle = [0]*4 self.exitCycle = [0]*4 self.currentUnit = 'No' self.currentSubUnit = -1 self.hasRead = False def __repr__(self): raw = "N" war = "N" waw = "N" struct = "N" if (self.raw == True): raw = "Y" if (self.war == True): war = "Y" if (self.waw == True): waw = "Y" if (self.struct == True): struct = "Y" #return "\t\t%s %s %s %s %s %s %s %s" % (self.exitCycle[0], self.exitCycle[1], self.exitCycle[2], self.exitCycle[3], raw, war, waw, struct) return "\t\t[%s-%s]\t\t%s,%s %s,%s %s,%s %s,%s %s %s %s %s" % (self.currentUnit, self.currentSubUnit, self.entryCycle[0],self.exitCycle[0], self.entryCycle[1],self.exitCycle[1], self.entryCycle[2],self.exitCycle[2], self.entryCycle[3],self.exitCycle[3], raw, war, waw, struct) def enterFetch(self, clock, cpu): self.currentUnit = 'Fet' self.currentSubUnit = 1 self.entryCycle[0] = clock cpu.fetch.isBusy = True def exitFetch(self, clock, cpu): self.exitCycle[0] = clock - 1 cpu.fetch.isBusy = False def enterIU(self, clock, cpu): self.currentUnit = 'IU' self.currentSubUnit = 1 self.entryCycle[2] = clock cpu.alu.intUnit.isBusy = True def exitIU(self, clock, cpu): cpu.alu.intUnit.isBusy = False def enterMem(self, clock, cpu): self.currentUnit = 'Mem' self.currentSubUnit = 1 cpu.alu.memUnit.isBusy = True def exitMem(self, clock, cpu): self.exitCycle[2] = clock - 1 cpu.alu.memUnit.isBusy = False def enterWB(self, clock, cpu): self.currentUnit = 'WB' self.currentSubUnit = 1 self.entryCycle[3] = clock cpu.writeback.isBusy = True def update(self, clock, cpu): if (self.currentUnit == 'No'): if (cpu.fetch.isBusy): self.struct |= True else: self.enterFetch(clock, cpu) return False if (self.currentUnit == 'Fet'): if (self.currentSubUnit == cpu.fetch.execCycles): if (cpu.decode.isBusy): self.struct |= True else: self.exitFetch(clock, cpu) self.enterDecode(clock, cpu) else: self.currentSubUnit += 1 return False if (self.currentUnit == 'Dec'): if (not self.hasRead): if (not self.tryRead(cpu)): return False if (self.currentSubUnit == cpu.decode.execCycles): if (cpu.alu.intUnit.isBusy): self.struct |= True else: self.exitDecode(clock, cpu) self.enterIU(clock, cpu) else: self.currentSubUnit += 1 return False if (self.currentUnit == 'IU'): if (self.currentSubUnit == cpu.alu.intUnit.execCycles): if (cpu.alu.memUnit.isBusy): self.struct |= True else: self.exitIU(clock, cpu) self.enterMem(clock, cpu) else: self.currentSubUnit += 1 return False if (self.currentUnit == 'Mem'): if (self.currentSubUnit == cpu.alu.memUnit.execCycles): if (cpu.writeback.isBusy): self.struct |= True else: self.exitMem(clock, cpu) self.enterWB(clock, cpu) else: self.currentSubUnit += 1 return False if (self.currentUnit == 'WB'): if (self.currentSubUnit == cpu.writeback.execCycles): self.exitWB(clock, cpu) return True else: self.currentSubUnit += 1 return False class DestRegInstruction(Instruction): def __init__(self, name, destName): Instruction.__init__(self, name) self.destName = destName self.destVal = 0 def exitWB(self, clock, cpu): self.exitCycle[3] = clock - 1 cpu.writeback.isBusy = False cpu.registerFile.registers[self.destName].isBusy = False #print "Marked " + self.destName + " " + str(cpu.registerFile.registers[self.destName].isBusy) class ThreeRegInstruction(DestRegInstruction): def __init__(self, name, destName, src1Name, src2Name): DestRegInstruction.__init__(self, name, destName) self.src1Name = src1Name self.src2Name = src2Name self.src1Val = 0 self.src2Val = 0 def __repr__(self): return "%s %s, %s, %s %s" % (self.name, self.destName, self.src1Name, self.src2Name, Instruction.__repr__(self)) def tryRead(self, cpu): print self.destName, cpu.registerFile.registers[self.destName].isBusy, self.src1Name, cpu.registerFile.registers[self.src1Name].isBusy, self.src2Name, cpu.registerFile.registers[self.src2Name].isBusy, "hasread", self.hasRead if (self.hasRead): return True if (not (cpu.registerFile.registers[self.destName].isBusy) and not (cpu.registerFile.registers[self.src1Name].isBusy) and not (cpu.registerFile.registers[self.src2Name].isBusy)): cpu.registerFile.registers[self.destName].isBusy = True self.src1Val = cpu.registerFile.registers[self.src1Name].val self.src2Val = cpu.registerFile.registers[self.src2Name].val self.hasRead = True print "in if" else: print "in else" self.raw += True return not self.hasRead def enterDecode(self, clock, cpu): self.currentUnit = 'Dec' self.currentSubUnit = 1 self.entryCycle[1] = clock cpu.decode.isBusy = True ret = self.tryRead(cpu) def exitDecode(self, clock, cpu): self.exitCycle[1] = clock - 1 cpu.decode.isBusy = False class DADD(ThreeRegInstruction): def __init__(self, name, destName, src1Name, src2Name): ThreeRegInstruction.__init__(self, name, destName, src1Name, src2Name) def executeInst(self): self.destVal = self.src1Val + self.src2Val class DSUB(ThreeRegInstruction): def __init__(self, name, destName, src1Name, src2Name): ThreeRegInstruction.__init__(self, name, destName, src1Name, src2Name) def executeInst(self): self.destVal = self.src1Val - self.src2Val class ADDD(ThreeRegInstruction): def __init__(self, name, destName, src1Name, src2Name): ThreeRegInstruction.__init__(self, name, destName, src1Name, src2Name) def executeInst(self): self.destVal = self.src1Val + self.src2Val class SUBD(ThreeRegInstruction): def __init__(self, name, destName, src1Name, src2Name): ThreeRegInstruction.__init__(self, name, destName, src1Name, src2Name) def executeInst(self): self.destVal = self.src1Val - self.src2Val class MULD(ThreeRegInstruction): def __init__(self, name, destName, src1Name, src2Name): ThreeRegInstruction.__init__(self, name, destName, src1Name, src2Name) def executeInst(self): self.destVal = self.src1Val * self.src2Val class DIVD(ThreeRegInstruction): def __init__(self, name, destName, src1Name, src2Name): ThreeRegInstruction.__init__(self, name, destName, src1Name, src2Name) def executeInst(self): self.destVal = self.src1Val / self.src2Val class AND(ThreeRegInstruction): def __init__(self, name, destName, src1Name, src2Name): ThreeRegInstruction.__init__(self, name, destName, src1Name, src2Name) def executeInst(self): self.destVal = self.src1Val and self.src2Val class OR(ThreeRegInstruction): def __init__(self, name, destName, src1Name, src2Name): ThreeRegInstruction.__init__(self, name, destName, src1Name, src2Name) def executeInst(self): self.destVal = self.src1Val or self.src2Val class TwoRegOneImmInstruction(DestRegInstruction): def __init__(self, name, destName, srcName, imm): DestRegInstruction.__init__(self, name, destName) self.srcName = srcName self.srcVal = 0 self.imm = imm def __repr__(self): return "%s %s, %s, %s %s" % (self.name, self.destName, self.srcName, self.imm, Instruction.__repr__(self)) def tryRead(self, cpu): print self.destName, cpu.registerFile.registers[self.destName].isBusy, self.srcName, cpu.registerFile.registers[self.srcName].isBusy if (self.hasRead): return True if (not (cpu.registerFile.registers[self.destName].isBusy) and not (cpu.registerFile.registers[self.srcName].isBusy)): cpu.registerFile.registers[self.destName].isBusy = True self.srcVal = cpu.registerFile.registers[self.srcName].val self.hasRead = True else: self.raw += True return not self.hasRead def enterDecode(self, clock, cpu): self.currentUnit = 'Dec' self.currentSubUnit = 1 self.entryCycle[1] = clock cpu.decode.isBusy = True ret = self.tryRead(cpu) def exitDecode(self, clock, cpu): self.exitCycle[1] = clock - 1 cpu.decode.isBusy = False class DADDI(TwoRegOneImmInstruction): def __init__(self, name, destName, srcName, imm): TwoRegOneImmInstruction.__init__(self, name, destName, srcName, imm) def executeInst(self): self.destVal = self.srcVal + self.immVal class DSUBI(TwoRegOneImmInstruction): def __init__(self, name, destName, srcName, imm): TwoRegOneImmInstruction.__init__(self, name, destName, srcName, imm) def executeInst(self): self.destVal = self.srcVal - self.immVal class ANDI(TwoRegOneImmInstruction): def __init__(self, name, destName, srcName, imm): TwoRegOneImmInstruction.__init__(self, name, destName, srcName, imm) def executeInst(self): self.destVal = self.srcVal and self.immVal class ORI(TwoRegOneImmInstruction): def __init__(self, name, destName, srcName, imm): TwoRegOneImmInstruction.__init__(self, name, destName, srcName, imm) def executeInst(self): self.destVal = self.srcVal or self.immVal class LW(TwoRegOneImmInstruction): def __init__(self, name, destName, srcName, imm): TwoRegOneImmInstruction.__init__(self, name, destName, srcName, imm) def __repr__(self): return "%s %s, %s(%s) %s" % (self.name, self.destName, self.imm, self.srcName, Instruction.__repr__(self)) class LD(TwoRegOneImmInstruction): def __init__(self, name, destName, srcName, imm): TwoRegOneImmInstruction.__init__(self, name, destName, srcName, imm) def __repr__(self): return "%s %s, %s(%s) %s" % (self.name, self.destName, self.imm, self.srcName, Instruction.__repr__(self)) class SW(TwoRegOneImmInstruction): def __init__(self, name, destName, srcName, imm): TwoRegOneImmInstruction.__init__(self, name, destName, srcName, imm) def execute(self): #self.destVal = Mem[self.immVal + self.srcVal] pass class SD(TwoRegOneImmInstruction): def __init__(self, name, destName, srcName, imm): TwoRegOneImmInstruction.__init__(self, name, destName, srcName, imm) def execute(self): #self.destVal = Mem[self.immVal + self.srcVal] pass class Branch(Instruction): def __init__(self, name, label): Instruction.__init__(self, name) self.label = label class J(Branch): def __init__(self, name, label): Branch.__init__(self, name, label) def __repr__(self): return "%s %s %s" % (self.name, self.label, Instruction.__repr__(self)) def execute(self): #update pc to label pass class ConditionalBranch(Branch): def __init__(self, name, src1Name, src2Name, label): Branch.__init__(self, name, label) self.src1Name = src1Name self.src2Name = src2Name self.src1 = 0 self.src2 = 0 def __repr__(self): return "%s %s, %s, %s %s" % (self.name, self.src1Name, self.src2Name, self.label, Instruction.__repr__(self)) class BEQ(ConditionalBranch): def __init__(self, name, src1Name, src2Name, label): ConditionalBranch.__init__(self, name, src1Name, src2Name, label) def executeInst(self): # update pc is eq pass class BNE(ConditionalBranch): def __init__(self, name, src1Name, src2Name, label): ConditionalBranch.__init__(self, name, src1Name, src2Name, label) def executeInst(self): # update pc is ne pass class HLT(Instruction): def __init__(self, name): Instruction.__init__(self, name) def __repr__(self): return "%s %s" % (self.name, Instruction.__repr__(self)) def execute(self): pass class Register(): def __init__(self, val, isBusy): self.val = val self.isBusy = isBusy def __repr__(self): return "\nValue: %s\nBusy: %s" % (self.val, self. isBusy) class RegisterFile(): def __init__(self, regFile): self.regFileSize = REG_FILE_SIZE self.registers = {} self.parseRegisters(regFile) def __repr__(self): registers = "" for regName, reg in self.registers.items(): registers = registers + "Name: " + regName + "\n" + str(reg) + "\n" return "\n* RegisterFile *\n%s" % (registers) def parseRegisters(self, regFile): lines = readLines(regFile) count = 0 for line in lines: self.registers['r'+str(count)] = Register(bitsToVal(line), False) self.registers['f'+str(count)] = Register(0, False) count += 1 class Unit(): def __init__(self, name, cycles, isPipelined, unitId): self.name = name self.execCycles = int(cycles) self.pipelineSize = 1 if (isPipelined): self.pipelineSize = self.execCycles self.isBusy = False self.isPipelined = isPipelined self.instQ = deque([Instruction("noop")]*self.pipelineSize) self.unitId = unitId def __repr__(self): return "\n* %s *\nCycles: %s\nPipeLine Size: %s\nPipelined: %s" % (self.name, self.execCycles, self.pipelineSize, self.isPipelined) def execute(self, instruction, cycle): instruction.entryCycle[self.unitId] = cycle self.isBusy = True if not (self.isPipelined): instruction.exitCycle[self.unitId] = cycle + self.execCycles - 1 self.isBusy = False # May need to seperate IntegerUnit and FPUnits class ALU(): def __init__(self, configFile): lines = readLines(configFile) self.intUnit = Unit("IntegerUnit", INTEGER_EXEC_CYCLES, False, 2) for line in lines: pattern = re.compile('[\s:,\n]+') vals = pattern.split(line.strip()) if (vals[0].lower() == "fp"): isPipe = True if (vals[3].lower().replace('\n','') != "yes"): isPipe = False if (vals[1].replace(':','').lower() == "adder"): self.floatAddUnit = Unit("FPAdder", vals[2].replace(',',''), isPipe, 2) if (vals[1].replace(':','').lower() == "multiplier"): self.floatMulUnit = Unit("FPMultiplier", vals[2].replace(',',''), isPipe, 2) if (vals[1].replace(':','').lower() == "divider"): self.floatDivUnit = Unit("FPDivider", vals[2].replace(',',''), isPipe, 2) if (vals[0].lower() == "main"): self.memUnit = Unit("MemoryUnit", vals[2].replace('\n',''), False, 2) def __repr__(self): return "\n* ALU *\n%s\n%s\n%s\n%s\n%s" % (self.intUnit, self.memUnit, self.floatAddUnit, self.floatMulUnit, self.floatDivUnit) class CPU(): def __init__(self, regFile, configFile): self.registerFile = RegisterFile(regFile) self.fetch = Unit("Fetch", 1, False, 0) self.decode = Unit("Decode", 1, False, 1) self.alu = ALU(configFile) self.writeback = Unit("WriteBack", 1, False, 3) def __repr__(self): return "\n* CPU *\n%s%s" % (self.registerFile, self.alu) def execute(self, instruction, clock): self.fetch.execute(instruction, clock) class Computer(): def __init__(self, instFile, dataFile, regFile, configFile): self.pc = INSTRUCTION_SEGMENT_BASE self.memory = Memory(instFile, dataFile) self.cpu = CPU(regFile, configFile) self.clock = 0 def __repr__(self): return "* Computer *\nProgram Counter: %s\n%s%s\n" % (self.pc, self.memory, self.cpu) def getInstInstance(self, instruction): zero = 0 if (instruction[0][-1] == ':'): zero = 1 else: zero = 0 if (instruction[zero] == 'lw'): return LW(instruction[zero], instruction[zero+1], instruction[zero+2].split('(')[1].split(')')[0], instruction[zero+2].split('(')[0]) if (instruction[zero] == 'sw'): return SW(instruction[zero], instruction[zero+1], instruction[zero+2].split('(')[1].split(')')[0], instruction[zero+2].split('(')[0]) if (instruction[zero] == 'l.d'): return LD(instruction[zero], instruction[zero+1], instruction[zero+2].split('(')[1].split(')')[0], instruction[zero+2].split('(')[0]) if (instruction[zero] == 's.d'): return SD(instruction[zero], instruction[zero+1], instruction[zero+2].split('(')[1].split(')')[0], instruction[zero+2].split('(')[0]) if (instruction[zero] == 'dadd'): return DADD(instruction[zero], instruction[zero+1], instruction[zero+2], instruction[zero+3]) if (instruction[zero] == 'daddi'): return DADDI(instruction[zero], instruction[zero+1], instruction[zero+2], instruction[zero+3]) if (instruction[zero] == 'dsub'): return DSUB(instruction[zero], instruction[zero+1], instruction[zero+2], instruction[zero+3]) if (instruction[zero] == 'dsubi'): return DSUBI(instruction[zero], instruction[zero+1], instruction[zero+2], instruction[zero+3]) if (instruction[zero] == 'and'): return AND(instruction[zero], instruction[zero+1], instruction[zero+2], instruction[zero+3]) if (instruction[zero] == 'andi'): return ANDI(instruction[zero], instruction[zero+1], instruction[zero+2], instruction[zero+3]) if (instruction[zero] == 'or'): return OR(instruction[zero], instruction[zero+1], instruction[zero+2], instruction[zero+3]) if (instruction[zero] == 'ori'): return ORI(instruction[zero], instruction[zero+1], instruction[zero+2], instruction[zero+3]) if (instruction[zero] == 'add.d'): return ADDD(instruction[zero], instruction[zero+1], instruction[zero+2], instruction[zero+3]) if (instruction[zero] == 'sub.d'): return SUBD(instruction[zero], instruction[zero+1], instruction[zero+2], instruction[zero+3]) if (instruction[zero] == 'mul.d'): return MULD(instruction[zero], instruction[zero+1], instruction[zero+2], instruction[zero+3]) if (instruction[zero] == 'div.d'): return DIVD(instruction[zero], instruction[zero+1], instruction[zero+2], instruction[zero+3]) if (instruction[zero] == 'j'): return J(instruction[zero], instruction[zero+1]) if (instruction[zero] == 'beq'): return BEQ(instruction[zero], instruction[zero+1], instruction[zero+2], instruction[zero+3]) if (instruction[zero] == 'bne'): return BNE(instruction[zero], instruction[zero+1], instruction[zero+2], instruction[zero+3]) if (instruction[zero] == 'hlt'): return HLT(instruction[zero]) def reorderInst(self, activeInst): pass def execute(self): instruction = self.getInstInstance(self.memory.readInstAt(self.pc)) activeInst = [instruction] while(len(activeInst) != 0): self.clock += 1 self.reorderInst(activeInst) toRemove = [] for inst in activeInst: if (inst.update(self.clock, self.cpu)): print inst toRemove.append(inst) if not (self.cpu.fetch.isBusy): self.pc += WORD_SIZE instruction = self.memory.readInstAt(self.pc) if (instruction): instruction = self.getInstInstance(instruction) activeInst.append(instruction) for inst in toRemove: activeInst.remove(inst) def main(instFile, dataFile, regFile, configFile, resultFile="result.txt"): computer = Computer(instFile, dataFile, regFile, configFile) #print computer computer.execute() if __name__ == "__main__": nArgs = len(sys.argv) args = sys.argv if (nArgs != 5): print "Usage: simulator inst.txt data.txt reg.txt config.txt result.txt" exit() main(args[1], args[2], args[3], args[4]) <file_sep>/instruction_container.py """ Wrapper that wraps the instruction for passing between the stages in the pipeline. """ from computer import * from output import * import pipeline_fetch_stage class Instruction_Container(): """ Container for the instruction and its state. """ def __init__(self, instruction, clock_cycle): """ Initialize the container. """ self.current_pipeline_stage = pipeline_fetch_stage.Fetch_Stage(instruction) self.instruction = instruction self.current_pipeline_stage.execute(self.instruction) self.output = Output(instruction, clock_cycle) def __str__(self): """ Represent the instruction container as string. """ return "\nInstruction:%s\nOutput:%s" % (self.instruction, self.output) def keep_executing(self): """ Continue the execution in the same stage or enter the next stage. """ prev_pipeline_stage = self.current_pipeline_stage self.current_pipeline_stage = prev_pipeline_stage.proceed() if (self.current_pipeline_stage != prev_pipeline_stage): for hazard in HAZARDS: self.output.hazards[hazard] |= prev_pipeline_stage.hazards[hazard] if (self.current_pipeline_stage == None): return False self.increment_cycles(prev_pipeline_stage) self.current_pipeline_stage.execute(self.instruction) return True def increment_cycles(self, prev_pipeline_stage): """ Increment the pipeline stage cycles of the instruction. """ for i in range(len(STAGES)-1): if ((prev_pipeline_stage.name == STAGES[i]) and (self.current_pipeline_stage.name == STAGES[i])): self.output.cycles[STAGES[i]] += 1 elif ((prev_pipeline_stage.name == STAGES[i]) and (self.current_pipeline_stage.name == STAGES[i+1])): self.output.cycles[STAGES[i+1]] = self.output.cycles[STAGES[i]] + 1 <file_sep>/config.py """ Stores the configuration details. """ ACCESS_TIME = {} FP_CONFIG = { 'FP_ADD': {'CYCLES': 4, 'PIPELINED': False}, 'FP_MUL': {'CYCLES': 6, 'PIPELINED': False}, 'FP_DIV': {'CYCLES': 20, 'PIPELINED': False} } <file_sep>/pipeline_execute_stage.py from computer import * from instruction_cache import * from data_cache import * from pipeline_stage import * from pipeline_writeback_stage import * class Execute_Stage(Pipeline_Stage): """ Class for Integer execution stage. """ def __init__(self, instruction): """ Initialize the integer pipeline stage. """ Pipeline_Stage.__init__(self, instruction) self.name = 'EX' def execute(self, instruction): """ Execute the interger unit stage. """ if (STAGE_FLAG['IU'] == AVAILABLE): self.occupy_dest_register() self.operate() STAGE_FLAG['IU'] = OCCUPIED def proceed(self): """ Proceed in the integer unit stage. """ if (STAGE_FLAG['MEM'] == AVAILABLE): STAGE_FLAG['IU'] = AVAILABLE return Memory_Stage(self.instruction) self.hazards['Struct'] = True return self def occupy_dest_register(self): """ Occupy the destination register. """ if (self.instruction.destReg != ''): REGISTER_FLAG[self.instruction.destReg] = OCCUPIED def operate(self): """ Perform the integer operation. """ if (self.instruction.name == 'dadd'): REGISTERS[self.instruction.destReg] = REGISTERS[self.instruction.srcRegs[0]] + REGISTERS[self.instruction.srcRegs[1]] elif (self.instruction.name == 'daddi'): REGISTERS[self.instruction.destReg] = REGISTERS[self.instruction.srcRegs[0]] + int(self.instruction.imm) elif (self.instruction.name == 'dsub'): REGISTERS[self.instruction.destReg] = REGISTERS[self.instruction.srcRegs[0]] - REGISTERS[self.instruction.srcRegs[1]] elif (self.instruction.name == 'dsubi'): REGISTERS[self.instruction.destReg] = REGISTERS[self.instruction.srcRegs[0]] - int(self.instruction.imm) elif (self.instruction.name == 'and'): REGISTERS[self.instruction.destReg] = REGISTERS[self.instruction.srcRegs[0]] & REGISTERS[self.instruction.srcRegs[1]] elif (self.instruction.name == 'andi'): REGISTERS[self.instruction.destReg] = REGISTERS[self.instruction.srcRegs[0]] & int(self.instruction.imm) elif (self.instruction.name == 'or'): REGISTERS[self.instruction.destReg] = REGISTERS[self.instruction.srcRegs[0]] | REGISTERS[self.instruction.srcRegs[1]] elif (self.instruction.name == 'ori'): REGISTERS[self.instruction.destReg] = REGISTERS[self.instruction.srcRegs[0]] | int(self.instruction.imm) class Memory_Stage(Execute_Stage): """ Class for memory stage of pipepline. """ bus_access_flag = False def __init__(self, instruction): """ Initialize the pipeline memory stage. """ Execute_Stage.__init__(self, instruction) self.wait_for_ibus = False self.word_hit = [True, True] self.word_cycles = self.calculate_required_memory_cycles() def execute(self, instruction): """ Execute the memory stage. """ if (not self.wait_for_ibus): if (not self.word_hit[0]): Memory_Stage.bus_access_flag = True self.wait_for_ibus = True if ((not self.word_hit[1]) and (self.word_cycles[0] == 0)): Memory_Stage.bus_access_flag = True self.wait_for_ibus = True else: Memory_Stage.bus_access_flag = False if ((Memory_Stage.bus_access_flag) and (STAGE_FLAG['IBUS'] == OCCUPIED)): if (not self.word_hit[0]): self.word_cycles[0] -= 1 elif (not self.word_hit[1]): self.word_cycles[1] -= 1 if (self.word_cycles[0] == 0): if ((not self.word_hit[1]) and (STAGE_FLAG['IBUS'] == AVAILABLE)): STAGE_FLAG['DBUS'] = OCCUPIED if ((self.word_hit[1]) or (STAGE_FLAG['DBUS'] == OCCUPIED)): self.word_cycles[1] -= 1 STAGE_FLAG['MEM'] = OCCUPIED if ((not self.word_hit[0]) and (STAGE_FLAG['IBUS'] == AVAILABLE) and (self.word_cycles[0] > 0)): STAGE_FLAG['DBUS'] = OCCUPIED if (((self.word_hit[0]) or (STAGE_FLAG['DBUS'] == OCCUPIED)) and (self.word_cycles[0] > 0)): self.word_cycles[0] -= 1 def proceed(self): """ Proceed in the memory stage. """ if ((not self.word_hit[0]) and (self.word_cycles[0] == 0) and (self.word_hit[1])): STAGE_FLAG['DBUS'] = AVAILABLE if ((not self.word_hit[1]) and (self.word_cycles[1] == 0)): STAGE_FLAG['DBUS'] = AVAILABLE if (self.word_cycles[1] < 0): self.hazards['Struct'] = True if (((self.word_cycles[0] + self.word_cycles[1]) <= 0) and (STAGE_FLAG['WB'] == AVAILABLE)): STAGE_FLAG['MEM'] = AVAILABLE return WriteBack_Stage(self.instruction) return self def calculate_required_memory_cycles(self): """ Calculate the address and the memory cycles required """ if (self.instruction.name == 'lw'): location = int(self.instruction.offset) + REGISTERS[self.instruction.srcRegs[0]] self.word_hit[0], REGISTERS[self.instruction.destReg], cycles = Data_Cache.read(location) return [cycles, 0] elif (self.instruction.name == 'l.d'): time_to_read = [0, 0] location = int(self.instruction.offset) + REGISTERS[self.instruction.srcRegs[0]] self.word_hit[0], word, time_to_read[0] = Data_Cache.read(location) self.word_hit[1], word, time_to_read[1] = Data_Cache.read(location + WORD_SIZE) return time_to_read elif (self.instruction.name == 'sw'): location = int(self.instruction.offset) + REGISTERS[self.instruction.srcRegs[1]] self.word_hit[0], cycles = Data_Cache.write(location, REGISTERS[self.instruction.srcRegs[0]]) return [cycles, 0] elif (self.instruction.name == 's.d'): time_to_write = [0, 0] location = int(self.instruction.offset) + REGISTERS[self.instruction.srcRegs[1]] self.word_hit[0], time_to_write[0] = Data_Cache.write(location, 0, False) self.word_hit[1], time_to_write[1] = Data_Cache.write(location + WORD_SIZE, 0, False) return time_to_write return [1, 0] from computer import * from instruction_cache import * from data_cache import * from pipeline_writeback_stage import * from pipeline_execute_stage import * class FP_Adder_Stage(Execute_Stage): """ Class for FP Adder stage. """ def __init__(self, instruction): """ Initialize FP Adder stage. """ Execute_Stage.__init__(self, instruction) self.clock_cycles = FP_CONFIG['FP_ADD']['CYCLES'] def execute(self, instruction): """ Execute the FP Adder stage. """ if (self.clock_cycles == FP_CONFIG['FP_ADD']['CYCLES']): self.occupy_dest_register() STAGE_FLAG['FP_ADD'] = OCCUPIED self.clock_cycles -= 1 def proceed(self): """ Proceed in the FP Adder stage execution. """ if (self.clock_cycles < 0): self.hazards['Struct'] = True if FP_CONFIG['FP_ADD']['PIPELINED']: STAGE_FLAG['FP_ADD'] = AVAILABLE if ((self.clock_cycles <= 0) and (STAGE_FLAG['WB'] == AVAILABLE)): STAGE_FLAG['FP_ADD'] = AVAILABLE return WriteBack_Stage(self.instruction) return self class FP_Multiplier_Stage(Execute_Stage): """ Class for FP Multiplier stage. """ def __init__(self, instruction): """ Initialize FP Multiplier stage. """ Execute_Stage.__init__(self, instruction) self.clock_cycles = FP_CONFIG['FP_MUL']['CYCLES'] def execute(self, instruction): """ Execute FP Multiplier stage. """ if (self.clock_cycles == FP_CONFIG['FP_MUL']['CYCLES']): self.occupy_dest_register() STAGE_FLAG['FP_MUL'] = OCCUPIED self.clock_cycles -= 1 def proceed(self): """ Proceed in the FP Multiplier stage execution. """ if (self.clock_cycles < 0): self.hazards['Struct'] = True if (FP_CONFIG['FP_MUL']['PIPELINED']): STAGE_FLAG['FP_MUL'] = AVAILABLE if ((self.clock_cycles <= 0) and (STAGE_FLAG['WB'] == AVAILABLE)): STAGE_FLAG['FP_MUL'] = AVAILABLE return WriteBack_Stage(self.instruction) return self class FP_Divider_Stage(Execute_Stage): """ Class for FP Divider stage. """ def __init__(self, instruction): """ Initialize FP Divider stage. """ Execute_Stage.__init__(self, instruction) self.clock_cycles = FP_CONFIG['FP_DIV']['CYCLES'] def execute(self, instruction): """ Execute FP Divider stage. """ if (self.clock_cycles == FP_CONFIG['FP_DIV']['CYCLES']): self.occupy_dest_register() STAGE_FLAG['FP_DIV'] = OCCUPIED self.clock_cycles -= 1 def proceed(self): """ Proceed in FP Divider stage execution. """ if (self.clock_cycles < 0): self.hazards['Struct'] = True if (FP_CONFIG['FP_DIV']['PIPELINED']): STAGE_FLAG['FP_DIV'] = AVAILABLE if ((self.clock_cycles <= 0) and (STAGE_FLAG['WB'] == AVAILABLE)): STAGE_FLAG['FP_DIV'] = AVAILABLE return WriteBack_Stage(self.instruction) return self <file_sep>/memory_cache_set.py """ Sets of blocks in cache. """ from memory_cache_block import * from computer import * class Cache_Set: """ Class for the cache set. """ def __init__(self, id, size): """ Initialize cache set. """ self.id = 0 self.size = size self.cache_block = [] for i in range(self.size): self.cache_block.append(Cache_Block(i, CACHE_BLOCK_SIZE)) <file_sep>/scanner.py """ Class that provides functionality to scan the files. """ from computer import * from instruction import * from utils import * class Scanner(): """ Class for scanning the files """ @classmethod def scan_instructions(self, fileName): """ Method to scan the instructions from file. """ lines = readLines(fileName) try: for i in range(len(lines)): line = lines[i] line = line.lower().strip() instr = line.split(':') if (len(instr) == 1): # No label present instr = instr[0].strip().split(' ') elif (len(instr) == 2): # 1 label present LABEL[instr[0].strip()] = Instruction.counter * WORD_SIZE instr = instr[1].strip().split(' ') else: raise Exception(': invalid number of labels') # INSTRUCTIONS += Instruction(instr_name, operands) INSTRUCTIONS.append(Instruction(instr[0], filter(None, ''.join(instr[1:]).split(',')))) for instr in INSTRUCTIONS: if (instr.imm in LABEL.keys()): instr.update_imm(LABEL[instr.imm]) elif (instr.get_instruction_type() == 'BRANCH'): raise Exception(': missing label [' + instr.imm + ']') except Exception as e: raise Exception('Invalid instruction' + str(e) + ' [Line ' + str(i+1) +']') @classmethod def scan_data(self, fileName): """ Method to scan the data from the file. """ lines = readLines(fileName) try: data_count = 0 for i in range(len(lines)): line = lines[i] DATA[DATA_MEMORY_BASE_ADDRESS + data_count*WORD_SIZE] = int(line, 2) data_count += 1 except: raise Exception('Invalid data [Line ' + str(i+1) +']') @classmethod def scan_registers(self, fileName): """ Method to scan the registers from the file. """ lines = readLines(fileName) try: register_count = 0 for i in range(len(lines)): line = lines[i] REGISTERS['r'+str(register_count)] = int(line, 2) REGISTER_FLAG['r'+str(register_count)] = AVAILABLE REGISTER_FLAG['f'+str(register_count)] = AVAILABLE register_count += 1 except: raise Exception('Invalid registers [Line ' + str(i+1) +']') @classmethod def fill_FP_configuration(self, FP_UNIT, configs): """ Populate the FU_CONFIG. """ configs = [conf.strip() for conf in configs.split(',')] if (len(configs) !=2): raise Exception(': invalid ' + FP_UNIT + ' parameters') if (int(configs[0]) < 1): raise Exception(': invalid cycle number') if (configs[1] not in ['yes', 'no']): raise Exception(': invalid pipelined value') isPipelined = True if (configs[1] == 'no'): isPipelined = False FP_CONFIG[FP_UNIT] = {'CYCLES': int(configs[0]), 'PIPELINED': isPipelined} @classmethod def scan_configuration(self, fileName): """ Method to scan the configuration from the file. """ lines = readLines(fileName) try: for i in range(len(lines)): line = lines[i] line = line.lower().strip() config_line = line.split(':') if ('fp' in config_line[0]): if ('adder' in config_line[0]): self.fill_FP_configuration('FP_ADD', config_line[1]) elif ('multiplier' in config_line[0]): self.fill_FP_configuration('FP_MUL', config_line[1]) elif ('divider' in config_line[0]): self.fill_FP_configuration('FP_DIV', config_line[1]) else: raise Exception(': invalid FP unit') else: if (int(config_line[1].strip()) < 1): raise Exception(': invalid cycle number') if ('main' in config_line[0] and 'memory' in config_line[0]): ACCESS_TIME['MEMORY'] = int(config_line[1].strip()) elif ('i-cache' in config_line[0]): ACCESS_TIME['ICACHE'] = int(config_line[1].strip()) elif ('d-cache' in config_line[0]): ACCESS_TIME['DCACHE'] = int(config_line[1].strip()) else: raise Exception(': invalid unit') except Exception as e: raise Exception('Invalid config file' + str(e) + ' [Line ' + str(i+1) + ']') <file_sep>/data_cache.py """ Details of the data cache. """ from computer import * from memory_cache_block import * from memory_cache_set import * class Data_Cache(): """ Class for data cache. """ cache_sets = [] cache_block_lru = [0, 0] requests = 0 hits = 0 def __init__(self): """ Initialize data cache. """ for id in range(NUMBER_OF_CACHE_SETS): Data_Cache.cache_sets.append(Cache_Set(id, NUMBER_OF_CACHE_BLOCKS / NUMBER_OF_CACHE_SETS)) @classmethod def read(self, location): """ Read from the location. """ Data_Cache.requests += 1 location -= DATA_MEMORY_BASE_ADDRESS block_id = (location >> NUMBER_OF_CACHE_BLOCKS) % NUMBER_OF_CACHE_SETS read_cycles = 0 for id in range(NUMBER_OF_CACHE_SETS): if Data_Cache.lookup_address_in_set(location, id): Data_Cache.hits += 1 Data_Cache.use_for_lru(block_id, id) return HIT, Data_Cache.cache_sets[id].cache_block[block_id].words[(location & 12) >> NUMBER_OF_CACHE_SETS], ACCESS_TIME['DCACHE'] set_id = Data_Cache.cache_block_lru[block_id] if Data_Cache.cache_sets[set_id].cache_block[block_id].dirty_bit: read_cycles += Data_Cache.memory_write_back(set_id, block_id) Data_Cache.prepare_block(location, set_id) read_cycles += 2* (ACCESS_TIME['MEMORY'] + ACCESS_TIME['DCACHE']) return MISS, Data_Cache.cache_sets[set_id].cache_block[block_id].words[(location & 12) >> NUMBER_OF_CACHE_SETS], read_cycles @classmethod def write(self, location, data, isWritable = True): """ Write to the data cache. """ Data_Cache.requests += 1 location -= DATA_MEMORY_BASE_ADDRESS block_id = (location >> NUMBER_OF_CACHE_BLOCKS) % NUMBER_OF_CACHE_SETS write_cycles = 0 for id in range(NUMBER_OF_CACHE_SETS): if Data_Cache.lookup_address_in_set(location, id): Data_Cache.hits += 1 Data_Cache.use_for_lru(block_id, id) Data_Cache.write_data(location, id, data, isWritable) return HIT, ACCESS_TIME['DCACHE'] set_id = Data_Cache.cache_block_lru[block_id] if Data_Cache.cache_sets[set_id].cache_block[block_id].dirty_bit: write_cycles += Data_Cache.memory_write_back(set_id, block_id) Data_Cache.prepare_block(location, set_id) Data_Cache.write_data(location, set_id, data, isWritable) return MISS, write_cycles + 2 * (ACCESS_TIME['MEMORY'] + ACCESS_TIME['DCACHE']) @classmethod def lookup_address_in_set(self, location, id): """ Check if the address is present in the set """ tag = location >> 5 block_id = (location >> NUMBER_OF_CACHE_BLOCKS) % NUMBER_OF_CACHE_SETS if ((Data_Cache.cache_sets[id].cache_block[block_id].valid_bit) and (Data_Cache.cache_sets[id].cache_block[block_id].tag == tag)): return True return False @classmethod def use_for_lru(self, block_id, set_id): """ Update the LRU for the set. """ if (set_id == 0): Data_Cache.cache_block_lru[block_id] = 1 else: Data_Cache.cache_block_lru[block_id] = 0 @classmethod def memory_write_back(self, set_id, block_id): """ Write Back from cache to memory. """ tag = Data_Cache.cache_sets[set_id].cache_block[block_id].tag base_address = DATA_MEMORY_BASE_ADDRESS + ((tag << 5) | (block_id << NUMBER_OF_CACHE_BLOCKS)) for id in range(CACHE_BLOCK_SIZE): DATA[base_address + (id * WORD_SIZE)] = Data_Cache.cache_sets[set_id].cache_block[block_id].words[i] return 2 * (ACCESS_TIME['MEMORY'] + ACCESS_TIME['DCACHE']) @classmethod def prepare_block(self, location, set_id): """ Prepare the block """ block_id = (location >> NUMBER_OF_CACHE_BLOCKS) % NUMBER_OF_CACHE_SETS Data_Cache.cache_sets[set_id].cache_block[block_id].tag = location >> 5 Data_Cache.cache_sets[set_id].cache_block[block_id].valid_bit = True Data_Cache.use_for_lru(block_id, set_id) base_address = DATA_MEMORY_BASE_ADDRESS + ((location >> 4) << 4) for id in range(CACHE_BLOCK_SIZE): Data_Cache.cache_sets[set_id].cache_block[block_id].words[id] = DATA[base_address + (id * WORD_SIZE)] @classmethod def write_data(self, location, set_id, data, isWritable): block_id = (location >> NUMBER_OF_CACHE_BLOCKS) % NUMBER_OF_CACHE_SETS Data_Cache.cache_sets[set_id].cache_block[block_id].dirty_bit = True if isWritable: Data_Cache.cache_sets[set_id].cache_block[block_id].words[(location & 12) >> NUMBER_OF_CACHE_SETS] = data <file_sep>/pipeline_fetch_stage.py from computer import * from instruction_cache import * from data_cache import * from pipeline_stage import * from pipeline_decode_stage import * class Fetch_Stage(Pipeline_Stage): """ Class for instruction fetch stage. """ def __init__(self, instruction): """ Initialize the instruction fetch stage. """ Pipeline_Stage.__init__(self, instruction) self.name = 'IF' self.isHit, self.clock_cycles = Instruction_Cache.read(self.instruction.location) def execute(self, instruction): """ Execute the instruction fetch stage. """ STAGE_FLAG[self.name] = OCCUPIED if (not self.isHit): if ((self.clock_cycles > 0) and (STAGE_FLAG['DBUS'] == AVAILABLE)): STAGE_FLAG['IBUS'] = OCCUPIED if (Memory_Stage.bus_access_flag): STAGE_FLAG['IBUS'] = OCCUPIED STAGE_FLAG['DBUS'] = AVAILABLE Memory_Stage.bus_access_flag = False if ((STAGE_FLAG['IBUS'] == OCCUPIED) or (self.isHit)): self.clock_cycles -= 1 def proceed(self): """ Proceed in the instruction fetch stage. """ if (self.clock_cycles == 0): STAGE_FLAG['IBUS'] = AVAILABLE if (self.clock_cycles <= 0): if (REGISTERS['CLEAN']): STAGE_FLAG[self.name] = AVAILABLE STAGE_FLAG['IBUS'] = AVAILABLE REGISTERS['CLEAN'] = False return None if (STAGE_FLAG['ID'] == AVAILABLE): STAGE_FLAG[self.name] = AVAILABLE return Decode_Stage(self.instruction) return self <file_sep>/instruction.py """ Representation details of an instructions. """ from computer import * import re class Instruction(): """ Class to represent an Instruction. """ counter = 0 def __init__(self, name, operands): """ Initialize the Instruction. """ self.name = name self.operands = operands self.extract_registers() self.location = Instruction.counter * WORD_SIZE Instruction.counter += 1 def __str__(self): """ Convert to string representation. """ return self.name + ' ' + ','.join(self.operands) def get_instruction_type(self): """ Return the type of the instruction. """ if (self.name in ALU_INSTRUCTIONS): return 'ALU' elif (self.name in BRANCH_INSTRUCTIONS): return 'BRANCH' elif (self.name in DATA_INSTRUCTIONS): return 'DATA' elif (self.name in MISC_INSTRUCTIONS): return 'MISC' else: raise Exception('') def split_operands(self): """ Split operands into registers and immediates. """ operands = [] if (len(self.operands) > 1) and ('(' in self.operands[1]): operands.append(self.operands[0]) operands.append(self.operands[1].split('(')[0]) operands.append(self.operands[1].split('(')[1].split(')')[0]) else: operands = self.operands return operands def extract_registers(self): """ Extract destination and source registers. """ operands = self.split_operands() self.destReg = '' self.srcRegs = [] self.imm = '' self.offset = '' if (self.name in MISC_INSTRUCTIONS): # Instructions with no operands. return if (((self.name in UNCONDITIONAL_BRANCH_INSTRUCTIONS) and (len(operands) > 1)) or ((self.name not in UNCONDITIONAL_BRANCH_INSTRUCTIONS) and (len(operands) > 3))): raise Exception(': more than expected offsets or registers mentioned') if (self.name in DESTFUL_INSTRUCTIONS): # Instructions that have destination. if (len(operands) > 0): self.destReg = operands[0] else: raise Exception(': missing destination register') if (self.name in LOAD_INSTRUCTIONS): if (len(operands) == 3): self.offset = operands[1] self.srcRegs = [operands[2]] else: raise Exception(': missing offset or source register') elif (self.name in STORE_INSTRUCTIONS): if (len(operands) == 3): self.offset = operands[1] self.srcRegs = [operands[0], operands[2]] else: raise Exception(': missing offset or source register') elif (self.name in IMMEDIATE_ALU_INSTRUCTIONS): if (len(operands) == 3): self.srcRegs = [operands[1]] self.imm = operands[2] else: raise Exception(': missing offset or source register') elif (self.name in CONDITIONAL_BRANCH_INSTRUCTIONS): if (len(operands) == 3): self.srcRegs = operands[:2] self.imm = operands[2] else: raise Exception(': missing immediate or source register') elif (self.name in UNCONDITIONAL_BRANCH_INSTRUCTIONS): if (len(operands) == 1): self.imm = operands[0] else: raise Exception(': missing immediate') elif (self.name in INTEGER_ALU_INSTRUCTIONS + FLOAT_ALU_INSTRUCTIONS): if (len(operands) == 3): self.srcRegs = operands[1:] else: raise Exception(': missing source register') else: raise Exception(': invalid instruction name <' + self.name + '>') register_pattern = "^[rf]\d+$" constant_pattern = "^\d+$" if (self.name in DESTFUL_INSTRUCTIONS): if (re.match(register_pattern, self.destReg) == None): raise Exception(': invalid destination register <' + self.destReg + '>') if (self.name in LOAD_INSTRUCTIONS + STORE_INSTRUCTIONS): if (re.match(constant_pattern, self.offset) == None): raise Exception(': invalid offset <' + self.offset + '>') if (self.name in IMMEDIATE_ALU_INSTRUCTIONS + BRANCH_INSTRUCTIONS): if (self.imm == ''): raise Exception(': missing label') for srcReg in self.srcRegs: if (re.match(register_pattern, srcReg) == None): raise Exception(': invalid source register <' + srcReg + '>') def update_imm(self, location): """ Update the immediate value. """ self.imm = location def determine_exec_functional_unit(self): """ Determine the functional unit to be used in execution stage. """ if (self.name in BRANCH_INSTRUCTIONS + MISC_INSTRUCTIONS): return 'NO_UNIT' elif (self.name in ['add.d', 'sub.d']): return 'FP_ADD' elif (self.name in ['mul.d']): return 'FP_MUL' elif (self.name in ['div.d']): return 'FP_DIV' else: return 'IU' <file_sep>/simulator #! /usr/bin/python """ Entry point for the simulation. """ from collections import deque from computer import * from data_cache import * from instruction_cache import * from instruction_container import * from instruction_organizer import * from printer import * from scanner import * import operator import sys output = [] def simulate(): """ Simulate the execution of the instructions. """ Instruction_Cache() Data_Cache() clock_cycle = 1 active_instruction_containers = deque([Instruction_Container(INSTRUCTIONS[0], clock_cycle)]) REGISTERS['PC'] = 1 while (len(active_instruction_containers) > 0): active_instruction_containers = Instruction_Organizer.organize(active_instruction_containers) future_instruction_containers = deque([]) while (len(active_instruction_containers) > 0): ic = active_instruction_containers.pop() if (ic.keep_executing()): future_instruction_containers.appendleft(ic) else: output.append(ic.output) active_instruction_containers = future_instruction_containers clock_cycle += 1 if ((REGISTERS['PC'] < len(INSTRUCTIONS)) and (STAGE_FLAG['IF'] == AVAILABLE)): active_instruction_containers.appendleft(Instruction_Container(INSTRUCTIONS[REGISTERS['PC']], clock_cycle)) REGISTERS['PC'] += 1 def main(instFile, dataFile, regFile, configFile, resultFile): """ Scan the files and issue simulation. """ try: Scanner.scan_instructions(instFile) Scanner.scan_data(dataFile) Scanner.scan_registers(regFile) Scanner.scan_configuration(configFile) except Exception as e: string = 'Error: ' + str(e) try: writeString(resultFile, string) except Exception as e: print 'Error: ' + str(e) exit() simulate() try: Printer.print_output(resultFile, output) except Exception as e: print 'Error: ' + str(e) exit() if __name__ == "__main__": """ Entry point to the simulator. """ nArgs = len(sys.argv) args = sys.argv if (nArgs != 6): print "Usage: simulator inst.txt data.txt reg.txt config.txt result.txt" exit() main(args[1], args[2], args[3], args[4], args[5]) <file_sep>/memory_cache_block.py """ Cache Block and its state. """ class Cache_Block(): """ Class for the cache block. """ def __init__(self, id, size): """ Initilize the cache block """ self.id = id self.size = size self.words = [0] * size self.valid_bit = False self.dirty_bit = False <file_sep>/utils.py """ Basic functional utilities. """ def readLines(fileName): """ Return list of lines from the file. """ try: f = open(fileName, 'r') lines = [line for line in f] f.close() newlines = [] for line in lines: if (len(line.strip()) != 0): newlines.append(line) return newlines except: print 'File read error!' def writeString(fileName, string): """ Write string to the file. """ try: f = open(fileName, 'w') f.write(string) f.close() except: print 'File write error!' <file_sep>/output.py """ Stores the result of the instruction. """ from computer import * class Output(): """ Class to present the resulting output. """ def __init__(self, instruction, cycle = 0): """ Initialize the output. """ self.instruction = instruction self.cycles = {} for stage in STAGES: self.cycles[stage] = 0 self.cycles[STAGES[0]] = cycle self.hazards = {} for hazard in HAZARDS: self.hazards[hazard] = False def __str__(self): """ Convert to string representation. """ string = '' for label, location in LABEL.items(): if (self.instruction.location == location): string += label + ': ' string += str(self.instruction) string = string.ljust(INSTRUCTION_LEFT_JUSTIFY) for stage in STAGES: if (self.cycles[stage] != 0): string += '\t' + str(self.cycles[stage]) + '\t' else: string += '\t\t' for hazard in HAZARDS: if (self.hazards[hazard]): string += '\tY\t' else: string += '\tN\t' return string
febc1c7d673dae4b1cc2e19bc758093d4e74c337
[ "Python" ]
20
Python
manishc1/MIPS_Simulator
fe92989ee0d1a864e3985fce3e708041c2917768
ebe439675af1cacce41af369a98f4cdbbdcb612e
refs/heads/master
<file_sep>import time from bst_names import BST start_time = time.time() f = open('names_1.txt', 'r') names_1 = f.read().split("\n") # List containing 10000 names f.close() f = open('names_2.txt', 'r') names_2 = f.read().split("\n") # List containing 10000 names f.close() # This runtime is O(n^2) duplicates = [] for name_1 in names_1: for name_2 in names_2: if name_1 == name_2: duplicates.append(name_1) end_time = time.time() print (f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n") print (f"runtime: {end_time - start_time} seconds") start_time2 = time.time() root = BST('names') for name2 in names_2: root.insert(name2) duplicates2 = [] for name_1 in names_1: if root.contains(name_1): duplicates2.append(name_1) end_time2 = time.time() print (f"{len(duplicates2)} duplicates:\n\n{', '.join(duplicates2)}\n\n") print (f"runtime: {end_time2 - start_time2} seconds")
e856f0a83b90d2df1ea6878fe1a754ec28cea863
[ "Python" ]
1
Python
ndoshi83/Sprint-Challenge--Data-Structures-Python
db7d079545a759b0a3e0250e579d2db8c2a71844
56a6ae56981471c6d1a860c43afb09224aba0395
refs/heads/master
<repo_name>chenjeffrey23/chenjeffrey23.github.io<file_sep>/js/myscript.js function main() { $("#indexpic1").fancybox({ helpers: { title : { type : 'float' } } }); $("#biopic").fancybox({ helpers: { title : { type : 'float' } } }); $("#resumepic").fancybox({ helpers: { title : { type : 'float' } } }); $('#accomplishments').hide(); $('#accomplishmentsbutton').on('click',function(){ $(this).next().slideToggle(350); $(this).toggleClass('aactive'); }); } $(document).ready(main);
50620332f5293399571d7c711d411e062e3556b9
[ "JavaScript" ]
1
JavaScript
chenjeffrey23/chenjeffrey23.github.io
d2c5369a2f523f5f49d7522b6c1a8e0673d75301
31d1d5bdf8194028e60a26403a402eb209f9b023
refs/heads/master
<file_sep>import networkx as nx import matplotlib.pyplot as plt l = [1, 2, 3, 4, 5] print(*l) <file_sep>import networkx as nx import json import numpy as np from pprint import pprint import matplotlib.pyplot as plt data = [] with open('zhihu.json', 'r') as f: for line in f.readlines(): data.append(json.loads(line)) start = [each.get('name') for each in data] end = [each.get('relations') for each in data] edges = [] for u in start: for v in end: if v: for each in v: edges.append((u, v)) print(edges) <file_sep># -*- coding: utf-8 -*- import json import time import re import requests import scrapy from scrapy import Request from zhihu_users.items import UserItem, FollowItem pattern = "(.*?)members/(.*?)/follow(.*?)" class ZhihuSpider(scrapy.Spider): name = 'zhihu' allowed_domains = ['www.zhihu.com'] start_urls = ['http://www.zhihu.com/'] start_user = 'zhou-bo-lei' user_url = 'https://www.zhihu.com/api/v4/members/{user}?include={include}' user_query = 'allow_message,is_followed,is_following,is_org,is_blocking,employments,answer_count,follower_count,articles_count,gender,badge[?(type=best_answerer)].topics' follows_url = 'https://www.zhihu.com/api/v4/members/{user}/followees?include={include}&offset={offset}&limit={limit}' follows_query = 'data[*].answer_count,articles_count,gender,follower_count,is_followed,is_following,badge[?(type=best_answerer)].topics' fans_url = 'https://www.zhihu.com/api/v4/members/{user}/followers?include={include}&offset={offset}&limit={limit}' fans_query = 'data[*].answer_count,articles_count,gender,follower_count,is_followed,is_following,badge[?(type=best_answerer)].topics' # url = "https://www.zhihu.com/api/v4/members/excited-vczh/followees?include=data%5B*%5D.answer_count%2Carticles_count%2Cgender%2Cfollower_count%2Cis_followed%2Cis_following%2Cbadge%5B%3F(type%3Dbest_answerer)%5D.topics&offset=0&limit=20" def start_requests(self): yield Request(self.user_url.format(user=self.start_user, include=self.user_query), callback=self.parse_user) yield Request(self.follows_url.format(user=self.start_user, include=self.follows_query, offset=0, limit=20), callback=self.parse_follows, dont_filter=True) yield Request(self.follows_url.format(user=self.start_user, include=self.fans_query, offset=0, limit=20), callback=self.parse_fans, dont_filter=True) def parse_user(self, response): # print(response.text) result = json.loads(response.text) item = UserItem() # user_url = result.get('url') # followers_url = user_url + '/followers' # following_url = user_url + '/following' for field in item.fields: if field in result.keys(): item[field] = result.get(field) yield item yield Request(self.follows_url.format(user=result.get('url_token'), include=self.follows_query, offset=0, limit=20), callback=self.parse_follows) yield Request(self.fans_url.format(user=result.get('url_token'), include=self.fans_query, offset=0, limit=20), callback=self.parse_fans) # yield Request(self.follows_url.format(user=result.get('url_token'), include=self.follows_query, offset=0, limit=20), callback=self.parse_relation_list) # yield Request(self.fans_url.format(user=result.get('url_token'), include=self.follows_query, offset=0, limit=20), callback=self.parse_relation_list) def parse_follows(self, response): # print(response.text) results = json.loads(response.text) item = FollowItem() if 'data' in results.keys(): data = results.get('data') item['url_token'] = re.search(pattern, results.get( 'paging').get('previous'), re.S).group(2) item['relations'] = [data[i].get('name') for i in range(min(20, len(data)))] yield item for result in results.get('data'): yield Request(self.user_url.format(user=result.get('url_token'), include=self.user_query), callback=self.parse_user) if 'paging' in results.keys() and results.get('paging').get('is_end') == False: next_page = results.get('paging').get('next') yield Request(next_page, callback=self.parse_follows) def parse_fans(self, response): results = json.loads(response.text) item = FollowItem() if 'data' in results.keys(): data = results.get('data') item['url_token'] = re.search(pattern, results.get( 'paging').get('previous'), re.S).group(2) item['relations'] = [data[i].get('name') for i in range(min(20, len(data)))] yield item for result in data: yield Request(self.user_url.format(user=result.get('url_token'), include=self.user_query), callback=self.parse_user) if 'paging' in results.keys() and results.get('paging').get('is_end') == False: next_page = results.get('paging').get('next') yield Request(next_page, callback=self.parse_fans) # def crackImageCode(self): # browser = Chrome() # unhuman_url = "https://www.zhihu.com/account/unhuman?type=unhuman&message=%E7%B3%BB%E7%BB%9F%E6%A3%80%E6%B5%8B%E5%88%B0%E6%82%A8%E7%9A%84%E5%B8%90%E5%8F%B7%E6%88%96IP%E5%AD%98%E5%9C%A8%E5%BC%82%E5%B8%B8%E6%B5%81%E9%87%8F%EF%BC%8C%E8%AF%B7%E8%BF%9B%E8%A1%8C%E9%AA%8C%E8%AF%81%E7%94%A8%E4%BA%8E%E7%A1%AE%E8%AE%A4%E8%BF%99%E4%BA%9B%E8%AF%B7%E6%B1%82%E4%B8%8D%E6%98%AF%E8%87%AA%E5%8A%A8%E7%A8%8B%E5%BA%8F%E5%8F%91%E5%87%BA%E7%9A%84&need_login=true" # browser.get(unhuman_url) # def parse_relation_list(self, response): # results = json.loads(response.text) # item = FollowItem() # if 'data' in results.keys(): # data = results.get('data') # for i in range(20): # info = data.get(str(i)) # item['url_token'] = info.get('url_token') # yield item <file_sep># -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import pymongo import pymysql from pymysql.err import OperationalError as OE from zhihu_users.items import UserItem, FollowItem class MongoPipeline(object): def __init__(self, mongo_uri, mongo_db): self.mongo_uri = mongo_uri self.mongo_db = mongo_db @classmethod def from_crawler(cls, crawler): return cls( mongo_uri=crawler.settings.get('MONGO_URI'), mongo_db=crawler.settings.get('MONGO_DATABASE') ) def open_spider(self, spider): self.client = pymongo.MongoClient(self.mongo_uri) self.db = self.client[self.mongo_db] self.db[UserItem.collection].create_index( [('url_token', pymongo.ASCENDING)]) # self.db[FollowItem.collection].create_index( # [('url_token', pymongo.ASCENDING)]) def close_spider(self, spider): self.client.close() def process_item(self, item, spider): if isinstance(item, UserItem): self.db[item.collection].update( {'url_token': item.get('url_token')}, {'$set': item}, True) if isinstance(item, FollowItem): self.db[item.collection].update( {'url_token': item.get('url_token')}, { '$addToSet': { 'relations': {"$each": item['relations']} } }, True ) return item class MySQL_Pipeline(object): table_name = 'user_info' def __init__(self, sql_uri, user, pswd, sql_db): self.sql_uri = sql_uri self.user = user self.pswd = pswd self.sql_db = sql_db @classmethod def from_crawler(cls, crawler): return cls( sql_uri=crawler.settings.get('SQL_URI'), user=crawler.settings.get('USER'), pswd=crawler.settings.get('PSWD'), sql_db=crawler.settings.get('SQL_DB') ) def open_spider(self, spider): self.db = pymysql.connect( self.sql_uri, self.user, self.pswd, self.sql_db) self.cursor = self.db.cursor() def close_spider(self, spider): self.db.close() def process_item(self, item, spider): sql = "INSERT INTO user_info(name, answer_count, articles_count, follower_count) VALUES(%s, %s, %s, %s)" values = item.get('name'), int(item.get('answer_count')), int(item.get( 'articles_count')), int(item.get('follower_count')) try: self.cursor.execute(sql, values) self.db.commit() except OE: self.db.rollback() finally: return item # self.cursor.execute(sql, values) # self.db.commit() # return item
bb2ba09f6ff4ff51b0de5189a8f8668cdeea75b3
[ "Python" ]
4
Python
DallasAutumn/zhihu_users
68122dd9779ee4df82c2d6fe084b74cf8f456a3b
06b8a4006d9e38c2d209937181f71db24c5d1720
refs/heads/master
<repo_name>sexteam1/SexyProject<file_sep>/app/src/main/java/com/example/lenovo/studio_c/fragment/Attention/AttentionP.java package com.example.lenovo.studio_c.fragment.Attention; import com.example.lenovo.studio_c.base.BasePresenter; /** * Created by Lenovo on 2019/5/22. */ public class AttentionP extends BasePresenter<AttentionV> implements AttentionCollect{ @Override protected void initModel() { } } <file_sep>/app/src/main/java/com/example/lenovo/studio_c/fragment/Fragments/WanFragment.java package com.example.lenovo.studio_c.fragment.Fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.lenovo.studio_c.R; import com.example.lenovo.studio_c.base.BaseFragment; import com.example.lenovo.studio_c.fragment.Wan.WanP; import com.example.lenovo.studio_c.fragment.Wan.WanV; /** * A simple {@link Fragment} subclass. */ public class WanFragment extends BaseFragment<WanV,WanP> implements WanV { @Override protected void initListener() { } @Override protected void initView() { } @Override protected WanP initPresenter() { return new WanP(); } @Override protected int getLayoutId() { return R.layout.fragment_wan; } } <file_sep>/app/src/main/java/com/example/lenovo/studio_c/fragment/Find/FindM.java package com.example.lenovo.studio_c.fragment.Find; import com.example.lenovo.studio_c.base.BaseModel; /** * Created by Lenovo on 2019/5/22. */ public class FindM extends BaseModel { } <file_sep>/app/src/main/java/com/example/lenovo/studio_c/bean/CouponBean.java package com.example.lenovo.studio_c.bean; /** * Created by 003 on 2019/5/23. */ public class CouponBean { private String name; private int img; private int price; private String time; public CouponBean(String name, int img, int price, String time) { this.name = name; this.img = img; this.price = price; this.time = time; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getImg() { return img; } public void setImg(int img) { this.img = img; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } @Override public String toString() { return "CouponBean{" + "name='" + name + '\'' + ", img=" + img + ", price=" + price + ", time='" + time + '\'' + '}'; } } <file_sep>/app/src/main/java/com/example/lenovo/studio_c/fragment/Wan/WanV.java package com.example.lenovo.studio_c.fragment.Wan; import com.example.lenovo.studio_c.base.BaseView; /** * Created by Lenovo on 2019/5/22. */ public interface WanV extends BaseView { } <file_sep>/app/src/main/java/com/example/lenovo/studio_c/activity/MainActivity.java package com.example.lenovo.studio_c.activity; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.DrawerLayout; import android.support.v7.widget.CardView; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.example.lenovo.studio_c.Main.MainP; import com.example.lenovo.studio_c.Main.MainV; import com.example.lenovo.studio_c.R; import com.example.lenovo.studio_c.base.BaseActivity; import com.example.lenovo.studio_c.fragment.Fragments.AttentionFragment; import com.example.lenovo.studio_c.fragment.Fragments.FindFragment; import com.example.lenovo.studio_c.fragment.Fragments.WanFragment; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import de.hdodenhof.circleimageview.CircleImageView; public class MainActivity extends BaseActivity<MainV, MainP> implements MainV { //jjjjjjjjj @BindView(R.id.mains_tooblar) Toolbar mMainTooblar; @BindView(R.id.main_fragment) FrameLayout mMainFragment; @BindView(R.id.main_tablay) TabLayout mMainTablay; int position1; @BindView(R.id.main_toobla_avatar) CircleImageView mMainTooblaAvatar; @BindView(R.id.main_toobla_envelope) ImageView mMainTooblaEnvelope; @BindView(R.id.main_toobla_bell) ImageView mMainTooblaBell; @BindView(R.id.head_image) CircleImageView mHeadImage; @BindView(R.id.heads_relati) CardView mHeadsRelati; @BindView(R.id.heads_card) RelativeLayout mHeadsCard; @BindView(R.id.heads_stroke) RelativeLayout mHeadsStroke; @BindView(R.id.heads_collect) RelativeLayout mHeadsCollect; @BindView(R.id.heads_atten) RelativeLayout mHeadsAtten; @BindView(R.id.heads_service) TextView mHeadsService; @BindView(R.id.heads_feedback) TextView mHeadsFeedback; @BindView(R.id.heads_detection) TextView mHeadsDetection; @BindView(R.id.main_navi) NavigationView mMainNavi; @BindView(R.id.dl) DrawerLayout mDl; private ArrayList<Fragment> fraglist = new ArrayList<>(); private FragmentManager manager; @Override protected void initListener() { } @Override protected void initView() { mMainTooblar.setTitle(""); setSupportActionBar(mMainTooblar); manager = getSupportFragmentManager(); mMainTablay.setSelectedTabIndicatorHeight(0); initFragment(); FragmentData(); View tab = getTab(0); mMainTablay.addTab(mMainTablay.newTab().setCustomView(tab)); View tab1 = getTab(1); mMainTablay.addTab(mMainTablay.newTab().setCustomView(tab1)); View tab2 = getTab(2); mMainTablay.addTab(mMainTablay.newTab().setCustomView(tab2)); mMainTablay.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { int position = tab.getPosition(); getFragmentData(position); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); mMainTooblaAvatar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDl.openDrawer(Gravity.LEFT); } }); } private void FragmentData() { FragmentTransaction transaction = manager.beginTransaction(); transaction.add(R.id.main_fragment, fraglist.get(0)); transaction.commit(); } private void initFragment() { fraglist.add(new WanFragment()); fraglist.add(new FindFragment()); fraglist.add(new AttentionFragment()); } private View getTab(int position) { View inflate = LayoutInflater.from(this).inflate(R.layout.tablalayout, null, false); ImageView image = inflate.findViewById(R.id.tabla_image); TextView text = inflate.findViewById(R.id.tabla_text); if (position == 0) { image.setImageResource(R.drawable.wan); text.setText(R.string.wan); } else if (position == 1) { text.setText(R.string.find); } else if (position == 2) { image.setImageResource(R.drawable.attention); text.setText(R.string.attention); } return inflate; } private void getFragmentData(int position) { FragmentTransaction transaction = manager.beginTransaction(); Fragment fragment = fraglist.get(position); if (!fragment.isAdded()) { transaction.add(R.id.main_fragment, fragment); } transaction.show(fragment); transaction.hide(fraglist.get(position1)); transaction.commit(); position1 = position; } @Override protected MainP initPresenter() { return new MainP(); } @Override protected int getLayoutId() { return R.layout.activity_main; } @OnClick({R.id.main_toobla_avatar, R.id.main_toobla_envelope, R.id.main_toobla_bell, R.id.heads_relati, R.id.heads_card, R.id.heads_stroke, R.id.heads_collect, R.id.heads_atten, R.id.heads_service, R.id.heads_feedback, R.id.heads_detection}) public void onClick(View v) { switch (v.getId()) { default: break; case R.id.main_toobla_avatar: break; case R.id.main_toobla_envelope: Intent intent4 = new Intent(MainActivity.this, MessageActivity.class); startActivity(intent4); break; case R.id.main_toobla_bell: Intent intent1 = new Intent(MainActivity.this, NotificationActivity.class); startActivity(intent1); break; case R.id.heads_relati: break; case R.id.heads_card: Intent intent = new Intent(this, CouponActivity.class); startActivity(intent); break; case R.id.heads_stroke: Intent intent2 = new Intent(MainActivity.this, AlreadyActivity.class); startActivity(intent2); break; case R.id.heads_collect: Intent intent3 = new Intent(MainActivity.this, CollectActivity.class); startActivity(intent3); break; case R.id.heads_atten: break; case R.id.heads_service: break; case R.id.heads_feedback: startActivity(new Intent(this, FeedbackActivity.class)); break; case R.id.heads_detection: break; } } } <file_sep>/app/src/main/java/com/example/lenovo/studio_c/fragment/Fragments/CouponFragment.java package com.example.lenovo.studio_c.fragment.Fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.lenovo.studio_c.R; import com.example.lenovo.studio_c.adapter.CouponRlvAdapter; import com.example.lenovo.studio_c.bean.CouponBean; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ public class CouponFragment extends Fragment { private View view; private RecyclerView mMoneyRlv; private ArrayList<CouponBean> mList; public CouponFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View inflate = inflater.inflate(R.layout.fragment_coupon, container, false); initView(inflate); return inflate; } private void initData() { mList = new ArrayList<>(); for (int i = 0; i < 6; i++) { mList.add(new CouponBean("伴米旅行", R.mipmap.icon_me_kaquan_banmi1, 20, "有效期至: 2017-11-1")); } } private void initView(View inflate) { mMoneyRlv = (RecyclerView) inflate.findViewById(R.id.money_rlv); initData(); mMoneyRlv.setLayoutManager(new LinearLayoutManager(getContext())); CouponRlvAdapter adapter = new CouponRlvAdapter(getContext(), mList); mMoneyRlv.setAdapter(adapter); } } <file_sep>/app/src/main/java/com/example/lenovo/studio_c/Main/MainM.java package com.example.lenovo.studio_c.Main; import com.example.lenovo.studio_c.base.BaseModel; /** * Created by Lenovo on 2019/5/22. */ public class MainM extends BaseModel{ } <file_sep>/app/src/main/java/com/example/lenovo/studio_c/activity/WechatActivity.java package com.example.lenovo.studio_c.activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.example.lenovo.studio_c.R; public class WechatActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_wechat); } } <file_sep>/app/src/main/java/com/example/lenovo/studio_c/fragment/Wan/WanP.java package com.example.lenovo.studio_c.fragment.Wan; import com.example.lenovo.studio_c.base.BasePresenter; /** * Created by Lenovo on 2019/5/22. */ public class WanP extends BasePresenter<WanV> implements WanCollect{ @Override protected void initModel() { } } <file_sep>/app/src/main/java/com/example/lenovo/studio_c/base/BaseView.java package com.example.lenovo.studio_c.base; /** * Created by Lenovo on 2019/5/22. */ public interface BaseView { } <file_sep>/app/src/main/java/com/example/lenovo/studio_c/fragment/Wan/WanM.java package com.example.lenovo.studio_c.fragment.Wan; /** * Created by Lenovo on 2019/5/22. */ public class WanM { } <file_sep>/app/src/main/java/com/example/lenovo/studio_c/fragment/Find/FindCollect.java package com.example.lenovo.studio_c.fragment.Find; /** * Created by Lenovo on 2019/5/22. */ public interface FindCollect { } <file_sep>/app/src/main/java/com/example/lenovo/studio_c/activity/RegisterActivity.java package com.example.lenovo.studio_c.activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.lenovo.studio_c.R; import com.example.lenovo.studio_c.bean.CodeResult; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class RegisterActivity extends AppCompatActivity { @BindView(R.id.et_phone) EditText etPhone; @BindView(R.id.btn_send_verif) Button btnSendVerif; @BindView(R.id.view) View view; @BindView(R.id.um_wechat) ImageView umWechat; @BindView(R.id.tv_name) TextView tvName; private ArrayList<CodeResult> list; private CodeResult num; /*UMAuthListener authListener = new UMAuthListener() { *//** * @desc 授权开始的回调 * @param platform 平台名称 *//* @Override public void onStart(SHARE_MEDIA platform) { } *//** * @desc 授权成功的回调 * @param platform 平台名称 * @param action 行为序号,开发者用不上 * @param data 用户资料返回 *//* @Override public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) { Toast.makeText(RegisterActivity.this, "成功了", Toast.LENGTH_LONG).show(); } *//** * @desc 授权失败的回调 * @param platform 平台名称 * @param action 行为序号,开发者用不上 * @param t 错误原因 *//* @Override public void onError(SHARE_MEDIA platform, int action, Throwable t) { Toast.makeText(RegisterActivity.this, "失败:" + t.getMessage(), Toast.LENGTH_LONG).show(); } */ /** * @desc 授权取消的回调 * //* @param platform 平台名称 * //* @param action 行为序号,开发者用不上 *//* @Override public void onCancel(SHARE_MEDIA platform, int action) { Toast.makeText(RegisterActivity.this, "取消了", Toast.LENGTH_LONG).show(); } };*/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); ButterKnife.bind(this); initView(); initData(); } private void initData() { list=new ArrayList<>(); num = new CodeResult("9874"); } private void initView() { final String etphone = etPhone.getText().toString(); btnSendVerif.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!TextUtils.isEmpty(etphone)) { btnSendVerif.setBackgroundResource(R.drawable.button_unavailable); } else { btnSendVerif.setBackgroundResource(R.drawable.button_highlight); } Intent intent = new Intent(RegisterActivity.this,CodeActivity.class); intent.putExtra("9874",num); startActivity(intent); } }); } @OnClick({R.id.btn_send_verif, R.id.um_wechat, R.id.tv_name}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.btn_send_verif: break; case R.id.um_wechat: Intent intent = new Intent(RegisterActivity.this, WechatActivity.class); startActivity(intent); break; case R.id.tv_name: break; } } }
a449abe5bb0282e92f56d24523eff4545d9aae73
[ "Java" ]
14
Java
sexteam1/SexyProject
fb4a0800d6d68783d76c9b5de3f73102839f82e0
4b64e750a5469a42ed07297954361b1fe478baf3
refs/heads/master
<file_sep>README.md: guessinggame.sh echo "# Guessing Game" > README.md echo "Date and time when making this README file:" >> README.md date >> README.md echo >> README.md echo "number of lines of code contained in guessinggame.sh:" >> README.md cat guessinggame.sh | wc -l >> README.md clean: rm README.md <file_sep># Guessing Game Date and time when making this README file: Thu Jun 11 01:30:21 PDT 2020 number of lines of code contained in guessinggame.sh: 30 <file_sep>#!/usr/bin/env bash # File: guessinggame.sh function guessinggame { # store the correct answer first local answer=$(ls | wc -l) # first guess echo "How many files are there in this directory? Please take a guess:" read response echo "You guessed: $response" # whether the guess is correct while [[ !($response -eq $answer) ]] do # if the guess is too high if [[ $response -gt $answer ]] then echo "I'm sorry. Your guess is too high! Please try again:" # if the guess is too low else echo "I'm sorry. Your guess is too low! Please try again:" fi # guess again. update the response value read response response=$response done # while loop ends when guess/response is equal to the answer echo "Congratulation! You got the right answer! Answer is: $answer" } guessinggame
a9e62ab59a1354583ae512c276b326d015e7f140
[ "Markdown", "Makefile", "Shell" ]
3
Makefile
fanzhaom/guessing-game
f052c7e4b87267a0b67871de473e2b59011448f5
4f58836998ccfdc97461253062a707163f6bcda2
refs/heads/master
<file_sep># -*- coding: utf-8 -*- from django.conf import settings from django.http import HttpResponseRedirect, HttpResponseForbidden from django.shortcuts import render_to_response from django.template import RequestContext from masquerade.forms import MaskForm START_MASQUERADE_REDIRECT_URL = getattr(settings, 'START_MASQUERADE_REDIRECT_URL', '/') STOP_MASQUERADE_REDIRECT_URL = getattr(settings, 'STOP_MASQUERADE_REDIRECT_URL', '/') MASQUERADE_REQUIRE_SUPERUSER = getattr(settings, 'MASQUERADE_REQUIRE_SUPERUSER', False) def mask(request, template_name='masquerade/mask_form.html'): if not request.user.is_masked and not request.user.is_staff: return HttpResponseForbidden() elif not request.user.is_superuser and MASQUERADE_REQUIRE_SUPERUSER: return HttpResponseForbidden() if request.method == 'POST' or 'username' in request.REQUEST: form = MaskForm(request.REQUEST) if form.is_valid(): # turn on masquerading request.session['mask_user'] = form.cleaned_data['instance'].username return HttpResponseRedirect(START_MASQUERADE_REDIRECT_URL) else: form = MaskForm() return render_to_response(template_name, {'form': form}, context_instance=RequestContext(request)) def unmask(request): # Turn off masquerading. Don't bother checking permissions. try: del(request.session['mask_user']) except KeyError: pass return HttpResponseRedirect(STOP_MASQUERADE_REDIRECT_URL) <file_sep># -*- coding: utf-8 -*- from django import forms from django.contrib.auth.models import User class MaskForm(forms.Form): username = forms.CharField(required=False) email = forms.CharField(required=False) def clean_username(self): if not self.cleaned_data['username']: return if self.data.get('username') and self.data.get('email'): raise forms.ValidationError('Please provide either username or email') try: self.cleaned_data['instance'] = User.objects.get(username=self.cleaned_data['username']) except User.DoesNotExist: raise forms.ValidationError('Unknown username') return self.cleaned_data['username'] def clean_email(self): if not self.cleaned_data['email']: return try: self.cleaned_data['instance'] = User.objects.get(email=self.cleaned_data['email']) except User.DoesNotExist: raise forms.ValidationError('Unknown email') return self.cleaned_data['email'] def clean(self): if not self.data.get('username', None) and not self.data.get('email', None): raise forms.ValidationError('Please provide username or email') return super(MaskForm, self).clean()
84e9d5ca585bce0ee0edb5b90b7d73c619355d71
[ "Python" ]
2
Python
vogogo/django-masquerade
b1224eba4f539e6f60bd9a382fe33971cf5503b9
1ba6e7ae6e8b39e12848d24848a4fcff36436626
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace ConsoleApp7 { class Program { //Instructions: //Write a function that takes a single string (word) as argument.The function must return //an ordered list containing the indexes of all capital letters in the string. public static int[] Capitals(string word) { List<int> CapList = new List<int>(); for (int i = 0; i < word.Length; i++) { if (char.IsUpper(word[i])) CapList.Add(i); } return CapList.ToArray(); } } } <file_sep>namespace SampleEFProject.Models { public class Table { public int Id { get; set; } public int Number { get; set; } public string Dealer { get; set; } public string Description { get; set; } public GameType Game { get; set; } } public enum GameType { TwoTwoTexas = 22, TwoFiveTexas = 25, FiveFivePot = 5500, FiveTenTexas = 510, FiveTenPot = 5100 } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace GroceryCodingChallenge { class Program { /*You are a grocery bagger at a grocery store. The store just enacted a new policy in which every bag can only hold one type of grocery item (produce, meat, dairy, ect). Every bag has a max weight of 7 pounds The challenge is this: Create a collection of 20 or more grocery items and at least 3 different types, which vary in weight. Then create function that calculates how many bags will be needed in order to complete the bagging. */ static void Main(string[] args) { var chickenBreast = new GroceryItem(2.3f, GroceryType.Meat); var milk = new GroceryItem(1.5f, GroceryType.Dairy); var cheese = new GroceryItem(.4f, GroceryType.Dairy); var yogert = new GroceryItem(2.3f, GroceryType.Dairy); var cheeseSticks = new GroceryItem(2.3f, GroceryType.Dairy); var meatballs = new GroceryItem(3f, GroceryType.Meat); var tums = new GroceryItem(.1f, GroceryType.General); var dogFood = new GroceryItem(6f, GroceryType.General); var fishFood = new GroceryItem(0.1f, GroceryType.General); var salt = new GroceryItem(0.3f, GroceryType.General); var pepper = new GroceryItem(0.3f, GroceryType.General); var salmon = new GroceryItem(3f, GroceryType.Meat); var peanutButter = new GroceryItem(0.8f, GroceryType.General); var oranges = new GroceryItem(0.7f, GroceryType.Produce); var onion = new GroceryItem(0.6f, GroceryType.Produce); var frozenPizza = new GroceryItem(1.6f, GroceryType.Dairy); var avocado = new GroceryItem(0.3f, GroceryType.Produce); var banana = new GroceryItem(0.7f, GroceryType.Produce); var broccoli = new GroceryItem(0.4f, GroceryType.Produce); var almonds = new GroceryItem(0.2f, GroceryType.Produce); List<GroceryItem> groceries = new List<GroceryItem> { chickenBreast, milk, cheese, yogert, cheeseSticks, meatballs, tums, dogFood, fishFood, salt, pepper, salmon, peanutButter, oranges, onion, frozenPizza, avocado, banana, broccoli, almonds }; GroceryBagger tori = new GroceryBagger(); Console.WriteLine(tori.BagCount(groceries)); Console.ReadLine(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GroceryCodingChallenge { public class GroceryBag { public const float MaxWeight = 7.0f; public List<GroceryItem> Contents = new List<GroceryItem>(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GroceryCodingChallenge { public enum GroceryType { Produce = 0, Meat = 1, Dairy = 2, General = 3, } public class GroceryItem { public float weight; public GroceryType type; public GroceryItem(float w, GroceryType t) { weight = w; type = t; } } } <file_sep>using System; using System.Math; namespace Keep_Hydrated { class MainClass /*Because Nathan knows it is important to stay hydrated, he drinks 0.5 litres of water per hour of cycling. You get given the time in hours and you need to return the number of litres Nathan will drink, rounded to the smallest value. For example: time = 3 ----> litres = 1 time = 6.7---> litres = 3 time = 11.8--> litres = 5 */ { public static void Main(string[] args) { Console.WriteLine(Litres(5.8); } public static int Litres(double time) { return double litres = math.floor(0.5 * time); } } } <file_sep>using System; namespace Code_Wars { //You get an array of numbers, return the sum of all of the positives ones. // Example [1,-4,7,12] => 1 + 7 + 12 = 20 // Note: if there is nothing to sum, the sum is default to 0. class MainClass { public int sum; public static void Main(string[] args) { } public static int PositiveSum(int[] arr) { //find a place to store the int int sum = 0; foreach (int number in arr) { if (number >= 0) sum += number; } return sum; } //Best Practice is to use a LINQ return arr.Where(x => x > 0).Sum(); } } <file_sep>using Microsoft.AspNetCore.Mvc; using SampleEFProject.Models; using System.Collections.Generic; using System.Linq; namespace SampleEFProject.Controllers { public class HomeController : Controller { public IActionResult Index() { List<Table> tables = new List<Table>(); #region Add Table Data Table t1 = new Table() { Id = 1, Number = 101, Dealer = "<NAME>", Description = "On Thursday Nights Only", Game = GameType.FiveFivePot }; Table t2 = new Table() { Id = 2, Number = 55, Dealer = "<NAME>", Description = "", Game = GameType.TwoFiveTexas }; Table t3 = new Table() { Id = 3, Number = 32, Dealer = "<NAME>", Description = "", Game = GameType.TwoFiveTexas }; Table t4 = new Table() { Id = 4, Number = 87, Dealer = "<NAME>", Description = "", Game = GameType.TwoFiveTexas }; Table t5 = new Table() { Id = 5, Number = 23, Dealer = "<NAME>", Description = "", Game = GameType.FiveFivePot }; Table t6 = new Table() { Id = 6, Number = 5, Dealer = "<NAME>", Description = "", Game = GameType.FiveFivePot }; Table t7 = new Table() { Id = 7, Number = 3, Dealer = "<NAME>", Description = "", Game = GameType.FiveFivePot }; Table t8 = new Table() { Id = 8, Number = 51, Dealer = "<NAME>", Description = "", Game = GameType.FiveTenTexas }; Table t9 = new Table() { Id = 9, Number = 19, Dealer = "<NAME>", Description = "", Game = GameType.TwoFiveTexas }; Table t10 = new Table() { Id = 10, Number = 12, Dealer = "<NAME>", Description = "", Game = GameType.TwoTwoTexas }; tables.Add(t1); tables.Add(t2); tables.Add(t3); tables.Add(t4); tables.Add(t5); tables.Add(t6); tables.Add(t7); tables.Add(t8); tables.Add(t9); tables.Add(t10); #endregion Add Table Data //Select Count of all tables -- Result should be 10 //Query version: SELECT COUNT(*) FROM tables int numOfTables = tables.count(); //Select Count of all tables where <NAME> is the Dealer --Result should be 3 //Query version: SELECT COUNT(*) FROM tables WHERE Dealer = '<NAME>' int janeDoeTables = tables.Where(x => table.Dealer = "<NAME>"); //Select Count of all tables where the GameType is TwoFiveTexas -- Result should be 4 //Query version: SELECT COUNT(*) FROM tables WHERE GameType = '25' //Select the Smallest Table Number -- Result should return 1 table record that contains the smallest value in Number field //Query version: SELECT MIN(Number) FROM tables //Select the Largest Table Number -- Result should return 1 table record that contains the largest value in Number field. // Query version: SELECT MAX(Number) FROM tables //Order List by Table Number // Query version: Select * FROM tables Order By Number //Order list by GameType // Query version: Select * FROM tables Order By GameType return View(); } //public IActionResult Privacy() //{ // return View(); //} //[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] //public IActionResult Error() //{ // return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); //} } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Shortest_Word { //Simple, given a string of words, return the length of the shortest word(s). //String will never be empty and you do not need to account for different data types. class Program { static void Main(string[] args) { } public static int FindShort(string s) { string[] seperatedStringsArray = s.Split(new Char[] { ' ', ',', '.', '-', '\n', '\t' }); string lowestString = seperatedStringsArray[0]; foreach (string n in seperatedStringsArray) { if (n.Length < lowestString.Length) { lowestString = n; } } return lowestString.Count(); //Best Practices //return s.Split(' ').Min(x => x.Length); // OR //return s.Split(' ').Min(s1 => s1.Length ); // OR /* string[] strArr = s.Split(' '); int maxx = int.MaxValue; foreach (string item in strArr) { if (item.Length < maxx) { maxx = item.Length; } } return maxx; */ } } } <file_sep>using System; namespace Stay_Hydrated { public class EmptyClass { /*Because Nathan knows it is important to stay hydrated, he drinks 0.5 litres of water per hour of cycling. You get given the time in hours and you need to return the number of litres Nathan will drink, rounded to the smallest value. For example: time = 3 ----> litres = 1 time = 6.7---> litres = 3 time = 11.8--> litres = 5 */ public static int Litres(double time) { int litres; return litres = (int)System.Math.Floor(0.5 * time); //Best Practice // return (int)(time/2); } } } <file_sep>using System; namespace Reverse_String /*Task: Your task is to write a function which returns the sum of following series upto nth term(parameter). Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +... Rules: You need to round the answer to 2 decimal places and return it as String. If the given value is 0 then it should return 0.00 You will only be given Natural Numbers as arguments.*/ { public class NthSedries { public static class NthSeries { public static string seriesSum(int n) { double result = 0; double reverage = 1; for (int i = 0; i < n; i += 1) { if (i == 0) { result = 1; } else { reverage += 3; result = result + (1 / reverage); } } result = Math.Round(result, 2); return result.ToString("N2"); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp8 { //This time no story, no theory.The examples below show you how to write function accum: //Examples: //accum("abcd") -> "A-Bb-Ccc-Dddd" //accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" //accum("cwAt") -> "C-Ww-Aaa-Tttt" //The parameter of accum is a string which includes only letters from a..z and A..Z. class Program { static void Main(string[] args) { Console.WriteLine(Accum("AZBd")); Console.ReadLine(); } public static String Accum(string s) { var convertedString = new StringBuilder(); int i = 1; char last = s.Last(); foreach (char c in s) { string stringToAdd = new String(c, i).ToLower(); if (convertedString.Length > 1) { stringToAdd = stringToAdd.Remove(stringToAdd.Length - 1); convertedString.Append(stringToAdd.First().ToString().ToUpper() + stringToAdd + "-"); if (i == s.Length) { convertedString.Length--; } } else convertedString.Append(stringToAdd.First().ToString().ToUpper() + "-"); i++; } return convertedString.ToString(); } //Best Practices : return string.Join("-",s.Select((x,i)=>char.ToUpper(x)+new string(char.ToLower(x),i))); //or /* public static String Accum(string s) { // your code string result = ""; char[] stringArray; stringArray = s.ToCharArray(); for (int i = 0; i < stringArray.Length; i++) { char.ToLower(stringArray[i]); for (int j = 0; j <= i; j++) { if (j == 0) { result = result + char.ToUpper(stringArray[i]); } else { result = result + char.ToLower(stringArray[i]); } } if (i != stringArray.Length - 1) { result = result + '-'; } } return result; }*/ } } <file_sep>using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace ConsoleApp8 { /*In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number. Example: Kata.HighAndLow("1 2 3 4 5"); // return "5 1" Kata.HighAndLow("1 2 -3 4 5"); // return "5 -3" Kata.HighAndLow("1 9 3 4 -5"); // return "9 -5" Notes: All numbers are valid Int32, no need to validate them. There will always be at least one number in the input string. Output string must be two numbers separated by a single space, and highest number is first. */ class Program { static void Main(string[] args) { } public static string HighAndLow(string numbers) { string finalString = null; int? minNumber = null; int? maxNumber = null; char[] splitter = {' '}; string[] arrayOfNums = numbers.Split(splitter); int[] convertedArray = new int[arrayOfNums.Length]; convertedArray = Array.ConvertAll<string, int>(arrayOfNums, int.Parse); minNumber = convertedArray.Min(); maxNumber = convertedArray.Max(); return finalString = maxNumber.ToString() + " " + minNumber.ToString(); } /* --------------------------------------------------Best Practices--------------------------------------------------------- var parsed = numbers.Split().Select(int.Parse); return parsed.Max() + " " + parsed.Min(); LINQ var numbersList = numbers.Split(' ').Select(x => Convert.ToInt32(x)); return string.Format("{0} {1}", numbersList.Max(), NumbersList.Min()); */ } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace ConsoleApp8 { //You are going to be given a word.Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters. //#Examples: //Kata.getMiddle("test") should return "es" //Kata.getMiddle("testing") should return "t" //Kata.getMiddle("middle") should return "dd" //Kata.getMiddle("A") should return "A" class Program { static void Main(string[] args) { } public static string GetMiddle(string s) { if (s.Length % 2 == 0) { string middleCount = s.Substring((s.Length / 2) - 1, 2); return middleCount; } else { string middleCount = s.Substring((s.Length / 2), 1); return middleCount; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DNA { /*Deoxyribonucleic acid(DNA) is a chemical found in the nucleus of cells and carries the "instructions" for the development and functioning of living organisms. If you want to know more http://en.wikipedia.org/wiki/DNA In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G". You have function with one side of the DNA(string, except for Haskell); you need to get the other complementary side.DNA strand is never empty or there is no DNA at all (again, except for Haskell).*/ class Program { static void Main(string[] args) { } public static string MakeComplement(string dna) { char[] conversionString = dna.ToCharArray(); for(int i = 0; i < conversionString.Length; i++) switch(conversionString[i]) { case 'A': conversionString[i] = 'T'; break; case 'C': conversionString[i] = 'G'; break; case 'T': conversionString[i] = 'A'; break; case 'G': conversionString[i] = 'C'; break; } string output = new string(conversionString); return output; } } } <file_sep>using System; namespace Reverse_String /*Task: Return the number (count) of vowels in the given string. We will consider a, e, i, o, and u as vowels for this Kata. The input string will only consist of lower case letters and/or spaces.*/ { public static int GetVowelCount(string str) { int vowelCount = 0; string vowels = "aeiou"; foreach (char letter in str) { if (vowels.IndexOf(letter) != -1) vowelCount++; } return vowelCount; } //Best Practice Or Lamda Expression would be //return str.Count(i => "aeiou".Contains(i)); } <file_sep>using System; /*Consider an array of sheep where some sheep may be missing from their place. * We need a function that counts the number of sheep present in the array * (true means present).*/ namespace Reverse_String { public class CountingSheep { private static int SheepCounter(bool[] sheepArray) { int numberOfSheep = 0; foreach (var sheep in sheepArray) { if (sheep) numberOfSheep++; } return numberOfSheep; } //Best Practice return sheepArray.Count(s => s); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GroceryCodingChallenge { public class GroceryBagger { public int BagCount (List<GroceryItem> GList) { //create a function that adds each type in its own seperate bag, and if the list(bag) //exceeds 7 pounds in weight, create a new bag. float bags = 0f; float weightInProduce = 0f; float weightInMeat = 0f; float weightInGeneral = 0f; float weightInDairy = 0f; List<float> weightCatagory = new List<float>() { weightInDairy, weightInMeat, weightInGeneral, weightInProduce }; foreach (GroceryItem g in GList) { //find out which type of grocery it is and which weight in catagory. if (g.type == GroceryType.Produce) weightCatagory[3] += g.weight; if (g.type == GroceryType.Meat) weightCatagory[1] += g.weight; if (g.type == GroceryType.General) weightCatagory[2] += g.weight; if (g.type == GroceryType.Dairy) weightCatagory[0] += g.weight; } /*find out the weight of each catagory and divide it by 7, add a bag for each sum and the remainder.*/ foreach (float w in weightCatagory) { float tempSum; tempSum = w / 7f; bags += tempSum; bags = (int)Math.Ceiling(bags); } return (int)bags; } } } <file_sep>using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SampleEFProject.Models { public class SampleEFProjectContext : DbContext { public SampleEFProjectContext(DbContextOptions<SampleEFProjectContext> options) : base(options) { } public DbSet<User> Users { get; set; } public DbSet<Table> Tables { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EnoughIsEnough { class Program { static void Main(string[] args) { } public class Kata { public static int[] DeleteNth(int[] arr, int x) { if (x <= 0) return new int[0]; List<int> listArr = new List<int>(); listArr = arr.ToList(); var newListArr = new List<int>(); foreach (int num in listArr) { int numCount = newListArr.Where(y => y == num).Count(); //var that determines the amount of times an elemment appears in an array. if (numCount < x) newListArr.Add(num); } return newListArr.ToArray(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace ConsoleApp8 { //Directions: //Given an array, find the int that appears an odd number of times. //There will always be only one integer that appears an odd number of times. class Program { static void Main(string[] args) { int[] test_Array = { 20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5 }; find_it(test_Array); } public static int find_it(int[] seq) { string finalAnswer = ""; Dictionary<string, int> odd_Finder = new Dictionary<string, int>(); int i = 1; foreach (int s in seq) { if (odd_Finder.ContainsKey(s.ToString())) { odd_Finder[s.ToString()] += 1; } else odd_Finder.Add(s.ToString(),i); } foreach (KeyValuePair<string, int> s in odd_Finder) { if (s.Value % 2 == 1) { finalAnswer = s.Key; } } return Convert.ToInt32(finalAnswer); } /* --------------------------------------------------Best Practices--------------------------------------------------------- return seq.GroupBy(x => x).Single(g => g.Count() % 2 == 1).Key; ------------- public static int find_it(int[] seq) { int found = 0; foreach (var num in seq) { found ^= num; } return found; } This is the most clever thing ever of the XOR opperator ----------------------------------------------------------------------------------------------------------------------------*/ } } <file_sep># Code_Wars Studies/Practice using the code wars website. These are simply exercises that I have used from the website www.CodeWars.com I enjoy the site because of its ranking system, and ease of access to challenging code test known as Kata's. It's basically a on the fly way to keep skills relivient. These are not really meant to be run as an actual application. I just use these for personal references. <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace ConsoleApp8 { class Program { static void Main(string[] args) { } public static int Opposite(int number) { //if number is positive return it as a negative, if number is negative, return it as a positive. return (number <=0) ? Math.Abs(number) : -Math.Abs(number); //Best Practices //return number * -1; //return -number; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace Persistent_Bugger { /*Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit. For example: persistence(39) == 3 // because 3*9 = 27, 2*7 = 14, 1*4=4 // and 4 has only one digit persistence(999) == 4 // because 9*9*9 = 729, 7*2*9 = 126, // 1*2*6 = 12, and finally 1*2 = 2 persistence(4) == 0 // because 4 is already a one-digit number*/ class Program { static void Main(string[] args) { Console.WriteLine(Persist.Persistence(39)); Console.ReadLine(); } } public class Persist { public static int Persistence(long n) { int count = 0; if (n.ToString().Length == 1) { return count; } count = 1; //break up each number in the long individually. List<long> listofLong = new List<long>(); while (n > 0) { listofLong.Add(n % 10); n = n / 10; } //First iteration of each number mult each other in list long calculate(List<long> seperatedNums) { long mult = 1; for (int i = 0; i < seperatedNums.Count; i++) mult *= seperatedNums[i]; return (int)mult;//barely broken } do { calculate(listofLong); count++; } while ((Math.Floor(Math.Log10(n)) + 1) > 1);//broken return count; } //Best Practices /* int count = 0; while (n > 9) { count++; n = n.ToString().Select(digit => int.Parse(digit.ToString())).Aggregate((x, y) => x* y); } return count; */ //OR /* int i = 0; while (n > 9l) { long mul = 1l; while (n > 0l) { mul *= n % 10l; n /= 10l; } n = mul; i++; } return i; */ } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace List_Filtering { class Program { static void Main(string[] args) { List<object> newList = new List<object> {"cool", 3, "six", 4, "I hope I dont get fired", 19}; List<int> practiceList = new List<int>(); practiceList = ListFilterer.GetIntegersFromList(newList).ToList(); practiceList.ForEach(i => Console.WriteLine("{0}\t", i)); Console.ReadLine(); } public class ListFilterer { public static IEnumerable<int> GetIntegersFromList(List<object> listOfItems) { //create a place to store the new list List<int> numList = new List<int>(); foreach (object item in listOfItems) { if (item.GetType() == typeof(int)) { int newItem = Convert.ToInt32(item); numList.Add(newItem); } } return numList; //Best Practice //return listOfItems.OfType<int>(); } } } }
7adf005ddd02efc789b0dd2dc64592cdd87e49b7
[ "Markdown", "C#" ]
25
C#
JeffPadgett/Code_Wars
46955f8bf0155807e5c0456bd6893b89555bd072
ebf765ab866db36c6fe19877dffd5cd258cff9ae
refs/heads/master
<repo_name>junlinguo11/vue-firebase-demo<file_sep>/src/components/firebaseConfig.js export default { apiKey: '<KEY>', authDomain: 'vue-fs-1934f.firebaseapp.com', databaseURL: 'https://vue-fs-1934f.firebaseio.com', projectId: 'vue-fs-1934f', storageBucket: 'vue-fs-1934f.appspot.com', messagingSenderId: '852543661112', }; <file_sep>/src/vuex/employees.js import Vue from 'vue'; import Vuex from 'vuex'; import db from '../components/firebaseInit'; import * as types from './mutation-types'; Vue.use(Vuex); export default new Vuex.Store({ state: { employees: [], }, getters: { employeesCount: state => state.employees.length, }, mutations: { [types.GET_EMPLOYEE](state, { doc }) { const employee = doc.data(); state.employees.push({ id: doc.id, employee_id: employee.employee_id, name: employee.name, dept: employee.dept, position: employee.position, }); }, [types.ADD_EMPLOYEE](state, { newEmployee }) { state.employees.push(newEmployee); }, [types.DELETE_EMPLOYEE](state, { doc }) { const deletedEmployee = doc.data(); for (let i = 0; i < state.employees.length; i += 1) { if (state.employees[i].employee_id === deletedEmployee.employee_id) { state.employees.splice(i, 1); } } }, }, actions: { getEmployees({ commit }) { return db.collection('employees').get() .then((querySnapshot) => { querySnapshot.forEach((doc) => { commit(types.GET_EMPLOYEE, { doc }); }); }) .catch(); }, addEmployee({ commit }, employee) { const newEmployee = employee; return db.collection('employees').add(newEmployee) .then((docRef) => { newEmployee.id = docRef.id; commit(types.ADD_EMPLOYEE, { newEmployee }); }); }, deleteEmployee({ commit }, id) { return db.collection('employees').doc(id).get() .then((documentSnapshot) => { documentSnapshot.ref.delete(); commit(types.DELETE_EMPLOYEE, { doc: documentSnapshot }); }); }, }, });
60b6544059131cb18d09a1612f0d2e5d1064b40e
[ "JavaScript" ]
2
JavaScript
junlinguo11/vue-firebase-demo
696d6f04d4228021c98f6dd5e6e271de40f5ced8
52556a114c2d9bdb684172f079c136f7f7d83953
refs/heads/master
<file_sep>import argparse import tkinter as tk from PIL import ImageTk, Image import os.path as path import cv2 def binary_image(image, th): new_image = image.copy() for d in (0, 1, 2): mat = new_image[:, :, d] for r in range(mat.shape[0]): for c in range(mat.shape[1]): mat[r][c] = 255 if mat[r][c] > th else 0 return new_image def binary_image_name(image_path, image_name): return image_path.replace(image_name, 'binary-' + image_name) def binarize_image_hook(image_path, image_name, val): bv = val.get() image = cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB) bi = binary_image(image, bv) b_path = binary_image_name(image_path, image_name) cv2.imwrite(b_path, bi) print('wrote binary image to path ' + str(b_path)) def build_gui(image_path, image_name): w_dim = 800 start_y = 50 slider_gap = 50 window = tk.Tk() window.title('Image binarization') window.geometry('800x800') window.configure(background='grey') #read images image = ImageTk.PhotoImage(Image.open(image_path)) b_path = binary_image_name(image_path, image_name) if path.exists(b_path): print('build_gui, reading in binary image') binary_image = ImageTk.PhotoImage(image=Image.fromarray(cv2.imread(b_path), 'RGB')) else: print('build_gui, reading original image') binary_image = image #left image og = 'Original' left_image_label = tk.Text(window, height=1, width=len(og)) left_image_label.place(x=0, y=0) left_image_label.insert(tk.END, og) panel1 = tk.Label(image=image) panel1.place(x=0, y=start_y) #right image bin_text = 'Binary' right_image_label = tk.Text(window, height=1, width=len(bin_text)) right_image_label.place(x=w_dim - image.width(), y=0) right_image_label.insert(tk.END, bin_text) panel2 = tk.Label(image=binary_image) panel2.place(x=w_dim - binary_image.width(), y=start_y) #slider sv = tk.IntVar() slider = tk.Scale(window, from_=0.0, to=255.0, orient=tk.HORIZONTAL, variable=sv) slider.set(0) slider.place(x=slider_gap, y=start_y + image.height() + slider_gap) #binarize button exec_button = tk.Button(window, text='Binarize', width=15, command=lambda: binarize_image_hook(image_path, image_name, sv)) exec_button.place(x=slider_gap, y=start_y + image.height() + slider_gap * 2) button = tk.Button(window, text='Stop', width=15, command=window.destroy) button.pack() window.mainloop() def parse_args(): parser = argparse.ArgumentParser(description='Image binarization') parser.add_argument('--image', required=False, help='Path to input image') parser.add_argument('--case', required=False, help='test case run') return parser.parse_args() def run_gui(args): base = path.basename(args.image) name = base[:base.index('.')] build_gui(args.image, name) def test_case_1(): bt = 0 in_file = 'images/apple.jpeg' ri = cv2.imread(in_file) bi = binary_image(ri, 0) print("Input file: %s, binary threshold: %d, \n\nExplanation: %s" % (in_file, bt, "This is a bad input because the threshold was set too low. Therefore,\nmost of the pixels were set to white")) cv2.imshow('original', ri) cv2.imshow('binarized', bi) while True: cv2.waitKey(1000) if input() == 'q': break cv2.destroyAllWindows() def test_case_2(): bt = 255 in_file = 'images/apple.jpeg' ri = cv2.imread(in_file) bi = binary_image(ri, bt) print("Input file: %s, binary threshold: %d, \n\nExplanation: %s" % (in_file, bt, "This is a bad input because the threshold was set too high. Therefore,\nmost of the pixels were set to black")) cv2.imshow('original', ri) cv2.imshow('binarized', bi) while True: cv2.waitKey(1000) if input() == 'q': break cv2.destroyAllWindows() def test_case_3(): bt = 80 in_file = 'images/apple.jpeg' ri = cv2.imread(in_file) bi = binary_image(ri, bt) print("Input file: %s, binary threshold: %d, \n\nExplanation: %s" % (in_file, bt, "This is a good input because the threshold was set at a level that allowed\nfor pixels to be both black and white, thus producing the desired effect")) cv2.imshow('original', ri) cv2.imshow('binarized', bi) while True: cv2.waitKey(1000) if input() == 'q': break cv2.destroyAllWindows() if __name__ == '__main__': args = parse_args() if args.case == '1': test_case_1() elif args.case == '2': test_case_2() elif args.case == '3': test_case_3() elif args.image: run_gui(args) else: print("bad inputs") <file_sep>import numpy as np import math import cv2 import tkinter as tk from PIL import ImageTk, Image import os.path as path def pad_segment(segment, kcy): h = len(segment) pad = kcy * 2 ns = np.add(segment.shape, pad) padded = np.zeros(np.product(ns)).reshape(ns) ds, de = (pad // 2, ns[0] - (pad // 2)) padded[ds:de, ds:de] = segment return padded, (ds, de), pad def segment_portion(segment, x, y, kc): bx, ex = (x - kc, x + kc + 1) by, ey = (y - kc, y + kc + 1) return segment[by:ey, bx:ex] def convolution(segment, kernel, kc, ds, de, p): data_segment = segment[ds:de, ds:de] new_seg = np.zeros(data_segment.shape) for ri, rv in enumerate(data_segment): for ci, cv in enumerate(data_segment[ri]): im_seg = segment_portion(segment=segment, x=ri + p, y=ci + p, kc=kc) if im_seg.shape != kernel.shape: filler = np.zeros((kernel.shape)) filler[:im_seg.shape[0], :im_seg.shape[1]] = im_seg im_seg = filler new_seg[ri][ci] = np.sum(im_seg * kernel) return new_seg def sign(num): return num >= 0 def zero_cross(segment, x, y, s_func=sign): left = s_func(num=segment[x-1][y]) right = s_func(num=segment[x+1][y]) up = s_func(num=segment[x][y-1]) down = s_func(num=segment[x][y+1]) up_left = s_func(num=segment[x-1][y-1]) down_right = s_func(num=segment[x+1][y+1]) up_right = s_func(num=segment[x+1][y-1]) down_left = s_func(num=segment[x-1][y+1]) return (left != right) or (up != down) or (up_left != down_right) or (up_right != down_left) def log_kernel_size(sigma): m = math.ceil(sigma * 7) dim = len(range(-m, m + 1)) return dim, dim // 2 def x_y_vals(m, center): grid = np.zeros((m, m)).tolist() sx = -center sy = -center for ri, rv in enumerate(grid): for ci, cv in enumerate(grid[ri]): grid[ri][ci] = (sx + ri, sy + ci) return grid def log_kernel(sigma, const_factor, m, xy_grid): # result = np.zeros((m, m)) # for ri, rv in enumerate(result): # for ci, cv in enumerate(result[ri]): # x, y = xy_grid[ri][ci] # r_sq = x**2 + y**2 # sig_sq = sigma**2 # sig_cube = sigma**4 # result[ri][ci] = (((r_sq - sig_sq) / sig_sq) - (r_sq / 2 * sig_sq)) + const_factor result = np.asarray([[0, -1, 0], [-1, 4, -1], [0, -1, 0]]) #result = np.asarray([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]]) return result def apply_image(image, func, func_args): result = [] for d in range(image.shape[2]): result.append(func(segment=image[:, :, d], **func_args)) return result def zero_crossing(segment, ds, de, zc_func=zero_cross): data_segment = segment[ds:de + 1, ds:de + 1] crossing_segment = np.zeros(data_segment.shape) for ri, rv in enumerate(data_segment): for ci, cv in enumerate(data_segment[ri]): r, g, b = segment[ri, ci, :] zc = all(map(lambda d: zero_cross(segment=segment[:, :, d], x=ri, y=ci), (0, 1, 2))) if 0 in {r, g, b} and zc: crossing_segment[ri][ci][:] = 255 else: crossing_segment[ri][ci][:] = 0 return crossing_segment def log_image(sigma, image): #m, center = log_kernel_size(sigma=sigma) m, center = 1, 1 grid = x_y_vals(m=m, center=center) kernel = log_kernel(sigma=sigma, const_factor=0, m=m, xy_grid=grid) padded = apply_image(image=image, func=pad_segment, func_args={'kcy': center}) pi_sh, dse, pad = padded[0] new_shape = (pi_sh.shape[0], pi_sh.shape[1], image.shape[-1]) ds, de = dse ps = np.transpose(np.asarray(list(map(lambda t: t[0], padded))), (1, 2, 0)) log_image = apply_image(image=ps, func=convolution, func_args={'kernel': kernel, 'kc': center, 'ds': ds, 'de': de, 'p': pad}) log_tensor = np.transpose(np.asarray(log_image), (1, 2, 0)) zero_cross = zero_crossing(segment=log_tensor, ds=ds, de=de) zero_cross_tensor = np.transpose(np.asarray(zero_cross), (1, 0, 2)) return zero_cross_tensor def test_log(): kobe = cv2.resize(cv2.imread('./images/kobe_bryant.jpg'), (300, 300)) log_kobe = log_image(sigma=0.1, image=kobe) print(log_kobe.shape) cv2.imwrite('./log_kobe.jpg', log_kobe) def invoke_log(sigma, image, log_path): print('Computing LoG...') image = log_image(sigma=1, image=image) cv2.imwrite(log_path, image) print("Wrote image to {}".format(log_path)) def build_gui(image_path, log_image_path): start_y = 50 image_gap = 40 w_dim = 800 h_dim = 300 label_gap = 20 slider_gap = 5 button_gap = 60 image_label_gap = 20 image_shape = (224, 224) window = tk.Tk() window.title('LoG Eddge Detection') window.geometry('800x300') window.configure(background='grey') #images cv_image = cv2.resize( cv2.imread(image_path), image_shape) raw_image = Image.fromarray(cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB), 'RGB') image = ImageTk.PhotoImage(raw_image) if path.exists(log_image_path): raw_log_image = Image.fromarray(cv2.cvtColor(cv2.resize( cv2.imread(log_image_path), image_shape), cv2.COLOR_BGR2RGB), 'RGB') log_image = ImageTk.PhotoImage(raw_log_image) else: log_image = image #left side og = 'Original' panel1 = tk.Label(image=image) panel1.place(x=0, y=start_y) #right side edge_str = 'Edge Image' panel2 = tk.Label(image=log_image) panel2.place(x=w_dim - log_image.width(), y=start_y) slider_x = tk.Scale(window, from_=0.1, to=5.0, digits = 2, resolution=0.1, orient=tk.HORIZONTAL, variable=0, length=w_dim-10) slider_x.set(0) slider_x.place(x=0, y=slider_gap) #LoG button lb_w, lb_h = 5, 1 log_button = tk.Button(window, text='LoG', width=lb_w, height=lb_h, command=lambda: invoke_log(sigma=1, image=cv_image, log_path=log_image_path)) log_button.place(x=(w_dim / 2) - lb_w, y=(h_dim / 2) - lb_h / 2) window.mainloop() if __name__ == '__main__': image_path = './images/kobe_bryant.jpg' log_image_path = './images/log_kobe.jpg' build_gui(image_path=image_path, log_image_path=log_image_path) <file_sep>import gui import cv2 import os.path as path BASE_PATH = './images' def examples(image_paths): for ip, ob, _ in image_paths: print("Computing LoG for {}...".format(ip)) image = cv2.resize(cv2.imread(ip), (300, 300)) log_img = gui.log_image(sigma=1, image=image) cv2.imshow('original_' + ob, image) cv2.imshow('LoG_' + ob, log_img) stars = 100 for _, ob, descr in image_paths: print() print("*" * stars) print("{} description:\n{}".format(ob.capitalize(), descr)) print("*" * stars) print() print("\n\tClick on one of the windows and hit ENTER to exit the program.\n") cv2.waitKey(0) if __name__ == '__main__': flower_descr = "The flower is a good example for LoG because the lines are distinguishable\n"\ + "from background. The pedals serve as a boundary as the intensities are\n"\ + "different from the green background. This helps the LoG kernel find the "\ + "edges." tree_descr = "The tree is a bad example for edge detection. This image makes it difficult\n"\ + "for the LoG kernel because the intensities are nearly all the same. Also,\n"\ + "all off the lines are vertical which means a horizontal kernel would not work\n"\ + "well on this image input." field_descr = "The field is a mediocre example of LoG edge detection. The image contains almost\n"\ "no edges. The sky and field are not good inputs because they do not have many edges. The\n"\ "LoG kernel can find the horizon line, but it is difficult to see. It also picks up\n"\ "some of the edges of the clouds, but these are difficult to see as well." image_paths = ((path.join(BASE_PATH, 'flower.jpg'), 'flower', flower_descr), (path.join(BASE_PATH, 'tree.jpg'), 'tree', tree_descr), (path.join(BASE_PATH, 'field.jpg'), 'field', field_descr)) examples(image_paths=image_paths) <file_sep>import numpy as np import math import cv2 import tkinter as tk from PIL import ImageTk, Image import os.path as path def pad_segment(segment, kcy): h = len(segment) pad = kcy * 2 ns = np.add(segment.shape, pad) padded = np.zeros(np.product(ns)).reshape(ns) ds, de = (pad // 2, ns[0] - (pad // 2)) padded[ds:de, ds:de] = segment return padded, (ds, de), pad def segment_portion(segment, x, y, kc): bx, ex = (x - kc, x + kc + 1) by, ey = (y - kc, y + kc + 1) return segment[by:ey, bx:ex] def convolution(segment, kernel, kc, ds, de, p): data_segment = segment[ds:de, ds:de] new_seg = np.zeros(data_segment.shape) for ri, rv in enumerate(data_segment): for ci, cv in enumerate(data_segment[ri]): im_seg = segment_portion(segment=segment, x=ri + p, y=ci + p, kc=kc) if im_seg.shape != kernel.shape: filler = np.zeros((kernel.shape)) filler[:im_seg.shape[0], :im_seg.shape[1]] = im_seg im_seg = filler new_seg[ri][ci] = np.sum(im_seg * kernel) return new_seg def sign(num): return num >= 0 def zero_cross(segment, x, y, s_func=sign): left = s_func(num=segment[x-1][y]) right = s_func(num=segment[x+1][y]) up = s_func(num=segment[x][y-1]) down = s_func(num=segment[x][y+1]) up_left = s_func(num=segment[x-1][y-1]) down_right = s_func(num=segment[x+1][y+1]) up_right = s_func(num=segment[x+1][y-1]) down_left = s_func(num=segment[x-1][y+1]) return (left != right) or (up != down) or (up_left != down_right) or (up_right != down_left) def log_kernel_size(sigma): m = math.ceil(sigma * 7) dim = len(range(-m, m + 1)) return dim, dim // 2 def x_y_vals(m, center): grid = np.zeros((m, m)).tolist() sx = -center sy = -center for ri, rv in enumerate(grid): for ci, cv in enumerate(grid[ri]): grid[ri][ci] = (sx + ri, sy + ci) return grid def log_kernel(sigma, const_factor, m, xy_grid): # result = np.zeros((m, m)) # for ri, rv in enumerate(result): # for ci, cv in enumerate(result[ri]): # x, y = xy_grid[ri][ci] # r_sq = x**2 + y**2 # sig_sq = sigma**2 # sig_cube = sigma**4 # result[ri][ci] = (((r_sq - sig_sq) / sig_sq) - (r_sq / 2 * sig_sq)) + const_factor result = np.asarray([[0, -1, 0], [-1, 4, -1], [0, -1, 0]]) #result = np.asarray([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]]) return result def apply_image(image, func, func_args): result = [] for d in range(image.shape[2]): result.append(func(segment=image[:, :, d], **func_args)) return result def zero_crossing(segment, ds, de, zc_func=zero_cross): data_segment = segment[ds:de + 1, ds:de + 1] crossing_segment = np.zeros(data_segment.shape) for ri, rv in enumerate(data_segment): for ci, cv in enumerate(data_segment[ri]): r, g, b = segment[ri, ci, :] zc = all(map(lambda d: zero_cross(segment=segment[:, :, d], x=ri, y=ci), (0, 1, 2))) if 0 in {r, g, b} and zc: crossing_segment[ri][ci][:] = 255 else: crossing_segment[ri][ci][:] = 0 return crossing_segment def log_image(sigma, image): #m, center = log_kernel_size(sigma=sigma) m, center = 1, 1 grid = x_y_vals(m=m, center=center) kernel = log_kernel(sigma=sigma, const_factor=0, m=m, xy_grid=grid) padded = apply_image(image=image, func=pad_segment, func_args={'kcy': center}) pi_sh, dse, pad = padded[0] new_shape = (pi_sh.shape[0], pi_sh.shape[1], image.shape[-1]) ds, de = dse ps = np.transpose(np.asarray(list(map(lambda t: t[0], padded))), (1, 2, 0)) log_image = apply_image(image=ps, func=convolution, func_args={'kernel': kernel, 'kc': center, 'ds': ds, 'de': de, 'p': pad}) log_tensor = np.transpose(np.asarray(log_image), (1, 2, 0)) zero_cross = zero_crossing(segment=log_tensor, ds=ds, de=de) zero_cross_tensor = np.transpose(np.asarray(zero_cross), (1, 0, 2)) return zero_cross_tensor <file_sep>import cv2 import log_funcs import os.path as path import numpy as np import math import operator as op import matplotlib.pyplot as plt BASE_DIR = './images/original' PSPACE_DIR = './images/pspace' EX_1_DESCR = "This is a good example for hough transformation. The basketball player\n"\ + "has an upright stance which makes for edges to be clearly defined. He\n"\ + "also stands against a black background which helps the hough transform\n"\ + "find the vertical lines in the edge image. There are also other player's\n"\ + "arms that make it in the picture which provide a good input for hough transform." EX_2_DESCR = "This image is a mediocre example for hough transform. The image has some lines,\n"\ + "but the vertical lines are all in the clouds and they are not clearly visible.\n"\ + "The field has no edges and the horizon provides the best chance at hough transform\n"\ + "finding an edge." EX_3_DESCR = "The flower is a bad example for hough transformation. The pedals of the flower are\n"\ + "not straight and the leaves do not provide straight edges for edge detection. The background\n"\ + "is not as discernable from the leaves which makes it harder to detect edges.\n"\ + "The stem is also barely visible which does not provide a straight line for hough\n"\ + "transform to detect." EXAMPLE_ARGS = {'Example_1': {'original_image': path.join(BASE_DIR, 'kobe_bryant.jpg'), 'log_image': None, 'pspace_image': path.join(PSPACE_DIR, 'kb.png'), 'descr': EX_1_DESCR}, 'Example_2': {'original_image': path.join(BASE_DIR, 'field.jpg'), 'log_image': None, 'pspace_image': path.join(PSPACE_DIR, 'lf.png'), 'descr': EX_2_DESCR}, 'Example_3': {'original_image': path.join(BASE_DIR, 'flower.jpg'), 'log_image': None, 'pspace_image': path.join(PSPACE_DIR, 'flower.png'), 'descr': EX_3_DESCR}} def compute_logs(image_paths, example_args, image_shape): for ip, ex in image_paths: print("Computing LoG for {}".format(ip)) image = cv2.resize(cv2.imread(ip), image_shape) log_image = cv2.resize(log_funcs.log_image(sigma=1, image=image), image_shape) example_args[ex].update({'log_image': log_image}) def compute_all_logs(example_args): image_paths = ((path.join(BASE_DIR, 'kobe_bryant.jpg'), 'Example_1'), (path.join(BASE_DIR, 'field.jpg'), 'Example_2'), (path.join(BASE_DIR, 'flower.jpg'), 'Example_3')) compute_logs(image_paths=image_paths, example_args=example_args, image_shape=(300, 300)) def p_space(points): pm = {} thetas = range(0, 181) for x, y in points: theta_map = {} for t in thetas: theta = round(math.radians(t)) p = x * math.cos(theta) + y * math.sin(theta) if (theta, p) not in theta_map: theta_map[(theta, p)] = 0 theta_map[(theta, p)] += 1 pm[(x, y)] = theta_map return pm, thetas def local_maxes(p_space): result = {} for k, v in p_space.items(): result[k] = max(v.items(), key=op.itemgetter(1)) return result def edge_points(image): x, y, _ = image.shape ep = [] for r in range(0, x): for c in range(0, y): d1, d2, d3 = map(lambda d: int(d), image[r, c, :]) if {d1, d2, d3} == {255}: ep.append((r, c)) return ep def plot_p_space(space, path): for point, tp in space.items(): th_p, _ = tp theta, p = th_p xs = [] ys = [] for k, v in space.items(): x, y = k comp_p = x * math.cos(theta) + y * math.sin(theta) xs.append((theta, p)) ys.append(comp_p) plt.plot(xs, ys) plt.xlabel('theta') plt.ylabel('p') plt.savefig(path) plt.clf() def compute_p_space(log_image): ep = edge_points(image=log_image) ps, _ = p_space(points=ep) lm = local_maxes(p_space=ps) return lm def show_examples(example_args, image_shape): stars = 110 for ex, ex_args in example_args.items(): oi_image = cv2.resize(cv2.imread(ex_args['original_image']), image_shape) log_image = ex_args['log_image'] lm = compute_p_space(log_image=log_image) plot_p_space(space=lm, path=ex_args['pspace_image']) pspace_image = cv2.imread(ex_args['pspace_image'], cv2.IMREAD_UNCHANGED) show_images = ((ex + '_original', oi_image), (ex + '_LoG', log_image), (ex + '_pspace', pspace_image), (ex + '_overlay', oi_image)) for title, img in show_images: cv2.imshow(title, img) print() print("*" * stars) print("{} description: \n{}".format(ex, ex_args['descr'])) print("*" * stars) print() print("\n\tClick on one of the windows and hit ENTER to exit the program.\n") cv2.waitKey(0) if __name__ == '__main__': compute_all_logs(example_args=EXAMPLE_ARGS) show_examples(example_args=EXAMPLE_ARGS, image_shape=(300, 300)) <file_sep>import cv2 import matplotlib.mlab as mlab import matplotlib.pyplot as plt from matplotlib import cm from functools import reduce import numpy as np import time import tkinter as tk import argparse from PIL import ImageTk, Image from random import randint import os.path as path import os import operator as op TEMP_DIR = 'tmp' ORIG_HISTO_FN = 'orig_histo.png' EQ_HISTO_FN = 'eq_histo.png' ORIG_HISTO_PATH = path.join(TEMP_DIR, ORIG_HISTO_FN) EQ_HISTO_PATH = path.join(TEMP_DIR, EQ_HISTO_FN) def show_images(ims): for im, i in zip(ims, range(0, len(ims))): cv2.imshow('image_' + str(i), im) while True: cv2.waitKey(1000) if input() == 'q': break cv2.destroyAllWindows() def histogram(data): histo = {} for i in data: if i not in histo: histo[i] = 0 histo[i] = histo[i] + 1 return histo def img_histo_added(img): h0, h1, h2 = map(lambda d: histogram(list(img[:, :, d].reshape(-1))), (0, 1, 2)) all_keys = set(list(h0.keys()) + list(h1.keys()) + list(h2.keys())) return {k: reduce(lambda v1, v2: v1 + v2 , map(lambda histo: histo.get(k, 0), (h0, h1, h2))) for k in all_keys} def img_histo(img): return map(lambda d: histogram(list(img[:, :, d].reshape(-1))), (0, 1, 2)) def histogram_plots(img_histos): xs = range(256) num_bins = 256 plt.hist(list(xs), num_bins, facecolor='blue', alpha=0.5) plt.show() def equalization(mat, histo, ab_range, cd_range, c): new_mat = np.zeros(len(mat.reshape(-1))).reshape(mat.shape) ds = mat.shape start = time.time() for r in range(0, mat.shape[0]): for c in range(0, mat.shape[1]): if mat[r][c] in ab_range: ab = sum(map(lambda i: histo.get(i, mat[r][c]), ab_range)) ap = sum(map(lambda i: histo.get(i, mat[r][c]), range(min(ab_range), mat[r][c] + 1)))\ if min(ab_range) <= mat[r][c] else 0 dc = max(cd_range) - min(cd_range) new_mat[r][c] = int((dc / ab) * ap) + c else: new_mat[r][c] = mat[r][c] return new_mat def equalize_image(image, ab_range, cd_range): new_img = image.copy() for h, d in zip(img_histo(image), (0, 1, 2)): print('EQUALIZER, is at image dimension ' + str(d)) eq_mat = equalization(image[:, :, d], h, ab_range, cd_range, 0) new_img[:, :, d] = eq_mat return new_img def equalize_image_name(image_path, image_name): return image_path.replace(image_name, 'histo-equalized-' + image_name) def invoke_equalize(adv, bdv, cdv, ddv, image_path, image_ext, image_name): a, b, c, d = int(adv.get()), int(bdv.get()), int(cdv.get()), int(ddv.get()) if abs(c - d) > 0 and abs(a - b) > 0: eq_img = equalize_image(cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB), range(a, b), range(c, d)) path = equalize_image_name(image_path, image_name) make_histo_from_image(eq_img, EQ_HISTO_PATH) cv2.imwrite(path, eq_img) print('invoke_equalize, wrote path ' + str(path)) else: print("abs(a - b) and abs(c - d) must both be greater than 0") def build_gui(image_path, image_ext, image_name, old_histo_path, eq_histo_path): start_y = 50 image_gap = 40 w_dim = 1000 label_gap = 20 slider_gap = 10 button_gap = 60 image_label_gap = 20 window = tk.Tk() window.title('Histogram equalization') window.geometry('1500x1000') window.configure(background='grey') eq_path = equalize_image_name(image_path, image_name) #histos image = ImageTk.PhotoImage(Image.open(image_path)) orig_histo = ImageTk.PhotoImage(Image.open(old_histo_path)) eq_histo = ImageTk.PhotoImage(Image.open(eq_histo_path)) #equalization if path.exists(eq_path): print('build_gui, reading in equalized image') eq_image = ImageTk.PhotoImage(image=Image.fromarray(cv2.imread(eq_path), 'RGB')) else: print('build_gui, reading in original image') eq_image = image = ImageTk.PhotoImage(Image.open(image_path)) #left side og = 'Original' left_image_label = tk.Text(window, height=1, width=len(og)) left_image_label.place(x=0, y=start_y - image_label_gap) left_image_label.insert(tk.END, og) panel1 = tk.Label(image=image) panel1.place(x=0, y=start_y) panel2 = tk.Label(image=orig_histo) panel2.place(x=0, y=start_y + image.height() + image_gap) #right side eq = 'Equalized' right_image_label = tk.Text(window, height=1, width=len(eq)) right_image_label.place(x=w_dim - image.width(), y=start_y - image_label_gap) right_image_label.insert(tk.END, eq) panel3 = tk.Label(image=eq_image) panel3.place(x=w_dim - eq_image.width(), y=start_y) panel4 = tk.Label(image=eq_histo) panel4.place(x=w_dim - image.width(), y=start_y + image.height() + image_gap) #sliders right side adv, bdv, cdv, ddv = (tk.DoubleVar(), tk.DoubleVar(), tk.DoubleVar(), tk.DoubleVar()) for sl, ig, sv, iv in zip(['a', 'b', 'c', 'd'], (1, 2, 3, 4), (adv, bdv, cdv, ddv), (0, 255, 0, 255)): slider_x = tk.Scale(window, from_=0, to=255, orient=tk.HORIZONTAL, variable=sv) slider_x.set(iv) sl_y = start_y + image.height() + image_gap + eq_image.height() + (image_gap * ig) sl_x = w_dim - image.width() slider_x.place(x=sl_x + label_gap, y=sl_y) text_a = tk.Text(window, height=1, width=2) text_a.place(x=sl_x, y=sl_y) text_a.insert(tk.END, sl) #equalize button eq_button = tk.Button(window, text='equalize', width=25, command=lambda: invoke_equalize(adv, bdv, cdv, ddv, image_path, image_ext, image_name)) eq_button.place(x=w_dim - image.width(), y=start_y + image.height() + image_gap + eq_image.height()\ + (image_gap * 4) + button_gap) button = tk.Button(window, text='Stop', width=15, command=window.destroy) button.pack() window.mainloop() def make_histo_from_image(image, fn): added_histo = img_histo_added(image) k, v = max(added_histo.items(), key=op.itemgetter(1)) added_histo.pop(k) ys = added_histo.values() plt.figure(figsize=((image.shape[0] / 100) + 3, image.shape[1] / 100)) plt.bar(added_histo.keys(), ys) plt.savefig(fn) plt.close() def parse_args(): parser = argparse.ArgumentParser(description='Histogram equalization') parser.add_argument('--image', required=False, help='Path to input image') parser.add_argument('--case', required=False, help='test case run') return parser.parse_args() def make_dirs(dirs): created = [] for d in dirs: if not path.exists(d): os.makedirs(d) created.append(d) return created def run_gui(args): make_dirs([TEMP_DIR]) image = cv2.imread(args.image) make_histo_from_image(image, ORIG_HISTO_PATH) if not path.exists(EQ_HISTO_PATH): make_histo_from_image(image, EQ_HISTO_PATH) base = path.basename(args.image) ext = base[base.index('.'):] name = base[:base.index('.')] build_gui(args.image, ext, name, ORIG_HISTO_PATH, EQ_HISTO_PATH) def test_case(ab_range, cd_range, explanation): in_file = 'images/apple.jpeg' image = cv2.imread(in_file) make_histo_from_image(image, '/tmp/ih.png') ih = cv2.imread('/tmp/ih.png') eq_image = equalize_image(image, ab_range, cd_range) make_histo_from_image(eq_image, '/tmp/eh.png') eh = cv2.imread('/tmp/eh.png') print("Inputs: ab_range: [%d, %d], cd_range: [%d, %d], \n\nExplanation: %s" % (min(ab_range), max(ab_range), min(cd_range), max(cd_range), explanation)) cv2.imshow('original', image) cv2.imshow('original histogram', ih) cv2.imshow('equalized', eq_image) cv2.imshow('equalized histogram', eh) while True: cv2.waitKey(1000) if input() == 'q': break cv2.destroyAllWindows() if __name__ == '__main__': args = parse_args() if args.case == '1': test_case(range(0, 2), range(0, 2), "This is not a good input because the ranges are not wide enough to produce\nA visible effect on the image. As a result, only the black border pixels are changed.") elif args.case == '2': test_case(range(70, 100),range(100, 130), "This case is interesting and a good input. The middle values are equalized and the shiny spot\non the apple is turned to pink and yellow. The shiny portion at the bottom turns yellow as well.") elif args.case == '3': test_case(range(200, 255), range(200, 255), "In this case the ranges are equalized and the apple experiences distortion, which is a bad input. The left\nside appears to turn green while the outer edges have some pixel values other than white.") elif args.image: run_gui(args) else: print("bad inputs")
3c1440fc5996d81ba68500c05ed3425b06727f46
[ "Python" ]
6
Python
getrdone93/image_functions
a8cd655795855bcea0ffa4049bb7ee663838e44d
fb237da41ad56acd73699aed02b85fc3e4a6887f
refs/heads/master
<file_sep>from flask import Flask, render_template, request, url_for, redirect, session from mmxai.interpretability.classification.lime import lime_mmf from shap4mmf import shap_mmf from mmxai.interpretability.classification.torchray.extremal_perturbation import torchray_mmf from mmxai.text_removal.smart_text_removal import SmartTextRemover from app_utils import prepare_explanation, text_visualisation import os import random app = Flask(__name__) app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 app.secret_key = 'Secret Key' def mkdir(path): path = path.strip() path = path.rstrip("\\") isExists = os.path.exists(path) if not isExists: os.makedirs(path) print(path + "Directory created successfully") return True else: print(path + "Directory has already existed!") return False def generate_random_str(randomlength=16): random_str = '' base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789' length = len(base_str) - 1 for i in range(randomlength): random_str += base_str[random.randint(0, length)] return random_str @app.before_request def before_request(): user_id = generate_random_str(8) if session.get('user') is None: mkdir('./static/user/' + user_id) print(user_id + "created") session['user'] = user_id else: print(session.get('user') + " has existed") @app.route('/') def home(): return render_template('home.html') @app.route('/docs/') def docs(): return render_template('docsify.html') @app.route('/explainers/hateful-memes') def hateful_memes(): img_name = session.get('imgName') img_exp = session.get('imgExp') img_text = session.get('imgText') text_exp = session.get('textExp') user_model = session.get('userModel') model_type = session.get('modelType') model_path = session.get('modelPath') cls_result = session.get('clsResult') exp_text_visl = session.get('textVisual') if img_name is None: img_name = 'logo.png' if img_exp is None: img_exp = 'logo.png' if model_path is not None: model_name = model_path.split('/')[-1] # only display part of the filename if the filename is longer than 6 chars name, extension = os.path.splitext(model_name) if len(name) > 6: model_name = name[0:3] + '...' + name[-1] + extension else: model_name = None if user_model == 'no_model': cur_opt = 'MMF ({}) with pretrained checkpoint'.format(model_type) elif user_model == 'mmf': cur_opt = 'MMF ({}) with user checkpoint'.format(model_type) elif user_model == 'onnx': cur_opt = 'ONNX' else: cur_opt = None print("xxx", exp_text_visl) return render_template('explainers/hateful-memes.html', imgName=img_name, imgTexts=img_text, imgExp=img_exp, textExp=text_exp, clsResult=cls_result, curOption=cur_opt, fileName=model_name, textVisual=exp_text_visl) @app.route('/uploadImage', methods=['POST']) def upload_image(): file = request.files['inputImg'] img_name = 'user/' + session['user'] + '/' + file.filename img_path = 'static/' + img_name file.save(img_path) session['imgName'] = img_name session['imgText'] = None session['imgExp'] = None session['textExp'] = None session['textVisual'] = None session['clsResult'] = None return redirect(url_for('hateful_memes')) @app.route('/uploadModel', methods=['POST']) def upload_model(): option = request.form['selectOption'] if option == 'internalModel': selectedModel = request.form['selectModel'] file = request.files['inputCheckpoint1'] file_path = 'user/' + session['user'] + '/' + file.filename session['modelPath'] = file_path session['modelType'] = selectedModel session['userModel'] = 'mmf' file.save('static/' + file_path) elif option == 'selfModel': file = request.files['inputCheckpoint2'] file_path = 'user/' + session['user'] + '/' + file.filename session['modelPath'] = file_path session['modelType'] = None session['userModel'] = 'onnx' file.save('static/' + file_path) elif option == 'noModel': selectedExistingModel = request.form['selectExistingModel'] session['modelType'] = selectedExistingModel session['modelPath'] = None session['userModel'] = 'no_model' else: raise Exception("Sorry, you must select an option to continue!!!") return redirect(url_for('hateful_memes')) @app.route('/inpaint') def inpaint(): img_name = session.get('imgName') # Prepare the image path and names folder_path = 'static/' image_path = folder_path + img_name img_name_no_extension = os.path.splitext(img_name)[0] img_extension = os.path.splitext(img_name)[1] inpainted_image_name = img_name_no_extension + "_inpainted" + img_extension save_path = folder_path + inpainted_image_name print(save_path) if not os.path.isfile(save_path): # Load the inpainter inpainter = SmartTextRemover( "../mmxai/text_removal/frozen_east_text_detection.pb") # Inpaint image img_inpainted = inpainter.inpaint(image_path) # save inpainted image img_inpainted.save(save_path) session['imgName'] = inpainted_image_name return redirect(url_for('hateful_memes')) @app.route('/restoreImage') def restore(): img_path = session['imgName'] root, extension = os.path.splitext(img_path) if '_inpainted' in root: img_path = root[:-10] + extension session['imgName'] = img_path return redirect(url_for('hateful_memes')) @app.route('/explainers/hateful-memes/predict', methods=['POST']) def predict(): img_text = request.form['texts'] exp_method = request.form['expMethod'] exp_direction = request.form['expDir'] user_model = session.get('userModel') img_name = session.get('imgName') model_type = session.get('modelType') model_path = session.get('modelPath') model, label_to_explain, cls_label, cls_confidence = prepare_explanation( img_name, img_text, user_model, model_type, model_path, exp_direction) hateful = 'HATEFUL' if cls_label == 1 else 'NON-HATEFUL' cls_result = 'Your uploaded image and text combination ' \ 'looks like a {} meme, with {}% confidence.'.format(hateful, "%.2f" % (cls_confidence * 100)) print(cls_result) if exp_method == 'shap': text_exp, img_exp = shap_mmf.shap_multimodal_explain(img_name, img_text, model) elif exp_method == 'lime': text_exp, img_exp = lime_mmf.lime_multimodal_explain(img_name, img_text, model) elif exp_method == 'torchray': text_exp, img_exp = torchray_mmf.torchray_multimodal_explain(img_name, img_text, model) else: text_exp, img_exp = shap_mmf.shap_multimodal_explain(img_name, img_text, model) session['clsResult'] = cls_result session['imgText'] = img_text session['textExp'] = text_exp session['imgExp'] = img_exp img_exp_name, _ = os.path.splitext(img_exp) exp_text_visl = img_exp_name + '_text.png' try: print("SHAP text") print(type(text_exp)) print(text_exp) text_visualisation(text_exp, cls_label, exp_text_visl) session['textVisual'] = exp_text_visl except: print("error unable to plot shap text") session['textVisual'] = None print(session['imgText']) print(session['textExp']) print(session['imgExp']) print(session['modelPath']) return redirect(url_for('hateful_memes')) if __name__ == '__main__': app.run()
08bf54b4ead2acb3fbf3c85bc83ca2c77b09bd23
[ "Python" ]
1
Python
yongkangzzz/mmxai
36bd869919c25d07e553cd8fac2fd22e32014a96
31bad989a7e6ca2ea3f8540e60e4b4b5da6ee3a6
refs/heads/master
<file_sep>let obj={}; //获取所有商品数据 obj.getGoodsList=function(){ return JSON.parse(window.localStorage.getItem('goods')||'{}'); } //保存商品 obj.saveGoods = function(goodsList){ //本地存储 window.localStorage.setItem('goods',JSON.stringify(goodsList)); } //新增一个商品 obj.add=function(goods){ //判断goodsList是否有该商品,有则追加,无则赋值 let goodsList= this.getGoodsList(); if(goodsList[goods.id]){ //有就追加 goodsList[goods.id]+=goods.num; }else{ goodsList[goods.id]=goods.num; } //保存数据 this.saveGoods(goodsList); } //获取购物车总数 obj.getTotalCount=function(){ let goodsList = this.getGoodsList(); let values = Object.values(goodsList); let num=0; values.forEach(val=>sum+=val); return sum; } export default obj;
edda48845e243bce9f7a0fcf726c82966ae1816c
[ "JavaScript" ]
1
JavaScript
wodeshiyong/vue-imitation-demo
0cc0c3ee142c62901b37200f08821fa73f9ee91c
c3cf2f07103aed31ea59c487b50ab60d821cc297
refs/heads/master
<file_sep>package lab05; import java.util.ArrayList; import java.util.Iterator; /** * Controle de cenarios em um sistema de aposta. * O controle possui uma lista de cenarios no sistema, * o valor em caixa e uma porcentagem de quanto deve * ser retirado para o caixa. * @author <NAME> * */ public class ControllerCenario { private ArrayList<Cenario> cenarios; private int caixa; private double porcentagemRetirada; /** * O sistema eh iniciado com um valor inicial em caixa * e a porcentagem que deve ser retirada das apostas para o * caixa. * @param valorCaixa valor inicial do caixa. * @param porcentagem porcentagem de retirada para o caixa. */ public ControllerCenario(int valorCaixa, double porcentagem) { if(valorCaixa<0) throw new IllegalArgumentException("Erro na inicializacao: Caixa nao pode ser inferior a 0"); if(porcentagem<0) throw new IllegalArgumentException("Erro na inicializacao: Taxa nao pode ser inferior a 0"); this.cenarios = new ArrayList<>(); this.caixa = valorCaixa; this.porcentagemRetirada = porcentagem; } /** * Retorna um inteiro representando * o valor em caixa do sistema. * @return o valor em caixa do sistema. */ public int getCaixa() { return this.caixa; } /** * Verifica se a numeracao do cenario eh valida. * Um cenario valido eh o que sua numeracao esta * lista dos cenarios cadastrados. * @param cenario numeracao de um cenario. */ public int isValid(int cenario) { if(cenario < 0) return 0; else if(cenario >=cenarios.size()){ return 1; } return 2; } /** * Cadastra cenario no sistema a partir * de uma descricao e retorna a numeracao * dada pelo sistema ao cenario. * @param descricao descricao do sistema. * @return numeracao do sistema cadastrado. */ public int cadastrarCenario(String descricao) { cenarios.add(new Cenario(descricao)); return cenarios.size(); } /** * Retorna uma string representando um cenario * pesquisado a partir da sua numeracao. * * @param numeracao numeracao do cenario a ser exibido. * @return representacao em string do cenario buscado. */ public String exibirCenario(int numeracao) { if(numeracao-1 < 0) throw new IllegalArgumentException("Erro na consulta de cenario: Cenario invalido"); else if(numeracao-1 >=cenarios.size()){ throw new IllegalArgumentException("Erro na consulta de cenario: Cenario nao cadastrado"); } String res = numeracao + " - "; res +=cenarios.get(numeracao-1).toString(); return res; } /** * Retorna uma string representando uma lista * com a representacao de todos os cenarios * cadastrados no sistema. * @return representacao em string de todos os cenarios * cadastrados no sistema. */ public String exibirCenarios() { Iterator <Cenario> it = cenarios.iterator(); String res = ""; int index = 1; while(it.hasNext()){ res+= index++ + " - " + it.next().toString() + "\n"; } return res; } /** * Fecha um cenario a partir da sua numeracao e * a informacao se ele ocorreu ou nao. * A informacao se ocorreu ou nao ocorreu eh dada * a partir de um boolean que eh True se ocorreu * e False caso contrario. * * @param cenario inteiro que representa a * numeracao do cenario a ser fechado. * * @param ocorreu informacao se o cenario ocorreu ou nao. */ public void fecharCenario(int cenario, boolean ocorreu) { if(cenario-1 < 0) throw new IllegalArgumentException("Erro ao fechar aposta: Cenario invalido"); else if(cenario-1 >=cenarios.size()){ throw new IllegalArgumentException("Erro ao fechar aposta: Cenario nao cadastrado"); } if(ocorreu) { cenarios.get(cenario-1).fecharCenario(Estado.FINALIZADO_OCORREU); }else { cenarios.get(cenario-1).fecharCenario(Estado.FINALIZADO_NAO_OCORREU); } this.caixa += getCaixaCenario(cenario); } /** * Retorna um inteiro representado o valor de um * cenario finalizado, que sera * adicionado ao caixa do sistema. * @param cenario numeracao do cenario * @return valor de um cenario que sera adicionado ao caixa do sistema. */ public int getCaixaCenario(int cenario) { if(cenario-1 < 0) throw new IllegalArgumentException("Erro na consulta do caixa do cenario: Cenario invalido"); else if(cenario-1 >=cenarios.size()){ throw new IllegalArgumentException("Erro na consulta do caixa do cenario: Cenario nao cadastrado"); } int soma_perdedoras = cenarios.get(cenario-1).getSomaPerdedoras(); if(soma_perdedoras == -1) throw new IllegalArgumentException("Erro na consulta do caixa do cenario: Cenario ainda esta aberto"); int caixaCenario = (int) (soma_perdedoras * this.porcentagemRetirada); //caixaCenario*=100; return caixaCenario; } /** * Retorna o valor total das apostas do cenario que sera * rateado entre as apostas vencedoras do cenario. * * @param cenario numeracao do cenario. * * @return inteiro representado o valor a ser rateado * entre as apostas vencedoras. * */ public int getTotalRateio(int cenario) { if(cenario-1 < 0) throw new IllegalArgumentException("Erro na consulta do total de rateio do cenario: Cenario invalido"); else if(cenario-1 >=cenarios.size()){ throw new IllegalArgumentException("Erro na consulta do total de rateio do cenario: Cenario nao cadastrado"); } int rateio = cenarios.get(cenario-1).getSomaPerdedoras(); if(rateio==-1) { throw new IllegalArgumentException("Erro na consulta do total de rateio do cenario: Cenario ainda esta aberto"); } rateio -= getCaixaCenario(cenario); return rateio; } } <file_sep>package lab05; import easyaccept.EasyAccept; public class Facade { private ControllerCenario controleCenarios; public Facade() { controleCenarios = new ControllerCenario(100000, 0.01); } public static void main(String[] args) { args = new String[] {"lab05.Facade", "acceptance_test/eu.txt"}; //EasyAccept.main(args1); EasyAccept.main(args); } public void inicializa(int caixa, double porcentagem) { this.controleCenarios = new ControllerCenario(caixa, porcentagem); } public int getCaixa() { return this.controleCenarios.getCaixa(); } public int cadastrarCenario(String descricao) { return this.controleCenarios.cadastrarCenario(descricao); } public String exibirCenario(int numeracao) { return this.controleCenarios.exibirCenario(numeracao); } public String exibirCenarios() { return this.controleCenarios.exibirCenarios(); } public void cadastrarAposta(int cenario, String apostador, int valor, String previsao) { this.controleCenarios.cadastrarAposta(cenario, apostador, valor, previsao); } public int valorTotalDeApostas(int cenario) { return controleCenarios.valorTotalDeApostas(cenario); } public int totalDeApostas(int cenario) { return controleCenarios.totalDeApostas(cenario); } public String exibeApostas(int cenario) { return controleCenarios.exibeApostas(cenario); } public void fecharAposta(int cenario, boolean ocorreu) { controleCenarios.fecharCenario(cenario, ocorreu); } public int getCaixaCenario(int cenario) { return controleCenarios.getCaixaCenario(cenario); } public int getTotalRateioCenario(int cenario) { return controleCenarios.getTotalRateio(cenario); } } <file_sep>package testes; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import lab05.ControllerCenario; public class ControllerCenarioTest { ControllerCenario controleCenario; @Before public void setUp(){ controleCenario = new ControllerCenario(100, 0.01); } @Test(expected = IllegalArgumentException.class) public void sistemaApostasCaixaNegativoTest() { controleCenario = new ControllerCenario(-100, 0.1); } @Test(expected = IllegalArgumentException.class) public void sistemaApostasCaixaZeroTest() { controleCenario = new ControllerCenario(0, 0.1); } @Test(expected = IllegalArgumentException.class) public void sistemaApostasPorcentagemZeroTest() { controleCenario = new ControllerCenario(100, 0); } @Test(expected = IllegalArgumentException.class) public void sistemaApostasPorcentagemNegativoTest() { controleCenario = new ControllerCenario(100, -1); } @Test public void cadastrarCenarioTest() { int expected = 1; assertEquals(expected, controleCenario.cadastrarCenario("Todos os alunos vao ser aprovados")); } @Test public void exibirCenarioTest() { controleCenario.cadastrarCenario("Todos os alunos vao ser aprovados"); String expected = "1 - Todos os alunos vao ser aprovados - Nao finalizado"; assertEquals(expected, controleCenario.exibirCenario(1)); } @Test(expected = IllegalArgumentException.class) public void exibirCenarioNumeracaoInvalidaTest() { controleCenario.cadastrarCenario("Todos os alunos vao ser aprovados"); String expected = "1 - Todos os alunos vao ser aprovados - Nao finalizado"; assertEquals(expected, controleCenario.exibirCenario(2)); } @Test public void exibirCenariosTest() { controleCenario.cadastrarCenario("Todos os alunos vao ser aprovados"); controleCenario.cadastrarCenario("Todos os alunos vao ser reprovados"); String expected = "1 - Todos os alunos vao ser aprovados - Nao finalizado\n" + "2 - Todos os alunos vao ser reprovados - Nao finalizado\n" ; assertEquals(expected, controleCenario.exibirCenarios()); } @Test(expected = IllegalArgumentException.class) public void fecharCenarioNumeracaoInvalidaTest() { controleCenario.cadastrarCenario("Todos os alunos vao ser aprovados"); controleCenario.fecharCenario(0, false); } @Test(expected = IllegalArgumentException.class) public void fecharCenarioFinalizadoTest() { controleCenario.cadastrarCenario("Todos os alunos vao ser aprovados"); //fechando cenario controleCenario.fecharCenario(1, false); //tentando fechar o mesmo cenario controleCenario.fecharCenario(1, true); } @Test(expected = IllegalArgumentException.class) public void cadastrarApostaTestNumeracaoInvalidaTest() { controleCenario.cadastrarCenario("Todos os alunos vao ser aprovados"); controleCenario.cadastrarAposta(2, "Brito", 200, "N VAI ACONTECER"); } @Test public void totalDeApostasTest() { controleCenario.cadastrarCenario("Todos os alunos vao ser aprovados"); controleCenario.cadastrarAposta(1, "Brito", 200, "N VAI ACONTECER"); controleCenario.cadastrarAposta(1, "Mateus", 200, "VAI ACONTECER"); int expected = 2; assertEquals(expected, controleCenario.totalDeApostas(1)); } @Test(expected = IllegalArgumentException.class) public void totalDeApostasCenarioInvalidoTest() { controleCenario.cadastrarCenario("Todos os alunos vao ser aprovados"); controleCenario.cadastrarAposta(1, "Brito", 200, "N VAI ACONTECER"); controleCenario.cadastrarAposta(1, "Mateus", 200, "VAI ACONTECER"); int expected = 2; assertEquals(expected, controleCenario.totalDeApostas(2)); } @Test(expected = IllegalArgumentException.class) public void valorTotalDeApostasCenarioInvalidoTest() { controleCenario.cadastrarCenario("Todos os alunos vao ser aprovados"); controleCenario.cadastrarAposta(1, "Brito", 200, "N VAI ACONTECER"); controleCenario.cadastrarAposta(1, "Mateus", 200, "VAI ACONTECER"); int expected = 2; assertEquals(expected, controleCenario.valorTotalDeApostas(2)); } @Test public void valorTotalDeApostasTest() { controleCenario.cadastrarCenario("Todos os alunos vao ser aprovados"); controleCenario.cadastrarAposta(1, "Brito", 200, "N VAI ACONTECER"); controleCenario.cadastrarAposta(1, "Mateus", 200, "VAI ACONTECER"); int expected = 400; assertEquals(expected, controleCenario.valorTotalDeApostas(1)); } @Test public void getcaixaCenarioTest() { controleCenario.cadastrarCenario("Todos os alunos vao ser aprovados"); controleCenario.cadastrarAposta(1, "<NAME>", 200, "VAI ACONTECER"); controleCenario.cadastrarAposta(1, "Brito", 200, "N VAI ACONTECER"); controleCenario.fecharCenario(1, true); int expected = 2; assertEquals(expected, controleCenario.getCaixaCenario(1)); } @Test(expected = IllegalArgumentException.class) public void getcaixaCenarioNumeracaoInvalidaTest() { controleCenario.cadastrarCenario("Todos os alunos vao ser aprovados"); controleCenario.cadastrarAposta(1, "<NAME>", 200, "VAI ACONTECER"); controleCenario.cadastrarAposta(1, "Brito", 200, "N VAI ACONTECER"); controleCenario.fecharCenario(1, true); int expected = 2; assertEquals(expected, controleCenario.getCaixaCenario(2)); } @Test public void getTotalRateioTest() { controleCenario.cadastrarCenario("Todos os alunos vao ser aprovados"); controleCenario.cadastrarAposta(1, "<NAME>", 200, "VAI ACONTECER"); controleCenario.cadastrarAposta(1, "Brito", 200, "N VAI ACONTECER"); controleCenario.fecharCenario(1, true); int expected = 198; assertEquals(expected, controleCenario.getTotalRateio(1)); } @Test(expected = IllegalArgumentException.class) public void getTotalRateioNumeracaoInvalidaTest() { controleCenario.cadastrarCenario("Todos os alunos vao ser aprovados"); controleCenario.cadastrarAposta(1, "<NAME>", 200, "VAI ACONTECER"); controleCenario.cadastrarAposta(1, "Brito", 200, "N VAI ACONTECER"); controleCenario.fecharCenario(1, true); int expected = 198; assertEquals(expected, controleCenario.getTotalRateio(2)); } @Test public void exibeApostasTest() { controleCenario.cadastrarCenario("Todos os alunos vao ser aprovados"); controleCenario.cadastrarAposta(1, "<NAME>", 200, "VAI ACONTECER"); controleCenario.cadastrarAposta(1, "Brito", 200, "N VAI ACONTECER"); String expected = "Francisco Cisco - R$200.0 - Vai acontecer\n" + "Brito - R$200.0 - Nao vai acontecer\n"; assertEquals(expected, controleCenario.exibeApostas(1)); } @Test(expected = IllegalArgumentException.class) public void exibeApostasNumeracaoInvalidaTest() { controleCenario.cadastrarCenario("Todos os alunos vao ser aprovados"); controleCenario.cadastrarAposta(1, "<NAME>", 200, "VAI ACONTECER"); controleCenario.cadastrarAposta(1, "Brito", 200, "N VAI ACONTECER"); String expected = "Francisco Cisco - R$200 - Vai acontecer\n" + "Brito - R$200 - Nao vai acontecer\n"; assertEquals(expected, controleCenario.exibeApostas(2)); } } <file_sep>package testes; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import lab05.Cenario; import lab05.Estado; public class CenarioTest { private Cenario cenario; @Before public void setUp() { cenario = new Cenario("Todos os alunos vao ser aprovados"); } @Test(expected = NullPointerException.class) public void cenarioComDescricaoNulaTest() { cenario = new Cenario(null); } @Test(expected = IllegalArgumentException.class) public void cenarioComDescricaoVaziaTest() { cenario = new Cenario(" "); } @Test(expected = NullPointerException.class) public void cadastraApostaComNomeNullTest() { cenario.cadastrarAposta(null, 200, "VAI ACONTECER"); } @Test(expected = IllegalArgumentException.class) public void cadastraApostaComNomeVazioTest() { cenario.cadastrarAposta(" ", 2000, "N VAI ACONTECER"); } @Test(expected = IllegalArgumentException.class) public void fecharCenarioFinalizadoTest() { cenario.fecharCenario(Estado.FINALIZADO_OCORREU); cenario.fecharCenario(Estado.FINALIZADO_NAO_OCORREU); } @Test public void getApostasPerdedorasTest() { cenario.cadastrarAposta("Jose", 200, "VAI ACONTECER"); cenario.cadastrarAposta("Joao", 500, "N VAI ACONTECER"); int expected = 500; cenario.fecharCenario(Estado.FINALIZADO_OCORREU); assertEquals(expected, (int)cenario.getSomaPerdedoras()); } @Test(expected = IllegalArgumentException.class) public void getApostasPerdedorasCenarioNaoFinalizadoTest() { cenario.getSomaPerdedoras(); } @Test public void listarApostasTest() { cenario.cadastrarAposta("Jose", 200, "VAI ACONTECER"); cenario.cadastrarAposta("Joao", 500, "N VAI ACONTECER"); String expected = "Jose - R$200.0 - Vai acontecer\n" + "Joao - R$500.0 - Nao vai acontecer\n"; assertEquals(expected, cenario.listarApostas()); } @Test public void numeroApostasTest() { cenario.cadastrarAposta("Jose", 200, "VAI ACONTECER"); cenario.cadastrarAposta("Joao", 500, "N VAI ACONTECER"); assertEquals(2, cenario.numeroApostas()); } @Test public void valorApostasCenarioTest() { cenario.cadastrarAposta("Jose", 200, "VAI ACONTECER"); cenario.cadastrarAposta("Joao", 500, "N VAI ACONTECER"); assertEquals(700, cenario.valorApostas()); } @Test public void getDescricaoTest() { String expected = "Todos os alunos vao ser aprovados"; assertEquals(expected, cenario.getDescricao()); } @Test public void toStringCenarioNaoFinalizadoTest() { String expected = "Todos os alunos vao ser aprovados - Nao finalizado"; assertEquals(expected, cenario.toString()); } @Test public void toStringCenarioFinalizadoOcorreuTest() { cenario.fecharCenario(Estado.FINALIZADO_OCORREU); String expected = "Todos os alunos vao ser aprovados - Finalizado (ocorreu)"; assertEquals(expected, cenario.toString()); } public void toStringCenarioFinalizadoNaoOcorreuTest() { cenario.fecharCenario(Estado.FINALIZADO_NAO_OCORREU); String expected = "Todos os alunos vao ser aprovados - Finalizado ( n ocorreu)"; assertEquals(expected, cenario.toString()); } } <file_sep>package lab05; /** * Representacao de uma aposta que pode ou nao ocorrer. * Uma aposta armazena o nome do apostador, * o valor apostado e a previsao (ocorre ou nao ocorre). * * @author <NAME> */ public class Aposta { private String nomeApostador; private double valorAposta; private Previsao previsao; private int cenario; /** * Constroi uma aposta utilizando o nome do apostador, * o valor que foi apostado e a previsao (vai ou nao ocorrer). * @param nomeApostador nome do apostador. * @param valorAposta valor apostado. * @param previsao previsao da aposta. */ public Aposta(int cenario, String nomeApostador, double valorAposta, String previsao) { isValid(nomeApostador,valorAposta, previsao); if(previsao.equals("N VAI ACONTECER")) { this.previsao = Previsao.NAO_VAI_ACONTECER; }else if(previsao.equals("VAI ACONTECER")){ this.previsao = Previsao.VAI_ACONTECER; }else { throw new IllegalArgumentException("Erro no cadastro de aposta: Previsao invalida"); } this.nomeApostador = nomeApostador; this.valorAposta = valorAposta; } private void isValid(String nomeApostador, double valorAposta, String previsao) { if(nomeApostador==null) throw new NullPointerException("Erro no cadastro de aposta: Apostador nao pode ser vazio ou nulo"); if(nomeApostador.trim().equals("")) throw new IllegalArgumentException("Erro no cadastro de aposta: Apostador nao pode ser vazio ou nulo"); if(valorAposta<=0) throw new IllegalArgumentException("Erro no cadastro de aposta: Valor nao pode ser menor ou igual a zero"); if(previsao.trim().equals("")) throw new IllegalArgumentException("Erro no cadastro de aposta: Previsao nao pode ser vazia ou nula"); } /** * Retorna um double representando o valor da aposta. * @return valor da aposta. */ public double getValor() { return this.valorAposta; } public int getCenario() { return this.cenario; } /** * Retorna a representacao em string * de uma aposta. * A representacao segue o formato * nome do apostador - R$ valor da aposta - previsao(vai ocorrer ou nao vai ocorrer) * * @return representacao em string da aposta. */ public String toString() { return this.nomeApostador + " - R$" + this.valorAposta + " - " + this.previsao.getPrevisao(); } } <file_sep>package lab05; import java.util.ArrayList; import java.util.Iterator; public class ControllerAposta { private ArrayList <Aposta> apostas; public ControllerAposta() { apostas = new ArrayList<>(); } /** * Cadastra apostas em um determinado cenario. * Eh necessario que seja informado um inteiro * que representa o cenario no qual a aposta deve ser * cadastrada. * @param cenario inteiro que representa um cenario. * @param apostador nome do apostador. * @param valor valor da aposta. * @param previsao previsao para aposta(ocorre ou nao ocorre). */ public void cadastrarAposta(int cenario, String nomeApostador, int valorAposta, String previsao) { apostas.add(new Aposta(cenario, nomeApostador, valorAposta, previsao)); } /** * Retorna a soma de todas as apostas perdedoras. * @return soma das apostas perdedoras. */ public int getSomaPerdedoras(int cenario) { if(this.estado.equals(Estado.NAO_FINALIZADO)) return -1; if(this.estado.equals(Estado.FINALIZADO_OCORREU)) { return (int)soma_nao_ocorre; } return (int)soma_ocorre; } /** * Retorna as representacoes em string das * apostas cadastradas em um determinado cenario. * * @return representacoes em string das apostas no cenario. */ public String listarApostas(int cenario) { Iterator <Aposta> it = apostas.iterator(); String res = ""; while(it.hasNext()){ Aposta aposta = it.next(); if(aposta.getCenario() == cenario) { res += aposta.toString() + "\n"; } } return res; } /** * Retorna o numero de apostas de um determinado cenario. * @param cenario inteiro que representa um cenario. * @return numero de apostas em um cenario. */ public int numeroApostas(int cenario) { int cont = 0; for(Aposta aposta : apostas) { if(aposta.getCenario() == cenario) { cont++; } } return cont; } /** * Retorna o valor total de apostas de um * determinado cenario. * @param cenario inteiro que representa um cenario. * @return valor total de apostas em um cenario. */ public int valorApostas(int cenario) { int valor = 0; for(Aposta aposta : apostas) { if(aposta.getCenario() == cenario) { valor += aposta.getValor(); } } return valor; } }
a04461ad8b563fe46f274d208a0b02eaf46aced5
[ "Java" ]
6
Java
jmarcelinho/Lab5.1
970b76c75420722680ad47dbcfd10975519700c9
7b50fce4850e70717bf2eb7965770a428c33bd53
refs/heads/master
<file_sep>package com.tdc.vpp.Activities.Admin; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.tdc.vpp.Adapter.ManagerAdapter; import com.tdc.vpp.Adapter.UserAdapter; import com.tdc.vpp.Core.Broadcast; import com.tdc.vpp.Core.Config; import com.tdc.vpp.Core.LocalData; import com.tdc.vpp.Core.LocalStorage; import com.tdc.vpp.Core.Nav; import com.tdc.vpp.Core.Utils; import com.tdc.vpp.Entities.Manager; import com.tdc.vpp.Entities.User; import com.tdc.vpp.R; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import cz.msebera.android.httpclient.Header; public class StationeryDetailActivity extends AppCompatActivity implements View.OnClickListener{ private String StationeryId; private Button AddManager, AddUser; private ArrayList<Manager> managers; private ArrayList<User> users; private ManagerAdapter managerAdapter; private UserAdapter userAdapter; private ListView ListManager, ListUser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_stationery_detail); managers = new ArrayList<Manager>(); users = new ArrayList<User>(); managerAdapter = new ManagerAdapter(this, R.layout.item_general, managers); userAdapter = new UserAdapter(this, R.layout.item_general, users); StationeryId = getIntent().getExtras().getString("StationeryId"); AddManager = (Button) findViewById(R.id.AddManager); AddManager.setOnClickListener(this); AddUser = (Button) findViewById(R.id.AddUser); AddUser.setOnClickListener(this); ListManager = (ListView) findViewById(R.id.ListManager); ListManager.setAdapter(managerAdapter); ListUser = (ListView) findViewById(R.id.ListUser); ListUser.setAdapter(userAdapter); showManagers(); showUsers(); getManagers(); getUsers(); registerBroadcast(); } private void registerBroadcast() { IntentFilter filter = new IntentFilter(); filter.addAction(Broadcast.ACCOUNT_SELECT); filter.addAction(Broadcast.RELOAD_MANAGERS); filter.addAction(Broadcast.RELOAD_USERS); OnBroadcast onBroadcast = new OnBroadcast(); registerReceiver(onBroadcast, filter); } private class OnBroadcast extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equalsIgnoreCase(Broadcast.ACCOUNT_SELECT)) { String Id = intent.getExtras().getString("Id"); if (Id.equalsIgnoreCase(StationeryId + "MANAGER")) { String accountId = intent.getExtras().getString("AccountId"); createManager(accountId); return; } if (Id.equalsIgnoreCase(StationeryId + "USER")) { String accountId = intent.getExtras().getString("AccountId"); createUser(accountId); return; } return; } if (intent.getAction().equalsIgnoreCase(Broadcast.RELOAD_MANAGERS)) { getManagers(); return; } if (intent.getAction().equalsIgnoreCase(Broadcast.RELOAD_USERS)) { getUsers(); return; } } } public void showManagers() { LocalData.loadManagers(); managers.clear(); for (int i = 0; i < LocalData.Managers.size(); i++) { if (LocalData.Managers.get(i).getStationeryId().equals(StationeryId)) { managers.add(LocalData.Managers.get(i)); } } managerAdapter.notifyDataSetChanged(); } public void showUsers() { LocalData.loadUsers(); users.clear(); for (int i = 0; i < LocalData.Users.size(); i++) { if (LocalData.Users.get(i).getStationeryId().equals(StationeryId)) { users.add(LocalData.Users.get(i)); } } userAdapter.notifyDataSetChanged(); } private void createManager(String accountId) { AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = Utils.UserParams(); params.put("stationeryid", StationeryId); params.put("accountid", accountId); client.post(Config.BaseURL +"/admin/stationery/manager", params, new JsonHttpResponseHandler() { public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { if (response.getBoolean("Success")) { getManagers(); } else Utils.messageShort(Config.CurrentActivity, response.getString("Message")); } catch (Exception E) {} } }); } private void createUser(String accountId) { AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = Utils.UserParams(); params.put("stationeryid", StationeryId); params.put("accountid", accountId); client.post(Config.BaseURL +"/admin/stationery/user", params, new JsonHttpResponseHandler() { public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { if (response.getBoolean("Success")) { getUsers(); } else Utils.messageShort(Config.CurrentActivity, response.getString("Message")); } catch (Exception E) {} } }); } private void getManagers() { AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = Utils.UserParams(); client.get(Config.BaseURL +"/admin/sms", params, new JsonHttpResponseHandler() { public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { if (response.getBoolean("Success")) { JSONArray result = response.getJSONArray("Result"); LocalStorage.clean("Managers"); LocalData.saveManagers(result); showManagers(); } else Utils.messageShort(Config.CurrentActivity, response.getString("Message")); } catch (Exception E) {} } }); } private void getUsers() { AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = Utils.UserParams(); client.get(Config.BaseURL +"/admin/sus", params, new JsonHttpResponseHandler() { public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { if (response.getBoolean("Success")) { JSONArray result = response.getJSONArray("Result"); LocalStorage.clean("Users"); LocalData.saveUsers(result); showUsers(); } else Utils.messageShort(Config.CurrentActivity, response.getString("Message")); } catch (Exception E) {} } }); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.AddManager: { Nav.selectAccount(this, StationeryId + "MANAGER", 1); break; } case R.id.AddUser: { Nav.selectAccount(this, StationeryId + "USER", 2); break; } } } } <file_sep>package com.tdc.vpp.Activities; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.tdc.vpp.Core.Config; import com.tdc.vpp.Core.Nav; import com.tdc.vpp.Core.Utils; import com.tdc.vpp.R; import org.json.JSONObject; import cz.msebera.android.httpclient.Header; public class LoginActivity extends AppCompatActivity implements View.OnClickListener{ private EditText Username, Password; private Button Login; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); Config.CurrentActivity = this; Username = (EditText) findViewById(R.id.Username); Password = (EditText) findViewById(R.id.Password); Login = (Button) findViewById(R.id.Login); Login.setOnClickListener(this); logged(); } private void logged() { Config.load(); Username.setText(Config.Username); if ((Config.UserId != null) && (Config.UserId != "") && (Config.Token != null) && (Config.Token != "")) { openPanel(); } } private void openPanel() { switch (Config.Type) { case 0: { Nav.openAdminPanel(this); break; } case 1: { Nav.openManagerPanel(this); break; } case 2: { Nav.openUserPanel(this); break; } } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.Login: { login(); break; } } } private void login() { Config.Username = Username.getText().toString(); AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); params.put("username", Username.getText()); params.put("password", <PASSWORD>()); client.get(Config.BaseURL +"/login", params, new JsonHttpResponseHandler() { public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { if (response.getBoolean("Success")) { JSONObject result = response.getJSONObject("Result"); Config.UserId = result.getString("Id"); Config.Token = result.getString("Token"); Config.Type = result.getInt("Type"); Config.save(); openPanel(); } else Utils.messageLong(LoginActivity.this, response.getString("Message")); } catch (Exception E) { Utils.messageLong(LoginActivity.this, E.getMessage()); } } }); } } <file_sep>package com.tdc.vpp.Adapter; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.TextView; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.tdc.vpp.Core.Broadcast; import com.tdc.vpp.Core.Config; import com.tdc.vpp.Core.LocalData; import com.tdc.vpp.Core.Utils; import com.tdc.vpp.Entities.Item; import com.tdc.vpp.R; import org.json.JSONObject; import java.util.ArrayList; import cz.msebera.android.httpclient.Header; public class ItemAdapter extends ArrayAdapter<Item> { private Activity context = null; private ArrayList<Item> datas = null; private int layoutId; public ItemAdapter(Activity context, int layoutId, ArrayList<Item> datas){ super(context, layoutId, datas); this.context = context; this.layoutId = layoutId; this.datas = datas; } public View getView(int position, View convertView, ViewGroup parent) { if ((position >= 0) && (position < datas.size())) { LayoutInflater inflater = context.getLayoutInflater(); convertView = inflater.inflate(layoutId, null); Item obj = datas.get(position); TextView Name = (TextView) convertView.findViewById(R.id.Name); Name.setText("Name: " + obj.getName()); TextView Count = (TextView) convertView.findViewById(R.id.Count); Count.setText("Count: " + obj.getCount()); TextView Price = (TextView) convertView.findViewById(R.id.Price); Price.setText("Price: " + obj.getPrice()); } return convertView; } }<file_sep>package com.tdc.vpp.Activities.Admin; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.tdc.vpp.Core.Broadcast; import com.tdc.vpp.Core.Config; import com.tdc.vpp.Core.LocalData; import com.tdc.vpp.Core.LocalStorage; import com.tdc.vpp.Core.Nav; import com.tdc.vpp.Core.Utils; import com.tdc.vpp.R; import org.json.JSONArray; import org.json.JSONObject; import cz.msebera.android.httpclient.Header; public class AdminPanelActivity extends AppCompatActivity implements View.OnClickListener { private Button Admins, Managers, Users, Stationeries, Logout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_admin_panel); Config.CurrentActivity = this; Admins = (Button) findViewById(R.id.Admins); Admins.setOnClickListener(this); Managers = (Button) findViewById(R.id.Managers); Managers.setOnClickListener(this); Users = (Button) findViewById(R.id.Users); Users.setOnClickListener(this); Stationeries = (Button) findViewById(R.id.Stationeries); Stationeries.setOnClickListener(this); Logout = (Button) findViewById(R.id.Logout); Logout.setOnClickListener(this); getAccounts(); registerBroadcast(); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.Admins: { Nav.openAdmins(this); break; } case R.id.Managers: { Nav.openManagers(this); break; } case R.id.Users: { Nav.openUsers(this); break; } case R.id.Stationeries: { Nav.openStationeries(this); break; } case R.id.Logout: { Utils.logout(); break; } } } private void registerBroadcast() { IntentFilter filter = new IntentFilter(); filter.addAction(Broadcast.RELOAD_ACCOUNTS); OnBroadcast onBroadcast = new OnBroadcast(); registerReceiver(onBroadcast, filter); } private class OnBroadcast extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equalsIgnoreCase(Broadcast.RELOAD_ACCOUNTS)) { getAccounts(); return; } } } private void getAccounts() { AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = Utils.UserParams(); client.get(Config.BaseURL +"/admin/accounts", params, new JsonHttpResponseHandler() { public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { if (response.getBoolean("Success")) { JSONArray result = response.getJSONArray("Result"); LocalStorage.clean("Accounts"); LocalData.saveAccounts(result); Broadcast.reloadAccountsList(); } else Utils.logout(); } catch (Exception E) {} } }); } } <file_sep>package com.tdc.vpp.Activities.Manager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.tdc.vpp.Core.Config; import com.tdc.vpp.Core.LocalData; import com.tdc.vpp.Core.LocalStorage; import com.tdc.vpp.Core.Nav; import com.tdc.vpp.Core.Utils; import com.tdc.vpp.R; import org.json.JSONArray; import org.json.JSONObject; import cz.msebera.android.httpclient.Header; public class StationeryManagerActivity extends AppCompatActivity implements View.OnClickListener{ private TextView Name; private Button Products, Items, Receipts, Demands, Deliveries; private String StationeryId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_stationery_manager); Config.CurrentActivity = this; StationeryId = getIntent().getExtras().getString("StationeryId"); Name = (TextView) findViewById(R.id.Name); Name.setText(LocalData.getStationery(StationeryId).getName()); Products = (Button) findViewById(R.id.Products); Products.setOnClickListener(this); Items = (Button) findViewById(R.id.Items); Items.setOnClickListener(this); Receipts = (Button) findViewById(R.id.Receipts); Receipts.setOnClickListener(this); Demands = (Button) findViewById(R.id.Demands); Demands.setOnClickListener(this); Deliveries = (Button) findViewById(R.id.Deliveries); Deliveries.setOnClickListener(this); getProducts(); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.Products: { Nav.openStationeryProducts(this, StationeryId); break; } case R.id.Items: { Nav.openStationeryItems(this, StationeryId); break; } case R.id.Receipts: { Nav.openStationeryReceipts(this, StationeryId); break; } case R.id.Demands: { Nav.openStationeryDemands(this, StationeryId); break; } case R.id.Deliveries: { Nav.openStationeryDeliveries(this, StationeryId); break; } } } private void getProducts() { AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = Utils.UserParams(); params.put("stationeryid", StationeryId); client.get(Config.BaseURL +"/manager/stationery/products", params, new JsonHttpResponseHandler() { public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { if (response.getBoolean("Success")) { JSONArray result = response.getJSONArray("Result"); LocalStorage.clean("Products"); LocalData.saveProducts(result); } else Utils.messageShort(Config.CurrentActivity, response.getString("Message")); } catch (Exception E) {} } }); } } <file_sep>package com.tdc.vpp.Adapter; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.tdc.vpp.Core.Broadcast; import com.tdc.vpp.Core.Config; import com.tdc.vpp.Core.LocalData; import com.tdc.vpp.Core.Utils; import com.tdc.vpp.Entities.Demand; import com.tdc.vpp.R; import org.json.JSONObject; import java.util.ArrayList; import cz.msebera.android.httpclient.Header; public class DemandUserAdapter extends ArrayAdapter<Demand> implements View.OnClickListener { private Activity context = null; private ArrayList<Demand> datas = null; private int layoutId; public DemandUserAdapter(Activity context, int layoutId, ArrayList<Demand> datas){ super(context, layoutId, datas); this.context = context; this.layoutId = layoutId; this.datas = datas; } public View getView(int position, View convertView, ViewGroup parent) { if ((position >= 0) && (position < datas.size())) { LayoutInflater inflater = context.getLayoutInflater(); convertView = inflater.inflate(layoutId, null); Demand obj = datas.get(position); TextView Name = (TextView) convertView.findViewById(R.id.Name); Name.setText("Name: " + obj.getProductName()); TextView Count = (TextView) convertView.findViewById(R.id.Count); Count.setText("Count: " + obj.getCount()); TextView User = (TextView) convertView.findViewById(R.id.User); User.setText("User: " + obj.getUserName()); Button Delete = (Button) convertView.findViewById(R.id.Delete); if (obj.getStatus() == 0) { Delete.setTag(obj.getId()); Delete.setOnClickListener(this); } else Delete.setVisibility(View.GONE); } return convertView; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.Delete: { Button Accept = (Button) v; String Id = (String) Accept.getTag(); delete(Id); break; } } } private void delete(String id) { Demand obj = LocalData.getDemand(id); AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = Utils.UserParams(); params.put("demandid", obj.getId()); client.delete(Config.BaseURL +"/manager/stationery/demand", params, new JsonHttpResponseHandler() { public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { if (response.getBoolean("Success")) { Broadcast.reloadDemands(); } else Utils.messageShort(context, response.getString("Message")); } catch (Exception E) {} } }); } }<file_sep>package com.tdc.vpp.Activities.User; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Spinner; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.tdc.vpp.Adapter.DemandAdapter; import com.tdc.vpp.Adapter.DemandUserAdapter; import com.tdc.vpp.Adapter.ReceiptAdapter; import com.tdc.vpp.Adapter.StationeryAdapter; import com.tdc.vpp.Core.Config; import com.tdc.vpp.Core.LocalData; import com.tdc.vpp.Core.LocalStorage; import com.tdc.vpp.Core.Nav; import com.tdc.vpp.Core.Utils; import com.tdc.vpp.Entities.Demand; import com.tdc.vpp.Entities.Product; import com.tdc.vpp.Entities.Receipt; import com.tdc.vpp.Entities.Stationery; import com.tdc.vpp.R; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import cz.msebera.android.httpclient.Header; public class UserPanelActivity extends AppCompatActivity implements View.OnClickListener { private String StationeryId = ""; private ArrayList<Product> lstProduct; private ArrayAdapter productAdapter; private ArrayList<Demand> lstData; private DemandUserAdapter adapter; private Button Add, Logout; private ListView ListData; private EditText Count, Price; private Spinner Product; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_panel); Config.CurrentActivity = this; lstData = new ArrayList<Demand>(); adapter = new DemandUserAdapter(this, R.layout.item_demand_user, lstData); lstProduct = new ArrayList<Product>(); productAdapter = new ArrayAdapter<Product>(this, android.R.layout.simple_spinner_item, lstProduct); Product = (Spinner) findViewById(R.id.Product); Product.setAdapter(productAdapter); Product.setSelection(0); Count = (EditText) findViewById(R.id.Count); Add = (Button) findViewById(R.id.Add); Add.setOnClickListener(this); Logout = (Button) findViewById(R.id.Logout); Logout.setOnClickListener(this); ListData = (ListView) findViewById(R.id.ListData); ListData.setAdapter(adapter); shows(); gets(); getStationery(); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.Logout: { Utils.logout(); break; } case R.id.Add: { create(lstProduct.get(Product.getSelectedItemPosition()).getId(), Count.getText().toString()); break; } } } public void shows() { LocalData.loadDemands(); lstData.clear(); lstData.addAll(LocalData.Demands); adapter.notifyDataSetChanged(); } private void gets() { AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = Utils.UserParams(); client.get(Config.BaseURL +"/user/stationery/demands", params, new JsonHttpResponseHandler() { public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { if (response.getBoolean("Success")) { JSONArray result = response.getJSONArray("Result"); LocalStorage.clean("Demands"); LocalData.saveDemands(result); shows(); } else Utils.logout(); } catch (Exception E) {} } }); } private void create(String ProductId, String Count) { AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = Utils.UserParams(); params.put("stationeryid", StationeryId); params.put("productid", ProductId); params.put("count", Count); client.post(Config.BaseURL +"/user/stationery/demand", params, new JsonHttpResponseHandler() { public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { if (response.getBoolean("Success")) { gets(); } else Utils.messageShort(Config.CurrentActivity, response.getString("Message")); } catch (Exception E) {} } }); } private void showProducts() { LocalData.loadProducts(); lstProduct.clear(); lstProduct.addAll(LocalData.Products); productAdapter.notifyDataSetChanged(); } private void getStationery() { AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = Utils.UserParams(); params.put("stationeryid", StationeryId); client.get(Config.BaseURL +"/user/stationery", params, new JsonHttpResponseHandler() { public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { if (response.getBoolean("Success")) { JSONObject result = response.getJSONObject("Result"); StationeryId = result.getString("Id"); LinearLayout Operator = (LinearLayout) findViewById(R.id.Operator); Operator.setVisibility(View.VISIBLE); getProducts(); } else Utils.messageShort(Config.CurrentActivity, response.getString("Message")); } catch (Exception E) {} } }); } private void getProducts() { AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = Utils.UserParams(); params.put("stationeryid", StationeryId); client.get(Config.BaseURL +"/user/stationery/products", params, new JsonHttpResponseHandler() { public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { if (response.getBoolean("Success")) { JSONArray result = response.getJSONArray("Result"); LocalStorage.clean("Products"); LocalData.saveProducts(result); showProducts(); } else Utils.messageShort(Config.CurrentActivity, response.getString("Message")); } catch (Exception E) {} } }); } } <file_sep>package com.tdc.vpp.Activities.Manager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.tdc.vpp.Adapter.DemandAdapter; import com.tdc.vpp.Adapter.ProductAdapter; import com.tdc.vpp.Core.Broadcast; import com.tdc.vpp.Core.Config; import com.tdc.vpp.Core.LocalData; import com.tdc.vpp.Core.LocalStorage; import com.tdc.vpp.Core.Utils; import com.tdc.vpp.Entities.Demand; import com.tdc.vpp.Entities.Product; import com.tdc.vpp.R; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import cz.msebera.android.httpclient.Header; public class StationeryDemandsActivity extends AppCompatActivity { private String StationeryId; private ArrayList<Demand> lstData; private DemandAdapter adapter; private ListView ListData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_stationery_demands); StationeryId = getIntent().getExtras().getString("StationeryId"); lstData = new ArrayList<Demand>(); adapter = new DemandAdapter(this, R.layout.item_demand, lstData); ListData = (ListView) findViewById(R.id.ListData); ListData.setAdapter(adapter); shows(); gets(); registerBroadcast(); } private void registerBroadcast() { IntentFilter filter = new IntentFilter(); filter.addAction(Broadcast.RELOAD_DEMANDS); OnBroadcast onBroadcast = new OnBroadcast(); registerReceiver(onBroadcast, filter); } private class OnBroadcast extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equalsIgnoreCase(Broadcast.RELOAD_DEMANDS)) { shows(); gets(); return; } } } public void shows() { LocalData.loadDemands(); lstData.clear(); for (int i = 0; i < LocalData.Demands.size(); i++) { if (LocalData.Demands.get(i).getStationeryId().equalsIgnoreCase(StationeryId)) lstData.add(LocalData.Demands.get(i)); } adapter.notifyDataSetChanged(); } private void gets() { AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = Utils.UserParams(); params.put("stationeryid", StationeryId); client.get(Config.BaseURL +"/manager/stationery/demands", params, new JsonHttpResponseHandler() { public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { if (response.getBoolean("Success")) { JSONArray result = response.getJSONArray("Result"); LocalStorage.clean("Demands"); LocalData.saveDemands(result); shows(); } else Utils.messageShort(Config.CurrentActivity, response.getString("Message")); } catch (Exception E) {} } }); } } <file_sep>package com.tdc.vpp.Activities.Manager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.tdc.vpp.Activities.Admin.ManagersActivity; import com.tdc.vpp.Adapter.AccountAdapter; import com.tdc.vpp.Adapter.ProductAdapter; import com.tdc.vpp.Core.Broadcast; import com.tdc.vpp.Core.Config; import com.tdc.vpp.Core.LocalData; import com.tdc.vpp.Core.LocalStorage; import com.tdc.vpp.Core.Nav; import com.tdc.vpp.Core.Utils; import com.tdc.vpp.Entities.Account; import com.tdc.vpp.Entities.Product; import com.tdc.vpp.R; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import cz.msebera.android.httpclient.Header; public class StationeryProductsActivity extends AppCompatActivity implements View.OnClickListener { private String StationeryId; private ArrayList<Product> lstData; private ProductAdapter adapter; private Button Add; private ListView ListData; private EditText ProductName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_stationery_products); StationeryId = getIntent().getExtras().getString("StationeryId"); lstData = new ArrayList<Product>(); adapter = new ProductAdapter(this, R.layout.item_general, lstData); ProductName = (EditText) findViewById(R.id.ProductName); Add = (Button) findViewById(R.id.Add); Add.setOnClickListener(this); ListData = (ListView) findViewById(R.id.ListData); ListData.setAdapter(adapter); shows(); gets(); registerBroadcast(); } private void registerBroadcast() { IntentFilter filter = new IntentFilter(); filter.addAction(Broadcast.RELOAD_PRODUCTS); OnBroadcast onBroadcast = new OnBroadcast(); registerReceiver(onBroadcast, filter); } private class OnBroadcast extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equalsIgnoreCase(Broadcast.RELOAD_PRODUCTS)) { shows(); gets(); return; } } } public void shows() { LocalData.loadProducts(); lstData.clear(); for (int i = 0; i < LocalData.Products.size(); i++) { if (LocalData.Products.get(i).getStationeryId().equalsIgnoreCase(StationeryId)) lstData.add(LocalData.Products.get(i)); } adapter.notifyDataSetChanged(); } private void gets() { AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = Utils.UserParams(); params.put("stationeryid", StationeryId); client.get(Config.BaseURL +"/manager/stationery/products", params, new JsonHttpResponseHandler() { public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { if (response.getBoolean("Success")) { JSONArray result = response.getJSONArray("Result"); LocalStorage.clean("Products"); LocalData.saveProducts(result); shows(); } else Utils.messageShort(Config.CurrentActivity, response.getString("Message")); } catch (Exception E) {} } }); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.Add: { create(ProductName.getText().toString()); break; } } } private void create(String Name) { AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = Utils.UserParams(); params.put("stationeryid", StationeryId); params.put("name", Name); client.post(Config.BaseURL +"/manager/stationery/product", params, new JsonHttpResponseHandler() { public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { if (response.getBoolean("Success")) { gets(); } else Utils.messageShort(Config.CurrentActivity, response.getString("Message")); } catch (Exception E) {} } }); } }
f414768b17165aa1b91e1409c5f9b4f4bce60218
[ "Java" ]
9
Java
LyokoVN/VPP-Mobile
2b4c989d072e070ce7acfee78b9ec9bfe92d8566
579d132c231e92c29e5d0eb70d4413b91c4fa662
refs/heads/master
<repo_name>kiran-bobade/Quiz-Pad<file_sep>/src/app/models/test-result.ts export interface TestResult { score: number; totalQuestions: number; passed: boolean; } <file_sep>/README.md # Quiz-Pad Simple Quiz Application <file_sep>/src/app/app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { WelcomeComponent } from './components/welcome/welcome.component'; import { TestpadComponent } from './components/testpad/testpad.component'; const routes: Routes = [ { path: '', component: WelcomeComponent }, { path: 'testpad', component: TestpadComponent }, { path: 'forms', loadChildren: () => import('./form/form.module').then(mod => mod.FormModule) }, { path: '**', component: WelcomeComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>/src/app/services/quiz-pad.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Question } from '../models/question'; import { map } from 'rxjs/operators'; import { Observable, of } from 'rxjs'; import { TestResult } from '../models/test-result'; import { QuestionsService } from './questions.service'; @Injectable({ providedIn: 'root' }) export class QuizPadService { private readonly CACHE_KEY = 'testpad'; private readonly DATA_URL = '../../assets/data.json'; private questions: Question[]; constructor( private readonly httpClient: HttpClient, private readonly questionService: QuestionsService) { } public setAnswers(id: number, selectedOption: string): void { this.questions = this.questionService.tryGetCachedQuestions(); if (this.questions) { const index = this.questions.findIndex((qstn) => qstn.id === id); this.questions[index].userAnswer = selectedOption; localStorage.setItem(this.CACHE_KEY, JSON.stringify(this.questions)); } } public finishTest(): Observable<TestResult> { let score = 0; this.questions = this.questionService.tryGetCachedQuestions(); return this.httpClient.get(this.DATA_URL) .pipe( map((response: []) => { response.forEach((question: Question, index: number) => { if (question.id === this.questions[index].id) { if (this.questions[index].userAnswer && question.answer === this.questions[index].userAnswer) { score = score + 1; } } }); localStorage.removeItem(this.CACHE_KEY); return { score, totalQuestions: response.length, passed: ((score / response.length) * 100) >= 50 }; })); } } <file_sep>/src/app/components/testpad/testpad.component.spec.ts import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { TestpadComponent } from './testpad.component'; describe('TestpadComponent', () => { let component: TestpadComponent; let fixture: ComponentFixture<TestpadComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ TestpadComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(TestpadComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>/src/app/services/questions.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Question } from '../models/question'; import { map } from 'rxjs/operators'; import { Observable, of } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class QuestionsService { private readonly CACHE_KEY = 'testpad'; private readonly DATA_URL = '../../assets/data.json'; private questions: Question[]; constructor(private readonly httpClient: HttpClient) { } public getQuestions(pageSize: number, currentPage: number): Observable<any> { this.tryGetCachedQuestions(); if (this.questions && this.questions.length > 0) { return of({ total: this.questions.length, questions: this.questions.splice(currentPage - 1, pageSize) }); } else { return this.paginateQuestions(currentPage, pageSize); } } public tryGetCachedQuestions(): Question[] { const chachedQuestions = localStorage.getItem(this.CACHE_KEY); if (chachedQuestions) { this.questions = JSON.parse(chachedQuestions); return this.questions; } } private paginateQuestions(currentPage: number, pageSize: number): Observable<any> { return this.httpClient.get(this.DATA_URL) .pipe(map((response: []) => { response.forEach((item: any) => { delete item.answer; }); localStorage.setItem(this.CACHE_KEY, JSON.stringify(response)); return { total: response.length, questions: response.splice(currentPage - 1, pageSize) }; })); } } <file_sep>/src/app/form/reactive/reactive.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { debounceTime, distinctUntilChanged, tap } from 'rxjs/operators'; @Component({ selector: 'app-reactive', templateUrl: './reactive.component.html', styleUrls: ['./reactive.component.css'] }) export class ReactiveComponent implements OnInit { languages = ['English', 'Hindi', 'Marathi']; searchTerm: FormControl; terms: string[] = []; myForm: FormGroup; nameGroup: FormGroup; firstName: FormControl; lastName: FormControl; email: FormControl; password: FormControl; lang: FormControl; constructor() { } generateFormControls() { this.firstName = new FormControl('', Validators.required); this.lastName = new FormControl('', Validators.required); this.email = new FormControl('', [Validators.required]); this.password = new FormControl('', [Validators.required, Validators.minLength(6)]); this.lang = new FormControl('', Validators.required); } public ngOnInit(): void { this.searchTerm = new FormControl(); this.generateFormControls(); this.generateForm(); this.searchTerm.valueChanges .pipe( debounceTime(400) , distinctUntilChanged() , tap() ) .subscribe((term) => { this.terms.push(term); }); } submitForm() { if (this.myForm.valid) { } } private generateForm() { this.nameGroup = new FormGroup({ firstName: this.firstName, lastName: this.lastName }); this.myForm = new FormGroup({ name: this.nameGroup, email: this.email, password: <PASSWORD>, lang: this.lang }); } } <file_sep>/src/app/components/question/question.component.ts import { Component, OnInit, Input } from '@angular/core'; import { Question } from '../../models/question'; import { QuizPadService } from 'src/app/services/quiz-pad.service'; @Component({ selector: 'app-question', templateUrl: './question.component.html', styleUrls: ['./question.component.css'] }) export class QuestionComponent implements OnInit { @Input() question: Question; tooltip = 'this is the text of a tooltip'; constructor(private readonly quizeService: QuizPadService) { } ngOnInit(): void { } public selectOption(option: string): void { console.log('current quetion', this.question); this.quizeService.setAnswers(this.question.id, option); } } <file_sep>/src/app/directives/tooltip.directive.ts import { ElementRef, Directive, Renderer2, Input, OnInit, HostListener, HostBinding } from '@angular/core'; @Directive({ selector: '[appTooltip]' }) export class TooltipDirective implements OnInit { @HostBinding('class.tooltip-hover') private hovering: boolean; @Input('appTooltip') text; constructor( private readonly element: ElementRef, private readonly renderer: Renderer2) { } @HostListener('mouseover') onMouseOver() { this.renderer.setStyle(this.element.nativeElement, 'color', 'red'); this.hovering = true; } @HostListener('mouseleave') onMouseLeave() { this.renderer.setStyle(this.element.nativeElement, 'color', 'blue'); this.hovering = false; } ngOnInit(): void { console.log('text', this.text); console.log(this.element.nativeElement); this.renderer.setAttribute(this.element.nativeElement, 'title', this.text); this.renderer.addClass(this.element.nativeElement, 'has-tooltip'); } } <file_sep>/src/app/components/testpad/testpad.component.ts import { Component, OnInit } from '@angular/core'; import { QuestionsService } from '../../services/questions.service'; import { QuestionList } from '../../models/questionList'; import { TestResult } from '../../models/test-result'; import { QuizPadService } from 'src/app/services/quiz-pad.service'; @Component({ selector: 'app-testpad', templateUrl: './testpad.component.html', styleUrls: ['./testpad.component.css'] }) export class TestpadComponent implements OnInit { public questionList: QuestionList; public currentQuestionIndex = 0; private PAGE_SIZE = 1; public finished = false; public testResult: TestResult; constructor( private readonly questionService: QuestionsService, private readonly quizService: QuizPadService) { } public ngOnInit(): void { this.getQuestions(); } public previous() { this.currentQuestionIndex = this.currentQuestionIndex - 1; this.getQuestions(); } public next() { this.currentQuestionIndex = this.currentQuestionIndex + 1; this.getQuestions(); } public finish() { this.finished = true; this.quizService.finishTest().subscribe((result) => { this.testResult = result; }); } private getQuestions() { this.questionService.getQuestions(this.PAGE_SIZE, this.currentQuestionIndex + 1) .subscribe((response) => { this.questionList = response; }); } }
22902013b50c40cea447352422273dc8f61165da
[ "Markdown", "TypeScript" ]
10
TypeScript
kiran-bobade/Quiz-Pad
d4305ea68e262c62ad8746c7d14f44cf6e2d4810
39c4f9e18671abe5e23642778ba9d7794d92daff
refs/heads/master
<file_sep>from scipy import ndimage import numpy as np ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ") def get_char(image, r, g, b, alpha=256): gray = r * image[:, :, 1] + g * image[:, :, 2] + b * image[:, :, 3] # transfer a RGB image to a gray image1 length = len(ascii_char) unit = (alpha+1) / length return np.ceil(gray/unit) if __name__ == '__main__': filename = 'wm.png' ori_image = ndimage.imread(filename) m, n, _ = ori_image.shape index = get_char(ori_image, 0.3, 0.4, 0.3) txt = '' for i in range(m): for j in range(n): txt += ascii_char[index[i, j]] txt += '\n' with open('output.txt','w') as f: f.write(txt) <file_sep># -*- coding: utf-8 -*- """ Created on Sat Apr 14 14:55:29 2018 @author: Administrator """ #子类的类型判断 issubclass #实例类型判断 isinstance class Programmer(object): hobby = 'Play computer' def __init__(self,name,age,*weight): #实例方法的第一参数 self.name = name if isinstance(age,int): self._age = age #protect self.__weight = weight #private #运算符 #比较运算符 #__cmp__(self,other)(包含所有比较情况 一般用于排序) #__eq__(self,other),__lt__(self,other),__gt__(self,other) def __eq__ (self,other): if isinstance(other,Programmer): if other._age == self._age: return True else: return False else: raise Exception('The type of object must be a Programmer') #数字运算符 #__add__(self,other),__sub__(self,other),__mul__(self,other),__div__(self,other) def __add__(self,other): if isinstance(other,Programmer): return self._age + other._age else: raise Exception('The type of object must be a Programmer') #逻辑运算符 #__or__(self,other),__and__(self,other) def __and__(self,other): if isinstance(other,Programmer): return other._age + Programmer._age else: raise Exception('The type of object must be a Programmer') #转化为字符串 #__str__ 转化为适合人看的字符串 #__repr__转化为适合机器看的字符串 输出可以直接使用eval #__unicode__ def __str__(self): return '%s is %d years old.'%(self.name,self._age) #选择性地展现对象属性 #__dir__ def __dir__(self): return self.__dict__.keys() #设置对象属性 def __setattr__(self,name,value): self.__dict__[name] = value #查询对象属性 #__getattr__(self,name) #默认属性没有被查询到 #__getattribute(self,name) #每次访问 容易引起无限调用 def __getattribute__(self,name): #__dict__[name]调用getattribute 造成无限调用 return super(Programmer,self).__getattribute__(name) #调用父类方法 #删除对象属性 #__delattr__(self,name) @classmethod #调用的时候用类名,而不是某个对象 def get_hobby(cls): #类方法的第一参数 return cls.hobby @property #像访问属性一样调用方法 def get_weight(self): return self.__weight def self_introduction(self): print('My name is %s\nMy age is %d years old\n' %(self.name,self._age)) class BackendProgrammer(Programmer): def __init__(self,name,age,weight,language): super(BackendProgrammer,self).__init__(name,age,weight) #调用父类 # Programmer.__init__(name,age,weight) self.language = language def self_introduction(self): print('My name is %s\nMy favorite language is %s\n' %(self.name,self.language)) def introduce(programmer): if isinstance(programmer,Programmer): programmer.self_introduction() if __name__ == '__main__': programmer = Programmer('Tim',23,74) back_end_programmer = BackendProgrammer('Albert',26,65,'Python') print(programmer.get_weight) print(Programmer.hobby) introduce(programmer) introduce(back_end_programmer) p1 = Programmer('Jack',56) p2 = Programmer('Rose',48) print(p1 == p2) print(p1+p2)
df358698f368821165e19841c5a93a85292ca8f0
[ "Python" ]
2
Python
chizawa/PythonLearning
15ccfb2ff74edc8aada66fe6345e61c8986bc85f
007cfb37e8486cc70245e4a924b14a5c734e9061
refs/heads/master
<file_sep>Please note that this is a team event, and your submission will be accepted only as a part of a team, even single member teams are allowed. Please click here to register as a team, if you have NOT already registered. Given a word w, rearrange the letters of w to construct another word s in such a way that, s is lexicographically greater than w. In case of multiple possible answers, find the lexicographically smallest one. Input Format The first line of input contains t, number of test cases. Each of the next t lines contains w. Constraints 1≤t≤105 1≤|w|≤100 w will contain only lower case english letters and its' length will not exceed 100. Output Format For each testcase, output a string lexicographically bigger than w in a separate line. In case of multiple possible answers, print the lexicographically smallest one and if no answer exists, print no answer. Sample Input 3 ab bb hefg Sample Output ba no answer hegf Explanation Testcase 1 : There exists only one string greater than ab which can be built by rearranging ab. That is ba. Testcase 2 : Not possible to re arrange bb and get a lexicographically greater string. Testcase 3 : hegf is the next string ( lexicographically greater ) to hefg. <file_sep>import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void solve (char str[]) { int i, flag=0; loop: for(i=str.length-1; i>0; i--) { if(str[i]>str[i-1]) { int j = str.length-1; while(flag==0 && j!=i-1){ if(str[i-1]<str[j]) { char t = str[j]; str[j] = str[i-1]; str[i-1] = t; flag = 1; break loop; } j--; } } } Arrays.sort(str,i,str.length); if(flag==0) System.out.println("no answer"); else System.out.println(str); } public static void main(String[] args) { char name[]; int t; Scanner in = new Scanner(System.in); t = in.nextInt(); for(int i=0; i<t; i++) { name = in.next().toCharArray(); solve(name); } } } <file_sep>John has discovered various rocks. Each rock is composed of various elements, and each element is represented by a lowercase latin letter from 'a' to 'z'. An element can be present multiple times in a rock. An element is called a 'gem-element' if it occurs at least once in each of the rocks. Given the list of rocks with their compositions, display the number of gem-elements that exist in those rocks. Input Format The first line consists of N, the number of rocks. Each of the next N lines contain rocks' composition. Each composition consists of lowercase letters of English alphabet. Output Format Print the number of gem-elements that are common in these rocks. Constraints 1 ≤ N ≤ 100 Each composition consists of only small latin letters ('a'-'z'). 1 ≤ Length of each composition ≤ 100 Sample Input 3 abcdde baccd eeabg Sample Output 2 Explanation Only "a", "b" are the two kind of gem-elements, since these are the only characters that occur in each of the rocks' composition. <file_sep>#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <assert.h> #include <stddef.h> void insertionSort(int ar_size, int * ar) { int i,j; int value; for(i=1;i<ar_size;i++) { value=ar[i]; j=i-1; while(j>=0 && value<ar[j]) { ar[j+1]=ar[j]; j=j-1; } ar[j+1]=value; } for(j=0;j<ar_size;j++) { printf("%d",ar[j]); printf(" "); } } int main(void) { int _ar_size; scanf("%d", &_ar_size); int _ar[_ar_size], _ar_i; for(_ar_i = 0; _ar_i < _ar_size; _ar_i++) { scanf("%d", &_ar[_ar_i]); } insertionSort(_ar_size, _ar); return 0; } <file_sep>#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <assert.h> void insertionSort(int size, int * ar) { int i,t,v; i = size-2; v = ar[size-1]; while(i>=0){ if (v<ar[i]) { ar[i+1]=ar[i]; } else { ar[i+1]=v; break; } i--; for(t=0;t<=size-1;t++) printf("%d ",ar[t]); printf("\n"); } if(i==-1){ ar[i+1]=v; } for(t=0;t<=size-1;t++) printf("%d ",ar[t]); } int main(void) { int size; scanf("%d", &size); int ar[size], i; for(i = 0; i < size; i++) { scanf("%d", &ar[i]); } insertionSort(size, ar); return 0; } <file_sep>#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int count1 =0,count2=0; void insertionSort(int size, int * ar) { int i,j,t; for(i=1;i<size;i++){ j=i; while(ar[j]<ar[j-1]&&j>0){ t=ar[j]; ar[j]=ar[j-1]; ar[j-1]=t; j--; count1++; } } } void quicksort(int * A, int p, int r){ if(p<r){ int q = partition(A,p,r); quicksort(A,p,q-1); quicksort(A,q+1,r); } } int partition(int *A, int p, int r){ int x,i,j,temp; x = A[r]; i = p-1; for(j=p;j<r;j++){ if(A[j]<=x){ i++; temp = A[i]; A[i] = A[j]; A[j] = temp; count2++; } } temp = A[i+1]; A[i+1] = A[r]; A[r] = temp; count2++; return i+1; } int main() { int n,i; scanf("%d",&n); int a[n],b[n]; for(i=0;i<n;i++){ scanf("%d",&a[i]); b[i]=a[i]; } insertionSort(n,a); quicksort(b,0,n-1); printf("%d",count1-count2); return 0; } <file_sep>#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <assert.h> void insertionSort(int size, int * ar) { int i,j,t,count=0; for(i=1;i<size;i++){ j=i; while(ar[j]<ar[j-1]&&j>0){ t=ar[j]; ar[j]=ar[j-1]; ar[j-1]=t; j--; count++; } } printf("%d",count); } int main(void) { int size; scanf("%d", &size); int ar[size], i; for(i = 0; i < size; i++) { scanf("%d", &ar[i]); } insertionSort(size, ar); return 0; } <file_sep>There are n groups of friends, and each group is numbered from 1 to n. The ith group contains ai people. They live near a bus stop, and only a single bus operates on this route. An empty bus arrives at the bus stop and all the groups want to travel by the bus. However, group of friends do not want to get separated. So they enter the bus only if the bus can carry the entire group. Moreover, the groups do not want to change their relative positioning while travelling. In other words, group 3 cannot travel by bus, unless group 1 and group 2 have either (a) already traveled by the bus in the previous trip or (b) they are also sitting inside the bus at present. You are given that a bus of size x can carry x people simultaneously. Find the size x of the bus so that (1) the bus can transport all the groups and (2) every time when the bus starts from the bus station, there is no empty space in the bus (i.e. the total number of people present inside the bus is equal to x)? Input Format The first line contains an integer n (1≤n≤105). The second line contains n space-separated integers a1,a2,…,an (1≤ai≤104). Output Format Print all possible sizes of the bus in an increasing order. Sample Input 8 1 2 1 1 1 2 1 3 Sample Output 3 4 6 12 Sample Explanation In the above example, a1 = 1, a2 = 2, a3 = 1, a4 = 1, a5 = 1, a6 = 2, a7 = 1, a8 = 3. If x = 1 : In the first trip, a1 go by the bus. There will be no second trip because the bus cannot accommodate group 2. Hence "x = 1" is not the required answer. If x = 2 : No bus trip is possible. That's because a1 cannot go alone, as one seat will be left vacant in the bus. And, a1 & a2 cannot go together, because the bus is cannot accommodate both the groups simultaneously. If x = 3 : In the first trip, a1 & a2 go by the bus. In the second trip, a3, a4 & a5 go by the bus. In the third trip, a6 & a7 go by the bus. In the fourth trip, a8 go by the bus. If x = 4 : In the first trip, a1, a2 & a3 go by the bus. In the second trip, a4, a5 & a6go by the bus. In the third trip, a7 & a8 go by the bus. Similarly you can figure out the output for x= 5, 6 & 7. <file_sep>#include<stdio.h> int main() { int T, N[10],m,i,j; scanf("%d",&T); for(i=0;i<T;i++){ scanf("%d",&N[i]); m=1; if(N[i]!=0){ for(j=1;j<=N[i];j++) { if(j%2!=0) m=2*m; else m=m+1; }} printf("%d \n",m); } return 0; } <file_sep>Problem Statement Watson gives to Sherlock an array: A1,A2,⋯,AN. He also gives to Sherlock two other arrays: B1,B2,⋯,BM and C1,C2,⋯,CM. Then Watson asks Sherlock to perform the following program: for i = 1 to M do for j = 1 to N do if j % B[i] == 0 then A[j] = A[j] * C[i] endif end do end do Can you help Sherlock and tell him the resulting array A? You should print all the array elements modulo (109+7). Input Format The first line contains two integer numbers N and M. The next line contains N integers, the elements of array A. The next two lines contains M integers each, the elements of array B and C. Output Format Print N integers, the elements of array A after performing the program modulo (109+7). Constraints 1≤N,M≤105 1≤B[i]≤N 1≤A[i],C[i]≤105 Sample Input 4 3 1 2 3 4 1 2 3 13 29 71 Sample Output 13 754 2769 1508 <file_sep>import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.nextLine().toLowerCase(); char[] c = s.toCharArray(); int[] a = new int[26]; int t,f=1; for(int i=0; i<c.length; i++){ if(c[i]!=32){ t = c[i] - 'a'; a[t] = 1;} } for(int i=0; i<26; i++){ if(a[i]!=1){ f = 0; break; } } if(f==0) System.out.print("not pangram"); else System.out.print("pangram"); } } <file_sep>#include<stdio.h> main() { int n,i,j; scanf("%d",&n); int ar[n]; int count[100] = {0}; //for 0 to 100 for(i=0;i<n;i++) { scanf("%d",&ar[i]); count[ar[i]]++; } for(i=0;i<100;i++) { if(count[i]>0) { for(j=0;j<count[i];j++) { printf("%d ",i); } } } } <file_sep>Sherlock is given an array of N integers A0, A1 ... AN-1 by Watson. Now Watson asks Sherlock that how many different pairs of indices i and j exist such that i is not equal to j but Ai is equal to Aj. That is, Sherlock has to count total number of pairs of indices (i, j) where Ai = Aj AND i ≠ j. Input Format First line contains T, the number of testcases. T test case follows. Each testcase consists of two lines, first line contains an integer N, size of array. Next line contains N space separated integers. Output Format For each testcase, print the required answer in different line. Constraints 1 ≤ T ≤ 10 1 ≤ N ≤ 105 1 ≤ A[i] ≤ 106 Sample input 2 3 1 2 3 3 1 1 2 Sample output 0 2 Explanation In the first testcase, no two pair of indices exist which satisfy the given property. In second testcase as A[0] = A[1] = 1, the pairs of indices (0,1) and (1,0) satisfy the given property. <file_sep>Mark and Jane are very happy after having their first kid. Their son is very fond of toys, so Mark wants to buy some. There are N different toys lying in front of him, tagged with their prices, but he has only $K. He wants to maximize the number of toys he buys with this money. Now, you are Mark's best friend and have to help him buy as many toys as possible. Input Format The first line contains two integers, N and K, followed by a line containing N space separated integers indicating the products' prices. Output Format An integer that denotes maximum number of toys Mark can buy for his son. Constraints 1<=N<=105 1<=K<=109 1<=price of any toy<=109 A toy can't be bought multiple times. Sample Input 7 50 1 12 5 111 200 1000 10 Sample Output 4 Explanation He can buy only 4 toys at most. These toys have the following prices: 1,12,5,10. <file_sep>Roy wanted to increase his typing speed for programming contests. So, his friend advised him to type the sentence "The quick brown fox jumps over the lazy dog" repeatedly because it is a pangram. ( pangrams are sentences constructed by using every letter of the alphabet at least once. ) After typing the sentence several times, Roy became bored with it. So he started to look for other pangrams. Given a sentence s, tell Roy if it is a pangram or not. Input Format Input consists of a line containing s. Constraints Length of s can be atmost 103 (1≤|s|≤103) and it may contain spaces, lowercase and uppercase letters. Lowercase and uppercase instances of a letter are considered same. Output Format Output a line containing pangram if s is a pangram, otherwise output not pangram. Sample Input #1 We promptly judged antique ivory buckles for the next prize Sample Output #1 pangram Sample Input #2 We promptly judged antique ivory buckles for the prize Sample Output #2 not pangram Explanation In the first testcase, the answer is pangram because the sentence contains all the letters. <file_sep>#include<stdio.h> /*int string_to_int(char str[]){ int i,num=0; for(i=0;str[i]!='\0';i++) { if(str[i]>=48 && str[i]<=57) num=num*10+(str[i]-48); } return num; }*/ main() { int n,i,sum=0; scanf("%d",&n); int ar[n]; char s[100]; int count[100] = {0}; for(i=0;i<n;i++) { //fgets (s, 100, stdin); //ar[i]= string_to_int(s); scanf("%d %s",&ar[i],s); //can be always done using this as i/p is always in this format count[ar[i]]++; } for(i=0;i<100;i++) { sum+= count[i]; printf("%d ",sum); } } <file_sep>#include<stdio.h> int main(){ int n,k,q,temp,x,i; scanf("%d %d %d",&n,&k,&q); int a[n],b[n]; for(i=0;i<n;i++){ scanf("%d",&a[i]); b[i]=a[i]; } k = k % n; for(i=0;i<n;i++){ temp = (i+n-k)%n; a[i]=b[temp]; } for(i=0;i<q;i++){ scanf("%d",&x); printf("%d\n",a[x]); } return 0; } <file_sep>#include<stdio.h> int main(){ int T,t,n,i,j; scanf("%d",&T); for(t=0;t<T;t++){ scanf("%d",&n); int a[n]; for(i=0;i<n;i++){ scanf("%d",&a[i]); } int first=0,last=0; for(i=1;i<n;i++){ last+=a[i]; } for(i=0;i<n-1;i++){ if(first==last){ printf("YES\n"); break; } first+= a[i]; last-= a[i+1]; } if(i==n-1 && n!=1) printf("NO\n"); if(n==1) printf("YES\n"); } return 0; } <file_sep>Problem Statement Sorting is often useful as the first step in many different tasks. The most common task is to make finding things easier, but there are other uses also. Challenge Given a list of unsorted numbers, can you find the numbers that have the smallest absolute difference between them? If there are multiple pairs, find them all. Input Format There will be two lines of input: n - the size of the list array - the n numbers of the list Output Format Output the pairs of numbers with the smallest difference. If there are multiple pairs, output all of them in ascending order, all on the same line (consecutively) with just a single space between each pair of numbers. If there's a number which lies in two pair, print it two times (see sample case #3 for explanation). Constraints 2 <= n <= 200000 -(107) <= x <= (107), where x ∈ array array[i] != array[j], 0 <= i, j < N, and i != j Sample Input #1 10 -20 -3916237 -357920 -3620601 7374819 -7330761 30 6246457 -6461594 266854 Sample Output #1 -20 30 Explanation (30) - (-20) = 50, which is the smallest difference. Sample Input #2 12 -20 -3916237 -357920 -3620601 7374819 -7330761 30 6246457 -6461594 266854 -520 -470 Sample Output #2 -520 -470 -20 30 Explanation (-470) - (-520) = 30 - (-20) = 50, which is the smallest difference. Sample Input #3 4 5 4 3 2 Sample Output #3 2 3 3 4 4 5 Explanation Here, the minimum difference will be 1. So valid pairs are (2, 3), (3, 4), (4, 5). So we have to print 2 one time, 3 and 4 two times, and 5 one time. <file_sep>import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void solve(int n){ long s=4,m=1; if(n==0){ System.out.println(s); } else{ for(int i=1; i<=n; i++){ m = 2*m; if(m>1000000007) m = m % 1000000007; s = s + m; if(s > 1000000007) s = s % 1000000007; } System.out.println(s); } } public static void main(String[] args) { int n,t; Scanner in = new Scanner(System.in); t = in.nextInt(); for(int i=0; i<t; i++){ n = in.nextInt(); solve(n); } } } <file_sep>#include <stdio.h> int main() { int n,i,k; scanf("%d",&n); long long int a[n],sum[n], ans, s=0,temp; sum[0] =0; for(i=0;i<n;i++){ scanf("%lld",&a[i]); sum[0]+=(i+1)*a[i]; s+= a[i]; } ans = sum[0]; for(k=1;k<n;k++){ temp = n*a[k-1]; sum[k]= sum[k-1] - s + temp; if(ans<sum[k]) ans = sum[k]; } printf("%lld",ans); return 0; } <file_sep>#include<stdio.h> #include<string.h> #include<math.h> int main() { char s1[10000],s2[10000]; scanf("%s",s1); scanf("%s",s2); int t,i,l1, l2; int c1[26]={0}; int c2[26]={0}; l1 = strlen(s1); l2 = strlen(s2); for(i=0;i<l1;i++){ t = s1[i] - 'a'; c1[t]++; } for(i=0;i<l2;i++){ t= s2[i] - 'a'; c2[t]++; } int ans = 0; for(i=0;i<26;i++){ ans+= abs(c1[i]-c2[i]); } printf("%d",ans); return 0; } <file_sep>import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] a = new int[n]; for(int i=0; i<n; i++){ a[i] = in.nextInt(); } int min=0, temp=0; HashMap<Integer, ArrayList<Integer>> minMap = new HashMap<Integer,ArrayList<Integer>>(); Arrays.sort(a); for(int i=0; i<n-1; i++){ temp = a[i+1] - a[i]; if(!minMap.containsKey(temp)) minMap.put(temp, new ArrayList<Integer>()); minMap.get(temp).add(a[i]); minMap.get(temp).add(a[i+1]); if(min>temp || i==0) min = temp; } for(int i=0; i<minMap.get(min).size();i++) System.out.print(minMap.get(min).get(i)+" "); } } <file_sep>#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { int t,T,n,i,j,temp; long long int count,k; scanf("%d",&T); int c[1000000] = {0}; for(t=0;t<T;t++){ scanf("%d",&n); int a[n]; count =0; for(i=0;i<n;i++){ scanf("%d",&temp); c[temp-1]++ ; } for(i=0;i<1000000;i++){ if(c[i]>1){ k = c[i]; count+= k*(k-1); } c[i] = 0; } printf("%lld\n",count); } return 0; } <file_sep>import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] a = new int[n]; ArrayList<Integer> ans = new ArrayList<Integer>(); int temp; HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>(); for(int i=0; i<n; i++){ a[i] = in.nextInt(); if(!hash.containsKey(a[i])) hash.put(a[i],1); else{ temp = hash.get(a[i]); hash.put(a[i],temp+1); } } int m = in.nextInt(); int[] b = new int[m]; for(int i=0; i<m; i++){ b[i] = in.nextInt(); if(!hash.containsKey(b[i]) || hash.get(b[i])==0) ans.add(b[i]); else{ temp = hash.get(b[i]); hash.put(b[i],temp-1); } } Collections.sort(ans); for(int i: ans) System.out.print(i+" "); } } <file_sep>#include<stdio.h> void ascending(int *a,int size){ int i,j,t; for(i=0;i<size;i++){ for(j=i+1;j<size;j++){ if( *(a+i)> *(a+j)){ t= *(a+i); *(a+i)= *(a+j); *(a+j)= t; } } } } void descending(int *a,int size){ int i,j,t; for(i=0;i<size;i++){ for(j=i+1;j<size;j++){ if( *(a+i)< *(a+j)){ t= *(a+i); *(a+i)= *(a+j); *(a+j)= t; } } } } main (){ int t,i,j,temp,flag; scanf("%d",&t); int n,k; for(i=0;i<t;i++){ scanf("%d %d",&n,&k); int a[n],b[n]; for(j=0;j<n;j++){ scanf("%d",&a[j]); } for(j=0;j<n;j++){ scanf("%d",&b[j]); } ascending(a,n); descending(b,n); flag=1; for(temp=0;temp<n;temp++){ if((a[temp]+b[temp])<k) flag=0; } if(flag==1) printf("YES\n"); else printf("NO\n"); } } <file_sep>Watson gives a square of side length 1 to Sherlock. Now, after each second, each square of side L will break into four squares each of side L/2(as shown in the image below). img Now, Watson asks Sherlock: What will be the sum of length of solid lines after N seconds? As the number can be large print result mod (109+7). For example, after 0 seconds, the length is 4. After 1 second, the length is 6. Input Format First line contains T, the number of testcases. Each testcase contains N in one line. Output Format For each testcase, print the required answer in a new line. Constraints 1≤T≤105 0≤N≤109 Sample input 2 0 1 Sample output 4 6 <file_sep>#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> void quicksort(int * A, int p, int r){ if(p<r){ int q = partition(A,p,r); quicksort(A,p,q-1); quicksort(A,q+1,r); } } int partition(int *A, int p, int r){ int x,i,j,temp; x = A[r]; i = p-1; for(j=p;j<r;j++){ if(A[j]<=x){ i++; temp = A[i]; A[i] = A[j]; A[j] = temp; } } temp = A[i+1]; A[i+1] = A[r]; A[r] = temp; return i+1; } int main() { int n,i,g, l=1,sum = 0; scanf("%d",&n); int a[n]; for(i=0;i<n;i++){ scanf("%d",&a[i]); sum+= a[i]; if(g>a[i] || i==0) g = a[i]; } int k=0,m,d[n]; m = sqrt(sum); while(l<= m){ if(sum % l == 0){ if(l>=g){ d[k] = l; k++; } if(l != sum/l && (sum/l)>=g){ d[k] = sum/l; k++; } } l++; } int e[k]; l = 0; int t = 0; while(l<k){ m = d[l]; i = 0; while(m>0){ m-= a[i]; i++; if(m==0 && i<n) m = d[l]; } if(m==0 && i==n){ e[t] = d[l]; t++; } l++; } quicksort(e,0,t-1); for(i=0;i<t;i++) printf("%d ",e[i]); return 0; } <file_sep> <NAME> performs an operation called Right Circular Rotation on an integer array a0,a1 ... an-1. Right Circular Rotation transforms the array from a0,a1 ... aN-1 to aN-1,a0,... aN-2. He performs the operation K times and tests Sherlock's ability to identify the element at a particular position in the array. He asks Q queries. Each query consists of one integer x, for which you have to print the element ax. Input Format The first line consists of 3 integers N, K and Q separated by a single space. The next line contains N space separated integers which indicates the elements of the array A. Each of the next Q lines contain one integer per line denoting x. Output Format For each query, print the value in the location in a newline. Constraints 1 ≤ N ≤ 105 1 ≤ A[i] ≤ 105 1 ≤ K ≤ 105 1 ≤ Q ≤ 500 0 ≤ x ≤ N-1 Sample input 3 2 3 1 2 3 0 1 2 Sample output 2 3 1 Explanation After one rotation array becomes, 3 1 2. After another rotation array becomes 2 3 1. Final array now is 2,3,1. 0th element of array is 2. 1st element of array is 3. 2nd element of array is 1. <file_sep>Sunny and Johnny together have M dollars and want to spend the amount at an ice cream parlour. The parlour offers N flavors, and they want to choose 2 flavors so that they end up spending the whole amount. You are given a list of cost of these N flavors. The cost of ith flavor is denoted by (ci). You have to display the indices of two flavors whose sum is M. Input Format The first line of the input contains T, T test cases follow. Each test case follows the format: The first line contains M. The second line contains N. The third line contains N single space separated integers denoting the price of each flavor. Here, ith integer denotes ci. Output Format Output two integers, each of which is a valid index of the flavor. The lower index must be printed first. Indices are indexed from 1 to N. Constraints 1 ≤ T ≤ 50 2 ≤ M ≤ 10000 2 ≤ N ≤ 10000 1 ≤ ci ≤ 10000 The prices of two items may be same and each test case has a unique solution. Sample Input 2 4 5 1 4 5 3 2 4 4 2 2 4 3 Sample Output 1 4 1 2 Explanation The sample input has two test cases. For the 1st, the amount M = 4 and there are 5 flavors at the store. The flavors indexed at 1 and 4 sums to 4. For the 2nd test case, the amount M = 4 and the flavors indexed at 1 and 2 sums to 4. <file_sep>import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { int T; Scanner in = new Scanner(System.in); T = in.nextInt(); for(int t=0; t<T; t++){ int m,n,temp1=0,temp2=0; m = in.nextInt(); n = in.nextInt(); int[] c = new int[n]; HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>(n); for(int i=0; i<n; i++){ c[i] = in.nextInt(); hash.put(c[i],i+1); } for(int i=0; i<n; i++){ if(hash.containsKey(m-c[i]) && i+1!=hash.get(m-c[i])){ temp1 = i+1; temp2 = hash.get(m-c[i]); break; } } if(temp1<temp2) System.out.println(temp1+" "+temp2); else System.out.println(temp2+" "+temp1); } } } <file_sep>import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Long N = scanner.nextLong(); Long M = scanner.nextLong(); scanner.nextLine(); ArrayList<Long> A = new ArrayList<Long>(); ArrayList<Long> B = new ArrayList<Long>(); ArrayList<Long> C = new ArrayList<Long>(); A.add(0L); for (String string : scanner.nextLine().split(" ")) { A.add(new Long(string)); } B.add(0L); for (String string : scanner.nextLine().split(" ")) { B.add(new Long(string)); } C.add(0L); for (String string : scanner.nextLine().split(" ")) { C.add(new Long(string)); } HashMap<Long, Long> counts = new HashMap<Long, Long>(); for (int i = 1; i < M+1; i++) { if (counts.containsKey(B.get(i))) { counts.put(B.get(i), (counts.get(B.get(i)) * C.get(i)) % 1000000007L); } else { counts.put(B.get(i), C.get(i)); } } for (Long i = 1L; i < N+1; i++) { for (Long j = 1L; j < (N / i) + 1L; j++) { if (counts.containsKey(i)) { A.set((int)(i * j), (A.get((int)(i * j)) * counts.get(i)) % 1000000007L); } } } System.out.print(A.get(1)); for (int i = 2; i < A.size(); i++) { System.out.print(" " + A.get(i)); } } } <file_sep>#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> void quicksort(int * A, int p, int r){ if(p<r){ int q = partition(A,p,r); quicksort(A,p,q-1); quicksort(A,q+1,r); } } int partition(int *A, int p, int r){ int x,i,j,temp; x = A[r]; i = p-1; for(j=p;j<r;j++){ if(A[j]<=x){ i++; temp = A[i]; A[i] = A[j]; A[j] = temp; } } temp = A[i+1]; A[i+1] = A[r]; A[r] = temp; return i+1; } int main() { int n, k, i, count,d,t; scanf("%d %d", &n, &k); int prices[n]; for(i=0; i<n; i++) { scanf("%d", &prices[i]); } quicksort(prices,0,n-1); int answer = 0; // Compute the answer for(i=0;i<n;i++){ answer+=prices[i]; if(answer>k){ break; } } printf("%d\n", i); return 0; } <file_sep>Problem Statement Numeros, The Artist, had two lists A and B, such that, B was a permutation of A. Numeros was very proud of these lists. Unfortunately, while transporting them from one exhibition to another, some numbers from List A got left out. Can you find out the numbers missing from A? Notes If a number occurs multiple times in the lists, you must ensure that the frequency of that number in both the lists is the same. If that is not the case, then it is also a missing number. You have to print all the missing numbers in ascending order. Print each missing number once, even if it is missing multiple times. The difference between maximum and minimum number in the list B is less than or equal to 100. Input Format There will be four lines of input: n - the size of the first list This is followed by n space separated integers that make up the first list. m - the size of the second list This is followed by m space separated integers that make up the second list. Output Format Output the missing numbers in ascending order Constraints 1<= n,m <= 1000010 1 <= x <= 10000 , x ∈ B Xmax - Xmin < 101 Sample Input 10 203 204 205 206 207 208 203 204 205 206 13 203 204 204 205 206 207 205 208 203 206 205 206 204 Sample Output 204 205 206 Explanation 204 is present in both the arrays. Its frequency in A is 2, while its frequency in B is 3. Similarly, 205 and 206 occur twice in A, but thrice in B. So, these three numbers are our output. Rest of the numbers have same frequency in both the list <file_sep>Hackerrank-Solution-in-C ======================== The programs for following problems are uploaded: 1. Utopian Tree 2. The Love-Letter Mystery 3. Gem Stones 4. Insertion Sort-Part 1 5. Insertion Sort-Part 2
bd569fe1e0f43ee75c1e3a90059e3b644de206d4
[ "Markdown", "C#" ]
35
Markdown
rflaperuta/Hackerrank-Solution-in-C
042885814a7ea6a3c950bbd400c642e8f067b66a
c50244ecfc46dd029a9d91f4e3e9a9e12d62e296
refs/heads/master
<file_sep>topic=1111test createdir=e\:\\test\\ movedir=e\:\\move\\ threadnum=10 zookeeper=192.168.138.129:2181 broker=192.168.138.129:9091,192.168.138.130:9091 size=3 encoding=gbk mobilepath=E\:\\data-file\\SMSCDR_20130901\\tc_balanceremind_jtlt_2016-05-19 debug=0<file_sep>package unicom.basic; import java.util.Properties; import java.util.concurrent.TimeUnit; import kafka.javaapi.producer.Producer; import kafka.producer.KeyedMessage; import kafka.producer.ProducerConfig; import kafka.serializer.StringEncoder; /** * ������� * ������: 0 ������: 1 ������: 2 ������: 3 ������: 4 ������: 5 ������: 6 ������: 7 ������: 8 ������: 9 ������: 10 ������: 11 ������: 12 ������: 13 ������: 14 ������: 15 ������: 16 ������: 17 ������: 18 * @author zm * */ public class kafkaProducer_test extends Thread{ private String topic; public kafkaProducer_test(String topic){ super(); this.topic = topic; } @Override public void run() { Producer producer = createProducer(); int i=1; while(true){ producer.send(new KeyedMessage<String, String>(topic, String.valueOf(i),"18611701625您的余额不足10元 " + i)); System.out.println("正在发送: " + i); try { //TimeUnit.MILLISECONDS.sleep(1); i++; } catch (Exception e) { e.printStackTrace(); } } } private Producer createProducer() { Properties properties = new Properties(); properties.put("zookeeper.connect", "10.124.3.61:21810,10.124.3.62:21810,10.124.3.63:21810");//����zk properties.put("serializer.class", StringEncoder.class.getName()); properties.put("metadata.broker.list", "10.124.3.61:9092,10.124.3.62:9092,10.124.3.63:9092");// ����kafka broker return new Producer<Integer, String>(new ProducerConfig(properties)); } public static void main(String[] args) { new kafkaProducer_test("test").start();// ʹ��kafka��Ⱥ�д����õ����� test } } <file_sep>package unicom; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import unicom.diction.Diction; import unicom.file.CFile; import kafka.consumer.Consumer; import kafka.consumer.ConsumerConfig; import kafka.consumer.ConsumerIterator; import kafka.consumer.KafkaStream; import kafka.javaapi.consumer.ConsumerConnector; /** * * @author wwh * 不需要配置文件,从 Diction全局类中读取设置启动 * * */ public class kafkaConsumer extends Thread{ private String topic; private int part; private String provinceValue;//默认是50 public kafkaConsumer(String topic,int p){ super(); this.topic = topic; this.part=p; provinceValue="50"; } public kafkaConsumer(String topic,int p,String value){ super(); this.topic = topic; this.part=p; provinceValue=value; } @Override public void run() { String threadname=this.getName(); ConsumerConnector consumer = createConsumer(); Map<String, Integer> topicCountMap = new HashMap<String, Integer>(); topicCountMap.put(topic, this.part); // Map<String, List<KafkaStream<byte[], byte[]>>> messageStreams = consumer.createMessageStreams(topicCountMap); for(final KafkaStream<byte[], byte[]> stream:messageStreams.get(topic)) { //ConsumerThread thread=new ConsumerThread(stream,topic,provinceValue);//用哪个ConsumerThread_HttpClients //thread.start(); ConsumerPartion consumerOne=new ConsumerPartion(stream,topic,provinceValue); consumerOne.recieve(threadname); } } private ConsumerConnector createConsumer() { Properties properties = new Properties(); properties.put("zookeeper.connect", Diction.zookeeper);//����zk properties.put("group.id", "group1"); properties.put("metadata.broker.list", Diction.broker);// ����kafka broker return Consumer.createJavaConsumerConnector(new ConsumerConfig(properties)); } public static void main(String[] args) { //int num_thread=30; String path="e:\\test\\"; String balances="50"; new kafkaConsumer("threetest",Diction.num_thread,balances).start();// ʹ��kafka��Ⱥ�д����õ����� test //new kafkaConsumer("demotest",5).start();// ʹ��kafka��Ⱥ�д����õ����� test } } <file_sep>package urlencode; import java.net.URLDecoder; import java.net.URLEncoder; public class URL { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String param="accessToken=ad39b7dbd59b87cda827223c0e520d6f&appOAuthID=700042973&charset=gbk&format=xml&randomValue=58095&sellerUin=1280863473&timeStamp=1344568374452&uin=1280863473"; String paramtest="authkey=<KEY>&charset=utf8&format=xml&random=58095&sp=chinaunion&timestamp=1461933168"; String data="2016-06-21 15:21"; String paramurlencode=URLEncoder.encode(data); //String md5=MD5.makeMD5("authkey%3D<KEY>2pC%26charset%3Dutf8%26format%3Dxml%26random%3D58095%26sp%3Dchinaunion%26timestamp%3D1461933168"); //String md51=MD5.makeMD5(paramurlencode); // System.out.println(paramurlencode); // System.out.println(md5); // System.out.println(md51); // if(md5.equals(md51)) // { // System.out.println("right"); // } String paramurldecode=URLDecoder.decode(data); System.out.println(paramurlencode); } } <file_sep>package unicom.basic; import java.io.IOException; import kafka.consumer.ConsumerIterator; import kafka.consumer.KafkaStream; import unicom.diction.Diction; import unicom.file.CFile; /* * 每个consumer进程的处理线程启动类,实时通过httpclient传给url * * */ public class ConsumerRealTimeThread extends Thread { KafkaStream<byte[], byte[]> stream; CFile file=null;//接收消息存放文件 String createDir=Diction.createDir;//开始存放的位置 String moveDir=Diction.moveDir;//达到切割大小移动的位置 public ConsumerRealTimeThread(KafkaStream<byte[], byte[]> outstream) { super(); this.stream = outstream; } public void run() { String threadname=this.getName(); createDir=createDir+threadname+"-"; file = new CFile(createDir); // TODO Auto-generated method stub ConsumerIterator<byte[], byte[]> iterator = stream.iterator(); file.renameFile(); while (iterator.hasNext()) { String message = new String(iterator.next().message()); System.out.println("消费:--- " + message); try { if(file.isFull()) { if(file.moveFile(moveDir)) { file=new CFile(createDir); file.renameFile(); } } else//文件没有达到切分大小,判断时间 { file.open(); file.writeRow(message); file.close(); if(file.isToSendDate()) { if(file.moveFile(moveDir)) { file=new CFile(createDir); file.renameFile(); } } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } <file_sep>package unicom; import java.io.IOException; import java.io.UnsupportedEncodingException; import kafka.consumer.ConsumerIterator; import kafka.consumer.KafkaStream; import unicom.diction.Diction; import unicom.file.CFile; import unicom.http.HttpClient; import urlencode.UrlTools; /* * 每个consumer进程的处理线程启动类,实现实时的http方式的数据传输接口 * * */ public class ConsumerThread_HttpClient extends Thread { KafkaStream<byte[], byte[]> stream; UrlTools urltools=new UrlTools();//计算url类 String t; String provinceValue=null; public ConsumerThread_HttpClient(KafkaStream<byte[], byte[]> outstream,String topic,String value) { super(); this.stream = outstream; t=topic; provinceValue=value; } public void run() { ConsumerIterator<byte[], byte[]> iterator = stream.iterator(); while (iterator.hasNext()) { String message = null; try { message = new String(iterator.next().message(),Diction.encoding);//gbk } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println("消费:--- " + message); HttpClient client=new HttpClient(); String url=urltools.createUrl(message,provinceValue); if(null!=url) { client.get(url); } } } } <file_sep>package unicom.diction; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import unicom.bitset.BitSetL; import unicom.bitset.MobileBitSet; import unicom.bitset.NumBitSet; public class Diction { //public static String moveDir="e:\\move\\";//切割之后移动的文件夹 //public static String createDir="e:\\test\\";//生成文件的文件夹 public static String moveDir="/home/wwb/move/";//切割之后移动的文件夹 public static String createDir="/home/wwb/create/";//生成文件的文件夹 public static long fileSize=3*1024;//3kb public static String fileSuffix=".txt";//生成的文件后缀 public static int num_thread=10;//每个消费者起几个线程 public static String topic="remain"; public static String zookeeper=null; public static String broker=null; public static int diffTime=2;//2minute public static String encoding=null; public static Map<String,String> provinceHashMap=new HashMap<String,String>(); public static Map<String,Long> offsetHashMap=new HashMap<String,Long>(); //public static MobileBitSet mobileBitSet=new MobileBitSet();//存放为 1和为2的 情况 public static NumBitSet numBitSet=new NumBitSet();//存放为 1和为2的 情况 public static String mobilepath=null; public static String debug="1";//默认开启测试模式 public static ReadWriteLock lock = new ReentrantReadWriteLock(); public static final Lock readLock = lock.readLock(); public static final Lock writeLock = lock.writeLock(); static { //initSGWDic(sgwdic); readTag("province"); //loadFromFile(mobilepath); } //初始化省份 topic和阈值 public static void readTag(String name) { InputStream in; BufferedReader bf; in=Diction.class.getResourceAsStream("/"+name+".txt"); bf=new BufferedReader(new InputStreamReader(in)); String line=null; String provinceCode=null; String provinceName=null; String provinceValue=null; try { for(;(line=bf.readLine())!=null;) { String []tag=line.split("\\|"); provinceName=tag[0]; provinceCode=tag[1]+"_00"; provinceValue=tag[2]; provinceHashMap.put(provinceCode,provinceValue); provinceCode=null; provinceName=null; provinceValue=null; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>package unicom.job; import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; //import com.alibaba.rocketmq.common.ThreadFactoryImpl; public class ScheduledThreadPoolDemo01 { public static void main(String[] args) throws InterruptedException { // ScheduledExecutorService scheduledExecutorService = Executors // .newSingleThreadScheduledExecutor(new ThreadFactoryImpl("BrokerControllerScheduledThread")); ScheduledExecutorService executor = Executors.newScheduledThreadPool(10); //timer.schedule(task1, 100); final long period = 60 ; executor.scheduleAtFixedRate(new Runnable() { public void run() { // TODO Auto-generated method stub System.out.println("run"); } }, 10,1, TimeUnit.SECONDS); // int i=0; // while(true) // { // i++; // Thread.sleep(1); // // } } } <file_sep>package unicom.basic; import java.io.IOException; import java.io.UnsupportedEncodingException; import kafka.consumer.ConsumerIterator; import kafka.consumer.KafkaStream; import unicom.diction.Diction; import unicom.file.CFile; /* * 每个consumer进程的处理线程启动类,实现文件的自动切割,实现花旦的自动切分 * 按照时间和大小切割文件 * * */ public class ConsumerThread_File extends Thread { KafkaStream<byte[], byte[]> stream; CFile file=null;//接收消息存放文件 String createDir=Diction.createDir;//开始存放的位置 String moveDir=Diction.moveDir;//达到切割大小移动的位置 String t; public ConsumerThread_File(KafkaStream<byte[], byte[]> outstream,String topic) { super(); this.stream = outstream; t=topic; } public void run() { String threadname=this.getName(); createDir=createDir+threadname+"-"+this.t+"-"; file = new CFile(createDir); // TODO Auto-generated method stub ConsumerIterator<byte[], byte[]> iterator = stream.iterator(); file.renameFile(); while (iterator.hasNext()) { String message = null; try { message = new String(iterator.next().message(),Diction.encoding); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println("topic "+this.t +" 消费:--- " + message); try { if(file.isFull()) { if(file.moveFile(moveDir)) { file=new CFile(createDir); file.renameFile(); } } else//文件没有达到切分大小,判断时间 { file.open(); file.writeRow(message); file.close(); if(file.isToSendDate()) { if(file.moveFile(moveDir)) { file=new CFile(createDir); file.renameFile(); } } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } <file_sep>package unicom.file; import java.io.File; /* * * 删除特定目录的文件 * */ public class deleteFile { /** * @param args */ public static void deleteFile(String path) { File dir=new File(path); if(dir.isDirectory()) { int i=0; for(String f:dir.list()) { File file=new File(path+f); // File dest=new File(path+i+".txt"); // file.renameTo(dest); // i++; //dest.delete(); file.delete(); } } } public static void main(String[] args) { // TODO Auto-generated method stub String []pathArr={"e:\\test\\","e:\\move\\"}; for(String path:pathArr) { deleteFile(path); } } } <file_sep>package unicom.bitset; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class MobileBitSet { /** * @param args * 直接使用手机号码 */ BitSetL mobileBitSetIn=new BitSetL();//有效手机号码 状态1 BitSetL mobileBitSetNot=new BitSetL();//无效手机号码 状态 2 String path; /* * 初始化加载 mobile文件 * * */ public boolean loadFromFileQQ(String file) { System.out.println("load qq mobile"); boolean flag=false; InputStream in=null; try { in=new FileInputStream(new File(file)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } BufferedReader reader=new BufferedReader(new InputStreamReader(in)); String line=null; String [] lineArr=null; long mobileNum=0; String mobileStr=null; String openStr=null; try { while((line=reader.readLine())!=null) { lineArr=line.split("\\|"); mobileStr=lineArr[0]; openStr=lineArr[1]; if(11==mobileStr.length()) { mobileNum=Long.parseLong(mobileStr); if(openStr.equals("1"))//开通 { mobileBitSetIn.setComp(mobileNum); } else if(openStr.equals("2"))//取消 { mobileBitSetNot.setComp(mobileNum); } } } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } flag=true; return flag; } /* * 初始化加载 mobile文件 * * */ public boolean loadFromFile(String file) { boolean flag=false; InputStream in=null; try { in=new FileInputStream(new File(file)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } BufferedReader reader=new BufferedReader(new InputStreamReader(in)); String line=null; long mobilenum=0; try { while((line=reader.readLine())!=null) { if(11==line.length()) { mobilenum=Long.parseLong(line); mobileBitSetIn.setComp(mobilenum); } } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } flag=true; return flag; } public boolean geMobileExist(long mobile) { boolean flag=false; if(mobileBitSetIn.getComp(mobile)) { flag=true; } return flag; } //被取消 为 true public boolean geMobileNotExist(long mobile) { boolean flag=false; if(mobileBitSetNot.getComp(mobile)) { flag=true; } return flag; } public BitSetL getMobileBitSet() { return mobileBitSetIn; } public void setMobileBitSet(BitSetL mobileBitSet) { this.mobileBitSetIn = mobileBitSet; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public static void main(String[] args) { // TODO Auto-generated method stub MobileBitSet bitset=new MobileBitSet(); String path="E:\\data-file\\SMSCDR_20130901\\mobile.txt"; //bitset.setPath(path); bitset.loadFromFile(path); System.out.println(bitset.geMobileExist(18601106193L)); } } <file_sep>package unicom; import java.io.IOException; import kafka.consumer.ConsumerIterator; import kafka.consumer.KafkaStream; import unicom.file.CFile; public class ConsumerRunable implements Runnable{ KafkaStream<byte[], byte[]> stream; CFile file=null; String path="e:\\test\\"; public ConsumerRunable(KafkaStream<byte[], byte[]> outstream) { super(); this.stream = outstream; } public void run() { // TODO Auto-generated method stub file = new CFile(path); // TODO Auto-generated method stub ConsumerIterator<byte[], byte[]> iterator = stream.iterator(); while (iterator.hasNext()) { String message = new String(iterator.next().message()); System.out.println("消费:--- " + message); try { file.open(); file.writeRow(message); file.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } <file_sep>package unicom.bitset; public class MobileShort { /** * @param args * * 186 1 * 185 2 * 156 3 * 155 4 * 132 5 * 131 6 * */ private String mobilePre[]={"186","185","156","155","132","131","130","176","175","145"}; public int changePre(String pre) { int index=0; boolean flag=false; for(String a:mobilePre) { index++; if(a.equals(pre)) { flag=true; break; } } if(!flag) { index=0;//表示没有找到前缀匹配。 } return index; } public String getShortMobile(String mobile) { String shortMobile=null; String pre=mobile.substring(0, 3); int index=changePre(pre); if(0!=index) { shortMobile=index+mobile.substring(3, 11); } return shortMobile; } public static void main(String[] args) { // TODO Auto-generated method stub MobileShort mobileShort=new MobileShort(); String s=mobileShort.getShortMobile("13011701625"); System.out.println(s); } }
7123df60cd76ef931612711e9b55c0a77db222a8
[ "Java", "INI" ]
13
INI
xmas25/kafka
8eecc46470e567d65ad713e2d380d9e375cbf9a5
ff196a0582bf5a70972c934e276a1c74e419d41e
refs/heads/master
<file_sep>;(function(){ 'use strict'; angular .module('app') .controller('FileStructureCtrl', FileStructureCtrl); function FileStructureCtrl($scope){ $scope.number = 1; } }).call(this);<file_sep>module.exports = function (gulp, g, install, conflict, template, rename, _, inflections, inquirer, mkdirp, express) { var app = express(); gulp.task('run', function (done) { app.use( express.static('.') ) app.listen(9000, function(){ console.log('Go to Localhost:9000') done() }); }); return gulp; };<file_sep>var es = require('event-stream'); var path = require('path'); module.exports = function(gulp, g, install, conflict, template, rename, _, inflection, inquirer, mkdirp){ gulp.task('default', function(done){ // if (!this.args[0]) { // console.log('****** Incorrect usage of the sub-generator!! ******'); // console.log('****** Try slush build <level-name> ******'); // console.log('****** Ex: slush build biginner ******'); // console.log('****** Ex: slush build basic ******'); // console.log('****** Ex: slush build expert ******'); // console.log('****** Ex: slush build fullstack ******'); // return done(); // } var templatePath = __dirname + '/../templates'; var prompts = [{ name: 'appName', message: 'What would you like to call your application?', default: 'Build' },{ type: 'list', name: 'level', message: 'Which Level would you like to start at?', choices: [ { value: 'beginner', name: 'Beginner', default: true },{ value: 'basic', name: 'Basic', default: false } ] },{ name: 'appAuthor', message: 'What is your company/author name?' }]; //Ask inquirer.prompt(prompts, function (answers) { if (!answers.appName) { return done(); } answers.slugifiedAppName = _.slugify(answers.appName); answers.humanizedAppName = _.humanize(answers.appName); answers.capitalizedAppAuthor = _.capitalize(answers.appAuthor); gulp.src(path.join(templatePath, '/build.json')) .pipe( g.jsonEditor( function ( json ) { json.appName = answers.appName json.slugifiedAppName = answers.slugifiedAppName json.humanizedAppName = answers.humanizedAppName json.capitalizedAppAuthor = answers.capitalizedAppAuthor json.level = answers.level return json; })) .pipe( gulp.dest('./') ) gulp.src(path.join(templatePath, answers.level, '/templates/**')) .pipe(rename(function(file) { if (file.basename.indexOf('__') == 0) { file.basename = '.' + file.basename.slice(2); } })) .pipe(template(answers)) .pipe(conflict('./')) .pipe(gulp.dest('./')) .pipe(install()) .on('end', function () { done() }); }); }); return gulp; }<file_sep>/* * slush-meanjs * https://github.com/arvindr21/slush-meanjs * * Copyright (c) 2014, <NAME> * Licensed under the MIT license. */ 'use strict'; var gulp = require('gulp'), g = require('gulp-load-plugins')({lazy:false}), install = require('gulp-install'), conflict = require('gulp-conflict'), template = require('gulp-template'), rename = require('gulp-rename'), _ = require('underscore.string'), inflection = require('inflection'), inquirer = require('inquirer'), mkdirp = require('mkdirp'), express = require('express'), fs = require('fs-extra'); // load generators gulp = require('./generators/app')(gulp, g, install, conflict, template, rename, _, inflection, inquirer, mkdirp); gulp = require('./generators/run')(gulp, g, install, conflict, template, rename, _, inflection, inquirer, mkdirp, express); gulp = require('./generators/fileStructure')(gulp, g, install, conflict, template, rename, _, inflection, inquirer, mkdirp); <file_sep>;(function(){ 'use struct'; angular .module('app') .controller('SideBarCtrl', SideBarCtrl); /* @inject */ function SideBarCtrl($scope, $location, $state, StatesService) { StatesService.get() .then( function ( data ){ $scope.steps = data.states; }) $scope.isCollapsed = true; $scope.isActive = function(route) { return route === $state.current.name }; } }).call(this);<file_sep>;(function(){ 'use strict'; angular .module('app', [ 'ui.router']) .config( States ); function States($stateProvider, $urlRouterProvider){ $urlRouterProvider.otherwise('/'); } }).call(this);
90189c88e56dbd96aa66401f7855df74e1a43f0d
[ "JavaScript" ]
6
JavaScript
NeoTim/slush-build
f0c70c54bd4b50c6b94547edece12ac1a8ed2e75
aee55f73cba01f36ec5fa8e5102482b321d21664
refs/heads/main
<file_sep>import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class ForkPoolDemo { public static void main(String[] args) throws InterruptedException { List<String> st = Arrays.asList("ax","bx","cx","dx","ex","fx","gx","hx","ix","jx","kx","lx","mx","nx","ox","px","qx","rx","sx","tx","ux","vx","wx","yx","zx"); /*Long startTime = System.currentTimeMillis(); ForkJoinPool pool1 = new ForkJoinPool(4); pool1.execute(() -> { st.stream().forEach(det -> { try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " " + myMthod(det)); }); }); Long timeTaken = System.currentTimeMillis() - startTime; System.out.println(timeTaken); System.out.println(); System.out.println();*/ /* Long startTime2 = System.currentTimeMillis(); System.out.println(Runtime.getRuntime().availableProcessors()); ForkJoinPool pool2 = new ForkJoinPool(4); st.stream().forEach(det -> { pool2.execute(() -> { System.out.println(Thread.currentThread().getName() + " " + myMthod(det)); }); }); Long timeTaken2 = System.currentTimeMillis() - startTime2; System.out.println(timeTaken2); System.out.println(); System.out.println();*/ List<Callable<String>> listCallable = new ArrayList<>(); st.stream().forEach(det -> { Callable<String> callable = () -> { System.out.println(Thread.currentThread().getName() + " " + myMthod(det)); return det; }; listCallable.add(callable); }); Long startTime3 = System.currentTimeMillis(); ExecutorService exec = Executors.newFixedThreadPool(5); List<Future<String>> str = exec.invokeAll(listCallable); exec.shutdown(); Long timeTaken3 = System.currentTimeMillis() - startTime3; System.out.println(timeTaken3); /* //Long startTime3 = System.currentTimeMillis(); ExecutorService exec1 = Executors.newFixedThreadPool(4); try { exec1.submit(() -> { st.stream().forEach(det -> { System.out.println(Thread.currentThread().getName() + " " + myMthod(det)); }); }).get(); } catch (InterruptedException | ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } //Long timeTaken3 = System.currentTimeMillis() - startTime3; //System.out.println(timeTaken3); */ } private static String myMthod(String det) { try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return det; } } <file_sep>import java.util.*; public class Compare { public static void main(String[] args) { List<String> destinationIds = Arrays.asList("abc", "bcd", "pqr", "str", "xyz"); List<String> sortedProducts1 = Arrays.asList("abc","str","bcd"); sortedProducts1.sort(Comparator.comparingInt(destinationIds::indexOf)); System.out.println(sortedProducts1); System.out.println("------------------------------------------"); List<Product> products = new ArrayList<>(); Product product1 = new Product("abc", "abc"); Product product2 = new Product("str", "str"); Product product3 = new Product("bcd", "bcd"); products.add(product1); products.add(product2); products.add(product3); System.out.println("Before Sorting"); System.out.println(products); System.out.println("------------------------------------------"); products.stream().forEach(product -> product.getId()); products.sort(Comparator.comparing( v -> destinationIds.indexOf(v.getId()))); System.out.println("After Sorting"); System.out.println(products); } } <file_sep>import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class LearnQueueAndBlockedQueue { public static void main(String[] args) throws InterruptedException { Queue<String> queue = new LinkedList<>(); System.out.println(queue.poll()); BlockingQueue<String> blockedQueue = new LinkedBlockingQueue<>(); blockedQueue.put("12"); System.out.println(blockedQueue.take()); } } <file_sep>import java.util.List; public class EntityObject { List address; List addLine1; String addLine2; public List getAddress() { return address; } public void setAddress(List address) { this.address = address; } public List getAddLine1() { return addLine1; } public void setAddLine1(List addLine1) { this.addLine1 = addLine1; } public String getAddLine2() { return addLine2; } public void setAddLine2(String addLine2) { this.addLine2 = addLine2; } } <file_sep>import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; public class MainClass { static List<List<String>> addressList = null; static List<EntityObject> entityList = null; public static void main(String[] args) { // TODO Auto-generated method stub populateList(); populateListOfEntityObject(); for(int i=0;i<addressList.size();i++) { System.out.println(addressList.get(i)); } for(int i=0;i<entityList.size();i++) { System.out.println(entityList.get(i).addLine1); } /* for(int i=0;i<addressList.size();i++) { entityList.get(i).setAddLine1(addressList.get(i)); } */ List<EntityObject> entityListOne = IntStream.range(0, addressList.size()) .mapToObj(i -> mapping(entityList.get(i), addressList.get(i))) .collect(Collectors.toList()); for(int i=0;i<entityListOne.size();i++) { System.out.println(entityListOne.get(i).addLine1); } } private static EntityObject mapping(EntityObject entityObject, List<String> address) { entityObject.setAddLine1(address); return entityObject; } private static void populateList() { List<String> addList = Arrays.asList("House 123"); List<String> addList1 = Arrays.asList("House 456"); List<String> addList2 = Arrays.asList("House 789"); addressList = Arrays.asList(addList, addList1, addList2); } private static void populateListOfEntityObject() { EntityObject enObj = new EntityObject(); enObj.setAddLine1(Arrays.asList("H 123")); enObj.setAddLine2("Gurgaon"); EntityObject enObj1 = new EntityObject(); enObj1.setAddLine1(Arrays.asList("H 456")); enObj1.setAddLine2("Gurgaon"); EntityObject enObj2 = new EntityObject(); enObj2.setAddLine1(Arrays.asList("H 789")); enObj2.setAddLine2("Gurgaon"); entityList = Arrays.asList(enObj,enObj1,enObj2); } } <file_sep>import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; public class Demo { public static void main(String[] args) { String a[] = { "A", "B", "C", "D" }; List<String> st = new ArrayList<>(); st.add("suspendResume"); st.add("changeWirelessUserID"); String one = "changeWirelessUserID"; if (st.contains(one)) { System.out.println("contains " + true); } else { System.out.println("contains " + false); } List<String> data = new LinkedList<String>(Arrays.asList(a)); data.add("E"); System.out.println(data); boolean boo = true; Boolean flush = Boolean.FALSE; flush = flush || boo; System.out.println(flush); System.out.println(""); String secretPhrase = "<PASSWORD>"; System.out.println(secretPhrase.getBytes()); } } <file_sep>import java.util.ArrayList; import java.util.List; import java.util.Locale; public class dummy { public static void main(String[] args) { if (true && false || true && false) { System.out.println("hey"); } Boolean ab = Boolean.valueOf(""); System.out.println(ab); System.out.println("hey " + null); List<String> phones = new ArrayList<>(); phones.add("123"); phones.add(" "); phones.add("last"); for (String phone : phones) { System.out.println("phone :" + phone + ";"); } Locale locale = Locale.US; Object object = locale; String stringLocale = (String) object; System.out.println(stringLocale); } } <file_sep>import java.util.List; import java.util.Scanner; public class Hello { public static void main(String[] args) { String [] array = {"a","b","c"}; List<String> data= List.of(array); array[1] = "d"; System.out.println(data); Scanner sc = new Scanner(System.in); int lsc = sc.nextInt(); System.out.println(lsc); } } <file_sep>import java.util.Arrays; import java.util.List; public class StringAppend { public static void main(String[] args) { List<String> blockNumberList = Arrays.asList("a","b","c"); StringBuilder output = new StringBuilder(); int pipecount = 0; for (String blockNumber : blockNumberList) { output.append(blockNumber); if (pipecount < 4) { output.append("|"); } pipecount++; } for (int i = pipecount; i<4; i++) { output.append("|"); } System.out.println(output.toString()); } } <file_sep>import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class DemoSleep { public static void main(String[] args) { DemoSleep sleep = new DemoSleep(); String A = "Sun 10:00-20:00\n"+ "Fri 05:00-10:00\n"+ "Fri 16:30-23:50\n"+ "Sat 10:00-24:00\n"+ "Sun 01:00-04:00\n"+ "Sat 02:00-06:00\n"+ "Tue 03:30-18:15\n"+ "Tue 19:00-20:00\n"+ "Wed 04:25-15:14\n"+ "Wed 15:14-22:40\n"+ "Thu 00:00-23:59\n"+ "Mon 05:00-13:00\n"+ "Mon 15:00-21:00"; sleep.solution(A); } public int solution(String A) { String [] array = A.split("\n"); List<List<String>> startTimeArrayList = new ArrayList<>(); List<List<String>> endTimeArrayList = new ArrayList<>(); List<String> mon = new ArrayList<>(); List<String> tue = new ArrayList<>(); List<String> wed = new ArrayList<>(); List<String> thu = new ArrayList<>(); List<String> fri = new ArrayList<>(); List<String> sat = new ArrayList<>(); List<String> sun = new ArrayList<>(); List<String> monE = new ArrayList<>(); List<String> tueE = new ArrayList<>(); List<String> wedE = new ArrayList<>(); List<String> thuE = new ArrayList<>(); List<String> friE = new ArrayList<>(); List<String> satE = new ArrayList<>(); List<String> sunE = new ArrayList<>(); for (String a : array) { String [] singleValueSplit = a.split(" "); if (singleValueSplit[0].equals("Mon")) { mon.add(singleValueSplit[1].split("-")[0]); monE.add(singleValueSplit[1].split("-")[1]); } if (singleValueSplit[0].equals("Tue")) { tue.add(singleValueSplit[1].split("-")[0]); tueE.add(singleValueSplit[1].split("-")[1]); } if (singleValueSplit[0].equals("Wed")) { wed.add(singleValueSplit[1].split("-")[0]); wedE.add(singleValueSplit[1].split("-")[1]); } if (singleValueSplit[0].equals("Thu")) { thu.add(singleValueSplit[1].split("-")[0]); thuE.add(singleValueSplit[1].split("-")[1]); } if (singleValueSplit[0].equals("Fri")) { fri.add(singleValueSplit[1].split("-")[0]); friE.add(singleValueSplit[1].split("-")[1]); } if (singleValueSplit[0].equals("Sat")) { sat.add(singleValueSplit[1].split("-")[0]); satE.add(singleValueSplit[1].split("-")[1]); } if (singleValueSplit[0].equals("Sun")) { sun.add(singleValueSplit[1].split("-")[0]); sunE.add(singleValueSplit[1].split("-")[1]); } } startTimeArrayList.add(mon.stream().sorted().collect(Collectors.toList())); startTimeArrayList.add(tue.stream().sorted().collect(Collectors.toList())); startTimeArrayList.add(wed.stream().sorted().collect(Collectors.toList())); startTimeArrayList.add(thu.stream().sorted().collect(Collectors.toList())); startTimeArrayList.add(fri.stream().sorted().collect(Collectors.toList())); startTimeArrayList.add(sat.stream().sorted().collect(Collectors.toList())); startTimeArrayList.add(sun.stream().sorted().collect(Collectors.toList())); endTimeArrayList.add(monE.stream().sorted().collect(Collectors.toList())); endTimeArrayList.add(tueE.stream().sorted().collect(Collectors.toList())); endTimeArrayList.add(wedE.stream().sorted().collect(Collectors.toList())); endTimeArrayList.add(thuE.stream().sorted().collect(Collectors.toList())); endTimeArrayList.add(friE.stream().sorted().collect(Collectors.toList())); endTimeArrayList.add(satE.stream().sorted().collect(Collectors.toList())); endTimeArrayList.add(sunE.stream().sorted().collect(Collectors.toList())); List<String> endTimeList = endTimeArrayList.stream().flatMap(List::stream).collect(Collectors.toList()); List<String> startTimeList = startTimeArrayList.stream().flatMap(List::stream).collect(Collectors.toList()); int [] startTimeArray = new int[startTimeList.size()]; int count = 0; for (String startTime : startTimeList) { int min = 0; String[] split = startTime.split(":"); min += Integer.parseInt(split[0])*60; min += Integer.parseInt(split[1]); startTimeArray[count]=min; count++; } int [] endTimeArray = new int[endTimeList.size()]; count = 0; for (String endTime : endTimeList) { int min = 0; String[] split = endTime.split(":"); min += Integer.parseInt(split[0])*60; min += Integer.parseInt(split[1]); endTimeArray[count]=min; count++; } for (int startTime : startTimeArray) { System.out.print(startTime + ","); } System.out.println(); for (int endTime : endTimeArray) { System.out.print(endTime + ","); } int [] endTimeArray1 = {780,1260,1095,1200,914,1360,1439,600,1430,360,1440,240,1200}; int [] startTimeArray1 = {300,900,210,1140,265,914,0,300,990,120,600,60,600}; int maxSleepTime = 0; for (int i=0;i < endTimeArray.length; i++) { int sleepTime = 0; if (i+1 < endTimeArray.length && startTimeArray[i+1] >= endTimeArray[i]) { sleepTime = startTimeArray[i+1] - endTimeArray[i]; } else if (i+1 < endTimeArray.length && startTimeArray[i+1] < endTimeArray[i]) { sleepTime = startTimeArray[i+1] + (1440 - endTimeArray[i]); } if (maxSleepTime < sleepTime) { maxSleepTime = sleepTime; } } System.out.println(); System.out.println(maxSleepTime); return maxSleepTime; } }
2aeaec17a7bbcd9c7327cb9127e91fe4a90c6b22
[ "Java" ]
10
Java
tanujjunat/Miscellaneous
2d7dd7cb4912cef03e000e8002f445eb7992ebf6
cecb30ebe8d40633f1757dc6107bd7e34879a2ee
refs/heads/main
<file_sep># nodejs-backend backend api for nodejs <file_sep>const {validationResult} = require('express-validator/check'); const http = require('http'); const Order = require('../models/order'); exports.addOrder = (req, res, next) => { const errors = validationResult(req); if (!errors.isEmpty()) { const error = new Error('Validation failed, entered data is incorrect.'); error.statusCode = 422; throw error; } const item = req.body.item; const totalPrice = req.body.totalPrice; const order = new Order({ item: item, totalPrice: totalPrice, }); order .save() .then(result => { res.status(201).json({ message: 'Order created successfully!', post: result }); }) .catch(err => { if (!err.statusCode) { err.statusCode = 500; } next(err); }); }; exports.getOrder = (req, res, next) => { Order.find().then((order) => { if (!order) { const error = new Error('Could not find order.'); error.statusCode = 404; throw error; } res.status(200).json({message: 'Order fetched.', order: order}); }).catch(err => { if (!err.statusCode) { err.statusCode = 500; } next(err); }); }; exports.proceedPayment = async (req, res, next) => { const orderId = req.body.orderId; const data = req.body; await Order.findById(orderId) .then(async order => { if (!order) { const error = new Error('Could not find post.'); error.statusCode = 404; throw error; } //inject order into request body data['order'] = order; let result = await callPayment(orderId, data); let message = "Something is wrong while making payment" if (result) { message = "Order has completed"; } res.status(200).json({ status: result, message: message, data: [] }).end(); }).catch(err => { if (!err.statusCode) { err.statusCode = 500; } next(err); }); } function callPayment(orderId, data) { return new Promise((resolve, reject) => { //call to another instance on port 8082 to simulate microservices const request = http.request({ host: 'nodejs-2', port: "8082", path: '/payment/try', method: 'POST', headers: { 'Content-Type': 'application/json', } }, function (response) { console.log("here"); let data = ''; response.on('data', (chunk) => { data += chunk; }); response.on('end', () => { data = JSON.parse(data); if (data.success) { updateOrder(orderId, {"status": "delivered"}); resolve(true); } else { updateOrder(orderId, {"status": "pending payment"}); resolve(false); } }); }); request.write(JSON.stringify(data)); request.end(); }); } function updateOrder(orderId, message) { Order.findByIdAndUpdate(orderId, message).then(order => { }).catch(err => { console.log(err); }); }<file_sep>const Router = require('express-group-router'); let router = new Router(); const {body} = require('express-validator/check'); const feedController = require('../controllers/feed'); const orderController = require('../controllers/order'); const paymentController = require('../controllers/payment'); router.group('/feed', [], (router) => { router.get('/posts', function (req, res, next) { feedController.getPosts(req, res, next) }); router.post('/post', function (req, res, next) { feedController.createPost(req, res, next) }); router.get('/post/:postId', function (req, res, next) { feedController.getPost(req, res, next) }); }); router.group('/order', [], (router) => { router.get('/list', function (req, res, next) { orderController.getOrder(req, res, next) }); router.post('/add', function (req, res, next) { orderController.addOrder(req, res, next) }); router.post('/payment', function (req, res, next) { orderController.proceedPayment(req, res, next) }); }); module.exports = router;
f9e27f783b51f5a32c53f116f6c6de6e00397c31
[ "Markdown", "JavaScript" ]
3
Markdown
aalihusni/nodejs-backend
62f8ccd23d5fcf85f67e05771f84d2b50c19db0b
b2d1393f5a8785a5b6ee684c71cd2180875bfd34
refs/heads/master
<repo_name>YooDongGi/java_firstproject<file_sep>/src/service/ReserService.java package service; import java.util.Date; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import controller.Controller; import util.ScanUtil; import util.View; import dao.ReserDao; import dao.RoomDao; public class ReserService { private ReserService() {} private static ReserService instance; public static ReserService getInstance() { if(instance == null) { instance = new ReserService(); } return instance; } Calendar cal = Calendar.getInstance(); //날짜 계산을 위해 추가 private ReserDao reserDao = ReserDao.getInstance(); private RoomDao roomDao = RoomDao.getInstance(); public int reser_lookup() { List<Map<String, Object>> reserlookup = reserDao.reserlookup(); SimpleDateFormat sdf_dt = new SimpleDateFormat("yy/MM/dd"); System.out.println("=====================[예약 목록]===================="); System.out.println("호실\t예약자\t인원\t 예약일\t\t퇴실일"); System.out.println("-------------------------------------------------"); for(int i = 0; i < reserlookup.size(); i++) { String s_date = sdf_dt.format(reserlookup.get(i).get("S_DATE")); String e_date = sdf_dt.format(reserlookup.get(i).get("E_DATE")); System.out.println(reserlookup.get(i).get("R_NO") + "\t" + reserlookup.get(i).get("NAME") + "\t" + reserlookup.get(i).get("PEOPLE")+ "\t" + s_date +" ~\t" + e_date); } System.out.println("================================================="); System.out.println("1.삭제\t0.뒤로가기"); int input = ScanUtil.nextInt(); switch (input) { case 1: return View.RE_DELETE; case 0: return View.RE_HOME; } return View.RE_LOOKUP; } public int reser_delete() { System.out.print("삭제할 호실을 입력하시오.> "); int ho = ScanUtil.nextInt(); System.out.print("예약한 날짜를 입력하시오.(YYYY-MM-DD)> "); String s_date = ScanUtil.nextLine(); Map<String, Object> param = new HashMap<>(); param.put("HO", ho); param.put("S_DATE", s_date); int result = reserDao.reser_delete(param); if(0 < result) { System.out.println("삭제되었습니다."); } else { System.out.println("삭제되지 않았습니다."); } return View.RE_LOOKUP; } public int reser_insert() { Date today = new Date(); String e_date = null; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); System.out.print("방 호실 > "); int r_no = ScanUtil.nextInt(); List<Map<String, Object>> r_ho = roomDao.roomho(); boolean ok = true; ha : while(ok){ for(int i = 0; i < r_ho.size(); i++) { if(r_no == Integer.parseInt(r_ho.get(i).get("R_NO").toString() ) ) { ok = false; break ha; } } System.out.println("존재하지 않는 방입니다."); return View.RE_ADD; } System.out.print("인원 수 > "); int people = ScanUtil.nextInt(); Map<String, Object> r_people = roomDao.roompeople(r_no); if(people > Integer.parseInt(r_people.get("PERSONNEL").toString())) { System.out.println("최대인원을 넘어갈 수 없습니다."); return View.RE_ADD; } System.out.println("YYYY-MM-DD 형식으로 입력하시오."); System.out.print("예약 날짜 > "); String s_date = ScanUtil.nextLine(); System.out.print("묵을 일 수 > "); int day = ScanUtil.nextInt(); while(true) { try { Date s_d = sdf.parse(s_date); cal.setTime(s_d); cal.add(Calendar.DAY_OF_MONTH, day); e_date = sdf.format(cal.getTime()); if(today.getTime() > s_d.getTime()){ System.out.println("예약일 기준 다음날부터 예약 가능합니다."); return View.RE_ADD; } else { break; } } catch (ParseException e) { e.printStackTrace(); } } Map<String , Object> param1 = new HashMap<>(); param1.put("R_NO", r_no); param1.put("S_DATE", s_date); param1.put("E_DATE", e_date); List<Map<String, Object>> room_date = roomDao.roomdate(param1); if(room_date.isEmpty()) { }else{ System.out.println("이미 예약되있는 방입니다."); return View.RE_ADD; } Map<String, Object> param = new HashMap<>(); param.put("R_NO", r_no); param.put("PEOPLE", people); param.put("DAY",day); param.put("S_DATE", s_date); param.put("E_DATE", e_date); int result = reserDao.insertreser(param); if(0 < result) { System.out.println("예약되었습니다."); } else { System.out.println("예약되지 않았습니다."); } return View.RE_HOME; } public int reser_lookup_M() { List<Map<String, Object>> reserlookup = reserDao.reserlookup_M(); SimpleDateFormat sdf_dt = new SimpleDateFormat("yy/MM/dd"); System.out.println("============================[예약 목록]============================"); System.out.println("호실\t예약자\t인원\t 전화번호\t\t 예약일\t\t퇴실일"); System.out.println("--------------------------------------------------------------"); for(int i = 0; i < reserlookup.size(); i++) { String s_date = sdf_dt.format(reserlookup.get(i).get("S_DATE")); String e_date = sdf_dt.format(reserlookup.get(i).get("E_DATE")); System.out.println(reserlookup.get(i).get("R_NO") + "\t" + reserlookup.get(i).get("NAME") + "\t" + reserlookup.get(i).get("PEOPLE") + "\t" + reserlookup.get(i).get("TEL") +"\t" + s_date + " ~ " + e_date ); } System.out.println("================================================================="); System.out.println("1.삭제\t0.뒤로가기"); int input = ScanUtil.nextInt(); switch (input) { case 1: return View.RE_DELETE_M; case 0: return View.RE_HOME; } return View.RE_LOOKUP_M; } public int reser_delete_M() { System.out.print("삭제할 호실을 입력하시오.> "); int ho = ScanUtil.nextInt(); System.out.print("예약한 날짜를 입력하시오.(YYYY-MM-DD)> "); String s_date = ScanUtil.nextLine(); Map<String, Object> param = new HashMap<>(); param.put("HO", ho); param.put("S_DATE", s_date); int result = reserDao.reser_delete_M(param); if(0 < result) { System.out.println("삭제되었습니다."); } else { System.out.println("삭제되지 않았습니다."); } return View.RE_LOOKUP_M; } public int money_all() { Map<String, Object> money_all = reserDao.money_all(); System.out.print("총 매출은 "); System.out.println(money_all.get("MONEY")+ "원 입니다."); return View.M_HOME; } } <file_sep>/src/dao/UserDao.java package dao; import java.util.ArrayList; import java.util.List; import java.util.Map; import util.JDBCUtil; public class UserDao { private UserDao() {} private static UserDao instance; public static UserDao getInstance() { if(instance == null) { instance = new UserDao(); } return instance; } private JDBCUtil jdbc = JDBCUtil.getInstance(); public Map<String, Object> selectUser(String userId, String password) { //로그인 String sql = "SELECT NUM, ID, NAME, TYPE" + " FROM p_user" + " WHERE ID = ? " + " AND PASSWORD = ?"; List<Object> param = new ArrayList<>(); param.add(userId); param.add(password); return jdbc.selectOne(sql, param); } public int insertUser(Map<String, Object> p) { //회원가입 String sql = "INSERT INTO p_user VALUES ((SELECT NVL(MAX(num),0) + 1 from p_user),?, ?, ? ,? , 1)"; List<Object> param = new ArrayList<>(); param.add(p.get("ID")); param.add(p.get("PASSWORD")); param.add(p.get("NAME")); param.add(p.get("TEL")); return jdbc.update(sql, param); } public List<Map<String, Object>> selectidlist() { String sql = "SELECT ID FROM p_user"; return jdbc.selectList(sql); } } <file_sep>/src/dao/RoomDao.java package dao; import java.util.ArrayList; import java.util.List; import java.util.Map; import util.JDBCUtil; public class RoomDao { private RoomDao() {} private static RoomDao instance; public static RoomDao getInstance() { if(instance == null) { instance = new RoomDao(); } return instance; } private JDBCUtil jdbc = JDBCUtil.getInstance(); public List<Map<String, Object>> selectRoomList() { //방 목록 조회 String sql = "SELECT * FROM room ORDER BY r_no DESC"; return jdbc.selectList(sql); } public int insertRoom(Map<String, Object> p) { //방 추가 String sql = "INSERT INTO room VALUES (?,?,?,?,?)"; List<Object> param = new ArrayList<>(); param.add(p.get("R_NO")); param.add(p.get("R_NAME")); param.add(p.get("PERSONNEL")); param.add(p.get("INTRODUCE")); param.add(p.get("PRICE")); return jdbc.update(sql, param); } public int deleteRoom(int input) { //방 삭제 String sql = "DELETE room WHERE r_no = "+ input; return jdbc.update(sql); } public Map<String, Object> roompeople(int r_no) { String sql = "SELECT personnel FROM room WHERE r_no = " + r_no; return jdbc.selectOne(sql); } public List<Map<String, Object>> roomho() { String sql = "SELECT r_no FROM room"; return jdbc.selectList(sql); } public List<Map<String, Object>> roomdate(Map<String, Object> p) { String sql = "SELECT r_no FROM reservation WHERE r_no = ?" + " AND (s_date BETWEEN TO_DATE(? , 'YYYY-MM-DD') AND TO_DATE( ?, 'YYYY-MM-DD')" + " OR e_date BETWEEN TO_DATE(?, 'YYYY-MM-DD') AND TO_DATE(?, 'YYYY-MM-DD')" + " AND TO_DATE( ? ,'YYYY-MM-DD') BETWEEN s_date AND e_date" + " OR TO_DATE( ? ,'YYYY-MM-DD') BETWEEN s_date AND e_date)"; List<Object> param = new ArrayList<>(); param.add(p.get("R_NO")); param.add(p.get("S_DATE")); param.add(p.get("E_DATE")); param.add(p.get("S_DATE")); param.add(p.get("E_DATE")); param.add(p.get("S_DATE")); param.add(p.get("E_DATE")); return jdbc.selectList(sql, param); } } <file_sep>/src/dao/BoardDao.java package dao; import java.util.ArrayList; import java.util.List; import java.util.Map; import controller.Controller; import service.BoardService; import util.JDBCUtil; public class BoardDao { private BoardDao() {} private static BoardDao instance; public static BoardDao getInstance() { if(instance == null) { instance = new BoardDao(); } return instance; } private JDBCUtil jdbc = JDBCUtil.getInstance(); public List<Map<String, Object>> selectBoardList() { //공지사항 목록 조회 String sql = "SELECT A.NO, A.TITLE, A.CONTENT, B.NAME, A.N_DATE " +" FROM notice A, p_user B " +" WHERE A.user_no = B.num(+) " +" ORDER BY A.NO DESC"; return jdbc.selectList(sql); } public int insertBoard(Map<String, Object> p) { //공지사항 작성 String sql = "INSERT INTO notice VALUES ((SELECT NVL(MAX(no),0) + 1 from notice)," + "?, ?, SYSDATE, ?)"; List<Object> param = new ArrayList<>(); param.add(p.get("TITLE")); param.add(p.get("CONTENT")); param.add(p.get("USER_NO")); return jdbc.update(sql, param); } public Map<String, Object> notice_lookup() { //공지사항 게시글 조회 String sql = "SELECT A.NO, A.TITLE, A.CONTENT, B.NAME, A.N_DATE " + " FROM notice A, p_user B " + " WHERE A.user_no = B.num(+) AND NO = " + BoardService.no; return jdbc.selectOne(sql); } public int notice_delete() { //공지사항 삭제 String sql = "DELETE notice WHERE no = " + BoardService.no; return jdbc.update(sql); } public int notice_update(Map<String, Object> p) { //공지사항 수정 String sql = "UPDATE notice set" +" title = ? , content = ?, n_date = sysdate " +" where no = "+ BoardService.no; List<Object> param = new ArrayList<>(); param.add(p.get("TITLE")); param.add(p.get("CONTENT")); return jdbc.update(sql, param); } public List<Map<String, Object>> selectReviewList() { //리뷰 목록 조회 String sql = "SELECT A.no, A.title, B.name, A.score " +" FROM review A, p_user B " +" WHERE A.user_no = B.num(+)" +" ORDER BY no DESC"; return jdbc.selectList(sql); } public Map<String, Object> review_lookup() { //리뷰 게시글 조회 String sql = "SELECT A.no, A.title, B.name, A.score, A.content, A.r_date, A.user_no" +" FROM review A, p_user B " +" WHERE A.user_no = B.num(+) AND no =" + BoardService.no; return jdbc.selectOne(sql); } public int insertreview(Map<String, Object> p) { //리뷰 작성 String sql = "INSERT INTO review VALUES ( " +" (SELECT NVL(MAX(no),0) + 1 FROM review) " +", ?, ?, ?, SYSDATE, ?)"; List<Object> param = new ArrayList<>(); param.add(p.get("TITLE")); param.add(p.get("SCORE")); param.add(p.get("CONTENT")); param.add(p.get("USER_NO")); return jdbc.update(sql, param); } public int review_delete() { //리뷰 삭제 String sql = "DELETE review WHERE no = "+ BoardService.no; return jdbc.update(sql); } public int review_update(Map<String, Object> p) { //리뷰 수정 String sql = "UPDATE review SET TITLE = ? " + ", SCORE = ?, CONTENT = ?, R_DATE = SYSDATE WHERE no = " + BoardService.no; List<Object> param = new ArrayList<>(); param.add(p.get("TITLE")); param.add(p.get("SCORE")); param.add(p.get("CONTENT")); return jdbc.update(sql, param); } } <file_sep>/src/service/BoardService.java package service; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.List; import java.util.Map; import controller.Controller; import util.ScanUtil; import util.View; import dao.BoardDao; public class BoardService { private BoardService() {} private static BoardService instance; public static BoardService getInstance() { if(instance == null) { instance = new BoardService(); } return instance; } private BoardDao boardDao = BoardDao.getInstance(); public int notice_view() { //공지사항 목록 조회 SimpleDateFormat sdf_n = new SimpleDateFormat("yyyy-MM-dd"); List<Map<String, Object>> boardList = boardDao.selectBoardList(); System.out.println("===============[공지사항]================"); System.out.println("번호\t제목\t작성자\t작성일"); System.out.println("---------------------------------------"); for(int i = 0; i < boardList.size(); i++) { String n_date = sdf_n.format(boardList.get(i).get("N_DATE")); System.out.println(boardList.get(i).get("NO") + "\t" + boardList.get(i).get("TITLE") + "\t" + boardList.get(i).get("NAME") + "\t" + n_date); // + boardList.get(i).get("N_DATE")); } System.out.println("======================================="); if(Controller.type == 0) { System.out.println("1.조회\t2.등록\t0.뒤로가기"); int input = ScanUtil.nextInt(); switch (input) { case 1: return View.BOARD_NOTICE_LOOKUP; case 2: return View.BOARD_NOTICE_ADD; case 0: return View.M_HOME; } } else if(Controller.type == 1) { System.out.println("1.조회\t0.뒤로가기"); int input = ScanUtil.nextInt(); switch (input) { case 1: return View.BOARD_NOTICE_LOOKUP; case 0: return View.U_HOME; } } return View.BOARD_NOTICE; } public int notice_insert() { //공지사항 작성 System.out.print("제목을 입력하시오> "); String title = ScanUtil.nextLine(); System.out.print("내용을 입력하시오> "); String content = ScanUtil.nextLine(); Map<String, Object> param = new HashMap<>(); param.put("TITLE", title); param.put("CONTENT", content); param.put("USER_NO", Controller.loginUser.get("NUM")); int result = boardDao.insertBoard(param); if(0 < result) { System.out.println("등록되었습니다."); } else { System.out.println("등록되지 않았습니다."); } return View.BOARD_NOTICE; } public static int no; //조회한 게시글 번호 저장 public int notice_lookup() { //공지사항 게시글 조회 System.out.print("게시글 번호> "); no = ScanUtil.nextInt(); Map<String, Object> boardNo = boardDao.notice_lookup(); System.out.println("=================[공지]==================="); System.out.println("번호\t" + boardNo.get("NO") + "\t"); System.out.println("작성자\t" + boardNo.get("NAME") + "\t"); System.out.println("작성일\t" + boardNo.get("N_DATE") + "\t"); System.out.println("제목\t" + boardNo.get("TITLE") + "\t"); System.out.println("내용\t" + boardNo.get("CONTENT") + "\t"); System.out.println("========================================="); if(Controller.type == 0) { System.out.println("1.수정\t2.삭제\t0.뒤로가기"); int input = ScanUtil.nextInt(); switch (input) { case 1: return View.BOARD_NOTICE_UPDATE; case 2: return View.BOARD_NOTICE_DELETE; case 0: return View.BOARD_NOTICE; } } else if(Controller.type == 1) { System.out.println("0.뒤로가기"); int input = ScanUtil.nextInt(); switch(input) { case 0: return View.BOARD_NOTICE; } } return View.BOARD_NOTICE_LOOKUP; } public int notice_delete() { //공지사항 삭제 int result = boardDao.notice_delete(); if(0 < result) { System.out.println("삭제되었습니다."); } else { System.out.println("삭제되지 않았습니다."); } return View.BOARD_NOTICE; } public int notice_update() { //공지사항 수정 System.out.print("제목을 입력하시오.> "); String title = ScanUtil.nextLine(); System.out.print("내용을 입력하시오.> "); String content = ScanUtil.nextLine(); Map<String , Object> param = new HashMap<>(); param.put("TITLE", title); param.put("CONTENT", content); int result = boardDao.notice_update(param); if(0 < result) { System.out.println("수정되었습니다."); } else { System.out.println("수정되지 않았습니다."); } return View.BOARD_NOTICE; } public int review_view() { //리뷰 목록 조회 List<Map<String, Object>> boardList = boardDao.selectReviewList(); System.out.println("================[리뷰]================="); System.out.println("번호\t제목\t작성자\t별점"); System.out.println("--------------------------------------"); for(int i = 0; i < boardList.size(); i++) { System.out.print(boardList.get(i).get("NO") + "\t" + boardList.get(i).get("TITLE") + "\t" + boardList.get(i).get("NAME") + "\t"); for(int j = 1; j <= Integer.parseInt(boardList.get(i).get("SCORE").toString()); j++ ) { System.out.print("★"); } System.out.println(); } System.out.println("======================================"); if(Controller.type == 0) { System.out.println("1.조회\t0.뒤로가기"); int input = ScanUtil.nextInt(); switch (input) { case 1: return View.BOARD_REVIEW_LOOKUP; case 0: return View.M_HOME; } } else if(Controller.type == 1) { System.out.println("1.조회\t2.등록\t0.뒤로가기"); int input = ScanUtil.nextInt(); switch(input) { case 1: return View.BOARD_REVIEW_LOOKUP; case 2: return View.BOARD_REVIEW_ADD; case 0: return View.U_HOME; } } return View.BOARD_REVIEW; } public int review_lookup() { //리뷰 게시글 조회 System.out.print("게시글 번호> "); no = ScanUtil.nextInt(); Map<String, Object> boardNo = boardDao.review_lookup(); System.out.println("=================[리뷰]==================="); System.out.println("번호\t" + boardNo.get("NO") + "\t"); System.out.println("작성자\t" + boardNo.get("NAME") + "\t"); System.out.println("작성일\t" + boardNo.get("R_DATE") + "\t"); System.out.print("별점\t"); for(int i = 1; i <= Integer.parseInt(boardNo.get("SCORE").toString()); i++ ) { System.out.print("★"); } System.out.println(); System.out.println("제목\t" + boardNo.get("TITLE") + "\t"); System.out.println("내용\t" + boardNo.get("CONTENT") + "\t"); System.out.println("========================================="); if(Controller.type == 0) { System.out.println("0.뒤로가기"); int input = ScanUtil.nextInt(); switch (input) { case 0: return View.BOARD_REVIEW; } } else if(Controller.type == 1) { if(Integer.parseInt(Controller.loginUser.get("NUM").toString()) == Integer.parseInt(boardNo.get("USER_NO").toString())) { System.out.println("1.수정\t2.삭제\t0.뒤로가기"); int input = ScanUtil.nextInt(); switch (input) { case 1: return View.BOARD_REVIEW_UPDATE; case 2: return View.BOARD_REVIEW_DELETE; case 0: return View.BOARD_REVIEW; } } else { System.out.println("0.뒤로가기"); int input = ScanUtil.nextInt(); switch (input) { case 0: return View.BOARD_REVIEW; } } } return View.BOARD_REVIEW_LOOKUP; } public int review_insert() { //리뷰 작성 System.out.print("제목을 입력하시오.> "); String title = ScanUtil.nextLine(); System.out.print("내용을 입력하시오.> "); String content = ScanUtil.nextLine(); System.out.println("5점 만점입니다."); System.out.print("별점을 입력하시오.> "); int score = ScanUtil.nextInt(); while(true) { if(score > 5 || score < 1) { System.out.println("평점은 1 ~ 5점으로 입력해야합니다."); score = ScanUtil.nextInt(); } else { break; } } Map<String, Object> param = new HashMap<>(); param.put("TITLE", title); param.put("CONTENT", content); param.put("SCORE", score); param.put("USER_NO", Controller.loginUser.get("NUM")); int result = boardDao.insertreview(param); if(result > 0) { System.out.println("등록되었습니다."); } else { System.out.println("등록되지 않았습니다."); } return View.BOARD_REVIEW; } public int review_delete() { //리뷰 삭제 int result = boardDao.review_delete(); if(0 < result) { System.out.println("삭제되었습니다."); } else { System.out.println("삭제되지 않았습니다."); } return View.BOARD_REVIEW; } public int review_update() { //리뷰 수정 System.out.print("제목을 입력하시오.> "); String title = ScanUtil.nextLine(); System.out.print("내용을 입력하시오.> "); String content = ScanUtil.nextLine(); System.out.print("별점을 입력하시오.> "); int score = ScanUtil.nextInt(); Map<String , Object> param = new HashMap<>(); param.put("TITLE", title); param.put("CONTENT", content); param.put("SCORE", score); int result = boardDao.review_update(param); if(0 < result) { System.out.println("수정되었습니다."); } else { System.out.println("수정되지 않았습니다."); } return View.BOARD_REVIEW; } }
528c322dbeec93f02727840bdc30621e38c4840e
[ "Java" ]
5
Java
YooDongGi/java_firstproject
649b985f63704d42465cfe9ff22ccd39498f22bf
d90d0f0bd23d0a2277aaa239d9e9ac2b5fb737c9
refs/heads/master
<repo_name>anushachandrappa/Classic-Arcade-Game<file_sep>/js/app.js // adds winning text when game is won var winBox = document.querySelector(".win-text"); // HTML text template to add when winning the game var winHTML = `<h3>You Made It!</h3> <p>Play Again?</p> <button id="reload" name="replay" type="button">Start</button>`; // Enemies our player must avoid var Enemy = function(x, y, speed) { // Variables applied to each of our instances go here, // we've provided one for you to get started this.x = x; this.y = y; this.speed = speed; // The image/sprite for our enemies, this uses // a helper we've provided to easily load images this.sprite = 'images/enemy-bug.png'; }; // Update the enemy's position, required method for game // Parameter: dt, a time delta between ticks Enemy.prototype.update = function(dt) { // You should multiply any movement by the dt parameter // which will ensure the game runs at the same speed for // all computers. this.x += this.speed * dt; if (this.x > 550) { this.x = 0; this.speed = 100 + Math.floor(Math.random() * 512); } //check for collisions between enemies and player if (player.x < this.x + 650 && player.x + 37 > this.x && player.y < this.y + 25 && 30 + player.y > this.y) { player.x = 200; player.y = 380; } }; // Draw the enemy on the screen, required method for game Enemy.prototype.render = function() { ctx.drawImage(Resources.get(this.sprite), this.x, this.y); // a handleInput() method. }; // Now write your own player class // This class requires an update(), render() and // a handleInput() method. var Player = function(x, y, speed) { this.x = x; this.y = y; this.speed = speed; this.sprite = 'images/char-boy.png'; } Player.prototype.update = function() { if (this.y > 380) { this.y = 380; } if (this.x > 400) { this.x = 400; } if (this.x < 0) { this.x = 0; } /*if(this.y<0){ this.x=200; this.y=380; }*/ player.playerWin(); }; // method that takes action when player wins Player.prototype.playerWin = function() { if (this.y < 0) { allEnemies = []; this.x = 200; this.y = 380; winBox.innerHTML = winHTML; // variable for the reset button var resetButton = document.querySelector("#reload"); // Event listener for the reset button resetButton.addEventListener('click', reset, true); } else { return; } } // function to reset the game function reset() { window.location.reload(true); } Player.prototype.render = function() { ctx.drawImage(Resources.get(this.sprite), this.x, this.y); } Player.prototype.handleInput = function(keypress) { switch (keypress) { case 'left': this.x -= this.speed + 50; break; case 'up': this.y -= this.speed + 30; break; case 'right': this.x += this.speed + 50; break; case 'down': this.y += this.speed + 30; break; } }; // Now instantiate your objects. // Place all enemy objects in an array called allEnemies // Place the player object in a variable called player var allEnemies = []; var enemyPosition = [60, 140, 220]; var player = new Player(200, 380, 50); var enemy; enemyPosition.forEach(function(posY) { enemy = new Enemy(0, posY, 100 + Math.floor(Math.random() * 512)); allEnemies.push(enemy); }); // This listens for key presses and sends the keys to your // Player.handleInput() method. You don't need to modify this. document.addEventListener('keyup', function(e) { var allowedKeys = { 37: 'left', 38: 'up', 39: 'right', 40: 'down' }; player.handleInput(allowedKeys[e.keyCode]); });
bc2eff88ac10b6276aca2174f1d654db346195de
[ "JavaScript" ]
1
JavaScript
anushachandrappa/Classic-Arcade-Game
64175e4de211dc7bc66ea56da54d0e7f622ae6a6
7192162d753d707f9c22010b7c75241d456d6191
refs/heads/master
<repo_name>Aries0331/CMPUT404Lab2<file_sep>/client.py #!/usr/bin/env python import socket clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # AF_INET means we want an Ipv4 socket # SOCK_STREAM means we want a TCP socket # connect clientSocket.connect(("www.google.com", 80)) # 80:port (()): c API request = "GET / HTTP/1.0\r\n\r\n" # \r\n indicate the end of the header # send request clientSocket.sendall(request) # get respond back from google response = bytearray() while True: part = clientSocket.recv(1024) if(part): response.extend(part) #print 'aaaaaaaaaaaaaaa' #print part else: break print response # same output as tying curl -i www.google.com ''' HTTP/1.0 302 Found Cache-Control: private Content-Type: text/html; charset=UTF-8 Location: http://www.google.ca/?gfe_rd=cr&ei=Y2-BWKbeNube8Afz54jwCw Content-Length: 258 Date: Fri, 20 Jan 2017 02:01:07 GMT <HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"> <TITLE>302 Moved</TITLE></HEAD><BODY> <H1>302 Moved</H1> The document has moved <A HREF="http://www.google.ca/?gfe_rd=cr&amp;ei=Y2-BWKbeNube8Afz54jwCw">here</A>. </BODY></HTML> '''
f21463f2ac250938a5cd9645d9420a0b12800d6b
[ "Python" ]
1
Python
Aries0331/CMPUT404Lab2
8575e03646cadd2dd5c1e88b9e13c4b95626e484
0be34631b83f0f816a2ba95ff491f298abce0d78
refs/heads/master
<repo_name>MogamiTsuchikawa/NovelGameManager<file_sep>/test-code/getchu_get.py import os import time import urllib.error import urllib.request from bs4 import BeautifulSoup from urllib import request import requests import json from datetime import datetime as dt import firebase_admin from firebase_admin import credentials from firebase_admin import firestore from google.cloud import storage FIREBASE_STORAGE_BUCKET = 'home-data-store-994e9.appspot.com' GOOGLE_APPLICATION_CREDENTIALS = os.environ["GOOGLE_APPLICATION_CREDENTIALS"] cred = credentials.Certificate(GOOGLE_APPLICATION_CREDENTIALS) # ダウンロードした秘密鍵 firebase_admin.initialize_app(cred,{'storageBucket':FIREBASE_STORAGE_BUCKET }) #bucket = storage.bucket() cookie = {'getchu_adalt_flag': 'getchu.com'} def download_file(url, dst_path,session,ITEM_HISTORY): dummy_user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0' try: cookie = {'getchu_adalt_flag': 'getchu.com','ITEM_HISTORY':ITEM_HISTORY} response = session.get(url, cookies=cookie, allow_redirects=False, timeout=10, headers={"User-Agent": dummy_user_agent,"Referer":"http://www.getchu.com/soft.phtml?id="+ITEM_HISTORY}) print(response.status_code) if response.status_code != 200: e = Exception("HTTP status: " + str(response.status_code)) raise e content_type = response.headers["content-type"] if 'image' not in content_type: e = Exception("Content-Type: " + content_type) raise e with open(dst_path, "wb") as fout: fout.write(response.content) except urllib.error.URLError as e: print(e) def save_json(erg): f = open('data.json', 'r') json_dict = json.load(f) f.close() json_dict.append(erg) json_str = json.dumps(json_dict) w = open('data.json','w') w.write(json_str) w.close() def get_erg_data(jan_code): session = requests.session() url = 'http://www.getchu.com/php/search.phtml?search_keyword={0}&list_count=30&sort=sales&sort2=down&search_title=&search_brand=&search_person=&search_jan=&search_isbn=&genre=all&start_date=&end_date=&age=&list_type=list&search=search'.format(jan_code) html = session.get(url, cookies=cookie).content soup = BeautifulSoup(html) #print(soup) gethu_item_id = soup.find('div',class_='package').find('a')['href'].split('=')[1] print('げっちゅうやID:'+gethu_item_id) response = session.get('http://www.getchu.com/soft.phtml?id='+gethu_item_id, cookies=cookie) html = response.content ITEM_HISTORY = response.cookies.get('ITEM_HISTORY') print("####"+ITEM_HISTORY) soup = BeautifulSoup(html) erg_title = soup.find('h1').get_text().replace('\n','').replace('(このタイトルの関連商品)','').strip() print(erg_title) erg_maker = soup.find('a',class_='glance').get_text() erg_maker_url = soup.find('a',class_='glance')['href'] erg_pubdate = soup.find('a',{'title':'同じ発売日の同ジャンル商品を開く'}).get_text() img_url = 'http://www.getchu.com/brandnew/{0}/c{1}package.jpg'.format(gethu_item_id,gethu_item_id) download_file(img_url,'img/{0}.jpg'.format(jan_code),session,ITEM_HISTORY) erg = {'title':erg_title,'maker':erg_maker,'makerUrl':erg_maker_url,'pubDate':dt.strptime(erg_pubdate,'%Y/%m/%d'),'janCode':jan_code} return erg def upload_blob(source_file_name, destination_blob_name): storage_client = storage.Client() bucket = storage_client.bucket(FIREBASE_STORAGE_BUCKET) blob = bucket.blob(destination_blob_name) blob.upload_from_filename(source_file_name) print( "File {} uploaded to {}.".format( source_file_name, destination_blob_name ) ) def main(): erg = get_erg_data(input()) db = firestore.client() if len(db.collection('erg').where('janCode','==',erg['janCode']).get()) != 0: return response = db.collection('erg').add(erg) print(response) upload_blob('img/'+erg['janCode']+'.jpg','erg_img/'+erg['janCode']+'.jpg') main()<file_sep>/test-code/requirements.txt BeautifulSoup4 firebase-admin google-cloud-storage
660716f2b1fcf6a9c852f097d8870dfdaf2dd84e
[ "Python", "Text" ]
2
Python
MogamiTsuchikawa/NovelGameManager
1e0491f54653760f452167c608cb6d70a7176c56
239ac7f6525bf1fc2f4845fd01ac52ecff0b3679
refs/heads/master
<repo_name>amakhno/NodeSelfEduaction<file_sep>/1st chapter/OOP/test.js var alert = ((msg) => console.log(msg)); //------------------------1 function func1 (greetings) { return function func2 (name) { alert(greetings + " " + name); }; } var russian = func1("Привет"); russian("Артем"); //------------------------2 function counter (n) { var n1 = n; return function subFunction () { alert(++n1); }; } var ct = counter(2); ct(); ct(); ct(); //------------------------3 var outerVal = 4; var handle; function outerFunction () { var innerVal = 5; function innerFunction () { alert(outerVal); alert(innerVal); } handle = innerFunction; } alert("Переназначение указателя"); outerFunction(); alert("Переназначение указателя завершено"); handle(); //------------------------4 alert("\nПрожка 4"); function funcBuilder (prod) { return function func3 (x) { return prod * x; }; } var doubleF = funcBuilder(2); var tripleF = funcBuilder(3); alert(doubleF(2)); alert(tripleF(2)); //------------------------5 alert("\nПрожка 5"); function counter1 () { var count1 = 0; this.GetCount = function () { return count1; }; this.SetCount = function (value) { count1 = value; }; this.Implement = function () { count1++; }; } var a = new counter1(); alert(a.GetCount()); a.SetCount(5); alert(a.GetCount()); alert(a.count1); //------------------------6 alert("\nПрожка 6"); <file_sep>/start.js var tid; function toConsole (n) { console.log(n); tid = setTimeout(toConsole, 1000, n+1); if (n > 5) { clearTimeout(tid); } } toConsole(0);<file_sep>/jQuery/Примеры/_js/runnow.js var luckyNumber = prompt("Какое ваше счастливое число?", ""); if (luckyNumber == 7) { document.write("<p>Эй, 7 - это и мое счастливое число!</p>"); }<file_sep>/1st chapter/OOP/test2.js //------------------------5 console.log("\nПрожка 5"); function counter1 () { var count1 = 0; function SetCount (value) { count1 = value; } return { safeSetCount: function (n) { if (n != 13) { SetCount(n); } else { console.log("bad number!"); } }, getCount: function () { return count1; }, incrCount: function () { count1 ++; }, }; } var counterZ = counter1(); counterZ.safeSetCount(5); console.log(counterZ.getCount()); counterZ.safeSetCount(13); counterZ.incrCount(13); console.log(counterZ.getCount());<file_sep>/1st chapter/start.js /*var http = require("http"); var server = http.createServer(function (request, response) { response.writeHead(200, {"ContentType": "text/html", } ); response.write("<h2>Hello</h2> "); response.write("<h1>Hello</h1>"); response.end(); }); server.listen(8000);*/ var fs = require("fs"); var url = require("url"); var path = require("path"); var mimeType = { ".js": "text/javascript", ".html": "text/html", ".gif": "image/gif", ".css": "text/css", ".jpg": "text/jpeg", ".ico": "image/x-icon", }; /*var httpServer = require("http").createServer(function onRequest (req, res) { var pathName = url.parse(req.url).path; if (pathName == "/") { pathName = "/index.html"; } pathName = pathName.substring(1, pathName.length); console.log("Получен запрос: " + pathName); fs.readFile(pathName, "utf8", function (err, data) { if (err) { console.log("Could not find or open file " + pathName + " for reading\n"); res.end(); } else { res.writeHead(200, {"ContentType": mimeType[path.extname(pathName)],} ); res.write(data); res.end(); } }); });*/ var httpServer = require("http").createServer(function (req, res) { var pathName = url.parse(req.url).path; if (pathName == "/") { pathName = "/index.html"; } var extname = path.extname(pathName); var mimeTypeNow = mimeType[extname]; if ( (extname == ".gif") || (extname == ".jpg") || (extname == ".ico")) { var imageExits = fs.existsSync("./" + pathName); if (imageExits) { //var img = fs.readFileSync("./" + pathName); fs.readFile("./" + pathName, function (err, data) { if (err) { res.end(); } else { res.end(data, "binary"); } }) console.log(pathName + " " + mimeTypeNow); res.writeHead(200, {"ContentType": mimeTypeNow,}); //res.end(img, "binary"); } else { console.log("Image no found! (" + pathName + ")"); res.end(); } } else { fs.readFile("./" + pathName, {encoding: "utf8", }, function (err, data) { if (err) { console.log("Could not find or open file " + pathName + " for reading\n"); res.end(); } else { console.log(pathName + " " + mimeTypeNow); res.writeHead(200, {"ContentType": mimeTypeNow,}); res.end(data); } }); } }); httpServer.listen(8000);<file_sep>/2nd chapter/1.js process.stdin.setEncoding("utf8"); process.stdin.resume(); console.log("PID: %d", process.pid); process.on("SIGHUP", function () { console.log("Got a SIGHUP"); process.kill(process.pid); });<file_sep>/README.md # NodeSelfEduaction Рассматриваю примеры из учебника <file_sep>/2nd chapter/buf/start.js var buf1 = new Buffer(24); var buf2 = new Buffer(16); for (var i = 0; i<24; i+=4) { buf1[i] = 78; buf1[i+1] = 111; buf1[i+2] = 100; buf1[i+3] = 101; } for (var j = 0; j<16; j++) { buf2[j] = 42; } buf1.copy(buf2, 6, 16, 20); console.log(buf2.toString("ASCII")); var buf3; buf3 = buf2.slice(0, 3); console.log(buf3.toString("ASCII", 0, buf3.lenght)); buf3[0] = 33; console.log(buf2.toString("ASCII", 0, buf2.lenght));<file_sep>/1st chapter/OOP/test1.js /*var User = function (id, name) { this.id = id; this.name = name; }; User.prototype.SayHello = function () { console.log("Hello " + this.name); }; var Admin = function () {}; var admin = new Admin(); Admin.prototype.SayHello = User.prototype.SayHello; console.log(admin instanceof Admin); console.log(admin instanceof User);*/ //---------------------------------Class example---------------------------------// var User = function (id, name) { this.id = id; this.name = name; }; User.prototype.SayHello = function () { console.log("Hello " + this.name); }; var Admin = function () {}; Admin.prototype = new User(); var admin = new Admin(); admin.name = "Ian"; admin.id = 56; admin.SayHello(); console.log (admin instanceof User); console.log (admin instanceof Admin); Admin.prototype.SayHi = function () { console.log("Hi " + this.name); }; var usr = new User(14, "UserName"); //usr.SayHi(); usr.SayHi is not a function admin.SayHi();
3ec3ba763478529c244b9145ff7a945ebf9ab05b
[ "JavaScript", "Markdown" ]
9
JavaScript
amakhno/NodeSelfEduaction
2661d7c81af26cbfa1d74289e1ab2b74f1b01368
20617e0bcc9c8661027c10411c5c7c040adfb9b1
refs/heads/main
<file_sep>const counters = document.querySelectorAll('.counter'); counters.forEach((counter) => { counter.innerText = '0'; const increaseCounter = () => { const target = +counter.getAttribute('data-target'); const innerText = +counter.innerText; const increment = target / 1000; if (innerText < target) { counter.innerText = `${Math.ceil(innerText + increment)}`; setTimeout(increaseCounter, 1); } else { counter.innerText = target; } }; increaseCounter(); }); <file_sep># 50Projects50Days This #50Projects50Days challenge is based on the ["50 Projects In 50 Days - HTML, CSS & JavaScript"](https://www.udemy.com/course/50-projects-50-days/) Udemy course. [Challenge Website](https://geraldelorm.github.io/50projects50days/) | # | Project | Live Demo | | :-: | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | 01 | Expanding Cards [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-01-expanding-cards) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-01-expanding-cards/index.html) | | 02 | Progress Steps [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-02-progress-steps) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-02-progress-steps/index.html) | | 03 | Rotating Navigation Animation [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-03-rotating-navigation) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-03-rotating-navigation/index.html) | | 04 | Hidden Search widget [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-04-hidden-search-widget) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-04-hidden-search-widget/index.html) | | 05 | Blurry Loading [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-05-blurry-loading) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-05-blurry-loading/index.html) | | 06 | Scroll Animation [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-06-scroll-animation) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-06-scroll-animation/index.html) | | 07 | Split Landing Page [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-7-split-landing-page) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-7-split-landing-page/index.html) | | 08 | Form Wave Animation [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-08-form-wave-animation) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-08-form-wave-animation/index.html) | | 09 | Sound Board [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-09-sound-board) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-09-sound-board/index.html) | | 10 | Dad Jokes [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-10-dad-jokes) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-10-dad-jokes/index.html) | | 11 | Event KeyCode [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-11-event-keycodes) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-11-event-keycodes/index.html) | | 12 | FAQ collapse [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-12-faq-collapse) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-12-faq-collapse/index.html) | | 13 | Random choice picker [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-13-random-choice-picker) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-13-random-choice-picker/index.html) | | 14 | Animated Navigation [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-14-animated-navigation) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-14-animated-navigation/index.html) | | 15 | Incrementing Counter [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-15-incrementing-counter) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-15-incrementing-counter/index.html) | | 16 | Drink Water App [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-16-drink-water) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-16-drink-water/index.html) | | 17 | Movie App [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-17-movie-app) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-17-movie-app/index.html) | | 18 | Background Slider [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-18-background-slider) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-18-background-slider/index.html) | | 19 | Clock App [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-19-theme-clock) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-19-theme-clock/index.html) | | 20 | Button Ripple Effect [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-20-ripple-effect) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-20-ripple-effect/index.html) | | 21 | Drag N Drop [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-21-drag-drop) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-21-drag-drop/index.html) | | 22 | Drawing App [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-22-drawing-app) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-22-drawing-app/index.html) | | 23 | Kinetic CSS Loader [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-23-kinetic-loader) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-23-kinetic-loader/index.html) | | 24 | Content Placeholder [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-24-content-placeholder) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-24-content-placeholder/index.html) | | 25 | Sticky Navbar [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-25-sticky-navbar) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-25-sticky-navbar/index.html) | | 26 | Double Vertical Slider [(Code)](https://github.com/geraldelorm/50projects50days/tree/main/Day-26-double-vertical-slider) | [Live Demo](https://geraldelorm.github.io/50projects50days/Day-26-double-vertical-slider/index.html) |
bd2d0e73f3b5d4e34e9bd51f230288d801d229f6
[ "JavaScript", "Markdown" ]
2
JavaScript
geraldelorm/50projects50days
826ee7873b9dd9dc7d9c34dc7943ef04923b1960
f90e1a8759a5fdd1c31ea9dfa09abb547b6fe8c0
refs/heads/master
<file_sep>/** @author <NAME> Set up the basic server (http) Set up Sockets (io) Set up the file system (fs) */ var app = require('http').createServer(handler), io = require('socket.io').listen(app), fs = require('fs'); /** Figure out the port or fall back to 1337 */ var port = process.env.PORT || 1337; /** Start the server */ app.listen(port, function() { console.log('App listening on http://localhost:' + port); }); // === FOR AZURE WEB === /** Azure websites doesn't support websockets yet, so we force Sockets.IO to use Long-polling */ io.configure(function () { io.set('transports', ['xhr-polling']); }); //======= /** The main application handler */ function handler(req, res) { // If the request is the html file or the root // serve the index.html file if (req.url.indexOf('.html') != -1 || req.url === '/') { fs.readFile(__dirname + '/index.html', function(err, data) { if (err) { res.writeHead(500); return res.end('Error loading index.html'); } res.writeHead(200); res.end(data); }); } // If the request is for a JavaScript file // server the client.js file if (req.url.indexOf('.js') != -1) { fs.readFile(__dirname + '/client.js', function(err, data) { if (err) { res.writeHead(500); return res.end('Error loading client.js'); } res.writeHead(200, { 'Content-Type': 'text/javascript' }); res.end(data); }); } // If the request is for a CSS file // server the style.css file if (req.url.indexOf('.css') != -1) { fs.readFile(__dirname + '/style.css', function(err, data) { if (err) { res.writeHead(500); return res.end('Error loading client.js'); } res.writeHead(200, { 'Content-Type': 'text/css' }); res.end(data); }); } } /** Setup sockets When Socket.IO has started */ io.sockets.on('connection', function(socket) { // .. emit a welcome message to the client // which is connecting socket.emit('message', { message: "Welcome to the chatroom" }); // Listen for incoming messages from clients socket.on('send', function(data) { // Remove any tags from the message sent by the client // Nooo..we don't trust them, this is a server goddammit! // ..and you should do more work here if your going to use this!! data.message = data.message.replace(/(<([^>]+)>)/ig,""); // Send the message back to ALL connected clients io.sockets.emit('message', data); }); }); <file_sep># Node.js / Socket.IO demo # This is a basic demo of how to use [Socket.IO](http://socket.io/ "Socket.IO") to create a basic live chatroom. This demo also includes: * Some extra code on how to make this work on Windows Azure * A demo of how to load and use external JavaScript files on the client side
d9dfc2e57f7942fe5a9902a04392b73d97187e9b
[ "JavaScript", "Markdown" ]
2
JavaScript
jornki/socketTest
1640ff1c332a3750260d270a03e2d8e1109aee2d
af0bc75acde7c0456d1f389ee0808627c9c7cc44
refs/heads/master
<repo_name>matveyclark/hogwarts-london-web-111819<file_sep>/src/components/HogList.js import React from 'react'; import hogs from '../porkers_data'; import HogCard from './HogCard' export default class HogList extends React.Component { state = { hogs: hogs } renderHogs = () => { return this.state.hogs.map( hog => <HogCard details={hog} filterHogs={this.filterHogs} hogs={this.state.hogs} renderHogs={this.renderHogs} />) } filterHogs = (hog) => { this.setState({ hogs: this.state.hogs.filter( element => element === hog ) }) } filterGreasedHogs = (e) => { if(e.target.value === 'greased') { this.setState({ hogs: [ ...this.state.hogs.filter( hog => hog.greased === true) ] }) } if(e.target.value === 'all') { this.setState({ hogs: hogs }) } } filterHogsByName = () => { console.log(this.state) } render() { return( <div> <button onClick={this.filterHogsByName}>Sort by name</button> <button>Sort by weight</button> <select onChange={this.filterGreasedHogs}> <option>all</option> <option>greased</option> </select> {this.renderHogs()} </div> ) } }
1b4374857b9172b983a9da20340782a416308af9
[ "JavaScript" ]
1
JavaScript
matveyclark/hogwarts-london-web-111819
27eed5304809292b600058109c8e4cb5534dd9df
62147113e871287ca87d309e27df4c51425221a8
refs/heads/master
<repo_name>Polygonschmiede/bachelor<file_sep>/index.php <?php echo "HPups";
821715e312d3c5690e41286e617dfcc138466246
[ "PHP" ]
1
PHP
Polygonschmiede/bachelor
bfe7013f3f808a9a9d1fecadc0c44e2a20a0b34e
2bda06cb51b8a78617dcafe4d822d768a14c2431
refs/heads/master
<repo_name>sidd36/ORAM<file_sep>/src/pyoram/crypto/keyfile.py __all__ = ('KeyFile') import json import data from pyoram import utils from pyoram.exceptions import ErrorInKeyMap JSON_SALT = 'salt' JSON_WAES_KEY = 'waes_key' JSON_WMAC_KEY = 'wmac_key' class KeyFile(object): def __init__(self, salt, waes_key, wmac_key): self.salt = salt self.waes_key = waes_key self.wmac_key = wmac_key def save_to_file(self): with data.open_data_file(utils.KEY_MAP_FILE_NAME, utils.WRITE_MODE) as key_map: salt = utils.byte_to_str(self.salt) waes_key = utils.byte_to_str(self.waes_key) wmac_key = utils.byte_to_str(self.wmac_key) json.dump({JSON_SALT: salt, JSON_WAES_KEY: waes_key, JSON_WMAC_KEY: wmac_key}, key_map, indent=2, sort_keys=True) @classmethod def load_from_file(cls): with data.open_data_file(utils.KEY_MAP_FILE_NAME, utils.READ_MODE) as key_map: try: json_key_map = json.load(key_map) salt = utils.str_to_byte(json_key_map[JSON_SALT]) waes_key = utils.str_to_byte(json_key_map[JSON_WAES_KEY]) wmac_key = utils.str_to_byte(json_key_map[JSON_WMAC_KEY]) key_file = KeyFile(salt, waes_key, wmac_key) return key_file except(ValueError, KeyError): raise ErrorInKeyMap('key.map might be empty or the data is not a valid JSON format.') @classmethod def verify_content(cls): try: cls.load_from_file() return True except ErrorInKeyMap: return False <file_sep>/src/pyoram/core/__init__.py import pyoram.core.chunk_file import pyoram.core.cloud import pyoram.core.config import pyoram.core.map import pyoram.core.oram import pyoram.core.stash <file_sep>/src/pyoram/crypto/__init__.py import pyoram.crypto.aes_crypto import pyoram.crypto.keyfile<file_sep>/src/pyoram/__init__.py import pyoram.controller import pyoram.exceptions import pyoram.log import pyoram.main import pyoram.ui import pyoram.utils <file_sep>/src/pyoram/core/cloud.py __all__ = ('Cloud') import json import os import dropbox import data from pyoram import utils, log from pyoram.core import config from pyoram.exceptions import ErrorInCloudMap, CloudTokenError logger = log.get_logger(__name__) JSON_TOKEN = 'token' JSON_INIT = 'init' TOKEN_PLACEHOLDER = 'My token' FOLDER_NAME = 'data' FILE_NAME = 'block%d.oram' RANDOM_BYTE_FACTOR = 0.74 RESPONSE_CODE_OK = 200 class Cloud: def __init__(self, aes_crypto): if not data.file_exists(utils.CLOUD_MAP_FILE_NAME): logger.info('Create cloud map') self.create_cloud_map() cloud_map = self.load_cloud_map() self.aes_crypto = aes_crypto self.token = cloud_map[0] self.cloud_init = cloud_map[1] self.dbx = self.get_dropbox_access(self.token) def create_cloud_map(self): with data.open_data_file(utils.CLOUD_MAP_FILE_NAME, utils.WRITE_MODE) as cloud_map: json.dump({JSON_TOKEN: TOKEN_PLACEHOLDER, JSON_INIT: False}, cloud_map, indent=2) def load_cloud_map(self): with data.open_data_file(utils.CLOUD_MAP_FILE_NAME, utils.READ_MODE) as cloud_map: try: cloud_data = json.load(cloud_map) return cloud_data[JSON_TOKEN], cloud_data[JSON_INIT] except(ValueError, KeyError): logger.warning('Error in cloud map.') raise ErrorInCloudMap('Error in cloud map.') def update_cloud_map(self): with data.open_data_file(utils.CLOUD_MAP_FILE_NAME, utils.READ_WRITE_MODE) as cloud_map: cloud_data = json.load(cloud_map) cloud_data[JSON_INIT] = self.cloud_init cloud_map.seek(0) json.dump(cloud_data, cloud_map, indent=2) cloud_map.truncate() def get_dropbox_access(self, dropbox_token): """ Call Dropbox api to gain access to the api :param dropbox_token: to make api calls to dropbox :return: dropbox instance """ return dropbox.Dropbox(dropbox_token) def create_folder(self): """ Call Dropbox api to create a folder """ self.dbx.files_create_folder(self.get_path_to_folder()) def delete_folder(self): """ Call Dropbox api to delete a folder and the content """ try: self.dbx.files_delete(self.get_path_to_folder()) logger.info('delete cloud folder and all content') except dropbox.exceptions.ApiError: logger.info('cloud folder does not exist') pass def file_upload(self, content, block): """ Call Dropbox api to upload a file :param content: to be uploaded to dropbox :param block: number to identify the name of the file """ try: self.dbx.files_upload(content, self.get_path_to_file(block), mode=dropbox.files.WriteMode.overwrite) except dropbox.exceptions.BadInputError: raise CloudTokenError('Please provide your token.') def file_download(self, block): """ Call Dropbox api to download a file :param block: number to identify the name of the file :return: response token is a tuple of: dropbox.files.FileMetadata, requests.models.Response """ return self.dbx.files_download(self.get_path_to_file(block)) def get_path_to_folder(self): return '/%s' % FOLDER_NAME def get_path_to_file(self, node): return self.get_path_to_folder() + '/' + FILE_NAME % node def setup_cloud(self, max_block_size): if not self.cloud_init: self.delete_folder() self.create_folder() logger.info('start setup of the cloud with a total of %d blocks' % max_block_size) for block in range(0, max_block_size): logger.info('upload file %d' % block) self.file_upload(self.create_dummy_data(), block) logger.info('end setup of the cloud') self.cloud_init = True self.update_cloud_map() def create_dummy_data(self): dummy_id = config.DUMMY_ID dummy_data = os.urandom(config.BLOCK_SIZE) return self.aes_crypto.encrypt(dummy_data, dummy_id) def download_node(self, node): response_token = self.file_download(node) # Response model carries the content response = response_token[1] if response.status_code == RESPONSE_CODE_OK: return response.content return None def upload_to_node(self, node, content=None): if content is None: content = self.create_dummy_data() self.file_upload(content, node) <file_sep>/src/pyoram/core/config.py import math import random from enum import Enum # Block size of the chunk files in terms of bytes BLOCK_SIZE = 10000 # The height of the binary tree (as integer) ORAM_LEVEL = 5 # The height of the binary tree (as integer) LEAF_MIN = int(math.pow(2, ORAM_LEVEL) - 1) LEAF_MAX = int(math.pow(2, ORAM_LEVEL + 1) - 2) # dummy data id DUMMY_ID = 999999999999999 # for packing the data id FORMAT_CHAR = '>Q' def get_random_leaf_id(): return random.randrange(LEAF_MIN, LEAF_MAX + 1) class DataType(Enum): kB = 1000 MB = 1000000 GB = 1000000000 TB = 1000000000000 def get_name(self): return self.name def get_value(self): return self.value def get_format(storage): data_type_name = None data_type_value = None if storage <= DataType.MB.get_value(): data_type_name = DataType.kB.get_name() data_type_value = DataType.kB.get_value() elif storage < DataType.GB.get_value(): data_type_name = DataType.MB.get_name() data_type_value = DataType.MB.get_value() elif storage < DataType.TB.get_value(): data_type_name = DataType.GB.get_name() data_type_value = DataType.GB.get_value() elif storage >= DataType.TB.get_value(): data_type_name = DataType.TB.get_name() data_type_value = DataType.TB.get_value() return data_type_name, data_type_value <file_sep>/data/__init__.py import os from pyoram import utils import data base_dir = os.path.dirname(__file__) stash_dir = os.path.join(base_dir, utils.STASH_FOLDER_NAME) def open_data_file(filename, mode): return open(os.path.join(base_dir, filename), mode) def open_data_file_in_stash(filename, mode): return open(os.path.join(stash_dir, filename), mode) def is_file_in_stash(filename): return os.path.isfile(os.path.join(stash_dir, filename)) def delete_file_in_stash(filename): if os.path.isfile(os.path.join(stash_dir, filename)): os.remove(os.path.join(stash_dir, filename)) def get_file_names_from_stash(): return os.listdir(stash_dir) def file_exists(filename): return os.path.isfile(os.path.join(base_dir, filename)) def is_folder(folder_name): return os.path.isdir(os.path.join(base_dir, folder_name)) def create_folder(folder_name): os.makedirs(os.path.join(base_dir, folder_name)) def get_stash_size(): return len([name for name in os.listdir(stash_dir) if os.path.isfile(os.path.join(stash_dir, name))]) def get_log_file_name(): return os.path.join(base_dir, utils.LOG_FILE_NAME) <file_sep>/src/pyoram/core/map.py __all__ = ('FileMap') import json import data from pyoram import utils from pyoram.core import config # file.map JSON_FILES = 'files' JSON_ID_COUNTER = 'counter' JSON_FILE_NAME = 'file_name' JSON_FILE_SIZE = 'file_size' JSON_DATA_ITEMS = 'data_items' # position.map JSON_LEAF_ID = 'leaf_id' JSON_DATA_ID = 'data_id' class FileMap: def __init__(self): if not data.file_exists(utils.FILE_MAP_FILE_NAME): with data.open_data_file(utils.FILE_MAP_FILE_NAME, utils.WRITE_MODE) as file_map: json.dump({JSON_FILES: (), JSON_ID_COUNTER: 0}, file_map, indent=2) def add_file(self, file_name, file_size, data_items, data_id_counter): with data.open_data_file(utils.FILE_MAP_FILE_NAME, utils.READ_WRITE_MODE) as file_map: file_data = json.load(file_map) file_data[JSON_FILES].append( {JSON_FILE_NAME: file_name, JSON_FILE_SIZE: file_size, JSON_DATA_ITEMS: data_items}) # updating the data id counter file_data[JSON_ID_COUNTER] = data_id_counter file_map.seek(0) json.dump(file_data, file_map, indent=2, sort_keys=True) file_map.truncate() def get_files(self): file_names = [] with data.open_data_file(utils.FILE_MAP_FILE_NAME, utils.READ_MODE) as file_map: file_data = json.load(file_map) for file in file_data[JSON_FILES]: file_names.append(file[JSON_FILE_NAME]) return file_names def get_id_counter(self): with data.open_data_file(utils.FILE_MAP_FILE_NAME, utils.READ_MODE) as file_map: file_data = json.load(file_map) return file_data[JSON_ID_COUNTER] def get_data_ids_of_file(self, filename): with data.open_data_file(utils.FILE_MAP_FILE_NAME, utils.READ_MODE) as file_map: file_data = json.load(file_map) for file in file_data[JSON_FILES]: if file[JSON_FILE_NAME] == filename: return file[JSON_DATA_ITEMS] def get_file_len(self, filename): with data.open_data_file(utils.FILE_MAP_FILE_NAME, utils.READ_MODE) as file_map: file_data = json.load(file_map) for file in file_data[JSON_FILES]: if file[JSON_FILE_NAME] == filename: return file[JSON_FILE_SIZE] def delete_file(self, filename): with data.open_data_file(utils.FILE_MAP_FILE_NAME, utils.READ_WRITE_MODE) as file_map: file_data = json.load(file_map) files = file_data[JSON_FILES] for entry in list(files): if entry[JSON_FILE_NAME] == filename: files.remove(entry) break file_map.seek(0) json.dump(file_data, file_map, indent=2, sort_keys=True) file_map.truncate() class PositionMap: def __init__(self): if not data.file_exists(utils.POSITION_MAP_FILE_NAME): with data.open_data_file(utils.POSITION_MAP_FILE_NAME, utils.WRITE_MODE) as position_map: json.dump((), position_map, indent=2) def add_data(self, data_id): with data.open_data_file(utils.POSITION_MAP_FILE_NAME, utils.READ_WRITE_MODE) as position_map: position_data = json.load(position_map) position_data.append({JSON_LEAF_ID: -config.get_random_leaf_id(), JSON_DATA_ID: data_id}) position_map.seek(0) json.dump(position_data, position_map, indent=2, sort_keys=True) position_map.truncate() def delete_data_ids(self, data_ids): copy_data_ids = list(data_ids) with data.open_data_file(utils.POSITION_MAP_FILE_NAME, utils.READ_WRITE_MODE) as position_map: position_data = json.load(position_map) for entry in list(position_data): if entry[JSON_DATA_ID] in data_ids: position_data.remove(entry) copy_data_ids.remove(entry[JSON_DATA_ID]) if not copy_data_ids: # stop iterating when all data ids are deleted break position_map.seek(0) json.dump(position_data, position_map, indent=2, sort_keys=True) position_map.truncate() def get_leaf_ids(self, data_ids): copy_data_ids = list(data_ids) leaf_ids = [] with data.open_data_file(utils.POSITION_MAP_FILE_NAME, utils.READ_MODE) as position_map: position_data = json.load(position_map) for entry in position_data: if entry[JSON_DATA_ID] in data_ids: leaf_ids.append((entry[JSON_DATA_ID], entry[JSON_LEAF_ID])) copy_data_ids.remove(entry[JSON_DATA_ID]) if not copy_data_ids: # stop iterating when all leaf ids are found break return leaf_ids def get_leaf_id(self, data_id): with data.open_data_file(utils.POSITION_MAP_FILE_NAME, utils.READ_MODE) as position_map: position_data = json.load(position_map) for entry in position_data: if entry[JSON_DATA_ID] == data_id: return entry[JSON_LEAF_ID] def update_leaf_id(self, data_id, is_in_cloud): with data.open_data_file(utils.POSITION_MAP_FILE_NAME, utils.READ_WRITE_MODE) as position_map: position_data = json.load(position_map) for entry in position_data: if entry[JSON_DATA_ID] == data_id: if is_in_cloud: entry[JSON_LEAF_ID] = abs(entry[JSON_LEAF_ID]) else: entry[JSON_LEAF_ID] = -entry[JSON_LEAF_ID] break position_map.seek(0) json.dump(position_data, position_map, indent=2, sort_keys=True) position_map.truncate() def choose_new_leaf_id(self, data_id): with data.open_data_file(utils.POSITION_MAP_FILE_NAME, utils.READ_WRITE_MODE) as position_map: position_data = json.load(position_map) for entry in position_data: if entry[JSON_DATA_ID] == data_id: entry[JSON_LEAF_ID] = -config.get_random_leaf_id() break position_map.seek(0) json.dump(position_data, position_map, indent=2, sort_keys=True) position_map.truncate() def data_id_exist(self, data_id): with data.open_data_file(utils.POSITION_MAP_FILE_NAME, utils.READ_MODE) as position_map: position_data = json.load(position_map) for entry in position_data: if entry[JSON_DATA_ID] == data_id: return True return False def count_data_ids(self): with data.open_data_file(utils.POSITION_MAP_FILE_NAME, utils.READ_MODE) as position_map: position_data = json.load(position_map) return len(position_data) <file_sep>/src/pyoram/crypto/aes_crypto.py __all__ = ('AESCrypto') import base64 import os import struct import six from cryptography.exceptions import InvalidSignature from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes, padding from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives.hmac import HMAC from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.hazmat.primitives.keywrap import aes_key_wrap, aes_key_unwrap, InvalidUnwrap from pyoram.core import config from pyoram.crypto.keyfile import KeyFile from pyoram.exceptions import WrongPassword, DummyFileFound class InvalidToken(Exception): pass class AESCrypto(object): def __init__(self, key_file, pw, backend=None): if backend is None: backend = default_backend() salt = self.from_base64(key_file.salt) waes_key = self.from_base64(key_file.waes_key) wmac_key = self.from_base64(key_file.wmac_key) if len(salt) != 16: raise ValueError( "Master key salt must be 16 url-safe base64-encoded bytes." ) master_key = self.generate_key(pw, salt) self.aes_key = self.unwrap_key(master_key, waes_key) self.mac_key = self.unwrap_key(master_key, wmac_key) self.backend = backend if len(self.aes_key) != 32: raise ValueError( "AES key must be 32 url-safe base64-encoded bytes." ) if len(self.mac_key) != 32: raise ValueError( "Mac key must be 32 url-safe base64-encoded bytes." ) @classmethod def add_padding(cls, plaintext, block_size): padder = padding.PKCS7(block_size).padder() return padder.update(plaintext) + padder.finalize() @classmethod def remove_padding(cls, plaintext_padded, block_size): unpadder = padding.PKCS7(block_size).unpadder() plaintext = unpadder.update(plaintext_padded) try: plaintext += unpadder.finalize() except ValueError: raise InvalidToken return plaintext @classmethod def to_base64(cls, att): return base64.urlsafe_b64encode(att) @classmethod def from_base64(cls, att): return base64.urlsafe_b64decode(att) @classmethod def generate_key(cls, password, salt): kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=default_backend()) return kdf.derive(password.encode()) @classmethod def generate_random_key(cls): return os.urandom(32) @classmethod def wrap_key(cls, wrapping_key, key_to_wrap): return aes_key_wrap(wrapping_key, key_to_wrap, default_backend()) @classmethod def create_keys(cls, pw): salt = os.urandom(16) master_key = cls.generate_key(pw, salt) aes_key = cls.generate_random_key() mac_key = cls.generate_random_key() wrapped_aes_key = cls.wrap_key(master_key, aes_key) wrapped_mac_key = cls.wrap_key(master_key, mac_key) return KeyFile(cls.to_base64(salt), cls.to_base64(wrapped_aes_key), cls.to_base64(wrapped_mac_key)) def unwrap_key(self, wrapping_key, key_to_unwrap): try: return aes_key_unwrap(wrapping_key, key_to_unwrap, default_backend()) except InvalidUnwrap: raise WrongPassword("Password is incorrect.") def encrypt(self, data, data_id): iv = os.urandom(16) return self.encrypt_with_hmac(data, data_id, iv) def encrypt_with_hmac(self, data, data_id, iv): if not isinstance(data, bytes): raise TypeError("data must be bytes.") if not isinstance(data_id, int): raise TypeError("data_id must be int.") main_parts = ( struct.pack(config.FORMAT_CHAR, data_id) + data ) # PKCS7 padding padded_data = self.add_padding(main_parts, algorithms.AES.block_size) # AES with CBC mode encryptor = Cipher(algorithms.AES(self.aes_key), modes.CBC(iv), backend=self.backend).encryptor() ciphertext = encryptor.update(padded_data) + encryptor.finalize() basic_parts = ( b"\x80" + iv + ciphertext ) h = HMAC(self.mac_key, hashes.SHA256(), backend=self.backend) h.update(basic_parts) hmac = h.finalize() return basic_parts + hmac def decrypt(self, token): if not isinstance(token, bytes): raise TypeError("token must be bytes") if not token or six.indexbytes(token, 0) != 0x80: raise InvalidToken hmac = token[-32:] h = HMAC(self.mac_key, hashes.SHA256(), backend=self.backend) h.update(token[:-32]) try: h.verify(hmac) except InvalidSignature: raise InvalidToken iv = token[1:17] ciphertext = token[17:-32] decryptor = Cipher(algorithms.AES(self.aes_key), modes.CBC(iv), self.backend).decryptor() plaintext_padded = decryptor.update(ciphertext) try: plaintext_padded += decryptor.finalize() except ValueError: raise InvalidToken plaintext = self.remove_padding(plaintext_padded, algorithms.AES.block_size) try: data_id, = struct.unpack(config.FORMAT_CHAR, plaintext[:8]) except struct.error: raise InvalidToken if data_id == config.DUMMY_ID: raise DummyFileFound data = plaintext[8:] return data_id, data <file_sep>/src/pyoram/core/stash.py _all__ = ('Stash') import data from pyoram import utils FILE_NAME = 'data%d.oram' class Stash: def __init__(self): if not data.is_folder(utils.STASH_FOLDER_NAME): data.create_folder(utils.STASH_FOLDER_NAME) def get_filename(self, data_id): return FILE_NAME % data_id def add_file(self, data_id, main_part): with data.open_data_file_in_stash(self.get_filename(data_id), utils.WRITE_BINARY_MODE) as data_item: data_item.write(main_part) def open_file(self, data_id): with data.open_data_file_in_stash(self.get_filename(data_id), utils.READ_BINARY_MODE) as data_item: data_block = data_item.read() return data_block def delete_data_items(self, data_ids): for data_id in data_ids: self.delete_data_item(data_id) def delete_data_item(self, data_id): data.delete_file_in_stash(self.get_filename(data_id)) def get_data_item(self, data_id): if data.is_file_in_stash(self.get_filename(data_id)): with data.open_data_file_in_stash(self.get_filename(data_id), utils.READ_BINARY_MODE) as data_item: return data_id, data_item.read() def get_potential_data_id(self): data_ids = [] stash_file_names = data.get_file_names_from_stash() for file_name in stash_file_names: data_ids.append(int(file_name[4:-5])) return data_ids def get_stash_size(self): return data.get_stash_size() <file_sep>/src/pyoram/core/chunk_file.py __all__ = ('ChunkFile') from pyoram import log from pyoram.core import config from pyoram.core.map import FileMap, PositionMap from pyoram.core.stash import Stash from pyoram.exceptions import FileSizeError logger = log.get_logger(__name__) PADDING = b'0' class ChunkFile: def __init__(self, aes_crypto=None): self.aes_crypto = aes_crypto self.data_id_counter = FileMap().get_id_counter() def split(self, file_name, file_input): logger.info('length of the selected file %d ' % len(file_input)) data_ids = [] for x in range(0, len(file_input), config.BLOCK_SIZE): if self.data_id_counter == config.DUMMY_ID: self.data_id_counter += 1 data_id = self.data_id_counter self.data_id_counter += 1 data_ids.append(data_id) chunk = file_input[x:config.BLOCK_SIZE + x] logger.info('chunk size is %d after splitting' % len(chunk)) if len(chunk) != config.BLOCK_SIZE: logger.info('chunk is smaller than the block size, add padding here') chunk = chunk.rjust(config.BLOCK_SIZE, PADDING) logger.info('chunk size %d after padding' % len(chunk)) token = self.aes_crypto.encrypt(chunk, data_id) logger.info('chunk size is %d after encryption' % len(token)) Stash().add_file(data_id, token) PositionMap().add_data(data_id) FileMap().add_file(file_name, len(file_input), data_ids, self.data_id_counter) def combine(self, data_items, expected_file_len): plaintext = bytearray() for position, data_item in enumerate(data_items): logger.info('combining data item with id %d' % data_item[0]) plaintext_chunk = data_item[1] if position == len(data_items) - 1: remaining_length = expected_file_len - len(plaintext) plaintext_chunk = plaintext_chunk[-remaining_length:] logger.info('unpadding the chunk with id %d' % data_item[0]) plaintext.extend(plaintext_chunk) if expected_file_len != len(plaintext): raise FileSizeError('File size of the downloaded file is not correct.') return plaintext <file_sep>/src/pyoram/log.py import logging import data def get_logger(name): # create logger logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) # create console handler and set level to debug stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.DEBUG) #file_handler = logging.FileHandler(data.get_log_file_name()) #file_handler.setLevel(logging.DEBUG) # create formatter formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s') # add formatter to handlers stream_handler.setFormatter(formatter) #file_handler.setFormatter(formatter) # add handlers to logger logger.addHandler(stream_handler) #logger.addHandler(file_handler) return logger <file_sep>/src/pyoram/core/oram.py __all__ = ('PathORAM') import math from pyoram import log from pyoram.exceptions import DummyFileFound from pyoram.core import config from pyoram.core.cloud import Cloud from pyoram.core.map import PositionMap from pyoram.core.stash import Stash logger = log.get_logger(__name__) class PathORAM: def __init__(self, aes_crypto): self.cloud = Cloud(aes_crypto) self.aes_crypto = aes_crypto @classmethod def get_max_oram_block_size(cls): return int(math.pow(2, config.ORAM_LEVEL + 1) - 1) @classmethod def get_max_oram_storage_size(cls): return cls.get_max_oram_block_size() * config.BLOCK_SIZE def setup_cloud(self): self.cloud.setup_cloud(self.get_max_oram_block_size()) # Find the path from root to leaf # __author__: Dr. <NAME> def path_to_leaf(self, leaf): path = [0] * (config.ORAM_LEVEL + 1) leafmin = config.LEAF_MIN leafmax = config.LEAF_MAX for curlevel in range(config.ORAM_LEVEL): mid = (leafmax - leafmin) // 2 + leafmin if leaf <= mid: path[curlevel + 1] = path[curlevel] * 2 + 1 leafmax = mid else: path[curlevel + 1] = path[curlevel] * 2 + 2 leafmin = mid + 1 return path # Find the path from leaf to root # __author__: Dr. <NAME> def path_to_root(self, leaf): path = self.path_to_leaf(leaf) path.reverse() return path def get_potential_data_ids_with_leaf(self): potential_data_ids = Stash().get_potential_data_id() potential_data_properties = PositionMap().get_leaf_ids(potential_data_ids) return potential_data_properties def access_oram(self, path_to_root, data_id_of_interest=None): # TODO: lock the function to be used only in one thread at the time downloaded_data_items = self.read_path(path_to_root) data_item = self.write_stash(downloaded_data_items, data_id_of_interest) self.write_path(path_to_root) logger.info('STASH SIZE - %d' % Stash().get_stash_size()) return data_item def read_path(self, path_to_root): data_items = [] for node in path_to_root: logger.info('READ PATH - download from node %d' % node) data_item = self.read_node(node) data_items.append(data_item) return data_items def write_path(self, path_to_root): for node in path_to_root: potential_data_properties = self.get_potential_data_ids_with_leaf() has_potential_item = False for potential_data_property in potential_data_properties: potential_leaf_id = abs(potential_data_property[1]) potential_path = self.path_to_root(potential_leaf_id) if node in potential_path: has_potential_item = True data_id = potential_data_property[0] data_item = Stash().get_data_item(data_id) self.write_node(node, data_item[1]) logger.info('WRITE PATH - upload to node %d data item with id %d' % (node, data_id)) PositionMap().update_leaf_id(data_id, True) Stash().delete_data_item(data_id) break if not has_potential_item: self.write_node(node) logger.info('WRITE PATH - upload to node %d dummy data' % node) def decrypt_data_item(self, data_item): return self.aes_crypto.decrypt(data_item) def write_stash(self, downloaded_data_items, data_id_of_interest=None): data_item_of_interest = None for downloaded_data_item in downloaded_data_items: try: data_id, plaintext = self.decrypt_data_item(downloaded_data_item) if PositionMap().data_id_exist(data_id): logger.info('WRITE STASH - downloaded data item with id %d' % data_id) token = self.aes_crypto.encrypt(plaintext, data_id) Stash().add_file(data_id, token) if data_id_of_interest is not None and data_id_of_interest == data_id: PositionMap().choose_new_leaf_id(data_id) data_item_of_interest = data_id, plaintext else: PositionMap().update_leaf_id(data_id, False) except DummyFileFound: logger.info('WRITE STASH - downloaded dummy file') pass return data_item_of_interest def read_node(self, node): return self.cloud.download_node(node) def write_node(self, node, data_item=None): self.cloud.upload_to_node(node, data_item) def download_data_items(self, data_ids): data_items = [] for data_id in data_ids: leaf_id = PositionMap().get_leaf_id(data_id) if leaf_id < 0: data_item = Stash().get_data_item(data_id) logger.info('PATH ORAM - access stash') # decrypt data item data_item = self.decrypt_data_item(data_item[1]) data_items.append(data_item) else: path_to_root = self.path_to_root(leaf_id) data_item = self.access_oram(path_to_root, data_id) data_items.append(data_item) return data_items def update_data(self, data_properties): for data_property in data_properties: leaf_id = abs(data_property[1]) path_to_root = self.path_to_root(leaf_id) self.access_oram(path_to_root)
dcdf157e738617f2ee04b13d3446f8f638316aba
[ "Python" ]
13
Python
sidd36/ORAM
b234e6f86f15945d86d3217e0dd6c608bb5d487d
24ff5d5c6dc981bb9cfec20b16bce334fdc440eb
refs/heads/main
<file_sep>#include <iostream> #include <cmath> #include <conio.h> #include <ctype.h> #include <cstdlib> #include <cstdio> #include <cstring> #include "problem.h" #include <string> #include <Windows.h> using namespace std; int main() { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); bool exit = 0; int view_problem; vector <Problem> problem; while (!exit) { cout << "\n请输入表达式进行计算(空格或回车结束表达式输入)或按上、下方向键进入查看计算记录界面\n按ESC退出程序\n"; fflush(stdin); char ch = _getch(); if (ch == -32)//72up 80down { cout << "按键查看成功计算的表达式,按上、下方向键切换,按ESC退出查看\n"; if (problem.size() == 0) { cout << "没有成功计算的表达式\n"; ch = _getch(); continue; } bool exit_view = 0; int viewing; ch = _getch(); if (ch == 72) viewing = problem.size() - 1; else if (ch == 80) viewing = 0; else continue; while (!exit_view) { cout << problem[viewing] << endl; ch = _getch(); if (ch == 27) { exit_view = 1; cout << "退出查看表达式\n"; continue; } else if (ch == -32) { ch = _getch(); if (ch == 72) { viewing--; while (viewing < 0) viewing += problem.size(); } else if (ch == 80) { viewing++; viewing %= problem.size(); } else continue; } } continue; } else if (ch == 27)//esc { exit = 1; cout << "退出程序\n"; continue; } else if (ch == 16)//shift { ch = _getch(); if (ch == 57)//( ch = '('; else if (ch == 48)//) ch = ')'; } cout << ch; Problem new_problem; bool unknown_char = 0; getline(cin, new_problem.problem_string); new_problem.problem_string = ch + new_problem.problem_string; for (int i = 0; i < new_problem.problem_string.length(); i++) { char c = new_problem.problem_string[i]; if (c == 's' or c == 'S')//sin { c = new_problem.problem_string[++i]; if (i == new_problem.problem_string.length()) { unknown_char = 1; cout << "输入有误,或许想要输入的是sin?\n"; break; } if (c != 'i' and c != 'I') { unknown_char = 1; cout << "输入有误,或许想要输入的是sin?\n"; } c = new_problem.problem_string[++i]; if (i == new_problem.problem_string.length()) { unknown_char = 1; cout << "输入有误,或许想要输入的是sin?\n"; break; } if (c != 'n' and c != 'N') { unknown_char = 1; cout << "输入有误,或许想要输入的是sin?\n"; } if (!unknown_char) new_problem.problem.push_back({ 's',0,false,-1 }); } else if (c == 'c' or c == 'C')//cos { c = new_problem.problem_string[++i]; if (i == new_problem.problem_string.length()) { unknown_char = 1; cout << "输入有误,或许想要输入的是cos?\n"; break; } if (c != 'o' and c != 'O') { unknown_char = 1; cout << "输入有误,或许想要输入的是cos?\n"; } c = new_problem.problem_string[++i]; if (i == new_problem.problem_string.length()) { unknown_char = 1; cout << "输入有误,或许想要输入的是cos?\n"; break; } if (c != 's' and c != 'S') { unknown_char = 1; cout << "输入有误,或许想要输入的是cos?\n"; } if (!unknown_char) new_problem.problem.push_back({ 'c',0,false,-1 }); } else if (c == 't' or c == 'T')//tan { c = new_problem.problem_string[++i]; if (i == new_problem.problem_string.length()) { unknown_char = 1; cout << "输入有误,或许想要输入的是tan?\n"; break; } if (c != 'a' and c != 'A') { unknown_char = 1; cout << "输入有误,或许想要输入的是tan?\n"; } c = new_problem.problem_string[++i]; if (i == new_problem.problem_string.length()) { unknown_char = 1; cout << "输入有误,或许想要输入的是tan?\n"; break; } if (c != 'n' and c != 'N') { unknown_char = 1; cout << "输入有误,或许想要输入的是tan?\n"; } if (!unknown_char) new_problem.problem.push_back({ 't',0,false,-1 }); } else if (c == 'p' or c == 'P')//pi { c = new_problem.problem_string[++i]; if (i == new_problem.problem_string.length()) { unknown_char = 1; cout << "输入有误,或许想要输入的是pi?\n"; break; } if (c != 'i' and c != 'I') { unknown_char = 1; cout << "输入有误,或许想要输入的是pi?\n"; } if (!unknown_char) new_problem.problem.push_back({ 'n',3.1415926,false,-1 }); } else if (isdigit(c)) { double number = c - '0'; double decimal = 1.0; int count_point = 0; while (i + 1 < new_problem.problem_string.length() and (new_problem.problem_string[i + 1] == '.' or isdigit(new_problem.problem_string[i + 1]))) { i++; if (new_problem.problem_string[i] == '.') { count_point++; } else if (!count_point) { number = number * 10 + (new_problem.problem_string[i] - '0'); } else { decimal *= 0.1; number += (new_problem.problem_string[i] - '0') * decimal; } } new_problem.problem.push_back({ 'n',number,false,-1 }); if (count_point > 1) { unknown_char = 1; cout << "输入了过多的小数点\n或许想要输入的是" << number << "?\n"; } } else if (c == '+' or c == '-' or c == '*' or c == '/' or c == '(' or c == ')' or c == ' ') { new_problem.problem.push_back({ c,0,false,-1 }); } else { unknown_char = 1; } } if (unknown_char) { cout << "不正确的输入,请重新输入表达式\n"; continue; } CheckProblem(new_problem); if (new_problem.error) { cout << "表达式有误\n"; ProblemPrintWithError(new_problem); } else { SolveProblem(new_problem); if (new_problem.error) { cout << "计算过程中出现了除以0!\n"; continue; } cout << new_problem << endl; problem.push_back(new_problem); } while (problem.size() > 5) problem.erase(problem.begin()); } return 0; }<file_sep># TriFuncSolver 支持含三角函数在内的多项式计算工具 ## 需求概述 项目实现一个可进行多次计算、支持三角函数计算、支持圆周率参加运算、支持浮点数计算的多项式计算器。 - 支持对多项式合法性的检验 - 支持非法多项式的报错 - 支持已计算多项式的查看 ## 业务逻辑 ```mermaid graph TD 0[程序运行]-->A(输入表达式) A-->B{判断合法性} B-->|表达式合法| C[计算表达式] B-->|表达式非法| D[报错] C-->E{是否退出} D-->E E-->|继续计算| A E-->|退出程序| F[程序结束] ``` ## 架构设计 ### 源文件 #### problem.cpp 实现对表达式的检验、查错、计算、查询 ```c++ bool CheckProblem(Problem problem); ErrorInfo FindError(Problem problem); double SolveProblem(Problem problem); void ViewProblem(Problem problem); ``` #### main.cpp 实现和用户的交互等操作,通过调用`problem.cpp`的函数实现程序功能 ### 头文件 #### problem.h 定义了`struct Item`表示运算符或运算数 定义了`struct Problem`表示表达式 定义了`struct ErrorInfo`表示错误信息 ```c++ struct Item { char c; double n; }; struct Problem { vector <Item> problem; double answer; }; struct ErrorInfo { int error_position; int error_type; }; ``` ### 数据结构 表达式内的运算符、运算数用向量`vector`存储 已计算的表达式用队列`queue`存储 <file_sep>#include "problem.h" #include <iostream> #include <cmath> #include <stack> #include <algorithm> #include <queue> #include <Windows.h> using namespace std; inline bool isoperater(char c) { if (c == '+' or c == '-' or c == '*' or c == '/') return 1; return 0; } void CheckProblem(Problem& problem) { //删除表达式开头的多余空格 while (problem.problem[0].c == ' ') problem.problem.erase(problem.problem.begin()); while (problem.problem[problem.problem.size() - 1].c == ' ') problem.problem.pop_back(); //15:数字被空格隔断 for (auto i = problem.problem.begin() + 1; i <= problem.problem.end() - 1; i++) { if (i->c == ' ') { auto j = i + 1; while (j != problem.problem.end() and j->c == ' ') j++; if ((i - 1)->c == 'n' and j->c == 'n') { (i - 1)->error = 1, (i - 1)->error_type = 15; j->error = 1, j->error_type = 15; problem.error = 1; } } } bool problem_read_finish = 0; //删除表达式中间的多余空格 while (!problem_read_finish) { for (auto i = problem.problem.begin(); i != problem.problem.end(); i++) { if (i + 1 == problem.problem.end()) problem_read_finish = 1; if (i->c == ' ') { problem.problem.erase(i); break; } } } //负号前为左括号或三角函数时前补0 problem_read_finish = 0; while (!problem_read_finish) { for (auto i = problem.problem.begin(); i != problem.problem.end(); i++) { if (i + 1 == problem.problem.end()) problem_read_finish = 1; if (i->c == '-') { if (i == problem.problem.begin() or (i - 1)->c == '(' or (i - 1)->c == 's' or (i - 1)->c == 'c' or (i - 1)->c == 't') { problem.problem.insert(i, { 'n',0,0,0 }); break; } } } } //1:表达式开头 auto problem_begin = problem.problem.begin(); if (problem_begin->c == 'n' or problem_begin->c == 's' or problem_begin->c == 'c' or problem_begin->c == 't' or problem_begin->c == '(') { //OK } else { problem.problem[0].error = 1, problem.problem[0].error_type = 1; problem.error = 1; } //2:表达式结尾 auto problem_back = problem.problem.end() - 1; if (problem_back->c == 'n' or problem_back->c == ')') { //OK } else { problem.problem[problem.problem.size() - 1].error = 1, problem.problem[problem.problem.size() - 1].error_type = 2; problem.error = 1; } //3:操作符后不能是右括号 for (auto i = problem.problem.begin(); i != problem.problem.end(); i++) { if (isoperater(i->c)) { if (i + 1 != problem.problem.end()) { if ((i + 1)->c == ')') { i->error = 1, i->error_type = 3; problem.error = 1; } } } } //4:操作符后不能是操作符 for (auto i = problem.problem.begin(); i != problem.problem.end(); i++) { if (isoperater(i->c)) { if (i + 1 != problem.problem.end()) { if (isoperater((i + 1)->c)) { i->error = 1, i->error_type = 4; problem.error = 1; } } } } //5:三角函数后不能是右括号 for (auto i = problem.problem.begin(); i != problem.problem.end(); i++) { if (i->c == 's' or i->c == 'c' or i->c == 't') { if (i + 1 != problem.problem.end()) { if ((i + 1)->c == ')') { i->error = 1, i->error_type = 5; problem.error = 1; } } } } //6:数字中出现空格 problem_read_finish = 0; while (!problem_read_finish) { for (auto i = problem.problem.begin(); i != problem.problem.end(); i++) { if (i + 1 == problem.problem.end()) { problem_read_finish = 1; } if (i->c == ' ') { if (i - 1 >= problem.problem.begin() and i + 1 != problem.problem.end()) { if ((i - 1)->c == 'n' and (i + 1)->c == 'n') { (i - 1)->error = (i + 1)->error = 1; (i - 1)->error_type = (i + 1)->error_type = 6; problem.error = 1; } else { problem.problem.erase(i); break; } } } } } //7:数字后不能是左括号 for (auto i = problem.problem.begin(); i != problem.problem.end(); i++) { if (i->c == 'n') { if ((i + 1) != problem.problem.end() and (i + 1)->c == '(') { i->error = 1, i->error_type = 7; problem.error = 1; } } } //8:数字后不能是三角函数 for (auto i = problem.problem.begin(); i != problem.problem.end(); i++) { if (i->c == 'n') { if ((i + 1) != problem.problem.end() and ((i + 1)->c == 's' or (i + 1)->c == 'c' or (i + 1)->c == 't')) { i->error = 1, i->error_type = 8; problem.error = 1; } } } //9:左括号后不能是右括号 for (auto i = problem.problem.begin(); i != problem.problem.end(); i++) { if (i->c == '(') { if ((i + 1) != problem.problem.end() and (i + 1)->c == ')') { i->error = 1, i->error_type = 9; problem.error = 1; } } } //10:左括号后不能是运算符 for (auto i = problem.problem.begin(); i != problem.problem.end(); i++) { if (i->c == '(') { if ((i + 1) != problem.problem.end() and isoperater((i + 1)->c)) { i->error = 1, i->error_type = 10; problem.error = 1; } } } //11:右括号后不能是左括号 for (auto i = problem.problem.begin(); i != problem.problem.end(); i++) { if (i->c == ')') { if ((i + 1) != problem.problem.end() and (i + 1)->c == '(') { i->error = 1, i->error_type = 11; problem.error = 1; } } } //12:右括号后不能是运算数 for (auto i = problem.problem.begin(); i != problem.problem.end(); i++) { if (i->c == ')') { if ((i + 1) != problem.problem.end() and (i + 1)->c == 'n') { i->error = 1, i->error_type = 12; problem.error = 1; } } } //13:右括号后不能是三角函数 for (auto i = problem.problem.begin(); i != problem.problem.end(); i++) { if (i->c == ')') { if ((i + 1) != problem.problem.end() and ((i + 1)->c == 's' or (i + 1)->c == 'c' or (i + 1)->c == 't')) { i->error = 1, i->error_type = 13; problem.error = 1; } } } //14:左右括号匹配 stack < vector<Item>::iterator > bracket; for (auto i = problem.problem.begin(); i != problem.problem.end(); i++) { if (i->c != '(' and i->c != ')') continue; if (i->c == '(') { bracket.push(i); } if (i->c == ')') { if (bracket.empty()) { i->error = 1, i->error_type = 14; problem.error = 1; } else bracket.pop(); } } while (!bracket.empty()) { auto i = bracket.top(); bracket.pop(); i->error = 1, i->error_type = 14; problem.error = 1; } } inline void PrintErrorInfo(int error_type) { switch (error_type) { case 1: cout << "表达式开头非法\n"; break; case 2: cout << "表达式结尾非法\n"; break; case 3: cout << "运算符后不能接右括号\n"; break; case 4: cout << "运算符后不能是运算符\n"; break; case 5: cout << "三角函数后不能是右括号\n"; break; case 6: cout << "有空格的运算数是非法的\n"; break; case 7: cout << "操作数后不能是左括号\n"; break; case 8: cout << "操作数后不能是三角函数\n"; break; case 9: cout << "括号内的内容不能为空\n"; break; case 10: cout << "左括号后不能是运算符\n"; break; case 11: cout << "右括号后不能是左括号\n"; break; case 12: cout << "右括号后不能是运算数\n"; break; case 13: cout << "右括号后不能是三角函数\n"; break; case 14: cout << "左右括号不匹配\n"; break; case 15: cout << "数字中有空格\n"; break; default: cout << "不是合法的输入\n"; break; } } void ProblemPrintWithError(Problem problem) { for (auto i : problem.problem) { if (i.error) SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED); switch (i.c) { case 'n': if (i.n == 3.1415926) cout << "pi"; else cout << i.n; break; case 's': cout << "sin"; break; case 'c': cout << "cos"; break; case 't': cout << "tan"; break; default: cout << i.c; break; } if (i.error) SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); } cout << endl; for (auto i : problem.problem) { if (i.error) { switch (i.c) { case 'n': if (i.n == 3.1415926) cout << "pi"; else cout << i.n; break; case 's': cout << "sin"; break; case 'c': cout << "cos"; break; case 't': cout << "tan"; break; default: cout << i.c; break; } PrintErrorInfo(i.error_type); } } } void SolveProblem(Problem& problem) { int in_priority[150], out_priority[150]; fill(in_priority, in_priority + 150, 0); fill(out_priority, out_priority + 150, 0); in_priority['('] = 1, in_priority['s'] = in_priority['c'] = in_priority['t'] = 8, in_priority['*'] = in_priority['/'] = 6, in_priority['+'] = in_priority['-'] = 4; out_priority['('] = 9, out_priority['s'] = out_priority['c'] = out_priority['t'] = 7, out_priority['*'] = out_priority['/'] = 5, out_priority['+'] = out_priority['-'] = 3, out_priority[')'] = 1; stack<char> mid_to_back; queue<Item> back; stack<double> solve_number; for (auto i : problem.problem) { if (i.c == 'n') back.push(i); else { if (i.c == ')') { while (mid_to_back.top() != '(') back.push({ mid_to_back.top(),0,0,0 }), mid_to_back.pop(); mid_to_back.pop(); } else { while (!mid_to_back.empty() and in_priority[mid_to_back.top()] >= out_priority[i.c]) back.push({ mid_to_back.top(),0,0,0 }), mid_to_back.pop(); mid_to_back.push(i.c); } } } while (!mid_to_back.empty()) back.push({ mid_to_back.top(),0,0,0 }), mid_to_back.pop(); while (!back.empty()) { double x, y; switch (back.front().c) { case 'n': solve_number.push(back.front().n); break; case '+': y = solve_number.top(), solve_number.pop(); x = solve_number.top(), solve_number.pop(); solve_number.push(x + y); break; case '-': y = solve_number.top(), solve_number.pop(); x = solve_number.top(), solve_number.pop(); solve_number.push(x - y); break; case '*': y = solve_number.top(), solve_number.pop(); x = solve_number.top(), solve_number.pop(); solve_number.push(x * y); break; case '/': y = solve_number.top(), solve_number.pop(); x = solve_number.top(), solve_number.pop(); if (y == 0) { problem.error = 1; return; } else solve_number.push(x / y); break; case 's': y = solve_number.top(), solve_number.pop(); solve_number.push(sin(y)); break; case 'c': y = solve_number.top(), solve_number.pop(); solve_number.push(cos(y)); break; case 't': y = solve_number.top(), solve_number.pop(); solve_number.push(tan(y)); break; default: break; } back.pop(); } problem.answer = solve_number.top(); } <file_sep>#pragma once #include <vector> #include <iomanip> using namespace std; struct Item { char c; double n; bool error; int error_type; }; struct Problem { string problem_string; vector <Item> problem; bool error; double answer; Problem() { error = 0; answer = 0; } friend ostream& operator<<(ostream& out, const Problem& x) { out << x.problem_string; out << "=" << fixed << setprecision(8) << x.answer, out << defaultfloat;; return out; } }; void CheckProblem(Problem& problem); void SolveProblem(Problem& problem); void ProblemPrintWithError(Problem problem);
a57bb3166180aa20f8b9208b2d2c4befe43f0e5b
[ "Markdown", "C++" ]
4
C++
syhien/TriFuncSolver
cc2afd50bdbe1c1f0a9f1f87808b293a5964cf8d
bf1d84414538c6c63dfc66d732e8f8dfbb830d31
refs/heads/master
<repo_name>hongning666/MyUILib<file_sep>/QUISkin/QUISkin/QUIWnd.cpp #include"stdafx.h" #include"QUIWnd.h" CQUIWnd::CQUIWnd() { m_hWnd = NULL; m_hInst = NULL; m_hRgn = NULL; m_bDrag = FALSE; } CQUIWnd::~CQUIWnd() { } HWND CQUIWnd::Create(HWND hWndParent, LPCTSTR lpszCaption, const RECT rc,DWORD dwStyle, HINSTANCE hInst) { m_hInst = hInst; if (!RegisterWndClass()) return NULL; dwStyle |= WS_CLIPSIBLINGS; dwStyle |= WS_CLIPCHILDREN; m_hWnd = CreateWindow(GetWndClassName(), lpszCaption, dwStyle, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, hWndParent, NULL, hInst, this); return m_hWnd ; } BOOL CQUIWnd::RegisterWndClass() { WNDCLASS wc = { 0 }; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hbrBackground =CreateSolidBrush(RGB(255,0,0)) ; wc.hCursor = LoadCursor(NULL,IDC_ARROW); wc.hIcon = NULL; wc.hInstance = m_hInst; wc.lpfnWndProc = WndProc; wc.lpszClassName = GetWndClassName(); wc.style = CS_VREDRAW | CS_HREDRAW; wc.lpszMenuName = NULL; return 0 != RegisterClass(&wc);//注册成功返回0 } LRESULT CALLBACK CQUIWnd::WndProc(HWND hWnd, UINT msg, WPARAM wparam, LPARAM lparam) { //把窗口过程函数绑定到窗口实例 CQUIWnd* pThis = NULL; if (msg == WM_NCCREATE) { LPCREATESTRUCT lpcs = (LPCREATESTRUCT)lparam; pThis = (CQUIWnd*)lpcs->lpCreateParams; pThis->m_hWnd = hWnd; ::SetWindowLongPtr(hWnd, GWLP_USERDATA, (LPARAM)pThis); } else { pThis = (CQUIWnd*)GetWindowLongPtr(hWnd, GWLP_USERDATA); } if (pThis != NULL) return pThis->HandleMessage(msg, wparam, lparam); else return DefWindowProc(hWnd, msg, wparam, lparam); } LPCTSTR CQUIWnd::GetWndClassName() { return L"QUIWnd"; } LRESULT CQUIWnd::HandleMessage(UINT message, WPARAM wparam, LPARAM lparam) { switch (message) { case WM_SIZE: OnSize(wparam, lparam); break; case WM_CREATE: OnCreate(wparam, lparam); break; case WM_PAINT: OnPaint(wparam, lparam); break; case WM_LBUTTONDOWN: OnLButtonDown(wparam, lparam); break; case WM_LBUTTONUP: OnLButtonUp(wparam, lparam); break; case WM_MOUSEMOVE: OnMouseMove(wparam, lparam); break; case WM_CLOSE://窗口关闭消息,这个时候窗口没有销毁 OnClose(wparam, lparam); break; case WM_DESTROY: OnDestoryWindow(wparam, lparam); break; case WM_ACTIVATE: OnActivate(wparam, lparam); break; case WM_KILLFOCUS: OnKillFocus(wparam, lparam); break; case WM_SETFOCUS: OnSetFocus(wparam, lparam); break; case WM_SHOWWINDOW: OnShowWindow(wparam, lparam); break; case WM_KEYDOWN: OnKeyDown(wparam, lparam); break; /*case WM_CTLCOLOREDIT: return (LRESULT)OnCtrlColorEdit(wparam, lparam); break;*/ } return DefWindowProc(m_hWnd,message,wparam,lparam); } void CQUIWnd::SetIcon(UINT iRes) { //1.加载图标 int icx = GetSystemMetrics(SM_CXICON); int icy = GetSystemMetrics(SM_CYICON); HICON hIcon = (HICON)LoadImage(m_hInst, MAKEINTRESOURCE(iRes), IMAGE_ICON, icx, icy, LR_DEFAULTCOLOR); //2.设置图标 SendMessage(m_hWnd, WM_SETICON, (WPARAM)TRUE, (LPARAM)hIcon); } void CQUIWnd::SetMiniSize(int iWidth, int iHeight) { m_iMinWidth = iWidth; m_iMinHeight = iHeight; } void CQUIWnd::OnSize(WPARAM wparam, LPARAM lparam) { } void CQUIWnd::SetWindowRgn(POINT* lpPoint, int count) { m_hRgn = CreatePolygonRgn(lpPoint, count, ALTERNATE); } void CQUIWnd::OnCreate(WPARAM wparam, LPARAM lparam) { if (m_hRgn) ::SetWindowRgn(m_hWnd, m_hRgn, TRUE); } void CQUIWnd::SetDragRect(const RECT& rc) { m_tDragRc.left = rc.left; m_tDragRc.bottom = rc.bottom; m_tDragRc.right = rc.right; m_tDragRc.top = rc.top; } void CQUIWnd::OnLButtonDown(WPARAM wparam, LPARAM lparam) { //1.获取鼠标按下的坐标 POINT pt; ::GetCursorPos(&pt); m_tPt = pt; //2.把坐标转化为窗口坐标 ScreenToClient(m_hWnd, &pt); //3.判断坐标点是否在拖动区域 if (!PtInRect(&m_tDragRc, pt)) return; m_bDrag = TRUE; SetCapture(m_hWnd);//设置捕捉鼠标,即使鼠标不在窗口上面 } void CQUIWnd::OnLButtonUp(WPARAM wparam, LPARAM lparam) { if (m_bDrag) {//退出拖动状态 m_bDrag = FALSE; ReleaseCapture(); } } void CQUIWnd::OnMouseMove(WPARAM wparam, LPARAM lparam) { if (!m_bDrag) return; POINT pt; ::GetCursorPos(&pt); int iLeft = pt.x - m_tPt.x; int iTop = pt.y - m_tPt.y; m_tPt = pt; RECT rcWnd; GetWindowRect(&rcWnd); //计算窗口新坐标 rcWnd.left += iLeft; rcWnd.right += iLeft; rcWnd.top += iTop; rcWnd.bottom += iTop; //移动窗口 ::MoveWindow(m_hWnd, rcWnd.left, rcWnd.top, rcWnd.right - rcWnd.left, rcWnd.bottom - rcWnd.top, TRUE); } void CQUIWnd::ShowWindow(UINT nCmd) { ::ShowWindow(m_hWnd, nCmd); } void CQUIWnd::UpdateWindow() { ::UpdateWindow(m_hWnd); } void CQUIWnd::OnClose(WPARAM wparam, LPARAM lparam) { DestroyWindow(m_hWnd); } void CQUIWnd::OnDestoryWindow(WPARAM wparam, LPARAM lparam) { } void CQUIWnd::OnPaint(WPARAM wparam, LPARAM lparam) { PAINTSTRUCT pcs; HDC hdc = BeginPaint(m_hWnd, &pcs); RECT rc; GetClientRect(&rc); //gdi+的双缓冲绘制,先把界面所有的元素在内存里面绘制一张图片 //绘制完之后,把缓冲图片一次性绘制到窗口上面 //内存位图 Gdiplus::Bitmap membmp(rc.right - rc.left, rc.bottom - rc.top); //根据内存位图生成一个内存绘图器 Gdiplus::Graphics* pGrx = Gdiplus::Graphics::FromImage(&membmp); if (m_szBground.length()) { //把背景图绘制在内存绘图器上面 Gdiplus::Image im(m_szBground.c_str()); pGrx->DrawImage(&im, Gdiplus::Rect(rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top)); } //把界面元素绘制在内存绘图器上面 OnPaintControl(*pGrx);//绘制元素 //把内存位图一次性绘制在窗口上面 Gdiplus::Graphics grx(hdc); grx.DrawImage(&membmp, Gdiplus::Rect(0, 0, membmp.GetWidth(), membmp.GetHeight())); delete pGrx; pGrx = NULL; ::EndPaint(m_hWnd, &pcs); } void CQUIWnd::MoveWindow(const RECT& rc,BOOL bRepaint) { ::MoveWindow(m_hWnd, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, bRepaint); } void CQUIWnd::OnActivate(WPARAM wparam, LPARAM lparam) { } void CQUIWnd::OnKillFocus(WPARAM wparam, LPARAM lparam) { } void CQUIWnd::OnSetFocus(WPARAM wparam, LPARAM lparam) { } void CQUIWnd::EnableWindow(BOOL bEnable) { ::EnableWindow(m_hWnd, bEnable); } void CQUIWnd::OnShowWindow(WPARAM wparam, LPARAM lparam) { } void CQUIWnd::OnKeyDown(WPARAM wparam, LPARAM lparam) { } void CQUIWnd::SetBground(const StdString& strFile) { m_szBground = strFile; } BOOL CQUIWnd::GetClientRect(RECT* rc) { if (m_hWnd == nullptr) return FALSE; ::GetClientRect(m_hWnd, rc); return TRUE; } BOOL CQUIWnd::GetWindowRect(RECT* rc) { if (m_hWnd == nullptr) return FALSE; ::GetWindowRect(m_hWnd, rc); return TRUE; } void CQUIWnd::OnPaintControl(Gdiplus::Graphics& grx) { } HBRUSH CQUIWnd::OnCtrlColorEdit(WPARAM wparam, LPARAM lparam) { HWND hEdit = (HWND)lparam; HDC hdc = (HDC)wparam; SetBkMode(hdc, TRANSPARENT); SetBkColor(hdc, RGB(255, 0, 0)); return (HBRUSH)CreateSolidBrush(RGB(255, 0, 0)); }<file_sep>/QUISkin/QUISkin/QUIWnd.h #ifndef _QUIWND_H_ #define _QUIWND_H_ #include"QUISkin.h" #include<gdiplus.h> class QUISKIN_API CQUIWnd { public: CQUIWnd(); virtual~CQUIWnd(); public: HWND Create(HWND hWndParent, LPCTSTR lpszCaption, const RECT rc, DWORD dwStyle, HINSTANCE hInst); /* 功能:设置图标 参数: @iRes:资源id号 */ void SetIcon(UINT iRes); /* 功能:设置窗口最小大小 参数: @iWidth:最小宽度 @iHeight:最小高度 */ void SetMiniSize(int iWidth, int iHeight); /* 功能:设置窗口区域 参数: @lpPoint:坐标点列表 @count:点的数量 */ void SetWindowRgn(POINT* lpPoint, int count); /* 功能:设置鼠标按下拖动窗口的坐标 */ void SetDragRect(const RECT& rc); void ShowWindow(UINT nCmd); void UpdateWindow(); /* 功能:改变窗口坐标 */ void MoveWindow(const RECT& rc,BOOL bRepaint); /* 功能:允许/禁止窗口接受鼠标和键盘输入 参数: @bEnable:TRUE 是允许,FLASE是禁止 */ void EnableWindow(BOOL bEnable); /* 功能:设置背景图 */ void SetBground(const StdString& strFile); /* 功能:获取窗口客户区坐标 */ BOOL GetClientRect(RECT* rc); /* 功能:获取窗口坐标 */ BOOL GetWindowRect(RECT* rc); protected: //注册窗口 virtual BOOL RegisterWndClass(); static LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wparam, LPARAM lparam); //获取窗口名字 virtual LPCTSTR GetWndClassName(); //消息处理函数 virtual LRESULT HandleMessage(UINT message, WPARAM wparam, LPARAM lparam); protected: virtual void OnPaint(WPARAM wparam, LPARAM lparam); virtual void OnSize(WPARAM wparam,LPARAM lparam); virtual void OnCreate(WPARAM wparam, LPARAM lparam); virtual void OnLButtonDown(WPARAM wparam, LPARAM lparam); virtual void OnLButtonUp(WPARAM wparam, LPARAM lparam); virtual void OnMouseMove(WPARAM wparam, LPARAM lparam); virtual void OnClose(WPARAM wparam, LPARAM lparam); virtual void OnDestoryWindow(WPARAM wparam, LPARAM lparam); virtual void OnActivate(WPARAM wparam, LPARAM lparam); virtual void OnKillFocus(WPARAM wparam, LPARAM lparam); virtual void OnSetFocus(WPARAM wparam, LPARAM lparam); virtual void OnShowWindow(WPARAM wparam, LPARAM lparam); virtual void OnKeyDown(WPARAM wparam, LPARAM lparam); virtual HBRUSH OnCtrlColorEdit(WPARAM wparam, LPARAM lparam); protected: /* 功能:元素的绘制 */ virtual void OnPaintControl(Gdiplus::Graphics& grx); protected: HWND m_hWnd; HINSTANCE m_hInst; int m_iMinWidth;//窗口最小宽度 int m_iMinHeight;//窗口最小高度 HRGN m_hRgn;//窗口区域 RECT m_tDragRc;//鼠标按下拖动窗口的区域 BOOL m_bDrag;//是否处理窗口拖动状态 POINT m_tPt;//鼠标按下的坐标点 StdString m_szBground;//窗口背景位图 }; #endif<file_sep>/QUISkin/QUISkin/QUITree.h #ifndef QUITREE_H_ #define QUITREE_H_ #include"UIElement.h" /* 结点数据 */ class QUISKIN_API CVLNode { public: CVLNode(); ~CVLNode(); public: void SetName(const TCHAR* szName); const TCHAR* GetName(); void SetIcon(const TCHAR* szIcon); const TCHAR* GetIcon(); void SetX(int x){ m_iLeft = x; }; void SetY (int y){ m_iTop = y; }; int GetX(){ return m_iLeft; }; int GetY(){ return m_iTop; }; void SetHeight(int iHeight); int GetHeight(){ return m_iHeight; }; void SetWidth(int iWidth); int GetWidth(){ return m_iWidth; }; protected: std::basic_string<TCHAR> m_strName; std::basic_string<TCHAR> m_strIcon; //父节点没展开的话,x和y是无效的,每次展开,我们去更新它的一个实时坐标 int m_iLeft;//x int m_iTop;//y int m_iHeight;//高度 int m_iWidth;//宽度 }; /* 树型结点的类 */ class QUISKIN_API CVLTree { public: CVLTree(CVLNode* pNode=NULL); ~CVLTree(); public: /* 功能:插入子节点 参数: @pNode:是要插入新节点数据 @pInsNode:新节点插入到这个节点后面 如果pInsNode为NULL,默认插入最末尾 返回值:成功返回新插入的节点,失败返回0 */ CVLTree* InsertChildNode(CVLNode* pNode, CVLTree* pInsNode=NULL); int GetChildCount(); /* 功能:把子节点跟父节点脱离关系 */ CVLTree* DetachChildNode(); /* 功能:附加子节点 参数: @pTreeNode:链表头 @pInsNode:新节点插入到这个节点后面 如果pInsNode为NULL,默认插入最末尾 */ void AttachChildNode(CVLTree* pTreeNode,CVLTree* pInsNode=NULL); /* 功能:查找子节点的尾节点 */ CVLTree* GetTailChild(); /* 功能:获取子节点的首节点 */ CVLTree* GetFirstChild(); /* 功能:获取下一个子节点 */ CVLTree* GetNextNode(CVLTree* pTreeNode); /* 功能:获取节点数据 */ CVLNode* GetNode(); /* 功能:获取父节点 */ CVLTree* GetParentNode(); int GetLevel(); void Expend(BOOL bExpend); BOOL IsExpend(); protected: void CalcLevel(CVLTree* pTreeNode); protected: void ReleaseChild(); protected: CVLNode* m_pNode;//结点数据 CVLTree* m_pParent;//父结点 CVLTree* m_pNext;//下一个兄弟结点 CVLTree* m_pPre;//前一个兄弟结点 CVLTree* m_pFirstChild;//第一个子结点 CVLTree* m_pTailChild;//最后一个子结点 int m_iChildCounts;//子结点个数 int m_iLevel;//深度 BOOL m_bExpend;//是否展开 }; /* 树形控件的UI */ class QUISKIN_API CQUITree :public CUIElement { public: CQUITree(); ~CQUITree(); public: void SetItemHeight(int iItemHeight); CVLTree* Insert(const TCHAR* szName, const TCHAR* szIcon, CVLTree* pParent = NULL); virtual void DrawText(Gdiplus::Graphics& grx); void Expend(CVLTree* pTreeNode, BOOL bExpend=TRUE); public: virtual LRESULT OnControlMessage(UINT message, WPARAM wParam, LPARAM lParam); protected: void DrawItems(Gdiplus::Graphics& grx,CVLTree* pTreeNode); void DrawItem(Gdiplus::Graphics& grx, CVLNode* pNode); CVLTree* FindNodeByPoint(POINT pt, CVLTree* pNode=NULL); void CalcNodeRect(); BOOL CalcNodeRect(CVLTree* pTreeNode, int& y); private: CVLTree* m_pRoot;//树的根节点 int m_iItemHeight; int m_iLastY;//记录下一次插入节点的Y坐标 DWORD m_dwItemOverColor;//鼠标移动上去的颜色 DWORD m_dwItemSelColor;//当前选择项的背景 CVLTree* m_pItemOver; CVLTree* m_pItemSel; }; #endif<file_sep>/README.md # MyUILib 自己用c++面向对象思想,以及一些win32API,GDI+,dll动态链接库封装的界面库(未完成状态) 开发环境:vs2013 作者:小白 描述:自己封装的界面库,实现了一些按钮 list edit 树型控件 滚动条等基本控件。里面的Demo项目是自己写的测试程序 还有很多地方等待完善,框架还没配置,等以后技术高了再来解决。 <file_sep>/QUISkin/QUISkin/QUIStaticText.h #ifndef QUISTATICTEXT_H_ #define QUISTATICTEXT_H_ #include"UIElement.h" class QUISKIN_API CQUIStaticText :public CUIElement { public: CQUIStaticText(); ~CQUIStaticText(); public: void SetAlign(UINT uAStyle); void SetVlign(UINT uVStyle); void SetLightColor(DWORD dwColor); virtual void DrawText(Gdiplus::Graphics& grx); virtual LRESULT OnControlMessage(UINT message, WPARAM wParam, LPARAM lParam); virtual BOOL HitTest(POINT pt); private: UINT m_uAlign;//横向对齐方式 UINT m_uVlign;//竖向对齐方式 DWORD m_dwLightColor;//高亮显示的文本颜色 BOOL m_bLightColor;//是否需要高亮显示 RECT m_rcText;//文本区域 }; #endif<file_sep>/QUISkin/QUISkin/QUISkin.h #ifndef _QUISKIN_H_ #define _QUISKIN_H_ #include<string> #ifdef QUISKIN_EXPORTS #define QUISKIN_API _declspec(dllexport) #else #define QUISKIN_API _declspec(dllimport) #endif #define StdString std::basic_string<TCHAR> #endif<file_sep>/QUISkin/QUISkin/QUITab.cpp #include"stdafx.h" #include"QUITab.h" /****************************************************** Tab°´Å¥ *******************************************************/ CQUITabButton::CQUITabButton() { } CQUITabButton::~CQUITabButton() { } /****************************************************** TabÒ³ *******************************************************/ CQUITabPage::CQUITabPage() { } CQUITabPage::~CQUITabPage() { } /****************************************************** Tab¿Ø¼þ *******************************************************/ CQUITab::CQUITab() { } CQUITab::~CQUITab() { } void CQUITab::SetStyle(enTabStyle eStyle) { m_eStyle = eStyle; } void CQUITab::InsertTab(int iIndex, CQUITabButton* pTabBtn, CQUITabPage* pTabPage) { //1. ResetIndex(iIndex); TTabItem tItem; tItem.button = pTabBtn; tItem.page = pTabPage; m_tTabs[iIndex] = tItem; } void CQUITab::ResetIndex(int iIndex) { if (m_tTabs.size() == 0) return; TabItemMap::iterator it = m_tTabs.find(iIndex); if (it != m_tTabs.end()) { TabItemMap::reverse_iterator tmpIt = m_tTabs.rbegin(); --tmpIt; while ((*tmpIt).first <= (*it).first) { m_tTabs[(*tmpIt).first + 1] = (*tmpIt).second; --tmpIt; } ++it; } }<file_sep>/QUISkin/QUISkin/UIElement.h #ifndef UIELEMENT_H_ #define UIELEMENT_H_ #include"QUISkin.h" #include<gdiplus.h> class CUIElement; class IQUIEventCallBack { public: virtual void OnNotifyCmd(CUIElement* pElement) = 0;//按钮事件 }; /* 界面元素基类 */ class QUISKIN_API CUIElement { public: CUIElement(); virtual~CUIElement(); public: /* 功能:创建界面元素 */ virtual void Create(const TCHAR* szEleID,const RECT& rc,HWND hHostWnd,IQUIEventCallBack* pCallBack); void SetCaption(const TCHAR* szCaption); const TCHAR* GetCaption(); void SetBound(const RECT& rc); void GetBound(RECT* lpRect); void SetID(const TCHAR* szID); const TCHAR* GetID(); void SetVisible(BOOL bVisible); void SetEnable(BOOL bEnable); void SetBackColor(DWORD dwColor); void SetToolText(const TCHAR* szToolText); void SetBorderSize(DWORD dwBorderSize); void SetBorderColor(DWORD dwBorderColor); void SetBgImage(const TCHAR* szImage); void SetHostWnd(HWND hWnd); HWND GetHostWnd(); void SetFontSize(DWORD dwFontSize); DWORD GetFontSize(){ return m_dwFontSize; }; void SetFamily(const TCHAR* szFamily); const TCHAR* GetFamily(){ return m_strFont.c_str(); }; void SetTextColor(DWORD dwTxtColor); DWORD GetTextColor(){ return m_dwTextColor; }; public: virtual void DoPaint(Gdiplus::Graphics& grx); /* 功能:给控件一个处理与自己相关的系统消息 返回值: S_OK:子控件成功处理此消息,宿主窗口无需再处理 S_FALSE:此消息与子控件无关,继续由宿主窗口处理 */ virtual LRESULT OnControlMessage(UINT message,WPARAM wParam,LPARAM lParam); /* 功能:重绘我们的元素区域 */ virtual void InvalidBounds(); //判断鼠标点是否在元素区域内 virtual BOOL HitTest(POINT pt); BOOL IsVisible(); protected: virtual void DrawBkColor(Gdiplus::Graphics& grx); virtual void DrawBkImage(Gdiplus::Graphics& grx); virtual void DrawStatusImage(Gdiplus::Graphics& grx);//给子类重写 virtual void DrawText(Gdiplus::Graphics& grx); virtual void DrawBorder(Gdiplus::Graphics& grx); protected: HWND m_hHostWnd;//宿主窗体 RECT m_bound;//坐标位置 StdString m_strID;//ID号 BOOL m_bVisible;//是否可见 BOOL m_bEnable;//是否禁用 StdString m_strCaption;//标题 DWORD m_dwBackColor;//背景颜色 StdString m_strBgImage;//背景图 DWORD m_dwBorderColor;//边框颜色 DWORD m_dwBorder;//边框 DWORD m_dwTextColor;//文本颜色 StdString m_strFont;//字体 DWORD m_dwFontSize;//字体大小 StdString m_strToolTips; IQUIEventCallBack* m_pCallBack; }; #endif<file_sep>/QUISkin/Demo/MainFrame.h #pragma once #include "QUIWnd.h" #include"QUIButton.h" #include"QUIStaticText.h" #include"QUIEdit.h" #include"QUIListh.h" #include"QUITree.h" #include"QUIScrollBar.h" class CMainFrame :public CQUIWnd, public IQUIEventCallBack//,public IScrollbarCallback { public: CMainFrame(); ~CMainFrame(); protected: virtual LRESULT HandleMessage(UINT message, WPARAM wParam, LPARAM lParam); virtual LPCTSTR GetWndClassName(); virtual void OnCreate(WPARAM wParam, LPARAM lParam); virtual void OnPaint(WPARAM wParam, LPARAM lParam); virtual void OnDestoryWindow(WPARAM wParam, LPARAM lParam); virtual void OnSize(WPARAM wParam, LPARAM lParam); void OnNotifyCmd(CUIElement* pElement); virtual void OnPaintControl(Gdiplus::Graphics& grx); private: CQUIButton m_BtnClose; CQUIList m_List; }; <file_sep>/QUISkin/QUISkin/QUIStaticText.cpp #include"stdafx.h" #include"QUIStaticText.h" CQUIStaticText::CQUIStaticText() { memset(&m_rcText, 0, sizeof(RECT)); } CQUIStaticText::~CQUIStaticText() { } void CQUIStaticText::SetAlign(UINT uAStyle) { m_uAlign = uAStyle; } void CQUIStaticText::SetVlign(UINT uVStyle) { m_uVlign = uVStyle; } void CQUIStaticText::SetLightColor(DWORD dwColor) { m_dwLightColor = dwColor; } void CQUIStaticText::DrawText(Gdiplus::Graphics& grx) { //1.绘制之前背景设置透明 HDC hdc = grx.GetHDC(); ::SetBkMode(hdc, TRANSPARENT); //通过GDI+ GetHDC获取到hdc,必须要释放 grx.ReleaseHDC(hdc); //创建字体 Gdiplus::FontFamily family(m_strFont.c_str()); Gdiplus::Font font(&family, m_dwFontSize); //对齐格式 Gdiplus::StringFormat format; format.SetAlignment((Gdiplus::StringAlignment)m_uAlign); format.SetLineAlignment((Gdiplus::StringAlignment)m_uVlign); //创建画刷 Gdiplus::SolidBrush brush(Gdiplus::Color(GetRValue(m_dwTextColor), GetGValue(m_dwTextColor), GetBValue(m_dwTextColor))); //兼容高亮和不高亮显示两种风格 if (m_bLightColor&&m_dwLightColor != 0) brush.SetColor(Gdiplus::Color(GetRValue(m_dwLightColor), GetGValue(m_dwLightColor), GetBValue(m_dwLightColor))); //绘制文本 grx.DrawString(m_strCaption.c_str(), m_strCaption.length(), &font, Gdiplus::RectF(m_bound.left, m_bound.top, m_bound.right - m_bound.left, m_bound.bottom - m_bound.top), &format, &brush); //只计算一次文本区域 //if (m_rcText.right - m_rcText.left <= 0) {//计算文本区域 Gdiplus::RectF rcTxt; grx.MeasureString(m_strCaption.c_str(), m_strCaption.length(), &font, Gdiplus::RectF(m_bound.left, m_bound.top, m_bound.right - m_bound.left, m_bound.bottom - m_bound.top), &format, &rcTxt); m_rcText.left = rcTxt.GetLeft(); m_rcText.top = rcTxt.GetTop(); m_rcText.right = rcTxt.GetRight(); m_rcText.bottom = rcTxt.GetBottom(); } } LRESULT CQUIStaticText::OnControlMessage(UINT message, WPARAM wParam, LPARAM lParam) { __super::OnControlMessage(message, wParam, lParam); switch (message) { case WM_LBUTTONDOWN: {//鼠标左键按下在我的地盘,把这个按下事件要过滤掉 POINT pt; pt.x = LOWORD(lParam); pt.y = HIWORD(lParam); if (HitTest(pt)) return S_OK; } break; case WM_MOUSEMOVE: { POINT pt; pt.x = LOWORD(lParam); pt.y = HIWORD(lParam); if (HitTest(pt)) {//判断鼠标是否落在我们区域 if (!m_bLightColor) { m_bLightColor = TRUE; InvalidBounds(); } return S_OK; } else { if (m_bLightColor) {//如果当前是高亮显示,那么要恢复文本颜色 m_bLightColor = FALSE; InvalidBounds(); return S_OK; } } } break; } return S_FALSE; } BOOL CQUIStaticText::HitTest(POINT pt) { if (!IsVisible()) return FALSE; //不在区域范围 if (PtInRect(&m_rcText, pt)) return TRUE; return FALSE; }<file_sep>/QUISkin/QUISkin/QUITree.cpp #include"stdafx.h" #include"QUITree.h" //////////////////////////////////// //结点数据 CVLNode::CVLNode() { m_iWidth = 100; } CVLNode::~CVLNode() { } void CVLNode::SetName(const TCHAR* szName) { if (szName) m_strName = szName; } const TCHAR* CVLNode::GetName() { return m_strName.c_str(); } void CVLNode::SetIcon(const TCHAR* szIcon) { if (szIcon) m_strIcon = szIcon; } const TCHAR* CVLNode::GetIcon() { return m_strIcon.c_str(); } void CVLNode::SetHeight(int iHeight) { m_iHeight = iHeight; } void CVLNode::SetWidth(int iWidth) { m_iWidth = iWidth; } /////////////////////////////////// //树型结点 CVLTree::CVLTree(CVLNode* pNode) :m_pNode(pNode) { m_pParent = NULL; m_pNext = NULL; m_pPre = NULL; m_pFirstChild = NULL; m_iLevel = -1; m_bExpend = FALSE; m_iChildCounts = 0; } CVLTree::~CVLTree() { if (m_pNode) delete m_pNode; m_pNode = NULL; ReleaseChild(); } int CVLTree::GetChildCount() { return m_iChildCounts; } CVLTree* CVLTree::GetFirstChild() { return m_pFirstChild; } CVLTree* CVLTree::GetTailChild() { return m_pTailChild; } int CVLTree::GetLevel() { return m_iLevel; } void CVLTree::Expend(BOOL bExpend) { m_bExpend = bExpend; } BOOL CVLTree::IsExpend() { return m_bExpend; } CVLTree* CVLTree::GetNextNode(CVLTree* pTreeNode) { if (pTreeNode == NULL) return NULL; return pTreeNode->m_pNext; } CVLNode* CVLTree::GetNode() { return m_pNode; } CVLTree* CVLTree::GetParentNode() { return m_pParent; } void CVLTree::ReleaseChild() { CVLTree* pTreeNode = m_pFirstChild; while (pTreeNode) { CVLTree* pTmpNode = pTreeNode; pTreeNode = pTreeNode->m_pNext; delete pTmpNode; } } CVLTree* CVLTree::DetachChildNode() { CVLTree* pTmp = m_pFirstChild; m_pFirstChild = NULL; m_pTailChild = NULL; return pTmp; } CVLTree* CVLTree::InsertChildNode(CVLNode* pNode, CVLTree* pInsNode) { if (pNode == NULL) return NULL; CVLTree* pNewTreeNode = new CVLTree(pNode); pNewTreeNode->m_pParent = this; pNewTreeNode->m_iLevel = m_iLevel + 1; if (pInsNode) {//插入到pInsNode后面 pNewTreeNode->m_pNext = pInsNode->m_pNext; pNewTreeNode->m_pPre = pInsNode; pInsNode->m_pNext = pNewTreeNode; if (pNewTreeNode->m_pNext != NULL) pNewTreeNode->m_pNext->m_pPre = pNewTreeNode; if (m_pTailChild == pInsNode) m_pTailChild = pNewTreeNode; } else {//默认插入最末尾 pNewTreeNode->m_pPre = m_pTailChild; if (m_pFirstChild == NULL) m_pFirstChild = pNewTreeNode; else m_pTailChild->m_pNext = pNewTreeNode; m_pTailChild = pNewTreeNode; } m_iChildCounts++; return pNewTreeNode; } void CVLTree::AttachChildNode(CVLTree* pTreeNode, CVLTree* pInsNode) { if (pTreeNode == NULL) return; //重新计算深度 CalcLevel(pTreeNode); int iNewCount = 0; CVLTree* pTailNode = NULL; CVLTree* pTmpNode = pTreeNode; while (pTmpNode) {//查找最后一个兄弟节点 pTmpNode->m_pParent = this; pTailNode = pTmpNode; pTmpNode = pTmpNode->m_pNext; iNewCount++; } if (pInsNode != NULL) { pTmpNode = pInsNode->m_pNext; pInsNode->m_pNext = pTreeNode; pTreeNode->m_pPre = pInsNode; pTailNode->m_pNext = pTmpNode; if (pTmpNode != NULL) pTmpNode->m_pPre = pTailNode; if (m_pTailChild == pInsNode) m_pTailChild = pTailNode; } else { pTailNode->m_pPre = m_pTailChild; if (m_pFirstChild == NULL) m_pFirstChild = pTreeNode; else m_pTailChild->m_pNext = pTreeNode; m_pTailChild = pTailNode; } m_iChildCounts += iNewCount; } void CVLTree::CalcLevel(CVLTree* pTreeNode) { CVLTree* pTmpNode = pTreeNode; while (pTreeNode) { pTreeNode->m_iLevel = m_iLevel + 1; pTmpNode->CalcLevel(pTmpNode->m_pFirstChild); pTmpNode = pTmpNode->m_pNext; } } //////////////////////////////////// //树型控件UI CQUITree::CQUITree() { m_pRoot = new CVLTree();//生成一个空的根节点 m_iItemHeight = 30; m_iLastY = 0; m_dwItemOverColor = RGB(255, 0, 0); m_dwItemSelColor = RGB(0, 255, 0); m_pItemOver = NULL; m_pItemSel = NULL; } CQUITree::~CQUITree() { if (m_pRoot) delete m_pRoot; m_pRoot = NULL; } void CQUITree::SetItemHeight(int iItemHeight) { m_iItemHeight = iItemHeight; } CVLTree* CQUITree::Insert(const TCHAR* szName, const TCHAR* szIcon, CVLTree* pParent) { CVLTree* pTreeNode = NULL; CVLNode* pNode = new CVLNode(); pNode->SetName(szName); pNode->SetIcon(szIcon); pNode->SetHeight(m_iItemHeight); if (pParent) { pTreeNode = pParent->InsertChildNode(pNode); pNode->SetX(m_bound.left + pTreeNode->GetLevel() * 10); } else { int iCount = m_pRoot->GetChildCount(); pNode->SetX(m_bound.left); pNode->SetY(m_iLastY); m_iLastY += m_iItemHeight;//更新Y坐标 pTreeNode = m_pRoot->InsertChildNode(pNode); } return pTreeNode; } void CQUITree::DrawText(Gdiplus::Graphics& grx) { //遍历树 CVLTree* pTreeNode = m_pRoot->GetFirstChild(); while (pTreeNode) { DrawItems(grx, pTreeNode); pTreeNode = m_pRoot->GetNextNode(pTreeNode); } } void CQUITree::Expend(CVLTree* pTreeNode, BOOL bExpend) { if (pTreeNode == NULL) return; pTreeNode->Expend(TRUE); CalcNodeRect(); InvalidBounds(); } void CQUITree::DrawItems(Gdiplus::Graphics& grx, CVLTree* pTreeNode) { if (pTreeNode == NULL) return; CVLTree* pTmpNode = pTreeNode; while (pTmpNode) { CVLNode* pNode = pTmpNode->GetNode(); DrawItem(grx, pNode); if (pTmpNode->IsExpend()) {//如果展开了,要画子节点 DrawItems(grx, pTmpNode->GetFirstChild()); } pTmpNode = pTreeNode->GetNextNode(pTmpNode); } } void CQUITree::DrawItem(Gdiplus::Graphics& grx, CVLNode* pNode) { RECT rc; rc.left = pNode->GetX(); rc.top = pNode->GetY(); rc.right = m_bound.right; rc.bottom = rc.top + pNode->GetHeight(); //绘制背景 if (m_pItemSel&&m_pItemSel->GetNode() == pNode) { Gdiplus::SolidBrush fillbrush(Gdiplus::Color(50,GetRValue(m_dwItemSelColor), GetGValue(m_dwItemSelColor), GetBValue(m_dwItemSelColor))); grx.FillRectangle(&fillbrush, Gdiplus::RectF(rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top)); } else if (m_pItemOver&&m_pItemOver->GetNode() == pNode) { Gdiplus::SolidBrush fillbrush(Gdiplus::Color(50, GetRValue(m_dwItemOverColor), GetGValue(m_dwItemOverColor), GetBValue(m_dwItemOverColor))); grx.FillRectangle(&fillbrush, Gdiplus::RectF(rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top)); } //1.字体 Gdiplus::FontFamily family(m_strFont.c_str()); Gdiplus::Font font(&family, m_dwFontSize); //2.文本对齐格式 Gdiplus::StringFormat format; format.SetAlignment(Gdiplus::StringAlignmentNear); format.SetLineAlignment(Gdiplus::StringAlignmentCenter); Gdiplus::SolidBrush fbrush(Gdiplus::Color(GetRValue(m_dwTextColor), GetGValue(m_dwTextColor), GetBValue(m_dwTextColor))); std::basic_string<TCHAR> strName = pNode->GetName(); grx.DrawString(strName.c_str(), strName.length(), &font, Gdiplus::RectF(rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top), &format, &fbrush); } LRESULT CQUITree::OnControlMessage(UINT message, WPARAM wParam, LPARAM lParam) { __super::OnControlMessage(message, wParam, lParam); switch (message) { case WM_LBUTTONDOWN: { POINT pt; pt.x = LOWORD(lParam); pt.y = HIWORD(lParam); if (HitTest(pt)) { //1.查找 CVLTree* pTreeNode = FindNodeByPoint(pt); if (pTreeNode) { //鼠标点击的不是分组,不需要进行展开 if (pTreeNode->GetChildCount() > 0) { //2.设置展开标记 BOOL bExpend = pTreeNode->IsExpend(); if (pTreeNode) pTreeNode->Expend(!bExpend); //3.重新计算坐标 CalcNodeRect(); } m_pItemSel = pTreeNode; InvalidBounds(); return S_OK; } } } break; case WM_MOUSEMOVE: { POINT pt; pt.x = LOWORD(lParam); pt.y = HIWORD(lParam); if (HitTest(pt)) { CVLTree* pTreeNode = FindNodeByPoint(pt); if (pTreeNode) { m_pItemOver = pTreeNode; InvalidBounds(); } return S_OK; } } break; } return S_FALSE; } CVLTree* CQUITree::FindNodeByPoint(POINT pt, CVLTree* pNode) { CVLTree* pFindNode = NULL; CVLTree* pTreeNode = NULL; if (pNode == NULL) pTreeNode = m_pRoot->GetFirstChild(); else pTreeNode = pNode; while (pTreeNode) { CVLNode* pNode = pTreeNode->GetNode(); RECT rc; rc.left = pNode->GetX(); rc.top = pNode->GetY(); rc.right = m_bound.right; rc.bottom = rc.top + pNode->GetHeight(); if (PtInRect(&rc, pt)) {//找到了 pFindNode = pTreeNode; break; } //如果展开了,子节点也要展开 if (pTreeNode->IsExpend()&&pTreeNode->GetFirstChild()) pFindNode = FindNodeByPoint(pt,pTreeNode->GetFirstChild()); if (pFindNode) break; pTreeNode = pFindNode->GetNextNode(pTreeNode); } return pFindNode; } void CQUITree::CalcNodeRect() { int y = m_bound.top; CalcNodeRect(m_pRoot->GetFirstChild(), y); m_iLastY = y; } /* 返回值:返回TRUE,代表结束遍历 */ BOOL CQUITree::CalcNodeRect(CVLTree* pTreeNode, int& y) { BOOL bRet = FALSE; CVLTree* pChild = pTreeNode; while (pChild) { pChild->GetNode()->SetY(y); y += m_iItemHeight; //遍历展开节点的子节点 if (pChild->IsExpend()) CalcNodeRect(pChild->GetFirstChild(), y); pChild = pTreeNode->GetNextNode(pChild); } return bRet; }<file_sep>/QUISkin/QUISkin/QUIEdit.h #ifndef QUIEDIT_H_ #define QUIEDIT_H_ #include"UIElement.h" #include"QUIWnd.h" enum enEditState { E_EditState_Normal = 1, E_EditState_Over=2, E_EditState__Focus=3, }; class QUISKIN_API CQUIEdit :public CUIElement,public CQUIWnd {//└űË├CUIElement└┤╗ŠÍĂ▒▀┐˛ public: CQUIEdit(); ~CQUIEdit(); public: void SetStyle(DWORD dwStyle); BOOL Create(const TCHAR* szEleID, const RECT& rc, HWND hWndParent, HINSTANCE hInst, IQUIEventCallBack* pCallBack = NULL); public: void SetState(enEditState eState); void SetLightColor(DWORD dwLightColor1, DWORD dwLightColor2); virtual LRESULT OnControlMessage(UINT message, WPARAM wParam, LPARAM lParam); protected: virtual void DrawBorder(Gdiplus::Graphics& grx); static LRESULT CALLBACK OnControlProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); virtual LRESULT HandleMessage(UINT message, WPARAM wparam, LPARAM lparam); virtual LPCTSTR GetWndClassName(); virtual BOOL RegisterWndClass(); protected: enEditState m_eState; DWORD m_dwLightColor1;//over DWORD m_dwLightColor2;//Focus DWORD m_dwStyle; WNDPROC m_pOldWndProc; }; #endif<file_sep>/QUISkin/Demo/Demo.cpp // Demo.cpp : 定义应用程序的入口点。 // #include "stdafx.h" #include "Demo.h" #include "MainFrame.h" #include <gdiplus.h> #define MAX_LOADSTRING 100 CMainFrame g_MainFrame; // 全局变量: HINSTANCE hInst; // 当前实例 TCHAR szTitle[MAX_LOADSTRING]; // 标题栏文本 TCHAR szWindowClass[MAX_LOADSTRING]; // 主窗口类名 Gdiplus::GdiplusStartupInput g_Gdiplus; ULONG_PTR g_GdiToken = 0; int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { // TODO: 在此放置代码。 GdiplusStartup(&g_GdiToken, &g_Gdiplus, NULL); RECT rcDrag; rcDrag.left = 0; rcDrag.right = 500; rcDrag.top = 0; rcDrag.bottom = 100; g_MainFrame.SetDragRect(rcDrag); RECT rc; rc.left = 800; rc.top = 500; rc.right = 1300; rc.bottom = 900; g_MainFrame.SetBground(L"G:\\main.png"); g_MainFrame.Create(NULL, L"QUISkin", rc, WS_POPUP, hInstance); g_MainFrame.ShowWindow(SW_SHOW); g_MainFrame.UpdateWindow(); MSG msg; // 主消息循环: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, NULL, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } Gdiplus::GdiplusShutdown(g_GdiToken); return (int)msg.wParam; } <file_sep>/QUISkin/QUISkin/QUIListh.h #ifndef QUILIST_H_ #define QUILIST_H_ #include"UIElement.h" #include"QUIScrollBar.h" #include<map> class CQUIList; class QUISKIN_API CListColunm { //列头 typedef struct _tagColunm { std::basic_string<TCHAR> name;//列名 int iWidth;//宽度 std::basic_string<TCHAR> icon;//图标 }TColunm; typedef std::map<int, TColunm> TColMap; public: CListColunm(CQUIList* pParent); ~CListColunm(); public: void Init(int iHeight, DWORD dwBackColor); void Insert(int iIndex, const TCHAR* szName, int iWidth, const TCHAR* szIcon = NULL); void Draw(Gdiplus::Graphics& grx); int GetHeight(){ return m_iHeight; }; int GetCols(){ return m_tCols.size(); }; int GetColunmWidth(int iCol); /* 功能:鼠标移到相邻两列头的中间位置,改变光标为拖动状态 */ BOOL OnMouseMove(POINT pt); /* 功能:鼠标左键按下设置拖拽状态 */ BOOL SetDrag(POINT pt); /* 功能:终止拖拽 */ BOOL CancleDrag(); protected: /* 功能:改变指定列额的宽度 参数: @iCol:列 @iSubWidth:在原宽度基础上要改变的宽度 */ void SubColWidth(int iCol, int iSubWidth); private: TColMap m_tCols; DWORD m_dwBackColor;//列头背景 int m_iHeight;//列头高度 CQUIList* m_pParent;// HCURSOR m_hOldCursor;//保存旧的光标 BOOL m_bDrag;//开启拖拽状态标识 int m_iCurCol;//获取当前列 POINT m_tDragPt; }; //行 class QUISKIN_API CListItem { typedef struct _tagItem { int iItem; std::basic_string<TCHAR> name; std::basic_string<TCHAR> icon; }TItem; typedef std::map<int, TItem> TItemMap; public: CListItem(CQUIList* pParent); ~CListItem(); public: void Insert(int iItem, const TCHAR* szName, const TCHAR* szIcon = NULL); void Draw(Gdiplus::Graphics& grx, int iItem, const RECT& rc); protected: CQUIList* m_pParent; TItemMap m_tItems; }; class QUISKIN_API CQUIList :public CUIElement, public IScrollbarCallback { typedef std::map<int, CListItem*> TListItemMap; public: CQUIList(); ~CQUIList(); public: virtual void Create(const TCHAR* szEleID, const RECT& rc, HWND hHostWnd, IQUIEventCallBack* pCallBack); /* 功能:初始化列头 */ void InitColunm(int iHeight, DWORD dwBackColor); /* 功能:插入列头项 */ void InsertColunm(int iIndex, const TCHAR* szName, int iWidth, const TCHAR* szIcon = NULL); void SetItemBackColor(DWORD dwColor1, DWORD dwColor2); void SetItemHeight(int iHeight1, int iHeight2); /* 功能:插入一行 */ void InsertItem(int iItem, const TCHAR* szName, const TCHAR* szIcon = NULL); /* 功能:设置某一列的文本 */ void SetItemText(int iItem, int iSubItem, const TCHAR* szName, const TCHAR* szIcon=NULL); virtual LRESULT OnControlMessage(UINT message, WPARAM wParam, LPARAM lParam); public: void DrawText(Gdiplus::Graphics& grx); /* 功能:根据鼠标坐标查找行 参数: @pt:鼠标坐标 返回值:返回鼠标在哪一行上面,没找到返回-1 */ int FindItemByPoint(const POINT& pt); void SetVScrollImage(const TCHAR* szImage); protected: void OnHScrollBar(const TScrollInfo* pScrollInfo); void OnVScrollBar(const TScrollInfo* pScrollInfo); void DrawItems(Gdiplus::Graphics& grx); protected: CListColunm m_Colunm; TListItemMap m_tListItem; DWORD m_dwBackColor1; DWORD m_dwBackColor2; int m_iHeight1;//正常情况下的行高 int m_iHeight2;//鼠标移上去的行高 int m_iItemCurrent;//当前选择项 int m_iItemOver;//当前鼠标移动上去的项 CQUIScrollBar m_VscrollBar;//垂直滚动条 }; #endif<file_sep>/QUISkin/QUISkin/QUITab.h #ifndef QUITAB_H_ #define QUITAB_H_ #include"QUIButton.h" #include<map> /* Tab按钮 */ class QUISKIN_API CQUITabButton :public CQUIButton { public: CQUITabButton(); ~CQUITabButton(); }; /* Tab页 */ class QUISKIN_API CQUITabPage :public CUIElement { public: CQUITabPage(); ~CQUITabPage(); }; /* Tab控件 */ enum enTabStyle { E_TabStyle_HBtn=1,//控件按钮横向排列 E_TabStyle_VBtn=2,//控件按钮纵向排列 }; class QUISKIN_API CQUITab :public CUIElement { typedef struct _tagTabItem { CQUITabButton* button; CQUITabPage* page; _tagTabItem() { memset(this, 0, sizeof(_tagTabItem)); } }TTabItem; typedef std::map<int, TTabItem> TabItemMap; public: CQUITab(); ~CQUITab(); public: void SetStyle(enTabStyle eStyle); void InsertTab(int iIndex, CQUITabButton* pTabBtn, CQUITabPage* pTabPage); protected: void ResetIndex(int iIndex); protected: TabItemMap m_tTabs; enTabStyle m_eStyle; }; #endif<file_sep>/QUISkin/QUISkin/UIElement.cpp #include"stdafx.h" #include"UIElement.h" CUIElement::CUIElement() { m_dwBackColor = 0; m_dwBackColor = 0; m_pCallBack = NULL; m_bVisible = TRUE; m_dwFontSize = 10; m_strFont = L"楷体"; } CUIElement::~CUIElement() { } void CUIElement::Create(const TCHAR* szEleID, const RECT& rc, HWND hHostWnd, IQUIEventCallBack* pCallBack) { m_hHostWnd = hHostWnd; m_pCallBack = pCallBack; if (szEleID) m_strID = szEleID; m_bound = rc; } void CUIElement::SetCaption(const TCHAR* szCaption) { if (szCaption) { m_strCaption = szCaption; } } const TCHAR*CUIElement::GetCaption() { return m_strCaption.c_str(); } void CUIElement::SetBound(const RECT& rc) { m_bound = rc; } void CUIElement::GetBound(RECT* lpRect) { if (lpRect) *lpRect = m_bound; } void CUIElement::SetID(const TCHAR* szID) { if (szID) m_strID = szID; } const TCHAR* CUIElement::GetID() { return m_strID.c_str(); } void CUIElement::SetVisible(BOOL bVisible) { m_bVisible = bVisible; } void CUIElement::SetEnable(BOOL bEnable) { m_bEnable = bEnable; } void CUIElement::SetBackColor(DWORD dwColor) { m_dwBackColor = dwColor; } void CUIElement::SetToolText(const TCHAR* szToolText) { if (szToolText) m_strToolTips = szToolText; } void CUIElement::SetBorderSize(DWORD dwBorderSize) { m_dwBorder = dwBorderSize; } void CUIElement::SetBorderColor(DWORD dwBorderColor) { m_dwBorderColor = dwBorderColor; } void CUIElement::SetBgImage(const TCHAR* szImage) { if (szImage) m_strBgImage = szImage; } void CUIElement::SetHostWnd(HWND hWnd) { m_hHostWnd = hWnd; } HWND CUIElement::GetHostWnd() { return m_hHostWnd; } void CUIElement::InvalidBounds() { ::InvalidateRect(m_hHostWnd, &m_bound, FALSE); } BOOL CUIElement::HitTest(POINT pt) { if (PtInRect(&m_bound, pt)) return TRUE; return FALSE; } BOOL CUIElement::IsVisible() { //1.直接隐藏了 if (!m_bVisible) return FALSE; //2.元素不在窗口可见范围内 RECT rcParent; ::GetClientRect(m_hHostWnd, &rcParent); RECT rcVisible; ::IntersectRect(&rcVisible, &m_bound, &rcParent);//求两个矩形的交集 if (::IsRectEmpty(&rcVisible)) return FALSE; //3.元素尺寸等于0 if (m_bound.right - m_bound.left <= 0 || m_bound.bottom - m_bound.top <= 0) return FALSE; return TRUE; } void CUIElement::DrawBkColor(Gdiplus::Graphics& grx) { if (m_dwBackColor) { Gdiplus::SolidBrush hbr(Gdiplus::Color(255, GetRValue(m_dwBackColor), GetGValue(m_dwBackColor), GetBValue(m_dwBackColor))); grx.FillRectangle(&hbr, Gdiplus::Rect(m_bound.left, m_bound.top, m_bound.right - m_bound.left, m_bound.bottom - m_bound.top)); } } void CUIElement::DrawBkImage(Gdiplus::Graphics& grx) { if (m_strBgImage.length() <= 0) return; Gdiplus::Image im(m_strBgImage.c_str()); grx.DrawImage(&im, Gdiplus::Rect(m_bound.left, m_bound.top, m_bound.right - m_bound.left, m_bound.bottom - m_bound.top)); } void CUIElement::DrawStatusImage(Gdiplus::Graphics& grx) { //留给子类重写 } void CUIElement::DrawText(Gdiplus::Graphics& grx) { if (m_strCaption.length()) { //字体背景透明 HDC hdc = grx.GetHDC(); ::SetBkMode(hdc, TRANSPARENT); grx.ReleaseHDC(hdc); Gdiplus::SolidBrush hbr(Gdiplus::Color(255, (BYTE)m_dwTextColor >> 16, (BYTE)m_dwTextColor >> 8, BYTE(m_dwTextColor))); Gdiplus::FontFamily family(m_strFont.c_str()); Gdiplus::Font font(&family, m_dwFontSize); Gdiplus::Status stat = grx.DrawString(m_strCaption.c_str(), m_strCaption.length(), &font, Gdiplus::PointF(m_bound.left, m_bound.top), &hbr); if (stat != Gdiplus::Ok) int i = 0; } } void CUIElement::DrawBorder(Gdiplus::Graphics& grx) { if (m_dwBorder != 0) { Gdiplus::Pen pen(Gdiplus::Color(255, GetRValue(m_dwBorderColor), GetGValue(m_dwBorderColor), GetBValue(m_dwBorderColor)), m_dwBorder); grx.DrawRectangle(&pen, Gdiplus::Rect(m_bound.left, m_bound.top, m_bound.right - m_bound.left, m_bound.bottom - m_bound.top)); } } void CUIElement::DoPaint(Gdiplus::Graphics& grx) { //判断是否可见 if (!IsVisible()) return; //1.绘制背景颜色 DrawBkColor(grx); //2.绘制背景图 DrawBkImage(grx); //3.绘制状态图 DrawStatusImage(grx); //4.绘制文本 DrawText(grx); //5.绘制边框 DrawBorder(grx); } LRESULT CUIElement::OnControlMessage(UINT message,WPARAM wParam, LPARAM lParam) { return S_FALSE; } void CUIElement::SetFontSize(DWORD dwFontSize) { m_dwFontSize = dwFontSize; } void CUIElement::SetFamily(const TCHAR* szFamily) { if (szFamily) m_strFont = szFamily; } void CUIElement::SetTextColor(DWORD dwTxtColor) { m_dwTextColor = dwTxtColor; }<file_sep>/QUISkin/Demo/MainFrame.cpp #include "stdafx.h" #include "MainFrame.h" CMainFrame::CMainFrame() { } CMainFrame::~CMainFrame() { } LPCTSTR CMainFrame::GetWndClassName() { return L"XUIMainFrame"; } void CMainFrame::OnDestoryWindow(WPARAM wParam, LPARAM lParam) { PostQuitMessage(0); } void CMainFrame::OnCreate(WPARAM wParam, LPARAM lParam) { RECT rcWnd; GetClientRect(&rcWnd); RECT rc; rc.left = 10; rc.top = 32; rc.right = rcWnd.right-20; rc.bottom = rcWnd.bottom-10; m_List.Create(L"IDC_LIST", rc, m_hWnd, this); m_List.SetBackColor(RGB(255, 255, 255)); m_List.SetBorderColor(RGB(0, 0, 255)); m_List.SetBorderSize(1); m_List.InitColunm(32, RGB(0xa2, 0xa2, 0xa2)); m_List.InsertColunm(0, L"姓名", 100, NULL); m_List.InsertColunm(1, L"电话", 100, NULL); m_List.InsertColunm(2, L"地址", 200, NULL); m_List.SetItemBackColor(RGB(230, 0, 255), RGB(255, 111, 0)); m_List.SetItemHeight(32, 36); m_List.SetTextColor(RGB(0, 255, 0)); m_List.SetVScrollImage(L"E:\\win32\\QUISkin\\Bin\\Debug\\Skin\\Image\\Pub_vsrcoll.png"); for (int i = 0; i < 30; i++) { TCHAR szName[20] = { 0 }; wsprintf(szName, L"Text%d", i); m_List.InsertItem(i, szName); m_List.SetItemText(i, 1, L"1806632312"); m_List.SetItemText(i, 2, L"美国"); } m_BtnClose.SetStateImage(L"G:\\Window_btn_close.png", 5); rc.left = rcWnd.right - 23; rc.top = 5; rc.right = rc.left + 18; rc.bottom = rc.top + 18; m_BtnClose.Create(L"IDC_CLOSE", rc, m_hWnd, this); } void CMainFrame::OnPaint(WPARAM wParam, LPARAM lParam) { __super::OnPaint(wParam, lParam); /*PAINTSTRUCT pcs; HDC hdc = BeginPaint(m_hWnd, &pcs); RECT rc; GetClientRect(&rc); ::FillRect(hdc, &rc, CreateSolidBrush(RGB(0, 0, 255))); ::EndPaint(m_hWnd, &pcs);*/ } void CMainFrame::OnSize(WPARAM wParam, LPARAM lParam) { /*RECT rcClient; GetClientRect(m_hWnd, &rcClient); rcClient.right -= 20; rcClient.bottom -= 20; m_Child.MoveWindow(rcClient, TRUE);*/ } void CMainFrame::OnNotifyCmd(CUIElement* pElement) { StdString strID = pElement->GetID(); if (strID.compare(m_BtnClose.GetID()) == 0) { PostMessage(m_hWnd, WM_CLOSE, 0, 0); return; } //判断按下了哪个按钮 StdString strCaption = pElement->GetCaption(); MessageBox(m_hWnd, strCaption.c_str(), L"点击事件", MB_OK); } void CMainFrame::OnPaintControl(Gdiplus::Graphics& grx) { m_List.DoPaint(grx); m_BtnClose.DoPaint(grx); } LRESULT CMainFrame::HandleMessage(UINT message, WPARAM wParam, LPARAM lParam) { if (m_List.OnControlMessage(message, wParam, lParam) == S_OK) return S_OK; if (m_BtnClose.OnControlMessage(message, wParam, lParam) == S_OK) return S_OK; return __super::HandleMessage(message, wParam, lParam); } <file_sep>/QUISkin/QUISkin/QUIButton.cpp #include"stdafx.h" #include"QUIButton.h" CQUIButton::CQUIButton() { m_iStateCount = 4; m_eState = E_BtnState_Normal; } CQUIButton::~CQUIButton() { } void CQUIButton::SetStateImage(const TCHAR* szImage, int iStateCount) { if (szImage) { m_strStateImage = szImage; m_iStateCount = iStateCount; } } void CQUIButton::SetState(enButtonState eState) { m_eState = eState; OnChangeState(); } void CQUIButton::OnChangeState() { InvalidBounds();//置无效区域 } void CQUIButton::DrawStatusImage(Gdiplus::Graphics& grx) { if (m_strStateImage.length() <= 0) return; //1.加载图片 Gdiplus::Image im(m_strStateImage.c_str()); //2.进行图片等分 int iLeft = im.GetWidth() / m_iStateCount*(m_eState - 1); //3.切图画状态图 //按钮本身在宿主窗口上的坐标 Gdiplus::RectF destRc(m_bound.left, m_bound.top, m_bound.right - m_bound.left, m_bound.bottom - m_bound.top); //绘图 grx.DrawImage(&im, destRc,iLeft, 0, im.GetWidth() / m_iStateCount, im.GetHeight(), Gdiplus::UnitPixel); } LRESULT CQUIButton::OnControlMessage(UINT message, WPARAM wParam, LPARAM lParam) { __super::OnControlMessage(message, wParam, lParam); switch (message) { case WM_MOUSEMOVE: {//鼠标在按钮上划过(over状态) POINT pt; pt.x = LOWORD(lParam);//低字节保存鼠标的x坐标 pt.y = HIWORD(lParam);//高字节保存鼠标的y坐标 if (HitTest(pt)) {//判断鼠标是否在按钮上面 if (m_eState != E_BtnState_Over) {//如果已经是over状态,那么无需再重绘状态,减少绘制开销 SetState(E_BtnState_Over); } return S_OK; } else {//鼠标不在我们按钮区域,恢复按钮状态 if (m_eState != E_BtnState_Normal) {//判断这个鼠标是否是上次的当前按钮 SetState(E_BtnState_Normal); } } } break; case WM_LBUTTONDOWN: {//鼠标按下 POINT pt; pt.x = LOWORD(lParam); pt.y = HIWORD(lParam); if (HitTest(pt)) { SetState(E_BtnState_Down); return S_OK; } } break; case WM_LBUTTONUP: {//鼠标抬起 POINT pt; pt.x = LOWORD(lParam); pt.y = HIWORD(lParam); if (HitTest(pt)) { if (m_pCallBack) m_pCallBack->OnNotifyCmd(this);//响应鼠标点击事件 //重置按钮状态 SetState(E_BtnState_Normal); return S_OK; } } break; } return S_FALSE; } BOOL CQUIButton::HitTest(POINT pt) { if (IsVisible()) return __super::HitTest(pt); return FALSE; }<file_sep>/QUISkin/QUISkin/QUIScrollBar.h #ifndef QUISCROLLBAR_H_ #define QUISCROLLBAR_H_ #include"UIElement.h" enum enScrollBarStyle { E_ScrollBar_HBar=1,//横向滚动条 E_ScrollBar_VBar=2,//竖向滚动条 }; enum enScrollBarState { E_ScrollBarState_Normal = 1, E_ScrollBarState_Over=2, E_ScrollBarState_Down=3, E_ScrollBarState_Disable=4, }; //做一个回调接口 typedef struct _tagScrollInfo { int iPos;//当前的位置 int iMaxPos;//最大 }TScrollInfo; class IScrollbarCallback { public: virtual void OnHScrollBar(const TScrollInfo* pScrollInfo) = 0; virtual void OnVScrollBar(const TScrollInfo* pScrollInfo) = 0; }; class QUISKIN_API CQUIScrollBar :public CUIElement { public: CQUIScrollBar(IScrollbarCallback* pCallback=NULL); ~CQUIScrollBar(); public: void SetScrollBarStyle(enScrollBarStyle eBarStyle); enScrollBarStyle GetScrollBar(); void SetStateImage(const TCHAR* szImage); void SetState(enScrollBarState eState); enScrollBarState GetState(); virtual LRESULT OnControlMessage(UINT message, WPARAM wParam, LPARAM lParam); protected: virtual void DrawStatusImage(Gdiplus::Graphics& grx); /* 功能:绘制横向滚动条 */ void DrawHScroll(Gdiplus::Graphics& grx); /* 功能:绘制竖向滚动条 */ void DrawVScroll(Gdiplus::Graphics& grx); /* 功能:获取滑块左边的坐标 */ int GetThumLeft(); /* 功能:获取滑块坐标 */ void GetThumRect( RECT& rcThum); /* 功能:获取左边/顶端按钮坐标 */ void GetLeftBtnRect(RECT& rcBtn); /* 功能:获取右边/底端按钮坐标 */ void GetRightBtnRect(RECT& rcBtn); public: void SetRang(int iRang); int GetRang(); void SetPos(int iPos); int GetPos(); protected: enScrollBarStyle m_eBarStyle; std::basic_string<TCHAR> m_strStateImage; enScrollBarState m_eState; int m_iRang;//滑动的范围 int m_iScrollPos;//滑块当前位置 m_iScrollPos/m_iRang(百分比) BOOL m_bThumPress;//鼠标按下滑块 IScrollbarCallback* m_pCallBack; }; #endif<file_sep>/QUISkin/QUISkin/QUIEdit.cpp #include"stdafx.h" #include"QUIEdit.h" #include<windowsx.h> #include<commctrl.h> CQUIEdit::CQUIEdit() { m_dwStyle = WS_CHILD | WS_VISIBLE; m_pOldWndProc = NULL; m_eState = E_EditState_Normal; } CQUIEdit::~CQUIEdit() { } void CQUIEdit::SetState(enEditState eState) { m_eState = eState; InvalidBounds(); } void CQUIEdit::SetLightColor(DWORD dwLightColor1, DWORD dwLightColor2) { m_dwLightColor1 = dwLightColor1; m_dwLightColor2 = dwLightColor2; if (m_hWnd&&m_eState != E_EditState_Normal) { InvalidBounds(); } } void CQUIEdit::DrawBorder(Gdiplus::Graphics& grx) { Gdiplus::Color clr(GetRValue(m_dwBorderColor), GetGValue(m_dwBorderColor), GetBValue(m_dwBorderColor)); if (m_eState == E_EditState_Over) clr.SetFromCOLORREF(m_dwLightColor1); else if (m_eState == E_EditState__Focus) clr.SetFromCOLORREF(m_dwLightColor2); Gdiplus::Pen pen(clr, m_dwBorder); pen.SetAlignment(Gdiplus::PenAlignmentInset); grx.DrawRectangle(&pen, m_bound.left, m_bound.top, m_bound.right - m_bound.left, m_bound.bottom - m_bound.top); } void CQUIEdit::SetStyle(DWORD dwStyle) { m_dwStyle = dwStyle; } BOOL CQUIEdit::Create(const TCHAR* szEleID, const RECT& rc, HWND hWndParent, HINSTANCE hInst, IQUIEventCallBack* pCallBack) { //1.创建元素 CUIElement::Create(szEleID, rc, hWndParent, pCallBack); //2.创建窗口 RECT rcWnd; rcWnd.left = rc.left + m_dwBorder; rcWnd.top = rc.top + m_dwBorder; rcWnd.right = rc.right - m_dwBorder; rcWnd.bottom = rc.bottom - m_dwBorder; if (!CQUIWnd::Create(hWndParent, L"", rcWnd, m_dwStyle, hInst)) return FALSE; //怎么设置字体 HFONT hFont = (HFONT)GetStockFont(DEFAULT_GUI_FONT); SendMessage(m_hWnd, WM_SETFONT, (WPARAM)hFont, 1); //3.设置自己的窗口过程 SetWindowLongPtr(m_hWnd, GWL_USERDATA, (LONG)this); SetWindowLongPtr(m_hWnd, GWL_WNDPROC, (LONG)OnControlProc); return TRUE; } LRESULT CALLBACK CQUIEdit::OnControlProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { CQUIEdit* pThis = (CQUIEdit*)GetWindowLongPtr(hWnd, GWLP_USERDATA); return pThis->HandleMessage(message, wParam, lParam); } BOOL CQUIEdit::RegisterWndClass() { WNDCLASSEX wc = { 0 }; //获取已经注册的EDIT窗口 if (!GetClassInfoEx(NULL, GetWndClassName(), &wc)) return FALSE; m_pOldWndProc = wc.lpfnWndProc;//保存edit默认的窗口过程 return TRUE; } LPCTSTR CQUIEdit::GetWndClassName() { return WC_EDIT; } LRESULT CQUIEdit::HandleMessage(UINT message, WPARAM wparam, LPARAM lparam) { //调用默认的窗口过程 switch (message) { case WM_SETFOCUS: { SetState(E_EditState__Focus); } break; case WM_KILLFOCUS: { SetState(E_EditState_Normal); } break; } return CallWindowProc(m_pOldWndProc, m_hWnd, message, wparam, lparam); } LRESULT CQUIEdit::OnControlMessage(UINT message, WPARAM wParam, LPARAM lParam) { CUIElement::OnControlMessage(message, wParam, lParam); switch (message) { case WM_MOUSEMOVE: { POINT pt; pt.x = LOWORD(lParam); pt.y = HIWORD(lParam); if (HitTest(pt)) { if (m_eState == E_EditState_Normal) SetState(E_EditState_Over); return S_OK; } else { if (m_eState == E_EditState_Over) { SetState(E_EditState_Normal); return S_OK; } } } break; } return S_FALSE; }<file_sep>/QUISkin/QUISkin/QUIScrollBar.cpp #include"stdafx.h" #include"QUIScrollBar.h" CQUIScrollBar::CQUIScrollBar(IScrollbarCallback* pCallback) :m_pCallBack(pCallback) { m_eBarStyle = E_ScrollBar_VBar; m_eState = E_ScrollBarState_Normal; m_bVisible = FALSE; m_iRang = 0; m_iScrollPos = 0; m_bThumPress = FALSE; } CQUIScrollBar::~CQUIScrollBar() { } void CQUIScrollBar::SetScrollBarStyle(enScrollBarStyle eBarStyle) { m_eBarStyle = eBarStyle; } enScrollBarStyle CQUIScrollBar::GetScrollBar() { return m_eBarStyle; } void CQUIScrollBar::SetStateImage(const TCHAR* szImage) { m_strStateImage = szImage; } void CQUIScrollBar::SetState(enScrollBarState eState) { m_eState = eState; } enScrollBarState CQUIScrollBar::GetState() { return m_eState; } void CQUIScrollBar::DrawStatusImage(Gdiplus::Graphics& grx) { //横向滚动条 if (m_eBarStyle == E_ScrollBar_HBar) { DrawHScroll(grx); } else {//竖向滚动条 DrawVScroll(grx); } } void CQUIScrollBar::DrawHScroll(Gdiplus::Graphics& grx) { Gdiplus::Image im(m_strStateImage.c_str()); //1.先绘制背景 int iLeft = im.GetWidth()/4*2; int iTop = (m_eState - 1)*im.GetHeight() / 4; grx.DrawImage(&im, Gdiplus::RectF(m_bound.left, m_bound.top, m_bound.right - m_bound.left, m_bound.bottom - m_bound.top), iLeft, iTop, im.GetWidth() / 4, im.GetHeight() / 4, Gdiplus::UnitPixel); //2.左边按钮 iLeft = 0; grx.DrawImage(&im, Gdiplus::RectF(m_bound.left, m_bound.top, m_bound.bottom - m_bound.top, m_bound.bottom - m_bound.top), iLeft, iTop, im.GetWidth() / 4, im.GetHeight() / 4, Gdiplus::UnitPixel); //3.右边按钮 iLeft = im.GetWidth() / 4; grx.DrawImage(&im, Gdiplus::RectF(m_bound.right-m_bound.bottom+m_bound.top, m_bound.top, m_bound.bottom - m_bound.top, m_bound.bottom - m_bound.top), iLeft, iTop, im.GetWidth() / 4, im.GetHeight() / 4, Gdiplus::UnitPixel); //4.画滑块 if (m_iRang <= 0) return; iLeft = im.GetWidth() / 4 * 3; //滑块在窗口上面的左边实际坐标 int iThumLeft = GetThumLeft(); grx.DrawImage(&im, Gdiplus::RectF(iThumLeft, m_bound.top, m_bound.bottom - m_bound.top, m_bound.bottom - m_bound.top), iLeft, iTop, im.GetWidth() / 4, im.GetHeight() / 4, Gdiplus::UnitPixel); } int CQUIScrollBar::GetThumLeft() { int iThumLeft = 0; double dbRate = (double)m_iScrollPos / (double)m_iRang;//百分比 if (m_eBarStyle == E_ScrollBar_HBar) {//横向滚动条 int iWidth = m_bound.right - m_bound.left - (m_bound.bottom - m_bound.top) * 3; iThumLeft = m_bound.left + dbRate*iWidth + (m_bound.bottom - m_bound.top); } else {//竖向滚动条 //计算滑块的y轴坐标 int iHeight = m_bound.bottom - m_bound.top - (m_bound.right - m_bound.left) * 3; iThumLeft = m_bound.top + (m_bound.right - m_bound.left) + dbRate*iHeight; } return iThumLeft; } void CQUIScrollBar::GetThumRect( RECT& rcThum) { if (m_eBarStyle == E_ScrollBar_VBar) { rcThum.left = m_bound.left; rcThum.top = GetThumLeft(); rcThum.right = rcThum.left + (m_bound.right - m_bound.left); rcThum.bottom = rcThum.top + (m_bound.right - m_bound.left); } else { rcThum.left = GetThumLeft(); rcThum.top = m_bound.top; rcThum.right = rcThum.left + (m_bound.bottom - m_bound.top); rcThum.bottom = rcThum.top + (m_bound.bottom - m_bound.top); } } void CQUIScrollBar::GetLeftBtnRect(RECT& rcBtn) { if (m_eBarStyle == E_ScrollBar_HBar) { rcBtn.left = m_bound.left; rcBtn.top = m_bound.top; rcBtn.right = rcBtn.left + (m_bound.bottom - m_bound.top); rcBtn.bottom = rcBtn.top + (m_bound.bottom - m_bound.top); } else { rcBtn.left = m_bound.left; rcBtn.top = m_bound.top; rcBtn.right = rcBtn.left + (m_bound.right - m_bound.left); rcBtn.bottom = rcBtn.top + (m_bound.right - m_bound.left); } } void CQUIScrollBar::GetRightBtnRect(RECT& rcBtn) { if (m_eBarStyle == E_ScrollBar_HBar) { rcBtn.left = m_bound.right - (m_bound.bottom - m_bound.top); rcBtn.top = m_bound.top; rcBtn.right = rcBtn.left + (m_bound.bottom - m_bound.top); rcBtn.bottom = rcBtn.top + (m_bound.bottom - m_bound.top); } else { rcBtn.left = m_bound.left; rcBtn.top = m_bound.bottom - (m_bound.right - m_bound.left); rcBtn.right = m_bound.right; rcBtn.bottom = m_bound.bottom; } } void CQUIScrollBar::DrawVScroll(Gdiplus::Graphics& grx) { //1.绘制背景 Gdiplus::Image im(m_strStateImage.c_str()); int iLeft = im.GetWidth() / 4 * (m_eState - 1); int iTop = im.GetHeight() / 2; grx.DrawImage(&im, Gdiplus::RectF(m_bound.left, m_bound.top, m_bound.right - m_bound.left, m_bound.bottom - m_bound.top), iLeft, iTop, im.GetWidth() / 4, im.GetHeight() / 4, Gdiplus::UnitPixel); //2.向上的箭头按钮 iTop = 0; grx.DrawImage(&im, Gdiplus::RectF(m_bound.left, m_bound.top, m_bound.right - m_bound.left, m_bound.right - m_bound.left),iLeft, iTop, im.GetWidth() / 4, im.GetHeight() / 4, Gdiplus::UnitPixel); //3.向下的箭头按钮 iTop = im.GetHeight() / 4; grx.DrawImage(&im, Gdiplus::RectF(m_bound.left, m_bound.bottom-m_bound.right+m_bound.left, m_bound.right - m_bound.left, m_bound.right - m_bound.left), iLeft, iTop, im.GetWidth() / 4, im.GetHeight() / 4, Gdiplus::UnitPixel); //4.滑块 iTop = im.GetHeight() / 4 * 3; int iThumTop = GetThumLeft(); grx.DrawImage(&im, Gdiplus::RectF(m_bound.left, iThumTop, m_bound.right - m_bound.left, m_bound.right - m_bound.left), iLeft, iTop, m_bound.right - m_bound.left, m_bound.right - m_bound.left, Gdiplus::UnitPixel); } void CQUIScrollBar::SetRang(int iRang) { m_iRang = iRang; } int CQUIScrollBar::GetRang() { return m_iRang; } void CQUIScrollBar::SetPos(int iPos) { m_iScrollPos = iPos; if (m_pCallBack) { TScrollInfo tSInfo; tSInfo.iPos = iPos; tSInfo.iMaxPos = m_iRang; if (m_eBarStyle == E_ScrollBar_HBar) m_pCallBack->OnHScrollBar(&tSInfo); else m_pCallBack->OnVScrollBar(&tSInfo); } InvalidBounds(); } int CQUIScrollBar::GetPos() { return m_iScrollPos; } LRESULT CQUIScrollBar::OnControlMessage(UINT message, WPARAM wParam, LPARAM lParam) { __super::OnControlMessage(message, wParam, lParam); //滚动条禁用状态,不响应鼠标事件 if (m_eState == E_ScrollBarState_Disable) return S_FALSE; switch (message) { case WM_LBUTTONDOWN: { POINT pt; pt.x = LOWORD(lParam); pt.y = HIWORD(lParam); if (HitTest(pt)) { m_eState = E_ScrollBarState_Down; RECT rcThum; GetThumRect(rcThum); if (PtInRect(&rcThum, pt)) {//鼠标在滑块上按下 m_bThumPress=TRUE; } else { int iPos = m_iScrollPos; //先判断是否按下左边按钮 RECT rcLeftBtn; GetLeftBtnRect(rcLeftBtn); RECT rcRightBtn; GetRightBtnRect(rcRightBtn); if (PtInRect(&rcLeftBtn, pt)) {//点击了左边按钮 iPos -= 5; } //判断是否按下右边按钮 else if (PtInRect(&rcRightBtn, pt)) {//点击了右边按钮 iPos += 5; } else {//点击了滚动条空白的背景区域 if (m_eBarStyle == E_ScrollBar_HBar) { if (pt.x > rcThum.left) iPos += m_iRang/5; else iPos -= m_iRang / 5; } else { if (pt.y > rcThum.top) iPos += m_iRang / 5; else iPos -= m_iRang / 5; } } if (iPos < 0) iPos = 0; else if (iPos>m_iRang) iPos = m_iRang; SetPos(iPos); return S_OK; } InvalidBounds(); return S_OK; } } break; case WM_LBUTTONUP: { POINT pt; pt.x = LOWORD(lParam); pt.y = HIWORD(lParam); //if (m_bThumPress) { if (HitTest(pt)) m_eState = E_ScrollBarState_Over; else m_eState = E_ScrollBarState_Normal; InvalidBounds(); } m_bThumPress = FALSE; } break; case WM_MOUSEMOVE: { POINT pt; pt.x = LOWORD(lParam); pt.y = HIWORD(lParam); if (m_bThumPress) { int iPos = 0; double dbSub = 0; double dbWidth = 0; if (m_eBarStyle == E_ScrollBar_HBar) { dbSub = pt.x - m_bound.left; dbWidth = m_bound.right - m_bound.left - (m_bound.bottom - m_bound.top) * 3; } else { dbSub = pt.y - m_bound.top; dbWidth = m_bound.bottom - m_bound.top - (m_bound.right - m_bound.left) * 3; } iPos = dbSub / dbWidth*m_iRang; if (iPos < 0) iPos = 0; else if (iPos>m_iRang) iPos = m_iRang; SetPos(iPos); return S_OK; } if (HitTest(pt)) { m_eState = E_ScrollBarState_Over; InvalidBounds(); return S_OK; } else { if (m_eState != E_ScrollBarState_Normal&&m_eState != E_ScrollBarState_Disable) {//移出去,状态恢复回去 m_eState = E_ScrollBarState_Normal; InvalidBounds(); return S_OK; } } } break; } return S_FALSE; }<file_sep>/QUISkin/QUISkin/QUIListcpp.cpp #include"stdafx.h" #include"QUIListh.h" //////////////////////////// //列表头 CListColunm::CListColunm(CQUIList* pParent) :m_pParent(pParent) { } CListColunm::~CListColunm() { } void CListColunm::Init(int iHeight, DWORD dwBackColor) { m_iHeight = iHeight; m_dwBackColor = dwBackColor; } void CListColunm::Insert(int iIndex, const TCHAR* szName, int iWidth, const TCHAR* szIcon) { TColunm tCol; if (szName) tCol.name = szName; tCol.iWidth = iWidth; if (szIcon) tCol.icon = szIcon; m_tCols[iIndex] = tCol; } int CListColunm::GetColunmWidth(int iCol) { TColMap::iterator it = m_tCols.find(iCol); if (it == m_tCols.end()) return 0; return (*it).second.iWidth; } void CListColunm::Draw(Gdiplus::Graphics& grx) { //计算区域 RECT rcParent; m_pParent->GetBound(&rcParent); //1.画背景 Gdiplus::SolidBrush fillbrush(Gdiplus::Color(GetRValue(m_dwBackColor), GetGValue(m_dwBackColor), GetBValue(m_dwBackColor))); grx.FillRectangle(&fillbrush, rcParent.left, rcParent.top, rcParent.right - rcParent.left, m_iHeight); //2.画列表头 Gdiplus::FontFamily family(L"宋体"); Gdiplus::Font font(&family, 10); DWORD dwTxtColor = m_pParent->GetTextColor(); Gdiplus::SolidBrush fbrush(Gdiplus::Color(GetRValue(dwTxtColor), GetGValue(dwTxtColor), GetBValue(dwTxtColor))); //文本对齐格式 Gdiplus::StringFormat format; format.SetAlignment(Gdiplus::StringAlignmentNear); format.SetLineAlignment(Gdiplus::StringAlignmentFar); int iLeft = rcParent.left; TColMap::iterator it = m_tCols.begin(); while (it != m_tCols.end()) { //图标没画 if ((*it).second.iWidth != 0) { Gdiplus::RectF rcTxt(iLeft, rcParent.top, (*it).second.iWidth, m_iHeight); grx.DrawString((*it).second.name.c_str(), (*it).second.name.length(), &font, rcTxt, &format, &fbrush); iLeft += (*it).second.iWidth;//下一个列头的左边 //画一根线 Gdiplus::Pen pen(Gdiplus::Color(0xf2, 0xf2, 0xf2), 1); grx.DrawLine(&pen, Gdiplus::Point(iLeft, rcParent.top + 4), Gdiplus::Point(iLeft, rcParent.top + m_iHeight - 4)); } ++it; } } BOOL CListColunm::OnMouseMove(POINT pt) { RECT rcCol; m_pParent->GetBound(&rcCol); rcCol.bottom = rcCol.top + m_iHeight; //光标是否在列头区域 if (!PtInRect(&rcCol, pt)) { //光标不在列头区域,恢复就光标 if (m_hOldCursor) { SetClassLong(m_pParent->GetHostWnd(), GCL_HCURSOR, (LONG)m_hOldCursor); m_hOldCursor = NULL; } } if (m_bDrag) {//当前在拖拽状态 int iSubWidth = pt.x - m_tDragPt.x;//计算拖拽距离 //改变当前拖拽列的宽度 SubColWidth(m_iCurCol, iSubWidth); m_tDragPt = pt; return TRUE; } //判断光标在哪个列 int iLeft = rcCol.left; TColMap::iterator it = m_tCols.begin(); while (it != m_tCols.end()) { rcCol.left =iLeft+ (*it).second.iWidth - 2; rcCol.right = rcCol.left + 4; if (PtInRect(&rcCol, pt)) { if (m_hOldCursor == NULL) m_hOldCursor = (HCURSOR)SetClassLong(m_pParent->GetHostWnd(), GCL_HCURSOR, (LONG)LoadCursor(nullptr, IDC_SIZEWE)); return TRUE; } iLeft += (*it).second.iWidth; ++it; } //不在两列之间,恢复旧光标 if (m_hOldCursor) { SetClassLong(m_pParent->GetHostWnd(), GCL_HCURSOR, (LONG)m_hOldCursor); m_hOldCursor = NULL; } return FALSE; } BOOL CListColunm::SetDrag(POINT pt) { RECT rcCol; m_pParent->GetBound(&rcCol); rcCol.bottom = rcCol.top + m_iHeight; //光标是否在我们列头区域 if (!PtInRect(&rcCol, pt)) { m_bDrag = FALSE; return FALSE; } int iLeft = rcCol.left; TColMap::iterator it = m_tCols.begin(); while (it != m_tCols.end()) { rcCol.left = iLeft + (*it).second.iWidth - 2; rcCol.right = rcCol.left + 4; if (PtInRect(&rcCol, pt)) {//找到了,开启拖拽状态 m_bDrag = TRUE; //如果后面一个列的宽度为0,我们要优先拖后面一列 TColMap::iterator tmpIt = it; ++tmpIt; if (tmpIt != m_tCols.end() && (*tmpIt).second.iWidth == 0) it = tmpIt; m_iCurCol = (*it).first; m_tDragPt = pt; return TRUE; } iLeft += (*it).second.iWidth; ++it; } m_bDrag = FALSE; return FALSE; } void CListColunm::SubColWidth(int iCol, int iSubWidth) { TColMap::iterator it = m_tCols.find(iCol); if (it == m_tCols.end()) return; (*it).second.iWidth += iSubWidth; if ((*it).second.iWidth < 0) (*it).second.iWidth = 0; } BOOL CListColunm::CancleDrag() { if (m_bDrag) { m_bDrag = FALSE; if (m_hOldCursor) { SetClassLong(m_pParent->GetHostWnd(), GCL_HCURSOR, (LONG)m_hOldCursor); m_hOldCursor = NULL; } return TRUE; } return FALSE; } ////////////////// //行 CListItem::CListItem(CQUIList* pParent) :m_pParent(pParent) { } CListItem::~CListItem() { } void CListItem::Insert(int iItem, const TCHAR* szName, const TCHAR* szIcon) { TItem tItem; tItem.iItem = iItem; if (szName) tItem.name = szName; if (szIcon) tItem.icon = szIcon; m_tItems[iItem] = tItem; } void CListItem::Draw(Gdiplus::Graphics& grx, int iItem, const RECT& rc) { if (rc.left == rc.right) return; TItemMap::iterator it = m_tItems.find(iItem); if (it == m_tItems.end()) return; //创建字体 Gdiplus::FontFamily family(m_pParent->GetFamily()); Gdiplus::Font font(&family, m_pParent->GetFontSize()); //文本对齐风格 Gdiplus::StringFormat format; format.SetAlignment(Gdiplus::StringAlignmentNear); format.SetLineAlignment(Gdiplus::StringAlignmentCenter); //画刷 DWORD dwTxtColor = m_pParent->GetTextColor(); Gdiplus::SolidBrush fbrush(Gdiplus::Color(GetRValue(dwTxtColor), GetGValue(dwTxtColor), GetBValue(dwTxtColor))); //画文字 grx.DrawString((*it).second.name.c_str(), (*it).second.name.length(), &font, Gdiplus::RectF(rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top), &format, &fbrush); } //////////////////////////////// //列表框 CQUIList::CQUIList() :m_Colunm(this), m_VscrollBar(this) { m_iItemCurrent = -1; m_iItemOver = -1; m_VscrollBar.SetScrollBarStyle(E_ScrollBar_VBar); } CQUIList::~CQUIList() { } void CQUIList::Create(const TCHAR* szEleID, const RECT& rc, HWND hHostWnd, IQUIEventCallBack* pCallBack) { CUIElement::Create(szEleID, rc, hHostWnd, pCallBack); RECT rcScroll; rcScroll.left = m_bound.right - 16; rcScroll.top = m_bound.top; rcScroll.right = rcScroll.left+16; rcScroll.bottom = m_bound.bottom; m_VscrollBar.Create(NULL, rcScroll, hHostWnd, pCallBack); } void CQUIList::InitColunm(int iHeight, DWORD dwBackColor) { m_Colunm.Init(iHeight, dwBackColor); } void CQUIList::InsertColunm(int iIndex, const TCHAR* szName, int iWidth, const TCHAR* szIcon) { m_Colunm.Insert(iIndex, szName, iWidth, szIcon); } void CQUIList::DrawText(Gdiplus::Graphics& grx) { m_Colunm.Draw(grx); size_t count = m_tListItem.size(); int iTotalHeight = count * m_iHeight1 ; if (m_iItemCurrent != -1) iTotalHeight += (m_iHeight2 - m_iHeight1); if (m_iItemOver != -1) iTotalHeight += (m_iHeight2 - m_iHeight1); Gdiplus::Bitmap membmp(m_bound.right - m_bound.left, iTotalHeight); Gdiplus::Graphics* pGrx = Gdiplus::Graphics::FromImage(&membmp); DrawItems(*pGrx); int iY = 0; if (m_VscrollBar.IsVisible()) { iY = m_VscrollBar.GetPos(); } int iWidth = m_bound.right - m_bound.left; int iHeight = m_bound.bottom - m_bound.top - m_Colunm.GetHeight(); grx.DrawImage(&membmp, m_bound.left, m_bound.top + m_Colunm.GetHeight(), 0, iY, iWidth, iHeight, Gdiplus::UnitPixel); delete pGrx; pGrx = NULL; m_VscrollBar.DoPaint(grx); } void CQUIList::DrawItems(Gdiplus::Graphics& grx) { //画行 int iTop = 0; TListItemMap::iterator it = m_tListItem.begin(); while (it != m_tListItem.end()) { DWORD dwColor = m_dwBackColor; int iHeight = m_iHeight1; if (m_iItemCurrent == (*it).first) { dwColor = m_dwBackColor2; iHeight = m_iHeight2; } else if (m_iItemOver == (*it).first) { dwColor = m_dwBackColor1; iHeight = m_iHeight2; } //计算行的坐标 RECT rcItem; rcItem.left = 0; rcItem.top = iTop; rcItem.right = m_bound.right - m_bound.left; rcItem.bottom = iTop + iHeight; Gdiplus::SolidBrush fillbrush(Gdiplus::Color(GetRValue(dwColor), GetGValue(dwColor), GetBValue(dwColor))); grx.FillRectangle(&fillbrush, Gdiplus::Rect(rcItem.left, rcItem.top, rcItem.right - rcItem.left, rcItem.bottom - rcItem.top)); Gdiplus::Pen pen(Gdiplus::Color(99, GetRValue(m_dwTextColor), GetGValue(m_dwTextColor), GetBValue(m_dwTextColor))); grx.DrawRectangle(&pen, Gdiplus::Rect(rcItem.left, rcItem.top, rcItem.right - rcItem.left, rcItem.bottom - rcItem.top)); int iLeft = rcItem.left; int iCols = m_Colunm.GetCols(); for (int i = 0; i < iCols; i++) { RECT rcSubItem; rcSubItem.left = iLeft; rcSubItem.top = rcItem.top; rcSubItem.right = iLeft + m_Colunm.GetColunmWidth(i); rcSubItem.bottom = rcItem.bottom; (*it).second->Draw(grx, i, rcSubItem); iLeft += m_Colunm.GetColunmWidth(i); } ++it; iTop += iHeight; } } void CQUIList::SetItemBackColor(DWORD dwColor1, DWORD dwColor2) { m_dwBackColor1 = dwColor1; m_dwBackColor2 = dwColor2; } void CQUIList::SetItemHeight(int iHeight1, int iHeight2) { m_iHeight1 = iHeight1; m_iHeight2 = iHeight2; } void CQUIList::InsertItem(int iItem, const TCHAR* szName, const TCHAR* szIcon) { CListItem* pListItem = new CListItem(this); pListItem->Insert(0, szName, szIcon); m_tListItem[iItem] = pListItem; size_t count = m_tListItem.size(); int iTotalHeight = count* m_iHeight1; if (m_iItemCurrent != -1) iTotalHeight += (m_iHeight2 - m_iHeight1); if (m_iItemOver != -1) iTotalHeight += (m_iHeight2 - m_iHeight1); if (iTotalHeight > m_bound.bottom - m_bound.top - m_Colunm.GetHeight()) { m_VscrollBar.SetRang(iTotalHeight - (m_bound.bottom - m_bound.top )*3/4); m_VscrollBar.SetVisible(TRUE); } } void CQUIList::SetItemText(int iItem, int iSubItem, const TCHAR* szName, const TCHAR* szIcon) { TListItemMap::iterator it = m_tListItem.find(iItem); if (it == m_tListItem.end()) return; (*it).second->Insert(iSubItem, szName, szIcon); } LRESULT CQUIList::OnControlMessage(UINT message, WPARAM wParam, LPARAM lParam) { __super::OnControlMessage(message, wParam, lParam); if (m_VscrollBar.OnControlMessage(message, wParam, lParam) == S_OK) return S_OK; switch (message) { case WM_MOUSEMOVE: { POINT pt; pt.x = LOWORD(lParam); pt.y = HIWORD(lParam); if (HitTest(pt)) { if (m_Colunm.OnMouseMove(pt)) { InvalidBounds(); return S_OK; } int Item = FindItemByPoint(pt); if (Item >=0) { m_iItemOver = Item; InvalidBounds(); } return S_OK; } } break; case WM_LBUTTONDOWN: { POINT pt; pt.x = LOWORD(lParam); pt.y = HIWORD(lParam); if (HitTest(pt)) { if (m_Colunm.SetDrag(pt)) return S_OK; int Item = FindItemByPoint(pt); if (Item >= 0) { m_iItemCurrent = Item; InvalidBounds(); } return S_OK; } } break; case WM_LBUTTONUP: { if (m_Colunm.CancleDrag()) return S_OK; } break; } return S_FALSE; } int CQUIList::FindItemByPoint(const POINT& pt) { int Item = -1; int iTop = m_bound.top + m_Colunm.GetHeight(); TListItemMap::iterator it = m_tListItem.begin(); int iPos = m_VscrollBar.GetPos(); int iTotalHeight = 0; while (it != m_tListItem.end()) { int iHeight = m_iHeight1; if (m_iItemCurrent == (*it).first || m_iItemOver == (*it).first) iHeight = m_iHeight2; iTotalHeight += iHeight; if (iTotalHeight >= iPos) {//只比较在控件可见范围之内的行 RECT rcItem; rcItem.left = m_bound.left; rcItem.top = iTop; rcItem.right = m_bound.right; rcItem.bottom = iTop + iHeight; if (PtInRect(&rcItem, pt)) { Item = (*it).first; break; } iTop += iHeight; } ++it; //下一行的Y轴坐标超过控件的最低端,遍历结束 if (iTop >= m_bound.bottom) break; } return Item; } void CQUIList::OnHScrollBar(const TScrollInfo* pScrollInfo) { } void CQUIList::OnVScrollBar(const TScrollInfo* pScrollInfo) { InvalidBounds(); } void CQUIList::SetVScrollImage(const TCHAR* szImage) { m_VscrollBar.SetStateImage(szImage); }<file_sep>/QUISkin/QUISkin/QUIButton.h #ifndef QUIBUTTON_H_ #define QUIBUTTON_H_ #include"UIElement.h" enum enButtonState { E_BtnState_Normal = 1,//正常 E_BtnState_Over=2,//鼠标移上去 E_BtnState_Down=3,//鼠标按下 E_BtnState_Disable = 4,//鼠标不可用 E_BtnState_Focus=5,//获取焦点 }; class QUISKIN_API CQUIButton :public CUIElement { public: CQUIButton(); ~CQUIButton(); public: void SetStateImage(const TCHAR* szImage, int iStateCount = 4); /* 功能:设置按钮状态 */ void SetState(enButtonState eState); //判断鼠标点是否在元素区域内 virtual BOOL HitTest(POINT pt); protected: virtual void DrawStatusImage(Gdiplus::Graphics& grx); void OnChangeState(); public: virtual LRESULT OnControlMessage(UINT message, WPARAM wParam, LPARAM lParam); private: enButtonState m_eState;//鼠标状态 UINT m_iStateCount;//按钮有几种状态 StdString m_strStateImage;//按钮状态图 }; #endif
bd59646bcbae7a8e103e8debe110847e6c528cbe
[ "Markdown", "C++" ]
23
C++
hongning666/MyUILib
1b71ad6f2342cc6f66e440a436a144f0e6c1ed8d
080780ea9042ee68256d57f1b838c8a7c5c17fb5
refs/heads/master
<repo_name>garyld1962/go_rules_engine<file_sep>/README.md # go_rules_engine A basic rules / predicate engine in go <file_sep>/evaluator.go package rules import "fmt" // Evaluator ... type Evaluator interface { Evaluate(ex Expression) (bool, error) } // ValueExpressionEvaluator ... type ValueExpressionEvaluator struct { } // Evaluate ... func (ve ValueExpressionEvaluator) Evaluate(ex Expression) (bool, error) { e := ex.(ValueExpression) fmt.Println(e.Operator) switch e.Operator { case "IsEqualTo": return equals(e.Value, e.Target), nil case "IsNotEqualTo": return !equals(e.Value, e.Target), nil case "IsGreater": r, err := isGreater(e.Value, e.Target) if err != nil { return false, err } return r, nil case "IsGreaterThanOrEquals": r, err := isGreaterOrEqual(e.Target, e.Value) if err != nil { return false, err } return r, nil case "IsLessThanOrEquals": r, err := isLessOrEqual(e.Target, e.Value) if err != nil { return false, err } return r, nil case "IsLessThan": r, err := isGreater(e.Value, e.Target) if err != nil { return false, err } return !r, nil case "IsNull": return isNull(e.Value, e.Target) case "IsNotNull": return isNotNull(e.Value, e.Target) case "IsFalse": return isFalse(e.Value, e.Target) case "IsTrue": return isTrue(e.Value, e.Target) case "StartsWith": return startsWith(e.Value, e.Target) case "EndsWith": return endsWith(e.Value, e.Target) case "Contains": return contains(e.Value, e.Target) case "In": r := in(e.Value, e.Target) return r, nil case "NotIn": r := !in(e.Value, e.Target) return r, nil default: } panic("undefined Operator " + e.Operator) } <file_sep>/operator.go package rules //go:generate stringer -type=Operator type Operator int const ( IsEqualTo Operator = iota IsNotEqualTo IsGreaterThan In NotIn IsLessThan IsGreaterThanOrEqualTo IsLessThanOrEqualTo IsLike IsNotLike IsNull IsNotNull )<file_sep>/evaluator_test.go package rules_test import ( . "bce/rules" //"testing" //"github.com/stretchr/testify/assert" ) var eval = ValueExpressionEvaluator{} /* func TestIsNull(t *testing.T) { tt := ValueExpression{"IsNull", "", "one", ""} ret, _ := eval.Evaluate(tt) assert.True(t, ret, "Target should have been null") } func TestIsNotNull(t *testing.T) { tt := ValueExpression{"IsNotNull", "", "one", "two"} ret, _ := eval.Evaluate(tt) assert.True(t, ret, "Target should be null") } func TestIsEqualString(t *testing.T) { tt := ValueExpression{"IsEqualTo", "", "one", "one"} ret, _ := eval.Evaluate(tt) assert.True(t, ret, "Source and Target strings should be equal") } func TestIsEqualStringFalse(t *testing.T) { tt := ValueExpression{"IsEqualTo", "", "one", "two"} ret, _ := eval.Evaluate(tt) assert.False(t, ret, "Source and Target strings should not be equal") } func TestIsNotEqualString(t *testing.T) { tt := ValueExpression{"IsNotEqualTo", "", "one", "two"} ret, _ := eval.Evaluate(tt) assert.True(t, ret, "Source and Target strings should be equal") } func TestIsEqualNumeric(t *testing.T) { tt := ValueExpression{"IsEqualTo", "", "1", "1"} ret, _ := eval.Evaluate(tt) assert.True(t, ret, "Source and Target numbers should be equal") } func TestIsEqualNumericFalse(t *testing.T) { tt := ValueExpression{"IsEqualTo", "", "1", "2"} ret, _ := eval.Evaluate(tt) assert.False(t, ret, "Source and Target numbers should be equal") } func TestIsGreaterThan(t *testing.T) { tt := ValueExpression{"IsGreater", "", "3", "1"} ret, _ := eval.Evaluate(tt) assert.True(t, ret, "Source should be greater than Target") } /* func TestIsGreaterThanOrEqualTo(t *testing.T) { tt := ValueExpression{"IsGreaterThanOrEqualTo", "", "3", "1"} ret, _ := eval.Evaluate(tt) assert.True(t, ret, "Source should be greater than or equal to Target") } func TestIsGreaterThanOrEqualToEquals(t *testing.T) { tt := ValueExpression{"IsGreaterThanOrEqualTo", "", "3", "3"} st := ValueExpression{"IsGreaterThanOrEqualTo", "", "2", "3"} ret, _ := eval.Evaluate(tt) assert.True(t, ret, "Source should be greater than or equal to Target") ret1, _ := eval.Evaluate(st) assert.False(t, ret1, "Source should be greater than or equal to Target") } */ <file_sep>/andexpressionevaluator.go package rules type AndExpressionEvaluator struct { } func (a AndExpressionEvaluator) Evaluate(ex Expression) (bool, error) { return true, nil }<file_sep>/utility_test.go package rules import ( "testing" //"fmt" "github.com/stretchr/testify/assert" ) func TestGetNumber(t *testing.T) { n, _ := getNumber("32") assert.Equal(t, n, float64(32)) f, err := getNumber("abc") assert.Error(t, err) assert.Equal(t, f, float64(0)) } func TestEquals (t *testing.T) { v := "test" s := "test" assert.Equal(t,v,s,"values are not equal") s = "me" assert.NotEqual(t,v,s,"values are should not be equal") } <file_sep>/ruleSet.go package rules // RuleSet ... type RuleSet struct { rules []Rule } func (r RuleSet) Add(rule Rule) { r.rules = append(r.rules, rule) } func (r RuleSet) Evalute() (bool, error) { return true, nil; } type Rule struct { expressions []*Expression } func (r Rule) Evalute() (bool, error) { /* for _, e := range r.expressions { var isTrue, err = e.evalute() if err != nil { return false, err } if !isTrue { return false, nil } }*/ return true, nil } func (r Rule) Add(expression *Expression) { r.expressions = append(r.expressions, expression) } <file_sep>/expression.go package rules type Expression interface { Evaluate() (bool, error) } type ValueExpression struct { Operator string `json:"operator"` Path string `json:"path"` Value string `json:"value"` Target string `json:"target"` } // Evaluate ... func (v ValueExpression) Evaluate() (bool, error) { return true, nil } func CreateValueExpression(operator string, path string, value string) *ValueExpression { expression := &ValueExpression{Operator: operator, Path: path, Value: value} return expression } func CreateAndExpression(e Expression) *AndExpression { a := &AndExpression{} a.expressions = make([]*Expression, 1) a.Add(&e) return a } func CreateOrExpression(e Expression) *OrExpression { o := &OrExpression{} o.expressions = make([]*Expression, 1) o.Add(&e) return o } type AndExpression struct { expressions []*Expression } func (v AndExpression) Evaluate(target interface{}) (bool, error) { return true, nil } func (v AndExpression) Add(e *Expression) { v.expressions = append(v.expressions, e) } type OrExpression struct { expressions []*Expression } func (o OrExpression) Evaluate(target interface{}) (bool, error) { return true, nil } func (v OrExpression) Add(e *Expression) { v.expressions = append(v.expressions, e) } <file_sep>/conjunction.go package rules //go:generate stringer -type=Conjunction type Conjunction int const ( And Conjunction = iota Or ) <file_sep>/expression_test.go package rules_test import ( "testing" objects "github.com/stretchr/stew/objects" ) var testData = `{ "id": 25, "zip5": 33076, "zip3": 333, "state": "FL", "country": "USA", "subtotal": 25.00, "promoamount": 1.00, "orderItems": [ { "id": 3, "productId": 34354, "quantity": 3, "warehouse": "", "name": "test product 1", "availableInventory": "", "promos": [] } ], "promos": [] }` func TestValueFromJson(t *testing.T) { m, _ := objects.NewMapFromJSON(testData) value := m.Get("country").(string) if string(value) != "USA" { t.Error("country should return USA") } } <file_sep>/utility.go package rules import ( "errors" "reflect" "regexp" "strconv" "strings" ) func in(v, t string) bool { return strings.Contains(v, t) } func equals(value, target string) bool { return value == target } func isMatch(value, target string) (bool, error) { reg, err := regexp.Compile(value) if err != nil { return false, err } return reg.MatchString(target), nil } func isGreater(v, t string) (bool, error) { var val1, val2 float64 var err error if val1, err = getNumber(v); err != nil { return false, err } if val2, err = getNumber(t); err != nil { return false, err } return val1 > val2, nil } func isGreaterOrEqual(v, t string) (bool, error) { var val1, val2 float64 var err error if val1, err = getNumber(v); err != nil { return false, err } if val2, err = getNumber(t); err != nil { return false, err } return val1 > val2, nil } func isLessOrEqual(v, t string) (bool, error) { var val1, val2 float64 var err error if val1, err = getNumber(v); err != nil { return false, err } if val2, err = getNumber(t); err != nil { return false, err } return val1 < val2, nil } func getNumber(v string) (float64, error) { n, err := strconv.ParseFloat(v, 64) if err != nil { return 0, err } return n, err } func isNull(value, target string) (bool, error) { return target == "", nil } func isNotNull(value, target string) (bool, error) { return target != "", nil } func isTrue(value, target string) (bool, error) { r, err := strconv.ParseBool(target) if err != nil { return false, err } return r, nil } func isFalse(value, target string) (bool, error) { r, err := strconv.ParseBool(target) if err != nil { return false, err } return r, nil } func contains(value, target string) (bool, error) { return strings.Contains(value, target), nil } func startsWith(value, target string) (bool, error) { return strings.HasPrefix(value, target), nil } func endsWith(value, target string) (bool, error) { return strings.HasSuffix(value, target), nil } func getInterfaceType(t interface{}) reflect.Kind { switch t.(type) { case bool: return reflect.Bool case uint8, uint16, uint32, uint64, uint: return reflect.Uint64 case int8, int16, int32, int64, int: return reflect.Int64 case float32, float64: return reflect.Float64 case string: return reflect.String default: return reflect.TypeOf(t).Kind() } } func isArray(i interface{}) bool { return reflect.TypeOf(i).Kind() == reflect.Array || reflect.TypeOf(i).Kind() == reflect.Slice } func isMap(i interface{}) bool { return reflect.TypeOf(i).Kind() == reflect.Map } func getArrayType(arr interface{}) (reflect.Type, error) { if (isArray(arr)) == false { return nil, errors.New("value is not an arry or slice") } return reflect.TypeOf(arr).Elem(), nil } func isInArray(arr, val interface{}) (bool, error) { switch reflect.TypeOf(arr).Kind() { case reflect.Slice, reflect.Array: // get the value of "target". It should not be a collection type switch val.(type) { case uint8, uint16, uint32, uint64, uint: tv := reflect.ValueOf(val).Uint() ar := reflect.ValueOf(arr) for i := 0; i < ar.Len(); i++ { el := ar.Index(i).Uint() if el == tv { return true, nil } } return false, nil case int8, int16, int32, int64, int: tv := reflect.ValueOf(val).Int() ar := reflect.ValueOf(arr) for i := 0; i < ar.Len(); i++ { el := ar.Index(i).Int() if el == tv { return true, nil } } return false, nil case float32, float64: tv := reflect.ValueOf(val).Float() ar := reflect.ValueOf(arr) for i := 0; i < ar.Len(); i++ { el := ar.Index(i).Float() if el == tv { return true, nil } } return false, nil case string: tv := reflect.ValueOf(val).String() ar := reflect.ValueOf(arr) for i := 0; i < ar.Len(); i++ { el := ar.Index(i).String() if el == tv { return true, nil } } return false, nil default: } } return true, nil } func selectValue(m map[string]interface{}, path string) interface{} { propertyNames := strings.Split(path, ".") // we only have one path element so return what we have if len(propertyNames) == 1 { return m[propertyNames[0]] } // create map using propertyName as a key and the []interface{} as a value m1 := make(map[string]interface{}) m1[propertyNames[0]] = m[propertyNames[0]] // create a new path with the remainder of the parts. newPath := strings.Join(propertyNames[2:], ",") return selectValue(m1, newPath) } func getValue(m map[string]interface{}, path string) (bool, interface{}) { propertyNames := strings.Split(path, ".") if len(propertyNames) == 1 && m[propertyNames[0]] != nil { return true, m[propertyNames[0]] } return false, nil } <file_sep>/orexpressionevaluator.go package rules type OrExpressionEvaluator struct { } func (o OrExpressionEvaluator) Evaluate(ex Expression) (bool, error) { return true, nil }
0e384ed7b183c8b3900f1958af000dcf2bcad639
[ "Markdown", "Go" ]
12
Markdown
garyld1962/go_rules_engine
74b8de008886df6e9e7be714d2e85a68fc47e85c
4478a0769ecc711178c5b8499831fc1e8b3fd944
refs/heads/master
<file_sep>/** * Fizzbuzz class * Contains three question with 9 number translatet to FizzBuzz, user should guess the 10th. * * @return publicMethod */ window.Fizzbuzz = (function(){ 'use strict'; // Local variables console.log("Starting fizzbuzz"); var points; var maxpoints; var _screenSetup; var _scoreKeeper; var pageObjects = { "title": document.getElementById("title"), "middleText": document.getElementById("middleText"), "middleButton": document.getElementById('buttonMiddle'), "buttonRed": document.getElementById('buttonRed'), "answers": document.getElementById('answers'), }; // Public method. Start test. Called from activeTest class. var publicMethod = { "startTest": function(){ console.log("Fizzbuzz start test"); points = 0; maxpoints = 9; _screenSetup = window.Test; _scoreKeeper = window.ScoreKeeper; welcome(); }, }; // Display welcome text function welcome(){ pageObjects.title.textContent = "FizzBuzz"; pageObjects.middleText.textContent = "Du kommer du att göra FizzBuzz testet. Testet kommer att presentera en nummerserie på 9 siffror." + " Den 10:e siffran skall du avgöra vad som skall stå, talet, Fizz, Buzz eller FizzBuzz."+ " Hur vet jag då vilket jag skall välja?" + " Om talet är jämt delbart med 3 så är dett Fizz ex 9/3 = 3. Buzz om talet är jämt delbart med 5 ex 25/5 = 5. Om det är jämt delbart med både 3 och 5 är det FizzBuzz ex 15/3 = 5, 15/5 = 3." + " Om inget av de tidigare stämmer så är det talet själv som skall stå. LYCKA TILL!!"; continueButton(); } /* * Display when test is finished. * Show continue button to next test. * Passes points to ScoreKeeper. */ function finishedTest(){ pageObjects.middleText.textContent = "Testet är nu klart och din poäng blev " + points; var _startB = pageObjects.buttonRed; _startB.onclick = function(){ _scoreKeeper.getInstance().setScore(points, maxpoints); _screenSetup.chooseTest("memory"); }; pageObjects.buttonRed.classList.remove('onOff'); } // Display red button to start test. function continueButton(){ var _startB = pageObjects.buttonRed; _startB.onclick = function(){ clearMiddle(); showFizzBuzz(); }; pageObjects.middleButton.appendChild(_startB); } // Clear text and buttons function clearMiddle(){ pageObjects.title.textContent = null; pageObjects.middleText.innerHTML = null; pageObjects.buttonRed.classList.add('onOff'); } // Loop to display each fizzbuzz line. function showFizzBuzz(){ var loop = 0; function runFizz(){ userChoice(fizzBuzz(), function(){ if(loop < 2){ loop+= 1; runFizz(); } else{ finishedTest(); } }); } runFizz(); } /* * Create fizzbuzz array from random start number * Stores serie of 10 + 1(numeric value) * * @return fizzbuzz array */ function fizzBuzz(){ var start = Math.floor(Math.random() * 100); console.log("Creating FizzBuzz array " + start); var resultArray = []; for(var i = start; i <= start + 9; i++){ var resultString = ""; if(i%3 === 0){ resultString += "Fizz"; } if(i%5 === 0){ resultString += "Buzz"; } if(i%3 !== 0 && i%5 !== 0){ resultString += i; } resultArray.push(resultString); } resultArray.push(i-1); return resultArray; } /* * Display fizzbuzz line and 4 buttons. * * @param {fizzArray} FizzBuzz array * @param {callback} Callback function (showFizzBuzz) runFizz */ function userChoice(fizzArray, callback){ var line = fizzArray; var nrVal = line.pop(); var corrVal = line.pop(); console.log("Correct " + corrVal + " nrVal " + nrVal); console.log("Line: " + line); pageObjects.buttonRed.classList.add('onOff'); pageObjects.middleText.textContent = line; var _answer1 = document.createElement('li'); _answer1.textContent = nrVal; _answer1.id = nrVal; _answer1.classList.add("button"); _answer1.onclick = function () { chkAnswer(nrVal, corrVal, callback); }; pageObjects.answers.appendChild(_answer1); var _answer2 = document.createElement('li'); _answer2.textContent = "Fizz"; _answer2.id = "Fizz"; _answer2.classList.add("button"); _answer2.onclick = function () { chkAnswer("Fizz", corrVal, callback); }; pageObjects.answers.appendChild(_answer2); var _answer3 = document.createElement('li'); _answer3.textContent = "Buzz"; _answer3.id = "Buzz"; _answer3.classList.add("button"); _answer3.onclick = function () { chkAnswer("Buzz", corrVal, callback); }; pageObjects.answers.appendChild(_answer3); var _answer4 = document.createElement('li'); _answer4.textContent = "FizzBuzz"; _answer4.id = "FizzBuzz"; _answer4.classList.add("button"); _answer4.onclick = function () { chkAnswer("FizzBuzz", corrVal, callback); }; pageObjects.answers.appendChild(_answer4); } /* * Check if userchoice is correct answer * * @param {answer} users answer * @param {corrAnswer} correct answer * @param {callback} callback function redirected from userChoice */ function chkAnswer(answer, corrAnswer, callback){ console.log("Chk answer " + answer + " corr " + corrAnswer); document.getElementById(corrAnswer).classList.add("corrbutton"); pageObjects.buttonRed.classList.remove("onOff"); var _button = pageObjects.buttonRed; _button.onclick = function(){ pageObjects.answers.innerHTML = null; pageObjects.middleText.innerHTML = null; if(answer.toString() === corrAnswer.toString()){ console.log("Correct answer" + points); points += 3; } callback(); }; } return publicMethod; })(); <file_sep>/** * Quiz class. * Display three questions with three answers * * @return publicMethod */ window.Quiz = (function(){ 'use strict'; console.log("Quiz loaded"); // Local variables var points; var maxpoints; var questions = []; var _test; var _scoreKeeper; var pageObjects = { "title": document.getElementById("title"), "currTest": document.getElementById("currentTest"), "middleText": document.getElementById("middleText"), "middleButton": document.getElementById('buttonMiddle'), "buttonRed": document.getElementById('buttonRed'), "answers": document.getElementById('answers'), }; // Three question pushed to array. var q = { question: "Vilken är sveriges 4:e största stad?", answer1: "Uppsala", answer2: "Helsingborg", answer3: "Malmö", correct: "Uppsala", }; questions.push(q); q = { question: "När skrevs svenska nationalsången?", answer1: "1736", answer2: "1803", answer3: "1844", correct: "1844", }; questions.push(q); q = { question: "Hur många m.ö.h är Kebnekaise?", answer1: "2104", answer2: "2196", answer3: "2252", correct: "2104", }; questions.push(q); // Public method. Start test. Called from activeTest class. var publicMethod = { "startTest": function(){ clearMiddle(); console.log("Quiz start test"); points = 0; maxpoints = 9; welcome(); _scoreKeeper = window.ScoreKeeper; _test = _test = window.Test; }, }; // Test description function welcome(){ pageObjects.title.textContent = "FRÅGESTEST"; pageObjects.middleText.classList.add("center"); pageObjects.middleText.textContent = "Du kommer nu att få tre frågor att svara på. Varje fråga har tre alternativ varav ett är rätt. LYCKA TILL!!"; pageObjects.buttonRed.classList.remove('onOff'); startTestButton(); } // Clear all text and buttons function clearMiddle(){ pageObjects.title.textContent = null; pageObjects.middleText.textContent = null; pageObjects.answers.innerHTML = null; } // Red round button pressed to begin test. function startTestButton(){ var _startB = pageObjects.buttonRed; _startB.onclick = function(){ clearMiddle(); showQuiz(); }; pageObjects.middleButton.appendChild(_startB); } // Final text after finished test. function finishedTest(){ pageObjects.middleText.textContent = "Frågetestet är nu klart. Du fick totalt " + points + " poäng." + "Klicka på knappen för att fortsätta till nästa test."; showContinueButton(); } // Loop displaying each question. function showQuiz(){ var loop = 0; function runQuiz(){ showQuestion(questions[loop], function(){ if(loop < questions.length -1){ loop+= 1; runQuiz(); } else{ finishedTest(); } }); } runQuiz(); } /* * Show red round button to continue to next test. * Passes points to ScoreKeeper onclick. */ function showContinueButton(){ var _startB = pageObjects.buttonRed; _startB.classList.remove("onOff"); _startB.onclick = function(){ clearMiddle(); _scoreKeeper.getInstance().setScore(points, maxpoints); _test.chooseTest("fizzbuzz"); }; pageObjects.middleButton.appendChild(_startB); } /* * Display question and answer buttons * @param {question} question and answer from question array * @param {callback} callback function (showQuiz)runQuiz */ function showQuestion(question, callback){ pageObjects.buttonRed.classList.add('onOff'); function loop(){ pageObjects.middleText.textContent = question.question; var _answer1 = document.createElement('li'); _answer1.textContent = question.answer1; _answer1.id = question.answer1; _answer1.classList.add("button"); _answer1.onclick = function () { chkAnswer(question.answer1, question.correct, callback); }; pageObjects.answers.appendChild(_answer1); var _answer2 = document.createElement('li'); _answer2.textContent = question.answer2; _answer2.id = question.answer2; _answer2.classList.add("button"); _answer2.onclick = function () { chkAnswer(question.answer2, question.correct, callback); }; pageObjects.answers.appendChild(_answer2); var _answer3 = document.createElement('li'); _answer3.textContent = question.answer3; _answer3.id = question.answer3; _answer3.classList.add("button"); _answer3.onclick = function () { chkAnswer(question.answer3, question.correct, callback); }; pageObjects.answers.appendChild(_answer3); } loop(); } /* * Control if answer is correct * @param {answer} users answer * @param {corrAnswer} correct answer * @param {callback} callback function runQuiz, redirected from showQuestion */ function chkAnswer(answer, corrAnswer, callback){ document.getElementById(corrAnswer.toString().trim()).classList.add("corrbutton"); pageObjects.buttonRed.classList.remove("onOff"); var _button = pageObjects.buttonRed; _button.onclick = function(){ pageObjects.answers.innerHTML = null; pageObjects.middleText.innerHTML = null; if(answer === corrAnswer){ points += 3; } callback(); }; } return publicMethod; })();<file_sep>/* * User should click or not click on objects from given rules. * * @return publicMethods */ window.Perception = (function(){ 'use strict'; // Local variables var points; var maxpoints; var startIndex; var finalIndex; var _screenSetup; var _scoreKeeper; var objectType = ["square", "circle", "triangle"]; var cssColors = ["red", "yellow", "green", "black"]; var cssColorsTriangle = ["t_red", "t_green", "t_yellow", "t_black"]; var validShapes = ["red", "square", "clicked"]; var pageObjects = { "title": document.getElementById("title"), "currTest": document.getElementById("currentTest"), "middleText": document.getElementById("middleText"), "buttonRed": document.getElementById('buttonRed'), "answers": document.getElementById('answers'), "objectHolder": document.getElementById('objectHolder'), }; // Public method. Start test. Called from activeTest class. var publicMethod = { "startTest": function(){ points = 0; maxpoints = 10; startIndex = 0; finalIndex = 9; _screenSetup = window.Test; _scoreKeeper = window.ScoreKeeper; welcome(); }, }; // Display welcome text function welcome(){ pageObjects.title.textContent = "UPPFATTNINGSFÖRMÅGA"; pageObjects.middleText.textContent = "Du ska nu få testa din uppfattningsförmåga. " + "Testet går ut på att 10 objekt kommer att visas, ett i taget under 1 sekund. " + "Du skall klicka på följande, 1) Har en annan färg än röd, 2) Har en annan form" + " än kvadrat, 3) Är röd och kvadrat. Tryck på knappen för att starta och lycka till."; var _startB = pageObjects.buttonRed; _startB.onclick = function(){ clearMiddle(); drawObjects(); showObjects(); }; } /* * Display when test is finished. * Show continue button to next test. * Passes points to ScoreKeeper. */ function endTest(){ clearMiddle(); pageObjects.middleText.textContent = "Testet är nu klart. Din poäng blev " + points + " Tryck på knappen för att komma vidare."; pageObjects.buttonRed.classList.remove('onOff'); var _startB = pageObjects.buttonRed; _startB.onclick = function(){ _scoreKeeper.getInstance().setScore(points, maxpoints); _screenSetup.chooseTest('result'); }; } // Clear text and objects function clearMiddle(){ pageObjects.title.textContent = null; pageObjects.middleText.textContent = null; pageObjects.objectHolder.innerHTML = null; pageObjects.buttonRed.classList.add("onOff"); } /* * Get random data to create object. Stored in a array * * @return array of data to create object */ function createObject(){ var objSettings = []; objSettings[0] = "shape"; objSettings[1] = getRandom(objectType); objSettings[2] = getRandom(cssColors); objSettings[3] = getRandom(cssColorsTriangle); return objSettings; } // Create object and display it for 1 sec. function drawObjects(){ window.setTimeout(function(){ var objCreate = createObject(); console.log("objcreate = " + objCreate); var _obj = document.createElement('div'); _obj.id = objCreate[0]; if(objCreate[1] === 'triangle'){ _obj.className = objCreate[1] + " " + objCreate[3]; } if(objCreate[1] !== 'triangle'){ _obj.className = objCreate[1] + " " + objCreate[2]; } _obj.onclick = function(){ _obj.classList.add('clicked'); }; pageObjects.objectHolder.appendChild(_obj); },1000); } /* * Recursiv function to display objects until startIndex reach finalIndex(number of objects to display) */ function showObjects(){ if(startIndex < finalIndex){ window.setTimeout(function(){ validClick(document.getElementById('shape')); startIndex++; pageObjects.objectHolder.innerHTML = null; drawObjects(); showObjects(); },2000); } else{ window.setTimeout(function(){ validClick(document.getElementById('shape')); endTest(); },2000); } } /* * Get a random index from incoming array * * @param {arrayType} array * @return random array index */ function getRandom(arrayType){ var ranIndex = Math.floor((Math.random() * arrayType.length)); return arrayType[ranIndex]; } // For each object that is displayed check if user clicked or not and sees if it's valid for points. function validClick(obj){ var shape = obj.classList; var clicked = shape.contains(validShapes[2]); switch(clicked){ case true: if(!shape.contains(validShapes[0]) && !shape.contains(validShapes[1]) ){ points++; } else if(shape.contains(validShapes[0]) && shape.contains(validShapes[1])){ points++; } break; case false: if(shape.contains(validShapes[0]) || shape.contains(validShapes[1]) ){ points++; } break; } console.log("points: " + points + " shape: " + shape); } return publicMethod; })(); <file_sep>/** * Singelton keep track of current test. * You can set, reset and start tests. */ window.activeTest = (function(){ 'use strict'; console.log("ActiveTest loaded"); var instance; /* * Instance of activeTest * @return public functions * @return instance of activeTest */ function createInstance() { var currTest; /* * Sets current test. * @param {test} _currtest. */ function setCurrTest(_currtest){ currTest = _currtest; } return { setTest: function(_currtest){ setCurrTest(_currtest); }, startTest: function(){ currTest.startTest(); }, resetTest: function(){ if(currTest !== null){ currTest.startTest(); } }, }; } return { getInstance: function () { if (!instance) { instance = createInstance(); } return instance; }, }; })(); /** * Singelton keep track of score */ window.ScoreKeeper = (function(){ 'use strict'; console.log("ScoreKeeper loaded"); var instance; /* * Instance of scorekeeper. * @return public methods * @return instance of ScoreKeeper */ function createInstance() { var totalScore = 0; var maxScore = 0; var scoreCounter = document.getElementById("score"); function addScore(point, maxpoints){ totalScore += point; maxScore += maxpoints; } return { setScore: function(points, maxpoints){ addScore(points, maxpoints); scoreCounter.textContent = totalScore; }, getFinalScore: function(){ return totalScore; }, getMaxScore: function(){ return maxScore; }, resetScore: function(){ totalScore = 0; maxScore = 0; scoreCounter.textContent = totalScore; }, }; } return { getInstance: function () { if (!instance) { instance = createInstance(); } return instance; }, }; })(); /** * Main function. Present welcome and end text. Initiate different tests. */ window.Test = (function(){ "use strict"; console.log("screenSetup is ready!"); // Variables var _test = window.activeTest; var _scoreKeeper = window.ScoreKeeper; var _quiz = window.Quiz; var _fizzbuzz = window.Fizzbuzz; var _memory = window.Memory; var _perception = window.Perception; var pageObjects = { "title": document.getElementById("title"), "middleText": document.getElementById("middleText"), "buttonRed": document.getElementById('buttonRed'), }; // Public methods var publicMethods = { // Start IQ test "init": function(){ pageObjects.title.textContent = "IQ Test"; pageObjects.middleText.textContent = "Detta IQ test består av 4 tester. Innan varje test kommer du få information om vad du skall göra. " + "När testet är slut kommer du få ditt slutgiltiga resultat." + "Nere till vänster ser du 4 tester, för varje test lyser en ny test upp så du vet var du är. Nere till höger ser du ditt resultat efter hand. LYCKA TILL!!"; showStartButton(); }, /* * Test choice * @param {test} test */ "chooseTest": function(test){ changeTest(test); }, // Reset active test. "reset": function(){ _test.getInstance().resetTest(); }, }; /* * Show continuebutton and start animation before test begin. */ function showStartButton(){ var _startB = document.createElement('a'); _startB.classList.add("button"); _startB.textContent = "Starta"; _startB.onclick = function(){ document.getElementById('welcome').classList.add("animSlide"); window.setTimeout(function(){ displayHUD(); startTest(); },2500); }; document.getElementById('buttonMiddle').appendChild(_startB); } // Display bottom text (Test, score) function displayHUD(){ document.getElementById("score2").classList.remove("onOff"); document.getElementById("buttonRed").classList.remove("onOff"); } /* * Start test * @default {quiz} test */ function startTest(){ pageObjects.middleText.textContent = null; document.getElementById('buttonMiddle').innerHTML = null; pageObjects.title.innerHTML = null; _scoreKeeper.getInstance().resetScore(); publicMethods.chooseTest("quiz"); } /* * Show final result of the test. * Show continuebutton if redo test. */ function showResult(){ var finalScore = _scoreKeeper.getInstance().getFinalScore(); var maxScore = _scoreKeeper.getInstance().getMaxScore(); var iq = parseInt((finalScore/maxScore) * 100); pageObjects.middleText.textContent = "Testet är nu slut. " + " Din slutgiltiga poäng blev " + finalScore + " av totalt " + maxScore + ". Det innebär att din IQ är " + iq; var _startB = pageObjects.buttonRed; _startB.onclick = function(){ _scoreKeeper.getInstance().resetScore(); clearDoneTests(); publicMethods.chooseTest("quiz"); }; } // Select all currenttest lines and reset color function clearDoneTests(){ var p = document.querySelectorAll("p.tests"); for(var i = 0; i < p.length; i++){ p[i].classList.remove('currTest'); } } /* * Switch for incoming test. * @param {test} selected test. * @return publicMethods */ function changeTest(test){ switch(test){ case "quiz": document.getElementById('t_quiz').classList.add('currTest'); _test.getInstance().setTest(_quiz); _test.getInstance().startTest(); break; case "fizzbuzz": document.getElementById('t_fizzbuzz').classList.add('currTest'); _test.getInstance().setTest(_fizzbuzz); _test.getInstance().startTest(); break; case "memory": document.getElementById('t_memory').classList.add('currTest'); _test.getInstance().setTest(_memory); _test.getInstance().startTest(); break; case "perception": document.getElementById('t_perception').classList.add('currTest'); _test.getInstance().setTest(_perception); _test.getInstance().startTest(); break; case "result": showResult(); break; } } return publicMethods; })(); /* * Initiate test. */ var page = window.Test; page.init();
3420278f59b531a8c76d8b2f166c4bcc91090066
[ "JavaScript" ]
4
JavaScript
MangeSwe/School_Project_JS
8f05bbd6b1af90579e7b497bc10501061f3ba6f4
9b288a2f697d131b10ed4412303a87f080974efc
refs/heads/master
<repo_name>writemike/meetup-unit-demo<file_sep>/go/src/unit.nginx.org/go/env.go package unit /* #cgo CFLAGS: #cgo CPPFLAGS: -I/home/mholland/unit/src -I/home/mholland/unit/build #cgo LDFLAGS: -L/home/mholland/unit/build */ import "C" <file_sep>/README.md # NGINX Unit demo for APCJ meetup - June 2020 Sorry for the small terminal font in the actual demo! Here are all the files to used to setup the demo. This demo was based on <NAME>'s Meet-up demo (https://github.com/nshadrin/2018-04-unit-demo) Here are the steps taken before the starting the demonstration: - Downloaded and compiled the NGINX Unit Source code directly from the GitHub Repo (https://github.com/nginx/unit). - Downloaded and installed all the programming languages and dependencies from the Unbuntu Repository. - Uploaded code examples for all 8 supported programming languages (PHP, Python, Perl, Go, Ruby, Node.js, Java, and Assembly). - Compiled code examples using Go and Assembly (https://unit.nginx.org/howto/samples/). While trying out NGINX Unit, please consider how NGINX Plus can not only load balance your NGINX Unit Microservices, but also secure them with JWT Authentication, validate an operational service with active health checks, and maintain state, in stateful applications, using our integrated key-value store across multiple NGINX Plus instances. Once your NGINX Unit instance has been built, add these configurations by using: ```sudo curl --unix-socket /var/run/control.unit.sock -X PUT --data-binary @./certs/certkey.pem http://localhost/certificates/demo-bundle``` ```sudo curl --unix-socket /var/run/control.unit.sock -X PUT -d @./config/full-config.json http://localhost/config``` <file_sep>/nodejs/hello-version.js #!/usr/bin/env node var node_version = require('./package').version; require("unit-http").createServer(function (req, res) { res.writeHead(200, {"Content-Type": "text/plain"}); res.end(`Hello, Node.js ${node_version} Unit!`); }).listen()
22b5037682811fcce7fa98d72c29d33ce6dad6c0
[ "Markdown", "JavaScript", "Go" ]
3
Go
writemike/meetup-unit-demo
4e6a4148d6124b6a70cd4a2ee5b2ae88d5854478
1fe41717f720c8437dbbd754f5ccc9bb1fed7208
refs/heads/master
<file_sep>package com.payments.app.seey.rapyd; import androidx.appcompat.app.AppCompatActivity; import android.net.Uri; import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; import com.payments.app.seey.App; import com.payments.app.seey.R; public class RapydPaymentActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rapyd_payment); WebView webView = findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl(getIntent().getStringExtra(App.Content)); webView.setWebViewClient(webViewClient); } WebViewClient webViewClient = new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith("https://httpstat.us/")) { finish(); return true; } return false; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); /*if (url.contains("code=")) { Uri uri = Uri.EMPTY.parse(url); String access_token = uri.getEncodedFragment(); access_token = access_token.substring(access_token.lastIndexOf("=") + 1); App.Log("Instagram key "+access_token); }*/ } }; }<file_sep>package com.payments.app.seey.rapyd; import com.payments.app.seey.action.Beneficiary; public class RapydPayoutRequest { private Beneficiary beneficiary; private String beneficiary_country; private String beneficiary_entity_type; private String description; private String payout_method_type; private String ewallet; private String payout_amount; private String payout_currency; private String sender_country; private String sender_entity_type; private String sender_currency; public RapydPayoutRequest(){} public RapydPayoutRequest(String payout_amount,Beneficiary beneficiary){ this.payout_amount = payout_amount; this.beneficiary = beneficiary; beneficiary_country= "US"; beneficiary_entity_type= "individual"; description= "desc1562234632"; payout_method_type= "us_atmdebit_card"; ewallet= "ewallet_f387ced54b1d1fb6fee948d7c908da83"; payout_currency= "USD"; sender_country= "US"; sender_currency= "USD"; sender_entity_type= "individual"; } public Beneficiary getBeneficiary() { return beneficiary; } public void setBeneficiary(Beneficiary beneficiary) { this.beneficiary = beneficiary; } public String getBeneficiary_country() { return beneficiary_country; } public void setBeneficiary_country(String beneficiary_country) { this.beneficiary_country = beneficiary_country; } public String getBeneficiary_entity_type() { return beneficiary_entity_type; } public void setBeneficiary_entity_type(String beneficiary_entity_type) { this.beneficiary_entity_type = beneficiary_entity_type; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPayout_method_type() { return payout_method_type; } public void setPayout_method_type(String payout_method_type) { this.payout_method_type = payout_method_type; } public String getEwallet() { return ewallet; } public void setEwallet(String ewallet) { this.ewallet = ewallet; } public String getPayout_amount() { return payout_amount; } public void setPayout_amount(String payout_amount) { this.payout_amount = payout_amount; } public String getPayout_currency() { return payout_currency; } public void setPayout_currency(String payout_currency) { this.payout_currency = payout_currency; } public String getSender_country() { return sender_country; } public void setSender_country(String sender_country) { this.sender_country = sender_country; } public String getSender_entity_type() { return sender_entity_type; } public void setSender_entity_type(String sender_entity_type) { this.sender_entity_type = sender_entity_type; } public String getSender_currency() { return sender_currency; } public void setSender_currency(String sender_currency) { this.sender_currency = sender_currency; } } <file_sep>package com.payments.app.seey; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.Intent; import android.graphics.PixelFormat; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.util.Base64; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.webkit.JavascriptInterface; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.google.gson.Gson; import com.payments.app.seey.action.ContributionAction; import com.payments.app.seey.action.OcrAction; import com.payments.app.seey.rapyd.RapydPaymentActivity; import com.payments.app.seey.rapyd.RapydUtils; import com.payments.app.seey.storage.db.helpers.ContributionsDBHelper; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.TimeUnit; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class PaymentsActivity extends AppCompatActivity implements View.OnClickListener{ private EditText inputEditText; private Button[] inputButtons; private int[] buttonsIds; private String amount = ""; private String userName; private String social; private ImageView userImgView; private TextView userNameTextView; private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_payments); userName = getIntent().getStringExtra(App.User); social = getIntent().getStringExtra(App.Account); userImgView = findViewById(R.id.userImgView); userNameTextView = findViewById(R.id.userNameTextView); userNameTextView.setText(userName); Glide.with(this) .load(Uri.parse(App.BucketUrl+userName.replace("@","")+social)) // or URI/path .into(userImgView ); inputEditText = findViewById(R.id.input); inputButtons = new Button[10]; buttonsIds = new int[]{ R.id.inputBtn0, R.id.inputBtn1, R.id.inputBtn2 , R.id.inputBtn3, R.id.inputBtn4, R.id.inputBtn5 , R.id.inputBtn6, R.id.inputBtn7, R.id.inputBtn8 , R.id.inputBtn9 }; for (int i=0;i<buttonsIds.length;i++) { inputButtons[i] = findViewById(buttonsIds[i]); inputButtons[i].setOnClickListener(this); } findViewById(R.id.inputBtnDot).setOnClickListener(this); findViewById(R.id.inputBtnBackspace).setOnClickListener(this); findViewById(R.id.sendMoneyBtn).setOnClickListener(this); // doPayment(); } private void loadPage(String url){ webView = findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl(url); webView.setWebViewClient(webViewClient); // webView.addJavascriptInterface(new JavaScriptInterface(this), "Android"); } public class JavaScriptInterface { Context mContext; /** Instantiate the interface and set the context */ JavaScriptInterface(Context c) { mContext = c; } /** Show a toast from the web page */ @JavascriptInterface public void showToast(String toast) { Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show(); } } WebViewClient webViewClient = new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith("https://www.rapyd.net/")) { new Thread(new Runnable() { @Override public void run() { try{ sendSupport( amount); } catch (Exception ex){ App.Log("sendSupport error "+ex.toString()); } } }).start(); finish(); return true; } App.Log("page shouldOverrideUrlLoading "+url); return false; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); App.Log("page loaded "+url); webView.setVisibility(View.VISIBLE); if(url.equals("https://www.rapyd.net/")){ finish(); } /*if (url.contains("code=")) { Uri uri = Uri.EMPTY.parse(url); String access_token = uri.getEncodedFragment(); access_token = access_token.substring(access_token.lastIndexOf("=") + 1); App.Log("Instagram key "+access_token); }*/ } }; private void sendSupport(String amount) throws IOException { ContributionAction contributionAction = new ContributionAction( Long.toString(System.currentTimeMillis()), userName, social, amount ); OkHttpClient client2 = new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS).writeTimeout(30, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).build(); Gson gson = new Gson(); String json = gson.toJson(contributionAction); // App.Log("json"); // App.Log(json); Request requestaction = new Request.Builder() .url(App.Url).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json)) .build(); Response response = client2.newCall(requestaction).execute(); String searhTruResponse = response.body().string().replaceAll("^\"+|\"+$", "").replaceAll("\\\\", ""); App.Log("sendSupport "+searhTruResponse); ContributionsDBHelper contributionsDBHelper = new ContributionsDBHelper(getApplicationContext()); contributionsDBHelper.open(); contributionsDBHelper.insertEntry(contributionAction); contributionsDBHelper.close(); } private void doPayment(final String amount){ findViewById(R.id.sendMoneyBtn).setEnabled(false); findViewById(R.id.ani).setVisibility(View.VISIBLE); userNameTextView.setVisibility(View.INVISIBLE); new Thread(new Runnable() { @Override public void run() { String sendAmount = amount; if(!sendAmount.contains(".")){ sendAmount = sendAmount+".01"; } final String url= new RapydUtils().CreateCheckOut(Double.parseDouble(sendAmount)); runOnUiThread(new Runnable() { @Override public void run() { Intent intent = new Intent(PaymentsActivity.this, RapydPaymentActivity.class); intent.putExtra(App.Content,url); loadPage(url); // startActivity(intent); } }); } }).start(); } @Override public void onClick(View v) { int id = v.getId(); ArrayList<Integer> ids = new ArrayList<Integer>(buttonsIds.length); for (int i : buttonsIds) { ids.add(i); } if(ids.contains(id)){ String adding = Integer.toString(ids.indexOf(id)); amount +=adding; inputEditText.setText("$"+amount); } else if(id==R.id.inputBtnDot){ if(!amount.contains(".")){ amount +="."; inputEditText.setText("$"+amount); } } else if(id==R.id.inputBtnBackspace){ amount =removeLast(amount); inputEditText.setText("$"+amount); } else if(id==R.id.sendMoneyBtn){ doPayment(amount); } } public String removeLast(String str) { if (str != null && str.length() > 0 ) { str = str.substring(0, str.length() - 1); } return str; } }<file_sep>import json import boto3 import base64 import random import secrets import string import datetime bucketName = 'socialtruthbucket' SocialTruth ='SocialTruthTable' SeeyAccounts ='SeeyAccounts' SeeyCreators ='SeeyCreators' SeeyContributions ='SeeyContributions' def lambda_handler(event, context): # TODO implement if event['action'] == 'PutUrl': return putFile(event['Key']) elif event['action'] == 'SearchTruth': return searchForTruth(event['Key']) elif event['action'] == 'AddTruth': return addTruth(event['key'],event['url'],event['isTrue'],event['summary'],event['title']) elif event['action'] == 'SummarizeText': return json.dumps(summarizeText(event['key'])) elif event['action'] == 'ocr': return json.dumps(ocr(event['Key'])) elif event['action'] == 'signup': return signup(event['user'],event['password'],event['accountType']) elif event['action'] == 'signIn': return signIn(event['user'],event['password']) elif event['action'] == 'link': return link(event['user'],event['social'],event['img']) elif event['action'] == 'supportaction': return support(event['user'],event['social'],event['amount']) elif event['action'] == 'getsupport': return getsupport(event['user'],event['social']) return { 'statusCode': 200, 'body': json.dumps('Hello from Lambda!') } def link(user,social,img): s3 = boto3.client('s3', config=boto3.session.Config(signature_version='s3v4')) s3.put_object(Bucket=bucketName, Key=user+social, Body=base64.b64decode(img)) dynamodb = boto3.client('dynamodb') dynamodb.put_item(TableName=SeeyCreators,Item={'username': {'S': str(user)}, 'social': {'S': str(social)}, 'img': {'S': str(user+social)}}) return "success" def getPreviousAmount(user,social): dynamodb = boto3.client('dynamodb') try: response = dynamodb.get_item(Key={'username': {'S': str(user)}}, TableName=SeeyCreators)['Item'] if response is not None and response['username'] is not None: if response['password']['S'] == password: return "success" except: print("nothing found") def support(user,social,amount): cuurent = getsupport(user,social) toSave = float(cuurent)+float(amount) dynamodb = boto3.client('dynamodb') dynamodb.put_item(TableName=SeeyContributions,Item={'usernamesocial': {'S': str(user+social)}, 'amount': {'S': str(toSave)}}) return "success" def getsupport(user,social): dynamodb = boto3.client('dynamodb') try: response = dynamodb.get_item(Key={'usernamesocial': {'S': str(user+social)}}, TableName=SeeyContributions)['Item'] if response is not None and response['usernamesocial'] is not None: return response['amount']['S'] except: print("nothing found") return "0" def getAllsupport(user): socials = ['Youtube','Instagram','Twitter'] lines = [] for social in socials: lines.append(getsupport(user,social)) return lines def signup(user,password,accountType): dynamodb = boto3.client('dynamodb') dynamodb.put_item(TableName=SeeyAccounts,Item={'username': {'S': str(user)}, 'password': {'S': str(<PASSWORD>)}, 'accountType': {'S': str(accountType)}}) return "success" def signIn(user,password): dynamodb = boto3.client('dynamodb') try: response = dynamodb.get_item(Key={'username': {'S': str(user)}}, TableName=SeeyAccounts)['Item'] if response is not None and response['username'] is not None: if response['password']['S'] == password: return response['accountType']['S'] except: print("nothing found") return "fail" def ocr(key): lines = detect_textBytes(key) return lines def putFile(key): s3 = boto3.client('s3', config=boto3.session.Config(signature_version='s3v4')) return s3.generate_presigned_url('put_object', Params={'Bucket':bucketName, 'Key':key}, ExpiresIn=21600, HttpMethod='PUT') def getFile(key): s3 = boto3.client('s3', config=boto3.session.Config(signature_version='s3v4')) return s3.generate_presigned_url('get_object', Params={'Bucket':bucketName, 'Key':key}, ExpiresIn=21600) def detect_text(key): client=boto3.client('rekognition') response=client.detect_text(Image={'S3Object':{'Bucket':bucketName,'Name':key}}) textDetections=response['TextDetections'] #print(textDetections) lines = [] for text in textDetections: if text['Type'] == "LINE": print(text['DetectedText']) lines.append(text['DetectedText']) return lines def detect_textBytes(key): client=boto3.client('rekognition') response=client.detect_text(Image={'Bytes':base64.b64decode(key)}) open('/tmp/filename.png', 'wb').write(base64.b64decode(key)) s3 = boto3.resource('s3') s3.meta.client.upload_file('/tmp/filename.png', 'socialtruthbucket', 'filename.png') textDetections=response['TextDetections'] #print(textDetections) lines = [] for text in textDetections: if text['Type'] == "LINE": print(text['DetectedText']) lines.append(text['DetectedText']) return lines def searchForTruth(key): dynamodb = boto3.client('dynamodb') lines = detect_textBytes(key) resultCount = 0 result = None for line in lines: try: response = dynamodb.get_item(Key={'line': {'S': line}}, TableName=SocialTruth)['Item'] if response is not None and response['line'] is not None: resultCount = resultCount+1 result = {"line":response['line']['S'],"url":response['url']['S'],"isTrue":response['isTrue']['S'],"title":response['title']['S'],"summary":response['summary']['S']} except: print("nothing found") return result def addTruth(key,url,isTrue,summary,title): lines = detect_text(key) addToDb(lines,url,isTrue,summary,title) return "added" def addToDb(lines,url,isTrue,summary,title): alphabet = string.ascii_letters + string.digits fileName = ''.join(secrets.choice(alphabet) for i in range(20)) fileName = fileName+".txt" s3client = boto3.client('s3') text = "" textlines = summary.splitlines() for textLine in textlines: newText = text+' '+textLine if len(newText)<5000: text = newText s3client.put_object(Body=text, Bucket='socialtruthbucket', Key=fileName) summary = summarizeText(fileName) dynamodb = boto3.client('dynamodb') for line in lines: dynamodb.put_item(TableName=SocialTruth,Item={'line': {'S': str(line)}, 'url': {'S': str(url)}, 'isTrue': {'S': str(isTrue)}, 'summary': {'S': str(summary)}, 'title': {'S': str(title)}}) def summarizeText(key): # TODO implement client = boto3.client('sagemaker-runtime') s3 = boto3.resource('s3') obj = s3.Object("socialtruthbucket", key) #obj.get()['Body'].read().decode('utf-8') #s3://socialtruthbucket/self_driving_test.txt response = client.invoke_endpoint(EndpointName='Summarizer', ContentType="text/plain",Accept="text/plain", Body=obj.get()['Body'].read().decode('utf-8')) #response_body = response['Body'].read().decode("utf-8") print(response) body = response['Body'].read() #print(len(body.decode("utf-8"))) print(body.decode("utf-8")) return body.decode("utf-8") <file_sep>rootProject.name = "Seey" include ':app' <file_sep>plugins { id 'com.android.application' } apply plugin: 'kotlin-android' android { compileSdkVersion 29 defaultConfig { applicationId "com.payments.app.seey" minSdkVersion 21 targetSdkVersion 29 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar','*.aar']) implementation 'androidx.appcompat:appcompat:1.3.0' implementation 'androidx.constraintlayout:constraintlayout:2.0.4' implementation 'androidx.legacy:legacy-support-v4:1.0.0' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test.ext:junit:1.1.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' implementation "androidx.recyclerview:recyclerview:1.2.1" testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test.ext:junit:1.1.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' implementation 'com.google.android.material:material:1.4.0-rc01' implementation 'com.squareup.okhttp3:okhttp:3.10.0' implementation 'com.squareup.okio:okio:1.17.4' implementation 'com.google.code.gson:gson:2.6.2' implementation 'com.airbnb.android:lottie:3.3.0' implementation 'com.github.tajchert:nammu:1.2.0' implementation group: 'commons-io', name: 'commons-io', version: '2.6' testImplementation 'junit:junit:4.+' implementation('com.twitter.sdk.android:twitter:3.3.0@aar') { transitive = true } implementation 'com.bytedance.ies.ugc.aweme:opensdk-oversea-external:0.2.0.2' implementation "androidx.core:core-ktx:1.6.0" implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1' implementation 'com.quickbirdstudios:opencv:3.4.1' implementation 'com.github.adaptech-cz:tesseract4android:2.1.1' implementation 'com.android.volley:volley:1.2.0' implementation 'org.apache.commons:commons-collections4:4.4' implementation 'org.apache.commons:commons-lang3:3.9' implementation 'commons-io:commons-io:2.6' implementation 'androidx.browser:browser:1.3.0' implementation 'com.google.android.gms:play-services-auth:19.0.0' implementation 'pub.devrel:easypermissions:0.3.0' implementation('com.google.api-client:google-api-client-android:1.22.0') { exclude group: 'org.apache.httpcomponents' } implementation('com.google.apis:google-api-services-youtube:v3-rev183-1.22.0') { exclude group: 'org.apache.httpcomponents' } implementation 'com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava' implementation 'io.github.florent37:shapeofview:1.4.7' implementation "com.mikepenz:iconics-core:4.0.2" implementation 'com.mikepenz:fontawesome-typeface:5.9.0.0-kotlin@aar' implementation 'com.airbnb.android:lottie:3.3.0' implementation 'com.github.bumptech.glide:glide:4.5.0' implementation 'com.braintreepayments:card-form:5.1.1' annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0' implementation 'com.github.ozcanzaferayan:CreditCardView:0.1.0' } repositories { mavenCentral() }<file_sep># Seey See lambda.py for the backend <file_sep>package com.payments.app.seey; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.Settings; public class ContributionsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_contributions); init(); } private void init(){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForegroundService(new Intent(this,ScreenshootService.class)); } //startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (!Settings.canDrawOverlays(this)) { Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); startActivityForResult(intent, 0); } } } }<file_sep>package com.payments.app.seey.userrecognition; import android.content.Context; import android.graphics.Bitmap; import android.os.Environment; import com.googlecode.tesseract.android.TessBaseAPI; import com.payments.app.seey.App; import org.apache.commons.lang3.RandomStringUtils; import org.opencv.android.Utils; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.Point; import org.opencv.imgproc.Imgproc; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class InstagramUserRecognition extends AppUserRecognition { public InstagramUserRecognition(Context context,String app) { super(context,app); } @Override public String findUser(Bitmap screenshot) { TessBaseAPI baseApi = new TessBaseAPI(); baseApi.init(getDataDirPath(),"eng"); // baseApi.set baseApi.setPageSegMode(TessBaseAPI.PageSegMode.PSM_AUTO); Mat template = new Mat(); Mat matScreenshot = new Mat(); Mat result = new Mat(); Bitmap bmp32 = screenshot.copy(Bitmap.Config.ARGB_8888, true); Utils.bitmapToMat(bmp32, matScreenshot); Mat gray = new Mat(); Imgproc.cvtColor(matScreenshot, gray, Imgproc.COLOR_BGR2GRAY); Mat circles = new Mat(); double minDist = 100; // higher threshold of Canny Edge detector, lower threshold is twice smaller // double p1UpperThreshold = 200; double p1UpperThreshold = 80; // the smaller it is, the more false circles may be detected double p2AccumulatorThreshold = 40; int minRadius = 20; int maxRadius = 100; // use gray image, not edge detected Imgproc.HoughCircles(gray, circles, Imgproc.CV_HOUGH_GRADIENT, 1, minDist, p1UpperThreshold, p2AccumulatorThreshold, minRadius, maxRadius); double max = Double.MAX_VALUE; int resultRadius = 0; Point resultPoint = null; for (int x = 0; x < circles.cols(); x++) { double[] c1xyr = circles.get(0, x); Point xy = new Point(Math.round(c1xyr[0]), Math.round(c1xyr[1])); int radius = (int) Math.round(c1xyr[2]); if(xy.y<max){ resultRadius =radius; resultPoint =xy; max=xy.y; } } Bitmap sectionBitmap = Bitmap.createBitmap(screenshot, 0, (int) resultPoint.y-resultRadius, screenshot.getWidth(), resultRadius*2); baseApi.setImage(sectionBitmap); String texts= baseApi.getUTF8Text(); File fileName =new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), RandomStringUtils.random(12,true,false)+".png") ; try (FileOutputStream out = new FileOutputStream(fileName)) { sectionBitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance // PNG is a lossless format, the compression factor (100) is ignored } catch (IOException e) { e.printStackTrace(); } String resultk=""; try { resultk = ocr(fileName.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(); } App.Log("found text point: "+resultPoint.toString()+"" + " radius:"+resultRadius+" values: "+texts+" aws:"+resultk); // int radius = (int) Math.round(c1xyr[2]); // Core.circle(detected, xy, radius, new Scalar(0, 0, 255), 3); /* Imgproc.matchTemplate(matScreenshot,template,result,Imgproc.TM_CCOEFF); Core.MinMaxLocResult minMaxLocResult =Core.minMaxLoc(result); org.opencv.core.Point topLeft = minMaxLocResult.maxLoc; */ return resultk; } } <file_sep>package com.payments.app.seey.action; import com.zaferayan.creditcard.model.CreditCard; public class Beneficiary { private String email; private String card_number; private String card_expiration_month; private String card_expiration_year; private String card_cvv; public Beneficiary(){ email = "<EMAIL>"; } public Beneficiary( CreditCard creditCard){ email = "<EMAIL>"; card_number=creditCard.getNumber(); card_expiration_month=creditCard.getExpirationMonth(); card_expiration_year=creditCard.getExpirationYear(); card_cvv=creditCard.getCvv(); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getCard_number() { return card_number; } public void setCard_number(String card_number) { this.card_number = card_number; } public String getCard_expiration_month() { return card_expiration_month; } public void setCard_expiration_month(String card_expiration_month) { this.card_expiration_month = card_expiration_month; } public String getCard_expiration_year() { return card_expiration_year; } public void setCard_expiration_year(String card_expiration_year) { this.card_expiration_year = card_expiration_year; } public String getCard_cvv() { return card_cvv; } public void setCard_cvv(String card_cvv) { this.card_cvv = card_cvv; } } <file_sep>package com.payments.app.seey.action; public abstract class NetworkAction { public abstract String getAction(); public abstract void setAction(String action); } <file_sep>package com.payments.app.seey.storage.db.helpers; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import com.payments.app.seey.action.ContributionAction; import com.payments.app.seey.storage.db.ContributionsDB; import java.util.ArrayList; public class ContributionsDBHelper { private SQLiteDatabase db; private Context context; private ContributionsDB dbhelper; public ContributionsDBHelper(Context c){ context = c; this.dbhelper = new ContributionsDB(c, ContributionsDB.DATABASE_NAME, null, ContributionsDB.DATABASE_VERSION); } public Context getContext(){ return context; } public void close() { db.close(); } public SQLiteDatabase getDB(){ return db; } public void setDB(SQLiteDatabase db){ this.db =db; } public SQLiteOpenHelper getDbHelper(){ return dbhelper; } public void open() throws SQLiteException { try { db = dbhelper.getWritableDatabase(); } catch(SQLiteException ex) { db = dbhelper.getReadableDatabase(); } } public long insertEntry(ContentValues cv){ try{ return db.insert(dbhelper.getTableName(), null, cv); } catch(SQLiteException ex){; return -1; } } public Cursor query() { return query(null, null, null, null, null, null); } public Cursor query( String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) { Cursor c = db.query(dbhelper.getTableName(),columns, selection, selectionArgs, groupBy, having, orderBy); return c; } public void deleteEntry(String id){ db.delete(dbhelper.getTableName(), ContributionsDB.time+"='"+id+"'", null); } public ContributionAction[] queryAll(){ Cursor cursor = query(); ArrayList<ContributionAction> items = new ArrayList<>(); // cursor.moveToFirst(); while (cursor.moveToNext()) { ContributionAction item = new ContributionAction(); items.add(new ContributionAction( cursor.getString(cursor.getColumnIndex(ContributionsDB.time)), cursor.getString(cursor.getColumnIndex(ContributionsDB.to)), cursor.getString(cursor.getColumnIndex(ContributionsDB.social)), cursor.getString(cursor.getColumnIndex(ContributionsDB.amount)) )); } cursor.close(); return items.toArray(new ContributionAction[]{}); } public ContentValues insertEntry(ContributionAction item ){ db.beginTransaction(); try{ ContentValues cv = new ContentValues(); cv.put(ContributionsDB.amount,item.getAmount()); cv.put(ContributionsDB.to,item.getUser()); cv.put(ContributionsDB.time,item.getTime()); cv.put(ContributionsDB.social,item.getSocial()); getDB().insert(ContributionsDB.TABLE_NAME, null, cv); db.setTransactionSuccessful(); db.endTransaction(); return cv; } catch(SQLiteException ex) { return null; } } }
4bfcf43688b0c5e27dde50b58960248637a318c9
[ "Markdown", "Java", "Python", "Gradle" ]
12
Java
dnsking/Seey
65fc79c9338ef1e73d537755aac982596607637d
ea2ba33bf452a517a127e22171cb585d3de3b558
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Katas.Business { public class KataSimpleEncryptionAlternatingSplit { public static string Encrypt(string text, int n) { if (String.IsNullOrEmpty(text)) return text; if (n <= 0) return text; return DoEncryptationRefactor(text, n); } private static string DoEncryptationRefactor(string text, int n) { List<string> OddPosition; List<string> EvenPosition; string result; int loop = 0; int i = 0; result = text; while (loop < n) { OddPosition = new List<string>(); EvenPosition = new List<string>(); i = 0; while (i <= result.Length - 1) { if (i % 2 == 0) OddPosition.Add(result.Substring(i, 1)); if (i % 2 != 0) EvenPosition.Add(result.Substring(i, 1)); ++i; } result = string.Concat(EvenPosition.Select(x => x).Aggregate((x, j) => x + j), OddPosition.Select(x => x).Aggregate((x, j) => x + j)); ++loop; } return result; } private static string ExtractChar(string text, int i) { return text.Substring(i, 1); } public static string Decrypt(string encryptedText, int n) { if (string.IsNullOrEmpty(encryptedText)) return encryptedText; if (n <= 0) return encryptedText; return encryptedText; } } } <file_sep>using System; using System.Linq; namespace Katas { public class KataCountingBits { public static int CountBits(int n) { string pattern = "1"; //refactor //return Convert.ToString(n, 2).Count(x => x == '1'); return CountingOnes(TransformtoBinary(n), pattern); } private static string TransformtoBinary(int value) { return Convert.ToString(value, 2); } private static int CountingOnes(string binaryValue, string pattern) { int count = 0; int i = 0; while ((i = binaryValue.IndexOf(pattern, i)) != -1) { i += pattern.Length; count++; } return count; } } } <file_sep>using Xunit; using Katas.Business; namespace Katas.Tests { /// <summary> /// For building the encrypted string: /*Take every 2nd char from the string, then the other chars, that are not every 2nd char, and concat them as new String. Do this n times*/ /// </summary> public class KataSimpleEncryptionAlternatingSplitTests { [Fact] public void EncryptExampleTests() { Assert.Equal("This is a test!", KataSimpleEncryptionAlternatingSplit.Encrypt("This is a test!", 0)); Assert.Equal("hsi etTi sats!", KataSimpleEncryptionAlternatingSplit.Encrypt("This is a test!", 1)); Assert.Equal("s eT ashi tist!", KataSimpleEncryptionAlternatingSplit.Encrypt("This is a test!", 2)); Assert.Equal(" Tah itse sits!", KataSimpleEncryptionAlternatingSplit.Encrypt("This is a test!", 3)); Assert.Equal("This is a test!", KataSimpleEncryptionAlternatingSplit.Encrypt("This is a test!", 4)); Assert.Equal("This is a test!", KataSimpleEncryptionAlternatingSplit.Encrypt("This is a test!", -1)); Assert.Equal("hskt svr neetn!Ti aai eyitrsig", KataSimpleEncryptionAlternatingSplit.Encrypt("This kata is very interesting!", 1)); } [Fact] public void DecryptExampleTests() { Assert.Equal("This is a test!", KataSimpleEncryptionAlternatingSplit.Decrypt("This is a test!", 0)); Assert.Equal("This is a test!", KataSimpleEncryptionAlternatingSplit.Decrypt("hsi etTi sats!", 1)); Assert.Equal("This is a test!", KataSimpleEncryptionAlternatingSplit.Decrypt("s eT ashi tist!", 2)); Assert.Equal("This is a test!", KataSimpleEncryptionAlternatingSplit.Decrypt(" Tah itse sits!", 3)); Assert.Equal("This is a test!", KataSimpleEncryptionAlternatingSplit.Decrypt("This is a test!", 4)); Assert.Equal("This is a test!", KataSimpleEncryptionAlternatingSplit.Decrypt("This is a test!", -1)); Assert.Equal("This kata is very interesting!", KataSimpleEncryptionAlternatingSplit.Decrypt("hskt svr neetn!Ti aai eyitrsig", 1)); } [Fact] public void EmptyTests() { Assert.Equal("", KataSimpleEncryptionAlternatingSplit.Encrypt("", 0)); Assert.Equal("", KataSimpleEncryptionAlternatingSplit.Decrypt("", 0)); } [Fact] public void NullTests() { Assert.Null(KataSimpleEncryptionAlternatingSplit.Encrypt(null, 0)); Assert.Null(KataSimpleEncryptionAlternatingSplit.Decrypt(null, 0)); } } } <file_sep>using Katas.Business; using System; using System.Linq; using Xunit; namespace Katas.Tests { public class KataLongestConsecutivesTests { [Fact] public void xUnitTest() { Console.WriteLine("Basic Tests"); testing("abigailtheta", KataLongestConsecutives.LongestConsec(new String[] { "zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail" }, 2)); testing("oocccffuucccjjjkkkjyyyeehh", KataLongestConsecutives.LongestConsec(new String[] { "ejjjjmmtthh", "zxxuueeg", "aanlljrrrxx", "dqqqaaabbb", "oocccffuucccjjjkkkjyyyeehh" }, 1)); testing("", KataLongestConsecutives.LongestConsec(new String[] { }, 3)); testing("wkppqsztdkmvcuwvereiupccauycnjutlvvweqilsfytihvrzlaodfixoyxvyuyvgpck", KataLongestConsecutives.LongestConsec(new String[] { "itvayloxrp", "wkppqsztdkmvcuwvereiupccauycnjutlv", "vweqilsfytihvrzlaodfixoyxvyuyvgpck" }, 2)); testing("wlwsasphmxxowiaxujylentrklctozmymu", KataLongestConsecutives.LongestConsec(new String[] { "wlwsasphmxx", "owiaxujylentrklctozmymu", "wpgozvxxiu" }, 2)); testing("",KataLongestConsecutives.LongestConsec(new String[] { "zone", "abigail", "theta", "form", "libe", "zas" }, -2)); testing("ixoyx3452zzzzzzzzzzzz", KataLongestConsecutives.LongestConsec(new String[] { "it", "wkppv", "ixoyx", "3452", "zzzzzzzzzzzz" }, 3)); testing("", KataLongestConsecutives.LongestConsec(new String[] { "it", "wkppv", "ixoyx", "3452", "zzzzzzzzzzzz" }, 15)); testing("", KataLongestConsecutives.LongestConsec(new String[] { "it", "wkppv", "ixoyx", "3452", "zzzzzzzzzzzz" }, 0)); } private static void testing(string actual, string expected) { Assert.Equal(expected, actual); } } } <file_sep>using System; using System.Linq; using Xunit; namespace Katas.Tests { public class KataMumblingTests { [Fact] public void TestMethod1() { Assert.Equal("Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu", KataMumbling.Accum("ZpglnRxqenU")); Assert.Equal("N-Yy-Fff-Ffff-Sssss-Gggggg-Eeeeeee-Yyyyyyyy-Yyyyyyyyy-Llllllllll-Bbbbbbbbbbb", KataMumbling.Accum("NyffsGeyylB")); Assert.Equal("M-Jj-Ttt-Kkkk-Uuuuu-Bbbbbb-Ooooooo-Vvvvvvvv-Qqqqqqqqq-Rrrrrrrrrr-Uuuuuuuuuuu", KataMumbling.Accum("MjtkuBovqrU")); Assert.Equal("E-Vv-Iii-Dddd-Jjjjj-Uuuuuu-Nnnnnnn-Oooooooo-Kkkkkkkkk-Mmmmmmmmmm-Mmmmmmmmmmm", KataMumbling.Accum("EvidjUnokmM")); Assert.Equal("H-Bb-Iii-Dddd-Eeeee-Vvvvvv-Bbbbbbb-Xxxxxxxx-Nnnnnnnnn-Cccccccccc-Ccccccccccc", KataMumbling.Accum("HbideVbxncC")); } } } <file_sep>using System; using System.Linq; namespace Katas { public class KataMumbling { public static String Accum(string s) { int i = 1; string result = s.First().ToString().ToUpper(); while(i < s.Length) { result += string.Format("-{0}{1}", s.Substring(i, 1).ToUpper(), RepeatLetter(s.Substring(i,1).ToLower() ,i)); i++; } return result; } private static string RepeatLetter(string character, int position) { return string.Concat(Enumerable.Repeat(character, position)); } } } <file_sep>using System; using System.Linq; using Xunit; namespace Katas.Tests { public class KataFindNextSquareTest { [Fact] public void TestMethod1() { Assert.Equal(-1, KataFindNextSquare.FindNextSquare(155)); Assert.Equal(144, KataFindNextSquare.FindNextSquare(121)); Assert.Equal(676, KataFindNextSquare.FindNextSquare(625)); Assert.Equal(320356, KataFindNextSquare.FindNextSquare(319225)); Assert.Equal(15241630849, KataFindNextSquare.FindNextSquare(15241383936)); } } } <file_sep>using System; using Xunit; namespace Katas.Tests { public class KataCountingBitsTests { [Fact] public void Test1() { Assert.Equal(0, KataCountingBits.CountBits(0)); Assert.Equal(1, KataCountingBits.CountBits(4)); Assert.Equal(3, KataCountingBits.CountBits(7)); Assert.Equal(2, KataCountingBits.CountBits(9)); Assert.Equal(2, KataCountingBits.CountBits(10)); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace Katas { public class KataFindNextSquare { public static long FindNextSquare(long num) { double result = Math.Sqrt(num); bool isSquare = result % 1 == 0; if (isSquare == true) { result++; result *= result; long l = Convert.ToInt64(result); return l; } else { return -1; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; namespace Katas.Business { public class KataLongestConsecutives { public static String LongestConsec(string[] strarr, int k) { List<string> stringList = GetStringsFromArray(strarr: strarr, k: k); var sortedValues = stringList .OrderByDescending(x => x.Length); var finalString = sortedValues.FirstOrDefault(); if (finalString is null) return ""; if (finalString.Length == 0 || k > finalString.Length || k <= 0) return ""; return finalString; } private static List<string> GetStringsFromArray(string[] strarr, int k) { List<string> stringList = new List<string>(); int pos = 0; while ((pos + k) <= strarr.Length) { stringList.Add(GenerateString(strarr: strarr, pos: pos, k: k - 1, concat: "", start: 0)); pos += 1; } return stringList; } private static string GenerateString(string[] strarr, int pos, int k, string concat, int start) { while (start <= k) { concat = String.Concat(concat, strarr[pos]); ++pos; ++start; } return concat; } } }
98cc8e9a9da95fddc9a655845e5a35510145dde1
[ "C#" ]
10
C#
cctron/KatasFromCodeWars
270533939f0e093c0fe9217d613d41fc0ef0f343
874742640231198e5fa9b4b351d03bde2317032d
refs/heads/master
<repo_name>OleksandrZhytnyk/Test_Task_Semantic_Segmentation_with_UNET<file_sep>/requirements.txt keras==2.3.1 tensorflow==2.1.0 numpy==1.19.1 pandas==1.1.1 matplotlib==3.3.1 tqdm==4.48.2 scipy==1.4.1 <file_sep>/train.py #!/usr/bin/env python # coding: utf-8 # In[ ]: from keras.callbacks import EarlyStopping, ModelCheckpoint def train(model, X_train, Y_train, validation_split=0.1, batch_size=16, epochs=50): earlystopper = EarlyStopping(patience=5, verbose=1) checkpointer = ModelCheckpoint('model-dsbowl2018-1.h5', verbose=1, save_best_only=True) return model.fit(X_train, Y_train, validation_split=0.1, batch_size=16, epochs=50, callbacks=[earlystopper, checkpointer]) if __name__ == '__main__': from model_unet import model_unet, dice_coef from preprocessing import load_data, plot_example IMG_HEIGHT = 128 IMG_WIDTH = 128 IMG_CHANNELS = 3 TRAIN_PATH ='train_images' TEST_PATH ='test_images' # image path train_ids = next(os.walk(TRAIN_PATH))[1] test_ids = next(os.walk(TEST_PATH))[1] X_train, Y_train, X_test = load_data(IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS) model = model_unet(IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS) train(model, X_train, Y_train) <file_sep>/predict_masks.py #!/usr/bin/env python # coding: utf-8 # In[ ]: from tensorflow.keras.models import load_model from model_unet import dice_coef def load_model1(): return load_model('model-dsbowl2018-1.h5', custom_objects={'dice_coef': dice_coef}) def predict_masks(model, X_test): model = load_model1() return model.predict(X_test, verbose=1) if __name__ == '__main__': IMG_HEIGHT = 128 IMG_WIDTH = 128 IMG_CHANNELS = 3 model = load_model1() X_train, Y_train, X_test = load_data(IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS) preds_test = model.predict_masks(X_test, verbose=1) def plot_sample(X_test, preds_test, ix=None): if ix is None: ix = random.randint(0, len(X_test)) has_mask = preds_test[ix].max() > 0 fig, ax = plt.subplots(1, 2, figsize=(20, 10)) ax[0].imshow(X_test[ix, ..., 0], cmap='seismic') ax[0].set_title('Seismic') ax[1].imshow(preds_test[ix].squeeze(), vmin=0, vmax=1) ax[1].set_title('Salt Predicted'); plot_sample(X_test, preds_test, ix=None) <file_sep>/README.md # Test_Task_Semantic_Segmentation_with_UNET # Data Data loaded from [2018 Data Science Bowl](https://www.kaggle.com/c/data-science-bowl-2018/data). In my case, I used stage1_train.zip which contains training set images(images and annotated masks) and stage1_test.zip which contains test set images, preprocessing.py will create X_train, Y_train, X_test that used to train model. One example: ![example1](https://user-images.githubusercontent.com/71394662/93486818-4b36e000-f90d-11ea-9a88-ff27724b0c17.png) # UNET [UNET](https://arxiv.org/abs/1505.04597) - Convolutional Networks for Biomedical Image Segmentation. The goal of semantic image segmentation is to label each pixel of an image with a corresponding class of what is being represented. ![image](https://gabe.smedresman.zone/content/images/2019/06/u-net-architecture.png) # Train The model is trained for 36 epochs. After 36 epochs, calculated loss funcition is ~0.066 and dice_coef is ~0.764%. For dice_coef set smooth factor = 1e-6. ![image2](https://user-images.githubusercontent.com/71394662/93488261-d5337880-f90e-11ea-92e4-849d1df691b7.png) # Test The result of the model work on test data (X_test) ![Image3](https://user-images.githubusercontent.com/71394662/93516214-636d2600-f932-11ea-8700-0a5e9ee201cd.png) # Implementation 1. Create Python 3.6 + environment and install all requirements from requirements.txt 2. Download data (download stage1_train.zip, stage1_test.zip and unpack in the data folder) 3. Run preprocessing.py -> model_unet.py -> train.py -> predict_masks.py. 4. Run data_analysis.py. <file_sep>/data analysis.py #!/usr/bin/env python # coding: utf-8 # In[ ]: import os import random import matplotlib.pyplot as plt import numpy as np from skimage.io import imshow # Dataset consists of pictures (a large number of segmented nuclei images). # Within this folder are two subfolders: # -images contains the image file # -masks contains the segmented masks of each nucleus. This folder is only included in the training set. # Each mask contains one nucleus. Masks are not allowed to overlap (no pixel belongs to two masks) # Сonvert each image of the nucleus into one image so that each image of the nucleus is compared with one mask. # # Load data # In[ ]: from preprocessing import load_data, plot_example X_train, Y_train, X_test = load_data(IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS) # # Show example # In[ ]: plot_example(X_train, Y_train) #
935a10aa92482348e1b96572cd3215fd1448dcfe
[ "Markdown", "Python", "Text" ]
5
Text
OleksandrZhytnyk/Test_Task_Semantic_Segmentation_with_UNET
a6c3ffc97f0154c283d36251f230b3694e68d355
ad49196adbf649c0c04e4a054c9bc4fbfbdc35c9
refs/heads/master
<repo_name>lowsound42/eloquentJS<file_sep>/README.md <h1>Eloquent JS</h1> <p>I'm working through the 3rd edition of this book and using this repository to mark my progress. I'm breaking this up by chapter and working on each exercise within those folders.</p> <file_sep>/chapter-2/2-1.js //Chapter 2 exercise 1 let steps = 7; function hashPyramid () { let hashes = ""; for (let i = 0; i < steps; i++) { hashes += '#'; console.log(hashes); } } hashPyramid();
3c912f2ed06d7cc8bd5bc990c09a21861c8ae1d2
[ "Markdown", "JavaScript" ]
2
Markdown
lowsound42/eloquentJS
5a7e4b15bd3968d7fa75c695f5c77a96ffca959c
78cc405f5edfd717aeb4f8491fc8e34dc21557db
refs/heads/main
<repo_name>miikisalminen/runehelper<file_sep>/bot.py import os import discord import scraper as sc TOKEN = "SECRET TOKEN" client = discord.Client() @client.event async def on_message(message): # wiki linker if message.content.startswith ("!wiki"): response = sc.wiki(message.content.replace("!wiki ","")) print(response) await message.channel.send(response) # GE Price check if message.content.startswith ("!price"): response = sc.price(message.content.replace("!price ","")) await message.channel.send(response) # HiScore check #NeededToLevel #!ranks client.run(TOKEN)<file_sep>/scraper.py from urllib.request import Request, urlopen from bs4 import BeautifulSoup as soup def price(item): item_url = item.replace(" ","_") url = Request("https://oldschool.runescape.wiki/w/{0}".format(item_url), headers={'User-Agent': 'Mozilla/5.0'}) try: client = urlopen(url) except: return("Invalid item") html = client.read() client.close page_soup = soup(html, "html.parser") price = page_soup.find("span",{"class":"infobox-quantity-replace"}) name = page_soup.h1 print("{0} is worth {1}gp!".format(name.get_text(),price.get_text())) return("{0} is {1}gp on the Grand Exchange! :moneybag:".format(name.get_text(),price.get_text())) def wiki(thing): thing_url = thing.replace(" ","_") str_url = "https://oldschool.runescape.wiki/w/{0}".format(thing_url) url = Request("https://oldschool.runescape.wiki/w/{0}".format(thing_url), headers={'User-Agent': 'Mozilla/5.0'}) try: client = urlopen(url) client.close return(str_url) except: return("Invalid query :x:")
b56b01d1ae8fcdd73adc7a8697befda29dad62c7
[ "Python" ]
2
Python
miikisalminen/runehelper
b613786c32f94a0a592a0040a3f806be5f12b4fa
3d457cdb8f5e5a0994d9af715ae213331bb25af5
refs/heads/master
<file_sep>from bs4 import BeautifulSoup import re from data.Departments import Departments # define unit type RANGE = "RANGE" ABSOLUTE = "ABSOLUTE" """ SCHEMA OF AN INDIVIDUAL COURSE: key: <course abbreviation> <course number> i.e. CS 111 value: i.e. { 'title' : Operating Systems, 'description' : Lecture, four hours; laboratory, two hours; outside study......, 'unit' : 5, 'unitType' : 'ABSOLUTE', 'departmentFullName' : 'Computer Science', 'departmentAbbreviation' : 'COM SCI, 'prerequisiteDescription' : 'courses 32, 33, 35L', 'prerequisites' : [], 'corequisites' : [] } """ class CourseScraper: def __init__(self): self.departments = Departments() self.department_fullname = None self.department_abbrev = None def scrape_department_courses(self, html): soup = BeautifulSoup(html, "html.parser") department = soup.findAll("div", { "class" : "page-header" })[1].span.string.rstrip() department = department.replace(";", "") m = re.search(r"^(.*?) \((.*?)\)", department) if not m: self.department_fullname = department self.department_abbrev = department.upper() else: self.department_fullname = m.group(1) m = re.search(r"\(([A-Za-z&\-\s]+)\)", department) self.department_abbrev = m.group(1) courses = soup.findAll("div", { "class" : "media-body" }) res = {} for course in courses: course, course_details = self.parse_course(course) res[course] = course_details return self.department_abbrev, res def parse_course(self, course_html): # get important course metadata course_details = course_html.h3.string.split('. ') course_number = course_details[0] course_title = course_details[1].rstrip() unit, course_description = course_html.find_all('p') course_description = course_description.string unit = unit.string.replace('Units: ', '') unit_type = ABSOLUTE if not unit.isdigit(): unit_type = RANGE else: unit = int(unit) # start finding requisites within course description prerequisiteDescription = None corequisiteDescription = None prerequisites = [] corequisites = [] if course_description is not None: for sentence in course_description.split('. '): if re.search(r"\s?([cC]orequisite|[cC]orequisites):", sentence): corequisite_str = sentence[sentence.index(':')+2:] corequisiteDescription = self.parse_requisites(corequisite_str) corequisites = self.structure_single_requisite(corequisiteDescription) elif re.search(r"\s?([rR]equisite|[rR]equisites):", sentence): prerequisite_str = sentence[sentence.index(':')+2:] prerequisiteDescription = self.parse_requisites(prerequisite_str) prerequisites = self.structure_single_requisite(prerequisiteDescription) return "%s %s" % (self.department_abbrev, course_number), { 'title' : course_title, 'description' : course_description, 'unit' : unit, 'unitType' : unit_type, 'departmentFullName' : self.department_fullname, 'departmentAbbreviation' : self.department_abbrev, 'prerequisiteDescription' : prerequisiteDescription, 'corequisiteDescription' : corequisiteDescription, 'prerequisites' : prerequisites, 'corequisites' : corequisites } def parse_requisites(self, requisite_str): converted_requisite_str = requisite_str # convert all full department names to abbreviations with '_' delimiting words in course ID for department_name in self.departments.mapping: if department_name in converted_requisite_str: converted_requisite_str = converted_requisite_str.replace(department_name, self.departments.get_abbreviation(department_name)) return converted_requisite_str def structure_single_requisite(self, requisite_str): if re.search(r"^course [A-Z]{0,2}[0-9]{0,3}[A-Z]{0,2}$", requisite_str): return [[self.department_abbrev + " " + requisite_str.split()[-1]]] else: return [] <file_sep>import json, os class CourseJSONWriter(object): def writeJSONToFile(self, courses_json, output_path): # Retain manually input prerequisite/corequisite fields if they have been input before if os.path.exists(output_path): with open(output_path) as json_data: courses = json.load(json_data) for course_name in courses: if len(courses[course_name]['prerequisites']) > 0: courses_json[course_name]['prerequisites'] = courses[course_name]['prerequisites'] if len(courses[course_name]['corequisites']) > 0: courses_json[course_name]['corequisites'] = courses[course_name]['corequisites'] with open(output_path, 'w') as outfile: json.dump(courses_json, outfile, indent=4, sort_keys=True) print "Wrote JSON to " + output_path<file_sep>import React, { Component } from 'react'; import './CourseListHeader.css'; class CourseListHeader extends Component { render() { return ( <div className="CourseListHeader"> {`Year ${this.props.year} ${this.props.quarter.toUpperCase()}`} </div> ) } } export default CourseListHeader;<file_sep>import { get } from './utils/httpHelper'; import config from './config'; /** * @description Makes server request for username * @param {string} full department name (ie "computer science") * @returns {JSON} JSON for all courses in a particular department */ export function getCoursesFromDepartment(departmentAbbrev) { let uri = `${config.DEPT_COURSE_BASE_URL}${departmentAbbrev}.json`; return get(uri); } export function getAllDegreeRequirements() { let uri = config.degreeRequirements; return get(uri); }<file_sep>import React, { Component } from 'react'; import { CourseList } from '..'; import { Row, Col } from 'antd'; import './InteractiveGrid.css'; class InteractiveGrid extends Component { render() { return ( <div className="InteractiveGrid"> <Row gutter={24}> {Object.keys(this.props.columns).map((key, i) => { let keyTokens = key.split("-"); let year = parseInt(keyTokens[0], 10); let quarter = keyTokens[1]; return <Col xs={6} key={i}> <CourseList key={i} year={year} quarter={quarter} items={this.props.columns[key]} /> </Col> })} </Row> </div> ) } } export default InteractiveGrid;<file_sep>import React, { Component } from 'react'; import { Row, Col, Icon } from 'antd'; import { MajorCarousel, MajorTypeahead } from '..'; import './LandingContainer.css'; class LandingContainer extends Component { render() { return ( <Row type="flex" justify="center" className="LandingContainer"> <Col sm={12} md={6}> <p className="question">What is your major?</p> <MajorCarousel /> </Col> <Col sm={12} md={18}> <Row className="searchbox"> <Col xs={3} sm={2} lg={1}><Icon type="search" className="icon" /></Col> <Col xs={21} sm={22} lg={23}> <MajorTypeahead /> </Col> </Row> </Col> </Row> ); } } export default LandingContainer;<file_sep>import { REPOSITORY_ID, YEARS, QUARTERS } from '..'; const moveWithinList = (list, startIndex, endIndex) => { const result = Array.from(list); const [removed] = result.splice(startIndex, 1); result.splice(endIndex, 0, removed); return result; }; export const moveWithinGrid = ({ courses, columns, source, destination }) => { const sourceFromRepository = source.droppableId === REPOSITORY_ID; const destinationToRepository = destination.droppableId === REPOSITORY_ID; let current = sourceFromRepository ? courses : [...columns[source.droppableId]]; let next = destinationToRepository ? courses : [...columns[destination.droppableId]]; let result = null; // Tile was moved within the same list if (source.droppableId === destination.droppableId) { const reordered = moveWithinList( current, source.index, destination.index, ); result = { courses: sourceFromRepository ? reordered : courses, columns: sourceFromRepository ? columns : { ...columns, [source.droppableId]: reordered } } } // Tile was moved to different list else { // Remove from original and insert into next const target = current[source.index]; current.splice(source.index, 1); next.splice(destination.index, 0, target); if (sourceFromRepository) { result = { columns: { ...columns, [destination.droppableId]: next, }, courses: current } } else if (destinationToRepository) { result = { columns: { ...columns, [source.droppableId]: current, }, courses: next } } else { result = { columns: { ...columns, [source.droppableId]: current, [destination.droppableId]: next, }, courses }; } } return result; }; export const getGridColumns = () => { let columns = {}; for (let year = 1; year <= YEARS; year++) { for (let quarter of QUARTERS) { columns[getListId(year, quarter)] = []; } } return columns; } export const getListId = (year, quarter) => { return `${year}-${quarter.toLowerCase()}`; } export const shouldUpdateStateAfterDrag = (drag) => { const source = drag.source; const destination = drag.destination; // Tile was not dropped anywhere if (!destination) { return false; } // Tile did not move anywhere - can bail early if (source.droppableId === destination.droppableId && source.index === destination.index) { return false; } return true; }<file_sep>from HTMLFetcher import HTMLFetcher from DepartmentLinkScraper import DepartmentLinkScraper from CourseScraper import CourseScraper from CourseJSONWriter import CourseJSONWriter import argparse def main(): parser = argparse.ArgumentParser(description='Parse a UCLA registrar site.') parser.add_argument('-u','--url', help='URL for UCLA registrar site within quotes (i.e. \'http://www.registrar.ucla.edu/Academics/Course-Descriptions/Course-Details?SA=COM+SCI&funsel=3\')') args = parser.parse_args() url = args.url urls = [] if url: urls.append(url) else: deptLinkScraper = DepartmentLinkScraper() urls = deptLinkScraper.getRegistrarLinks() fetcher = HTMLFetcher() scraper = CourseScraper() writer = CourseJSONWriter() for link in urls: html = fetcher.get(link) try: department_abbrev, department_courses = scraper.scrape_department_courses(html) except: print "*** Error trying to scrape " + department_abbrev + " ***" continue try: writer.writeJSONToFile(department_courses, 'data/courses/' + department_abbrev + '.json') except: print "*** Error trying to write " + department_abbrev + " ***" continue if __name__ == '__main__': main()<file_sep>from bs4 import BeautifulSoup from HTMLFetcher import HTMLFetcher ALL_DEPT_ROOT_LINK = "http://www.registrar.ucla.edu/Academics/Course-Descriptions" BASE_URL = "http://www.registrar.ucla.edu" class DepartmentLinkScraper: def getRegistrarLinks(self): fetcher = HTMLFetcher() html = fetcher.get(ALL_DEPT_ROOT_LINK) soup = BeautifulSoup(html, "html.parser") urls = [] for cell in soup.find_all('td'): if not cell.find('a'): continue link_suffix = cell.find('a').get('href') urls.append(BASE_URL + link_suffix) return urls <file_sep>export const YEARS = 5; export const QUARTERS = ["Fall", "Winter", "Spring", "Summer"]; export const NUM_COURSES_PER_QUARTER = 4; export const REPOSITORY_ID = "CourseRepository";<file_sep>import React, { Component } from 'react'; class CourseDetailBody extends Component { render() { return ( <div className="CourseDetailBody"> <b>Description:</b> <p>{this.props.course.description}</p> {this.props.course.prerequisiteDescription ? <div> <b>Prerequisites:</b> <p>{this.props.course.prerequisiteDescription}</p> </div> : ''} {this.props.course.corequisiteDescription ? <div> <b>Corequisites:</b> <p>{this.props.course.corequisiteDescription}</p> </div> : ''} </div> ) } } export default CourseDetailBody;<file_sep>import urllib2 class HTMLFetcher: def get(self, url): html = urllib2.urlopen(url).read() return html <file_sep>majors: majors.txt echo "[" > majors.json cat majors.txt | awk '{ print "\t\""$$0"\",\t"}' >> majors.json echo "]" >> majors.json<file_sep>import * as api from '../api'; var handleError = (error, msg, cb) => { console.error(`${msg}: ${error}`); if (cb) cb(); }; /** * @description Calls the API method to get username and update store */ function getCoursesFromDepartment(department, cb) { return (dispatch, getState) => { // Only fetch if not in store yet let state = getState(); if (!(department in state.courses)) { return api.getCoursesFromDepartment(department) .then(courses => dispatch({ department, courses, type: "GET_COURSES_FOR_DEPT" })) .then(() => { if (cb) cb(); }) .catch(error => handleError(error, `Error in ${getCoursesFromDepartment.name}`, cb)); } else { console.log("cached"); } }; } function getAllDegreeRequirements(cb) { return (dispatch, getState) => { if (!getState().requirements.length) { return api.getAllDegreeRequirements() .then(requirements => dispatch({ requirements, type: "GET_ALL_REQUIREMENTS" })) .then(() => { if (cb) cb(); }) .catch(error => handleError(error, `Error in ${getAllDegreeRequirements.name}`, cb)); } }; } export function getCoursesForMajor(major) { return (dispatch, getState) => { return dispatch(getAllDegreeRequirements()) .then(() => { let state = getState(); let majorRequirements = state.requirements[major]; let departments = new Set(); for (let requirement of majorRequirements) { for (let courseTitle of requirement.courses) { let courseTitleTokens = courseTitle.split(" "); let deptAbbrev = courseTitleTokens.slice(0, courseTitleTokens.length - 1).join(" "); departments.add(deptAbbrev); } } return Array.from(departments); }) .then(departments => { return Promise.all(departments.map(deptName => { return dispatch(getCoursesFromDepartment(deptName)); })); }) .then(() => { let state = getState(); return state.requirements[major].map(requirement => { let courses = requirement.courses.map(courseTitle => { let courseTitleTokens = courseTitle.split(" "); let deptAbbrev = courseTitleTokens.slice(0, courseTitleTokens.length - 1).join(" "); let courseInfo = state.courses[deptAbbrev][courseTitle]; courseInfo["id"] = courseTitle; return courseInfo; }); return { ...requirement, courses }; }); }); } }<file_sep>import React, { Component } from 'react'; import Autosuggest from 'react-autosuggest'; import { Redirect } from 'react-router-dom'; import MAJORS from './majors'; import './MajorTypeahead.css'; class MajorTypeahead extends Component { constructor(props) { super(props); this.state = { value: '', suggestions: [], selectedMajor: null }; } onChange = (event, { newValue }) => { this.setState({ value: newValue }); }; escapeRegexCharacters(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } // Teach Autosuggest how to calculate suggestions for any given input value. getSuggestions(value) { const escapedValue = this.escapeRegexCharacters(value.trim()); if (escapedValue === '') { return []; } const regex = new RegExp('^' + escapedValue, 'i'); return MAJORS.filter(major => regex.test(major)); } getSuggestionValue = suggestion => suggestion; // Use your imagination to render suggestions. renderSuggestion = suggestion => ( <div>{suggestion}</div> ); // Autosuggest will call this function every time you need to update suggestions. // You already implemented this logic above, so just use it. onSuggestionsFetchRequested = ({ value }) => { this.setState({ suggestions: this.getSuggestions(value) }); }; // Autosuggest will call this function every time you need to clear suggestions. onSuggestionsClearRequested = () => { this.setState({ suggestions: [] }); }; onSuggestionSelected = (event, { suggestionValue }) => { this.setState({ selectedMajor: suggestionValue }); } render() { const { value, suggestions } = this.state; // Autosuggest will pass through all these props to the input. const inputProps = { placeholder: 'ie. economics, applied math, computer science, etc...', value, onChange: this.onChange }; return this.state.selectedMajor ? <Redirect to={{ pathname: `/${this.state.selectedMajor.toLowerCase()}` }} /> : <Autosuggest suggestions={suggestions} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.onSuggestionsClearRequested} renderSuggestion={this.renderSuggestion} getSuggestionValue={this.getSuggestionValue} onSuggestionSelected={this.onSuggestionSelected} inputProps={inputProps} /> } } export default MajorTypeahead;<file_sep>import React, { Component } from 'react'; import { Nav, LandingContainer, PlannerContainer } from '..' import { Route, Switch } from 'react-router-dom'; import { Layout } from 'antd'; const { Content } = Layout; class Main extends Component { render() { return ( <div> <Nav /> <Content style={{ paddingTop: 64 }}> <Switch> <Route path='/:major' render={(props) => <PlannerContainer {...this.props} {...props} />} /> <Route path='/' component={LandingContainer} /> </Switch> </Content> </div> ) } } export default Main; <file_sep>import React, { Component } from 'react'; import { Popover, Button } from 'antd'; import { CourseDetailHeader, CourseDetailBody } from '..'; import { Row, Col } from 'antd'; import './CourseTile.css'; class CourseTile extends Component { render() { return ( <div className="CourseTile"> <Row className="header"> <Col xs={20} className="id">{this.props.course.id}</Col> <Col xs={4}> <Popover placement="bottom" title={<CourseDetailHeader course={this.props.course} />} content={<CourseDetailBody course={this.props.course} />} trigger={["click", "hover"]} > <Button type="dashed" shape="circle" icon="info" size="small" /> </Popover> </Col> </Row> <Row className="title">{this.props.course.title}</Row> </div> ) } } export default CourseTile;<file_sep>import { combineReducers } from 'redux'; import CourseReducer from './courses'; import RequirementsReducer from './requirements'; const rootReducer = combineReducers({ courses: CourseReducer, requirements: RequirementsReducer }); export default rootReducer; <file_sep>class Departments: def __init__(self): self.mapping = { 'Aerospace Studies' : 'AERO ST', 'African American Studies' : 'AF AMER', 'African Studies' : 'AFRC ST', 'American Indian Studies' : 'AM IND', 'American Sign Language' : 'ASL', 'Ancient Near East' : 'AN N EA', 'Anesthesiology' : 'ANES', 'Anthropology' : 'ANTHRO', 'Applied Linguistics' : 'APPLING', 'Arabic' : 'Arabic', 'Archaeology' : 'ARCHEOL', 'Architecture and Urban Design' : 'ARCH&UD', 'Armenian' : 'ARMENIA', 'Art' : 'Art', 'Art History' : 'ART HIS', 'Arts and Architecture' : 'ART&ARC', 'Arts Education' : 'ARTS ED', 'Biostatistics' : 'BIOSTAT', 'Biomathematics' : 'BIOMATH', 'Chemistry and Biochemistry' : 'CHEM', 'Chemistry' : 'CHEM', 'Chemical Engineering' : 'CH ENGR', 'Computer Science' : 'COM SCI', 'Electrical Engineering' : 'EL ENGR', 'Mathematics' : 'MATH', 'Materials Science and Engineering' : 'MAT SCI', 'Materials Science' : 'MAT SCI', 'Mechanical and Aerospace Engineering' : 'MECH&AE', 'Civil and Environmental Engineering' : 'C&EE', 'Civil Engineering' : 'C&EE', 'Program in Computing' : 'PIC', 'Statistics' : 'STATS', 'Honors Collegium' : 'HNRS', 'Life Sciences' : 'LIFESCI', 'Physics' : 'PHYSICS' } def get_abbreviation(self, department_name): return self.mapping[department_name] <file_sep>import React, { Component } from 'react'; import { Droppable } from 'react-beautiful-dnd'; import { DraggableCourseTile, CourseListHeader, REPOSITORY_ID } from '..'; import { getListId } from '../PlannerContainer/utils'; import './CourseList.css'; const getListStyle = isDraggingOver => ({ }); class CourseList extends Component { constructor(props) { super(props); this.state = { droppableId: this.props.year && this.props.quarter ? getListId(this.props.year, this.props.quarter) : REPOSITORY_ID } } render() { return ( <div className="CourseList"> {this.props.year && this.props.quarter ? <CourseListHeader year={this.props.year} quarter={this.props.quarter} /> : ''} <Droppable droppableId={this.state.droppableId}> {(provided, snapshot) => ( <div ref={provided.innerRef} className="CourseList-tilelist" style={getListStyle(snapshot.isDraggingOver)}> {this.props.items.map((item, index) => ( <DraggableCourseTile key={index} item={item} index={index} /> ))} {provided.placeholder} </div> )} </Droppable> </div> ) } } export default CourseList;
747a25b843ae3d5be3020b2fc34775c07f2d1a4d
[ "JavaScript", "Python", "Makefile" ]
20
Python
shannonphu/BruinPlanner
de1a19819292a63a2d0bd89f78606400b63b14ef
97736265bea54b510afc1177cfd379ac65846776
refs/heads/main
<file_sep>package com.lev; import java.util.Scanner; public class Smallest_largest { public static int smallest(int a, int b, int c){ int sm = a; if(b < sm){ sm = b; } if(c < sm){ sm = c; } return sm; } public static int largest(int a, int b, int c){ int lg = a; if(b > lg){ lg = b; } if(c > lg){ lg = c; } return lg; } public static void main(String[] args) { System.out.print("Enter 3 numbers : "); Scanner in = new Scanner(System.in); int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); int sm = smallest(a,b,c); int lg = largest(a,b,c); System.out.println("Largest : "+lg); System.out.println("Smallest : "+sm); } } <file_sep>#Average of N numbers print("Enter number of elements : ",end='') n=int(input()) print("Enter elements : ",end='') temp=0 total=0 while(temp!=n): val=int(input()) total=total+val temp=temp+1 avg=total/n; print("Average :",avg) <file_sep>package com.lev; import java.util.Scanner; public class Number_of_digits { public static void main(String[] args) { System.out.print("Enter number : "); Scanner in = new Scanner(System.in); int n = in.nextInt(); int temp = 0; while(n != 0){ n = n / 10; temp++; } System.out.print(temp); } } <file_sep>print("Enter the sides :",end='') a=int(input()) b=int(input()) print("Area :",a*b) <file_sep># DS-Algorithm Revisiting CP, Data Structures and Algorithms <file_sep>#include<iostream> using namespace std; int main(){ int n,temp; temp=0; cout<<"Enter number : "; cin>>n; while(n!=0){ n=n/10; temp++; } cout<<temp; return 0; }{ <file_sep>print("Enter two numbers: ",end='') n1=int(input()) n2=int(input()) if(n1>n2): val=n1 else: val=n2 while(True): if((n1%val==0) and (n2%val==0)): break else: val=val-1 print("HCF of",n1,"and",n2,":",val) <file_sep>print("Enter two numbers: ",end='') n1=int(input()) n2=int(input()) if(n1>n2): val=n1 else: val=n2 while(True): if((val%n1==0) and (val%n2==0)): break else: val=val+1 print("LCM of",n1,"and",n2,":",val) <file_sep>package com.lev; import java.util.Scanner; public class Sum_of_digits { public static void main(String[] args) { int total=0; int r; System.out.print("Enter the number: "); Scanner in = new Scanner(System.in); int n = in.nextInt(); int temp = n; while (temp != 0){ r = temp % 10; total = total +r; temp=temp/10; } System.out.println(total); } } <file_sep>#include<iostream> using namespace std; int main(){ int n1,n2,a,b,temp,lcm,hcf; cout<<"Enter the numbers : "; cin>>n1>>n2; a=n1; b=n2; while(b!=0){ temp=b; b=a%b; a=temp; } hcf=a; lcm=n1*n2/hcf; cout<<"LCM of "<<n1<<" "<<n2<<" is :"<<lcm<<endl; cout<<"HCF of "<<n1<<" "<<n2<<" is :"<<hcf; return 0; } <file_sep>i=1 total=0 print("Enter the number :",end='') n=int(input()) while(i<n): if(n%i==0): total=total+i i=i+1 if(total==n): print(n,"is perfect") else: print(n,"is not perfect") <file_sep>#include<iostream> using namespace std; const float PI=3.14; int main(){ float r; cout<<"Enter the radius : "; cin>>r; cout<<"Area : "<<(PI*r*r); return 0; } <file_sep>package com.lev; import java.util.Scanner; public class Area_Triangle { public static void main(String[] args) { System.out.print("Enter 3 sides : "); Scanner in = new Scanner(System.in); int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); float s = (a + b + c)/2; float area =(float) Math.sqrt(s*(s-a)*(s-b)*(s-c)); System.out.print("Area : "+area); } } <file_sep>#include<iostream> using namespace std; int main(){ int n; cout<<"Enter the number"; cin>>n; if(n<=1){ cout<<n<<" is neither prime nor composite"; } else{ int c=2; while(c*c<=n){ if(n%c==0){ cout<<n<<" is not a prime"; exit(0); } c++; } cout<<n<<" is a prime"; } return 0; } <file_sep>pi=3.14 print("Enter the radius :",end='') r=float(input()) print("Area :",pi*r*r) <file_sep>import math print("Enter 3 sides :",end='') a=int(input()) b=int(input()) c=int(input()) s=(a+b+c)/2.0; area=math.sqrt(s*(s-a)*(s-b)*(s-c)) print("Area :",float(area)) <file_sep>#include<iostream> using namespace std; int main(){ int n1,n2,val; cout<<"Enter the numbers : "; cin>>n1>>n2; if(n1>n2){ val=n1; }else{ val=n2; } while(true){ if((val%n1==0) && (val%n2==0)){ break; } else{ val++; } } cout<<"LCM is : "<<val; return 0; } <file_sep>//AREA OF PARALLELOGRAM #include<iostream> using namespace std; int main() { float b,h,area; cout<<"Enter base, height : "; cin>>b>>h; area = b*h; cout<<"Area : "<<area; return 0; } <file_sep>#include<iostream> using namespace std; int main(){ int a,b,count,temp,n; a=0; b=1; cout<<"Enter n:"; cin>>n; count=2; cout<<a<<" "<<b<<" "; while(count<n){ temp=b; b=a+b; a=temp; cout<<b<<" "; count++; } return 0; } <file_sep>total=0 print("Enter the number :",end='') n=int(input()) temp=n while(temp!=0): r=temp%10 total=total+r temp=temp//10 print(total) <file_sep>#include<iostream> using namespace std; int main(){ int i=1,n; int sum=0; cout<<"Enter the number :"; cin>>n; while(i<n){ if(n%i==0) sum=sum+i; i++; } if(sum==n){ cout<<n<<" is a Perfect number";} else{ cout<<n<<" is not a Perfect number";} return 0; } <file_sep>print("Enter n:",end='') n=int(input()) a=0 b=1 count=2 print(a,b,end=' ') while(count<n): temp=b b=a+b a=temp print(b,end=' ') count=count+1 <file_sep>def natural(n): n=(n*(n+1)/2) return n print("Enter n :",end=' ') n=int(input()) print("Sum of first",n,"natural numbers :",natural(n)) <file_sep>//Area of equilateral triangle #include<iostream> #include<cmath> using namespace std; int main(){ int s; cout<<"Enter side :"; cin>>s; float area = sqrt(3)*s*s/4; cout<<"Area : "<<area; return 0; } <file_sep>print("Enter the year : ",end='') yr=int(input()) if(((yr%4==0) and (yr%100!=0)) or yr%400==0): print(yr,"is leap year") else: print(yr,"is not a leap year") <file_sep>#include<iostream> using namespace std; int main(){ int n,r,sum=0,temp; cout<<"Enter the number : "; cin>>n; temp=n; while(temp!=0){ r=temp%10; sum=sum+r; temp=temp/10; } cout<<sum; return 0; } <file_sep>#include<iostream> using namespace std; int smallest(int a, int b, int c){ int min=a; if(b<min){ min=b; } if(c<min){ min=c; } return min; } int largest(int a, int b, int c){ int max=a; if(b>max){ max=b; } if(c>max){ max=c; } return max; } int main(){ int a,b,c; cout<<"Enter 3 numbers :"; cin>>a>>b>>c; cout<<"Largest : "<<largest(a,b,c)<<endl; cout<<"Smallest: "<<smallest(a,b,c); return 0; } <file_sep>#include<iostream> using namespace std; int main(){ float p,r,t,s; cout<<"Enter Principal Amount : "; cin>>p; cout<<"Rate of Interest in % : "; cin>>r; cout<<"Time (in years) : "; cin>>t; s=p*r*t/100; cout<<"Simple Interest = "<<s; return 0; } <file_sep>def smallest(a,b,c): small=a if(b<small): small=b if(c<small): small=c return small def largest(a,b,c): large=a if(b>large): large=b if(c>large): large=c return large a,b,c=[int(x) for x in input("Enter three numbers :").split()] print("Largest :",largest(a,b,c)) print("Smallest:",smallest(a,b,c)) <file_sep>print("Enter Principal Amount : ",end='') p=float(input()) print("Rate of Interest in % : ",end='') r=float(input()) print("Time (in years) : ",end='') t=float(input()) s=p*r*t/100; print("Simple Interest :",s); <file_sep>print("Enter number : ",end='') n=int(input()) res=0 while(n!=0): r=n%10 res=res*10+r n=n//10 print(res) <file_sep>print("Enter two numbers: ",end='') n1=int(input()) n2=int(input()) a=n1 b=n2 while(b!=0): temp=b b=a%b a=temp hcf=a lcm=n1*n2//hcf print("LCM of",n1,n2,":",lcm) print("HCF of",n1,n2,":",hcf) <file_sep>#include<iostream> using namespace std; int sumNatural(int n){ n=(n*(n+1))/2; return n; } int main(){ int n; cout<<"Enter n : "; cin>>n; cout<<"Sum of first "<<n<<" natural numbers : "<<sumNatural(n); return 0; } <file_sep>package com.lev; import java.util.Scanner; public class Area_Circle { public static void main(String[] args) { System.out.print("Enter the radius : "); Scanner in = new Scanner(System.in); float r = in.nextFloat(); float res = (float) (Math.PI * r * r); System.out.println("Area : "+res); } } <file_sep>package com.lev; import java.util.Scanner; public class SimpleInterest { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter Principal Amount : "); float p = input.nextFloat(); System.out.print("Rate of Interest in % : "); float r = input.nextFloat(); System.out.print("Time (in years) : "); float t = input.nextFloat(); float s = (p*r*t)/100 ; System.out.println("Simple Interest : "+s); } } <file_sep>print("Enter base and height :",end='') b=float(input()) h=float(input()) area=b*h print("Area :",area) <file_sep>package com.lev; import java.util.Scanner; public class Area_Rectangle { public static void main(String[] args) { System.out.print("Enter the sides : "); Scanner in = new Scanner(System.in); int a = in.nextInt(); int b = in.nextInt(); System.out.println("Area : "+(a*b)); } } <file_sep>//Average of N numbers #include<iostream> using namespace std; int main(){ int n,temp,val,sum; float avg; cout<<"Enter number of elements : "; cin>>n; cout<<"Enter elements :"; temp=0; sum=0; while(temp!=n){ cin>>val; sum=sum+val; temp++; } avg=sum/n; cout<<"Average : "<<avg; return 0; } <file_sep>def fact(n): if(n==0): return 1 return n*fact(n-1) print("Enter the number : ",end='') n=int(input()) val=fact(n) print("Factorial of ",n," :",val) <file_sep>print("Enter the number: ") n=int(input()) if(n<=1): print(n, " is neither prime nor composite") else: c=2 while(c*c<=n): if(n%c==0): print(n," is not a prime") exit() c=c+1 print(n," is a prime") <file_sep>package com.lev; import java.util.Scanner; public class Checkprime { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the number : "); int n = input.nextInt(); if (n <= 1) { System.out.println(n + " is neither prime nor composite"); } else{ int c = 2; while (c * c <= n) { if (n % c == 0) { System.out.println(n + " is not a prime"); System.exit(0); } c++; } System.out.println(n + " is a prime"); } } } <file_sep>print("Enter the number :",end=' ') n=int(input()) if(n%2==0): print(n,"is even") else: print(n,"is odd") <file_sep>//Area of Triangle #include<iostream> #include<cmath> using namespace std; int main(){ int a,b,c; float s,area; cout<<"Enter 3 sides : "; cin>>a>>b>>c; s=(a+b+c)/2; area=sqrt(s*(s-a)*(s-b)*(s-c)); cout<<"Area : "<<area; return 0; } <file_sep>package com.lev; import java.util.Scanner; public class Reverse_number { public static void main(String[] args) { System.out.print("Enter number :"); Scanner a = new Scanner(System.in); int n = a.nextInt(); int res = 0; while(n!=0){ int r = n % 10; res = res * 10 + r; n = n / 10; } System.out.print(res); } } <file_sep>#include<iostream> using namespace std; int main(){ int yr; cout<<"Enter year to check : "; cin>>yr; if((yr%4==0 && yr%100!=0) || yr%400==0){ cout<<yr<<" is a leap year"; }else{ cout<<yr<<" is not a leap year"; } return 0; } <file_sep>#include<iostream> using namespace std; int main(){ int n1,n2,val; cout<<"Enter the numbers : "; cin>>n1>>n2; if(n1>n2){ val=n1; }else{ val=n2; } while(true){ if((n1%val==0) && (n2%val==0)){ break; } else{ val--; } } cout<<"HCF is : "<<val; return 0; } <file_sep>#Area of equilateral triangle import math print("Enter side :",end='') s=float(input()) a=math.sqrt(3)*s*s/4; print("Area :",round(a,5)); <file_sep>print("Enter number : ",end='') n=int(input()) temp=0 while(n!=0): n=n//10 temp=temp+1 print(temp)
02ac28215f83ffd43d35e0549b56eee98d2d99a1
[ "Markdown", "Java", "Python", "C++" ]
48
Java
labeebev/DS-Algorithm
57e1a66edb642d19e97ebda6ee6393f8370546bc
90ab29a9f257d202ff5d52c82a4170ce21dd18ec
refs/heads/master
<repo_name>jshepley14/scenevalidator<file_sep>/src/examples/src/build_tower.cpp /**************************************************** Author: <NAME> <EMAIL> Description: This code provides builds the highest stable tower of three objects. The order of objects to build the tower is known. The three objects are 1. paper bowl, 2. red mug, and 3. a model dog. First the paper bowl alone is placed in the simulator and it's z position is varried going from a low position incrementing grdually until it reaches a stable position. Then the red mug is placed in the simulator with the paper bowl. The paper bowl is now permanently at its lowest stable position. The red mug's z position is varried going from a low position incrementing grdually until it reaches a stable position (on top of the paper bowl). This process is repeated for the dog and it ends up stably on top of the mug which is on top of the paper bowl. All of this process takes place without drawing and happens in 0.3 sec. You can draw but it will take around 30 sec. because it has to open and immediately close around the window around 100 times. No matter if you decide to draw or not during the search time, at the end of this program, a window appears and draws the stable heighest configuration. ****************************************************/ #include "sceneValidator.h" #include <map> #include <cassert> #include <string.h> #include <fstream> #include <cmath> #include <chrono> #include <stdio.h> #include <iostream> #include <Eigen/Dense> #include <Eigen/Geometry> #include <ros/ros.h> #include <ros/package.h> using namespace std; //get file paths for models const string paper_bowl = ros::package::getPath("scenevalidator") + "/src/examples/src/models/paper_bowl.obj"; const string red_mug = ros::package::getPath("scenevalidator") + "/src/examples/src/models/red_mug.obj"; const string dog = ros::package::getPath("scenevalidator") + "/src/examples/src/models/dog.obj"; int main (int argc, char **argv) { // Here's all the input*********************************************************************************************************** //just the paper_bowl vector<string> filenames1 = {paper_bowl}; vector<string> modelnames1 = {"paper_bowl"}; //paper_bowl and red_mug vector<string> filenames2 = {paper_bowl, red_mug}; vector<string> modelnames2 = {"paper_bowl", "red_mug"}; //paper_bowl, red_mug, and dog vector<string> filenames3 = {paper_bowl, red_mug, dog}; vector<string> modelnames3 = {"paper_bowl", "red_mug","dog"}; //ground truth for a stable tower is paper_bowl (0,0,0.27) red_mug (0,0,1.13) dog (0,0,2.03) //make affine3d's Eigen::Quaterniond q; q = Eigen::Quaterniond(0.5, 0.5, 0, 0); //orientation is just standard identity matrix q.normalize(); Eigen::Affine3d aq = Eigen::Affine3d(q); Eigen::Affine3d t(Eigen::Translation3d(Eigen::Vector3d(0,0,0))); //paper_bowl Eigen::Affine3d a = (t*aq); q = Eigen::Quaterniond(0.5, 0.5, 0, 0); //orientation is just standard identity matrix q.normalize(); aq = Eigen::Affine3d(q); t = (Eigen::Translation3d(Eigen::Vector3d(0,0,0))); //mug Eigen::Affine3d b = (t*aq); q = Eigen::Quaterniond(0.5, 0.5, 0, 0); //orientation is just standard identity matrix q.normalize(); aq = Eigen::Affine3d(q); t = (Eigen::Translation3d(Eigen::Vector3d(0,0,0))); //dog Eigen::Affine3d c = (t*aq); vector<Eigen::Affine3d> model_poses = {a,b,c}; //put affines into vector ///........................................not used q = Eigen::Quaterniond(0.3, 0.7, 0, 0); q.normalize(); aq = Eigen::Affine3d(q); t = (Eigen::Translation3d(Eigen::Vector3d(-2,0, 1.59))); Eigen::Affine3d a2 = (t*aq); vector<Eigen::Affine3d> model_poses2 = {a2,b,c}; //teacup falling from the sky // Here's all the input^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //timer variables require c++11 static chrono::steady_clock::time_point startTime, endTime; startTime = chrono::steady_clock::now(); //start the timer /* Search #1: find lowest stable position for paper_bowl*/ // construct object and set parameters SceneValidator *scene = new SceneValidator; // construct object and set parameters //scene->setParams("DRAW", true); //you could draw the search if you want scene-> setModels(modelnames1, filenames1); // set all the model's data to be ready for simulation scene-> setParams("THRESHOLD", 0.01); // set the threshold to be 0.01 double i = 0; // this is where the bowl will start testing stability positions while(i <= 3){ // 3 is the highest z we will allow to be possibly in the search space model_poses[0].translation()[2]=i; // sets the model's z position to i bool valid = scene-> isValidScene(modelnames1, model_poses); //test if scene is stable (valid) or not if (valid){ cout<<"TRUE paper bowl z pos at "; cout<<model_poses[0].translation()[2]<<endl; //print the paper bowl's z position break; } i=i+0.01; //increment by 0.01 (that'll be our resolution) } delete scene; /* Search #2: find lowest stable position for red_mug (on top of paper_bowl) */ SceneValidator *scene2 = new SceneValidator; //scene2->setParams("DRAW", true); //you could draw the search if you want scene2->setModels(modelnames2, filenames2); scene2->setParams("THRESHOLD", 0.04); //decided threshold to be 0.04. using 0.01 might find not solutions //i = model_poses[0].translation()[2]*2; //you could make i start at 2*(the stable z position that was just found) i=1.0; //I just chose the z position search to start at this number while(i <= 3){ // 3 is the highest z we will allow to be possibly in the search space model_poses[1].translation()[2]=i; bool valid = scene2->isValidScene(modelnames2, model_poses); if (valid){ cout<<"TRUE red mug z pos at "; cout<<model_poses[1].translation()[2]<<endl; //print the red mug's z position break; } i=i+0.01; } delete scene2; /* Search #3: find lowest stable position for dog (on top of red_mug and paper_bowl) */ SceneValidator *scene3 = new SceneValidator; //scene3 ->setParams("DRAW", true); //you could draw the search if you want scene3->setScale(2,10); //need to scale the 2rd item (vector[2] = dog) down by factor of 10 (default is 100) scene3 ->setModels(modelnames3, filenames3); scene3 ->setParams("THRESHOLD", 0.05); //decided threshold to be 0.04 //i=model_poses[1].translation()[2]; //could start i based on position that was previusly found i=1.8; //decided to choose to start search at this numeber while(i <= 3){ //don't want to search beyond z = 3 model_poses[2].translation()[2]=i; bool valid = scene3 ->isValidScene(modelnames3, model_poses); if (valid){ cout<<"TRUE dog z pos at "; cout<<model_poses[2].translation()[2]<<endl; //print the dog's z position //end the timer endTime = chrono::steady_clock::now(); auto diff = endTime - startTime; cout <<"Time: "<< chrono::duration <double, milli> (diff).count() << " ms" << endl; scene3->setParams("DRAW", true); //draw the scene scene3->isValidScene(modelnames3, model_poses); //running the scene here would return false for some reason ...However see below cout<<"Look above the simulation command menu to see timing results and positions. Ctrl-X to close window"<<endl; break; } i=i+0.01; } //Run the simulator on the scene whic we know is valid and has heighest height scene3->setParams("PRINT_CHKR_RSLT", true); //print out the checking results scene3->setParams("STEP4", 1000); //4th check is set to super long time so viewer can have time to see the configuration scene3->isValidScene(modelnames3, model_poses); //run the simulator on scene we know is valid and highest delete scene3 ; //program is finished return 0; }<file_sep>/src/examples/src/testParams.cpp /**************************************************** Author: <NAME> <EMAIL> Description: This program loads three objects where the first configuration is in static equilibrium and the second scene configuration is not in static equilibrium. Additionally, this program demonstrates the use of how to set parameters and construct a custom scene object. ****************************************************/ #include "sceneValidator.h" #include <map> #include <cassert> #include <string.h> #include <fstream> #include <cmath> #include <chrono> #include <stdio.h> #include <iostream> #include <Eigen/Dense> #include <Eigen/Geometry> #include <ros/ros.h> #include <ros/package.h> using namespace std; //get file path for models const string wine_glass = ros::package::getPath("scenevalidator") + "/src/examples/src/models/wine_glass.obj"; const string paper_bowl = ros::package::getPath("scenevalidator") + "/src/examples/src/models/paper_bowl.obj"; const string red_mug = ros::package::getPath("scenevalidator") + "/src/examples/src/models/red_mug.obj"; int main (int argc, char **argv) { // Here's all the input*********************************************************************************************************** //doesn't load this flipped version of the file (reversing coordinates makes negative dot product calculations) vector<string> filenames = {wine_glass, paper_bowl, red_mug}; vector<string> modelnames = {"wine_glass", "paper_bowl", "red_mug"}; //make affine3d's Eigen::Quaterniond q; q = Eigen::Quaterniond(0.5, 0.5, 0, 0); //identity matrix q.normalize(); Eigen::Affine3d aq = Eigen::Affine3d(q); Eigen::Affine3d t(Eigen::Translation3d(Eigen::Vector3d(-4,0,1.25))); //wine_glass Eigen::Affine3d a = (t*aq); q = Eigen::Quaterniond(0.5, 0.5, 0, 0); //identity matrix q.normalize(); aq = Eigen::Affine3d(q); t = (Eigen::Translation3d(Eigen::Vector3d(0,0,0.13))); //paper bowl Eigen::Affine3d b = (t*aq); q = Eigen::Quaterniond(0.5, 0.5, 0, 0); //identity matrix q.normalize(); aq = Eigen::Affine3d(q); t = (Eigen::Translation3d(Eigen::Vector3d(4,0,0.66))); //<NAME> Eigen::Affine3d c = (t*aq); vector<Eigen::Affine3d> model_poses = {a,b,c}; //vector 1 of affines q = Eigen::Quaterniond(0.3, 0.7, 0, 0); //NOT identity matrix q.normalize(); aq = Eigen::Affine3d(q); t = (Eigen::Translation3d(Eigen::Vector3d(-2,0, 1.59))); //wine_glass Eigen::Affine3d a2 = (t*aq); vector<Eigen::Affine3d> model_poses2 = {a2,b,c}; //vector of new affines // Here's all the input^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // construct object and set parameters. ***See sceneValidator.cpp line 73 for explanation of parameters SceneValidator *scene = new SceneValidator(0,0,-0.5,0,0,1,0,100); //custom construct the object. See sceneValidator.h or sceneValidator.cpp for explanation of numbers in this constructor scene->setParams("BOUNCE", 0.0); scene->setParams("BOUNCE_vel", 0.0); scene->setParams("DENSITY", 5.0); scene->setParams("DRAW", true); //render the scene scene->setParams("FRICTION_mu", 1.0); //if you set this to 0 objects will be very slippery scene->setParams("FRICTION_mu2", 0.0); //changing this doesn't seem to do much scene->setParams("MAX_CONTACTS", 64); //maximum number of contact points per body scene->setParams("PRINT_AABB", true); //print the object's Bounding Box scene->setParams("PRINT_COM", true); //print the object's center of mass scene->setParams("PRINT_START_POS", true);//print an object's intial x,y,z center scene->setParams("PRINT_END_POS", true); //print an object's final x,y,z center scene->setParams("PRINT_DELTA_POS", true);//print an object's delta x,y,z for its center scene->setParams("PRINT_CHKR_RSLT", true);//print the result of check1, check2 etc.. scene->setParams("SOFT_CFM", 0.01); scene->setParams("STEP1", 5); //amount of simulation steps used in check #1 scene->setParams("STEP2", 14); scene->setParams("STEP3", 20); scene->setParams("STEP4", 110); scene->setParams("THRESHOLD", 0.08); //amount objects allowed to move while still being marked as in static equilibrium scene->setParams("TIMESTEP", 0.05); //controls how far each physics simulation step is taken scene->setScale(1, 200); //set modelnames[1] (paper bowl) to be scaled down by factor of 200 scene->setCamera(-0.0559, -8.2456, 6.0500, 89.0000, -25.0000, 0.0000 ); //set the camera position // API functions scene->setModels(modelnames, filenames); //set all the models and get their data scene->isValidScene(modelnames, model_poses); //check scene 1 cout<<"scene using modelposes2. Scroll ALL the way up for AABB and COM"<<endl; cout<<"\n"<<endl; scene->isValidScene(modelnames, model_poses2); //check scene 2 return 0; }<file_sep>/src/examples/src/singleModel.cpp /**************************************************** Author: <NAME> <EMAIL> Description: This program loads a single object four different times. You can use this program to see if it's possible to load a .obj file of your choice. The program also demonstrates how the object behaves in the simulation. While a window is open you can press Ctrl-X to slip to the next simulation of the object which will close current window and open new one. Remember to scale the item if neccessary in setScale. ****************************************************/ #include "sceneValidator.h" #include <map> #include <cassert> #include <string.h> #include <fstream> #include <cmath> #include <chrono> #include <stdio.h> #include <iostream> #include <Eigen/Dense> #include <Eigen/Geometry> #include <ros/ros.h> #include <ros/package.h> using namespace std; const string filename = ros::package::getPath("scenevalidator") + "/src/examples/src/models/wine_glass.obj"; int main (int argc, char **argv) { // Here's all the input*********************************************************************************************************** /* Doesn't load flipped version of file (reversing coordinate order in faces makes negative dot product calculations) Doing the flipping operation in some other software screws up center of mass calculations because the cross product produced is negative. Just unflip the flipped figures in software (meshlab), and in the future don't flip them at all. Or at the very least, just make sure your rotation/translation of the model in some other software doesn't screw up the vertice order for a face. */ vector<string> filenames = {filename}; vector<string> modelnames = {"test_object"}; //make affine3d's Eigen::Quaterniond q; q = Eigen::Quaterniond(0.5, 0.5, 0, 0); //identity matrix q.normalize(); Eigen::Affine3d aq = Eigen::Affine3d(q); Eigen::Affine3d t(Eigen::Translation3d(Eigen::Vector3d(0,0,2))); Eigen::Affine3d a = (t*aq); q = Eigen::Quaterniond(0.7, 0.3, 0, 0); //NOT identity matrix q.normalize(); aq = Eigen::Affine3d(q); t = (Eigen::Translation3d(Eigen::Vector3d(0,0,2))); Eigen::Affine3d b = (t*aq); q = Eigen::Quaterniond(0.5, 0.5, 0, 0); //identity matrix q.normalize(); aq = Eigen::Affine3d(q); t = (Eigen::Translation3d(Eigen::Vector3d(0,0,1))); Eigen::Affine3d c = (t*aq); q = Eigen::Quaterniond(0.3, 0.7, 0, 0); //NOT identity matrix q.normalize(); aq = Eigen::Affine3d(q); t = (Eigen::Translation3d(Eigen::Vector3d(0,0,1.7))); Eigen::Affine3d d = (t*aq); vector<Eigen::Affine3d> model_poses1 = {a}; vector<Eigen::Affine3d> model_poses2 = {b}; vector<Eigen::Affine3d> model_poses3 = {c}; vector<Eigen::Affine3d> model_poses4 = {d}; // Here's all the input^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // construct object and set parameters SceneValidator *scene = new SceneValidator; //construct the object scene->setParams("DRAW", true); //visualize what's actually happening scene->setParams("PRINT_CHKR_RSLT", true); //print out the result of each check scene->setParams("STEP1", 1000); //make the first check take 1000 steps (so viewer has plenty of time to see object's behavior) scene->setScale(0, 100); //set modelnames[0] to be scaled down by factor of 100 // API functions scene->setModels(modelnames, filenames); //set model and get its data scene->isValidScene(modelnames, model_poses1); //check scene 1 scene->isValidScene(modelnames, model_poses2); //check scene 2 scene->isValidScene(modelnames, model_poses3); //check scene 3 scene->isValidScene(modelnames, model_poses4); //check scene 4 return 0; }<file_sep>/README.md # scenevalidator catkin package I.) INSTALL instructions: 1.) Install libraries which SceneValidator depends on ODE(comes with Drawstuff), Eigen, OpenGl. (this assumes you already have ROS) To install ODE follow this guide: http://www.cs.cmu.edu/~cga/ode/ To install Eigen, follow this guide: http://eigen.tuxfamily.org/index.php?title=Main_Page To install OpenGl look online or try this: http://kiwwito.com/installing-opengl-glut-libraries-in-ubuntu/ 2.) In catkin workspace: catkin_make In ../devel/lib/scenevalidator: ./singleModel You can also try the demos build_tower, testParams, and load3twice RESOURCES ODE API: http://opende.sourceforge.net/docs/group__collide__sphere.html#ga25d47698e042a909be1fb9ffd81d0786 ODE Manual: http://ode-wiki.org/wiki/index.php?title=Manual:_All&printable=yes ODE guide and demos: http://demura.net/english II.) Understanding the code and loading models sceneValidator.cpp and sceneValidator.h are where the sceneValidator library is defined. There are a variety of parameters one can set in the physics simulator, so please consult line 73 in sceneValidator.cpp to find out info on those and see how changing them affects a simulation(testParams.cpp). You can choose to graphically visualize what is going on in the simulator and all the files in the examples folder have this as their default. To turn off the graphical rendering, just set the DRAW parameter to false. You can print out a lot of info about a scene's simulation by setting the PRINTxxx parameter to true. Some known limitations are that models with > 100,000 vertices can behave abnormally at the current parameter settings (however some parameters can be adjusted to allow better collision interaction). Using meshLab software can be helpful for reducing the number of vertices of an object. Follow the video here for instructions. https://www.youtube.com/watch?v=w_r-cT2jngk Some 3Dmodel scans may have holes in the object and it may be advantageous to close those holes too. Additionally, scaling the models is important. One can customize the object's size in the setScale() function. For models in Imperial College' s data set, to scale one object, you would do setScale(0, 0.1), but in sbpl_perception's data set you would do setScale(0,100). The difference is a factor of 1000 in terms of scale. That's because each model's data in the .obj file can be represented with large or smaller numbers so that's why scaling is important. If you load an object, but don't see anything it is most likely because you need to scale the object up (or down). The other files within src/svlibrary/src are files dedicated to parsing an object file's data. You'll also find a textures folder and that contains texture files which the drawstuff library relies on when drawing a scene. In testParams.cpp, a window opens showing a scene including a falling wine glass model. Then closes in around 0.5 sec. This is because the scene was considered not in static equilibrium. However if you wish to see the full unfolding of certain events even in a scene which is NOT in static equilibrium, then set CHECK1 to 1000 and the window will continue showing itself. III.) Motivation High level view for this project: In robotics, often times a robot's intended purpose is to manipulate objects whether it be picking items from a shelf and sorting them (Amazon Picking Challenge) or even grabbing ingredients from the table to cook. In these tasks it's critical for the robot to understand what it is picking up and exactly where it is in the enviornment. Perceiving many objects' positions and orientations in cluttered environments is a challenging task especially if some objects occlude others. Certain algorithms have been developed to solve this by virtually examining every object configuration that could possibly be generated and comparing it to the original image the robot sees. scenevalidator is a library that can be used to take in a multi-object scene and test if the objects are in a valid configuration or not. This prevents the algorithm from spending time comparing 1000s of scenes when in reality it never needed to because those scenes would not exist in real life due to the laws of physics. The result of using scenevalidator is that the computation time for the robot's perception algorithm is drastically reduced. Details and lower level goal: Coded in c++, uses Open Dynamics Engine, Drawstuff, and Eigen libraries. Given some number of objects along with their exact positions and orientations, the goal is to check if this set of objects called a "scene" is in static equilibrium or not. Taking a look at SceneValidator.h will give you a good idea. Because reducing computation time is the ultimate goal, I try to accomplish the scene validation as fast as possible while still giving good results. This is why Open Dynamics Engine was chosen as the physics library. Drawstuff is a primitive graphics library which can be turned off or on depending if the user wishes to view the scene unfold. Eigen is briefly used to manipulate some of the transform matrices. <file_sep>/src/svlibrary/src/texturepath.h //Specify the path to textures #include <string.h> #include <ros/ros.h> #include <ros/package.h> using namespace std; const string path = ros::package::getPath("scenevalidator") + "/src/svlibrary/src/textures"; const char *charPath = path.c_str(); #ifndef DRAWSTUFF_TEXTURE_PATH #define DRAWSTUFF_TEXTURE_PATH charPath #endif <file_sep>/src/examples/src/load3twice.cpp /**************************************************** Author: <NAME> <EMAIL> Description: This program loads three objects demonstrates how they behvae in the simulation. Then the some of the orientations or positions are changed and again the simulator shows how the objects behave. ****************************************************/ #include "sceneValidator.h" #include <map> #include <cassert> #include <string.h> #include <fstream> #include <cmath> #include <chrono> #include <stdio.h> #include <iostream> #include <Eigen/Dense> #include <Eigen/Geometry> #include <ros/ros.h> #include <ros/package.h> using namespace std; //get file path for models const string wine_glass = ros::package::getPath("scenevalidator") + "/src/examples/src/models/wine_glass.obj"; const string paper_bowl = ros::package::getPath("scenevalidator") + "/src/examples/src/models/paper_bowl.obj"; const string red_mug = ros::package::getPath("scenevalidator") + "/src/examples/src/models/red_mug.obj"; int main (int argc, char **argv) { // Here's all the input*********************************************************************************************************** //doesn't load this flipped version of the file (reversing coordinates makes negative dot product calculations) vector<string> filenames = {wine_glass, paper_bowl, red_mug}; vector<string> modelnames = {"wine_glass", "paper_bowl", "red_mug"}; //make affine3d's Eigen::Quaterniond q; q = Eigen::Quaterniond(0.5, 0.5, 0, 0); //identity matrix q.normalize(); Eigen::Affine3d aq = Eigen::Affine3d(q); Eigen::Affine3d t(Eigen::Translation3d(Eigen::Vector3d(-4,0,1.25))); //wine_glass Eigen::Affine3d a = (t*aq); q = Eigen::Quaterniond(0.5, 0.5, 0, 0); //identity matrix q.normalize(); aq = Eigen::Affine3d(q); t = (Eigen::Translation3d(Eigen::Vector3d(0,0,1.1))); //paper bowl Eigen::Affine3d b = (t*aq); q = Eigen::Quaterniond(0.5, 0.5, 0, 0); //identity matrix q.normalize(); aq = Eigen::Affine3d(q); t = (Eigen::Translation3d(Eigen::Vector3d(4,0,0.66))); //red mug Eigen::Affine3d c = (t*aq); vector<Eigen::Affine3d> model_poses = {a,b,c}; //vector 1 of affines q = Eigen::Quaterniond(0.3, 0.7, 0, 0); //NOT identity matrix q.normalize(); aq = Eigen::Affine3d(q); t = (Eigen::Translation3d(Eigen::Vector3d(-2,0, 1.59))); //wine_glass Eigen::Affine3d a2 = (t*aq); vector<Eigen::Affine3d> model_poses2 = {a2,b,c}; //vector of new affines // Here's all the input^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // construct object and set parameters SceneValidator *scene = new SceneValidator; //construct the object scene->setParams("DRAW", true); //visualize what's actually happening scene->setParams("PRINT_CHKR_RSLT", true); //print out the result of each check scene->setParams("STEP1", 1000); //make the first check take 1000 steps so user has plenty of time to see what's going on scene->setScale(1, 200); //set modelnames[1] to be scaled down by factor of 200 // API functions scene->setModels(modelnames, filenames); //set all the models and get their data scene->isValidScene(modelnames, model_poses); //check scene 1 //Press Ctrl-X when window pops up to exit above^ and start the simulation below scene->isValidScene(modelnames, model_poses2); //check scene 2 return 0; }<file_sep>/src/svlibrary/src/sceneValidator.h /****************************************************/ // Author: <NAME> // Contact: <EMAIL> // Location: Carnegie Mellon University Robotics Institute // Date: July 2016 //Description: This code provides functions which can be used to check if an set of objects are in static // equilibrium or not. The method to do this relies on in Open Dynamics Engine, a physics engine. // Gitthub: https://github.com/jshepley14/PhysicsEngine /****************************************************/ #include <stdio.h> #include <iostream> #include <Eigen/Dense> #include <Eigen/Geometry> #include <ode/ode.h> #ifndef SCENEVALIDATOR_H #define SCENEVALIDATOR_H class SceneValidator{ private: dThreadingThreadPoolID pool; //used for ODE's threating functions dThreadingImplementationID threading; //used for ODE's threating functions public: SceneValidator(double GRAVITYx, double GRAVITYy, double GRAVITYz, double PLANEa, double PLANEb, double PLANEc, double PLANEd, double DEFAULT_SCALE); //custom constructor SceneValidator(); //default constructor ~SceneValidator(); //destructor /* Allows the user to set certain parameters. All parameters able to be set are in explained in detail in sceneValidator.cpp */ bool setParams(std::string param_name, double param_value); /* Allows user to set scale of specific object. thisObject is the nth model in the modelnames vector. To scale the modelnames[0], thisObject should equal 0 */ bool setScale(int thisObject, double scaleFactor); /* Allows user to set camera viewpoint when rendering a scene */ bool setCamera(float x, float y, float z, float h, float p, float r); /*Given model names and their filepaths, set the model data to be ready for simulation in isValidScene. Files should be in .obj format. */ void setModels(std::vector<std::string> modelnames, std::vector<std::string> filepath); /*Given a list of objects and a list of the 6 DoF pose for each object, check if a scene is physically valid */ bool isValidScene(std::vector<std::string> modelnames, std::vector<Eigen::Affine3d> model_poses); }; #endif <file_sep>/src/svlibrary/src/sceneValidator.cpp /****************************************************/ // Author: <NAME> // Contact: <EMAIL> or <EMAIL> // Location: Carnegie Mellon University Robotics Institute // Date: July 2016 //Description: This code provides functions which can be used to check if a set of objects are in static // equilibrium or not. The method to do this relies on in Open Dynamics Engine, a physics engine. // Gitthub: https://github.com/jshepley14/PhysicsEngine // Glossary: // "ODE": Open Dynamics Engine http://www.ode.org/ // "draw": render a scene using the drawstuff graphics library and actually see how the objects are behaving // "ODE trimesh demo": refers to demo_moving_trimesh.cpp a demo program in ODE's demo folder /****************************************************/ /* headers */ #include "sceneValidator.h" //contains the header file for this .cpp file #include <map> //used to make hashmap #include <cassert> //used to make hashmap #include <ode/ode.h> //main physics engine library #include <drawstuff/drawstuff.h> //this is the graphics library #include <string.h> //allows strings to be used #include <fstream> //allows some extra printing functions #include <cmath> //allows math functions like absolute value #include <chrono> //used for timing code #include <stdio.h> //common and neccesary c++ library #include <iostream> //used for printing #include <Eigen/Dense> //used for dealing with Eigen data types #include <Eigen/Geometry> //used for dealing with Eigen data types #include "objLoader.h" //used for parsing .obj file #include "texturepath.h" //used for getting path to textures /*definitions */ #ifdef _MSC_VER #pragma warning(disable:4244 4305) // for VC++, no precision loss complaints #endif // select correct drawing functions, really only dsDrawTriangleD is used in this program #ifdef dDOUBLE #define dsDrawBox dsDrawBoxD #define dsDrawSphere dsDrawSphereD #define dsDrawCylinder dsDrawCylinderD #define dsDrawCapsule dsDrawCapsuleD #define dsDrawLine dsDrawLineD #define dsDrawTriangle dsDrawTriangleD #endif // some constants #define NUM 200 // max number of objects (FYI 14 objects make program 10x slower than 2 objects and Number of Objects vs Time is linear) #define GPB 3 // maximum number of geometries per body using namespace std; /* variables IMPORTANT --- Variables that will affect time to validate scene --- DRAW (rendering an image significantly slows down computation time) MAX_CONTACTS STEP1, STEP2, STEP3, and STEP4 THRESHOLD TIMESTEP --- Variables that affect THRESHOLD --- BOUNCE BOUNCE_vel DENSITY FRICTION_mu GRAVITYz SOFT_CFM --- Variables that affect physics accuracy --- BOUNCE BOUNCE_vel DENSITY FRICTION_mu GRAVITYz SOFT_CFM TIMESTEP DEFAULT_SCALE MAX_CONTACTS */ //Variables that can be set in setParams() or in custom constructor or in setScale() static double BOUNCE = 0.0; //change the bounciness static double BOUNCE_vel = 0.0; //change the bounciness speed static double DEFAULT_SCALE = 100; //The default value each .obj files data is scaled down by. Set scale in setScale static double DENSITY = 5.0; //The default is from ODE trimesh demo static bool DRAW = false; //used to switch on or off the drawing of the scene static double FRICTION_mu = 1.0; //if you set this to 0 objects will be very slippery static double FRICTION_mu2 = 0.0; //changing this doesn't seem to do much static int MAX_CONTACTS = 64; //maximum number of contact points per body static double GRAVITYx = 0; //gravitational force coming from x direction static double GRAVITYy = 0; //gravitational force coming from y direction static double GRAVITYz = -0.5; //yes, this is not -9.8, but this was the default that ODE trimesh demo had. Using -9.8 in this program prevents accuracy unless you change other variables like TIMESTEP static double PLANEa = 0; //Equation of a plane: a*x+b*y+c*z = d The normal vector must have length 1 static double PLANEb = 0; static double PLANEc = 1; static double PLANEd = 0; static bool PRINT_AABB = false; //print the object's Bounding Box static bool PRINT_CHKR_RSLT = false; //print the result of check1, check2 etc.. static bool PRINT_COM = false; //print the object's center of mass static bool PRINT_DELTA_POS = false; //print an object's delta x,y,z for its center static bool PRINT_END_POS = false; //print an object's final x,y,z center static bool PRINT_START_POS = false; //print an object's intial x,y,z center static double SOFT_CFM = 0.01; //makes "system more numerically robust" according to ODE manual. Not 100% sure what it does... The current number is from a default demo. static int STEP1=6; //amount of simulation steps used in check #1 static int STEP2=14; //amount of simulation steps used in check #2 static int STEP3=20; //amount of simulation steps used in check #3 static int STEP4=110; //amount of simulation steps used in check #4 static double THRESHOLD = 0.08; //amount objects allowed to move while still being marked as in static equilibrium static double TIMESTEP = 0.05; //controls how far each physics simulation step is taken //variables used when DRAW = true float xyz[3]={ -0.0559, -8.2456, 6.0500}; //this sets the x,y,z of the camera position when you view a drawing float hpr[3]={ 89.0000, -25.0000, 0.0000}; //this sets the heading, pitch and roll numbers in degrees(camera angle) of the camera when you view a drawing static int counter=0; //used within simulation to count until dsSTEP, indicates termination of drawing window static int dsSTEP=100; //default simulation step number when drawing a scene. To change dsSTEP, just change STEP1,2,3 or 4. static int HEIGHT=500; //window height static int WIDTH=1000; //window width //timer variables, requires c++11 static chrono::steady_clock::time_point startTime, endTime; /* dynamics and collision object (this is the model's data) */ struct MyObject { dBodyID body; // the body of the object dGeomID geom[GPB]; // geometries representing this body dReal matrix_dblbuff[ 16 * 2 ]; // double buffered matrices for 'last transform' setup (not sure what this does, it was from ODE trimesh demo) int last_matrix_index; // has to do with double buffered matrices (not sure what this does, it was from ODE trimesh demo) string model_ID; //model's I.D. dReal center[3]; //the center x,y,z coordinates int indCount; //number of triangles (indices) int vertCount; //number of vertices vector< vector<int> > indexDrawVec; //index list for Trimesh, but only used when drawing the Trimesh vector<int> indexGeomVec; //index list for the Trimesh, used all the time for Trimesh vector<float> vertexDrawVec; //vertex list for Trimesh, but only used when drawing the Trimesh vector<float> vertexGeomVec; //vetex list for the Trimesh, used all the time for Trimesh vector<float> centerOfMass; //center of mass x,y,z }; // this class is for center of mass calculations class data { public: float x1,y1,z1; float x2,y2,z2; float x3,y3,z3; }; //more variables, not really parameters though static int num=0; //number of objects in simulation static int nextobj=0; //next object to recycle if num==NUM static dWorldID world; //define the world in which simulation takes place static dSpaceID space; //define the space in which simulation takes place static MyObject obj[NUM]; //array of MyObject's static dJointGroupID contactgroup; //define the contactgroup in which objects have their contacts static int show_contacts = 0; //show contact points static int random_pos = 1; //drop objects from random position? static std::map<std::string, MyObject> m; //hashmap of object names and their MyObject data typedef dReal dVector3R[3]; //probably don't need this static double scaling[NUM]; //array to be filled with scaling info for each object /*functions are below*/ /* Handles objects' collisions (makes a termporary joint) This is called by dSpaceCollide when two objects in space are potentially colliding. I did not alter this function from ODE trimesh demo except for the parameter values. */ static void nearCallback (void *, dGeomID o1, dGeomID o2) { int i; // exit without doing anything if the two bodies are connected by a joint dBodyID b1 = dGeomGetBody(o1); dBodyID b2 = dGeomGetBody(o2); if (b1 && b2 && dAreConnectedExcluding (b1,b2,dJointTypeContact)) return; //set parameters for each contact on the object dContact contact[MAX_CONTACTS]; // up to MAX_CONTACTS contacts per box-box for (i=0; i<MAX_CONTACTS; i++) { contact[i].surface.mode = dContactBounce | dContactSoftCFM; contact[i].surface.mu = FRICTION_mu; contact[i].surface.mu2 = FRICTION_mu2; contact[i].surface.bounce = BOUNCE; contact[i].surface.bounce_vel = BOUNCE_vel; contact[i].surface.soft_cfm = SOFT_CFM; } //execute collision force (temporary joint) if (int numc = dCollide (o1,o2,MAX_CONTACTS,&contact[0].geom, sizeof(dContact))) { dMatrix3 RI; dRSetIdentity (RI); const dReal ss[3] = {0.02,0.02,0.02}; for (i=0; i<numc; i++) { dJointID c = dJointCreateContact (world,contactgroup,contact+i); dJointAttach (c,b1,b2); if (show_contacts) dsDrawBox (contact[i].geom.pos,RI,ss); } } } /* user can set viewpoint (camera angle) */ bool SceneValidator::setCamera(float x, float y, float z, float h, float p, float r){ xyz[0]=x; xyz[1]=y; xyz[2]=z; hpr[0]=h; hpr[1]=p; hpr[2]=r; } /* start simulation when drawing (sets the viewpoint) */ static void start(){ dsSetViewpoint (xyz,hpr); } /* after a certaint number of simulation steps, checks if an object from a the scene is valid or not */ static bool inStaticEquilibrium(MyObject &object){ double startX = object.center[0]; //get the object's initial x pos. double startY = object.center[1]; //get the object's initial y pos. double startZ = object.center[2]; //get the object's initial z pos. double endX = dBodyGetPosition(object.body)[0]; //get the object's final x pos. double endY = dBodyGetPosition(object.body)[1]; //get the object's final y pos. double endZ = dBodyGetPosition(object.body)[2]; //get the object's final z pos. double deltaX = std::abs(startX - endX); //calculate change in x double deltaY = std::abs(startY - endY); //calculate change in y double deltaZ = std::abs(startZ - endZ); //calculate change in z //some if statements for if you want to print out what's happening if (PRINT_START_POS || PRINT_END_POS || PRINT_DELTA_POS){ cout<<object.model_ID<<endl; } if (PRINT_START_POS){ cout<<"Start: "<<startX<<", "<<startY<<", "<<startZ<<endl; } if (PRINT_END_POS){ cout<<" End: "<<endX<<", "<<endY<<", "<<endZ<<endl; } if (PRINT_DELTA_POS){ cout<<"Delta: "<<deltaX<<", "<<deltaY<<", "<<deltaZ<<endl; } // compare the change in the object's position to see how far it moved // if change in object's position is greater than some threshold, return false if ( deltaX > THRESHOLD || deltaY > THRESHOLD || deltaZ > THRESHOLD ){ return false; } else{ return true; } } /* after a certaint number of simulation steps, checks if a scene is valid or not by iterating through the list of objects and checking if any of the object's moved too far */ static bool isValid(std::vector<string> modelnames){ bool stable = true; //bool that says scene is stable (valid) or not for (int i=0; i<num; i++){ //iterate through hashmap of modelnames that correspond to objects auto mappedObject= m.find(modelnames[i]); if (!inStaticEquilibrium(mappedObject->second) ){ //check if an object has moved too much (beyond threshold) stable = false; break; } } //print out the results and return the results as bools if (stable == true){ if(PRINT_CHKR_RSLT){ cout << "TRUE"<<endl; } return true; } else{ if(PRINT_CHKR_RSLT){ cout << "FALSE"<<endl; } return false; } } /* sets all the objects' data */ void setObject (MyObject &object, double number, char* filename){ double SCALE = number; //set the scale, or else object will be too big or too small, can set the scale manually if you want in setScale() //Load the file objLoader *objData = new objLoader(); //this objLoader code relies on objLoader.h and it's dependencies objData->load(filename); //load the file to be referenced as an objData object object.indCount = objData->faceCount; //get number of faces that make up the trimesh object.vertCount = objData->vertexCount; //get the number of vertices that make up the trimesh //get the center of mass. The procedure to do this was inspired by http://stackoverflow.com/questions/2083771/a-method-to-calculate-the-centre-of-mass-from-a-stl-stereo-lithography-file int numTriangles = objData->faceCount; data triangles[numTriangles]; for (int i =0; i < numTriangles; i ++){ // fill the triangles array with the data in the obj file obj_face *o = objData->faceList[i]; triangles[i].x1=objData->vertexList[ o->vertex_index[0] ]->e[0] ; triangles[i].y1=objData->vertexList[ o->vertex_index[0] ]->e[1] ; triangles[i].z1=objData->vertexList[ o->vertex_index[0] ]->e[2] ; triangles[i].x2=objData->vertexList[ o->vertex_index[1] ]->e[0] ; triangles[i].y2=objData->vertexList[ o->vertex_index[1] ]->e[1] ; triangles[i].z2=objData->vertexList[ o->vertex_index[1] ]->e[2] ; triangles[i].x3=objData->vertexList[ o->vertex_index[2] ]->e[0] ; triangles[i].y3=objData->vertexList[ o->vertex_index[2] ]->e[1] ; triangles[i].z3=objData->vertexList[ o->vertex_index[2] ]->e[2] ; } double totalVolume = 0, currentVolume; double xCenter = 0, yCenter = 0, zCenter = 0; for (int i = 0; i < numTriangles; i++) { totalVolume += currentVolume = (triangles[i].x1*triangles[i].y2*triangles[i].z3 - triangles[i].x1*triangles[i].y3*triangles[i].z2 - triangles[i].x2*triangles[i].y1*triangles[i].z3 + triangles[i].x2*triangles[i].y3*triangles[i].z1 + triangles[i].x3*triangles[i].y1*triangles[i].z2 - triangles[i].x3*triangles[i].y2*triangles[i].z1) / 6; xCenter += ((triangles[i].x1 + triangles[i].x2 + triangles[i].x3) / 4) * currentVolume; yCenter += ((triangles[i].y1 + triangles[i].y2 + triangles[i].y3) / 4) * currentVolume; zCenter += ((triangles[i].z1 + triangles[i].z2 + triangles[i].z3) / 4) * currentVolume; } double COMX = (xCenter/totalVolume)/SCALE; double COMY = (yCenter/totalVolume)/SCALE; double COMZ = (zCenter/totalVolume)/SCALE; if (PRINT_COM){ cout<<object.model_ID<<endl; printf("COM: %.4f, %.4f, %.4f\n", COMX, COMY, COMZ); } object.centerOfMass = {COMX,COMY,COMZ}; //finished getting the center of mass //Now get all the data from the .obj file (faces and vertices) //and put it in vectors so ODE can make a trimesh out of that data. //vectors "for drawing" have the same data as vectors "for geometry", //but it's more manageable to have seperate vectors when DRAW = true and when DRAW = false //Make 2D vector of indices for drawing int indexCount = object.indCount; for(int i=0; i<indexCount; i++) { vector<int> temp_vec; temp_vec.push_back((objData->faceList[i])->vertex_index[0]); temp_vec.push_back((objData->faceList[i])->vertex_index[1]); temp_vec.push_back((objData->faceList[i])->vertex_index[2]); object.indexDrawVec.push_back(temp_vec); } //Make 1D vector of indices for geometry for(int i=0; i< indexCount; i++) { object.indexGeomVec.push_back((objData->faceList[i])->vertex_index[0]); object.indexGeomVec.push_back((objData->faceList[i])->vertex_index[1]); object.indexGeomVec.push_back((objData->faceList[i])->vertex_index[2]); } //The object's center of mass must be at 0,0,0 relative to the rest of the object, that's why we scale and then shift by the calculated centerOfMass //Make 1D vector of vertices for drawing int vertCount = object.vertCount; for(int i=0; i< vertCount ; i++){ object.vertexDrawVec.push_back( objData->vertexList[i]->e[0]/SCALE - object.centerOfMass[0]); object.vertexDrawVec.push_back( objData->vertexList[i]->e[1]/SCALE - object.centerOfMass[1]); object.vertexDrawVec.push_back( objData->vertexList[i]->e[2]/SCALE - object.centerOfMass[2]); } //Make 1D vector of vertices for geometry for(int i=0; i< vertCount ; i++){ object.vertexGeomVec.push_back( objData->vertexList[i]->e[0]/SCALE - object.centerOfMass[0]); object.vertexGeomVec.push_back( objData->vertexList[i]->e[1]/SCALE - object.centerOfMass[1]); object.vertexGeomVec.push_back( objData->vertexList[i]->e[2]/SCALE - object.centerOfMass[2]); } } /* construct the object and put it into the world */ void makeObject (MyObject &object){ int i,j,k; dMass m; //this is ODE's special "mass" object. It contains inertia info, actual weight and center of mass. Look at mass.h and mass.cpp for more info in ODE library object.body = dBodyCreate (world); //you must create a "body" AND a "geom" (geometry) to represent an model in ODE dBodySetData (object.body,(void*)(size_t)i); //build Trimesh geom dTriMeshDataID new_tmdata = dGeomTriMeshDataCreate(); //set a trimesh ODE data type dGeomTriMeshDataBuildSingle(new_tmdata, object.vertexGeomVec.data(), 3 * sizeof(float), //build the geometry of the trimesh object.vertCount, (int*)object.indexGeomVec.data(), object.indCount*3, 3 * sizeof(int)); object.geom[0] = dCreateTriMesh(space, new_tmdata, 0, 0, 0); //create the trimesh using the ODE trimesh data that was just defined dGeomSetData(object.geom[0], new_tmdata); //officially set the data into the object's geom (geometry) dMassSetTrimesh( &m, DENSITY, object.geom[0] ); //set the trimesh's mass //gets the absolute bounding box, you can print it. Nothing currently used the the AABB info, but could be helpful at some point dReal aabb[6]; dGeomGetAABB (object.geom[0], aabb); if (PRINT_AABB){ printf("AABB: minX %.3f, maxX %.3f, minY %.3f, maxY %.3f, minZ %.3f, maxZ %.3f\n",aabb[0],aabb[1],aabb[2],aabb[3],aabb[4],aabb[5] ); printf("\n"); } dGeomSetPosition(object.geom[0], m.c[0], m.c[1], m.c[2]); //this is required because ODE's mass has to be at (0,0,0) dMassTranslate(&m, -m.c[0], -m.c[1], -m.c[2]); //object's center of mass must be at 0,0,0 relative to the rest of the object //build Trimesh body and unite geom with body for (k=0; k < GPB; k++){ //set body loop if (object.geom[k]){ dGeomSetBody(object.geom[k],object.body); //unite body and geometry } } dBodySetMass(object.body,&m); //set the body's mass } /* set the objects' 6DoF poses */ void translateObject(MyObject &object, const dReal* center, const dMatrix3 R ){ object.center[0] = center[0]; //set the object's initial x position (used when comparing initial vs final positions) object.center[1] = center[1]; //set the object's initial y position object.center[2] = center[2]; //set the object's initial z position dBodySetPosition (object.body, center[0], center[1], center[2]); //now we ACTUALLY set it's position in the simulation dBodySetRotation (object.body, R); //set it's rotation dBodySetLinearVel(object.body, 0, 0, 0); //set linear velocity to 0, else it would keep old lin. & ang. vel. from before we translated it dBodySetAngularVel(object.body, 0, 0, 0); //set angular velocity to 0 } /* set previous transformation matrix for trimesh not entirely sure what this function's purpose is as it was directly from ODE trimesh demo */ void setCurrentTransform(dGeomID geom){ const dReal* Pos = dGeomGetPosition(geom); //get the object's current position const dReal* Rot = dGeomGetRotation(geom); //get the object's current rotation const dReal Transform[16] = { Rot[0], Rot[4], Rot[8], 0, Rot[1], Rot[5], Rot[9], 0, Rot[2], Rot[6], Rot[10], 0, Pos[0], Pos[1], Pos[2], 1 }; dGeomTriMeshSetLastTransform( geom, *(dMatrix4*)(&Transform) ); } /* simulation loop */ static void simLoop (int pause) { //if DRAW = true, this is used to terminate the simloop from dsSimulationLoop() if (counter == dsSTEP){ dsStop(); } counter ++; //define the space and collide function dSpaceCollide (space,0,&nearCallback); //not quite sure what this code block or what setCurrentTransform() does, but it was from ODE trimesh demo #if 1 if (!pause) { for (int i=0; i<num; i++) for (int j=0; j < GPB; j++) if (obj[i].geom[j]) if (dGeomGetClass(obj[i].geom[j]) == dTriMeshClass) setCurrentTransform(obj[i].geom[j]); } #endif if (!pause) dWorldQuickStep (world,TIMESTEP); //<- this is a big factor in accuracy and how long simulation takes //not 100% what dSpaceGetNumGeoms() does... It was in ODE trimesh demo. for (int j = 0; j < dSpaceGetNumGeoms(space); j++){ dSpaceGetGeom(space, j); } // remove all contact joints dJointGroupEmpty (contactgroup); //set the color and the texture for the objects when drawing them if(DRAW){ dsSetColor (1,1,0); dsSetTexture (DS_WOOD); } //updates the position and rotation with every step through the simulation for (int i=0; i<num; i++) { for (int j=0; j < GPB; j++) { if (obj[i].geom[j]) { if (dGeomGetClass(obj[i].geom[j]) == dTriMeshClass) { const dReal* Pos = dGeomGetPosition(obj[i].geom[j]); //get and set the new position const dReal* Rot = dGeomGetRotation(obj[i].geom[j]); //get and set the new rotation //this is where drawstuff library actually draws the trimesh if (DRAW) { for (int ii = 0; ii < obj[i].indCount; ii++) { const dReal v[9] = { // explicit conversion from float to dReal obj[i].vertexDrawVec[obj[i].indexDrawVec[ii][0] * 3 + 0], obj[i].vertexDrawVec[obj[i].indexDrawVec[ii][0] * 3 + 1], obj[i].vertexDrawVec[obj[i].indexDrawVec[ii][0] * 3 + 2], obj[i].vertexDrawVec[obj[i].indexDrawVec[ii][1] * 3 + 0], obj[i].vertexDrawVec[obj[i].indexDrawVec[ii][1] * 3 + 1], obj[i].vertexDrawVec[obj[i].indexDrawVec[ii][1] * 3 + 2], obj[i].vertexDrawVec[obj[i].indexDrawVec[ii][2] * 3 + 0], obj[i].vertexDrawVec[obj[i].indexDrawVec[ii][2] * 3 + 1], obj[i].vertexDrawVec[obj[i].indexDrawVec[ii][2] * 3 + 2] }; dsDrawTriangle(Pos, Rot, &v[0], &v[3], &v[6], 1); //a trimesh is made up of triangles so triangles are drawn } } //not quite sure what the following code from here until the end of this function does but it was from ODE's trimesh demos //the following comments are from the demo as well // tell the tri-tri collider the current transform of the trimesh -- // this is fairly important for good results. // Fill in the (4x4) matrix. dReal* p_matrix = obj[i].matrix_dblbuff + ( obj[i].last_matrix_index * 16 ); p_matrix[ 0 ] = Rot[ 0 ]; p_matrix[ 1 ] = Rot[ 1 ]; p_matrix[ 2 ] = Rot[ 2 ]; p_matrix[ 3 ] = 0; p_matrix[ 4 ] = Rot[ 4 ]; p_matrix[ 5 ] = Rot[ 5 ]; p_matrix[ 6 ] = Rot[ 6 ]; p_matrix[ 7 ] = 0; p_matrix[ 8 ] = Rot[ 8 ]; p_matrix[ 9 ] = Rot[ 9 ]; p_matrix[10 ] = Rot[10 ]; p_matrix[11 ] = 0; p_matrix[12 ] = Pos[ 0 ]; p_matrix[13 ] = Pos[ 1 ]; p_matrix[14 ] = Pos[ 2 ]; p_matrix[15 ] = 1; // Flip to other matrix. obj[i].last_matrix_index = !obj[i].last_matrix_index; dGeomTriMeshSetLastTransform( obj[i].geom[j], *(dMatrix4*)( obj[i].matrix_dblbuff + obj[i].last_matrix_index * 16 ) ); } } } } } /* special simulation loop needed when drawing a scene (ultimately still uses simloop() though) */ void drawstuffsimLoop(){ int argc=NULL; //just an argument that dsSimulationLoop must take. not used. char **argv=NULL; //just an argument that dsSimulationLoop must take. not used. dsFunctions fn; //defines callback functions used in dsSimulationLoop fn.version = DS_VERSION; //gets version number fn.start = &start; //start() is a function defined above which set the viewpoint fn.step = &simLoop; //simloop() is the simulaiton routine used in dsSimulationLoop fn.command = NULL; //if you want to have keyboard input. not used. fn.stop = NULL; //if you want to customize the stop function. not used. fn.path_to_textures = DRAWSTUFF_TEXTURE_PATH; //Remember to include text path in texturepath.h dsSimulationLoop (argc,argv,WIDTH,HEIGHT,&fn); } /* sets all the models' data */ void SceneValidator::setModels(std::vector<string> modelnames, std::vector<string> filenames){ //set the data in an obj array if( modelnames.size() != filenames.size()){ std::cout<<"***ERROR*** in setModels(std::vector<string> modelnames, std::vector<string> filenames). The problem is that modelnames is not the same size as filenames"<<endl; } else{ num = filenames.size(); //number of models in scene for (int i =0; i < num; i++){ obj[i].model_ID=modelnames[i]; //set model ID to the corresponding model name char *charfilenames = new char[filenames[i].length() + 1]; //convert to string std::strcpy(charfilenames, filenames[i].c_str()); //convert to string setObject(obj[i], scaling[i], charfilenames ); //set object's data makeObject(obj[i]); //create an object that can be used in simulation } } //make hashmap between modelnames and their data for (int i =0; i < num; i++){ m[modelnames[i]]=obj[i]; } } /*checks if scene is stable after certain number of steps */ static bool isStableStill(std::vector<string> modelnames, int step){ if (DRAW){ counter=0; dsSTEP=step; drawstuffsimLoop(); } else { for(int i = 0; i <= step; i++) { simLoop(0); } } return isValid(modelnames); } /* allows user to set certain parameters */ bool SceneValidator::setParams(std::string param_name, double param_value){ if( param_name.compare("STEP1") == 0 ){ STEP1 = param_value; return true; } else if( param_name.compare("STEP2") == 0 ){ STEP2 = param_value; return true; } else if( param_name.compare("STEP3") == 0 ){ STEP3 = param_value; return true; } else if( param_name.compare("STEP4") == 0 ){ STEP4 = param_value; return true; } else if( param_name.compare("GRAVITYx") == 0 ){ cout<<"Need to set GRAVITYx in the custom SceneValidator constructor. See sceneValidator.h for how to do that"; return true; } else if( param_name.compare("GRAVITYy") == 0 ){ cout<<"Need to set GRAVITYy in the custom SceneValidator constructor. See sceneValidator.h for how to do that"; return true; } else if( param_name.compare("GRAVITYz") == 0 ){ cout<<"Need to set GRAVITYz in the custom SceneValidator constructor. See sceneValidator.h for how to do that"; return true; } else if( param_name.compare("PLANEa") == 0 ){ cout<<"Need to set PLANEa in the custom SceneValidator constructor. See sceneValidator.h for how to do that"; return true; } else if( param_name.compare("PLANEb") == 0 ){ cout<<"Need to set PLANEb in the custom SceneValidator constructor. See sceneValidator.h for how to do that"; return true; } else if( param_name.compare("PLANEc") == 0 ){ cout<<"Need to set PLANEc in the custom SceneValidator constructor. See sceneValidator.h for how to do that"; return true; } else if( param_name.compare("PLANEd") == 0 ){ cout<<"Need to set PLANEd in the custom SceneValidator constructor. See sceneValidator.h for how to do that"; return true; } else if( param_name.compare("THRESHOLD") == 0 ){ THRESHOLD = param_value; return true; } else if( param_name.compare("TIMESTEP") == 0 ){ TIMESTEP = param_value; return true; } else if( param_name.compare("FRICTION_mu") == 0 ){ FRICTION_mu = param_value; return true; } else if( param_name.compare("FRICTION_mu2") == 0 ){ FRICTION_mu2 = param_value; return true; } else if( param_name.compare("BOUNCE") == 0 ){ BOUNCE = param_value; return true; } else if( param_name.compare("BOUNCE_vel") == 0 ){ BOUNCE_vel = param_value; return true; } else if( param_name.compare("SOFT_CFM") == 0 ){ SOFT_CFM = param_value; return true; } else if( param_name.compare("DRAW") == 0 ){ DRAW = param_value; return true; } else if( param_name.compare("PRINT_START_POS") == 0 ){ PRINT_START_POS = param_value; return true; } else if( param_name.compare("PRINT_END_POS") == 0 ){ PRINT_END_POS = param_value; return true; } else if( param_name.compare("PRINT_DELTA_POS") == 0 ){ PRINT_DELTA_POS = param_value; return true; } else if( param_name.compare("PRINT_CHKR_RSLT") == 0 ){ PRINT_CHKR_RSLT = param_value; return true; } else if( param_name.compare("DENSITY") == 0 ){ DENSITY = param_value; return true; } else if( param_name.compare("MAX_CONTACTS") == 0 ){ MAX_CONTACTS = param_value; return true; } else if( param_name.compare("PRINT_AABB") == 0 ){ PRINT_AABB = param_value; return true; } else if( param_name.compare("PRINT_COM") == 0 ){ PRINT_COM = param_value; return true; } else { cout<<"Invalid parameter name: "<<param_name; return false; } } /* allows user to set the scale of a specific object */ bool SceneValidator::setScale(int thisObject, double scaleFactor){ scaling[thisObject] = scaleFactor; } /* checks if a given scene is in static equilibrium or not */ bool SceneValidator::isValidScene(std::vector<string> modelnames, std::vector<Eigen::Affine3d> model_poses){ //set all the Objects's positions num = modelnames.size(); for (int i =0; i < num; i++){ auto mappedObject= m.find(modelnames[i]); //get model from hashmap Eigen::Affine3d a = model_poses[i]; const dMatrix3 R = { //convert affine info to a 3x3 rotation matrix and a x,y,z position array a(0,0), a(0,1), a(0,2), a(1,0), a(1,1), a(1,2), a(2,0), a(2,1), a(2,2) }; const dReal center[3] = {a.translation()[0],a.translation()[1], a.translation()[2]}; translateObject(mappedObject->second, center, R); //get the model name's MyObject info and feed it the position and rotation } //complete series of checks to see if scene is still stable or not if (!isStableStill(modelnames, STEP1)){ //check #1 return false; } else if (!isStableStill(modelnames, STEP2)){ //check #2 return false; } else if (!isStableStill(modelnames, STEP3)){ //check #3 return false; } else if (!isStableStill(modelnames, STEP4)){ //check #4 return false; } else{ return true; } } /* custom constructor to construct a SceneValidator object */ SceneValidator::SceneValidator(double GRAVITYx, double GRAVITYy, double GRAVITYz, double PLANEa, double PLANEb, double PLANEc, double PLANEd, double DEFAULT_SCALE){ //initialize ODE and the simulation enviornment dInitODE2(0); world = dWorldCreate(); space = dSimpleSpaceCreate(0); contactgroup = dJointGroupCreate (0); dWorldSetGravity (world,GRAVITYx,GRAVITYy,GRAVITYz); dWorldSetCFM (world,1e-5); dCreatePlane (space,PLANEa,PLANEb,PLANEc,PLANEd); //initialize ODE's threading functions dAllocateODEDataForThread(dAllocateMaskAll); threading = dThreadingAllocateMultiThreadedImplementation(); pool = dThreadingAllocateThreadPool(4, 0, dAllocateFlagBasicData, NULL); dThreadingThreadPoolServeMultiThreadedImplementation(pool, threading); dWorldSetStepThreadingImplementation(world, dThreadingImplementationGetFunctions(threading), threading); //scale the ALL objects to DEFAULT_SCALE for (int i =0; i < NUM; i++){ scaling[i] = DEFAULT_SCALE; } } /* default constructor to construct a SceneValidator object */ SceneValidator::SceneValidator(){ //initialize ODE and the simulation enviornment dInitODE2(0); world = dWorldCreate(); space = dSimpleSpaceCreate(0); contactgroup = dJointGroupCreate (0); dWorldSetGravity (world,GRAVITYx,GRAVITYy,GRAVITYz); dWorldSetCFM (world,1e-5); dCreatePlane (space,PLANEa,PLANEb,PLANEc,PLANEd); //initialize ODE's threading functions dAllocateODEDataForThread(dAllocateMaskAll); threading = dThreadingAllocateMultiThreadedImplementation(); pool = dThreadingAllocateThreadPool(4, 0, dAllocateFlagBasicData, NULL); dThreadingThreadPoolServeMultiThreadedImplementation(pool, threading); dWorldSetStepThreadingImplementation(world, dThreadingImplementationGetFunctions(threading), threading); //scale the ALL objects to DEFAULT_SCALE for (int i =0; i < NUM; i++){ scaling[i] = DEFAULT_SCALE; } } /* default destructor to destruct a SceneValidator object */ SceneValidator::~SceneValidator(){ //shut down threading dThreadingImplementationShutdownProcessing(threading); dThreadingFreeThreadPool(pool); dWorldSetStepThreadingImplementation(world, NULL, NULL); dThreadingFreeImplementation(threading); //shut down simulation enviornment dJointGroupDestroy (contactgroup); dSpaceDestroy (space); dWorldDestroy (world); dCloseODE(); }
37043a623d54f2acd66ad66541c4f2181e631a95
[ "Markdown", "C++" ]
8
C++
jshepley14/scenevalidator
e9781f9ebd84c827da2f9c9c7b0e30fb83bec9d5
b24f38618803aa8c225ecc81335ed2a49a276864
refs/heads/master
<repo_name>alkuntze/notification<file_sep>/teste/index.php <?php require __DIR__ . '/../lib_ext/autoload.php'; use Notification\Email; $novoEmail = new Email( 'smtp.mailtrap.io', 'ffda583bb093f1', 'f56902baaf33fa', '587', '<EMAIL>', '<NAME>' ); $novoEmail->sendEmail("Teste de envio de e-mail", "Esse é um e-mail de <b>teste</b>.", "<EMAIL>", "Ale", "<EMAIL>", "<NAME>"); var_dump($novoEmail);
c75d3309c5a447b0dd14c1166a25f79159ebb763
[ "PHP" ]
1
PHP
alkuntze/notification
8a0f54a1f99bcf96fb9de81239e16c660b1afe63
f9c528582e27a7a80dcf8c33da164f39e61b57ac
refs/heads/master
<file_sep>package org.example.Intrest; public class Intrest { int principal, time, rate; public Intrest(int principal, int time, int rate) { this.principal = principal; this.time = time; this.rate = rate; } }
cdd8d13113a4364bdebcd7a8656758c5020b921d
[ "Java" ]
1
Java
Tushar0135/Tushar_Exceptions_Logging_Epam
e28e145cb795270ae1b2fb75051e7137eca72456
dd8b9bbbeefa129a116cb1afb5b1e248409c889f
refs/heads/master
<file_sep>package section3; import javax.swing.JOptionPane; public class Greeter { public static void main(String[] args) { String name=JOptionPane.showInputDialog(null,"put a sentence"); } } <file_sep>package section4; import javax.swing.JOptionPane; public class QuizGame { public static void main(String[] args) { // 1. Create a variable to hold the user's score int x=0; // 2. Ask the user a question String name=JOptionPane.showInputDialog(null,"what is the world based off of"); // 3. Use an if statement to check if their answer is correct String str="starbucks frappucino"; if(str.equals("starbucks frappucino")) { // 4. if the user's answer is correct // -- add one to their score x = x + 1; } // 5. Create more questions by repeating steps 1, 2, and 3 below. name=JOptionPane.showInputDialog(null,"why do we have to keep making questions"); str="I do not know"; if(str.equals("I dont know")) { // 6. After all the questions have been asked, print the user's score } } }
0e28c8f96f3e35ebc1bb63f2c933fba3359c61f6
[ "Java" ]
2
Java
League-Workshop/intro-to-java-workshop-trstedk
1752cb1828f5c9c0a8c29ca961e8d5c0a61dc91a
b249ee8d5c0937e4379be2e41912f6e6fdac3c9e
refs/heads/master
<file_sep>def draw_man(number_of_wrong) if number_of_wrong == 0 puts "___________" puts "| |" puts "|" puts "|" puts "|" puts "|" puts "|" puts "------------" elsif number_of_wrong == 1 puts "___________" puts "| |" puts "| @" puts "|" puts "|" puts "|" puts "|" puts "------------" elsif number_of_wrong == 2 puts "___________" puts "| |" puts "| @" puts "| |" puts "|" puts "|" puts "|" puts "------------" elsif number_of_wrong == 3 puts "___________" puts "| |" puts "| @" puts "| /|" puts "|" puts "|" puts "|" puts "------------" elsif number_of_wrong == 4 puts "___________" puts "| |" puts "| @" puts "| /|\\" puts "|" puts "|" puts "|" puts "------------" elsif number_of_wrong == 5 puts "___________" puts "| |" puts "| @" puts "| /|\\" puts "| |" puts "|" puts "|" puts "------------" elsif number_of_wrong == 6 puts "___________" puts "| |" puts "| @" puts "| /|\\" puts "| |" puts "| /" puts "|" puts "------------" elsif number_of_wrong == 7 puts "___________" puts "| |" puts "| @" puts "| /|\\" puts "| |" puts "| / \\" puts "|" puts "------------" end end def check_letter(word, letter_guessed) letter_location_array = [] word_array = word.split("") letter_number = 0 word_array.each do |letter| if letter_guessed == letter letter_location_array.push(letter_number) end letter_number = letter_number + 1 end letter_location_array end def display_result(word, letters_guessed) word_array = word.split('') word_array.pop letter_number = 0 word_array.each do |letter| if letters_guessed.include?(letter) word_array[letter_number] = letter else word_array[letter_number] = '_' end letter_number = letter_number + 1 end puts word_array.to_s word_array end #Get Word from dictionary f = File.new('EnglishDictionary.txt','r') @dictionary_array = f.readlines f.close def new_word word = 'initialword' while word.length < 4 or word.length > 10 word = @dictionary_array.sample puts word end word end puts 'Let\'s plays some hangman!' word = new_word letters_guessed = [] puts word display_result(word, letters_guessed) number_of_wrong = 0 while number_of_wrong <= 7 draw_man(number_of_wrong) display_result(word, letters_guessed) puts 'So far, you\'ve guessed:' + letters_guessed.to_s puts 'Guess:' guess = gets.chomp.downcase if letters_guessed.include?(guess) puts 'You already guessed ' + gets.chomp elsif display_result(word, letters_guessed).include?('_') == false puts 'WINNER!' break else letters_guessed.push(guess) if check_letter(word, guess).empty? number_of_wrong = number_of_wrong + 1 puts 'Wrong!' end end end if number_of_wrong == 8 puts 'Sorry you lose' puts 'The word was : ' + guess else puts 'WINNER!' end
9985f5d65232b722f16d5efb633718270f7dcbc2
[ "Ruby" ]
1
Ruby
oh46367/hang_man_final
e1ed136ccab92c2bd0e84fc8978db5c1b88e7c2b
20b13e1b4122379d3387faaba93b2b86f124ed6c
refs/heads/master
<repo_name>hannodrefke/sms-challenge<file_sep>/assesmentSpec.js describe( "sendSmsMessage", function () { beforeEach(function() { sendSmsMessage = require('./assessment.js'); }); it("Sends text with 84 characters as one message", function () { let result = sendSmsMessage("Sends text with 84 characters as one message"); expect(result).toEqual(['Sends text with 84 characters as one message']); }); it("Sends text with 297 characters as 3 messages", function () { let result = sendSmsMessage("Zu finden sind solche Rezepte in einer App des Ministeriums, sie heißt: Beste Reste. Wie Kochsendungen die Deutschen von der Fertigkost weglocken sollen, will die App sie nun von sinnloser Verschwendung abhalten: Sind Lebensmittel nicht mehr ganz makellos, gehören sie noch lang nicht in den Müll.") expect(result).toEqual([ 'Zu finden sind solche Rezepte in einer App des Ministeriums, sie heißt: Beste Reste. Wie Kochsendungen die Deutschen von der Fertigkost weglocken - Part 1 of 3', 'sollen, will die App sie nun von sinnloser Verschwendung abhalten: Sind Lebensmittel nicht mehr ganz makellos, gehören sie noch lang nicht in den - Part 2 of 3', 'Müll. - Part 3 of 3' ]); }); }); <file_sep>/assessment.js /* SMS can only be a maximum of 160 characters. If the user wants to send a message bigger than that, we need to break it up. We want a multi-part message to have this added to each message: " - Part 1 of 2" */ // This method sends a text as SMS from sender 'from' to receiver 'to'. // If needed, long messages with length > 'MAX_LENGTH' are split into smaller // text messages and a multi-part message information is added " - Part X of Y". function sendSmsMessage (text, to, from) { const MAX_LENGTH = 160; let sendText = []; let returnData = []; if(text.length > MAX_LENGTH) { const SPLIT_REGEX = new RegExp(".{1,"+MAX_LENGTH+"}", "g"); sendText = text.match(SPLIT_REGEX); sendText = sendText.map((text, index) => { return { text: text, index: index+1, total: sendText.length }}); do { addMessageInformationText(sendText, MAX_LENGTH); } while(containsInvalidTextLength(sendText, MAX_LENGTH)); } else { sendText.push(text); } sendText.forEach((message) => { let textMessage = (typeof message === 'string') ? message : message.text + generateMessagePart(message.index, message.total); deliverMessageViaCarrier(textMessage, to, from); returnData.push(textMessage) }); return returnData; } // This method actually sends the message via an already existing SMS carrier // This method works, you don't change it, function deliverMessageViaCarrier (text, to, from) { try { SmsCarrier.deliverMessage(text, to, from); } catch(err) { // catch error tbd } } // This method cycles the array of splitted messages and trims the message text, // so that the multi-part information " - Part X of Y" can be inserted and the // text length matches 'maxLength'. // The text part that is cut off is moved to the next element of the array, or // into a new element, if no next element exists. If a new element is created // the method 'updateAllTotalValues' is called to update all existing elements. function addMessageInformationText(textArray, maxLength) { textArray.forEach((message, mindex) => { let { text, index, total } = message; let insContent = generateMessagePart(index, total); let insPos = maxLength - insContent.length; let stringBefore = text.slice(0, insPos); let stringAfter = text.slice(insPos); message.text = stringBefore; if(mindex < textArray.length-1) { let nextItem = textArray[mindex+1]; nextItem.text = stringAfter + nextItem.text; } else { let newIndex = newTotal = textArray.length+1; textArray.push({ text: stringAfter, index: newIndex, total: newTotal }); updateAllTotalValues(textArray); } }); } // This method cycles the array of splitted messages and updates the value // of the parameter 'total' if it does not match the array's length. function updateAllTotalValues(textArray) { const totalLength = textArray.length; textArray.forEach((message) => { if(message.total !== totalLength) { message.total = totalLength; } }); } // This method cycles the array of splitted messages and returns 'true' // if one message is longer than 'maxLength', otherwise it returns 'false' function containsInvalidTextLength(textArray, maxLength) { let foundInvalidItem = false; textArray.forEach((message) => { let messageTextWithMessagePart = message.text + generateMessagePart(message.index, message.total); if(messageTextWithMessagePart.length > maxLength) foundInvalidItem = true; }); return foundInvalidItem; } // This method returns the string for the the multi-part information // depending on the parameters 'index' and 'total'. function generateMessagePart(index, total) { return ` - Part ${index} of ${total}` } module.exports = sendSmsMessage;
a5355401b186504e741675e34594e4491b7bb07e
[ "JavaScript" ]
2
JavaScript
hannodrefke/sms-challenge
8b154d45b6bbaed361d84b26282c3a6f81c3fb6b
acc4f3e0a611ad3acbeaa271a9e2176b30bc433f
refs/heads/master
<repo_name>tuxmeister/EDEngineer<file_sep>/EDEngineer.Models/Operations/DumpOperation.cs using System.Collections.Generic; using System.Linq; namespace EDEngineer.Models.Operations { public class DumpOperation : JournalOperation { public List<MaterialOperation> DumpOperations { get; set; } public HashSet<Kind> ResetFilter { get; set; } public override void Mutate(State state) { foreach (var item in state.Cargo.Where(item => ResetFilter.Contains(item.Value.Data.Kind))) { state.IncrementCargo(item.Key, -1 * item.Value.Count); } foreach (var operation in DumpOperations) { state.IncrementCargo(operation.MaterialName, operation.Size); } } } }
2253776828b97adf69dad029149b88a81469767a
[ "C#" ]
1
C#
tuxmeister/EDEngineer
22ace511ccd4891bc2aa33cdf90d76026a5d77f4
02d117d4850df0b58e91ea22ef70d6b858c555e6