branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>aquasheep/GTFTSTG<file_sep>/GTFTSTG/src/com/aquasheep/GTFTSTG/Items/Rattle.java package com.aquasheep.GTFTSTG.Items; import com.aquasheep.GTFTSTG.GTFTSTG; public class Rattle extends Item { private static float soundLength = 5.5f; public Rattle(GTFTSTG game, float leftX, float botY) { super(game,"rattle",leftX,botY,soundLength); } } <file_sep>/GTFTSTG/src/com/aquasheep/GTFTSTG/Screens/AbstractScreen.java package com.aquasheep.GTFTSTG.Screens; import com.aquasheep.GTFTSTG.GTFTSTG; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.FPSLogger; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.scenes.scene2d.Stage; public abstract class AbstractScreen implements Screen { protected GTFTSTG game; protected FPSLogger FPSLog; protected TextureAtlas atlas; protected final Stage stage; protected final SpriteBatch batch; public AbstractScreen(GTFTSTG game) { this.game = game; stage = new Stage(0,0,true); batch = new SpriteBatch(); FPSLog = new FPSLogger(); } /** Returns the class name of the calling screen */ public String getName() { return this.getClass().getSimpleName(); } public TextureAtlas getAtlas(String name) { if (atlas==null) { atlas = new TextureAtlas(Gdx.files.internal("image-atlases/"+name+".pack")); } return atlas; } //Screen implementation @Override public void show() { Gdx.app.log(GTFTSTG.LOG,"Showing screen "+getName()); } @Override public void render(float delta) { FPSLog.log(); Gdx.gl.glClearColor(0f, 0f, 0f, 1f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); //Update stage and actors stage.act(delta); stage.draw(); } @Override public void resize(int width, int height) { Gdx.app.log(GTFTSTG.LOG,"Resizing screen "+getName()+" to "+width+","+height); //Resize the stage stage.setViewport(width, height, true); game.setSize(width,height); } @Override public void hide() { Gdx.app.log(GTFTSTG.LOG,"Hiding screen "+getName()); } @Override public void pause() { Gdx.app.log(GTFTSTG.LOG,"Pausing screen "+getName()); } @Override public void resume() { Gdx.app.log(GTFTSTG.LOG,"Resuming screen "+getName()); } @Override public void dispose() { Gdx.app.log(GTFTSTG.LOG,"Disposing screen "+getName()); batch.dispose(); stage.dispose(); } } <file_sep>/GTFTSTG/src/com/aquasheep/GTFTSTG/Screens/GameScreen.java package com.aquasheep.GTFTSTG.Screens; import com.aquasheep.GTFTSTG.GTFTSTG; import com.aquasheep.GTFTSTG.Controller.Controller; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.Texture; public class GameScreen extends AbstractScreen { private Texture background; private Sound sirens; private Sound helicopter; private Sound carAlarm; private double randomEventCounter; public GameScreen(GTFTSTG game) { super(game); //Add all items to stage for (int i = 0; i < game.items.length; ++i) { stage.addActor(game.items[i]); } //Create controller and set as input processor Gdx.input.setInputProcessor(new Controller(game)); background = new Texture("images/BabyRoom.png"); game.backgroundSound = Gdx.audio.newSound(Gdx.files.internal("sounds/background.ogg")); game.backgroundSound.loop(0.5f); sirens = Gdx.audio.newSound(Gdx.files.internal("sounds/police.ogg")); helicopter = Gdx.audio.newSound(Gdx.files.internal("sounds/helicopter.ogg")); carAlarm = Gdx.audio.newSound(Gdx.files.internal("sounds/carAlarm.ogg")); } @Override public void render(float delta) { randomEventCounter = Math.random()*100000; if (randomEventCounter>99990) { sirens.play(); } if (randomEventCounter>20 && randomEventCounter<30) { helicopter.play(); } if (randomEventCounter<10) { carAlarm.play(); } //Draw background batch.begin(); //Compensate for bottom of background being transparent batch.draw(background,0,-(1024-768)); batch.end(); //Draw everything else stage.act(delta); stage.draw(); game.getBaby().update(delta); } @Override public void resize(int width, int height) { super.resize(width, height); //TODO reposition items based on size changes game.setSize(width,height); } } <file_sep>/GTFTSTG/src/com/aquasheep/GTFTSTG/View/DebugRenderer.java package com.aquasheep.GTFTSTG.View; import com.aquasheep.GTFTSTG.GTFTSTG; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; /** Renders items onto screen */ public class DebugRenderer { private GTFTSTG game; private SpriteBatch batch; private ShapeRenderer debugRenderer; public DebugRenderer(GTFTSTG game, SpriteBatch batch) { this.game = game; this.batch = batch; this.debugRenderer = new ShapeRenderer(); } public void render(float delta) { batch.begin(); for (int i = 0; i < game.items.length; ++i) { game.items[i].draw(batch, 1f); } batch.end(); } public void debugRender(float delta) { debugRenderer.begin(ShapeRenderer.ShapeType.Rectangle); for (int i = 0; i < game.items.length; ++i) { debugRenderer.rect(game.items[0].getPos().x, game.items[0].getPos().y, game.items[0].getPos().width, game.items[0].getPos().height); } debugRenderer.end(); } }<file_sep>/GTFTSTG/src/com/aquasheep/GTFTSTG/GTFTSTGApplet.java package com.aquasheep.GTFTSTG; import com.badlogic.gdx.backends.lwjgl.LwjglApplet; public class GTFTSTGApplet extends LwjglApplet { private static final long serialVersionUID = 1L; public GTFTSTGApplet() { super(new GTFTSTG(), false); } } <file_sep>/GTFTSTG/src/com/aquasheep/GTFTSTG/Items/Phone.java package com.aquasheep.GTFTSTG.Items; import com.aquasheep.GTFTSTG.GTFTSTG; public class Phone extends Item { private static float soundLength = 11.5f; public Phone(GTFTSTG game, float leftX, float botY) { super(game,"phone",leftX,botY,soundLength); } }
2e584ef6dcb6591aeac5f965f387ac67ca71e191
[ "Java" ]
6
Java
aquasheep/GTFTSTG
540446704a5875686756c24be3e93ca4018da610
2eea53748e60b6e6bd3a8853c39c23a0d0f5bec7
refs/heads/master
<repo_name>kkmanwilliam/quantmod<file_sep>/R/getOptionChain.R `getOptionChain` <- function(Symbols, Exp=NULL, src="yahoo", ...) { Call <- paste("getOptionChain",src,sep=".") if(missing(Exp)) { do.call(Call, list(Symbols=Symbols, ...)) } else { do.call(Call, list(Symbols=Symbols, Exp=Exp, ...)) } } getOptionChain.yahoo <- function(Symbols, Exp, ...) { parse.expiry <- function(x) { if(is.null(x)) return(NULL) if(inherits(x, "Date") || inherits(x, "POSIXt")) return(format(x, "%Y-%m")) if (nchar(x) == 5L) { x <- sprintf(substring(x, 4, 5), match(substring(x, 1, 3), month.abb), fmt = "20%s-%02i") } else if (nchar(x) == 6L) { x <- paste(substring(x, 1, 4), substring(x, 5, 6), sep = "-") } return(x) } parseOptionTable_ <- function(x) { opt <- x os <- lapply(as.list(lapply(strsplit(opt,"<tr>"), function(.) gsub(",","",gsub("N/A","NA",gsub("(^ )|( $)","",gsub("[ ]+"," ",gsub("<.*?>"," ", .))))))[[1]]), function(.) strsplit(.," ")[[1]]) which.opts <- sapply(os,function(.) length(.)==8) up <- grep("Up", strsplit(opt, "<tr>")[[1]][which.opts]) dn <- grep("Down", strsplit(opt, "<tr>")[[1]][which.opts]) allcontracts <- do.call(rbind,os[sapply(os,function(.) length(.) == 8)]) rownames. <- allcontracts[,2] allcontracts <- allcontracts[,-2] suppressWarnings(storage.mode(allcontracts) <- "double") allcontracts[dn,3] <- allcontracts[dn,3]*-1 allcontracts <- data.frame(allcontracts) rownames(allcontracts) <- rownames. colnames(allcontracts) <- c("Strike", "Last", "Chg", "Bid", "Ask", "Vol", "OI") call.rows <- which(substr(sprintf("%21s", rownames.),13,13) == "C") list(allcontracts[call.rows,], allcontracts[-call.rows,]) } if(missing(Exp)) opt <- readLines(paste(paste("http://finance.yahoo.com/q/op?s",Symbols,sep="="),"Options",sep="+"), warn=FALSE) else opt <- readLines(paste(paste("http://finance.yahoo.com/q/op?s=",Symbols,"&m=",parse.expiry(Exp),sep=""),"Options",sep="+"), warn=FALSE) opt <- opt[grep("Expire at",opt)] opt <- gsub("%5E","",opt) if(!missing(Exp) && is.null(Exp)) { ViewByExp <- grep("View By Expiration",strsplit(opt, "<tr.*?>")[[1]]) allExp <- substr(strsplit(strsplit(opt,"<tr.*?>")[[1]][ViewByExp],"m=")[[1]][-1],0,7) # fix for missing current month in links # allExp <- c(format(as.yearmon(allExp[1]) - 1/12, "%Y-%m"), allExp) return(structure(lapply(allExp, getOptionChain.yahoo, Symbols=Symbols), .Names=format(as.yearmon(allExp)))) } calls_puts <- parseOptionTable_(opt) list(calls=calls_puts[[1]],puts=calls_puts[[2]],symbol=Symbols) }
7175df3df6e193556588542527c1696585bca7ae
[ "R" ]
1
R
kkmanwilliam/quantmod
ac2f49a59e9169ecbba186e70f4f36cdd0150ed9
8face577c43b972ccdc10084becdeebd89a61e32
refs/heads/master
<repo_name>boruiwang/PinTool<file_sep>/simulator.py #!/usr/bin/python from optparse import OptionParser import sys, os class PIM(object): """docstring for ClassName""" def __init__(self, input): self.filename = input self.LogList = [] # LogList stores PIM output def ParsePIMLog(self): with open(self.filename, 'r') as file: start = file.readline() while start != '==========Total instruction=========\n': start = file.readline() for i in range(6): self.LogList.append(file.readline().split('=')[1].strip(' ')) def CalLatency(self): #Latencylist = [fix_comp, fix_mem, prog_comp, prog_mem, comp, mem ] fix_mem = '0' prog_mem = '0' LatencyList = [sys.argv[3], fix_mem, sys.argv[4], prog_mem, sys.argv[5], sys.argv[6]] exe_time = 0 # comp + mem for i in range(6): latency = float(LatencyList[i]) instrCount = float(self.LogList[i]) exe_time += latency * instrCount # offloading for i in range(7, 11): exe_time += float(sys.argv[i]) # sync exe_time += float(sys.argv[11]) return exe_time def usage(): usage = "usage: %prog -f logfile fixPIM_comp progPIM_comp comp mem\ fixPIM_offloading fixPIM_return progPIM_offloading progPIM_return sync" parser = OptionParser(usage=usage) parser.add_option("-f", "--file", type=="string", dest="PIMLog", help="parse PIM log file", metavar="FILE") (options, args) = parser.parse_args() # check log file if options.PIMLog == None: print "Please specify PIM Log\n" parser.print_help() sys.exit(4) # check input if len(sys.argv) != 12: print "Error: input parameters is wrong, Please check your input!" sys.exit(4) # check log file and then return the simulator if os.path.isfile(options.PIMLog): Simulator = PIM(options.PIMLog) return Simulator else: print 'Error: Unable to find PIM log file specified. Expected location: ', options.PIMLog sys.exit(4) def main(): Simulator = usage() Simulator.ParsePIMLog() exe_time = Simulator.CalLatency() print exe_time if __name__ == "__main__": main()
9cf239f81d751cfdaaf0b7890c404f34e6de620c
[ "Python" ]
1
Python
boruiwang/PinTool
4048ef6b63994bcd844127fb387d44a5956f545d
14dfef6f65c72c248177ea2947e7e520a4724a2a
refs/heads/master
<file_sep>class Post < ApplicationRecord belongs_to :user has_many :likes has_attached_file :img validates_attachment_content_type :img, content_type: /\Aimage\/.*\z/ end <file_sep>LIKES = YAML.load(ERB.new(File.read(Rails.root.join('config', 'paperclip_options.yml'))).result)[Rails.env] Paperclip::Attachment.default_options[:use_timestamp] = false<file_sep>Rails.application.routes.draw do devise_for :users # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html resources :posts root "home#index" post "/likes/:id/save_like", to: "likes#save_like" end <file_sep>class PostsController < ApplicationController def index @post = Post.all.order("created_at DESC") end def new @post = Post.new end def create @post = current_user.posts.build(posts_params) if @post.save p "=============" redirect_to posts_path else p "---------------------------" render 'new' end end def show @post = Post.find(params[:id]) end private def posts_params params.require(:post).permit(:title,:text,:img) end end <file_sep>class Addpostimage < ActiveRecord::Migration[5.1] def change add_attachment :posts, :img end end
4bcdd5248954abf12b3d536ad1d1fc74eab3ac16
[ "Ruby" ]
5
Ruby
joshishalini/likes
1adefdcc09ab488d8c5d66ae7c6157fcab197f67
a50c0a8c9f4247393d427ef07edeb635c94feea4
refs/heads/master
<file_sep>/************************************************************************** This is an example for our Monochrome OLEDs based on SSD1306 drivers Pick one up today in the adafruit shop! ------> http://www.adafruit.com/category/63_98 This example is for a 128x64 pixel display using SPI to communicate 4 or 5 pins are required to interface. Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by <NAME>/Ladyada for Adafruit Industries, with contributions from the open source community. BSD license, check license.txt for more information All text above, and the splash screen below must be included in any redistribution. **************************************************************************/ #include <SPI.h> #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #include <stdio.h> #include <float.h> #define SCREEN_WIDTH 128 // OLED display width, in pixels #define SCREEN_HEIGHT 64 // OLED display height, in pixels // Declaration for SSD1306 display connected using software SPI (default case): /*#define OLED_MOSI 11 #define OLED_CLK 13 #define OLED_DC 9 #define OLED_CS 10 #define OLED_RESET 8 Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT,OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);*/ /* Comment out above, uncomment this block to use hardware SPI*/ #define OLED_DC 9 #define OLED_CS 10 #define OLED_RESET 8 Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &SPI, OLED_DC, OLED_RESET, OLED_CS); int sensPin = 3; int sensPinLlanta = 2; int sensPinValue; int sensPinValueLlanta; int prevSensPinValue; int prevSensPinValueLlanta; int sensLedPin; int sensLedPinLlanta; unsigned long totalRevs; unsigned long totalRevsLlanta; unsigned long prevRevStartedAt; unsigned long thisRevStartedAt; unsigned long prevRevTook; unsigned long prevRevStartedAtLlanta; unsigned long thisRevStartedAtLlanta; unsigned long prevRevTookLlanta; int static RPM; char sRPM[4]; int RPMLlanta; int Velocidad; char sVelocidad[4]; float Odo =9.9; char sOdo[7]; int iCadence = 0; int iSpeed =0; int iOdo = 0; int iHeart = 0; char sCadence[4]; void setup() { Serial.begin(9600); pinMode(sensPin, INPUT); pinMode(sensPinLlanta, INPUT); // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally if(!display.begin(SSD1306_SWITCHCAPVCC)) { Serial.println(F("SSD1306 allocation failed")); for(;;); // Don't proceed, loop forever } // Clear the buffer display.clearDisplay(); // Show the display buffer on the screen. You MUST call display() after // drawing commands to make them visible on screen! display.display(); // Invert and restore display, pausing in-between display.invertDisplay(true); delay(1000); display.invertDisplay(false); delay(1000); testdrawchar(); } void testdrawchar(void) { display.clearDisplay(); display.setTextSize(2); // Normal 1:1 pixel scale display.setTextColor(SSD1306_WHITE); // Draw white text display.setCursor(0, 0); // Start at top-left corner display.cp437(true); // Use full 256 char 'Code Page 437' font // Not all the characters will fit on the display. This is normal. // Library will draw what it can and the rest will be clipped. /*for(int16_t i=0; i<256; i++) { if(i == '\n') display.write(' '); else display.write(i); }*/ //display.write("C: "); sprintf(sCadence, "%d", iCadence); sprintf(sRPM, "%d", RPM); display.write(sRPM); display.setTextSize(1); display.write(" RPM"); display.setTextSize(2); display.setCursor(60, 0); display.write(3); display.setTextSize(2); display.write(sCadence); display.setTextSize(1); display.write("bpm"); display.setCursor(0, 20); //display.write("V: "); display.setTextSize(2); sprintf(sVelocidad, "%d", Velocidad); display.write(sVelocidad); display.setTextSize(1); display.write(" km/H"); display.setTextSize(2); display.setCursor(0, 40); //display.write("O: "); sprintf(sOdo, "%0.2f", Odo); display.write(sOdo); display.setTextSize(1); display.write(" km"); display.display(); delay(20); iCadence++; if (iCadence == 1000) {iCadence = 0;} } void getRPM() { sensPinValue = digitalRead(sensPin); digitalWrite(sensLedPin, sensPinValue ); if (sensPinValue != prevSensPinValue) { // just broke or cleared beam, don't know which yet if (sensPinValue == LOW) { // just broke ie new rev just started totalRevs = totalRevs + 1; prevRevStartedAt = thisRevStartedAt; thisRevStartedAt = millis(); if (totalRevs > 0) { //so this rev took: prevRevTook = thisRevStartedAt - prevRevStartedAt; RPM = 60000. / prevRevTook; //Serial.print("Act RPM= "); //Serial.println(RPM); updateLlanta(); } } prevSensPinValue = sensPinValue; } } void getLlanta() { sensPinValueLlanta = digitalRead(sensPinLlanta); digitalWrite(sensLedPinLlanta, sensPinValueLlanta); if (sensPinValueLlanta != prevSensPinValueLlanta) { // just broke or cleared beam, don't know which yet if (sensPinValueLlanta == 0) { Serial.print("entró a cambio\n"); // just broke ie new rev just started totalRevsLlanta = totalRevsLlanta + 1; prevRevStartedAtLlanta = thisRevStartedAtLlanta; thisRevStartedAtLlanta = millis(); if (totalRevsLlanta > 0) { //so this rev took: prevRevTookLlanta = thisRevStartedAtLlanta - prevRevStartedAtLlanta; RPMLlanta = 60000. / prevRevTookLlanta; Velocidad = (7848 / prevRevTookLlanta); Serial.print("Act RPM= "); Serial.println(Velocidad); Odo=totalRevsLlanta * 0.00218; Serial.print("Odo= "); Serial.print(Odo); updateLlanta(); } } prevSensPinValueLlanta = sensPinValueLlanta; } } void updateLlanta(void){ display.clearDisplay(); display.setTextSize(2); // Normal 1:1 pixel scale display.setCursor(0, 0); sprintf(sCadence, "%d", iCadence); sprintf(sRPM, "%d", RPM); display.write(sRPM); Serial.println(RPM); display.setTextSize(1); display.write(" RPM"); display.setTextSize(2); display.setCursor(60, 0); display.write(3); display.setTextSize(2); display.write(sCadence); display.setTextSize(1); display.write("bpm"); display.setCursor(0, 20); //display.write("V: "); display.setTextSize(2); sprintf(sVelocidad, "%d", Velocidad); display.write(sVelocidad); display.setTextSize(1); display.write(" km/H"); display.setTextSize(2); display.setCursor(0, 40); //display.write("O: "); dtostrf(Odo, 4,2,sOdo); // string ssOdo= String(Odo); Serial.print(sOdo); display.write(sOdo); display.setTextSize(1); display.write(" km"); display.display(); iCadence++; if (iCadence == 1000) {iCadence = 0;} } void loop() { getRPM(); getLlanta(); //testdrawchar(); }
1b603e948ae19ed24e26a6976ed3a52256b1be6d
[ "C++" ]
1
C++
bico83/Bikomp
ed6a8952631223c6788f47d5622b42ab454d4b76
6490c9a4445f2f2e8ad84daf41c8a832ee849394
refs/heads/master
<repo_name>sindre97/GANs-pytorch<file_sep>/GANs-pytorch/GAN/train.py import torch import torch.nn as nn import torchvision.datasets as datasets import torchvision.transforms as transforms from torch.autograd import Variable import torch.backends.cudnn as cudnn # 工具包 import argparse # 载入网络 from network import G, D #############参数设置############# ####命令行设置######## parser = argparse.ArgumentParser (description='GAN') # 导入命令行模块 # 对关于函数add_argumen()第一个是选项,第二个是数据类型,第三个默认值,第四个是help命令时的说明 #关于训练参数 parser.add_argument ('--batch_size', type=int, default=12, help='训练batch-size大小 (default: 64)') parser.add_argument ('--imageSize', type=int, default=5, help='图片尺寸') parser.add_argument ('--max_epoch', type=int, default=5, help='最大迭代数 (default: 5)') #关于网络参数 parser.add_argument ('--lr_g', type=float, default=2e-4, help='生成器学习率 (default: 2e-4)') parser.add_argument ('--lr_d', type=float, default=2e-4, help='判别器学习率 (default: 2e-4)') parser.add_argument ('--ngf', type=int, default=32, help='生成器feature map数') parser.add_argument ('--ndf', type=int, default=32, help='判别器feature map数') parser.add_argument ('--d_every', type=int, default=1, help='每几个batch训练一次判别器') parser.add_argument ('--g_every', type=int, default=2, help='每几个batch训练一次生成器') parser.add_argument ('--nz', type=int, default=5, help='噪声维度') #关于优化器参数 parser.add_argument ('--beta1', type=int, default=0.5, help='Adam优化器的beta1参数') #路径 parser.add_argument ('--dataset', default='data/', help='数据集路径') parser.add_argument ('--save_data', default='save/', help='保存路径') #可视化 parser.add_argument ('--vis', action='store_true', help='使用visdom可视化') parser.add_argument ('--plot_every', type=int, default=1, help='每间隔_batch,visdom画图一次') # 其他 parser.add_argument ('--cuda', action='store_true', help='开启cuda训练') parser.add_argument ('--plt', action='store_true', help='开启画图') parser.add_argument ('--test', action='store_true', help='开启测试生成') parser.add_argument ('--save_every', type=int, default=3, help='几个epoch保存一次模型 (default: 3)') parser.add_argument ('--seed', type=int, default=1, help='随机种子 (default: 1)') args = parser.parse_args () # 相当于激活命令 #训练过程 def train(): ###############判断gpu############# device = torch.device ('cuda') if args.cuda else torch.device ('cpu') ####### 为CPU设置种子用于生成随机数,以使得结果是确定的########## torch.manual_seed (args.seed) if args.cuda: torch.cuda.manual_seed (args.seed) cudnn.benchmark = True #################可视化############### if args.vis: vis = Visualizer ('GANs') ##########数据转换##################### data_transforms = transforms.Compose ([transforms.Scale (args.imageSize), # 通过调整比例调整大小,会报警 transforms.CenterCrop (args.imageSize), # 在中心裁剪给指定大小方形PIL图像 transforms.ToTensor (),# 转换成pytorch 变量tensor transforms.Normalize ((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) ###############数据载入################ train_dataset = datasets.ImageFolder (root=args.dataset, # 数据路径目录 transform=data_transforms) # 把数据转换成上面约束样子 # test_dataset = datasets.ImageFolder (root=args.dataset, # transform=data_transforms) ##############数据装载############### train_loader = torch.utils.data.DataLoader (dataset=train_dataset, # 装载数据 batch_size=args.batch_size, # 设置批大小 shuffle=True) # 是否随机打乱 # test_loader = torch.utils.data.DataLoader (dataset=test_dataset, # batch_size=args.batch_size, # shuffle=True) #############模型载入################# netG ,netD= G (args),D (args) netG.to (device) netD.to (device) print (netD, netG) ###############损失函数################## optimizerD = torch.optim.Adam (netD.parameters (), lr=args.lr_d,betas=(0.5, 0.999)) # Adam优化器 optimizerG = torch.optim.Adam (netG.parameters (), lr=args.lr_g,betas=(0.5, 0.999)) # Adam优化器 ###############画图参数保存################## G_losses = [] D_losses = [] img_list = [] #############训练过程##################### import tqdm # Tqdm是一个快速,可扩展的Python进度条,可以在Python # 长循环中添加一个进度提示信息,用户只需要封装任意的迭代器 # tqdm (iterator)。 for epoch in range (args.max_epoch): for i, (images, labels) in tqdm.tqdm(enumerate (train_loader)): # 枚举出来 #数据处理 images = images.to (device) # 装箱 images = Variable (images) noises=Variable(torch.randn(args.batch_size, args.nz, 1, 1).to(device)) #遍历每张图片,并且根据指定的训练机制训练 if i % args.d_every==0:#满足此条件训练D #D前向传播 optimizerD.zero_grad () #D网络输出 output_r = netD (images) #G网络输出 noises.data.copy_ (torch.randn (args.batch_size, args.nz, 1, 1)) fake = netG (noises).detach () # 根据噪声生成假图 #把假图给d output_f = netD (fake) #D的损失 #print(fake.size(),output_f.size(),output_r.size()) D_loss = - torch.mean (torch.log (output_r) + torch.log (1. - output_f)) #D反向传播 D_loss.backward () #度量 D_x = output_r.mean ().item () D_G_z1 = output_f.mean ().item () #D更新参数 optimizerD.step () if i % args.g_every==0:#满足此条件训练G #G前向传播 optimizerG.zero_grad () #G网络输出 fake = netG (noises) # 根据噪声生成假图 #把假图给G output_f = netD (fake) #G的损失 G_loss = torch.mean (torch.log (1. - output_f)) #G反向传播 G_loss.backward () #度量 D_G_z2 = output_f.mean ().item () #D更新参数 optimizerG.step () ########################################### ##########可视化(可选)##################### if args.vis and i % args.plot_every == args.plot_every - 1: fake = netG (noises) vis.images (fake.detach ().cpu ().numpy () [:64] * 0.5 + 0.5, win='fixfake') vis.images (images.data.cpu ().numpy () [:64] * 0.5 + 0.5, win='real') vis.plot ('errord', D_loss.item ()) vis.plot ('errorg', G_loss.item ()) ####################################### ############打印记录################### if i % 1== 0: print ('[%d/%d][%d/%d]\tLoss_D: %.4f\tLoss_G: %.4f\tD(x): %.4f\tD(G(z)): %.4f / %.4f' % (epoch, args.max_epoch, i, len (train_loader), D_loss.item (), G_loss.item (), D_x, D_G_z1, D_G_z2)) ########添加画图参数######## G_losses.append (G_loss.item ()) D_losses.append (D_loss.item ()) with torch.no_grad (): noises = torch.randn (args.batch_size, args.nz, 1, 1).to (device) fake = netG (noises).detach ().cpu () import torchvision.utils as vutils img_list.append (vutils.make_grid (fake, padding=2, normalize=True)) ####################################### ############保存模型################### if (epoch + 1) % args.save_every == 0: import torchvision as tv # 保存模型、图片 tv.utils.save_image (fake.data [:64], '%s/%s.png' % (args.save_data, epoch), normalize=True,range=(-1, 1)) torch.save (netD.state_dict (), 'checkpoints/netd_%s.pth' % epoch) torch.save (netG.state_dict (), 'checkpoints/netg_%s.pth' % epoch) print('完成%s的模型保存'%epoch) ####################################### ############画图################### if args.plt: import matplotlib.pyplot as plt import numpy as np import torchvision.utils as vutils plt.figure (figsize=(10, 5)) plt.title ("GAN") plt.plot (G_losses, label="G") plt.plot (D_losses, label="D") plt.xlabel ("迭代次数",fontproperties='SimHei') plt.ylabel ("损失",fontproperties='SimHei') plt.legend () plt.show () # 从数据集加载 real_batch = next (iter (train_dataset)) # 画出真图 plt.figure (figsize=(15, 10)) plt.subplot (1, 2, 1) plt.axis ("off") plt.title ("真图",fontproperties='SimHei') plt.imshow (np.transpose ( vutils.make_grid (real_batch [0].to (device) [:64], padding=5, normalize=True).cpu (), (1, 2, 0))) # 画出假图 plt.subplot (1, 2, 2) plt.axis ("off") plt.title ("假图",fontproperties='SimHei') plt.imshow (np.transpose (img_list [-1], (1, 2, 0))) plt.show () @torch.no_grad()#禁用梯度计算 def test(): #判断Gpu device = torch.device ('cuda') if args.cuda else torch.device ('cpu') #初始化网络 netg, netd = netG (args).eval (), netD (args).eval () #定义噪声 noises = torch.randn (args.batch_size, args.nz, 1, 1).to (device) #载入网络 netd.load_state_dict (torch.load ('checkpoints/netd_%s.pth'%args.max_epoch)) netg.load_state_dict (torch.load ('checkpoints/netg_%s.pth'%args.max_epoch)) #设备化 netd.to (device) netg.to (device) # 生成图片,并计算图片在判别器的分数 fake_img = netg (noises) scores = netd (fake_img).detach () # 挑选最好的某几张 indexs = scores.topk (5) [1] result = [] for i in indexs: result.append (fake_img.data [i]) # 保存图片 import torchvision as tv tv.utils.save_image (torch.stack (result), 5, normalize=True, range=(-1, 1)) ###################可视化类################################## import visdom import time import torchvision as tv import numpy as np class Visualizer (): """ 封装了visdom的基本操作,但是你仍然可以通过`self.vis.function` 调用原生的visdom接口 """ def __init__ (self, env='default', **kwargs): import visdom self.vis = visdom.Visdom (env=env, use_incoming_socket=False, **kwargs) # 画的第几个数,相当于横座标 # 保存(’loss',23) 即loss的第23个点 self.index = {} self.log_text = '' def reinit (self, env='default', **kwargs): """ 修改visdom的配置 """ self.vis = visdom.Visdom (env=env, use_incoming_socket=False, **kwargs) return self def plot_many (self, d): """ 一次plot多个 @params d: dict (name,value) i.e. ('loss',0.11) """ for k, v in d.items (): self.plot (k, v) def img_many (self, d): for k, v in d.items (): self.img (k, v) def plot (self, name, y): """ self.plot('loss',1.00) """ x = self.index.get (name, 0) self.vis.line (Y=np.array ([y]), X=np.array ([x]), win=(name), opts=dict (title=name), update=None if x == 0 else 'append' ) self.index [name] = x + 1 def img (self, name, img_): """ self.img('input_img',t.Tensor(64,64)) """ if len (img_.size ()) < 3: img_ = img_.cpu ().unsqueeze (0) self.vis.image (img_.cpu (), win=(name), opts=dict (title=name) ) def img_grid_many (self, d): for k, v in d.items (): self.img_grid (k, v) def img_grid (self, name, input_3d): """ 一个batch的图片转成一个网格图,i.e. input(36,64,64) 会变成 6*6 的网格图,每个格子大小64*64 """ self.img (name, tv.utils.make_grid ( input_3d.cpu () [0].unsqueeze (1).clamp (max=1, min=0))) def log (self, info, win='log_text'): """ self.log({'loss':1,'lr':0.0001}) """ self.log_text += ('[{time}] {info} <br>'.format ( time=time.strftime ('%m%d_%H%M%S'), info=info)) self.vis.text (self.log_text, win=win) def __getattr__ (self, name): return getattr (self.vis, name) if __name__ == '__main__': if args.test: test() else: train()<file_sep>/GANs-pytorch/AlexNet/AlexNet.py import torch #跟着第一幅图走 class AlexNet(torch.nn.Module): def __init__(self): super(AlexNet, self).__init__() # 输入图片大小 227*227*3 #第一层 self.conv1 = torch.nn.Sequential( #卷积 torch.nn.Conv2d(in_channels=3, out_channels=96, kernel_size=11, stride=4, padding=0), # (227-11)/4+1=55, 输出图片大小:55*55*96 torch.nn.ReLU(),#激活层 torch.nn.MaxPool2d(kernel_size=3, stride=2, padding=0) # (55-3)/2+1=27, 输出图片大小: 27*27*96 ) # 从上面获得图片大小27*27*96 self.conv2 = torch.nn.Sequential( torch.nn.Conv2d(in_channels=96, out_channels=256, kernel_size=5, stride=1, padding=2), # (27-5 + 2*2)/ 1 + 1 = 27, 输出图片大小:27*27*256 torch.nn.ReLU(), torch.nn.MaxPool2d(kernel_size=3, stride=2, padding=0) # (27 - 3 )/2 + 1 = 13, 输出图片大小:13*13*256 ) # 从上面获得图片大小13*13*256 self.conv3 = torch.nn.Sequential( torch.nn.Conv2d(in_channels=256, out_channels=384, kernel_size=3, stride=1, padding=1), # (13 - 3 +1*2)/1 + 1 = 13 , 输出图片大小:13*13*384 torch.nn.ReLU() ) # 从上面获得图片大小13*13*384 self.conv4 = torch.nn.Sequential( torch.nn.Conv2d(in_channels=384, out_channels=384, kernel_size=3, stride=1, padding=1), # (13 - 3 + 1*2)/1 +1 = 13, 输出图片大小:13*13*384 torch.nn.ReLU() ) # 从上面获得图片大小13*13*384 self.conv5 = torch.nn.Sequential( torch.nn.Conv2d(in_channels=384, out_channels=256, kernel_size=3, stride=1, padding=1), # (13 - 3 + 1*2) +1 = 13, 13*13*256 torch.nn.ReLU(), torch.nn.MaxPool2d(kernel_size=3, stride=2, padding=0) # (13 - 3 )/2 +1 =6, 6*6*256 ) # 从上面获得图片大小 6*6*256 = 9216 共9216输出特征 self.lostlayer = torch.nn.Sequential( #第六层 torch.nn.Linear(9216, 4096),#全连接 torch.nn.ReLU(),#激活层 torch.nn.Dropout(0.5),#以0.5&几率随机忽略一部分神经元 #第七层 torch.nn.Linear(4096, 4096), torch.nn.ReLU(), torch.nn.Dropout(0.5), #第八层 torch.nn.Linear(4096, 2) # 最后输出2 ,因为只分猫狗两类 ) #前向传播 def forward(self, x): conv1_out = self.conv1(x) conv2_out = self.conv2(conv1_out) conv3_out = self.conv3(conv2_out) conv4_out = self.conv4(conv3_out) conv5_out = self.conv5(conv4_out) res = conv5_out.view(conv5_out.size(0), -1)#展平多维的卷积图成 一维(batch_size, 4096) out = self.lostlayer(res) return out <file_sep>/GANs-pytorch/VAEGAN/network.py ''' 跟着图走 ''' import torch.nn as nn #我们首先建立G (由一个编码器,一个解码器构成) class G(nn.Module): def __init__(self,args): super(G,self).__init__() ngf = args.ngf #ngf 设置为128 卷积一般扩大两倍 参数为4,2,1 self.encoder= nn.Sequential( # 输入一个真实图像3*64*64 nn.Conv2d (3, ngf, 4, 2, 1, bias=False), nn.BatchNorm2d (ngf), nn.LeakyReLU (True), # (ngf) x 32x 32 nn.Conv2d (ngf, ngf * 2, 4, 2, 1, bias=False), nn.BatchNorm2d (ngf * 2), nn.LeakyReLU (True), # (ngf*2) x 16 x 16 nn.Conv2d (ngf * 2, ngf, 4, 2, 1, bias=False), nn.BatchNorm2d (ngf), nn.LeakyReLU (True)) #还原尺寸 self.decoder = nn.Sequential ( nn.ConvTranspose2d(ngf,ngf*2,4,2,1), nn.BatchNorm2d(ngf*2), nn.ReLU(), nn.ConvTranspose2d (ngf*2,ngf,4,2,1), nn.BatchNorm2d (ngf), nn.ReLU (), nn.ConvTranspose2d (ngf, 3, 4, 2, 1), nn.Tanh ()) #3*64*64 #前向传播 def forward(self,x): out=self.encoder(x) out_x=self.decoder(out) #print(out_x.size()) return out_x #建立D class D(nn.Module): def __init__(self,args): super(D,self).__init__() ndf = args.ndf # ndf 128 self.D_layer= nn.Sequential( # 输入 1 x 64 x 64, nn.Conv2d (3, ndf, 4, 2, 1, bias=False), nn.BatchNorm2d (ndf), nn.LeakyReLU (True), #输出 (ndf)*32*32 nn.Conv2d(ndf,ndf*2,4,2,1, bias=False), nn.BatchNorm2d (ndf*2), nn.LeakyReLU (True), # 输出 (ndf*2)*16*16 nn.Conv2d (ndf*2, ndf*4, 4, 2, 1, bias=False), nn.BatchNorm2d (ndf*4), nn.LeakyReLU (True), # 输出 (ndf*4)*8*8 nn.Conv2d (ndf*4, ndf*8, 4, 2, 1, bias=False), nn.BatchNorm2d (ndf*8), nn.LeakyReLU (True), # 输出 (ndf*8)*4*4 nn.Conv2d (ndf * 8, 1, 4, 1, 0, bias=False), # 输出 1*1*1 nn.Sigmoid())#告诉D概率 #前向传播 def forward(self,x): out=self.D_layer(x) return out <file_sep>/README.md # GANs-pytorch 简单实现的GAN网络 # 一些从基础到实践的GAN简单的pytorch实现 <file_sep>/GANs-pytorch/VGG/train.py import torch import torch.nn as nn import torchvision.datasets as datasets import torchvision.transforms as transforms from torch.autograd import Variable # 工具包 import argparse # 载入网络 from VGG import VGG #############参数设置############# ####命令行设置######## parser = argparse.ArgumentParser (description='CNN') # 导入命令行模块 # 对于函数add_argumen()第一个是选项,第二个是数据类型,第三个默认值,第四个是help命令时的说明 parser.add_argument ('--batch-size', type=int, default=2, metavar='N', help='训练batch-size大小 (default: 2)') parser.add_argument ('--epochs', type=int, default=10, metavar='N', help='训练epochs大小 (default: 10)') parser.add_argument ('--lr', type=float, default=0.001, metavar='LR', help='学习率 (default: 0.001)') parser.add_argument ('--no-cuda', action='store_true', default=False, help='不开启cuda训练') parser.add_argument ('--seed', type=int, default=1, metavar='S', help='随机种子 (default: 1)') parser.add_argument ('--log-interval', type=int, default=1, metavar='N', help='记录等待n批次 (default: 1)') args = parser.parse_args () # 相当于激活命令 args.cuda = not args.no_cuda and torch.cuda.is_available () # 判断gpu torch.manual_seed (args.seed) if args.cuda: torch.cuda.manual_seed (args.seed) # 为CPU设置种子用于生成随机数,以使得结果是确定的 ##########数据转换##################### data_transforms = transforms.Compose ([transforms.Scale (224), # 通过调整比例调整大小,会报警 transforms.CenterCrop (224), # 在中心裁剪给指定大小方形PIL图像 transforms.ToTensor ()]) # 转换成pytorch 变量tensor ###############数据载入################ train_dataset = datasets.ImageFolder (root="./data/train/", # 保存目录 transform=data_transforms) # 把数据转换成上面约束样子 test_dataset = datasets.ImageFolder (root='./data/test/', transform=data_transforms) ##########数据如下#### # # root/dog/xxx.png # # root/dog/xxy.png # # root/dog/xxz.png # # # # root/cat/123.png # # root/cat/nsdf3.png # # root/cat/asd932_.png ###################### ##############数据装载############### train_loader = torch.utils.data.DataLoader (dataset=train_dataset, # 装载数据 batch_size=args.batch_size, # 设置批大小 shuffle=True) # 是否随机打乱 test_loader = torch.utils.data.DataLoader (dataset=test_dataset, batch_size=args.batch_size, shuffle=True) #############模型载入################# VGG=VGG () if not args.no_cuda: print ('正在使用gpu') VGG.cuda () print (VGG) ###############损失函数################## criterion = nn.CrossEntropyLoss () # 内置标准损失 optimizer = torch.optim.Adam (VGG.parameters (), lr=args.lr) # Adam优化器 #############训练过程##################### total_loss = 0 #内存循环使用 for epoch in range (args.epochs): for i, (images, labels) in enumerate (train_loader): # 枚举出来 if not args.no_cuda: # 数据处理是否用gpu images = images.cuda () labels = labels.cuda () images = Variable (images) # 装箱 labels = Variable (labels) ##前向传播 optimizer.zero_grad () outputs = VGG (images) # 损失 loss = criterion (outputs, labels) # 反向传播 loss.backward () optimizer.step ()#更新参数 total_loss += loss#内存循环使用 防止cuda超出内存 ##打印记录 if (i + 1) % args.log_interval == 0: print ('Epoch [%d/%d], Iter [%d/%d] Loss: %.4f' % (epoch + 1, args.epochs, i + 1, len (train_dataset) // args.batch_size, loss.item ())) # 保存模型 torch.save (VGG.state_dict (), 'VGG.pkl') <file_sep>/GANs-pytorch/CNN/train.py #pytorch import torch import torch.nn as nn import torchvision.datasets as datasets import torchvision.transforms as transforms from torch.autograd import Variable #工具包 import argparse #载入网络 from CNN import CNN #############参数设置############# ####命令行设置######## parser = argparse.ArgumentParser(description='CNN') #导入命令行模块 #对于函数add_argumen()第一个是选项,第二个是数据类型,第三个默认值,第四个是help命令时的说明 parser.add_argument('--batch-size', type=int, default=64, metavar='N', help='训练batch-size大小 (default: 64)') parser.add_argument('--epochs', type=int, default=10, metavar='N', help='训练epochs大小 (default: 10)') parser.add_argument('--lr', type=float, default=0.001, metavar='LR', help='学习率 (default: 0.001)') parser.add_argument('--no-cuda', action='store_true', default=False, help='不开启cuda训练') parser.add_argument('--seed', type=int, default=1, metavar='S', help='随机种子 (default: 1)') parser.add_argument('--log-interval', type=int, default=50, metavar='N', help='记录等待n批次 (default: 50)') parser.add_argument('--network', type=str, default='CNN', metavar='N', help='which model to use, CNN|NIN|ResNet') args = parser.parse_args()#相当于激活命令 args.cuda = not args.no_cuda and torch.cuda.is_available()#判断gpu torch.manual_seed(args.seed) if args.cuda: torch.cuda.manual_seed(args.seed)#为CPU设置种子用于生成随机数,以使得结果是确定的 ###############数据载入################ train_dataset=datasets.MNIST(root="./data/",#保存目录 train=True, #选择训练集 transform=transforms.ToTensor(), #把数据转换成pytorch张量 Tensor download=True) #是否下载数据集 test_dataset=datasets.MNIST(root='./data/', train=False,#关闭 表示选择测试集 transform=transforms.ToTensor(), download=True) ##############数据装载############### train_loader=torch.utils.data.DataLoader(dataset=train_dataset,#装载数据 batch_size=args.batch_size,#设置批大小 shuffle=True)#是否随机打乱 test_loader=torch.utils.data.DataLoader(dataset=test_dataset, batch_size=args.batch_size, shuffle=True) #############模型载入################# cnn=CNN() if not args.no_cuda: print('正在使用gpu') cnn.cuda() print(cnn) ###############损失函数################## criterion=nn.CrossEntropyLoss()#内置标准损失 optimizer=torch.optim.Adam(cnn.parameters(),lr=args.lr)#Adam优化器 #############训练过程##################### for epoch in range (args.epochs): for i, (images,labels) in enumerate(train_loader):#枚举出来 if not args.no_cuda:#数据处理是否用gpu images=images.cuda() labels=labels.cuda() images=Variable(images)#装箱 labels=Variable(labels) ##前向传播 optimizer.zero_grad() outputs=cnn(images) #损失 loss=criterion(outputs,labels) #反向传播 loss.backward() optimizer.step () ##打印记录 if (i+1)% args.log_interval==0: print('Epoch [%d/%d], Iter [%d/%d] Loss: %.4f' %(epoch+1, args.epochs, i+1, len(train_dataset)//args.batch_size, loss.item())) #保存模型 torch.save(cnn.state_dict(), 'cnn.pkl')<file_sep>/GANs-pytorch/Resnet/Resnet.py import torch ''' 今天在vgg基础上再优雅点 ''' #遵从原来步骤 class Resnet(torch.nn.Module): #初始化 def __init__(self): super(Resnet, self).__init__() # self.Sumlayers=self.make_layers()#这里我们交由make_layers函数创建相似的模块 # #假设我们上面已经创好五个模块(文章第一幅图block1->block5) #现在最顶端的不同层,看文章34层那个最上面橘色简化图的7*7 self.top=torch.nn.Sequential( torch.nn.Conv2d(3,64,7,2,3), torch.nn.BatchNorm2d(64), torch.nn.ReLU (inplace=True), torch.nn.MaxPool2d(3,2,1))#最顶部构建完成 #中间重复太多,交给make_layers函数创建相似的模块 #第三个参数来表示有多少个捷径(高速公路) #先来一打紫色的(文中图) self.layer1 = self.make_layer (64,64,3) # 再来一打绿色的(文中图) self.layer2 = self.make_layer (64, 128, 4,stride=2)#图中第一个有/2 # 再来一打橘色的(文中图) self.layer3 = self.make_layer ( 128,256, 6,stride=2)#图中第一个有/2 # 再来一打银色的(文中图) self.layer4= self.make_layer (256, 512, 3, stride=2) # 图中第一个有/2 #中间重复的构造完了 #开始最后的了 self.avgPool =torch.nn.AvgPool2d(7)#全局平均化 self.fc = torch.nn.Linear (512, 2)#最后分成猫狗两类 self.last=torch.nn.Softmax (dim=1) #前向传播 def forward (self, x): x = self.top (x) x = self.layer1 (x) x = self.layer2 (x) x = self.layer3 (x) x = self.layer4 (x) x = self.avgPool(x) res = x.view (x.size (0), -1) # 展平多维的卷积图成 一维 out = self.fc(res) out = self.last(out) return out #构建刚才的构建模块函数make_layers def make_layer(self,in_c,out_c,n_block,stride=1): #创建一个列表,用来放后面层 ,后面我们直接往里面添加就可以了 Sumlayers=[] #构建捷径(高速公路) shortcut=torch.nn.Sequential( torch.nn.Conv2d(in_c,out_c,1,stride),#1*1卷积 torch.nn.BatchNorm2d(out_c), ) #构建完成残差 Sumlayers.append(ResBlock(in_c,out_c,stride,shortcut)) #构建右边的公路 for i in range(1,n_block): Sumlayers.append (ResBlock (out_c, out_c))#注意输入,输出应该一样 return torch.nn.Sequential (*Sumlayers) #然后把构建好模型传出 #构建残差块 因为参数是变动的,所以引入变量,最后一个变量表示快捷通道个数,默认没有 class ResBlock(torch.nn.Module): def __init__(self,in_c,out_c,stride=1,shortcut=None): super(ResBlock, self).__init__() #左边的公路 self.left=torch.nn.Sequential( torch.nn.Conv2d (in_c,out_c,3,stride,1), torch.nn.BatchNorm2d (out_c), torch.nn.ReLU (inplace=True), torch.nn.Conv2d (out_c,out_c,3,1,1),#注意 这里输入输出应该一样 torch.nn.BatchNorm2d (out_c) ) #右边的高速公路 self.right=shortcut #最后 self.last_y=torch.nn.ReLU() #前向 def forward(self, x): y_l=self.left(x) y_r = x if self.right is None else self.right (x) #如果有高数路为空,就直接保存在res中,否则执行高速路保存在res sum_x=y_l+y_r #两个总和 out=self.last_y(sum_x) return out # # from torchvision import models # model = models.resnet34() # # net = Resnet() # print(net) # x = torch.randn(1,3,224,224) # #print(x) # print(net(torch.autograd.Variable(x)).size())<file_sep>/GANs-pytorch/VGG/VGG.py import torch ''' 今天这个有点难得堆 一个个写,重复性太高,而且不利于观看,不优雅 重复性事我们交给你喊函数完成 ''' #遵从原来步骤 class VGG(torch.nn.Module): #初始化 def __init__(self): super(VGG, self).__init__() self.Sumlayers=self.make_layers()#这里我们交由make_layers函数创建相似的模块 #假设我们上面已经创好五个模块(文章第一幅图block1->block5) #现在创建最后的Fc self.fc=torch.nn.Sequential( torch.nn.Linear (7*7*512, 4096), # 第一个全连接 torch.nn.ReLU(), torch.nn.Linear (4096, 4096), # 第二个全连接 torch.nn.ReLU(), torch.nn.Linear (4096, 2), # 第三个全连接 # 原版1000类 最后分成2类 因为只有猫狗两个类 torch.nn.ReLU(), torch.nn.Softmax (dim=1), # 最后一个 softmax 不填dim=1会报警 1.0以前好像可以直接写Softmax () ) #前向传播 def forward (self, x): conv = self.Sumlayers (x) res = conv.view (conv.size (0), -1) # 展平多维的卷积图成 一维 out = self.fc(res) return out #构建刚才的构建模块函数make_layers def make_layers(self): #创建一个列表,用来快速构造模块,你也可以测试vgg19等等 vgg16=[64, 64, 'Maxpool', 128, 128, 'Maxpool', 256, 256, 256, 'Maxpool', 512, 512, 512, 'Maxpool', 512, 512, 512, 'Maxpool'] #创建一个列表,用来放后面层 ,后面我们直接往里面添加就可以了 Sumlayers=[] #创建一个变量,来控制 卷积参数输入大小(in_channels)和输出大小(out_channels) in_c = 3 #第一次输入大小 #遍历列表 for x in vgg16: #获取到每个配置,我这只有vgg16这一行 if x =='Maxpool':#如果遇到Maxpool ,我们就创建maxpool层 Sumlayers+=[torch.nn.MaxPool2d(kernel_size=2, stride=2)]#参数看上文 else: #否则我们创建conv(卷积模块) Sumlayers+= [torch.nn.Conv2d (in_channels=in_c,out_channels=x , kernel_size=3, padding=1), #x是列表中的参数 torch.nn.BatchNorm2d (x),#标准化一下 torch.nn.ReLU ()] in_c=x #输出大小成为下个输入大小 return torch.nn.Sequential (*Sumlayers) #然后把构建好模型传出 # net = VGG() # print(net) # x = torch.randn(2,3,224,224) # print(x) # print(net(torch.autograd.Variable(x)).size())<file_sep>/GANs-pytorch/GAN/network.py ''' 为了简单明了,所以今天还是创最最简单的GAN 首先 有两个网络 分别是G D ''' import torch.nn as nn #我们首先建立G class G(nn.Module): def __init__(self,args): super(G,self).__init__() ngf = args.ngf # 生成器feature map数(该层卷积核的个数,有多少个卷积核,经过卷积就会产生多少个feature map) self.G_layer= nn.Sequential( #输入是一个nz维度的噪声,我们可以认为它是一个1 * 1 * nz的feature map nn.ConvTranspose2d(args.nz, 3,5,1,0),# 反conv2d nn.BatchNorm2d (3), nn.LeakyReLU(True),) # 输出大小为3*5*5 #前向传播 def forward(self,x): out=self.G_layer(x) return out #建立D class D(nn.Module): def __init__(self,args): super(D,self).__init__() ndf = args.ndf # 生成器feature map数(该层卷积核的个数,有多少个卷积核,经过卷积就会产生多少个feature map) self.D_layer= nn.Sequential( # 输入 3 x 5 x 5, nn.Conv2d(3,ndf, 3), nn.BatchNorm2d (ndf), nn.LeakyReLU (True), #输出 (ndf)*1*1 nn.Conv2d (ndf,1,1), # 输出 1*0*0 nn.Sigmoid())#告诉D概率 #前向传播 def forward(self,x): out=self.D_layer(x) return out <file_sep>/GANs-pytorch/DCGAN/network.py ''' 跟着图走 ''' import torch.nn as nn #我们首先建立G class G(nn.Module): def __init__(self,args): super(G,self).__init__() ngf = args.ngf #ndf 设置为128 卷积一般扩大两倍 参数为4,2,1 self.G_layer= nn.Sequential( # 输入的相当于nz*1*1 nn.ConvTranspose2d (args.nz, ngf * 8, 4, 1, 0, bias=False), nn.BatchNorm2d (ngf * 8), nn.ReLU (True), # (ngf*8) x 4 x 4 nn.ConvTranspose2d (ngf * 8, ngf * 4, 4, 2, 1, bias=False), nn.BatchNorm2d (ngf * 4), nn.ReLU (True), # (ngf*4) x 8 x 8 nn.ConvTranspose2d (ngf * 4, ngf * 2, 4, 2, 1, bias=False), nn.BatchNorm2d (ngf * 2), nn.ReLU (True), # (ngf*2) x 16 x 16 nn.ConvTranspose2d (ngf * 2, ngf, 4, 2, 1, bias=False), nn.BatchNorm2d (ngf), nn.ReLU (True), # (ngf) x 32 x 32 nn.ConvTranspose2d (ngf, 3, 4, 2, 1, bias=False), nn.Tanh ()) # 3 x 64 x 64 #前向传播 def forward(self,x): out=self.G_layer(x) return out #建立D class D(nn.Module): def __init__(self,args): super(D,self).__init__() ndf = args.ndf # ndf 128 self.D_layer= nn.Sequential( # 输入 3 x 64 x 64, nn.Conv2d(3,ndf,4,2,1), nn.BatchNorm2d (ndf), nn.LeakyReLU (True), #输出 (ndf)*32*32 nn.Conv2d(ndf,ndf*2,4,2,1), nn.BatchNorm2d (ndf*2), nn.LeakyReLU (True), # 输出 (ndf*2)*16*16 nn.Conv2d (ndf*2, ndf*4, 4, 2, 1), nn.BatchNorm2d (ndf*4), nn.LeakyReLU (True), # 输出 (ndf*4)*8*8 nn.Conv2d (ndf*4, ndf*8, 4, 2, 1), nn.BatchNorm2d (ndf*8), nn.LeakyReLU (True), # 输出 (ndf*8)*4*4 nn.Conv2d (ndf * 8, 1, 4, 1, 0), # 输出 1*0*0 nn.Sigmoid())#告诉D概率 #前向传播 def forward(self,x): out=self.D_layer(x) return out <file_sep>/GANs-pytorch/CNN/CNN.py import torch.nn as nn class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() # 输入MNIST 图片大小是(1,28,28) self.layer=nn.Sequential(nn.Conv2d(1,8,kernel_size=5,padding=2),#第一个参数,输入是1,表示输入图片通道为1 ,8表示输出,5卷积核大小,2补边大小 nn.BatchNorm2d(8),#归一化 nn.ReLU(),#激活层 nn.MaxPool2d(2),#池化层 到这 (8,28,28)图片就被池化成(8,14,14)了 ) self.fc=nn.Linear(14*14*8,10) #全连接层 第一个输入的特征数,第二个 输出的特征 (0-9) 共10特征 #前向传播 def forward(self, x): out=self.layer(x) out=out.view(out.size(0),-1)#展平多维的卷积图成 (batch_size, 32 * 7 * 7) out=self.fc(out) return out
5f88ebad460e0f7e630e3693c9ea4431a7ca9eca
[ "Markdown", "Python" ]
11
Python
sindre97/GANs-pytorch
3b674708ca18f558c66f76dca0f38e354219b418
658e34018e9749ae3c8c2c077f657a7d29306d23
refs/heads/master
<file_sep>from flask import Flask, jsonify, request import json, requests app = Flask(__name__) @app.route("/users", methods=["GET"]) def get_users(): users = "http://faker.hook.io/?property=helpers.userCard&amp;locale=en_US" user_cards = [] for i in range(25): raw_user = requests.get(users) raw_user = raw_user.json() user_cards.append(raw_user) print(user_cards) return "complete: printed user cards to terminal" """NOTE: if returning user cards is preferred instead of printing, run: return str(user_cards)""" if __name__ == ("__main__"): app.run(debug=True, port=5000, host="0.0.0.0")
1db6d2543eec29848efee011da1f2c3436670b88
[ "Python" ]
1
Python
lilianaguerrero/ALS_SWE
e230aac0059e98c567651abc6acd3b6c9289f726
50df8d023a7de44b2ddb560ff3ce1154299564fb
refs/heads/main
<file_sep>import pyautogui import argparse import helper imageSnapRegion = (590, 170,2600, 1420) parser = argparse.ArgumentParser() parser.add_argument('-name', type=str, help='Image file Name') parser.add_argument('-imgType', type=str, help='imageType') parser.add_argument('-wait', type=str, help='Time to wait before taking snap') args = parser.parse_args() imageName = args.name imageType = args.imgType wait = args.wait imageType = helper.imageTypeMap[helper.ImageType[imageType]] helper.PauseForEffect(int(wait)) helper.Beep() pyautogui.screenshot(imageName + imageType, region = imageSnapRegion) helper.Beep() <file_sep>import json import time import pyautogui from enum import Enum import winsound MIN_SLEEP_TIME = 10 SMALL_PAUSE = 3 MEDIUM_PAUSE = 10 LARGE_PAUSE = 20 WAIT_WINDOW = 40 class ImageType (Enum): JPEG = 1 PNG = 2 BMP = 3 imageTypeMap = {} imageTypeMap[ImageType['JPEG']] = ".jpg" imageTypeMap[ImageType['PNG']] = ".png" imageTypeMap[ImageType['BMP']] = ".bmp" class VideoCodec (Enum): MP4V = 1 XVID = 2 videoExtensionMap = {} videoExtensionMap[VideoCodec['MP4V']] = ".mp4" videoExtensionMap[VideoCodec['XVID']] = ".avi" def Beep(): duration = 1000 # milliseconds freq = 440 # Hz winsound.Beep(freq, duration) def PrettyPrintJSON(jsonObj, jsonIndent = 3): print(json.dumps(jsonObj, indent = jsonIndent)) def PauseForEffect(inputTime): while inputTime > 10: time.sleep(MIN_SLEEP_TIME) inputTime -= 10 print("Waited for 10 sec, Time Left: {}".format(inputTime)) time.sleep(inputTime) def LocateImage(templateImageLocation, confidence_input = 0.9): x = None y = None try: x, y = pyautogui.locateCenterOnScreen(templateImageLocation, grayscale = True, confidence= confidence_input) print("Button FOUND : {}".format(templateImageLocation)) except: print("Button not Found : {}".format(templateImageLocation)) return x, y def ClickAndWait(x,y, waitTime = 0): if x != None and y != None: pyautogui.click(x,y) if waitTime > 0: PauseForEffect(waitTime) else: exit(1) def LocateAndClick(templateImageLocation, waitTime = 0, adjX = 0, adjY = 0, confidence_input = 0.9): x, y = LocateImage(templateImageLocation, confidence_input) ClickAndWait(x + adjX, y + adjY, waitTime) <file_sep># Tour needs the following things # 1. The tour should have all the locations # 2. Time Stamp should be there as that will be replaced in new KML # 3. Start Point will be chosen by default # 4. It will create a new local KML file with the Date # 5. Google Earth should be open with places already expanded # 6. Add the new KML # 7. Start recording # 8. Play tour for the temp folder # 9. Record till atleast 10 times the image is repeated # 10. Stop Tour # 11. Clear Temp Folder Contents import pyautogui import math import os import time import re import helper import videoCreator # this will have to be determined based on the device IMAGE_WIDTH = 2600 IMAGE_HEIGHT = 1420 imageRegion = (590, 170,IMAGE_WIDTH, IMAGE_HEIGHT) closeX = 50 closeY = -50 #CONSTANTS (Independent of the screen resolution) DEFAULT_VIDEO_NAME = "video" DEFAULT_VIDEO_CODEC = "MP4V" DEFAULT_VIDEO_FPS = 3 SCROLL_AMOUNT = 30 DEFAULT_SCREENSHOT_NAME = "screenshot_tour_.jpg" def EndReached(): x, y = helper.LocateImage("./common/stopRecording.png") if x != None and y != None: return False else: return True def CheckJSON(inputJSON): assert "file" in inputJSON, "Initial File has to be provided" assert "dates" in inputJSON, "At least 1 date has to be provided" def GetNewFileName(inputFileName, inputDate): pathVal, fileName = os.path.split(inputFileName) fileName, extension = os.path.splitext(fileName) return os.path.join(pathVal, fileName + inputDate + extension) def CreateNewKMLFile(inputFileName, inputDate): newFileName = GetNewFileName(inputFileName, inputDate) print("New File Name: {}".format(newFileName)) lines = [] with open(inputFileName, "r") as f: lines = f.readlines() newLines = [] for line in lines: if "when" in line: line = re.sub("<when>(.*)</when>", "<when>"+ inputDate +"</when>", line) newLines.append(line) with open(newFileName, "w") as f: f.writelines(newLines) print("Created a new file") return newFileName def OpenFile(fileName): pyautogui.hotkey("ctrl", "o") helper.PauseForEffect(helper.SMALL_PAUSE) pyautogui.write(fileName) pyautogui.press(["enter"]) def CreateTour(inputFileName, totalTime): # Video Details pathVal, fileName = os.path.split(inputFileName) fileName, extension = os.path.splitext(fileName) videoName = os.path.join(pathVal, fileName + helper.videoExtensionMap[helper.VideoCodec[DEFAULT_VIDEO_CODEC]]) # Complete Recording x, y = helper.LocateImage("./common/saveTour.png") if x != None and y != None: helper.ClickAndWait(x, y, helper.SMALL_PAUSE) pyautogui.write("Tour") helper.PauseForEffect(helper.SMALL_PAUSE) pyautogui.press(["enter"]) helper.PauseForEffect(helper.SMALL_PAUSE) helper.ClickAndWait(x + closeX, y + closeY, helper.SMALL_PAUSE) pyautogui.hotkey("alt", "t") pyautogui.press(["down", "down", "down"]) pyautogui.press(["enter"]) helper.PauseForEffect(helper.SMALL_PAUSE) pyautogui.press(["tab", "tab"]) pyautogui.write(videoName) helper.LocateAndClick("./common/createMovie.png", helper.SMALL_PAUSE) def CleanUp(): x, y = helper.LocateImage("./common/tempPlacesNotSelected.png") if x != None and y != None: helper.ClickAndWait(x, y, helper.SMALL_PAUSE) pyautogui.click(button = 'right') pyautogui.press(["down", "down", "down"]) pyautogui.press(["enter"]) helper.PauseForEffect(helper.SMALL_PAUSE) pyautogui.press(["enter"]) def RecordTour(fileName, totalTime): x, y = helper.LocateImage("./common/tempPlacesNotSelected.png") if x != None and y != None: helper.ClickAndWait(x, y, helper.SMALL_PAUSE) helper.LocateAndClick("./common/recordTour.png", helper.SMALL_PAUSE) CreateTour(fileName, totalTime) def CreateAndRecord(inputFileName, inputDate, totalTime): fileName = CreateNewKMLFile(inputFileName, inputDate) print("Opening File") helper.PauseForEffect(helper.SMALL_PAUSE) print(os.path.join(os.getcwd(), "StartPoint.kml")) OpenFile(os.path.join(os.getcwd(), "StartPoint.kml")) helper.PauseForEffect(helper.SMALL_PAUSE) OpenFile(fileName) helper.PauseForEffect(helper.SMALL_PAUSE) RecordTour(fileName, totalTime) helper.PauseForEffect(helper.SMALL_PAUSE) # Check Every Few Interval if the recording has stopped while not EndReached(): helper.PauseForEffect(helper.MEDIUM_PAUSE) CleanUp() def record(inputJSON): CheckJSON(inputJSON) helper.PauseForEffect(helper.SMALL_PAUSE) allDates = inputJSON["dates"] for date in allDates: CreateAndRecord(inputJSON["file"], date, inputJSON["time"]) <file_sep>import pyautogui import math import os import helper import videoCreator # this will have to be determined based on the device backwardDelta = [-450, 150] forwardDelta = [220, 150] imageRegion = (590, 170,2600, 1420) searchBoxLocation = -200 centerOfPoint = 700 #CONSTANTS (Independent of the screen resolution) TIMELAPSE_IMAGE_NAME = "timelapse_" DEFAULT_VIDEO_NAME = "video" DEFAULT_VIDEO_CODEC = "MP4V" DEFAULT_VIDEO_FPS = 3 SCROLL_AMOUNT = 30 # There has to be only one result available for this to work def GoToPlace(inputPlace): helper.LocateAndClick('./common/search.png', adjX = searchBoxLocation) pyautogui.write(inputPlace, interval = 0.1) helper.LocateAndClick('./common/searchActive.png', helper.LARGE_PAUSE) helper.LocateAndClick('./common/closeSearch.png', helper.SMALL_PAUSE) def GetMode(startVal, endVal): return (-1, 1)[startVal > endVal] def GetListToCapture(inputJSON, startVal, endVal): listToCapture = [] # Capture All Steps if inputJSON["type"] == "TIMELAPSE": print(startVal, endVal) for i in range(startVal, endVal + (-1) * GetMode(startVal, endVal), (-1) * GetMode(startVal, endVal)): listToCapture.append(i) # Capture Only Start and End if inputJSON["type"] == "BNA": listToCapture.append(startVal) listToCapture.append(endVal) return listToCapture def CreateVideoFromJSON(videoJSON, currentImageType): videoName = DEFAULT_VIDEO_NAME videoFPS = DEFAULT_VIDEO_FPS videoCODEC = DEFAULT_VIDEO_CODEC if "name" in videoJSON: videoName = videoJSON["name"] if "codec" in videoJSON: videoCODEC = videoJSON["codec"] if "fps" in videoJSON: videoFPS = videoJSON["fps"] videoCreator.CreateVideo("./", videoName, currentImageType, videoCODEC, videoFPS) def GoToStartPoint(startVal, endVal, x, y): count = 0 # Need Extra as we are taking a snapshot after click # For FORWARD we should move 1 step ahead, hence range increases by 2 # For BACKWARD we should go 1 step behind, hence rnage should not increase for i in range(1, startVal + (1 + GetMode(startVal, endVal))): helper.ClickAndWait(x + backwardDelta[0], y + backwardDelta[1]) count += 1 print("Total Clicks : {}".format(str(count))) helper.PauseForEffect(helper.MEDIUM_PAUSE) print("Current Mode is {}".format(str(GetMode(startVal, endVal)))) def CreateImages(startVal, endVal, stepX, stepY, listToCapture, imageName, imageNamePadding, imageType, imageSnapRegion): # Click and Create image for i in range(startVal, endVal + (-1) * GetMode(startVal, endVal), (-1) * GetMode(startVal, endVal)): helper.ClickAndWait(stepX, stepY, helper.SMALL_PAUSE) # Click print("Now on Click {}".format(str(i))) # Skip the ones that are not necessary if i not in listToCapture: continue if i < 0: continue print("Snapshot Click is {}".format(str(i))) # Create image pyautogui.screenshot(imageName + str(i).zfill(imageNamePadding) + imageType, region = imageSnapRegion) def GetImageNameAndType(imageJSON): assert "image_type" in imageJSON imageType = helper.imageTypeMap[helper.ImageType[imageJSON["image_type"]]] imageName = TIMELAPSE_IMAGE_NAME if "image_name" in imageJSON: imageName = imageJSON["image_name"] return imageName, imageType def CheckJSONForCorrectness(inputJSON): assert "start_count" in inputJSON, "Need to Specify start count" assert "end_count" in inputJSON, "Need to Specify end count" assert "image" in inputJSON, "Image property has to be defined" def record(inputJSON): helper.PauseForEffect(helper.SMALL_PAUSE) if "place" in inputJSON: GoToPlace(inputJSON["place"]) if "cooridnate" in inputJSON: GoToPlace(inputJSON["cooridnate"]) if "scroll" in inputJSON: helper.LocateAndClick('./common/earth.png', helper.MEDIUM_PAUSE, adjY = centerOfPoint) for i in range(0,inputJSON["scroll"]): pyautogui.scroll(SCROLL_AMOUNT) # Locate Time Lapse x, y = helper.LocateImage('./common/timelapse.png') if x != None and y != None: # Start Time Lapse helper.ClickAndWait(x, y, helper.SMALL_PAUSE) startVal = inputJSON["start_count"] endVal = inputJSON["end_count"] assert startVal != endVal, "Start and End Cannot be the same" # When Imagery starts its on the actual date # At the current date there is not image # When you click BACK for the first time, it moves to the # Latest Available Imagery / Image Ticker 0 helper.ClickAndWait(x + backwardDelta[0], y + backwardDelta[1]) GoToStartPoint(startVal, endVal, x, y) # Preprocessing before taking snapshot stepX = x stepY = y if GetMode(startVal, endVal) == -1: stepX = x + backwardDelta[0] stepY = y + backwardDelta[1] if GetMode(startVal, endVal) == 1: stepX = x + forwardDelta[0] stepY = y + forwardDelta[1] listToCapture = GetListToCapture(inputJSON, startVal, endVal) print(listToCapture) totalPad = int(math.ceil(math.log10(max(startVal, endVal)))) imageName, imageType = GetImageNameAndType(inputJSON["image"]) CreateImages(startVal, endVal, stepX, stepY, listToCapture, imageName, totalPad, imageType, imageRegion) # Make the video if needed if "video" in inputJSON: videoJSON = inputJSON["video"] CreateVideoFromJSON(videoJSON, imageType) # Delete the images if "delete" in inputJSON["image"] and inputJSON["image"]["delete"] == "Yes": if inputJSON["type"] == "TIMELAPSE" and "video" in inputJSON: for fileName in os.listdir('./'): if fileName.endswith(imageType): os.remove(fileName) # Close Time Lapse helper.ClickAndWait(x, y) <file_sep>import cv2 import numpy as np import glob import helper def CreateVideo(folderPath, videoName, currentImageType, videoCODEC, videoFPS): videoExtension = helper.videoExtensionMap[helper.VideoCodec[videoCODEC]] videoName += videoExtension img_array = [] for filename in sorted(glob.glob(folderPath + "/*" + currentImageType), reverse = True): print(filename) img = cv2.imread(filename) height, width, layers = img.shape size = (width,height) img_array.append(img) print("Total Images : {} - {}".format(len(img_array), videoName)) fourcc = cv2.VideoWriter_fourcc(*videoCODEC) out = cv2.VideoWriter(videoName, fourcc, videoFPS, size) for i in range(len(img_array)): out.write(img_array[i]) out.release()<file_sep>import cv2 import argparse import math def WriteImage(i, zFillVal, frame, method): h, w = frame.shape[:2] width_start = int(w/4) final_width = int(w/2) if method == 1: print("Shortening Image") frame = frame[:, width_start: width_start+final_width] cv2.imwrite('extracted_slice_'+str(i).zfill(zFillVal)+'.jpg',frame) parser = argparse.ArgumentParser() parser.add_argument('-name', type=str, help='Video file Name') parser.add_argument('-frames', nargs ="+", help='Frame Numbers to be extracted') parser.add_argument('-typeVal', type=int, help='Type of Frame Extraction') args = parser.parse_args() videoName = args.name framesList = [int(x) for x in args.frames] method = args.typeVal zFillVal = int(math.ceil(max(framesList))) # Opens the Video file cap= cv2.VideoCapture(videoName) i=0 prevFrame = None while(cap.isOpened()): ret, frame = cap.read() if ret == False: break if i in framesList: WriteImage(i, zFillVal, frame, method) i+=1 prevFrame = frame if -1 in framesList: WriteImage(i, zFillVal, prevFrame, method) cap.release() cv2.destroyAllWindows()<file_sep># google_earth_automation Code for automation of Google Earth Automation <file_sep>import re import sys def GetCoordinate(line): results = re.search("<coordinates>(.*)</coordinates>", line) if results is None: return coord = results.groups()[0].split(',') print("{}, {}".format(coord[1], coord[0])) def GetName(line): results = re.search("<name>(.*)</name>", line) if results is None: return print(results.groups()[0]) fileName = sys.argv[1] print(fileName) lines = [] with open(fileName, "r") as f: lines = f.readlines() for line in lines: if "coordinates" in line: GetCoordinate(line) if "name" in line: GetName(line) <file_sep>import argparse import json import pywinauto import helper import timelapse import tour parser = argparse.ArgumentParser() parser.add_argument('-param', type=str, help='Param JSON', required = False) args = parser.parse_args() paramJSON = {} if args.param is not None: try: with open(args.param, "r") as f: paramJSON = json.load(f) except OSError: print("File Read Error") helper.PrettyPrintJSON(paramJSON) # Import pywinauto Application class from pywinauto.application import Application # Start a new process and specify a path to the text file app = Application().start('"C:/Program Files/Google/Google Earth Pro/client/googleearth.exe"', timeout=helper.WAIT_WINDOW) helper.PauseForEffect(helper.MEDIUM_PAUSE) dlg_spec = app.window() # Resize the window x, y = helper.LocateImage('./common/restore.png') if x != None and y != None: helper.LocateAndClick('./common/restore.png', helper.SMALL_PAUSE) helper.LocateAndClick('./common/maximize.png', helper.SMALL_PAUSE) x, y = helper.LocateImage('./common/closeIntro.png') if x != None and y != None: helper.LocateAndClick('./common/closeIntro.png', helper.SMALL_PAUSE) if paramJSON: assert "data" in paramJSON, "Data parameter not provided" allData = paramJSON["data"] for data in allData: assert "type" in data, "Type Parameter not provided" if data["type"] == "TIMELAPSE": timelapse.record(data) elif data["type"] == "BNA": timelapse.record(data) elif data["type"] == "TOUR": tour.record(data) else: print("TYPE not recognized")
234f2b00e3673480bcb2cc562e2988cb58ad38e1
[ "Markdown", "Python" ]
9
Python
aaprabhu1992/google_earth_automation
d0da659650836911ef460616296990b3d277cc8e
feb075a3addce1f1c341540a43c4e139bc4e7988
refs/heads/master
<file_sep>import java.util.ArrayList; public class Collections { public static void main(String[] args) { ArrayList<Sample> list = new ArrayList<Sample>(); list.add(new Sample("chandu", "IT", "TCS", 25000)); list.add(new Sample("Harish", "CBO", "wipro", 30000)); list.add(new Sample("Ravi", "electronics", "Infosys", 50000)); for(Sample p : list) { System.out.println(p.e_name +" " + p.e_id + " " + p.company + " " + p.salery); } } } <file_sep>import java.util.ArrayList; public class Sample { String e_name; String e_id; String company; int salery; public Sample(String e_name, String e_id, String company,int salery) { this.e_name = e_name; this.e_id = e_id; this.company = company; this.salery = salery; } }
67bee306ccb425e0adce0c9e0a4deb5d44ff95dc
[ "Java" ]
2
Java
chandu6262/colelctions
2beb8386cde033db63f1cd1ecbb5030b4c66fb7d
7fff79753357564d6d97ca3689c78f3490184aa2
refs/heads/master
<repo_name>imsifat/LoginPage<file_sep>/LoginPage/SignIn.swift // // SignIn.swift // LoginPage // // Created by <NAME> on 11/10/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit import Firebase class SignIn: UIViewController { @IBOutlet weak var segmentControl: UISegmentedControl! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passTextField: UITextField! @IBOutlet weak var loginLBL: UILabel! @IBOutlet weak var SignInOutlet: UIButton! var isSignIn = true override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func segmentButtonClicked(_ sender: Any) { isSignIn = !isSignIn if isSignIn{ loginLBL.text = "Sign in" SignInOutlet.setTitle("Sign in", for: .normal) emailTextField.text = "" passTextField.text = "" }else{ loginLBL.text = "Sign Up" SignInOutlet.setTitle("Sign Up", for: .normal) emailTextField.text = "" passTextField.text = "" } } @IBAction func SignIn(_ sender: Any) { if let email = emailTextField.text , let password = passTextField.text{ if isSignIn{ Auth.auth().signIn(withEmail: email, password: <PASSWORD>) { (user, error) in if let u = user{ self.performSegue(withIdentifier: "segue", sender: self) }else{ } } }else{ Auth.auth().createUser(withEmail: email, password: <PASSWORD>) { (user, error) in if let u = user{ self.performSegue(withIdentifier: "segue", sender: self) }else{ } } } }else{ } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?){ emailTextField.resignFirstResponder() passTextField.resignFirstResponder() } }
a4f80cfa543266fb1031b33a652300ef23761bab
[ "Swift" ]
1
Swift
imsifat/LoginPage
3bd2f0e335985a4a22b77a503fcbfca43608a7cf
7b4c8a5eec9a5865a4a49315e99b8f4f91cb0c41
refs/heads/master
<repo_name>kbahrar/builtins_42sh<file_sep>/libft/ft_strsplit.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strsplit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kbahrar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/03 19:28:48 by kbahrar #+# #+# */ /* Updated: 2019/04/25 21:49:57 by kbahrar ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static int how_many(char const *s, char c) { int i; int temp; temp = 0; i = 0; while (s[i] == c) i++; if (s[i]) temp = 1; while (s[i]) { if (s[i] == c) { while (s[i] == c) i++; if (s[i] == '\0') return (temp); temp++; } i++; } return (temp); } static int size_mallocc(char const *s, char c, int i) { int temp; temp = 0; while (s[i] == c) i++; while (s[i] != c && s[i]) { temp++; i++; } return (temp); } char **ta3mir(char **str, char const *s, char c, int i) { int j; int temp; j = 0; temp = -1; while (s[i]) { str[j][++temp] = s[i]; i++; if (s[i] == c || s[i] == '\0') { while (s[i] == c) i++; str[j][++temp] = '\0'; temp = -1; j++; if (s[i] != '\0') str[j] = (char*)ft_memalloc(size_mallocc(s, c, i) + 1); } } str[j] = NULL; return (str); } char **ft_strsplit(char const *s, char c) { char **str; int i; int j; i = 0; j = 0; if (s == NULL) return (NULL); if (!(str = (char**)malloc((how_many(s, c) + 1) * sizeof(str)))) return (NULL); while (s[i] == c) i++; str[j] = (char*)ft_memalloc(size_mallocc(s, c, i) + 1); str = ta3mir(str, s, c, i); return (str); } <file_sep>/builtins.h /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* builtins.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kbahrar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/12/27 18:35:20 by kbahrar #+# #+# */ /* Updated: 2020/01/22 18:10:04 by kbahrar ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef BUILTINS_H # define BUILTINS_H # include "libft/libft.h" # include <sys/stat.h> int ft_builtins(char **av); int ft_echo(char **args); int ft_type(char **args); int ft_type_options(int *opt, int *place, char **args); char *access_file(char **env, char *file); int if_builtin(char *str); int ft_cd_options(int *opt, int *place, char **args); int ft_cd(char **args); char *mod_path(char *path); char *mod_point(char *path); char *get_all_path(char *path); char *get_cdpath(char *pwd, char *path); #endif <file_sep>/libft/ft_itoa.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_itoa.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kbahrar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/28 20:44:25 by kbahrar #+# #+# */ /* Updated: 2019/04/11 19:07:19 by kbahrar ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static int ft_size(unsigned int nbr) { int t; t = 1; while (nbr >= 10) { nbr = nbr / 10; t++; } return (t); } static void ft_rev(char *t) { char temp; int i; int j; int s; i = 0; j = 0; while (t[i] != '\0') i++; s = i; while (j < (s / 2)) { temp = t[i - 1]; t[i - 1] = t[j]; t[j] = temp; i--; j++; } } static int ft_negpos(int n) { if (n < 0) return (-n); else return (n); } static int ft_negposs(int n) { if (n < 0) return (1); else return (0); } char *ft_itoa(int n) { char *tab; unsigned int s; unsigned int i; unsigned int l; unsigned int nn; i = ft_negposs(n) + 1; l = ft_negposs(n); n = ft_negpos(n); nn = n; s = ft_size(nn); if (!(tab = (char*)malloc(sizeof(char) * (s + i)))) return (0); i = -1; while (++i < s) { tab[i] = (nn % 10) + '0'; nn = nn / 10; } if (l == 1) tab[i++] = '-'; tab[i] = '\0'; ft_rev(tab); return (tab); } <file_sep>/ft_type.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_type.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kbahrar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/12/28 18:56:58 by kbahrar #+# #+# */ /* Updated: 2020/01/17 15:21:53 by kbahrar ### ########.fr */ /* */ /* ************************************************************************** */ #include "builtins.h" static int ft_type_t(char *str, int ret) { extern char **environ; if (if_builtin(str)) ft_putstr("builtin\n"); else { str = access_file(environ, str); if ((ft_strchr(str, '/')) && !access(str, F_OK)) { free(str); ft_putstr("file\n"); } else return (ret); } return (0); } static int ft_type_p(char *str, int opt, int a, int ret) { extern char **environ; if (opt == 1 && a == -1) if (if_builtin(str)) return (0); str = access_file(environ, str); if ((ft_strchr(str, '/')) && !access(str, F_OK)) { free(str); ft_putendl(str); } else return (ret); return (0); } static int ft_type_a(char *str, int ret) { extern char **environ; char *cpy; cpy = ft_strdup(str); if (if_builtin(str)) { ft_putstr(str); ft_putendl(" is a shell builtin"); } str = access_file(environ, str); if (ft_strchr(str, '/') && !access(str, F_OK)) { ft_putstr(cpy); ft_putstr(" is "); ft_putendl(str); free(str); } else if (!if_builtin(str)) { free(cpy); return (ret); } free(cpy); return (0); } static int ft_type_n(char *str, int ret) { extern char **environ; char *cpy; if (if_builtin(str)) ft_putstr_plus(str, " is a shell builtin\n"); else { cpy = ft_strdup(str); str = access_file(environ, str); if ((ft_strchr(str, '/')) && !access(str, F_OK)) { ft_putstr_plus(cpy, " is "); ft_putendl(str); free(cpy); free(str); } else { ft_putstr_fd("42sh: type: ", 2); ft_putstr_fd(str, 2); ft_putendl_fd(": not found", 2); return (ret); } } return (0); } int ft_type(char **args) { int i; int opt[5]; int ret; i = 1; ret = 1; if (!args[i]) return (0); if (ft_type_options(opt, &i, args) != 0) return (2); while (args[i]) { if (opt[3] == 1) ret = ft_type_t(args[i], ret); else if (opt[2] == 1 || opt[4] == 1) ret = ft_type_p(args[i], opt[2], opt[0], ret); else if (opt[0] == 1) ret = ft_type_a(args[i], ret); else ret = ft_type_n(args[i], ret); i++; } return (ret); } <file_sep>/ft_builtins.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_builtins.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kbahrar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/12/28 17:56:56 by kbahrar #+# #+# */ /* Updated: 2020/01/22 17:46:28 by kbahrar ### ########.fr */ /* */ /* ************************************************************************** */ #include "builtins.h" static int if_all_num(char *str) { int i; i = 0; while (str[i]) { if (!ft_isdigit(str[i])) return (0); i++; } return (1); } static int ft_exit(char **args) { int num; num = 0; if (!args[1]) exit(0); if (args[1] && args[2]) { ft_putendl_fd("42sh: exit: too many arguments", 2); return (1); } if (!if_all_num(args[1])) { ft_putstr_fd("42sh: ", 2); ft_putstr_fd(args[1], 2); ft_putendl_fd(": numeric argument required", 2); num = 255; } else num = ft_atoi(args[1]); exit(num); } int ft_builtins(char **av) { if (!ft_strcmp(av[0], "cd")) return (ft_cd(av)); else if (!ft_strcmp(av[0], "echo")) return (ft_echo(av)); else if (!ft_strcmp(av[0], "type")) return (ft_type(av)); else if (!ft_strcmp(av[0], "exit")) return (ft_exit(av)); return (-1); } <file_sep>/libft/Makefile # **************************************************************************** # # # # ::: :::::::: # # Makefile :+: :+: :+: # # +:+ +:+ +:+ # # By: kbahrar <<EMAIL>> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2019/03/28 15:09:45 by kbahrar #+# #+# # # Updated: 2019/07/11 16:06:29 by kbahrar ### ########.fr # # # # **************************************************************************** # NAME = libft.a SRC = ft_tabjoin.c rem_decal.c get_next_line.c ft_howmanynum.c ft_chreplace.c ft_pathjoin.c ft_strcpy_b.c ft_putstr_plus.c add_link.c ft_atoi.c ft_bzero.c ft_isalnum.c ft_isalpha.c ft_isascii.c ft_isdigit.c ft_isprint.c ft_itoa.c ft_lstadd.c ft_lstdel.c ft_lstdelone.c ft_lstiter.c ft_lstmap.c ft_lstnew.c ft_memalloc.c ft_memccpy.c ft_memchr.c ft_memcmp.c ft_memcpy.c ft_memdel.c ft_memmove.c ft_memset.c ft_print_list.c ft_putchar.c ft_putchar_fd.c ft_putendl.c ft_putendl_fd.c ft_putnbr.c ft_putnbr_fd.c ft_putstr.c ft_putstr_fd.c ft_strcat.c ft_strchr.c ft_strclr.c ft_strcmp.c ft_strcpy.c ft_strdel.c ft_strdup.c ft_strequ.c ft_striter.c ft_striteri.c ft_strjoin.c ft_strlcat.c ft_strlen.c ft_strlowcase.c ft_strmap.c ft_strmapi.c ft_strncat.c ft_strncmp.c ft_strncpy.c ft_strnequ.c ft_strnew.c ft_strnstr.c ft_strrchr.c ft_strsplit.c ft_strstr.c ft_strsub.c ft_strtrim.c ft_strupcase.c ft_swap.c ft_tolower.c ft_toupper.c OBJ = $(SRC:.c=.o) all:$(NAME) $(NAME): $(OBJ) @ar rc $(NAME) $(OBJ) clean: rm -rf $(OBJ) fclean: clean rm -rf $(NAME) re: fclean all %.o : $(SRC_DIR)%.c gcc -Wall -Wextra -Werror -c $< -o $@
b1312c2ffcac2a136137ec316032a33f0f8e4106
[ "C", "Makefile" ]
6
C
kbahrar/builtins_42sh
8112ac43f239fdf00beda11f4cc35b0f86b1d4c8
ce5f33d9c243f2c88ed456a76e4e42663a4b150d
refs/heads/master
<file_sep>import { Link, useLocation, matchPath } from 'react-router-dom'; import clsx from 'clsx'; export default function Nav() { const location = useLocation(); // Find currently active item by checking // which tab route "matches" the current path const homeTabClassName = clsx('px-3 py-2 rounded-md text-sm font-medium', { 'text-gray-300 hover:bg-gray-700 hover:text-white': !matchPath( location.pathname, '/', ).isExact, 'bg-gray-900 text-white': matchPath(location.pathname, '/').isExact, }); const forfeitTabClassName = clsx('px-3 py-2 rounded-md text-sm font-medium', { 'text-gray-300 hover:bg-gray-700 hover:text-white': !matchPath( location.pathname, '/forfeits', ), 'bg-gray-900 text-white': matchPath(location.pathname, '/forfeits'), }); const adminTabClassName = clsx('px-3 py-2 rounded-md text-sm font-medium', { 'text-gray-300 hover:bg-gray-700 hover:text-white': !matchPath( location.pathname, '/admin', ), 'bg-gray-900 text-white': matchPath(location.pathname, '/admin'), }); return ( <nav className="bg-gray-800"> <div className="max-w-7xl mx-auto px-2 sm:px-6 lg:px-8"> <div className="relative flex items-center justify-between h-16"> <div className="flex-1 flex items-center justify-center sm:items-stretch sm:justify-start"> <div className="block sm:ml-6"> <div className="flex space-x-4"> <Link to="/" className={homeTabClassName}> Home </Link> <Link to="/forfeits" className={forfeitTabClassName}> Gages </Link> <Link to="/admin" className={adminTabClassName}> Admin </Link> </div> </div> </div> </div> </div> </nav> ); } <file_sep>import Countdown from '../components/Countdown'; import Card from '../components/Card'; export default function Home() { return ( <div> <Card className="bg-gray-800 flex justify-center"> <Countdown /> </Card> <Card className="bg-gray-800 flex justify-center"> <iframe src="https://open.spotify.com/embed/playlist/2Gf7I3Gpn2fEUf1ifKCRK3" width="300" height="380" frameBorder="0" allowTransparency="true" allow="encrypted-media" ></iframe> </Card> </div> ); } <file_sep>import { useState, useEffect, useCallback } from 'react'; import { Formik, Form, Field, ErrorMessage } from 'formik'; import { auth, googleProvider, db } from '../firebase'; import Card from '../components/Card'; import GoogleSignInButton from '../components/GoogleSignInButton'; export default function Admin() { const [user, setUser] = useState(null); const [forfeits, setForfeits] = useState([]); const [hasInitialUserLoad, setHasInitialUserLoad] = useState(false); const [isLoginLoading, setIsLoginLoading] = useState(false); const login = async () => { setIsLoginLoading(true); try { await auth.signInWithPopup(googleProvider); setIsLoginLoading(false); } catch (e) { console.error(e); setIsLoginLoading(false); } }; const addForfeit = useCallback( async ({ description, title }) => { try { await db.collection('forfeits').add({ label: title, description: description, creator: user.displayName, }); } catch (e) { console.error(e); } }, [user], ); const removeForfeit = async (id) => { try { await db.collection('forfeits').doc(id).delete(); } catch (e) { console.error(e); } }; useEffect(() => { const handler = db.collection('forfeits').onSnapshot((snapshot) => { const docs = snapshot.docs.map((snap) => ({ ...snap.data(), docId: snap.id, })); setForfeits(docs); }); return handler; }, [setForfeits]); useEffect(() => { const handler = auth.onAuthStateChanged((nextUser) => { setUser(nextUser); setHasInitialUserLoad(true); if (nextUser) { setIsLoginLoading(false); } }); return handler; }, []); if (!hasInitialUserLoad) { return <div>LOADING !!!!</div>; } return ( <> <Card className="bg-gray-800 text-white"> {!user && ( <div> <p> Afin de pouvoir ajouter des gages, merci de t'identifier via ton compte Google </p> <GoogleSignInButton onClick={login} /> </div> )} {user && ( <div> <p className="mb-4"> Salut {user.displayName}, tu peux ajouter un gage (dans la limite du raisonnable) </p> <Formik initialValues={{ title: '', description: '' }} validate={(values) => { const errors = {}; if (!values.description) { errors.description = 'Required'; } return errors; }} onSubmit={( { title, description }, { setSubmitting, resetForm }, ) => { addForfeit({ title, description }).then(() => { setSubmitting(false); resetForm(); }); }} > {({ isSubmitting, errors }) => ( <Form> <div className=" relative mb-2 "> <label htmlFor="title">Titre (facultatif)</label> <Field type="text" className=" rounded-lg border-transparent flex-1 appearance-none border border-gray-300 w-full py-2 px-4 bg-white text-gray-700 placeholder-gray-400 shadow-sm text-base focus:outline-none focus:ring-2 focus:ring-purple-600 focus:border-transparent" name="title" /> </div> <div className="relative mb-2"> <label htmlFor="description"> Énoncé <span className="required-dot text-red-500">*</span> </label> <Field type="text" className={`${ errors.description && 'ring-red-500 ring-2' } rounded-lg border-transparent flex-1 appearance-none border border-gray-300 w-full py-2 px-4 bg-white text-gray-700 placeholder-gray-400 shadow-sm text-base focus:outline-none focus:ring-2 focus:ring-purple-600 focus:border-transparent`} name="description" placeholder="Quel est ton gage ?" /> {errors.description && ( <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" fill="currentColor" className="absolute right-2 text-red-500 bottom-8" viewBox="0 0 1792 1792" > <path d="M1024 1375v-190q0-14-9.5-23.5t-22.5-9.5h-192q-13 0-22.5 9.5t-9.5 23.5v190q0 14 9.5 23.5t22.5 9.5h192q13 0 22.5-9.5t9.5-23.5zm-2-374l18-459q0-12-10-19-13-11-24-11h-220q-11 0-24 11-10 7-10 21l17 457q0 10 10 16.5t24 6.5h185q14 0 23.5-6.5t10.5-16.5zm-14-934l768 1408q35 63-2 126-17 29-46.5 46t-63.5 17h-1536q-34 0-63.5-17t-46.5-46q-37-63-2-126l768-1408q17-31 47-49t65-18 65 18 47 49z"></path> </svg> )} <ErrorMessage name="description" component="p" className="-bottom-6 text-red-500 text-sm" /> </div> <button type="submit" disabled={isSubmitting} className="disabled:opacity-50 py-2 px-4 flex justify-center items-center bg-blue-600 hover:bg-blue-700 focus:ring-blue-500 focus:ring-offset-blue-200 text-white w-full transition ease-in duration-200 text-center text-base font-semibold py-2 px-4 rounded-lg shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 " > {isSubmitting && ( <svg width="20" height="20" fill="currentColor" className="mr-2 animate-spin" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg" > <path d="M526 1394q0 53-37.5 90.5t-90.5 37.5q-52 0-90-38t-38-90q0-53 37.5-90.5t90.5-37.5 90.5 37.5 37.5 90.5zm498 206q0 53-37.5 90.5t-90.5 37.5-90.5-37.5-37.5-90.5 37.5-90.5 90.5-37.5 90.5 37.5 37.5 90.5zm-704-704q0 53-37.5 90.5t-90.5 37.5-90.5-37.5-37.5-90.5 37.5-90.5 90.5-37.5 90.5 37.5 37.5 90.5zm1202 498q0 52-38 90t-90 38q-53 0-90.5-37.5t-37.5-90.5 37.5-90.5 90.5-37.5 90.5 37.5 37.5 90.5zm-964-996q0 66-47 113t-113 47-113-47-47-113 47-113 113-47 113 47 47 113zm1170 498q0 53-37.5 90.5t-90.5 37.5-90.5-37.5-37.5-90.5 37.5-90.5 90.5-37.5 90.5 37.5 37.5 90.5zm-640-704q0 80-56 136t-136 56-136-56-56-136 56-136 136-56 136 56 56 136zm530 206q0 93-66 158.5t-158 65.5q-93 0-158.5-65.5t-65.5-158.5q0-92 65.5-158t158.5-66q92 0 158 66t66 158z"></path> </svg> )} Valider </button> </Form> )} </Formik> </div> )} </Card> {user && ( <Card className="bg-gray-800 text-white"> <div className="flex flex-col w-full items-center justify-center bg-white rounded-lg shadow text-black"> <ul className="flex flex-col divide divide-y w-full"> {forfeits.map(({ creator, label, description, docId }) => ( <li className="flex flex-row" key={docId}> <div className="select-none flex justify-between items-center p-4 w-full"> <div className="flex items-center mr-4 text-sm flex-1"> <span>{creator}</span> </div> <div className="pl-1 mr-16 flex-1"> <div className="font-medium">{label}</div> <div className="text-gray-600 text-sm">{description}</div> </div> <div className="text-gray-600 text-xs"> <button onClick={() => removeForfeit(docId)} className="flex items-center p-2 transition ease-in duration-200 uppercase rounded-full hover:bg-gray-800 hover:text-white border-2 border-gray-900 focus:outline-none" > <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /> </svg> </button> </div> </div> </li> ))} </ul> </div> </Card> )} </> ); } <file_sep>import { useState, useEffect } from 'react'; export default function Countdown() { const [countdownDate, setCountdownDate] = useState( new Date('01/01/2021').getTime(), ); const [state, setState] = useState({ days: 0, hours: 0, minutes: 0, seconds: 0, }); useEffect(() => { setInterval(() => updateCountdown(), 1000); }, []); const updateCountdown = () => { if (countdownDate) { // Get the current time const currentTime = new Date().getTime(); // Get the time remaining until the countdown date const distanceToDate = countdownDate - currentTime; // Calculate days, hours, minutes and seconds remaining let days = Math.floor(distanceToDate / (1000 * 60 * 60 * 24)); let hours = Math.floor( (distanceToDate % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60), ); let minutes = Math.floor( (distanceToDate % (1000 * 60 * 60)) / (1000 * 60), ); let seconds = Math.floor((distanceToDate % (1000 * 60)) / 1000); // For visual appeal, add a zero to each number that's only one digit const numbersToAddZeroTo = [1, 2, 3, 4, 5, 6, 7, 8, 9]; if (numbersToAddZeroTo.includes(hours)) { hours = `0${hours}`; } else if (numbersToAddZeroTo.includes(minutes)) { minutes = `0${minutes}`; } else if (numbersToAddZeroTo.includes(seconds)) { seconds = `0${seconds}`; } // Set the state to each new time setState({ days: days, hours: hours, minutes, seconds }); } }; return ( <div className="flex flex-col md:flex-row text-white flex-wrap w-1/2 justify-center"> <div className="flex flex-col items-center md:mr-10"> <span className="text-5xl">{state.days || 'OO'}</span> <span className="uppercase text-gray-400 text-sm">Jours</span> </div> <div className="flex flex-col items-center md:mr-10"> <span className="text-5xl">{state.hours || 'OO'}</span> <span className="uppercase text-gray-400 text-sm">Heures</span> </div> <div className="flex flex-col items-center md:mr-10"> <span className="text-5xl">{state.minutes || 'OO'}</span> <span className="uppercase text-gray-400 text-sm">Minutes</span> </div> <div className="flex flex-col items-center"> <span className="text-5xl">{state.seconds || 'OO'}</span> <span className="uppercase text-gray-400 text-sm">Secondes</span> </div> </div> ); } <file_sep>import { BrowserRouter, Switch, Route, Link } from 'react-router-dom'; import Home from './pages/Home'; import Admin from './pages/Admin'; import Forfeits from './pages/Forfeits'; import './App.css'; import Nav from './components/Nav'; function App() { return ( <BrowserRouter> <Nav /> <Switch> <Route path="/admin"> <Admin /> </Route> <Route path="/forfeits"> <Forfeits /> </Route> <Route path="/"> <Home /> </Route> </Switch> </BrowserRouter> ); } export default App; <file_sep>import clsx from 'clsx'; export default function Card({ className, children }) { const classNames = clsx('shadow-md p-6 m-4 rounded-lg', className); return <div className={classNames}>{children}</div>; } <file_sep>// Firebase App (the core Firebase SDK) is always required and // must be listed before other Firebase SDKs import firebase from 'firebase/app'; // Add the Firebase services that you want to use import 'firebase/auth'; import 'firebase/firestore'; const firebaseConfig = { apiKey: '<KEY>', authDomain: 'new-year-eve-forfeit.firebaseapp.com', projectId: 'new-year-eve-forfeit', storageBucket: 'new-year-eve-forfeit.appspot.com', messagingSenderId: '191341746666', appId: '1:191341746666:web:bc115656d099de4c057a93', }; firebase.initializeApp(firebaseConfig); export const auth = firebase.auth(); export const googleProvider = new firebase.auth.GoogleAuthProvider(); export const db = firebase.firestore(); <file_sep>import { useEffect, useState } from 'react'; import { db } from '../firebase.js'; import Card from '../components/Card'; export default function Forfeits() { const [forfeits, setForfeit] = useState([]); const [selectedForfeit, setSelectedForfeit] = useState(null); function getForfeits() { let forfeitsFirestore = []; db.collection('forfeits') .get() .then((querySnapshot) => { querySnapshot.forEach((doc) => { forfeitsFirestore.push(doc.data()); }); setForfeit(forfeitsFirestore); }); } function getRandomForfeit() { const maxRange = forfeits.length - 1; const minRange = 0; const random = Math.floor( Math.random() * (maxRange - minRange + 1) + minRange, ); setSelectedForfeit(forfeits[random]); } function forfeitTemplate() { const { label, description, creator } = selectedForfeit; return ( <div className="bg-white - w-72 shadow-lg mx-auto rounded-xl p-4"> <p className="text-black text-sm mb-4">{label}</p> <p className="text-gray-600"> <span className="font-bold text-indigo-500 text-lg">“</span> {description} <span className="font-bold text-indigo-500 text-lg">”</span> </p> <div className="flex items-center mt-4"> <div className="flex flex-col ml-2 justify-between"> <span className="font-semibold text-indigo-500 text-sm"> {creator} </span> </div> </div> </div> ); } useEffect(() => { getForfeits(); }, []); return ( <Card className="bg-gray-800 text-white"> {selectedForfeit && forfeitTemplate()} <div className="flex justify-center mt-4"> <button onClick={getRandomForfeit} className="flex items-center px-6 py-2 transition ease-in duration-200 uppercase rounded-full bg-white text-black hover:bg-gray-800 hover:text-white border-2 border-gray-900 focus:outline-none" > <svg width="20" height="20" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" className="mr-2" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v13m0-13V6a2 2 0 112 2h-2zm0 0V5.5A2.5 2.5 0 109.5 8H12zm-7 4h14M5 12a2 2 0 110-4h14a2 2 0 110 4M5 12v7a2 2 0 002 2h10a2 2 0 002-2v-7" /> </svg> La mort ou Tchi Tchi ? </button> </div> </Card> ); }
a71d5ff36545afc3abe11e0471d9f725c80c574c
[ "JavaScript" ]
8
JavaScript
NaelFR/new-year-eve
42935bce85fe2fc2646232af017c1abc6611fd5e
2e27ff149a2ad57b0014c0aa8590e1c6a4061cc0
refs/heads/master
<repo_name>suncube/PrototypePenguinPushers<file_sep>/README.md # Catcher Prototype [![License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](/LICENSE) [![Twitter](https://img.shields.io/badge/follow-Twitter-9cf.svg)](https://twitter.com/suncubestudio) [![Facebook](https://img.shields.io/badge/follow-Facebook-blue.svg)](https://www.facebook.com/suncubestudio/) [![YouTube](https://img.shields.io/badge/follow-YouTube-red.svg)](https://www.youtube.com/channel/UC4O9GHjx0ovyVYJgMg4aFMA?view_as=subscriber) [![AssetStore](https://img.shields.io/badge/-AssetStore-lightgrey.svg)](https://assetstore.unity.com/publishers/14506) This is simple prototype of a game like Penguin Pushers for single player. Result: ![Result](/ReadmeSource/preview1.gif) A source: ![](/ReadmeSource/preview2.gif) <file_sep>/Assets/_Test/Scripts/EnemyController.cs using System.Collections; using UnityEngine; public class EnemyController: MonoBehaviour { [SerializeField] private EnemySettings m_Settings; [SerializeField] private Rigidbody Rigidbody; private EnemyState enemyState; private float currentSpeed; private Vector3 targetRun; private void Awake() { MakeRandomRotate(); currentSpeed = m_Settings.IdleSpeed; } public void Catch(PlayerCatcher player) { if(enemyState == EnemyState.Run) return; enemyState = EnemyState.Run; currentSpeed = m_Settings.RunSpeed; FindDirection(player); } public void Free(PlayerCatcher player) { enemyState = EnemyState.Free; } public void Idle() { enemyState = EnemyState.Idle; currentSpeed = m_Settings.IdleSpeed; } public void FixedUpdate() { Processing(); } private void Processing() { if (GetDistance(transform.forward) < 2f) { MakeRandomRotate(); if (enemyState == EnemyState.Free) Idle(); } else { MoveForward(); } } private Coroutine prevCoroutine; private void FindDirection(PlayerCatcher player) { var moveDir = transform.position - player.transform.position; Quaternion rotation = Quaternion.LookRotation(moveDir, Vector3.up); transform.rotation = rotation; if (prevCoroutine != null) StopCoroutine(prevCoroutine); prevCoroutine = StartCoroutine(FindRunDir()); } IEnumerator FindRunDir() { while (GetDistance(transform.forward) < 2f) { Debug.Log("Rotate"); MakeRandomRotate(); yield return null; } } private void MakeRandomRotate() { var range = Random.Range(0, 360); transform.rotation *= Quaternion.Euler(0f, range, 0f); } private float GetDistance(Vector3 dir) { RaycastHit hit; Ray downRay = new Ray(transform.position, dir); // Cast a ray straight downwards. if (Physics.Raycast(downRay, out hit, 10, 1 << 0)) { Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow); return hit.distance; } return 10; } private void MoveForward() { Rigidbody.AddForce(transform.forward * currentSpeed); } } public enum EnemyState { Idle, Free, Run }<file_sep>/Assets/_Test/Scripts/PlayerCatcher.cs using UnityEngine; public class PlayerCatcher : MonoBehaviour { private void OnTriggerEnter(Collider other) { var enemyController = other.GetComponent<EnemyController>(); if(!enemyController) return; enemyController.Catch(this); } private void OnTriggerExit(Collider other) { var enemyController = other.GetComponent<EnemyController>(); if (!enemyController) return; enemyController.Free(this); } }<file_sep>/Assets/_Test/Scripts/FinishPlace.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class FinishPlace : MonoBehaviour { [SerializeField] private Animator m_Aminator; public Action<EnemyController> OnFinished; private void OnTriggerEnter(Collider other) { var enemyController = other.GetComponent<EnemyController>(); if (!enemyController) return; if (OnFinished != null) { OnFinished.Invoke(enemyController); Debug.Log(other.gameObject.name + " Catched "); m_Aminator.Play("Action"); } } } <file_sep>/Assets/_Test/Scripts/GameController.cs using System; using UnityEngine; using UnityEngine.UI; public class GameController : MonoBehaviour { [SerializeField] private FinishPlace m_FinishPlace; [SerializeField] private Transform m_Player; private Vector3 startPlayer; [Header("Settings")] [SerializeField] private int m_MaxEnemies = 10; [SerializeField] private EnemyController[] m_Enemies; private Vector3[] enemyPositions; [Header("UI")] [SerializeField] private Text m_ProgressText; private int currentEnemies; private void Awake() { LaunchInit(); StartGame(); } private void LaunchInit() { // for restart // enemyPositions = new Vector3[m_Enemies.Length]; for (var index = 0; index < m_Enemies.Length; index++) { enemyPositions[index] = m_Enemies[index].transform.position; } startPlayer = m_Player.position; m_FinishPlace.OnFinished += OnEnemyFinished; // } public void StartGame() { // for restart m_Player.position = startPlayer; for (var index = 0; index < m_Enemies.Length; index++) { m_Enemies[index].transform.position = enemyPositions[index]; } if (m_MaxEnemies > m_Enemies.Length) m_MaxEnemies = m_Enemies.Length; var liveEnemies = (m_Enemies.Length - m_MaxEnemies) - 1; for (var index = liveEnemies; index >=0; index--) { m_Enemies[index].gameObject.SetActive(false); } currentEnemies = m_MaxEnemies; UpdateProgressStatus(); } private void UpdateProgressStatus() { m_ProgressText.text = string.Format("Catched {0} / {1}", m_MaxEnemies-currentEnemies, m_MaxEnemies); } private void OnEnemyFinished(EnemyController enemy) { enemy.gameObject.SetActive(false); currentEnemies--; UpdateProgressStatus(); if (currentEnemies <= 0) m_ProgressText.text = "GAME ENDED"; } private void OnDestroy() { m_FinishPlace.OnFinished -= OnEnemyFinished; } }<file_sep>/Assets/_Test/Scripts/EnemySettings.cs using UnityEngine; [CreateAssetMenu(fileName = "EnemySettings", menuName = "Configs/Add Enemy Settings")] public class EnemySettings : ScriptableObject { public float RunSpeed = 4; public float IdleSpeed = 2; // rigedbody drag }<file_sep>/Assets/_Test/Scripts/PlayerSettings.cs using UnityEngine; [CreateAssetMenu(fileName = "PlayerSettings", menuName = "Configs/Add Player Settings")] public class PlayerSettings : ScriptableObject { public float Speed = 10; public float RotateSpeed = 5; }<file_sep>/Assets/_Test/Scripts/PlayerMoveController.cs using UnityEngine; using System.Collections; public class PlayerMoveController : MonoBehaviour { [SerializeField] private PlayerSettings m_Settings; [SerializeField] private Rigidbody Rigidbody; void FixedUpdate() { Processing(); } private void Processing() { Move(); Rotate(); } private void Move() { float moveVertical = Input.GetAxis("Vertical"); Vector3 movement = transform.forward * moveVertical; Rigidbody.AddForce(movement * m_Settings.Speed); } private void Rotate() { float moveHorizontal = Input.GetAxis("Horizontal"); transform.rotation *= Quaternion.Euler(0f, moveHorizontal * m_Settings.RotateSpeed, 0f); } }
1609654b238f4ffcf39ef3348c0640939aff0318
[ "Markdown", "C#" ]
8
Markdown
suncube/PrototypePenguinPushers
6ba2eb7f406083ee106011dc18ab0a63d4cae664
923dbee82bdf9638c39d55b31beefac8c4d0ff58
refs/heads/master
<repo_name>nickflya/FusionCsharp<file_sep>/FusionCsharp/model/coordinate.cs using System; using System.Collections.Generic; using System.Text; /// <summary> /// 坐标系模型 /// </summary> namespace FusionCsharp.model { public class coordinate { double x; double y; double z; public double X { get => x; set => x = value; } public double Y { get => y; set => y = value; } public double Z { get => z; set => z = value; } public coordinate(double x , double y,double z) { this.x = x; this.y = y; this.z = z; } } } <file_sep>/FusionCsharp/model/viewmodel/View.cs using MathNet.Numerics.LinearAlgebra; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; namespace FusionCsharp.model.viewmodel { /// <summary> /// 视点基类 /// </summary> abstract public class View { private List<double> depthdata = null;//深度图 private Matrix<double> modelviewMatrix = null;//视图矩阵 private Matrix<double> projectMatrix = null;//投影矩阵 public List<double> Depthdata { get => depthdata; set => depthdata = value; } public Matrix<double> ModelviewMatrix { get => modelviewMatrix; set => modelviewMatrix = value; } public Matrix<double> ProjectMatrix { get => projectMatrix; set => projectMatrix = value; } } } <file_sep>/FusionCsharp/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using FusionCsharp.model; using MathNet.Numerics.LinearAlgebra; using FusionCsharp.Math; using AForge.Video.DirectShow; using AForge.Video; using FusionCsharp.model.viewmodel; using System.Threading; namespace FusionCsharp { public partial class Form1 : Form { MathHelper mh = new MathHelper(); MainView mainview = new MainView();//主视图 CameraView cameraview1 = new CameraView(1);//摄像机1号 public Form1() { cameraview1.FileSource = new AForge.Video.DirectShow.FileVideoSource("C:\\Users\\huahai\\Documents\\GitHub\\FusionCsharp\\FusionCsharp\\data\\摄像机\\movie.avi"); //步骤一:读取主视图背景图、深度图、摄像机背景图(后期换成视频)和深度图,存入本地 mainview.Colordata = IO.IOhelper.readBMP("C:\\Users\\huahai\\Documents\\GitHub\\FusionCsharp\\FusionCsharp\\data\\主视图\\test.bmp"); mainview.Depthdata = IO.IOhelper.getdepthdata("C:\\Users\\huahai\\Documents\\GitHub\\FusionCsharp\\FusionCsharp\\data\\主视图\\depthdata.txt"); cameraview1.Depthdata = IO.IOhelper.getdepthdata("C:\\Users\\huahai\\Documents\\GitHub\\FusionCsharp\\FusionCsharp\\data\\摄像机\\depthdata.txt"); //步骤二:读取主视图和摄像机图MVP矩阵 double[,] modelviewMatrix_mainview = { { 0.87274477586533461,-0.31853087327850532,0.36993869622979397,102.50361835799191}, {0.10809792746051593, 0.86508111464077375,0.48984640773472798,44.104662708586204}, {-0.47605818371130654,-0.38752128697699839,0.78942755073609061, -986.81032604767370}, {0.00000000000000000, 0.00000000000000000,0.00000000000000000,1.0000000000000000} }; double[,] modelviewMatrix_camera1 = { { 0.74775775165414804,-0.37934716130469248, 0.54493492827236278,95.762009173457713 }, {0.092463160613615841,0.87221644200955561,0.48030099127269366,-8.2428991067991237}, {-0.65750202187557893,-0.30876238355451124,0.68728224313688080,-776.94778055543122}, {0.00000000000000000,0.00000000000000000,0.00000000000000000,1.0000000000000000} }; double[,] projectMatrix_mainview = { { 3.0769231897839462,0.00000000000000000, 0.00000000000000000,0.00000000000000000}, {0.00000000000000000,3.8461539872299335,0.00000000000000000,0.00000000000000000}, {0.00000000000000000,0.00000000000000000,-2.6190933518446222,-2180.4271028338017}, {0.00000000000000000,0.00000000000000000,-1.0000000000000000,0.00000000000000000} }; double[,] projectMatrix_camera1 = { { 3.0769231897839462, 0.00000000000000000, 0.00000000000000000, 0.00000000000000000 }, {0.00000000000000000,3.8461539872299335,0.00000000000000000,0.00000000000000000}, {0.00000000000000000,0.00000000000000000,-1.9028681049656828,-1082.8718693111402 }, {0.00000000000000000,0.00000000000000000,-1.0000000000000000,0.00000000000000000} }; double[] viewport_mainview = { 0.0, 0.0, 1000.0, 800.0 }; double[] viewport_camera1depth = { 0.0, 0.0, 1000.0, 800.0 }; double[] viewport_camera1color = { 0.0, 0.0, 1920.0, 1080.0 }; mainview.ModelviewMatrix = mh.getMatrix(modelviewMatrix_mainview); mainview.ProjectMatrix = mh.getMatrix(projectMatrix_mainview); mainview.Viewport = mh.getVector(viewport_mainview); cameraview1.ModelviewMatrix = mh.getMatrix(modelviewMatrix_camera1); cameraview1.ProjectMatrix = mh.getMatrix(projectMatrix_camera1); cameraview1.Viewport_depthdata = mh.getVector(viewport_camera1depth); cameraview1.Viewport_colordata = mh.getVector(viewport_camera1color); //步骤三:计算主视图与摄像头对应像素关系 cameraview1.List_relationshipMainviewCamera = mh.getRelationship(1000, 800, mainview.Depthdata, cameraview1.Depthdata, mainview.ModelviewMatrix, mainview.ProjectMatrix, mainview.Viewport, cameraview1.ModelviewMatrix, cameraview1.ProjectMatrix, cameraview1.Viewport_depthdata, cameraview1.Viewport_colordata); InitializeComponent(); } #region 方法四:对方法三的改进,建立主视图像素与摄像头像素的关系 public void execute() { execute1(); } void execute1() { OpenVideoSource1(cameraview1.FileSource); } private void OpenVideoSource1(IVideoSource source) { // start new video source videoSourcePlayer1.VideoSource = source; videoSourcePlayer1.Start(); videoSourcePlayer1.NewFrame += new AForge.Controls.VideoSourcePlayer.NewFrameHandler(captureframe1); } private void captureframe1(object sender, ref Bitmap image) { //放入消息队列 if (image != null) { cameraview1.Colordata = image;//获得视频帧数据 DateTime start = DateTime.Now; //步骤三:视频与3D模型融合 mh.funsion4(cameraview1.List_relationshipMainviewCamera, mainview.Colordata, cameraview1.Colordata); //步骤四:渲染绘制融合后的结果 draw(mainview.Colordata); DateTime end = DateTime.Now; TimeSpan ts = end - start; string a = ts.TotalMilliseconds.ToString(); } } void draw(Bitmap colordata_mainview_bmp) { if (colordata_mainview_bmp != null) { Graphics g = panel_draw.CreateGraphics(); g.DrawImage(colordata_mainview_bmp, 0, 0, colordata_mainview_bmp.Width, colordata_mainview_bmp.Height); } } #endregion /// <summary> /// 融合按钮时间 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button_fusion_Click(object sender, EventArgs e) { execute(); } /// <summary> /// 绘制函数 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void panel_draw_Paint(object sender, PaintEventArgs e) { } private void button_colordata_camera_bmp_Click(object sender, EventArgs e) { if (openFileDialog_colordata_camera_bmp.ShowDialog() == DialogResult.OK) { // // 创建视频数据源 // fileSource = new FileVideoSource(openFileDialog_colordata_camera_bmp.FileName); } } } } <file_sep>/FusionCsharp/model/relationshipMainviewCamera.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FusionCsharp.model { /// <summary> /// 存放主视图与摄像机上像素的对应关系 /// </summary> public class relationshipMainviewCamera { private int mainview_x; private int mainview_y; private int camera_x; private int camera_y; public int Mainview_x { get => mainview_x; set => mainview_x = value; } public int Mainview_y { get => mainview_y; set => mainview_y = value; } public int Camera_x { get => camera_x; set => camera_x = value; } public int Camera_y { get => camera_y; set => camera_y = value; } } } <file_sep>/FusionCsharp/IO/IOhelper.cs using System; using System.Collections.Generic; using System.Text; using System.IO; using FusionCsharp.model; using System.Drawing; using System.Windows.Forms; /// <summary> /// 文件操作类 /// </summary> namespace FusionCsharp.IO { public class IOhelper { #region 读取TXT文件 /// <summary> /// 得到主视图和摄像机的深度图 /// </summary> /// <param name="filename"></param> /// <returns></returns> public static List<double> getdepthdata(string filename) { List<double> depthdata_list = new List<double>(); StreamReader sr = File.OpenText(filename); string depth_string = ""; string[] depth_array; try { while ((depth_string = sr.ReadLine()) != null) { depth_array = depth_string.Split(','); double depth_double = double.Parse(depth_array[0]); depthdata_list.Add(depth_double); } } catch (System.Exception ex) { } finally { sr.Close(); } return depthdata_list; } #endregion #region 读取bmp文件 public static Bitmap readBMP(string filename) { Bitmap curBitmap = (Bitmap)Image.FromFile(filename); return curBitmap; } #endregion } } <file_sep>/FusionCsharp/Math/MathHelper.cs using System; using System.Collections.Generic; using System.Text; using MathNet.Numerics; using MathNet.Numerics.LinearAlgebra; using FusionCsharp.model; using System.Drawing; /// <summary> /// 所有需要的数学函数 /// </summary> namespace FusionCsharp.Math { public class MathHelper { MatrixBuilder<double> mb; VectorBuilder<double> vb; public MathHelper() { //初始化一个矩阵和向量的构建对象 mb = Matrix<double>.Build; vb = Vector<double>.Build; } ~MathHelper() { } /// <summary> /// 向量与矩阵相乘算法 /// </summary> /// <param name="output"></param> /// <param name="vec"></param> /// <param name="mat"></param> /// <returns></returns> public Vector<double> multiVectorAndMatrix(Vector<double> output, Vector<double> vec, Matrix<double> mat) { double x = vec[0], y = vec[1], z = vec[2], w = vec[3]; output[0] = mat[0, 0] * x + mat[0, 1] * y + mat[0, 2] * z + mat[0, 3] * w; output[1] = mat[1, 0] * x + mat[1, 1] * y + mat[1, 2] * z + mat[1, 3] * w; output[2] = mat[2, 0] * x + mat[2, 1] * y + mat[2, 2] * z + mat[2, 3] * w; output[3] = mat[3, 0] * x + mat[3, 1] * y + mat[3, 2] * z + mat[3, 3] * w; return output; } /// <summary> /// 将世界坐标转换为屏幕坐标 /// </summary> /// <param name="ObjectCoordinate"></param> /// <param name="modelviewMatrix"></param> /// <param name="projectMatrix"></param> /// <param name="viewport"></param> /// <param name="WinCoordinate"></param> /// <returns></returns> public coordinate Project(coordinate ObjectCoordinate, Matrix<double> modelviewMatrix, Matrix<double> projectMatrix, Vector<double> viewport, coordinate WinCoordinate) { double[] a = { 0.0, 0.0, 0.0, 0.0 }; double[,] b = { { 0.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0, 0.0 } }; Vector<double> input = vb.DenseOfArray(a); Vector<double> output = vb.DenseOfArray(a); Matrix<double> modelviewproj_matrix = mb.DenseOfArray(b); input[0] = ObjectCoordinate.X; input[1] = ObjectCoordinate.Y; input[2] = ObjectCoordinate.Z; input[3] = 1.0; //output = input * modelviewMatrix;//模型视图变换 //input = output * projectMatrix;//投影变换 //input = input * (modelviewMatrix * projectMatrix);//MVP变换 output = multiVectorAndMatrix(output, input, modelviewMatrix); input = multiVectorAndMatrix(input, output, projectMatrix); //透视除法,进入标准化设备坐标 if (input[3] == 0.0) return null; input[0] /= input[3]; input[1] /= input[3]; input[2] /= input[3]; //将坐标由-1到1,转换到0-1 input[0] = input[0] * 0.5 + 0.5; input[1] = input[1] * 0.5 + 0.5; input[2] = input[2] * 0.5 + 0.5; //将x,y转换到屏幕坐标 input[0] = input[0] * viewport[2] + viewport[0]; input[1] = input[1] * viewport[3] + viewport[1]; WinCoordinate.X = input[0]; WinCoordinate.Y = input[1]; WinCoordinate.Z = input[2]; return WinCoordinate; } /// <summary> /// 将屏幕坐标转换为世界坐标 /// </summary> /// <param name="WinCoordinate"></param> /// <param name="modelviewMatrix"></param> /// <param name="projectMatrix"></param> /// <param name="viewport"></param> /// <param name="ObjectCoordinate"></param> /// <returns></returns> public coordinate Unproject(coordinate WinCoordinate, Matrix<double> modelviewMatrix, Matrix<double> projectMatrix, Vector<double> viewport, coordinate ObjectCoordinate) { double[] a = { 0.0, 0.0, 0.0, 0.0 }; double[,] b = { { 0.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0, 0.0 } }; Matrix<double> finalMatrix = mb.DenseOfArray(b); Matrix<double> modelviewMatrix_invert = mb.DenseOfArray(b); Matrix<double> projectMatrix_invert = mb.DenseOfArray(b); Vector<double> input = vb.DenseOfArray(a); Vector<double> output = vb.DenseOfArray(a); //求逆矩阵 modelviewMatrix_invert = modelviewMatrix.Inverse(); projectMatrix_invert = projectMatrix.Inverse(); //合并MVP矩阵 finalMatrix = modelviewMatrix_invert * projectMatrix_invert; input[0] = WinCoordinate.X; input[1] = viewport[3] - WinCoordinate.Y; input[2] = WinCoordinate.Z; input[3] = 1.0; //从屏幕坐标变换为0到1之间的坐标 input[0] = (input[0] - viewport[0]) / viewport[2]; input[1] = (input[1] - viewport[1]) / viewport[3]; //从0到1之间变换到-1到1之间 input[0] = input[0] * 2 - 1; input[1] = input[1] * 2 - 1; input[2] = input[2] * 2 - 1; //乘以MVP逆矩阵之后得到世界空间的坐标 //output = input * finalMatrix; output = multiVectorAndMatrix(output, input, finalMatrix); //从齐次坐标变换为笛卡尔坐标 if (output[3] == 0.0) return null; output[0] /= output[3]; output[1] /= output[3]; output[2] /= output[3]; //将结果赋值。 ObjectCoordinate.X = output[0]; ObjectCoordinate.Y = output[1]; ObjectCoordinate.Z = output[2]; return ObjectCoordinate; } /// <summary> /// 得到矩阵 /// </summary> /// <returns></returns> public Matrix<double> getMatrix(double[,] Matrix) { return mb.DenseOfArray(Matrix); } /// <summary> /// 得到向量 /// </summary> /// <returns></returns> public Vector<double> getVector(double[] vector) { double[] a = { 0.0, 0.0, 1000.0, 800.0 }; return vb.DenseOfArray(a); } public void funsion4(List<relationshipMainviewCamera> list_relationshipMainviewCamera, Bitmap colordata_mainview_bmp, Bitmap colordata_camera_bmp) { //内存法 System.Drawing.Imaging.BitmapData bmpdata_mainview = null; System.Drawing.Imaging.BitmapData bmpdata_camera = null; try { Rectangle rect_mainview = new Rectangle(0, 0, colordata_mainview_bmp.Width, colordata_mainview_bmp.Height); bmpdata_mainview = colordata_mainview_bmp.LockBits(rect_mainview, System.Drawing.Imaging.ImageLockMode.ReadWrite, colordata_mainview_bmp.PixelFormat); IntPtr ptr_mainview = bmpdata_mainview.Scan0; int bytes_mainview = colordata_mainview_bmp.Width * colordata_mainview_bmp.Height * 3; byte[] rgbvalues_mainview = new byte[bytes_mainview]; System.Runtime.InteropServices.Marshal.Copy(ptr_mainview, rgbvalues_mainview, 0, bytes_mainview); Rectangle rect_camera = new Rectangle(0, 0, colordata_camera_bmp.Width, colordata_camera_bmp.Height); bmpdata_camera = colordata_camera_bmp.LockBits(rect_camera, System.Drawing.Imaging.ImageLockMode.ReadWrite, colordata_camera_bmp.PixelFormat); IntPtr ptr_camera = bmpdata_camera.Scan0; int bytes_camera = colordata_camera_bmp.Width * colordata_camera_bmp.Height * 3; byte[] rgbvalues_camera = new byte[bytes_camera]; System.Runtime.InteropServices.Marshal.Copy(ptr_camera, rgbvalues_camera, 0, bytes_camera); foreach (var relationship in list_relationshipMainviewCamera) { rgbvalues_mainview[relationship.Mainview_y * bmpdata_mainview.Stride + relationship.Mainview_x * 3 + 2] = rgbvalues_camera[relationship.Camera_y * bmpdata_camera.Stride + relationship.Camera_x * 3 + 2]; rgbvalues_mainview[relationship.Mainview_y * bmpdata_mainview.Stride + relationship.Mainview_x * 3 + 1] = rgbvalues_camera[relationship.Camera_y * bmpdata_camera.Stride + relationship.Camera_x * 3 + 1]; rgbvalues_mainview[relationship.Mainview_y * bmpdata_mainview.Stride + relationship.Mainview_x * 3] = rgbvalues_camera[relationship.Camera_y * bmpdata_camera.Stride + relationship.Camera_x * 3]; ////提取像素法 //colordata_mainview_bmp.SetPixel(relationship.Mainview_x, relationship.Mainview_y, colordata_camera_bmp.GetPixel(relationship.Camera_x, relationship.Camera_y)); } System.Runtime.InteropServices.Marshal.Copy(rgbvalues_mainview, 0, ptr_mainview, bytes_mainview); colordata_mainview_bmp.UnlockBits(bmpdata_mainview); //System.Runtime.InteropServices.Marshal.Copy(rgbvalues_camera, 0, ptr_camera, bytes_camera); colordata_camera_bmp.UnlockBits(bmpdata_camera); } catch (System.Exception ex) { //if (bmpdata_mainview != null) // colordata_mainview_bmp.UnlockBits(bmpdata_mainview); //if (bmpdata_camera != null) // colordata_camera_bmp.UnlockBits(bmpdata_camera); } } public List<relationshipMainviewCamera> getRelationship(int WindowWidth, int WindowHeight, List<double> depthdata_mainview, List<double> depthdata_camera, Matrix<double> modelviewMatrix_mainview, Matrix<double> projectMatrix_mainview, Vector<double> viewport_mainview, Matrix<double> modelviewMatrix_camera, Matrix<double> projectMatrix_camera, Vector<double> viewport_cameradepth, Vector<double> viewport_cameracolor) { List<relationshipMainviewCamera> list_relationshipMainviewCamera = new List<relationshipMainviewCamera>(); for (int i = 0; i < WindowWidth * WindowHeight; i++) { //根据一维数组中的位置,转换成主视图屏幕上的X,Y坐标。 coordinate WinCoordinate_mainview = new coordinate(0.0, 0.0, 0.0); int int_iWindowWidth = ((int)(i / WindowWidth)) * WindowWidth; WinCoordinate_mainview.X = i - int_iWindowWidth; WinCoordinate_mainview.Y = (int)(i / WindowWidth); //从存储主视图屏幕深度信息的一维数组中取出对应的深度,即Z坐标。 WinCoordinate_mainview.Z = depthdata_mainview[i]; //从主视图屏幕的XYZ坐标反算到局部坐标 coordinate ObjectCoordinate = new coordinate(0.0, 0.0, 0.0); ObjectCoordinate = Unproject(WinCoordinate_mainview, modelviewMatrix_mainview, projectMatrix_mainview, viewport_mainview, ObjectCoordinate); //再从局部坐标正算到摄像机的深度屏幕坐标,这样就得到了主视图屏幕上一点在摄像机的屏幕坐标和深度。 coordinate WinCoordinate_cameradepth = new coordinate(0.0, 0.0, 0.0); WinCoordinate_cameradepth = Project(ObjectCoordinate, modelviewMatrix_camera, projectMatrix_camera, viewport_cameradepth, WinCoordinate_cameradepth); //对深度屏幕坐标进行取整,因为像素坐标只能是整数 WinCoordinate_cameradepth.X = (int)WinCoordinate_cameradepth.X; WinCoordinate_cameradepth.Y = WindowHeight - (int)WinCoordinate_cameradepth.Y;//因为project得到的Y是OpenGL坐标 if (WinCoordinate_cameradepth.X > 0 && WinCoordinate_cameradepth.X < WindowWidth && WinCoordinate_cameradepth.Y > 0 && WinCoordinate_cameradepth.Y < WindowHeight && WinCoordinate_cameradepth.Z > 0) { //将得到的摄像机深度屏幕坐标XY转换成一维数组中的位置 double depthdata_one_location_camera = WinCoordinate_cameradepth.Y * WindowWidth + WinCoordinate_cameradepth.X; //取出摄像机深度图里面对应像素的深度 double depthdata_one_camera = depthdata_camera[(int)depthdata_one_location_camera]; //从局部坐标正算到摄像机的颜色屏幕坐标,这样就得到了摄像机视频应该映射的屏幕坐标。 coordinate WinCoordinate_cameracolor = new coordinate(0.0, 0.0, 0.0); WinCoordinate_cameracolor = Project(ObjectCoordinate, modelviewMatrix_camera, projectMatrix_camera, viewport_cameracolor, WinCoordinate_cameracolor); //对颜色屏幕坐标进行取整,因为像素坐标只能是整数 WinCoordinate_cameracolor.X = (int)WinCoordinate_cameracolor.X; WinCoordinate_cameracolor.Y = viewport_cameracolor[3] - (int)WinCoordinate_cameracolor.Y;//因为project得到的Y是OpenGL坐标 relationshipMainviewCamera relationship = new relationshipMainviewCamera(); relationship.Mainview_x = (int)WinCoordinate_mainview.X; relationship.Mainview_y = (int)viewport_mainview[3] - (int)WinCoordinate_mainview.Y - 1; relationship.Camera_x = (int)WinCoordinate_cameracolor.X; relationship.Camera_y = (int)viewport_cameracolor[3] - (int)WinCoordinate_cameracolor.Y; list_relationshipMainviewCamera.Add(relationship); } } return list_relationshipMainviewCamera; } } } <file_sep>/FusionCsharp/model/viewmodel/MainView.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using MathNet.Numerics.LinearAlgebra; namespace FusionCsharp.model.viewmodel { /// <summary> /// 主视图模型 /// </summary> public class MainView : View { private Bitmap colordata = null;//主视图背景图 private Vector<double> viewport = null;//视点矩阵 public Bitmap Colordata { get => colordata; set => colordata = value; } public Vector<double> Viewport { get => viewport; set => viewport = value; } } } <file_sep>/FusionCsharp/model/viewmodel/CameraView.cs using AForge.Video.DirectShow; using MathNet.Numerics.LinearAlgebra; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; namespace FusionCsharp.model.viewmodel { /// <summary> /// 摄像机模型 /// </summary> public class CameraView : View { private int id = -1;//摄像机ID号 private Bitmap colordata = null;//每一帧的图像 private FileVideoSource fileSource = null;//视频数据 private List<relationshipMainviewCamera> list_relationshipMainviewCamera = new List<relationshipMainviewCamera>();//存储主视图与摄像头像素对应关系 private bool isActive = true;//是否激活 private Vector<double> viewport_colordata = null;//视频帧的viewport private Vector<double> viewport_depthdata = null;//深度图的viewport public int Id { get => id; set => id = value; } public FileVideoSource FileSource { get => fileSource; set => fileSource = value; } public List<relationshipMainviewCamera> List_relationshipMainviewCamera { get => list_relationshipMainviewCamera; set => list_relationshipMainviewCamera = value; } public bool IsActive { get => isActive; set => isActive = value; } public Vector<double> Viewport_colordata { get => viewport_colordata; set => viewport_colordata = value; } public Vector<double> Viewport_depthdata { get => viewport_depthdata; set => viewport_depthdata = value; } public Bitmap Colordata { get => colordata; set => colordata = value; } public CameraView(int id) { Id = id; } } }
7840c9072b59bf73725a6ae965cf10473ebc197a
[ "C#" ]
8
C#
nickflya/FusionCsharp
ddc63c1dfbee936bf32f49de4b3f6d87443d185e
f22c1c3c45adba051098064ac8fd6d3b5e75a175
refs/heads/master
<file_sep>var appKey = "ed5e5b4ee0b53cf1438bdaf6f7e05c0a504939cfe356095614f2562565a94b60"; var clientKey = "<KEY>"; var ncmb = new NCMB(appKey, clientKey); ///// Called when app launch ons.ready(function(){ $(function() { $("#LoginBtn").click(onLoginBtn); $("#RegisterBtn").click(onRegisterBtn); $("#posting").click(onPosting); $("#c_posting").click(onC_posting); $("#evaluationBtn").click(onEvaluation); $("#c_evaluationBtn").click(onC_evaluation); //$("#c_novelList").html(onC_novelList); $("#YesBtn_logout").click(onLogoutBtn); $("#password_change").click(onPasswordChange); $("#go_search").click(onSearch); $("#no_search").click(onNosearch); $("#newLine").click(onNewline); $("#c_newLine").click(onC_newline); $("#bookmark").click(onBookmark); //親作品投稿ボタン $('#title,#novel').bind('keydown keyup keypress change', function() { if ($('#title').val().length > 0 && $('#novel').val().length > 0) { $('#posting').removeAttr('disabled'); } else { $('#posting').attr('disabled', 'disabled'); } }); //子作品投稿ボタン $('#c_title,#c_novel').bind('keydown keyup keypress change', function() { if ($('#c_title').val().length > 0 && $('#c_novel').val().length > 0) { $('#c_posting').removeAttr('disabled'); } else { $('#c_posting').attr('disabled', 'disabled'); } }); }); }); //----------------------------------USER MANAGEMENT-------------------------------------// var currentLoginUser; //現在ログイン中ユーザー //登録ボタン function onRegisterBtn() { //入力フォームからusername, password変数にセット var username = $("#reg_username").val(); var handlename = $("#reg_handlename").val(); var password = $("#reg_password").val(); var mail = $("#reg_mail").val(); var user = new ncmb.User(); user.set("userName", username) .set("handlename", handlename) .set("password", <PASSWORD>) .set("mailAddress", mail); // 任意フィールドに値を追加 user.signUpByAccount() .then(function(user) { alert("登録しました"); currentLoginUser = ncmb.User.getCurrentUser(); location.href="index.html"; }) .catch(function(error) { alert("新規登録に失敗!次のエラー発生:" + error); }); } //ログインボタン function onLoginBtn() { var username = $("#login_username").val(); var password = $("#login_password").val(); // ユーザー名とパスワードでログイン ncmb.User.login(username, password) .then(function(user) { currentLoginUser = ncmb.User.getCurrentUser(); location.href="home.html"; }) .catch(function(error) { alert("ログイン失敗!次のエラー発生: " + error); }); } //ログアウト function onLogoutBtn() { myRet = confirm("ログアウトしますがよろしいですか?"); if(myRet==true){ ncmb.User.logout(); alert('ログアウトしました'); currentLoginUser = null; location.href="index.html"; } } //パスワード変更 function onPasswordChange() { myRet = confirm("パスワードを変更しますか?\n登録されているアドレスにメールが送信されます"); if(myRet==true){ var user = new ncmb.User(); var mail = ncmb.User.getCurrentUser().mailAddress; user.set("mailAddress", mail); user.requestPasswordReset() .then(function(data){ alert('メールを送信しました。'); }) .catch(function(err){ // エラー処理 }); } } //入力・チェックが入ると登録可能 $(function() { //ボタン無効 $('#RegisterBtn').attr('disabled', 'disabled'); //投稿関連 $('#posting').attr('disabled', 'disabled'); $('#c_posting').attr('disabled', 'disabled'); //ID,PASS,メール入力 $('#reg_username,#reg_handlename,#reg_password,#reg_mail').bind('keydown keyup keypress change', function() { if ($('#reg_username').val().length > 0 && $('#reg_handlename').val().length > 0 && $('#reg_password').val().length > 0 && $('#reg_mail').val().length > 0) { $('#RegisterBtn').removeAttr('disabled'); } else { $('#RegisterBtn').attr('disabled', 'disabled'); } }); }); //----------------------------------DATA STORE-------------------------------------// //親作品投稿 function onPosting() { var Taichel = ncmb.DataStore("Taichel"); var taichel = new Taichel(); var novel = $("#novel").val(); var contributor = ncmb.User.getCurrentUser().handlename; var noveltitle = $("#title").val(); taichel.set("novel", novel) .set("Contributor", contributor) .set("noveltitle", noveltitle) .save() .then(function(novels){ alert("投稿しました。"); $('textarea').val(""); $('input[type="text"]').val(""); location.href="home.html"; }) .catch(function(err){ alert("失敗しました" + error); }); }; //親作品タイトル表示 $(function(){ var Taichel = ncmb.DataStore("Taichel"); Taichel.order("createDate",true) .limit(3) .fetchAll() .then(function(results){ for (var i = 0; i < results.length; i++) { var object = results[i]; var title = object.noveltitle; var cont = object.Contributor; var novel = object.novel; var id = object.objectId; document.getElementById("novelList").innerHTML+="<a href='novels.html?"+novel+'&'+title+'&'+id+"'>"+title+"</a>"+"<br>"; } }) .catch(function(err){ console.log("読み込めませんでした\n"+err); }); }); function onSearch(){ var Taichel = ncmb.DataStore("Taichel"); var searchword = $("#search_form").val(); document.getElementById("novelList").innerHTML=""; Taichel.regularExpressionTo("noveltitle",searchword)   .order("createDate",true) .fetchAll() .then(function(results){ for (var i = 0; i < results.length; i++) { var object = results[i]; var title = object.noveltitle; var cont = object.Contributor; var novel = object.novel; var id = object.objectId; document.getElementById("novelList").innerHTML+="<a href='novels.html?"+novel+'&'+title+'&'+id+"'>"+title+"</a>"+"<br>"; } }) .catch(function(err){ console.log("読み込めませんでした\n"+err); }); }; function onNosearch(){ document.getElementById("novelList").innerHTML=""; var Taichel = ncmb.DataStore("Taichel"); $('input[type="text"]').val(""); Taichel.order("createDate",true) .limit(3) .fetchAll() .then(function(results){ for (var i = 0; i < results.length; i++) { var object = results[i]; var title = object.noveltitle; var cont = object.Contributor; var novel = object.novel; var id = object.objectId; //$("#novelList").html(object.get("noveltitle")); document.getElementById("novelList").innerHTML+="<a href='novels.html?"+novel+'&'+title+'&'+id+"'>"+title+"</a>"+"<br>"; } }) .catch(function(err){ console.log("読み込めませんでした\n"+err); }); }; //親作品評価順表示 $(function(){ var Taichel = ncmb.DataStore("Taichel"); var Taichel_jr = ncmb.DataStore("Taichel_jr"); Taichel.order("createDate",true) .limit(3) .fetchAll() .then(function(results){ for (var i = 0; i < results.length; i++) { var object = results[i]; var title = object.noveltitle; var cont = object.Contributor; var novel = object.novel; var id = object.objectId; document.getElementById("e_novelList").innerHTML+="<a href='novels.html?"+novel+'&'+title+'&'+id+"'>"+title+"</a>"+"<br>"; } }) .catch(function(err){ console.log("読み込めませんでした\n"+err); }); }); //親作品内容表示 function init() { var Taichel = ncmb.DataStore("Taichel"); var taichel = new Taichel(); var url = location.search.split("?")[1]; // 行A var para = url.split("&"); // 行B var n = para.length; for (var i=0; i<n; i++) { para[i] = decodeURIComponent(para[i]); // 行C } var novel = para[0]; var title = para[1]; var id = para[2]; var A_id = para[2]; document.getElementById('novelcontent').innerHTML = novel; document.getElementById('noveltitle').innerHTML = title; function onC_link(){ location.href="c_novelList.html?"+id+'&'+A_id+""; }; $("#c_link").click(onC_link); //以下評価関連 var Evaluation = ncmb.DataStore("Evaluation"); //var user = ncmb.User.getCurrentUser().userName; //評価表示 Evaluation.equalTo("novelId", id) .count() .fetchAll() .then(function(results){ var eval_count = results.count; document.getElementById('evaluation').innerHTML = eval_count; }) .catch(function(err){ console.log("読み込めませんでした\n"+err); }); //ボタン無効 // Evaluation.equalTo("novelId", id) // .equalTo("userName", user) // .count() // .fetchAll() // .then(function(results){ // var counter = results.count; // if(counter < 1) { // $('#evaluationBtn').removeAttr('disabled'); // } else { // $('#evaluationBtn').attr('disabled', 'disabled'); // } // }); }; //親作品評価 function onEvaluation(){ var Taichel = ncmb.DataStore("Taichel"); var taichel = new Taichel(); var Evaluation = ncmb.DataStore("Evaluation"); var evaluation = new Evaluation(); var url = location.search.split("?")[1]; // 行A var para = url.split("&"); // 行B var n = para.length; for (var i=0; i<n; i++) { para[i] = decodeURIComponent(para[i]); // 行C } var id = para[2]; var user = ncmb.User.getCurrentUser().userName; var eval_count; Evaluation.equalTo("userName", user) .equalTo("novelId", id) .count() .fetchAll() .then(function(results){ eval_count = results.count; if (eval_count >= 1){ for (var i = 0; i < results.length; i++) { var object = results[i]; object.delete(); alert("評価を削除しました。"); Evaluation.equalTo("novelId", id) .count() .fetchAll() .then(function(results){ var eval_counter = results.count; Taichel.equalTo("objectId", id) .fetchAll() .then(function(results){ for (var i = 0; i < results.length; i++) { var object = results[i]; object.set("evaluation", eval_counter); return object.update(); } }); document.getElementById('evaluation').innerHTML = eval_counter; }); } }else if (eval_count === 0){ evaluation.set("novelId", id) .set("userName", user) .set("A_parentId",A_id) .save() .then(function(){ alert("評価しました。"); Evaluation.equalTo("novelId", id) .count() .fetchAll() .then(function(results){ var eval_counter = results.count; Taichel.equalTo("objectId", id) .fetchAll() .then(function(results){ for (var i = 0; i < results.length; i++) { var object = results[i]; object.set("evaluation", eval_counter); return object.update(); } }); document.getElementById('evaluation').innerHTML = eval_counter; }); }); } }) .catch(function(err){ // エラー処理 }); }; //ブックマーク登録 function onBookmark(){ var Bookmark = ncmb.DataStore("Bookmark"); var bookmark = new Bookmark(); var url = location.search.split("?")[1]; // 行A var para = url.split("&"); // 行B var n = para.length; for (var i=0; i<n; i++) { para[i] = decodeURIComponent(para[i]); // 行C } var novel = para[0]; var title = para[1]; var id = para[2]; var user = ncmb.User.getCurrentUser().userName; var bm_count; Bookmark.equalTo("userName", user) .equalTo("novelId", id) .count() .fetchAll() .then(function(results){ bm_count = results.count; if (bm_count >= 1){ for (var i = 0; i < results.length; i++) { var object = results[i]; object.delete(); alert("ブックマークを削除しました。"); } }else if (bm_count === 0){ bookmark.set("novelId", id) .set("userName", user) .set("novel", novel) .set("noveltitle",title) .save() .then(function(){ alert("ブックマークしました。"); }) .catch(function(err){ alert("ブックマークできませんでした。" + error); }); } }) .catch(function(err){ // エラー処理 }); }; //子作品タイトル表示 function init2() { var url = location.search.split("?")[1]; // 行A var para = url.split("&"); // 行B var n = para.length; for (var i=0; i<n; i++) { para[i] = decodeURIComponent(para[i]); // 行C } var id = para[0]; var A_id = para[1]; var Taichel_jr = ncmb.DataStore("Taichel_jr"); Taichel_jr.equalTo("parentId", id) .order("createDate",true) .fetchAll() .then(function(results){ for (var i = 0; i < results.length; i++) { var object = results[i]; var title = object.noveltitle; var cont = object.Contributor; var novel = object.novel; var id = object.objectId; document.getElementById("c_novelList").innerHTML+="<a href='c_novels.html?"+novel+'&'+title+'&'+id+'&'+A_id+"'>"+title+"</a>"+"<br>"; } }) .catch(function(err){ console.log("読み込めませんでした\n"+err); }); function onC_pos(){ location.href="c_posting.html?"+id+'&'+A_id+""; }; $("#c_pos").click(onC_pos); }; //子作品内容表示 function init3() { var url = location.search.split("?")[1]; // 行A var para = url.split("&"); // 行B var n = para.length; for (var i=0; i<n; i++) { para[i] = decodeURIComponent(para[i]); // 行C } var novel = para[0]; var title = para[1]; var id = para[2]; var A_id = para[3]; document.getElementById('c_novelcontent').innerHTML = novel; document.getElementById('c_noveltitle').innerHTML = title; function onC_link(){ location.href="c_novelList.html?"+id+'&'+A_id+""; }; $("#c_link").click(onC_link); var Evaluation = ncmb.DataStore("Evaluation"); //評価表示 Evaluation.equalTo("novelId", id) .count() .fetchAll() .then(function(results){ var eval_count = results.count; document.getElementById('c_evaluation').innerHTML = eval_count; }) .catch(function(err){ console.log("読み込めませんでした\n"+err); }); }; //子作品評価 function onC_evaluation(){ var Taichel_jr = ncmb.DataStore("Taichel_jr"); var taichel_jr = new Taichel_jr(); var Evaluation = ncmb.DataStore("Evaluation"); var evaluation = new Evaluation(); var url = location.search.split("?")[1]; // 行A var para = url.split("&"); // 行B var n = para.length; for (var i=0; i<n; i++) { para[i] = decodeURIComponent(para[i]); // 行C } var id = para[2]; var A_id = para[3]; var user = ncmb.User.getCurrentUser().userName; var eval_count; Evaluation.equalTo("userName", user) .equalTo("novelId", id) .count() .fetchAll() .then(function(results){ eval_count = results.count; if (eval_count >= 1){ for (var i = 0; i < results.length; i++) { var object = results[i]; object.delete(); alert("評価を削除しました。"); Evaluation.equalTo("novelId", id) .count() .fetchAll() .then(function(results){ var eval_counter = results.count; Taichel_jr.equalTo("objectId", id) .fetchAll() .then(function(results){ for (var i = 0; i < results.length; i++) { var object = results[i]; object.set("evaluation", eval_counter); return object.update(); } }); document.getElementById('c_evaluation').innerHTML = eval_counter; }); } }else if (eval_count === 0){ evaluation.set("novelId", id) .set("userName", user) .set("A_parentId",A_id) .save() .then(function(){ alert("評価しました。"); Evaluation.equalTo("novelId", id) .count() .fetchAll() .then(function(results){ var eval_counter = results.count; Taichel_jr.equalTo("objectId", id) .fetchAll() .then(function(results){ for (var i = 0; i < results.length; i++) { var object = results[i]; object.set("evaluation", eval_counter); return object.update(); } }); document.getElementById('c_evaluation').innerHTML = eval_counter; }); }); } }) .catch(function(err){ // エラー処理 }); }; //子作品投稿 function onC_posting(){ var url = location.search.split("?")[1]; // 行A var para = url.split("&"); // 行B var n = para.length; for (var i=0; i<n; i++) { para[i] = decodeURIComponent(para[i]); // 行C } var id = para[0]; var A_id = para[1]; var Taichel_jr = ncmb.DataStore("Taichel_jr"); var taichel_jr = new Taichel_jr(); var c_novel = $("#c_novel").val(); var c_contributor = ncmb.User.getCurrentUser().handlename; var c_noveltitle = $("#c_title").val(); taichel_jr.set("novel", c_novel) .set("Contributor", c_contributor) .set("noveltitle", c_noveltitle) .set("parentId", id) .set("A_parentId", A_id) .save() .then(function(){ alert("投稿しました。"); // $('textarea').val(""); // $('input[type="text"]').val(""); location.href="home.html"; }) .catch(function(err){ alert("失敗しました" + error); }); }; //親作品改行 function onNewline() { //挿入する文字列 var strInsert = "<br>"; //現在のテキストエリアの文字列 var strOriginal = document.getElementById('novel').value; //現在のカーソル位置 var posCursole = document.getElementById('novel').selectionStart; //カーソル位置より左の文字列 var leftPart = strOriginal.substr(0, posCursole); //カーソル位置より右の文字列 var rightPart = strOriginal.substr(posCursole, strOriginal.length); //文字列を結合して、テキストエリアに出力 document.getElementById('novel').value = leftPart + strInsert + rightPart; } //子作品改行 function onC_newline() { //挿入する文字列 var strInsert = "<br>"; //現在のテキストエリアの文字列 var strOriginal = document.getElementById('c_novel').value; //現在のカーソル位置 var posCursole = document.getElementById('c_novel').selectionStart; //カーソル位置より左の文字列 var leftPart = strOriginal.substr(0, posCursole); //カーソル位置より右の文字列 var rightPart = strOriginal.substr(posCursole, strOriginal.length); //文字列を結合して、テキストエリアに出力 document.getElementById('c_novel').value = leftPart + strInsert + rightPart; } //評価 // function onEvaluation(){ // var Taichel = ncmb.DataStore("Taichel"); // var taichel = new Taichel(); // // var Evaluation = ncmb.DataStore("Evaluation"); // var evaluation = new Evaluation(); // // var url = location.search.split("?")[1]; // 行A // var para = url.split("&"); // 行B // var n = para.length; // for (var i=0; i<n; i++) { // para[i] = decodeURIComponent(para[i]); // 行C // } // // var novel = para[0]; // var title = para[1]; // var id = para[2]; // // var user = ncmb.User.getCurrentUser().userName; // // evaluation.set("novelId", id) // .set("userName", user) // .save() // .then(function(){ // alert("評価しました。"); // }) // .catch(function(err){ // alert("失敗しました" + error); // }); // // Taichel.equalTo("objectId", id) // .fetchAll() // .then(function(results){ // taichel.set("evaluation", eval_count); // taichel.save(); // return taichel.update(); // }); // // } //現在不要 //function onReration(){ //var Taichel_jr = ncmb.DataStore("Taichel_jr"); //var Taichel_jr1 = new Taichel_jr({name: "orange", type: "fruit"}); //var Taichel_jr2 = new Taichel_jr({name: "apple", type: "fruit"}); // // リレーションを作成してオブジェクトを追加 //var relation = new ncmb.Relation(); //relation.add(Taichel_jr1).add(Taichel_jr1); // //var Taichel = ncmb.DataStore("Taichel"); //var taichel = new Taichel(); // //// リレーションをプロパティに追加 //Taichel.equalTo("objectId", "a64kjj3DOUN4i7th") // .fetchAll() // .then(function(results){ // for (var i = 0; i < results.length; i++) { // var object = results[i]; // object.set("Relation", relation); // //object.save(); // return object.update(); // }; // }); // //}; // 保存(リレーションに追加されたオブジェクトも同時に保存されます) //入れるならinit2() //リレーション化 // var relation = new ncmb.Relation(); // relation.add(c_novels); // // var Taichel = ncmb.DataStore("Taichel"); // var taichel = new Taichel(); // // // リレーションをプロパティに追加 // Taichel.equalTo("objectId", para) // .fetchAll() // .then(function(results){ // for (var i = 0; i < results.length; i++) { // var object = results[i]; // object.set("Relation", relation); // //object.save(); // return object.update(); // }; // });
302da238b78293d125d28683f8e13e49e8a32724
[ "JavaScript" ]
1
JavaScript
tsuchiyaproject2016/treeco
a2e06532ce9c20dc11ccdd50d5ebcbe65106e166
71b980c9083503b45e9c00e126802ba05f2b2cc1
refs/heads/master
<file_sep>// Material/Shader Inspector for Unity 2017/2018 // Copyright (C) 2019 Thryrallo using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using UnityEditor; using UnityEngine; namespace Thry { public class Settings : EditorWindow { //this is dope: this.ShowNotification(new GUIContent(s)); // Add menu named "My Window" to the Window menu [MenuItem("Thry/Settings")] static void Init() { // Get existing open window or if none, make a new one: Settings window = (Settings)EditorWindow.GetWindow(typeof(Settings)); window.Show(); } public static void firstTimePopup() { Settings window = (Settings)EditorWindow.GetWindow(typeof(Settings)); window.isFirstPopop = true; window.is_data_share_expanded = true; window.Show(); } public static void updatedPopup(int compare) { Settings window = (Settings)EditorWindow.GetWindow(typeof(Settings)); if(Config.Get().share_user_data) Helper.SendAnalytics(); window.updatedVersion = compare; window.Show(); } public new void Show() { base.Show(); } public const string RSP_DRAWING_DLL_CODE = "-r:System.Drawing.dll"; public static Shader activeShader = null; public static Material activeShaderMaterial = null; public static PresetHandler presetHandler = null; public ModuleSettings[] moduleSettings; private bool isFirstPopop = false; private int updatedVersion = 0; private bool is_init = false; public static bool is_changing_vrc_sdk = false; public static ButtonData thry_message = null; private static string[][] SETTINGS_CONTENT = new string[][] { new string[]{ "Big Texture Fields", "Show big texure fields instead of small ones" }, new string[]{ "Use Render Queue", "enable a render queue selector" }, new string[]{ "Show popup on shader import", "This popup gives you the option to try to restore materials if they broke on importing" }, new string[]{ "Render Queue Shaders", "Have the render queue selector work with vrchat by creating seperate shaders for the different queues" }, new string[]{ "Gradient Save File Names", "configures the way gradient texture files are named. use <material>, <hash> and <prop> to identify the texture." } }; enum SETTINGS_IDX { bigTexFields = 0, render_queue = 1, show_popup_on_import = 2, render_queue_shaders = 3, gradient_file_name = 4 }; //------------------Message Calls------------------------- public void OnDestroy() { if (isFirstPopop && Config.Get().share_user_data) Helper.SendAnalytics(); if (!EditorPrefs.GetBool("thry_has_counted_user", false)) { Helper.DownloadStringASync(URL.COUNT_USER, delegate (string s) { if (s == "true") EditorPrefs.SetBool("thry_has_counted_user", true); }); } string projectPrefix = PlayerSettings.companyName + "." +PlayerSettings.productName; if (!EditorPrefs.GetBool(projectPrefix+"_thry_has_counted_project", false)) { Helper.DownloadStringASync(URL.COUNT_PROJECT, delegate (string s) { if (s == "true") EditorPrefs.SetBool(projectPrefix+"_thry_has_counted_project", true); }); } } //---------------------Stuff checkers and fixers------------------- //checks if slected shaders is using editor private void OnSelectionChange() { string[] selectedAssets = Selection.assetGUIDs; if (selectedAssets.Length == 1) { UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(AssetDatabase.GUIDToAssetPath(selectedAssets[0])); if (obj.GetType() == typeof(Shader)) { Shader shader = (Shader)obj; Material m = new Material(shader); if (m.HasProperty(Shader.PropertyToID(ThryEditor.PROPERTY_NAME_USING_THRY_EDITOR))) { setActiveShader(shader); } } } this.Repaint(); } public void Awake() { InitVariables(); } private void InitVariables() { is_changing_vrc_sdk = (Helper.LoadValueFromFile("delete_vrc_sdk", PATH.AFTER_COMPILE_DATA) == "true") || (Helper.LoadValueFromFile("update_vrc_sdk", PATH.AFTER_COMPILE_DATA) == "true"); CheckAPICompatibility(); //check that Net_2.0 is ApiLevel CheckDrawingDll(); //check that drawing.dll is imported CheckVRCSDK(); List<Type> subclasses = typeof(ModuleSettings).Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(ModuleSettings))).ToList<Type>(); moduleSettings = new ModuleSettings[subclasses.Count]; int i = 0; foreach(Type classtype in subclasses) { moduleSettings[i++] = (ModuleSettings)Activator.CreateInstance(classtype); } is_init = true; if (thry_message == null) Helper.DownloadStringASync(Thry.URL.SETTINGS_MESSAGE_URL, delegate (string s) { thry_message = Parser.ParseToObject<ButtonData>(s); }); } private static void CheckVRCSDK() { if (!Settings.is_changing_vrc_sdk) Helper.SetDefineSymbol(DEFINE_SYMBOLS.VRC_SDK_INSTALLED, VRCInterface.Get().sdk_is_installed); } private static void CheckAPICompatibility() { ApiCompatibilityLevel level = PlayerSettings.GetApiCompatibilityLevel(BuildTargetGroup.Standalone); if (level == ApiCompatibilityLevel.NET_2_0_Subset) PlayerSettings.SetApiCompatibilityLevel(BuildTargetGroup.Standalone, ApiCompatibilityLevel.NET_2_0); Helper.SetDefineSymbol(DEFINE_SYMBOLS.API_NET_TWO, true, true); } private static void CheckDrawingDll() { string rsp_path = null; //change to decision based on .net version string filename = "mcs"; if (Helper.compareVersions("2018", Application.unityVersion) == 1) filename = "csc"; bool rsp_good = false; if (DoesRSPExisit(filename, ref rsp_path)) { if (ISRSPAtCorrectPath(filename,rsp_path)) { if (DoesRSPContainDrawingDLL(rsp_path)) rsp_good = true; else AddDrawingDLLToRSP(rsp_path); }else AssetDatabase.MoveAsset(rsp_path, PATH.RSP_NEEDED_PATH + filename + ".rsp"); }else AddDrawingDLLToRSP(PATH.RSP_NEEDED_PATH + filename + ".rsp"); Helper.SetDefineSymbol(DEFINE_SYMBOLS.IMAGING_EXISTS, rsp_good, true); } private static bool DoesRSPExisit(string rsp_name,ref string rsp_path) { foreach (string id in AssetDatabase.FindAssets(rsp_name)) { string path = AssetDatabase.GUIDToAssetPath(id); if (path.Contains(rsp_name + ".rsp")) { rsp_path = path; return true; } } return false; } private static bool ISRSPAtCorrectPath(string rsp_name, string rsp_path) { return rsp_path.Contains(PATH.RSP_NEEDED_PATH + rsp_name + ".rsp"); } private static bool DoesRSPContainDrawingDLL(string rsp_path) { string rsp_data = Helper.ReadFileIntoString(rsp_path); return (rsp_data.Contains(RSP_DRAWING_DLL_CODE)); } private static void AddDrawingDLLToRSP(string rsp_path) { string rsp_data = Helper.ReadFileIntoString(rsp_path); rsp_data += RSP_DRAWING_DLL_CODE; Helper.WriteStringToFile(rsp_data,rsp_path); } //------------------Helpers---------------------------- public static void setActiveShader(Shader shader) { if (shader != activeShader) { activeShader = shader; presetHandler = new PresetHandler(shader); activeShaderMaterial = new Material(shader); } } public static Settings getInstance() { Settings instance = (Settings)Helper.FindEditorWindow(typeof(Settings)); if (instance == null) instance = ScriptableObject.CreateInstance<Settings>(); return instance; } //------------------Main GUI void OnGUI() { if (!is_init || moduleSettings==null) InitVariables(); GUILayout.Label("ThryEditor v" + Config.Get().verion); GUINotification(); drawLine(); GUIMessage(); GUIVRC(); GUIEditor(); drawLine(); GUIExtras(); drawLine(); GUIShareData(); drawLine(); foreach(ModuleSettings s in moduleSettings) { s.Draw(); drawLine(); } GUIModulesInstalation(); } //--------------------------GUI Helpers----------------------------- private static void drawLine() { Rect rect = EditorGUILayout.GetControlRect(false, 1); rect.height = 1; EditorGUI.DrawRect(rect, new Color(0.5f, 0.5f, 0.5f, 1)); } private void GUINotification() { if (isFirstPopop) GUILayout.Label(" Thry Shader Editor successfully installed. This is the editor settings window.", Styles.Get().greenStyle); else if (updatedVersion == -1) GUILayout.Label(" Thry editor has been updated", Styles.Get().greenStyle); else if (updatedVersion == 1) GUILayout.Label(" Warning: The Version of Thry Editor has declined", Styles.Get().yellowStyle); } private void GUIMessage() { if(thry_message!=null && thry_message.text.Length > 0) { GUIStyle style = new GUIStyle(); style.richText = true; style.margin = new RectOffset(7, 0, 0, 0); style.wordWrap = true; GUILayout.Label(new GUIContent(thry_message.text,thry_message.hover), style); Rect r = GUILayoutUtility.GetLastRect(); if (Event.current.type == EventType.MouseDown && r.Contains(Event.current.mousePosition)) thry_message.action.Perform(); drawLine(); } } private void GUIVRC() { if (VRCInterface.Get().sdk_is_installed) { GUILayout.BeginHorizontal(); GUILayout.Label("VRC Sdk version: " + VRCInterface.Get().installed_sdk_version + (VRCInterface.Get().sdk_is_up_to_date ? " (newest version)" : "")); RemoveVRCSDKButton(); GUILayout.EndHorizontal(); if (!VRCInterface.Get().sdk_is_up_to_date) { GUILayout.Label("Newest VRC SDK version: " + VRCInterface.Get().newest_sdk_version); UpdateVRCSDKButton(); } if (VRCInterface.Get().user_logged_in) { GUILayout.Label("VRChat user: " + EditorPrefs.GetString("sdk#username")); } } else { InstallVRCSDKButton(); } drawLine(); } private void InstallVRCSDKButton() { EditorGUI.BeginDisabledGroup(is_changing_vrc_sdk); if (GUILayout.Button("Install VRC SDK")) { is_changing_vrc_sdk = true; VRCInterface.DownloadAndInstallVRCSDK(); } EditorGUI.EndDisabledGroup(); } private void RemoveVRCSDKButton() { EditorGUI.BeginDisabledGroup(is_changing_vrc_sdk); if (GUILayout.Button("Remove VRC SDK", GUILayout.ExpandWidth(false))) { is_changing_vrc_sdk = true; VRCInterface.Get().RemoveVRCSDK(true); } EditorGUI.EndDisabledGroup(); } private void UpdateVRCSDKButton() { EditorGUI.BeginDisabledGroup(is_changing_vrc_sdk); if (GUILayout.Button("Update VRC SDK")) { is_changing_vrc_sdk = true; VRCInterface.Get().UpdateVRCSDK(); } EditorGUI.EndDisabledGroup(); } bool is_editor_expanded = true; private void GUIEditor() { is_editor_expanded = Foldout("Editor", is_editor_expanded); if (is_editor_expanded) { EditorGUI.indentLevel += 2; Toggle("useBigTextures", SETTINGS_CONTENT[(int)SETTINGS_IDX.bigTexFields]); Toggle("showRenderQueue", SETTINGS_CONTENT[(int)SETTINGS_IDX.render_queue]); if (Config.Get().showRenderQueue) Toggle("renderQueueShaders", SETTINGS_CONTENT[(int)SETTINGS_IDX.render_queue_shaders]); GUIGradients(); EditorGUI.indentLevel -= 2; } } private static void GUIGradients() { GUILayout.BeginHorizontal(GUILayout.ExpandWidth(false)); Text("gradient_name", SETTINGS_CONTENT[(int)SETTINGS_IDX.gradient_file_name], false); string gradient_name = Config.Get().gradient_name; if (gradient_name.Contains("<hash>")) GUILayout.Label("Good naming.", Styles.Get().greenStyle, GUILayout.ExpandWidth(false)); else if (gradient_name.Contains("<material>")) if (gradient_name.Contains("<prop>")) GUILayout.Label("Good naming.", Styles.Get().greenStyle, GUILayout.ExpandWidth(false)); else GUILayout.Label("Consider adding <hash> or <prop>.", Styles.Get().yellowStyle, GUILayout.ExpandWidth(false)); else if (gradient_name.Contains("<prop>")) GUILayout.Label("Consider adding <material>.", Styles.Get().yellowStyle, GUILayout.ExpandWidth(false)); else GUILayout.Label("Add <material> <hash> or <prop> to destingish between gradients.", Styles.Get().redStyle, GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); } bool is_extras_expanded = false; private void GUIExtras() { is_extras_expanded = Foldout("Extras", is_extras_expanded); if (is_extras_expanded) { EditorGUI.indentLevel += 2; Toggle("showImportPopup", SETTINGS_CONTENT[(int)SETTINGS_IDX.show_popup_on_import]); EditorGUI.indentLevel -= 2; } } bool is_data_share_expanded = false; private void GUIShareData() { is_data_share_expanded = Foldout("User Data Collection", is_data_share_expanded); if (is_data_share_expanded) { EditorGUI.indentLevel += 2; Toggle("share_user_data", "Share Anonomyous Data for usage statistics", "", EditorStyles.boldLabel); EditorGUILayout.LabelField("The data is identified by a hash of your macaddress. This is to make sure we don't log any user twice, while still keeping all data anonymous."); if (Config.Get().share_user_data) { Toggle("share_installed_unity_version", "Share my installed Unity Version", ""); Toggle("share_installed_editor_version", "Share my installed Thry Editor Version", ""); Toggle("share_used_shaders", "Share the names of installed shaders using thry editor", ""); GUILayout.BeginHorizontal(); GUILayout.Space(EditorGUI.indentLevel * 15); if (GUILayout.Button("Show all data collected about me", GUILayout.ExpandWidth(false))) { Helper.DownloadStringASync(URL.DATA_SHARE_GET_MY_DATA+"?hash="+Helper.GetMacAddress().GetHashCode(), delegate(string s){ TextPopup popup = ScriptableObject.CreateInstance<TextPopup>(); popup.position = new Rect(Screen.width / 2, Screen.height / 2, 512, 480); popup.titleContent = new GUIContent("Your Data"); popup.text = s; popup.ShowUtility(); }); } GUILayout.EndHorizontal(); } EditorGUI.indentLevel -= 2; } } private class TextPopup : EditorWindow { public string text = ""; private Vector2 scroll; void OnGUI() { EditorGUILayout.SelectableLabel("This is all data collected on your hashed mac address: ", EditorStyles.boldLabel); Rect last = GUILayoutUtility.GetLastRect(); Rect data_rect = new Rect(0, last.height, Screen.width, Screen.height - last.height); scroll = EditorGUILayout.BeginScrollView(scroll, GUILayout.Width(data_rect.width), GUILayout.Height(data_rect.height)); GUILayout.TextArea(text); EditorGUILayout.EndScrollView(); } } private void GUIModulesInstalation() { if (ModuleHandler.GetModules() == null) return; if (ModuleHandler.GetModules().Count > 0) GUILayout.Label("Extra Modules", EditorStyles.boldLabel); bool disabled = false; foreach (ModuleHeader module in ModuleHandler.GetModules()) if (module.is_being_installed_or_removed) disabled = true; EditorGUI.BeginDisabledGroup(disabled); foreach (ModuleHeader module in ModuleHandler.GetModules()) { EditorGUILayout.BeginHorizontal(); EditorGUI.BeginDisabledGroup(!module.available_requirement_fullfilled); EditorGUI.BeginChangeCheck(); bool is_installed = Helper.ClassExists(module.available_module.classname); bool update_available = is_installed; if (module.installed_module != null) update_available = Helper.compareVersions(module.installed_module.version, module.available_module.version) == 1; string displayName = module.available_module.name; if (module.installed_module != null) displayName += " v" + module.installed_module.version; bool install = GUILayout.Toggle(is_installed, new GUIContent(displayName, module.available_module.description), GUILayout.ExpandWidth(false)); if (EditorGUI.EndChangeCheck()) ModuleHandler.InstallRemoveModule(module,install); if(update_available) if (GUILayout.Button("update to v"+module.available_module.version, GUILayout.ExpandWidth(false))) ModuleHandler.UpdateModule(module); EditorGUI.EndDisabledGroup(); if (module.available_module.requirement != null && (update_available || !is_installed)) { if(module.available_requirement_fullfilled) GUILayout.Label("Requirements: " + module.available_module.requirement.ToString(), Styles.Get().greenStyle); else GUILayout.Label("Requirements: " + module.available_module.requirement.ToString(), Styles.Get().redStyle); } EditorGUILayout.EndHorizontal(); } EditorGUI.EndDisabledGroup(); } private static void Text(string configField, string[] content) { Text(configField, content, true); } private static void Text(string configField, string[] content, bool createHorizontal) { Config config = Config.Get(); System.Reflection.FieldInfo field = typeof(Config).GetField(configField); if (field != null) { string value = (string)field.GetValue(config); if (createHorizontal) GUILayout.BeginHorizontal(GUILayout.ExpandWidth(false)); GUILayout.Space(57); GUILayout.Label(new GUIContent(content[0], content[1]), GUILayout.ExpandWidth(false)); EditorGUI.BeginChangeCheck(); value = EditorGUILayout.DelayedTextField("", value, GUILayout.ExpandWidth(false)); if (EditorGUI.EndChangeCheck()) { field.SetValue(config, value); config.save(); } if (createHorizontal) GUILayout.EndHorizontal(); } } private static void Toggle(string configField, string[] content, GUIStyle label_style = null) { Toggle(configField, content[0], content[1], label_style); } private static void Toggle(string configField, string label, string hover, GUIStyle label_style = null) { Config config = Config.Get(); System.Reflection.FieldInfo field = typeof(Config).GetField(configField); if (field != null) { bool value = (bool)field.GetValue(config); if (Toggle(value, label, hover, label_style) != value) { field.SetValue(config, !value); config.save(); ThryEditor.repaint(); } } } private static bool Toggle(bool val, string text, GUIStyle label_style = null) { return Toggle(val, text, "",label_style); } private static bool Toggle(bool val, string text, string tooltip, GUIStyle label_style=null) { GUILayout.BeginHorizontal(); GUILayout.Space(35); val = GUILayout.Toggle(val, new GUIContent("", tooltip), GUILayout.ExpandWidth(false)); if(label_style==null) GUILayout.Label(new GUIContent(text, tooltip)); else GUILayout.Label(new GUIContent(text, tooltip),label_style); GUILayout.EndHorizontal(); return val; } private static bool Foldout(string text, bool expanded) { return Foldout(new GUIContent(text), expanded); } private static bool Foldout(GUIContent content, bool expanded) { var rect = GUILayoutUtility.GetRect(16f + 20f, 22f, Styles.Get().dropDownHeader); GUI.Box(rect, content, Styles.Get().dropDownHeader); var toggleRect = new Rect(rect.x + 4f, rect.y + 2f, 13f, 13f); Event e = Event.current; if (e.type == EventType.Repaint) EditorStyles.foldout.Draw(toggleRect, false, false, expanded, false); if (e.type == EventType.MouseDown && rect.Contains(e.mousePosition) && !e.alt) { expanded = !expanded; e.Use(); } return expanded; } } }<file_sep>using UnityEngine; public class PlayerTransformer { private GameObject playerModel; private float playerSpeed = 0.01F; public PlayerTransformer(GameObject playerObject) { playerModel = playerObject; } public void Forward(float amount) { playerModel.transform.Translate(Vector3.forward * amount * playerSpeed); } public void Sideways(float amount) { playerModel.transform.Translate(Vector3.right * amount * playerSpeed); } public void RotateHorizontal(float amount) { playerModel.transform.Rotate(Vector3.up * amount); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class InputHandler : MonoBehaviour { private PlayerTransformer playerModel; private CameraTransformer cameraObject; private float mouseHzReact = 3; private float mouseVtReact = 3; public void Start() { Cursor.lockState = CursorLockMode.Locked; playerModel = new PlayerTransformer(GameObject.Find("Player")); cameraObject = new CameraTransformer(GameObject.Find("Player Camera")); } public void Update() { if (Input.GetKey("escape")) { Application.Quit(); UnityEditor.EditorApplication.isPlaying = false; return; } var mouseMovementX = Input.GetAxis("Mouse X") * mouseHzReact; var mouseMovementY = Input.GetAxis("Mouse Y") * mouseVtReact; var keyMovementX = Input.GetAxis("Vertical"); var keyMovementY = Input.GetAxis("Horizontal"); playerModel.RotateHorizontal(mouseMovementX); cameraObject.RotateVertical(mouseMovementY); playerModel.Forward(keyMovementX); playerModel.Sideways(keyMovementY); } } <file_sep>using UnityEngine; public class CameraTransformer { private GameObject camera; private Vector3 cameraOffset; private int maxCameraDepression = 80; private int maxCameraElevation = 280; public CameraTransformer(GameObject cameraObject) { camera = cameraObject; cameraOffset = new Vector3(0, 3, 0); } public void RotateVertical(float amount) { var x = camera.transform.rotation.eulerAngles.x; if (x > 0 && x < 180 && amount < 0 && x - amount > maxCameraDepression) return; if (x > 180 && x < 360 && amount > 0 && x - amount < maxCameraElevation) return; Quaternion q = camera.transform.rotation; q.eulerAngles = new Vector3(q.eulerAngles.x - amount, q.eulerAngles.y, 0); camera.transform.rotation = q; } } <file_sep>// Material/Shader Inspector for Unity 2017/2018 // Copyright (C) 2019 Thryrallo using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; namespace Thry { [InitializeOnLoad] public class OnCompileHandler { static OnCompileHandler() { VRCInterface.OnCompile(); Config.OnCompile(); ModuleHandler.OnCompile(); Helper.TashHandler.EmptyThryTrash(); } } public class AssetChangeHandler : AssetPostprocessor { static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { if (importedAssets.Length > 0) AssetsImported(importedAssets); if (deletedAssets.Length > 0) AssetsDeleted(deletedAssets); if (movedAssets.Length > 0) AssetsMoved(movedAssets, movedFromAssetPaths); } private static void AssetsImported(string[] assets) { VRCInterface.SetVRCDefineSybolIfSDKImported(assets); ShaderHelper.AssetsImported(assets); } private static void AssetsMoved(string[] movedAssets, string[] movedFromAssetPaths) { ShaderHelper.AssetsMoved(movedFromAssetPaths, movedAssets); } private static void AssetsDeleted(string[] assets) { VRCInterface.SetVRCDefineSybolIfSDKDeleted(assets); ShaderHelper.AssetsDeleted(assets); } } }
a8b2fb4731671d32ffcabfe2991ce3bfe1b6067a
[ "C#" ]
5
C#
Dynosaur/transcendence
ef37dab7d693361bbd45523c12160f00cadc2060
f0cc8234f7c857fdb54523e57e1b027c7a960e18
refs/heads/master
<file_sep># Gists A collection of snippets (gists). ## Ontraport Optin The [`ontraport-optin.html`](ontraport-optin.html) snippet must be added to all Unbounce pages that use an Ontraport form to capture leads. - Name: **Ontraport Optin** - Placement: **Head** - Variants: **All** ## Ontraport Conversion The [`ontraport-conversion.html`](ontraport-conversion.html) snippet must be added to all Unbounce "thank you" pages that Ontraport forms redirect to. - Name: **Ontraport Conversion** - Placement: **Head** - Variants: **All** <file_sep>const secretKey = "..." const chargebeeKey = "..." const chargebeeURL = "https://laylamartin-test.chargebee.com/api/v2" const redirectURL = "https://learn.laylamartin.com/account" addEventListener("fetch", (event) => { event.respondWith( handleRequest(event.request).catch( (err) => new Response(err.stack, { status: 500 }) ) ) }) async function handleRequest(request) { const url = new URL(request.url) if (! url.pathname.startsWith("/sso/thinkific-chargebee")) { return new Response("Not Found", { status: 404 }) } if (! url.searchParams.has("email") || ! url.searchParams.has("secret") || ! url.searchParams.has("expiry")) { return new Response("Missing parameter", { status: 400 }) } const email = url.searchParams.get("email") const emailEncoded = encodeURIComponent(email) const expiry = Number(url.searchParams.get("expiry")) const signature = url.searchParams.get("secret") const secretKey = "squad-taps-earphone-sleek" const chargebeeAuth = btoa(`${chargebeeKey}:`) const encoder = new TextEncoder() try { const key = await crypto.subtle.importKey( "raw", encoder.encode(secretKey), { name: "HMAC", hash: "SHA-256" }, false, ["verify"], ) const verified = await crypto.subtle.verify( "HMAC", key, hexStringToUint8Array(signature), encoder.encode(email + expiry), ) if (! verified) { return new Response("Invalid signature", { status: 403 }) } if (Date.now() > (expiry * 1000)) { return new Response("Link expired", { status: 403 }) } const customerResponse = await fetch(`${chargebeeURL}/customers?email[is]=${emailEncoded}`, { headers: { "Authorization": `Basic ${chargebeeAuth}` }, }) if (! customerResponse.ok) { return new Response(`Failed to fetch customer (${customerResponse.status})`, { status: 500 }) } const customers = await customerResponse.json() if (! customers.list) { return new Response(`Error fetching customer (${customerResponse.status})`, { status: 500 }) } if (! customers.list.length) { return new Response(`No customer found with the email: ${email}`, { status: 404 }) } const customerId = customers.list[0].customer.id const sessionResponse = await fetch(`${chargebeeURL}/portal_sessions`, { method: "POST", headers: { "Authorization": `Basic ${chargebeeAuth}` }, body: new URLSearchParams({ "customer[id]": customerId, "redirect_url": redirectURL, }) }) if (! sessionResponse.ok) { return new Response(`Failed to create session for customer: ${customerId}`, { status: 500 }) } const session = await sessionResponse.json() if (! session.portal_session) { return new Response("Error creating session", { status: 500 }) } return Response.redirect( session.portal_session.access_url ) } catch (err) { return new Response(`Something went wrong. ${err.message}`, { status: 500 }) } } function hexStringToUint8Array(hexString) { var arrayBuffer = new Uint8Array(hexString.length / 2) for (var i = 0; i < hexString.length; i += 2) { arrayBuffer[i/2] = parseInt(hexString.substr(i, 2), 16) } return arrayBuffer } <file_sep> ## Unbounce 1. Use Unbounce for landing pages 2. Use "Show a Lightbox" button on UB landing pages 3. Configure & design lightbox (add 5 hidden utm_* fields) 4. Set "Form Confirmation" to "Go to URL" (use UB success page) 5. Set page goal to only "Lightbox" 6. Add Proof JavaScript snippet to lightbox and confirmation page 7. Setup UB Webhook (with OP form ID) ## Proof 1. Create individual goal for UB page 2. Set goal completion URL to UB success page 3. Create individual campaign for UB page 4. Choose created goal 5. Setup variants 6. Step 3: Choose "Auto Lead Capture" and enter _all_ "Lightbox" URLs 7. Step 4: Enter URL of UB landing page ## TODOs - OP referrer name - OP partners/affiliates ### UTM Fields - `utm_source` - `utm_medium` - `utm_term` - `utm_content` - `utm_campaign`
c5d901a2de4637d2ac338253aabc7419c228f0ef
[ "Markdown", "JavaScript" ]
3
Markdown
laylamartin/gists
955d516298a700e081a7a6ea5f4ffe6b175c0711
72d95f0735dba0c3dcc900120e9deab5662e00ee
refs/heads/master
<file_sep># Adoption Site ## Description >A site displaying pets for adoption, click a button to sort by pet type. ## ScreenShots ![alt text](https://raw.githubusercontent.com/BLRussell-09/adoption/master/screenshots/adoption.png "Logo Title Text 1") ## Fire It Up >Serve up the site and load the page. 1. Clone down the repo and cd into the project. 1. Install http-server plugin via vpm 1. Cd into the lib folder and run npm init 1. Cd into the lib folder and run npm install grunt --save -dev 1. Run npm install grunt-browserify grunt-contrib-watch gruntify-eslint --save-dev 1. Run grunt 1. In your terminal type: hs -p 9999 1. In your browser navigate to: localhost:9999<file_sep>const xhr = require('./xhr'); const dom = require('./dom'); const successF = function () { const animals = JSON.parse(this.responseText).pets; dom.domStringBuilder(animals); }; const errorF = function () { console.log('There was a mistake'); }; const initializer = () => { xhr.startApp(successF, errorF); }; const catSuccess = function () { const cats = JSON.parse(this.responseText).pets; dom.domCatBuilder(cats); }; const dogSuccess = function () { const dogs = JSON.parse(this.responseText).pets; dom.domDogBuilder(dogs); }; const dinoSuccess = function () { const dinos = JSON.parse(this.responseText).pets; dom.domDinoBuilder(dinos); }; const catCall = function () { xhr.startApp(catSuccess, errorF); }; const doggoCall = function () { xhr.startApp(dogSuccess, errorF); }; const dinoCall = function () { xhr.startApp(dinoSuccess, errorF); }; module.exports = { initializer, catCall, doggoCall, dinoCall, }; <file_sep>const data = require('./data'); const catButton = document.getElementById('cats'); const dogButton = document.getElementById('dogs'); const dinoButton = document.getElementById('dinos'); const resetButton = document.getElementById('reset'); const showCats = () => { data.catCall(); }; const showDogs = () => { data.doggoCall(); }; const showDinos = () => { data.dinoCall(); }; const resetPage = () => { data.initializer(); }; const buttonEvents = () => { catButton.addEventListener('click', showCats); dogButton.addEventListener('click', showDogs); dinoButton.addEventListener('click', showDinos); resetButton.addEventListener('click', resetPage); }; module.exports = buttonEvents;
c732655e17e41ab072a4b132ec7101f34804e7d5
[ "Markdown", "JavaScript" ]
3
Markdown
BLRussell-09/adoption
3e853a1b83c145f7fc895a9bdb6bc1d5f8402510
aed9c612e3e241d6d8b73c2f709c5125c7fffe50
refs/heads/master
<file_sep><?php error_reporting(0); include_once("db-connection.php"); $db = new DB('root', '', 'records_of_students'); $db1 = $db->query('SELECT schools.school_id, schools.school_name FROM schools'); $school_with_students = array(); $schools = array(); foreach($db1 as $value1) { $db2 = $db->select('SELECT students.student_name, students.student_surname, students.student_grade FROM students INNER JOIN classes ON students.class_id = classes.class_id WHERE classes.school_id = ? ORDER BY student_grade DESC LIMIT 5', array($value1->school_id), array('%d')); $schools["school"] = $value1->school_name; $students = array(); foreach($db2 as $value2) { array_push($students, $value2); } $schools["students"] = $students; array_push($school_with_students,$schools); } ?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Škole - Top pet učenika po prosjeku po svakoj školi.</title> <meta name="description" content="App for student grades"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="third-party/bootstrap-4.1.3/css/bootstrap.min.css"> <link rel="stylesheet" href="third-party/fontawesome-free-5.3.1-web/css/all.css"> <link rel="stylesheet" href="style.css"> </head> <body> <?php include("header.php"); ?> <div id="body"> <section class="page-header bg-secondary text-white mb-5 p-3"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <ul class="breadcrumb bg-light"> <li class="breadcrumb-item"><a href="index.php">Naslovnica</a></li> <li class="breadcrumb-item active">Top pet učenika po prosjeku po svakoj školi.</li> </ul> </div> </div> <div class="row"> <div class="col-md-12"> <h1>Top pet učenika po prosjeku po svakoj školi.</h1> </div> </div> </div> </section> <div id="body-bg"> <div class="container-fluid"> <div class="row"> <?php if ($school_with_students != null) { foreach ($school_with_students as $value) { ?> <div class="col-sm-12"> <h3><?php echo $value['school'] ?> </h3> <div class="table-responsive"> <table class="table table-striped table-sm"> <thead> <tr> <th>R.br.</th> <th>Učenik</th> <th>Prosječna ocjena</th> </tr> </thead> <tbody> <?php if($value['students']){ $row_number = 0; foreach ($value['students'] as $value2) { $row_number++; ?> <tr> <td><?php echo $row_number; ?></td> <td><?php echo $value2->student_name. " " . $value2->student_surname; ?></td> <td><?php echo $value2->student_grade; ?></td> </tr> <?php } }else{ echo '<tr"><td colspan="4" class="text-danger">Nema rezultata</td></tr>'; } ?> </tbody> </table> </div> </div> <?php } } ?> </div> </div> </div> </div> <?php include("footer.php"); ?> <script src="third-party/jquery/jquery-3.3.1.min.js"></script> <script src="third-party/bootstrap-4.1.3/js/bootstrap.min.js"></script> <script src="third-party/fontawesome-free-5.3.1-web/js/all.js"></script> </body> </html> <file_sep><?php include_once('db-connection.php'); $current_file_name = basename($_SERVER['PHP_SELF']); $db = new DB('root', '', 'records_of_students'); $db = $db->query('SELECT schools.school_id, schools.school_id, schools.school_name, schools.school_street, schools.school_telephone, schools.school_email, city.city_name FROM schools LEFT JOIN city ON schools.city_id=city.city_id'); ?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Škole</title> <meta name="description" content="App for student grades"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="third-party/bootstrap-4.1.3/css/bootstrap.min.css"> <link rel="stylesheet" href="third-party/fontawesome-free-5.3.1-web/css/all.css"> <link rel="stylesheet" href="style.css"> </head> <body> <?php include("header.php"); ?> <div id="body"> <section class="page-header bg-secondary text-white mb-5 p-3"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <ul class="breadcrumb bg-light"> <li class="breadcrumb-item"><a href="index.php">Naslovnica</a></li> <li class="breadcrumb-item active">Škole</li> </ul> </div> </div> <div class="row"> <div class="col-md-12"> <h1>Škole</h1> </div> </div> </div> </section> <div id="body-bg"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="table-responsive"> <table class="table table-striped table-sm"> <thead> <tr> <th>r.br.</th> <th>Naziv</th> <th>Adresa</th> <th>Telefon</th> <th>E-mail</th> </tr> </thead> <tbody> <?php if (!empty((array) $db)) { $row_number = 0; foreach($db as $value) { $row_number++; ?> <tr> <td><?php echo $row_number; ?>.</td> <td><?php echo $value->school_name; ?></td> <td><?php echo $value->school_street . " " . $value->city_name; ?></td> <td><?php echo $value->school_telephone; ?></td> <td><?php echo $value->school_email; ?></td> <td> <?php echo "<a class='btn btn-primary btn-sm btn-block' href='classes.php?school_id={$value->school_id}'>Vidi razrede</a>"; ?> </td> </tr> <?php } } else { echo '<tr"><td class="text-danger">Nema rezultata</td></tr>'; } ?> </tbody> </table> </div> </div> </div> </div> </div> </div> <?php include("footer.php"); ?> <script src="third-party/jquery/jquery-3.3.1.min.js"></script> <script src="third-party/bootstrap-4.1.3/js/bootstrap.min.js"></script> <script src="third-party/fontawesome-free-5.3.1-web/js/all.js"></script> <script src="app.js"></script> </body> </html> <file_sep><header> <nav class="navbar navbar-expand-lg bg-primary navbar-dark"> <div class="container-fluid"> <a class="navbar-brand mb-0 h1" href="index.php">Ocjene učenika</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" class="<?php if($current_file_name == "index.php"){echo "active";} ?>" href="index.php">Naslovnica <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" class="<?php if($current_file_name == "schools.php" OR $current_file_name == "student-edit.php"){echo "active";} ?>" href="schools.php">Škole</a> </li> <li class="nav-item"> <a class="nav-link" class="<?php if($current_file_name == "classes.php"){echo "active";} ?>" href="classes.php">Razredi</a> </li> <li class="nav-item"> <a class="nav-link" class="<?php if($current_file_name == "students.php"){echo "active";} ?>" href="students.php">Učenici</a> </li> </ul> </div> </div> </nav> </header><file_sep><?php include_once('db-connection.php'); $current_file_name = basename($_SERVER['PHP_SELF']); if (isset($_GET["school_id"]) AND !empty($_GET["school_id"])){ $school_id = $_GET["school_id"]; if(ctype_digit($school_id)){ $db = new DB('root', '', 'records_of_students'); $db = $db->select('SELECT classes.class_id, classes.school_id, classes.class_name, classes.class_mark, teachers.teacher_name, teachers.teacher_surname, schools.school_name FROM classes LEFT JOIN teachers ON classes.teacher_id=teachers.teacher_id LEFT JOIN schools ON classes.school_id=schools.school_id WHERE classes.school_id = ?', array($_GET['school_id']), array('%d')); }else{ header('Location: 404.php'); } }else{ $school_id = ""; $db = new DB('root', '', 'records_of_students'); $db = $db->query('SELECT * FROM classes LEFT JOIN teachers ON classes.teacher_id=teachers.teacher_id LEFT JOIN schools ON classes.school_id=schools.school_id'); } ?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Razredi</title> <meta name="description" content="App for student grades"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="third-party/bootstrap-4.1.3/css/bootstrap.min.css"> <link rel="stylesheet" href="third-party/fontawesome-free-5.3.1-web/css/all.css"> <link rel="stylesheet" href="style.css"> </head> <body> <?php include("header.php"); ?> <div id="body"> <section class="page-header bg-secondary text-white mb-5 p-3"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <ul class="breadcrumb bg-light"> <li class="breadcrumb-item"><a href="index.php">Naslovnica</a></li> <li class="breadcrumb-item"><a href="schools.php">Škole</a></li> <li class="breadcrumb-item active">Razredi<?php if (!empty((array)$db) AND !empty($school_id)) { echo ": " .$db[0]->school_name; } ?></li> </ul> </div> </div> <div class="row"> <div class="col-md-12"> <h1>Razredi<?php if (!empty((array)$db) AND !empty($school_id)) { echo ": " .$db[0]->school_name; } ?></h1> </div> </div> </div> </section> <div id="body-bg"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="table-responsive"> <table class="table table-striped table-sm"> <thead> <tr> <th>r.br.</th> <th>Razred</th> <th>Škola</th> <th>Razrednik</th> <th>Opcije</th> </tr> </thead> <tbody> <?php if (!empty((array) $db)) { $row_number = 0; foreach($db as $value) { $row_number++; ?> <tr> <td><?php echo $row_number; ?>.</td> <td><?php echo $value->class_name . " " . $value->class_mark; ?></td> <td><?php echo $value->school_name; ?></td> <td><?php echo $value->teacher_name . " " . $value->teacher_surname; ?></td> <td> <?php echo "<a class='btn btn-primary btn-sm btn-block' href='students.php?school_id={$value->school_id}&class_id={$value->class_id}'>Vidi učenike</a>"; ?> </td> </tr> <?php } } else { echo '<tr"><td class="text-danger">Nema rezultata</td></tr>'; } ?> </tbody> </table> </div> </div> </div> </div> </div> </div> <?php include("footer.php"); ?> <script src="third-party/jquery/jquery-3.3.1.min.js"></script> <script src="third-party/bootstrap-4.1.3/js/bootstrap.min.js"></script> <script src="third-party/fontawesome-free-5.3.1-web/js/all.js"></script> <script src="app.js"></script> </body> </html> <file_sep><?php include_once("db-connection.php"); $current_file_name = basename($_SERVER['PHP_SELF']); if (isset($_GET["school_id"]) AND !empty($_GET["school_id"]) AND isset($_GET["class_id"]) AND !empty($_GET["class_id"])){ $school_id = $_GET["school_id"]; $class_id = $_GET["class_id"]; if(!ctype_digit($school_id) OR !ctype_digit($class_id)){ header('Location: 404.php'); }else{ $db = new DB('root', '', 'records_of_students'); $db = $db->select('SELECT students.student_id, students.student_image, students.student_name, students.student_surname, students.student_oib, students.student_street, students.student_grade, students.student_status, city.city_name, classes.class_name, classes.class_mark, schools.school_name FROM students LEFT JOIN city ON students.city_id=city.city_id LEFT JOIN classes ON students.class_id=classes.class_id LEFT JOIN schools ON classes.school_id=schools.school_id WHERE students.class_id = ?', array($class_id), array('%d')); } } else{ $class_id = ""; $db = new DB('root', '', 'records_of_students'); $db = $db->query('SELECT students.student_id, students.student_image, students.student_name, students.student_surname, students.student_oib, students.student_street, students.student_grade, students.student_status, city.city_name FROM students LEFT JOIN city ON students.city_id=city.city_id'); } if(isset($_GET["student_delete"]) AND !empty($_GET["student_delete"])){ $student_delete = $_GET["student_delete"]; $sql = "DELETE FROM records_of_students.students WHERE students.student_id = " . $student_delete; doQuery($conn,$sql); } ?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Učenici</title> <meta name="description" content="App for student grades"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="third-party/bootstrap-4.1.3/css/bootstrap.min.css"> <link rel="stylesheet" href="third-party/fontawesome-free-5.3.1-web/css/all.css"> <link rel="stylesheet" href="style.css"> </head> <body> <?php include("header.php"); ?> <div id="body"> <section class="page-header bg-secondary text-white mb-5 p-3"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <ul class="breadcrumb bg-light"> <li class="breadcrumb-item"><a href="index.php">Naslovnica</a></li> <li class="breadcrumb-item"><a href="schools.php">Škole</a></li> <li class="breadcrumb-item active">Učenici <?php if (!empty((array)$db) AND !empty($class_id)) { echo ": " .$db[0]->class_name . "" . $db[0]->class_mark; } if (!empty((array)$db) AND !empty($school_id)) { echo " / " .$db[0]->school_name; } ?> </li> </ul> </div> </div> <div class="row"> <div class="col-md-12"> <h1>Učenici <?php if (!empty((array) $db) AND !empty($class_id)) { echo ": " .$db[0]->class_name . "" . $db[0]->class_mark; } if (!empty((array) $db) AND !empty($school_id)) { echo " / " .$db[0]->school_name; } ?> </h1> </div> </div> </div> </section> <div id="body-bg"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="table-responsive"> <table class="table table-striped table-sm"> <thead> <tr> <th>r.br.</th> <th>Slika</th> <th>Ime</th> <th>Prezime</th> <th>OIB</th> <th>Adresa</th> <th>Prosječna ocjena</th> <th>Status</th> <th>Opcije</th> </tr> </thead> <tbody> <?php if (!empty((array) $db)) { $row_number = 0; foreach($db as $value) { $row_number++; ?> <tr> <td><?php echo $row_number; ?>.</td> <td><img src="<?php if(!empty($value->student_image)){echo $value->student_image; }else{ echo "img/user.png"; } ?>" class="student-photo" /></td> <td><?php echo $value->student_name; ?></td> <td><?php echo $value->student_surname; ?></td> <td><?php echo $value->student_oib; ?></td> <td><?php echo $value->student_street . ", " . $value->city_name; ?></td> <td><?php echo $value->student_grade; ?></td> <td> <?php if ($value->student_status == 1){ echo "Aktivan"; }elseif($value->student_status == 0){ echo "Neaktivan"; } ?> </td> <td> <?php echo "<a class='btn btn-primary btn-sm btn-block' href='student-edit.php?student_id={$value->student_id}'>Uredi</a>"; ?> <a class="btn btn-danger btn-sm btn-block" onclick="return confirm('Jeste li sigurni da želite obrisati učenika?');" href="students.php?student_delete=<?php echo $value->student_id;?>">Obriši učenika</a> </td> </tr> <?php } } else { echo '<tr"><td class="text-danger">Nema rezultata</td></tr>'; } ?> </tbody> </table> </div> </div> </div> </div> </div> </div> <?php include("footer.php"); ?> <script src="third-party/jquery/jquery-3.3.1.min.js"></script> <script src="third-party/bootstrap-4.1.3/js/bootstrap.min.js"></script> <script src="third-party/fontawesome-free-5.3.1-web/js/all.js"></script> <script src="app.js"></script> </body> </html> <file_sep><?php error_reporting(0); include_once("db-connection.php"); $db = new DB('root', '', 'records_of_students'); /*students and average grade by classes*/ $school_with_students1 = array(); $schools1 = array(); $db1 = $db->query('SELECT *, count(students.student_id) AS students_count, ROUND(AVG(students.student_grade),2) AS average_grade FROM students RIGHT JOIN classes ON students.class_id=classes.class_id GROUP BY class_name ORDER BY class_name ASC'); foreach($db1 as $value1) { $schools1["class_name"] = $value1->class_name; $schools1["students_count"] = $value1->students_count; $schools1["average_grade"] = $value1->average_grade; array_push($school_with_students1,$schools1); } /*students and average grade by schools and classes*/ $db2 = $db->query('SELECT schools.school_id, schools.school_name FROM schools'); $school_with_students2 = array(); $schools2 = array(); foreach($db2 as $value2) { $db3 = $db->select('SELECT classes.class_name, count(students.student_id) AS students_count, ROUND(AVG(students.student_grade),2) AS average_grade FROM students RIGHT JOIN classes ON students.class_id=classes.class_id WHERE classes.school_id = ? GROUP BY class_name ORDER BY class_name ASC', array($value2->school_id), array('%d')); $schools2["school"] = $value2->school_name; $students2 = array(); foreach($db3 as $value3) { array_push($students2, $value3); } $schools2["students"] = $students2; array_push($school_with_students2,$schools2); } ?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Škole - Broj učenika po razredima i prosječna ocjena po razredu.</title> <meta name="description" content="App for student grades"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="third-party/bootstrap-4.1.3/css/bootstrap.min.css"> <link rel="stylesheet" href="third-party/fontawesome-free-5.3.1-web/css/all.css"> <link rel="stylesheet" href="style.css"> </head> <body> <?php include("header.php"); ?> <div id="body"> <section class="page-header bg-secondary text-white mb-5 p-3"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <ul class="breadcrumb bg-light"> <li class="breadcrumb-item"><a href="index.php">Naslovnica</a></li> <li class="breadcrumb-item active">Broj učenika po razredima i prosječna ocjena po razredu.</li> </ul> </div> </div> <div class="row"> <div class="col-md-12"> <h1>Broj učenika po razredima i prosječna ocjena po razredu.</h1> </div> </div> </div> </section> <div id="body-bg"> <div class="container-fluid"> <div class="row"> <div class="col-sm-12"> <div class="tabs"> <ul class="nav nav-pills mb-5"> <li class="nav-item"> <a href="#classes" data-toggle="pill" class="nav-link active">Ocjene po razredima</a> </li> <li> <a href="#schools" data-toggle="pill" class="nav-link">Ocjene po razredima u školama</a> </li> </ul> <div class="tab-content"> <div id="classes" class="tab-pane active"> <div class="table-responsive"> <table class="table table-striped table-sm"> <thead> <tr> <th>R.br.</th> <th>Razred</th> <th>Broj učenika</th> <th>Prosječna ocjena</th> </tr> </thead> <tbody> <?php $row_number = 0; foreach ($school_with_students1 as $value) { if(!empty($school_with_students1)){ $row_number++; ?> <tr> <td><?php echo $row_number; ?></td> <td><?php echo $value['class_name']; ?></td> <td> <?php if(!empty($value['students_count'])){ echo $value['students_count']; }else{ echo "-"; } ?> </td> <td> <?php if(!empty($value['average_grade'])){ echo $value['average_grade']; }else{ echo "-"; } ?> </td> </tr> <?php }else{ echo "<tr><td>Nema rezultata</td></tr>"; } } ?> </tbody> </table> </div> </div> <div id="schools" class="tab-pane"> <div class="row"> <?php if ($school_with_students2 != null) { foreach ($school_with_students2 as $value) { ?> <div class="col-sm-12"> <h3><?php echo $value['school'] ?> </h3> <div class="table-responsive"> <table class="table table-striped table-sm"> <thead> <tr> <th>R.br.</th> <th>Razred</th> <th>Broj učenika</th> <th>Prosječna ocjena</th> </tr> </thead> <tbody> <?php if($value['students']){ $row_number = 0; foreach ($value['students'] as $value2) { $row_number++; ?> <tr> <td><?php echo $row_number; ?></td> <td><?php echo $value2->class_name; ?></td> <td> <?php if(!empty($value2->students_count)){ echo $value2->students_count; }else{ echo "-"; } ?> </td> <td> <?php if(!empty($value2->average_grade)){ echo $value2->average_grade; }else{ echo "-"; } ?> </td> </tr> <?php } }else{ echo '<tr"><td colspan="4" class="text-danger">Nema rezultata</td></tr>'; } ?> </tbody> </table> </div> </div> <?php } } ?> </div> </div> </div> </div> </div> </div> </div> </div> </div> <?php include("footer.php"); ?> <script src="third-party/jquery/jquery-3.3.1.min.js"></script> <script src="third-party/bootstrap-4.1.3/js/bootstrap.min.js"></script> <script src="third-party/fontawesome-free-5.3.1-web/js/all.js"></script> </body> </html> <file_sep># records-of-students Start app notes: Download full project to your desktop. Start local server (e.g. xampp). In phpMyAdmin import sql script db/records_of_students_create.sql to create database and tables. In phpMyAdmin import sql script db/resords_of_students_insert_data.sql to insert data in database. Run app in browser as localhost. Server side specification: XAMPP v3.2.2 Apache server 2.4.29 PHP 7.0.27 MySQL 5.0.12 <file_sep>SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; USE `records_of_students`; /* Insert data into table `city` */ INSERT INTO `city` (`city_id`, `city_name`, `zip`) VALUES (1, 'Zagreb', '10000'), (2, 'Varaždin', '42000'), (3, 'Sisak', '10100'); /* Insert data into table `schools` */ INSERT INTO `schools` (`school_id`, `school_name`, `school_street`, `city_id`, `school_telephone`, `school_email`) VALUES (1, 'Osnovna škola Zagreb 1', 'Vukovarska ulica 11', 1, '78346394637', '<EMAIL>'), (2, 'Osnovna škola Zagreb 2', 'Vukovarska ulica 11', 1, '78346394637', '<EMAIL>'), (3, 'Osnovna škola Zagreb 3', 'Vukovarska ulica 11', 2, '78346394637', '<EMAIL>'), (4, 'Osnovna škola Zagreb 4', 'Vukovarska ulica 11', 2, '78346394637', '<EMAIL>'), (5, 'Osnovna škola Zagreb 5', 'Vukovarska ulica 11', 2, '78346394637', '<EMAIL>'), (6, 'Osnovna škola Zagreb 6', 'Vukovarska ulica 11', 3, '78346394637', '<EMAIL>'); /* Insert data into table `teachers` */ INSERT INTO `teachers` (`teacher_id`, `teacher_name`, `teacher_surname`, `teacher_street`, `city_id`, `teacher_telephone`, `teacher_email`) VALUES (1, 'Ivan', 'Ivić', 'Vukovarska ulica 11', 1, '78346394637', '<EMAIL>'), (2, 'Josipa', 'Josić', 'Vukovarska ulica 11', 2, '78346394637', '<EMAIL>'), (3, 'Vedrana', 'Horvat', 'Vukovarska ulica 11', 1, '78346394637', '<EMAIL>'), (4, 'Ana', 'Prpa', 'Vukovarska ulica 11', 1, '78346394637', '<EMAIL>'), (5, 'Marko', 'Grba', 'Vukovarska ulica 11', 3, '78346394637', '<EMAIL>'), (6, 'Božo', 'Kralj', 'Vukovarska ulica 11', 2, '78346394637', '<EMAIL>'), (7, 'Branka', 'Car', 'Vukovarska ulica 11', 2, '78346394637', '<EMAIL>'); /* Insert data into table `classes` */ INSERT INTO `classes` (`class_id`, `class_name`, `class_mark`, `school_id`, `teacher_id`) VALUES /*school_id=1 */ (1, '1', 'a', 1, 1), (2, '2', 'b', 1, 2), (3, '3', 'a', 1, 3), (4, '4', 'a', 1, 4), /*school_id=2 */ (5, '1', 'a', 2, 1), (6, '2', 'b', 2, 2), (7, '3', 'a', 2, 3), (8, '4', 'a', 2, 4), /*school_id=3 */ (9, '1', 'a', 3, 1), (10, '2', 'b', 3, 2), (11, '3', 'a', 3, 3), (12, '4', 'a', 3, 4), /*school_id=4 */ (13, '1', 'a', 4, 1), (14, '2', 'b', 4, 2), (15, '3', 'a', 4, 3), (16, '4', 'a', 4, 4), /*school_id=5 */ (17, '1', 'a', 5, 1), (18, '2', 'b', 5, 2), (19, '3', 'a', 5, 3), (20, '4', 'a', 5, 4), /*school_id=6 */ (21, '1', 'a', 6, 1), (22, '2', 'b', 6, 2), (23, '3', 'a', 6, 3), (24, '4', 'a', 6, 4); /* Insert data into table `students` */ INSERT INTO `students` (`student_id`, `student_image`, `student_name`, `student_surname`, `student_oib`, `student_telephone`, `student_street`, `city_id`, `student_email`, `student_grade`, `student_status`, `class_id`) VALUES /* class_id=1 school_id=1 */ (1, 'img/user.png', 'Ivan', 'Horvat', '1254777784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 2.24, 1, 1), (2, 'img/user.png', 'Marija', 'Marić', '2254654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 2.37, 1, 1), (3, 'img/user.png', 'Josipa', 'Jopina', '3254654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 3.49, 1, 1), (4, 'img/user.png', 'Antonio', 'Antić', '4254654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 4.50, 1, 1), (5, 'img/user.png', 'Boško', 'Balaban', '5254654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 5.00, 1, 1), /* class_id=2 school_id=1 */ (6, 'img/user.png', 'Nikolina', 'Niki', '6254654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 2, 1, 2), (7, 'img/user.png', 'Ivan', 'Marić', '7254654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 2.4, 1, 2), (8, 'img/user.png', 'Josipa', 'Balaban', '8254654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 3.34, 1, 2), (9, 'img/user.png', 'Antonio', 'Horvat', '9254654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 4, 1, 2), (10, 'img/user.png', 'Marija', 'Horvat', '1154654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 4.34, 1, 2), /* class_id=3 school_id=1 */ (11, 'img/user.png', 'Adrijana', 'Bobić', '1254888784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 3.46, 1, 3), (12, 'img/user.png', 'Andreja', 'Deka', '1354654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 3.44, 1, 3), (13, 'img/user.png', 'Ivan', 'Deka', '1454654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 3.76, 1, 3), (14, 'img/user.png', 'Marko', 'Markić', '1554654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 4.76, 1, 3), (15, 'img/user.png', 'Hrvoje', 'Vojko', '1654654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 4.56, 1, 3), /* class_id=4 school_id=1 */ (16, 'img/user.png', 'Andrijan', 'Deka', '1754654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 3.65, 1, 4), (17, 'img/user.png', 'Ivan', 'Bobić', '1854654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 3.75, 1, 4), (18, 'img/user.png', 'Hrvoje', 'Balaban', '1954654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 3.57, 1, 4), (19, 'img/user.png', 'Nikolina', 'Markić', '1214654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 3.86, 1, 4), (20, 'img/user.png', 'Msrijana', 'Marijanović', '1224654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 4.76, 1, 4), /* class_id=5 school_id=2 */ (21, 'img/user.png', 'Đuro', 'Đurić', '1234656784344', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 4.45, 1, 5), (22, 'img/user.png', 'Pero', 'Perić', '1244654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 4.67, 1, 5), (23, 'img/user.png', 'Branko', 'Brankić', '1254564784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 4.65, 1, 5), (24, 'img/user.png', 'Bosiljko', 'Horvat', '1264654784554', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 3.87, 1, 5), (25, 'img/user.png', 'Ana', 'Anić', '1274654784599', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 3.76, 1, 5), /* class_id=6 school_id=2 */ (26, 'img/user.png', 'Ana', 'Horvat', '1284654784774', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 2.24, 1, 6), (27, 'img/user.png', 'Marija', 'Marić', '2294654786624', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 2.37, 1, 6), (28, 'img/user.png', 'Josipa', 'Jopina', '3254655484524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 3.49, 1, 6), (29, 'img/user.png', 'Antonio', 'Antić', '4254678784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 4.50, 1, 6), (30, 'img/user.png', 'Boško', 'Balaban', '5984654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 5.00, 1, 6), /* class_id=7 school_id=2 */ (31, 'img/user.png', 'Nikolina', 'Niki', '0051654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 2, 1, 7), (32, 'img/user.png', 'Ivan', 'Marić', '7252608784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 2.4, 1, 7), (33, 'img/user.png', 'Josipa', 'Balaban', '8093654784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 3.34, 1, 7), (34, 'img/user.png', 'Antonio', 'Horvat', '9254650384524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 4, 1, 7), (35, 'img/user.png', 'Marija', 'Horvat', '1105654704524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 4.34, 1, 7), /* class_id=8 school_id=2 */ (36, 'img/user.png', 'Adrijana', 'Bobić', '0256654780524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 3.46, 1, 8), (37, 'img/user.png', 'Andreja', 'Deka', '1357650284524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 3.44, 1, 8), (38, 'img/user.png', 'Ivan', 'Deka', '4586044784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 3.76, 1, 8), (39, 'img/user.png', 'Marko', 'Markić', '1550554784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 4.76, 1, 8), (40, 'img/user.png', 'Hrvoje', 'Vojko', '1654154780924', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 4.56, 1, 8), /* class_id=9 school_id=3 */ (41, 'img/user.png', 'Andrijan', 'Deka', '1754299784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 3.65, 1, 9), (42, 'img/user.png', 'Ivan', 'Bobić', '1854354789224', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 3.75, 1, 9), (43, 'img/user.png', 'Hrvoje', 'Balaban', '1953554784524', '3467457458', 'Vukovarska ulica 11', 1, '<EMAIL>', 3.57, 1, 9), (44, 'img/user.png', 'Nikolina', 'Markić', '1214586784524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.86, 1, 9), (45, 'img/user.png', 'Msrijana', 'Marijanović', '1224984784524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4.76, 1, 9), /* class_id=10 school_id=3 */ (46, 'img/user.png', 'Đuro', 'Đurić', '1234854784004', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4.45, 1, 10), (47, 'img/user.png', 'Pero', 'Perić', '1244954000524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4.67, 1, 10), (48, 'img/user.png', 'Branko', 'Brankić', '1250004784524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4.65, 1, 10), (49, 'img/user.png', 'Bosiljko', 'Horvat', '1211124784524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.87, 1, 10), (50, 'img/user.png', 'Ana', 'Anić', '1274634784524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.76, 1, 10), /* class_id=11 school_id=3 */ (51, 'img/user.png', 'Ivan', 'Horvat', '1254644111524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 2.24, 1, 11), (52, 'img/user.png', 'Marija', 'Marić', '2254654222524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 2.37, 1, 11), (53, 'img/user.png', 'Josipa', 'Jopina', '3254651333524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.49, 1, 11), (54, 'img/user.png', 'Antonio', 'Antić', '4254652444524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4.50, 1, 11), (55, 'img/user.png', 'Boško', 'Balaban', '5254653555524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 5.00, 1, 11), /* class_id=12 school_id=3 */ (56, 'img/user.png', 'Nikolina', 'Niki', '6254666784524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 2, 1, 12), (57, 'img/user.png', 'Ivan', 'Marić', '7254655787774', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 2.4, 1, 12), (58, 'img/user.png', 'Josipa', 'Balaban', '8254888784524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.34, 1, 12), (59, 'img/user.png', 'Antonio', 'Horvat', '9254999784524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4, 1, 12), (60, 'img/user.png', 'Marija', 'Horvat', '1111659784524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4.34, 1, 12), /* class_id=13 school_id=4 */ (61, 'img/user.png', 'Adrijana', 'Bobić', '1233654184524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.46, 1, 13), (62, 'img/user.png', 'Andreja', 'Deka', '1354654344524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.44, 1, 13), (63, 'img/user.png', 'Ivan', 'Deka', '1454654364524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.76, 1, 13), (64, 'img/user.png', 'Marko', 'Markić', '1554654674524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4.76, 1, 13), (65, 'img/user.png', 'Hrvoje', 'Vojko', '165465584524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4.56, 1, 13), /* class_id=14 school_id=4 */ (66, 'img/user.png', 'Andrijan', 'Deka', '1754676468424', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.65, 1, 14), (67, 'img/user.png', 'Ivan', 'Bobić', '1854654784344', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.75, 1, 14), (68, 'img/user.png', 'Hrvoje', 'Balaban', '1954654889224', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.57, 1, 14), (69, 'img/user.png', 'Nikolina', 'Markić', '1214654999524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.86, 1, 14), (70, 'img/user.png', 'Msrijana', 'Marijanović', '1994654714524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4.76, 1, 14), /* class_id=15 school_id=4 */ (71, 'img/user.png', 'Đuro', 'Đurić', '1234654724954', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4.45, 1, 15), (72, 'img/user.png', 'Pero', 'Perić', '1244659234524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4.67, 1, 15), (73, 'img/user.png', 'Branko', 'Brankić', '1254854744524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4.65, 1, 15), (74, 'img/user.png', 'Bosiljko', 'Horvat', '1264654756524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.87, 1, 15), (75, 'img/user.png', 'Ana', 'Anić', '1274654766524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.76, 1, 15), /* class_id=16 school_id=4 */ (76, 'img/user.png', 'Ivan', 'Horvat', '1254654776624', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 2.24, 1, 16), (77, 'img/user.png', 'Marija', 'Marić', '2254654664524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 2.37, 1, 16), (78, 'img/user.png', 'Josipa', 'Jopina', '3266654794524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.49, 1, 16), (79, 'img/user.png', 'Antonio', 'Antić', '4254666781524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4.50, 1, 16), (80, 'img/user.png', 'Boško', 'Balaban', '5254654755524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 5.00, 1, 16), /* class_id=17 school_id=5 */ (81, 'img/user.png', 'Nikolina', 'Niki', '6254654443524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 2, 1, 17), (82, 'img/user.png', 'Ivan', 'Marić', '7254654774524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 2.4, 1, 17), (83, 'img/user.png', 'Josipa', 'Balaban', '8254656684524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.34, 1, 17), (84, 'img/user.png', 'Antonio', 'Horvat', '9254633786524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4, 1, 17), (85, 'img/user.png', 'Marija', 'Horvat', '1154654722524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4.34, 1, 17), /* class_id=18 school_id=5 */ (86, 'img/user.png', 'Adrijana', 'Bobić', '1254654782224', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.46, 1, 18), (87, 'img/user.png', 'Andreja', 'Deka', '1354654733524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.44, 1, 18), (88, 'img/user.png', 'Ivan', 'Deka', '1454656784124', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.76, 1, 18), (89, 'img/user.png', 'Marko', 'Markić', '1554654834224', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4.76, 1, 18), (90, 'img/user.png', 'Hrvoje', 'Vojko', '1654654734324', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4.56, 1, 18), /* class_id=19 school_id=5 */ (91, 'img/user.png', 'Andrijan', 'Deka', '1754654734424', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.65, 1, 19), (92, 'img/user.png', 'Ivan', 'Bobić', '1854654736524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.75, 1, 19), (93, 'img/user.png', 'Hrvoje', 'Balaban', '1954658684624', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.57, 1, 19), (94, 'img/user.png', 'Nikolina', 'Markić', '1214654664724', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.86, 1, 19), (95, 'img/user.png', 'Msrijana', 'Marijanović', '1333654784824', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4.76, 1, 19), /* class_id=20 school_id=5 */ (96, 'img/user.png', 'Đuro', 'Đurić', '1234876784524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4.45, 1, 20), (97, 'img/user.png', 'Pero', 'Perić', '1243454784524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4.67, 1, 20), (98, 'img/user.png', 'Branko', 'Brankić', '1287654784524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 4.65, 1, 20), (99, 'img/user.png', 'Bosiljko', 'Horvat', '1264864784524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.87, 1, 20), (100, 'img/user.png', 'Ana', 'Anić', '1274654788524', '3467457458', 'Vukovarska ulica 11', 2, '<EMAIL>', 3.76, 1, 20);<file_sep><!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Pračenje ocjena učenika</title> <meta name="description" content="App for student grades"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="third-party/bootstrap-4.1.3/css/bootstrap.min.css"> <link rel="stylesheet" href="third-party/fontawesome-free-5.3.1-web/css/all.css"> <link rel="stylesheet" href="style.css"> </head> <body> <?php include("header.php"); ?> <div id="body"> <div id="body-bg"> <div class="container-fluid"> <div class="row"> <div class="col-sm-12"> <h1 class="text-center">Greška 404: Stranica koju ste tražili ne postoji.</h1> </div> </div> </div> </div> </div> <?php include("footer.php"); ?> <script src="third-party/jquery/jquery-3.3.1.min.js"></script> <script src="third-party/bootstrap-4.1.3/js/bootstrap.min.js"></script> </body> </html><file_sep><?php include_once("db-connection.php"); ?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Pračenje ocjena učenika</title> <meta name="description" content="App for student grades"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="third-party/bootstrap-4.1.3/css/bootstrap.min.css"> <link rel="stylesheet" href="third-party/fontawesome-free-5.3.1-web/css/all.css"> <link rel="stylesheet" href="style.css"> </head> <body> <?php include("header.php"); ?> <div id="body" class="p-0"> <h1 class="main-heading text-center text-white pt-5 pb-5">Pregledajte izvještaje</h1> <div class="container"> <div class="row"> <div class="col-lg-4 col-md-6 col-sm-12"> <a href="report1.php" class="report-box mb-5"> <h1>Broj učenika po školi i prosječna ocjena po školi</h1> <i class="far fa-file-alt fa-10x"></i> </a> </div> <div class="col-lg-4 col-md-6 col-sm-12"> <a href="report2.php" class="report-box mb-5"> <h1>Broj učenika po razredima i prosječna ocjena po razredu.</h1> <i class="far fa-file-alt fa-10x"></i> </a> </div> <div class="col-lg-4 col-md-6 col-sm-12"> <a href="report3.php" class="report-box mb-5"> <h1>Top pet učenika po prosjeku po svakoj školi.</h1> <i class="far fa-file-alt fa-10x"></i> </a> </div> </div> </div> </div> <?php include("footer.php"); ?> <script src="third-party/jquery/jquery-3.3.1.min.js"></script> <script src="third-party/bootstrap-4.1.3/js/bootstrap.min.js"></script> <script src="app.js"></script> </body> </html><file_sep>-- phpMyAdmin SQL Dump -- version 4.8.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Oct 05, 2018 at 01:20 AM -- Server version: 10.1.34-MariaDB -- PHP Version: 7.0.31 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; -- -- Database: `records_of_students` -- CREATE SCHEMA IF NOT EXISTS `records_of_students` DEFAULT CHARACTER SET utf8; USE `records_of_students`; -- -- Table structure for table `city` -- CREATE TABLE IF NOT EXISTS `city` ( `city_id` int(11) NOT NULL AUTO_INCREMENT, `city_name` varchar(120) NOT NULL, `zip` varchar(20) NOT NULL, PRIMARY KEY (`city_id`)) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- -- Table structure for table `schools` -- CREATE TABLE IF NOT EXISTS `schools` ( `school_id` int(11) NOT NULL AUTO_INCREMENT, `school_name` varchar(120) NOT NULL, `school_street` varchar(200) NOT NULL, `city_id` int(11) NOT NULL, `school_telephone` varchar(30) NOT NULL, `school_email` varchar(50) NOT NULL, PRIMARY KEY (`school_id`), INDEX `fk_schools_city1_idx` (`city_id` ASC), CONSTRAINT `fk_schools_city1` FOREIGN KEY (`city_id`) REFERENCES `records_of_students`.`city` (`city_id`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- -- Table structure for table `teachers` -- CREATE TABLE IF NOT EXISTS `teachers` ( `teacher_id` int(11) NOT NULL AUTO_INCREMENT, `teacher_name` varchar(120) NOT NULL, `teacher_surname` varchar(120) NOT NULL, `teacher_street` varchar(200) NOT NULL, `city_id` int(11) NOT NULL, `teacher_telephone` varchar(30) NOT NULL, `teacher_email` varchar(50) NOT NULL, PRIMARY KEY (`teacher_id`), INDEX `fk_teachers_city1_idx` (`city_id` ASC), CONSTRAINT `fk_teachers_city1` FOREIGN KEY (`city_id`) REFERENCES `records_of_students`.`city` (`city_id`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- -- Table structure for table `classes` -- CREATE TABLE IF NOT EXISTS `classes` ( `class_id` int(11) NOT NULL AUTO_INCREMENT, `class_name` varchar(20) NOT NULL, `class_mark` varchar(20) NOT NULL, `school_id` int(11) NOT NULL, `teacher_id` int(11) NOT NULL, PRIMARY KEY (`class_id`), INDEX `fk_classes_school_idx` (`school_id` ASC), INDEX `fk_classes_teacher_idx` (`teacher_id` ASC), CONSTRAINT `fk_classes_school1` FOREIGN KEY (`school_id`) REFERENCES `records_of_students`.`schools` (`school_id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_classes_teacher1` FOREIGN KEY (`teacher_id`) REFERENCES `records_of_students`.`teachers` (`teacher_id`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- -- Table structure for table `students` -- CREATE TABLE IF NOT EXISTS `students` ( `student_id` int(11) NOT NULL AUTO_INCREMENT, `student_image` varchar(200) NOT NULL, `student_name` varchar(120) NOT NULL, `student_surname` varchar(120) NOT NULL, `student_oib` varchar(13) NOT NULL, `student_telephone` varchar(30) NOT NULL, `student_street` varchar(200) NOT NULL, `city_id` int(11) NOT NULL, `student_email` varchar(50) NOT NULL, `student_grade` decimal(3,2) NOT NULL, `student_status` int(1) NOT NULL, `class_id` int(11) NOT NULL, PRIMARY KEY (`student_id`), UNIQUE INDEX `student_oib_UNIQUE` (`student_oib` ASC), INDEX `fk_students_city_idx` (`city_id` ASC), INDEX `fk_students_class_idx` (`class_id` ASC), CONSTRAINT `fk_students_city1` FOREIGN KEY (`city_id`) REFERENCES `records_of_students`.`city` (`city_id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_students_class1` FOREIGN KEY (`class_id`) REFERENCES `records_of_students`.`classes` (`class_id`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; /*SET SQL_MODE=@OLD_SQL_MODE*/; /*SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS*/; /*SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS*/;<file_sep><?php include_once("db-connection.php"); error_reporting( error_reporting() & ~E_NOTICE); /*ini_set('display_errors', 'On'); error_reporting(E_ALL);*/ if (isset($_GET["student_id"]) AND !empty($_GET["student_id"])){ $student_id = $_GET["student_id"]; if(!ctype_digit($student_id)){ header('Location: 404.php'); } } $id_update_student = $student_id; if ($_SERVER["REQUEST_METHOD"] == "POST") { if(isset($_POST["submit"])){ function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } $student_name = test_input($_POST["student_name"]); $student_surname = test_input($_POST["student_surname"]); $student_image = test_input($_POST["student_image"]); $student_oib = test_input($_POST["student_oib"]); $student_telephone = test_input($_POST["student_telephone"]); $student_street = test_input($_POST["student_street"]); $city_id = test_input($_POST["city_id"]); $class_id = test_input($_POST["class_id"]); $student_email = test_input($_POST["student_email"]); $student_grade = test_input($_POST["student_grade"]); $student_status = test_input($_POST["student_status"]); if(empty($student_name)){ $error_student_name = "Unesite ime."; } if(empty($student_surname)){ $error_student_surname = "Unesite Prezime."; } if(empty($student_oib)){ $error_student_oib = "Unesite OIB."; } if (!filter_var($student_email, FILTER_VALIDATE_EMAIL)) { $error_student_email = "Morate unijeti ispravnu E-mail adresu"; } $msg = ""; if(!isset($_FILES['student_image']) || $_FILES['student_image']['error'] == UPLOAD_ERR_NO_FILE){ if (isset($_GET['student_id']) AND !empty($_GET['student_id'])){ $sql = "SELECT students.student_image FROM students WHERE student_id =".$id_update_student; $result = doQuery($conn,$sql); if ($result->num_rows > 0) { while($row = $result->fetch_array()) { $student_image = $row["student_image"]; } } } }else{ $file_name = $_FILES['student_image']['name']; $file_size = $_FILES['student_image']['size']; $file_tmp = $_FILES['student_image']['tmp_name']; $file_type = $_FILES['student_image']['type']; $file_ext = strtolower(end(explode('.',$_FILES['student_image']['name']))); $expensions= array("jpeg","jpg","png"); if(in_array($file_ext,$expensions)=== false){ $error_student_image = "Format slike nije dozvoljen, molim učitajte JPG ili PNG format.<br/>"; } if($file_size > 2097152) { $error_student_image .= "Veličina slike mora biti manja od 2 MB.<br/>"; } if(empty($error_student_image)==true) { move_uploaded_file($file_tmp,"img/".$file_name); $student_image = "img/".$file_name; } } if(empty($error_student_name) AND empty($error_student_surname) AND empty($error_student_oib) AND empty($error_student_email) AND empty($error_student_image)){ if (!empty($id_update_student)){ $msg = "Uspješno ste ažurirali učenika"; $sql = "UPDATE students SET student_name='".$student_name."', student_surname='".$student_surname."', student_image='".$student_image."', student_oib='".$student_oib."', student_telephone='".$student_telephone."', student_street='".$student_street."', city_id=".$city_id.", student_email='".$student_email."', student_grade=".$student_grade.", student_status=".$student_status." , class_id=".$class_id." WHERE student_id =".$id_update_student; doQuery($conn,$sql); } else { $sql = "INSERT INTO students (student_name, student_surname, student_image, student_oib, student_telephone, student_street, city_id, student_email, student_grade, student_status, class_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; if($stmt = $conn->prepare($sql)){ $stmt->bind_param('sssddsdsddd', $student_name, $student_surname, $student_image, $student_oib, $student_telephone, $student_street, $city_id, $student_email, $student_grade, $student_status, $class_id); $stmt->execute(); $stmt->close(); } $msg = "Uspješno ste dodali novog učenika"; } } } } if(isset($_GET["student_delete"]) AND !empty($_GET["student_delete"])){ $student_delete = $_GET["student_delete"]; $sql = "DELETE FROM records_of_students.students WHERE students.student_id = " . $student_delete; doQuery($conn,$sql); } if(!empty($id_update_student)){ $sql = "SELECT students.student_id, students.student_image, students.student_name, students.student_surname, students.student_oib, students.student_street, students.student_grade, students.student_status, students.student_email, students.student_telephone FROM students WHERE student_id={$id_update_student}"; $result = doQuery($conn,$sql); $result_student = mysqli_fetch_array($result); } $sql = "SELECT * FROM city"; $city = doQuery($conn,$sql); $sql = "SELECT classes.class_id, classes.class_name, schools.school_id, schools.school_name FROM classes LEFT JOIN schools ON classes.school_id=schools.school_id"; $classes = doQuery($conn,$sql); ?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Učenici</title> <meta name="description" content="App for student grades"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="third-party/bootstrap-4.1.3/css/bootstrap.min.css"> <link rel="stylesheet" href="third-party/fontawesome-free-5.3.1-web/css/all.css"> <link rel="stylesheet" href="style.css"> </head> <body> <?php include("header.php"); ?> <div id="body"> <section class="page-header bg-secondary text-white mb-5 p-3"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <ul class="breadcrumb bg-light"> <li class="breadcrumb-item"><a href="index.php">Naslovnica</a></li> <li class="breadcrumb-item"><a href="schools.php">Škole</a></li> <li class="breadcrumb-item"><a href="classes.php">Razredi</a></li> <li class="breadcrumb-item"><a href="students.php">Učenici</a></li> <li class="breadcrumb-item active">Editiranje učenika</li> </ul> </div> </div> <div class="row"> <div class="col-md-12"> <h1>Učenici</h1> </div> </div> </div> </section> <div id="body-bg"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <a class="btn btn-primary mb-4" href="student-edit.php">Dodaj novog učenika</a> <h2 class="text-primary"><?php if(!empty($msg)){echo $msg;} ?></h2> <form name="student-edit-form" id="student-edit-form" method="POST" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]."?student_id=".$id_update_student); ?>" > <div class="form-group"> <label for="student_image">Slika:</label> <p class="text-danger d-inline small"> <?php echo $error_student_image; ?></p> <?php if (!empty($result_student["student_image"])){ echo '<br><img class="student-photo" src="'.$result_student["student_image"].'" />'; }else { echo '<br><img class="student-photo" src="img/user.png"/>'; } ?> <input class="form-control" name="student_image" id="student_image" accept="img/*" type="file" value="<?php if(!empty($result_student["student_image"])){echo $result_student["student_image"];} ?>" /> </div> <div class="form-group"> <label for="student_name">*Ime:</label> <p class="text-danger d-inline small"> <?php echo $error_student_name; ?></p> <input class="form-control" name="student_name" id="student_name" type="text" maxlength="120" value="<?php if(!empty($result_student["student_name"])){echo $result_student["student_name"];} ?>" required /> </div> <div class="form-group"> <label for="student_surname">*Prezime:</label> <p class="text-danger d-inline small"> <?php echo $error_student_surname; ?></p> <input class="form-control" name="student_surname" id="student_surname" type="text" maxlength="120" value="<?php if(!empty($result_student["student_surname"])){echo $result_student["student_surname"];} ?>" required /> </div> <div class="form-group"> <label for="student_oib">*OIB:</label> <p class="text-danger d-inline small"> <?php echo $error_student_oib; ?></p> <input class="form-control" pattern="^[0-9]*$" name="student_oib" id="student_oib" type="text" minlength="13" maxlength="13" value="<?php if(!empty($result_student["student_oib"])){echo $result_student["student_oib"];} ?>" required /> </div> <div class="form-group"> <label for="student_telephone">Telefon:</label> <input class="form-control" name="student_telephone" id="student_telephone" type="text" maxlength="30" value="<?php if(!empty($result_student["student_telephone"])){echo $result_student["student_telephone"];} ?>"/> </div> <div class="form-group"> <label for="student_street">Ulica:</label> <input class="form-control" name="student_street" id="student_street" type="text" maxlength="120" value="<?php if(!empty($result_student["student_street"])){echo $result_student["student_street"];} ?>"/> </div> <div class="form-group"> <label for="city_id">Grad:</label> <select class="form-control" name="city_id" id="city_id"> <?php while($row = mysqli_fetch_array($city)){ echo "<option value=\"".$row["city_id"]."\""; if(!empty($result_student["city_id"]) AND $result_student["city_id"] == $row["city_id"]) { echo " selected=\"selected\" "; } echo ">".$row["city_name"]."</option>"; } ?> </select> </div> <div class="form-group"> <label for="class_id">Razred:</label> <select class="form-control" name="class_id" id="class_id"> <?php while($row = mysqli_fetch_array($classes)){ echo "<option value=\"".$row["class_id"]."\""; if(!empty($result_student["class_id"]) AND $result_student["class_id"] == $row["class_id"]) { echo " selected=\"selected\" "; } echo ">".$row["school_name"]. " - " .$row["class_name"]." razred</option>"; } ?> </select> </div> <div class="form-group"> <label for="student_email">E-mail:</label> <p class="text-danger d-inline small"> <?php echo $error_student_email; ?></p> <input class="form-control" name="student_email" id="student_email" type="email" maxlength="50" value="<?php if(!empty($result_student["student_email"])){echo $result_student["student_email"];} ?>"/> </div> <div class="form-group"> <label for="student_grade">Prosječna ocjena:</label> <input class="form-control" name="student_grade" id="student_grade" type="number" min="1" max="5" step="0.01" value="<?php if(!empty($result_student["student_grade"])){echo $result_student["student_grade"];} ?>"/> </div> <div class="form-group"> <label for="student_status">*Status:</label><br> <input type="radio" name="student_status" value="1" <?php if(!empty($result_student['student_status']) AND $result_student['student_status'] == 1){echo "checked";} ?> required> Aktivan<br> <input type="radio" name="student_status" value="0" <?php if(isset($result_student['student_status']) AND $result_student['student_status'] == 0){echo "checked";} ?> required> Neaktivan<br> </div> <div class="form-group"> <input type="submit" name="submit" class="btn btn-primary" value="Spremi"> <input type="reset" class="btn btn-basic" value="Očisti formu"> <?php if(!empty($id_update_student)){ echo '<a class="btn btn-danger" onclick="return confirm(\'Jeste li sigurni da želite obrisati učenika?\');" href="student-edit.php?student_delete=<?php echo $result_student["student_id"];?>Obriši učenika</a>'; } ?> </div> </form> </div> </div> </div> </div> </div> <?php include("footer.php"); ?> <script src="third-party/jquery/jquery-3.3.1.min.js"></script> <script src="third-party/bootstrap-4.1.3/js/bootstrap.min.js"></script> <script src="third-party/fontawesome-free-5.3.1-web/js/all.js"></script> </body> </html>
b54f90d364757429f73587953ed3d52fcfe48263
[ "Markdown", "SQL", "PHP" ]
12
PHP
dhmorinski/records-of-students
587e85c88fdfba434d52770e6211575c1864dd1d
d0ffd2974427681b776f039b0c3527ac21fb121a
refs/heads/master
<repo_name>epdjsmit/laravel-invoice<file_sep>/app/Http/Controllers/CustomersController.php <?php namespace App\Http\Controllers; use App\Customers; use Illuminate\Http\Request; use App\Http\Requests\CustomersFormRequest; use Session; class CustomersController extends Controller { function __construct() { $this->middleware('auth'); } public function index() { return view('customers.index'); } public function create() { // } public function store(CustomersFormRequest $request) { // } public function show(Customers $customers) { // } public function edit(Customers $customers) { return view('customers.edit', compact(['customers'])); } public function update(CustomersFormRequest $request, Customers $customers) { $duit = Customers::find($customers->id) ->update(request([ 'client', 'client_address', 'client_poskod', 'client_phone', 'client_email', ])); $customers->touch(); // info when update success Session::flash('flash_message', 'Data successfully edited!'); return redirect(route('customers.index')); } public function destroy(Customers $customers) { // } } <file_sep>/app/Http/Controllers/PaymentsController.php <?php namespace App\Http\Controllers; use App\Payments; use Illuminate\Http\Request; use Session; class PaymentsController extends Controller { function __construct() { $this->middleware('auth'); } public function index() { // } public function create() { // } public function store(Request $request) { // } public function show(Payments $payments) { // } public function edit(Payments $payments) { // } public function update(Request $request, Payments $payments) { // } public function destroy(Payments $payments) { $si = Payments::find($payments->id); // delete related model $si->delete(); // info when update success Session::flash('flash_message', 'Data successfully deleted!'); return redirect()->back(); // redirect back to original route } } <file_sep>/app/Taxes.php <?php namespace App; // use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Taxes extends Model { use SoftDeletes; protected $dates = ['deleted_at']; public function taxessales() { return $this->hasMany('App\Sales', 'id_sales'); } } <file_sep>/public/js/ucwords.js http://www.jquery4u.com/events/capitalize-letter-word-keypress/ //usage $("input").keyup(function() { toUpper(this); }); //function function toUpper(obj) { var mystring = obj.value; var sp = mystring.split(' '); var wl=0; var f ,r; var word = new Array(); for (i = 0 ; i < sp.length ; i ++ ) { f = sp[i].substring(0,1).toUpperCase(); r = sp[i].substring(1).toLowerCase(); word[i] = f+r; } newstring = word.join(' '); obj.value = newstring; return true; }<file_sep>/app/Product.php <?php namespace App; // use Illuminate\Database\Eloquent\Model; class Product extends Model { public function productimage() { return $this->hasMany('App\ProductImage', 'id_product'); } public function category() { return $this->belongsTo('App\ProductCategory'); } public function transaction() { return $this->hasMany('App\Transactions', 'id_user'); } }
b231767fa09259a98a4f8b819a31f8cb1ee5a809
[ "JavaScript", "PHP" ]
5
PHP
epdjsmit/laravel-invoice
208a18e4675850f6d05f52e57de4cd3e2d0ed736
494a0ceff8962868d43c0b96d0c7d2e96e6b0776
refs/heads/master
<repo_name>Tokiya/POJ-university<file_sep>/src/people/Lecturer.java package people; public class Lecturer extends PersonBase{ private String title; protected Lecturer(String name, String surname, String title) { super(name, surname); this.title=title; } @Override protected String showDetails() { return "tytuł naukowy: "+ this.title; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
9ffd38c1fd11e8b95f44505c49863a6aa4dfbb59
[ "Java" ]
1
Java
Tokiya/POJ-university
7edbb596424580d753341f04f38d33bd025083e3
4e3342cd08059807f14cdca11be5da874fdc1cb2
refs/heads/master
<repo_name>arvind351/SPOT<file_sep>/README.md # SPOT Simple Point Optical Tracker Visually identify a laser pointer using OpenCV and Python, and control a wheeled Boe-Bot to follow the laser. Developed for EEL4660- Robotic Systems. #Contributions: Vision module programming - <NAME> Control module programming - <NAME> Raspberry Pi setup - <NAME> BASIC controls programming - <NAME> (with kind assistance from <NAME>) Mounting and hardware - <NAME> and <NAME> Video Editing - <NAME> Testing - <NAME>, <NAME> and <NAME> SPOT video demo: https://www.youtube.com/watch?time_continue=1&v=QO8uOHRp5-k <file_sep>/control.py """SPOT: Sean's Point Optical Tracker - Control module Converts target location information from vision module (angle, distance) to pulses, which are transmitted by serial USB connection to control servos on a BOE-Bot. """ __author__= "<NAME>" import serial import time from collections import deque PORT = 0 class Controller: """This class manages the serial connection to the BOE-Bot and commands.""" def __init__(self, port=0): self.serial = serial_connect(port) self.detections = deque(maxlen=50) self.prev_command = (750, 750) self.time_since_last_detection = 0 self.prev_direction = 0 self.search = 0 def process_detection(self, angle, distance, flip=False): """Based on detection from vision module, this function determines and transmits the next command.""" if angle is not None and distance is not None: self.detections.append([angle, distance]) # record detection info command = get_command(angle, distance, flip) self.prev_command = command self.search = 0 else: self.detections.append([]) self.time_since_last_detection += 1 command = 0 if self.time_since_last_detection > 15: self.search = 1 if self.prev_command in [1, 4, 7]: command = 1 elif self.prev_command in [2, 5, 8]: command = 2 else: command = 0 if self.serial.isOpen(): transmit_command(self.serial, command) self.prev_command = command msg = 'Command: ' + str(command) def close(self): """End the serial connection.""" if self.serial.isOpen(): self.serial.close() print("Serial connection closed.") else: print("Serial connection is already closed.") def serial_connect(port=0): #s = serial.Serial(port='/dev/ttyUSB%d' % port, baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=None) s = serial.Serial('/dev/ttyUSB%d' % port, 9600) if s.isOpen(): print('Serial connection opened.') else: print('Serial connection failed.') return s def transmit_command(s, command): s.write('%s\n' % str(command)) print('Transmitted: %s' % command) def transmit_commandB(s, command): c = command if c == 0: s.write('0\n') # left elif c == 1: s.write('1\n') # straight elif c==-1: s.write('2\n') # right def get_command(angle, dist, flipped=False): angle_diff = 45 if angle > angle_diff: command = -1 elif angle < -angle_diff: command = 0 else: command = 1 if flipped: command *= -1 return command def transmit_commandB(s, command): (pulse1, pulse2) = command bc1 = byte_command(pulse1) bc2 = byte_command(pulse2) transmit_bytes(s, bc1) transmit_bytes(s, bc2) print(bc1, bc2) def byte_command(pulse): """Translates pulses to 8-bit values in range [0, 255]""" command = pulse bytes = str(command).zfill(3) return bytes def transmit_bytes(s, bytes): for b in bytes: s.write('%s\n' % b) print('%s\n' % b) def get_command(angle, distance, flipped=False): """Translates angle and distance to servo motor pulse widths""" #rotate_right = (770, 770) #rotate_left = (730, 730) #full_ahead = (850, 650) #half_ahead = (775, 725) #slight_right = (850, 700) #right = (850, 725) #left = (775, 650) #slight_left = (800, 650) #stop = (750, 750) stop = 0 rotate_right = 1 rotate_left = 2 half_ahead = 3 right = 4 left = 5 full_ahead = 6 slight_right = 7 slight_left = 8 full= [full_ahead, slight_right, slight_left] mid = [half_ahead, right, left] low = [stop, rotate_right, rotate_left] commands = [low, mid, full] speed_level = get_speed(distance) direction = get_direction(angle, flipped) command = commands[speed_level][direction] print('Command: %s, angle: %d, distance: %d' % (command, angle, distance)) return command def get_direction(angle, flipped=False): thresh_angle = 30 direction = 0 if angle < (-1 * thresh_angle): direction = -1 if angle > thresh_angle: direction = 1 if flipped: direction *= -1 return direction def get_speed(distance): if distance > 270: return 2 elif distance > 50: return 1 return 0 def convert_angle(angle): max_out = 1500 min_out = 1 a = angle + 90 a *= (1500 / 180) if a > max_out: a = max_out elif a < min_out: a = min_out return int(a) def convert_distance(distance): return 127 def main1(): s = serial_connect(PORT) while True: c = input("Command:") if c == 0: s.write('0\n') elif c == 1: s.write('1\n') elif c==2: s.write('2\n') else: break s.close() exit() def main(): """Test function.""" TRANSMIT = 1 if TRANSMIT: s = serial_connect(PORT) while True: command = input('Enter command: ') if TRANSMIT: transmit_command(s, command) if TRANSMIT: s.close() exit() if __name__ == "__main__": main() <file_sep>/video.py import numpy as np import cv2 import math ANALYSIS = 1 def main(): print(cv2.__version__) # Open video capture source, 0 is webcam # source = '/home/sean/Desktop/laser2.avi' source = '/home/sean/PycharmProjects/SPOT/pi1.avi' cap = cv2.VideoCapture(source) width = int(cap.get(3)) height = int(cap.get(4)) origin = (width // 2, height - 45) print("Size: %d x %d\nOrigin: %d, %d" % (width, height, origin[0], origin[1])) t = -1 # # Save video # fourcc = cv2.VideoWriter_fourcc(*'XVID') # out = cv2.VideoWriter('demo_vid.avi', fourcc, 20.0, (width, height)) prev_pt = origin while cap.isOpened(): _, frame = cap.read(10) if frame is None: print("Video stream ended") break t += 1 # time # red = frame[:, :, 2] # examine the red color channel of RGB image # red = cv2.medianBlur(red, 5) # blur to reduce noise # (_, maxVal, _, maxLoc) = cv2.minMaxLoc(red) # locate the pixel with the highest intensity value # mask = cv2.inRange(red, maxVal, 255) # frame = cv2.medianBlur(frame, 5) frame = cv2.GaussianBlur(frame, (5, 5), 0) # frame = cv2.medianBlur(frame, 3) mask = mask_laser(frame) # Draw origin and centerline # cv2.circle(frame, origin, 10, 255, 20) # cv2.line(frame, (width//2, height), (width//2, 0), 0, 2) # draw_grid(frame, 120, 120, width, height) # cv2.imshow("Video", frame) # # threshold = 220 # if maxVal > threshold: # # cv2.circle(frame, maxLoc, 5, (255, 0, 0), 2) # # cv2.line(frame, origin, maxLoc, 255, 3) # dist = distance(origin, maxLoc) # x = maxLoc[0] - width//2 # y = height - maxLoc[1] # theta = angle(x, y) # hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # bgr_val = frame[maxLoc] # hsv_val = hsv[maxLoc] # print(bgr_val, hsv_val) # # print(dist, theta, t) # string = str(dist) + ", " + str(theta) + "deg" # # cv2.rectangle(frame, (0, 0), (300, 100), (255, 255, 255), thickness=-1) # cv2.putText(frame, string, (maxLoc[0] - 5, maxLoc[1] - 15), cv2.FONT_HERSHEY_SIMPLEX, 1, 255, 2, cv2.LINE_AA) # else: # print("None") # # out.write(frame) # mask = morph(mask) contours = contour_select(mask) if len(contours) > 0: pt = get_point(contours, prev_pt) print pt cv2.circle(frame, pt, 5, (255, 0, 0), 2) else: print(None) # print(len(contours)) # if ANALYSIS and len(contours) != 1: # cv2.waitKey(0) masked = cv2.bitwise_and(frame, frame, mask=mask) cv2.imshow('Masked', frame) # cv2.imshow('Video', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break # Release capture and clean up windows cap.release() cv2.destroyAllWindows() def get_point(contours, prev): if len(contours) > 0: centers = [] for c in contours: M = cv2.moments(c) center = (int(M['m10'] / M['m00']), int(M['m01'] / M['m00'])) centers.append(center) pt = min(centers, key=lambda x: distance(x, prev)) return pt return None def contour_select(mask): """From a binary image mask, select the contours that could be the laser.""" contours = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] return contours def mask_laser(frame): hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # Red range target_min = np.array([170, 0, 0]) target_max = np.array([255, 255, 255]) t_min = 200 t_max = 190 bgr_red_min = np.array([0, 0, t_min]) bgr_red_max = np.array([t_max, t_max, 255]) # White range # target_lower_min = np.array([0, 0, 0]) # target_lower_max = np.array([255, 12, 255]) target_lower_min = np.array([0, 0, 0]) target_lower_max = np.array([255, 12, 255]) # Create masks mask1 = cv2.inRange(frame, bgr_red_min, bgr_red_max) # mask1 = cv2.inRange(hsv, target_min, target_max) mask2 = cv2.inRange(hsv, target_lower_min, target_lower_max) mask = cv2.addWeighted(mask1, 1, mask2, 1, 0) # combine the two masks return mask1 def black_hat(img): """The Black Hat operator isolates patches in an image that are brighter than their neighbors.""" bh = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT) (_, maxVal, _, maxLoc) = cv2.minMaxLoc(bh) return bh def morph(mask): """First erode the mask to remove noise, then dilate to fill in missing pixels. This is akin to morphological closing.""" img = cv2.erode(mask, None, iterations=4) # smooth/remove protrusions mask = cv2.dilate(mask, None, iterations=2) # smooth/fill concavities return mask def detect(img): """Returns the coordinates believed to be the center of the laser pointer, or None if not found.""" img = cv2.GaussianBlur(img, (5, 5), 0) red = img[:, :, 2] # examine the red color channel of RGB image (_, maxVal, _, maxLoc) = cv2.minMaxLoc(red) # locate the pixel with the highest intensity value mask = cv2.inRange(red, maxVal, 255) # Draw origin and centerline cv2.circle(img, origin, 10, 255, 20) cv2.line(frame, (width//2, height), (width//2, 0), 0, 2) draw_grid(frame, 120, 120, width, height) cv2.imshow("Video", frame) threshold = 220 if maxVal > threshold: # cv2.circle(frame, maxLoc, 5, (255, 0, 0), 2) # cv2.line(frame, origin, maxLoc, 255, 3) dist = distance(origin, maxLoc) x = maxLoc[0] - width//2 y = height - maxLoc[1] theta = angle(x, y) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) bgr_val = frame[maxLoc] hsv_val = hsv[maxLoc] # print(dist, theta, t) string = str(dist) + ", " + str(theta) + "deg" # cv2.rectangle(frame, (0, 0), (300, 100), (255, 255, 255), thickness=-1) cv2.putText(frame, string, (maxLoc[0] - 5, maxLoc[1] - 15), cv2.FONT_HERSHEY_SIMPLEX, 1, 255, 2, cv2.LINE_AA) else: print("None") def detect2(img): frame = cv2.GaussianBlur(img, (5, 5), 0) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # Red range target_min = np.array([170, 0, 0]) target_max = np.array([255, 255, 255]) # White range target_lower_min = np.array([0, 0, 0]) target_lower_max = np.array([255, 12, 255]) # Create masks mask1 = cv2.inRange(hsv, target_min, target_max) mask2 = cv2.inRange(hsv, target_lower_min, target_lower_max) mask = cv2.addWeighted(mask1, 1, mask2, 1, 0) def draw_grid(frame, x_step, y_step, width, height): for x in range(0, width, x_step): cv2.line(frame, (x, height), (x, 0), (0, 0, 0), 1) for y in range(0, height, y_step): cv2.line(frame, (width, y), (0, y), (0, 0, 0), 1) def angle(x, y): """Returns the angle between the point and the center line relative to the origin. A negative value indicates a detection left of the center line.""" rads = math.atan2(y, x) deg = int(math.degrees(rads)) if deg < 90: deg = 90 - deg elif deg >= 90: deg = deg - 90 if x < 0: deg *= -1 return deg def distance(p1, p2): """Returns the Euclidean distance between two points.""" x1, y1 = p1 x2, y2 = p2 return int(math.sqrt((x1-x2)**2 + (y1-y2)**2)) if __name__ == "__main__": main() <file_sep>/image.py import cv2 import numpy as np img = cv2.imread('Video_screenshot_09.12.2017.png') hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) hsl_img = cv2.cvtColor(img, cv2.COLOR_BGR2HLS) cv2.namedWindow('image') def get_color(event, x, y, flags, param): if event == cv2.EVENT_MOUSEMOVE: bgr = img[y, x] hsv = hsv_img[y,x] hsl = hsl_img[y, x] print("BGR: %s | HSV: %s | HSL: %s" % (bgr, hsv, hsl)) cv2.setMouseCallback('image', get_color) while 1: cv2.imshow('image', img) if cv2.waitKey(1) & 0xFF == ord('q'): break # Cleanup cv2.destroyAllWindows() <file_sep>/vision.py """SPOT: Simple Optical Point Tracker - Vision module This module performs visual identification of laser pointers using the OpenCV library on a Raspberry Pi 2. It uses video input from a Pi Camera module. Identification is performed in four main steps. Firstly, the image undergoes Gaussian blurring for smoothing and noise reduction. Next, a mask is created for values within a specified color range, to isolate bright and red regions. The mask is then eroded to reduce noise and protrusions, and dilated to fill in the gaps. From the modified mask, contours are calculated, and filtered by area. The center of the remaining contour closest to the previous detection is chosen as the new detection. This process requires tuning the parameters of Gaussian blur radius, color thresholds, and erosion/dilation iterations to achieve an acceptable rate of detections. A balance between type 1 and type 2 errors was eventually achieved. The output of the vision module is a tuple, specifying the distance from the detected point to the origin (center, bottom pixel) and the angle from the centerline. These values are used for controlling a robot to follow the laser pointer. """ __author__ = "<NAME>" import cv2 import time import math from picamera.array import PiRGBArray from picamera import PiCamera import argparse import numpy as np from control import Controller # CONFIG PORT = 0 width = 640 height = 480 def main(): parser = argparse.ArgumentParser() parser.add_argument("--d", "--display", help= "video") args = parser.parse_args() # Config DISPLAY = 1 FLIP = 0 RECORD = 1 CONTROL = 1 # Pi Cam setup cam = PiCamera() resolution = (width, height) cam.resolution = resolution cam.framerate = 32 #cam.brightness = 40 raw = PiRGBArray(cam, size=resolution) time.sleep(0.1) # BOE-BOT serial connection controller = Controller(PORT) # Record a quick test video #cam.start_recording('testA.avi') #print('Recording start') #time.sleep(8) #cam.stop_recording() #print('Rec end') # RECORD VIDEO - suprisingly difficult save_path = 'capture/img' #record_video(cam, 10) origin = (width // 2, height) if FLIP: origin = (width // 2, 0) print(resolution, origin) t = 0 prev = origin for frame in cam.capture_continuous(raw, format="bgr", use_video_port=True): img = frame.array if img is None: print('Stream ended. t=%d' %t) break if t == 10: cv2.imwrite('test.jpg', img) pt = detect(img, prev) if pt is not None: img = mark(img, pt, origin) d = dist(pt, origin) x = pt[0] - width//2 y = height - pt[1] theta = angle_offset(x, y) msg = controller.process_detection(theta, d, FLIP) #print("Distance: %d, Angle: %d, Time: %d" % (d, theta, t)) prev = pt else: msg = controller.process_detection(None, None, FLIP) print(msg) if DISPLAY: if FLIP: img = cv2.flip(img, 0) cv2.imshow('pi video', img) if RECORD: cv2.imwrite('capture/img%d.jpg' % t, img) raw.truncate(0) if cv2.waitKey(1) & 0xFF == ord('q'): break t += 1 controller.close() def morph(img): """First erode the mask to remove noise, the dilate to fill missing points""" #img = cv2.erode(img, None, iterations=1) img = cv2.dilate(img, None, iterations=3) return img def mask_laser(img): hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) red_hsv_min = np.array([170, 0, 0]) red_hsv_max = np.array([255, 255, 255]) t_min = 190 t_max = 200 red_bgr_min = np.array([0, 0, t_min]) red_bgr_max = np.array([t_max, t_max, 255]) bright_hsv_min = np.array([160, 0, 170]) bright_hsv_max = np.array([255, 40, 255]) #mask1 = cv2.inRange(hsv, red_hsv_min, red_hsv_max) mask1 = cv2.inRange(img, red_bgr_min, red_bgr_max) mask2 = cv2.inRange(hsv, bright_hsv_min, bright_hsv_max) mask = cv2.addWeighted(mask1, 1, mask2, 1, 0) return mask def dist(p1, p2): """Returns the Euclidean distance between two points.""" x1, y1 = p1 x2, y2 = p2 return int(math.sqrt((x1-x2)**2 + (y1-y2)**2)) def angle_offset(x, y): rads = math.atan2(y, x) deg = int(math.degrees(rads)) if deg < 90: deg = 90 - deg elif deg >= 90: deg = deg - 90 if x < 0: deg *= -1 return deg def mark(img, pt, origin): """Draw a circle over the point and a line to the origin.""" if pt is not None: cv2.circle(img, pt, 5, (255, 0, 0), 1) cv2.line(img, origin, pt, 255, 2) return img def record_video(camera, time): camera.start_recording('testvid1.h264') print('Recording started') camera.wait_recording(time) camera.stop_recording() print('Recording ended') def contour_select(mask): """Extract contours from a mask and examine their area.""" contours = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if len(contours) == 0: return None for c in contours[0]: area = cv2.contourArea(c) #print(area) return contours[0] def get_point(contours, prev): """From a set of contours, determine the center of each contour using its moments and select the center with the point nearest the previously detected point as the new detection point.""" if len(contours) > 0: centers = [] for c in contours: M = cv2.moments(c) if M['m00'] != 0: center = (int(M['m10'] / M['m00']), int(M['m01'] / M['m00'])) centers.append(center) if len(centers) > 0: pt = min(centers, key=lambda x: dist(x, prev)) return pt return None def detect(img, prev): img = cv2.GaussianBlur(img, (3, 3), 0) mask = mask_laser(img) #mask = morph(mask) masked = cv2.bitwise_and(img, img, mask=mask) #cv2.imshow('Masked', mask) contours = contour_select(mask) pt = get_point(contours, prev) return pt if __name__ == "__main__": main()
34a3f31020e7bc79ebfd316729703b82e764e4d0
[ "Markdown", "Python" ]
5
Markdown
arvind351/SPOT
291efaeacaabcf9929e7274da3885293ca95d0e8
b7000ba637c3175cdd5f9eaf38f9db7058f97a03
refs/heads/master
<repo_name>TristanXiaoxiang/AdminLoginProjectI-Struts<file_sep>/src/service/AdminService.java package service; import java.sql.SQLException; import java.util.List; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import com.sun.org.apache.regexp.internal.recompile; import dao.AdminDao; import entity.Admin; import utils.JdbcUtils; public class AdminService { AdminDao adminDao=new AdminDao(); public AdminService() { // TODO Auto-generated constructor stub } public Admin login(Admin admin){ try { return adminDao.login(admin); } catch (Exception e) { throw new RuntimeException(e); } } public List<Admin> getAll(){ try { return adminDao.getAll(); } catch (Exception e) { throw new RuntimeException(e); } } }
64a8321c9c6da253341ff4542d05eaf99920b81a
[ "Java" ]
1
Java
TristanXiaoxiang/AdminLoginProjectI-Struts
75b53d49bd1fa5a82a9cea835443886aec3ca0ce
54331e0853c4f9daf20bac97565a74848da1c98a
refs/heads/master
<file_sep>import { Component, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-fetch-employees', templateUrl: './fetch-employees.component.html' }) export class FetchEmployeesComponent { public employees: Employee[]; constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) { http.get<Employee[]>(baseUrl + 'api/Employee/employees').subscribe(result => { this.employees = result; }, error => console.error(error)); } } interface Employee { name: string; position: number; } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { RouterModule } from '@angular/router'; import { AppComponent } from './app.component'; import { NavMenuComponent } from './nav-menu/nav-menu.component'; import { HomeComponent } from './home/home.component'; import { CounterComponent } from './counter/counter.component'; import { FetchDataComponent } from './fetch-data/fetch-data.component'; import { FetchEmployeesComponent } from './fetch-employees/fetch-employees.component'; import { AddOrUpdateEmployeeComponent } from './addorupdateemployee/addOrUpdateEmployee.component'; import { EmployeeService } from './employee_service/employee.service'; import * as _ from 'lodash'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {MatButtonModule} from '@angular/material/button'; import {MatCardModule } from '@angular/material'; import {MatInputModule} from '@angular/material/input'; import {MatFormFieldModule} from '@angular/material'; @NgModule({ declarations: [ AppComponent, NavMenuComponent, HomeComponent, CounterComponent, FetchDataComponent, FetchEmployeesComponent, AddOrUpdateEmployeeComponent ], imports: [ BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }), MatButtonModule, HttpClientModule, FormsModule, MatCardModule, MatInputModule, MatFormFieldModule, BrowserAnimationsModule, RouterModule.forRoot([ { path: '', component: HomeComponent, pathMatch: 'full' }, { path: 'counter', component: CounterComponent }, { path: 'fetch-data', component: FetchDataComponent }, { path: 'fetch-employees', component: FetchEmployeesComponent }, ]) ], exports:[ ], providers: [EmployeeService], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AngularEmployeeManagement.Models; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; namespace AngularEmployeeManagement.Controllers { [EnableCors("OpenPolicy")] [Route("api/[controller]")] public class EmployeeController : Controller { static List<Employee> list = new List<Employee>() { new Employee { Name="Philip", Position = "Developer" }, new Employee { Name = "Mimi", Position = "Developer" } }; [Route("employees")] public async Task<IActionResult> GetEmployees() { return Ok(list); } [HttpPut("{name}")] public async Task<IActionResult> PutEmployee([FromRoute] string name, [FromBody] Employee employee) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var e = list.FirstOrDefault(em => em.Name == name); e = employee; return Ok(); } [HttpPost] public async Task<IActionResult> PostEmployee([FromBody] Employee employee) { if (!ModelState.IsValid) { return BadRequest(ModelState); } list.Add(employee); return Ok(); } [HttpDelete("{name}")] public async Task<IActionResult> DeleteEmployee([FromRoute] string name) { var em=list.FirstOrDefault(e => e.Name == name); list.Remove(em); return Ok(); } } }<file_sep> import { EmployeeService } from '../employee_service/employee.service'; import * as _ from 'lodash'; import { Component, EventEmitter, Input, Output, OnInit } from '@angular/core'; @Component({ selector: 'app-fetch-employees', templateUrl: './fetch-employees.component.html' }) export class FetchEmployeesComponent implements OnInit { public employees: Employee[]; public currentEmployee: any; constructor(private employeeService: EmployeeService) { debugger; employeeService.get().subscribe((data: any) => this.employees = data); this.currentEmployee = this.setInitialValuesForEmployeeData(); } ngOnInit() { } private setInitialValuesForEmployeeData() { return { name: '', position: '' } } public deleteRecord(employee) { debugger; const deleteIndex = _.findIndex(this.employees, { name: employee.name }); this.employeeService.remove(employee).subscribe( result => this.employees.splice(deleteIndex, 1) ); } public editRecord(record) { debugger; const clonedRecord = Object.assign({}, record); this.currentEmployee = clonedRecord; } public newRecord() { debugger; this.currentEmployee = this.setInitialValuesForEmployeeData(); } public createOrUpdateEmployee = function (employee: any) { debugger; let employeeWithId; employeeWithId = _.find(this.employees, (el => el.name === employee.name)); if (employeeWithId) { const updateIndex = _.findIndex(this.employees, { name: employeeWithId.name }); this.employeeService.update(employee).subscribe( employeeRecord => this.employees.splice(updateIndex, 1, employee) ); } else { this.employeeService.add(employee).subscribe( employeeRecord => this.employees.push(employee) ); } this.currentEmployee = this.setInitialValuesForEmployeeData(); }; } interface Employee { name: string; position: string; } <file_sep>import { Component, EventEmitter, Input, Output, OnInit } from '@angular/core'; @Component({ selector: 'app-addOrUpdateEmployee', templateUrl: './addOrUpdateEmployee.component.html' }) export class AddOrUpdateEmployeeComponent implements OnInit { @Output() employeeCreated = new EventEmitter<any>(); @Input() employee: any; public buttonText = 'Save'; constructor() { this.clearEmployeeInfo(); console.log(this.employee.name); } ngOnInit() { } private clearEmployeeInfo = function () { // Create an empty employee object this.employee = { name: '', position: '', }; }; public addOrUpdateEmployeeRecord = function (event) { debugger; this.employeeCreated.emit(this.employee); this.clearEmployeeInfo(); }; }
a1546a8acb50da20978ed8ccac766354b8cae540
[ "C#", "TypeScript" ]
5
TypeScript
spectre359/Angular_NETCore_EmployeeManagementSystem
e584a24c53732391e9d9cb3e4829d993aebf934e
d836e6f6ac4d81af1ae6af8acd763459efb7eb2b
refs/heads/master
<repo_name>ruskofulanito/bbdd2<file_sep>/src/main/java/bd2/Muber/dto/CalificacionDTO.java package bd2.Muber.dto; import bd2.Muber.model.Calificacion; /** * * @author <NAME> * Representación (DTO) de la entidad Calificacion. * Los DTO son representaciones no persistentes de los objetos * del modelo que permiten trabajar en memoria fuera del ambiente * transaccional con objetos que se asemejan a los originales. * */ public class CalificacionDTO { private long viaje; private long pasajero; private String comentario; private Integer puntaje; private Long idCalificacion; public CalificacionDTO(Calificacion calificacion){ this.setIdCalificacion(calificacion.getIdCalificacion()); this.setViaje(calificacion.getViaje().getIdViaje()); this.setPasajero(calificacion.getPasajero().getIdUsuario()); this.setComentario(calificacion.getComentario()); this.setPuntaje(calificacion.getPuntaje()); } public long getViaje() { return viaje; } public void setViaje(long viaje) { this.viaje = viaje; } public long getPasajero() { return pasajero; } public void setPasajero(long pasajero) { this.pasajero = pasajero; } public String getComentario() { return comentario; } public void setComentario(String comentario) { this.comentario = comentario; } public Integer getPuntaje() { return puntaje; } public void setPuntaje(Integer puntaje) { this.puntaje = puntaje; } public Long getIdCalificacion() { return idCalificacion; } public void setIdCalificacion(Long idCalificacion) { this.idCalificacion = idCalificacion; } } <file_sep>/src/main/java/bd2/Muber/services/impl/PasajeroService.java package bd2.Muber.services.impl; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.transaction.annotation.Transactional; import bd2.Muber.dto.PasajeroDTO; import bd2.Muber.model.Pasajero; import bd2.Muber.repositories.impl.RepositoryLocator; import bd2.Muber.services.interfaces.PasajeroServiceInterface; /** * * @author <NAME> * Implementación del proveedor de servicios de Pasajero. * La notación Transactional indica a Spring que las llamadas * a métodos de esta clase se realizan en un ambiente transaccional * para administrar los pasajeros de Muber. * Ver los comentarios de la interfaz que implementa. * */ @Transactional public class PasajeroService implements PasajeroServiceInterface{ public PasajeroService(){ } public List<PasajeroDTO> getPasajeros(){ List<PasajeroDTO> pasajerosDTO = new ArrayList<PasajeroDTO>(); for (Pasajero pasajero : RepositoryLocator.getInstance().getPasajeroRepository().getAll()) { pasajerosDTO.add(new PasajeroDTO(pasajero)); } return pasajerosDTO; } public PasajeroDTO acreditar(long idPasajero, double monto) { Pasajero pasajero = RepositoryLocator.getInstance().getPasajeroRepository().get(idPasajero); return this.setCredito(idPasajero, monto+pasajero.getCredito()); } public PasajeroDTO setCredito(long idPasajero, double monto) { Pasajero pasajero = RepositoryLocator.getInstance().getPasajeroRepository().get(idPasajero); pasajero.setCredito(monto); return new PasajeroDTO(pasajero); } @Override public PasajeroDTO getPasajero(long idPasajero) { try { return new PasajeroDTO(RepositoryLocator.getInstance().getPasajeroRepository().get(idPasajero)); } catch(NullPointerException e) { return null; } } @Override public PasajeroDTO addPasajero(String nombre, String password, Date fechaIngreso, Double credito) { Pasajero p = new Pasajero(nombre, password, fechaIngreso, credito); RepositoryLocator.getInstance().getMuberRepository().getMuber().getPasajeros().add(p); return new PasajeroDTO(p); } }<file_sep>/src/main/java/bd2/Muber/services/impl/ViajeService.java package bd2.Muber.services.impl; import java.util.Date; import java.util.LinkedList; import java.util.List; import org.springframework.transaction.annotation.Transactional; import bd2.Muber.dto.CalificacionDTO; import bd2.Muber.dto.ViajeDTO; import bd2.Muber.model.Calificacion; import bd2.Muber.model.Ciudad; import bd2.Muber.model.Conductor; import bd2.Muber.model.Pasajero; import bd2.Muber.model.Viaje; import bd2.Muber.repositories.impl.RepositoryLocator; import bd2.Muber.services.impl.ViajeService; import bd2.Muber.services.interfaces.ViajeServiceInterface; /** * * @author <NAME> * Implementación del proveedor de servicios de Viaje. * La notación Transactional indica a Spring que las llamadas * a métodos de esta clase se realizan en un ambiente transaccional * para administrar los viajes de Muber. * Ver los comentarios de la interfaz que implementa. * */ @Transactional public class ViajeService implements ViajeServiceInterface { public List<ViajeDTO> getOpenTrips() { List<ViajeDTO> viajesDTO = new LinkedList<ViajeDTO>(); for (Viaje viaje : RepositoryLocator.getInstance().getViajeRepository().getOpenTrips()) { viajesDTO.add(new ViajeDTO(viaje)); } return viajesDTO; } public List<ViajeDTO> getViajes() { List<ViajeDTO> viajesDTO = new LinkedList<ViajeDTO>(); for (Viaje viaje : RepositoryLocator.getInstance().getViajeRepository().getAll()) { viajesDTO.add(new ViajeDTO(viaje)); } return viajesDTO; } @Override public ViajeDTO addViaje(long idDestino, long idOrigen, Date fecha, int cantidadPasajeros, double costo, long idConductor) { Conductor conductor = RepositoryLocator.getInstance().getConductorRepository().get(idConductor); Ciudad origen = RepositoryLocator.getInstance().getCiudadRepository().get(idOrigen); Ciudad destino = RepositoryLocator.getInstance().getCiudadRepository().get(idDestino); try { Viaje viaje; viaje = new Viaje(conductor, fecha, origen, destino, costo, cantidadPasajeros); RepositoryLocator.getInstance().getMuberRepository().getMuber().addViaje(viaje); conductor.addViaje(viaje); return new ViajeDTO(viaje); } catch (Exception e) { return null; } } public CalificacionDTO addCalificacion(long idViaje, long idPasajero, int puntaje, String comentario) { Viaje viaje = RepositoryLocator.getInstance().getViajeRepository().get(idViaje); Pasajero pasajero = RepositoryLocator.getInstance().getPasajeroRepository().get(idPasajero); try { Calificacion calificacion = new Calificacion(viaje, pasajero, comentario, puntaje); viaje.agregarCalificacion(calificacion); return new CalificacionDTO(calificacion); } catch (Exception e) { return null; } } public ViajeDTO addPasajero(long idPasajero, long idViaje) { Pasajero pasajero = RepositoryLocator.getInstance().getPasajeroRepository().get(idPasajero); Viaje viaje = RepositoryLocator.getInstance().getViajeRepository().get(idViaje); try { viaje.agregarPasajero(pasajero); return new ViajeDTO(viaje); } catch (Exception e) { return null; } } public ViajeDTO finalizarViaje(long idViaje) { Viaje viaje = RepositoryLocator.getInstance().getViajeRepository().get(idViaje); viaje.finalizarViaje(); return new ViajeDTO(viaje); } @Override public ViajeDTO getViaje(long idViaje) { try { return new ViajeDTO(RepositoryLocator.getInstance().getViajeRepository().get(idViaje)); } catch (NullPointerException e) { return null; } } }<file_sep>/src/main/java/bd2/Muber/repositories/impl/CiudadRepository.java package bd2.Muber.repositories.impl; import org.hibernate.Query; import org.hibernate.SessionFactory; import bd2.Muber.model.Ciudad; public class CiudadRepository extends Repository<Ciudad> { public CiudadRepository(SessionFactory sessionFactory) { super(sessionFactory, Ciudad.class); } public Ciudad getByName(String nombreCiudad) { Query query = getCurrentSession().createQuery("from Ciudad c where c.ciudad LIKE :ciudad"); query.setParameter("ciudad", nombreCiudad); return (Ciudad) query.list().get(0); } }<file_sep>/src/main/java/bd2/Muber/model/Muber.java package bd2.Muber.model; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import java.util.List; /** * * @author <NAME> * Representación (modelo) de la entidad Muber. * */ public class Muber { private Collection<Conductor> conductores; private Collection<Pasajero> pasajeros; private Collection<Viaje> viajes; private Collection<Ciudad> ciudades; private Long idMuber; public Muber() { this.conductores = new HashSet<Conductor>(); this.pasajeros = new HashSet<Pasajero>(); this.viajes = new HashSet<Viaje>(); this.ciudades = new HashSet<Ciudad>(); } public void setIdMuber(Long idMuber) { this.idMuber = idMuber; } public Long getIdMuber() { return this.idMuber; } public void setConductores(Collection<Conductor> conductores) { this.conductores = conductores; } public Collection<Conductor> getConductores() { return this.conductores; } public void setPasajeros(Collection<Pasajero> pasajeros) { this.pasajeros = pasajeros; } public void addViaje(Viaje v) { this.viajes.add(v); } public Collection<Pasajero> getPasajeros() { return this.pasajeros; } public void setViajes(Collection<Viaje> viajes) { this.viajes = viajes; } public Collection<Viaje> getViajes() { return this.viajes; } public Collection<Ciudad> getCiudades() { return this.ciudades; } public void setCiudades(Collection<Ciudad> ciudades) { this.ciudades = ciudades; } public void addCiudad(Ciudad c) { this.ciudades.add(c); } } <file_sep>/src/main/java/bd2/Muber/dto/ViajeDTO.java package bd2.Muber.dto; import bd2.Muber.model.Calificacion; import bd2.Muber.model.Pasajero; import bd2.Muber.model.Viaje; import java.util.Collection; import java.util.Date; import java.util.HashSet; /** * * @author <NAME> * Representación (DTO) de la entidad Viaje. * Los DTO son representaciones no persistentes de los objetos * del modelo que permiten trabajar en memoria fuera del ambiente * transaccional con objetos que se asemejan a los originales. * */ public class ViajeDTO { private Collection<Long> pasajeros; private Collection<Long> calificaciones; private Long conductor; private Boolean finalizado; private Date fechaViaje; private Long origen, destino; private Long idViaje; private Double costo; private Integer cantidadPasajeros; public ViajeDTO() { setPasajeros(new HashSet<Long>()); setCalificaciones(new HashSet<Long>()); } public ViajeDTO(Viaje viaje) { this(); this.setIdViaje(viaje.getIdViaje()); this.setConductor(viaje.getConductor().getIdUsuario()); this.setFechaViaje(viaje.getFechaViaje()); this.setOrigen(viaje.getOrigen().getIdCiudad()); this.setDestino(viaje.getDestino().getIdCiudad()); this.setCosto(viaje.getCosto()); this.setCantidadPasajeros(viaje.getCantidadPasajeros()); this.setFinalizado(viaje.isFinalizado()); for (Pasajero pasajero: viaje.getPasajeros()) { this.pasajeros.add(pasajero.getIdUsuario()); } for (Calificacion calificacion: viaje.getCalificaciones()) { this.calificaciones.add(calificacion.getIdCalificacion()); } } public Collection<Long> getPasajeros() { return pasajeros; } public void setPasajeros(Collection<Long> pasajeros) { this.pasajeros = pasajeros; } public Collection<Long> getCalificaciones() { return calificaciones; } public void setCalificaciones(Collection<Long> calificaciones) { this.calificaciones = calificaciones; } public Long getConductor() { return conductor; } public void setConductor(Long conductor) { this.conductor = conductor; } public Boolean getFinalizado() { return finalizado; } public void setFinalizado(Boolean finalizado) { this.finalizado = finalizado; } public Date getFechaViaje() { return fechaViaje; } public void setFechaViaje(Date fechaViaje) { this.fechaViaje = fechaViaje; } public Long getOrigen() { return origen; } public void setOrigen(Long origen) { this.origen = origen; } public Long getDestino() { return destino; } public void setDestino(Long destino) { this.destino = destino; } public Long getIdViaje() { return idViaje; } public void setIdViaje(Long idViaje) { this.idViaje = idViaje; } public Double getCosto() { return costo; } public void setCosto(Double costo) { this.costo = costo; } public Integer getCantidadPasajeros() { return cantidadPasajeros; } public void setCantidadPasajeros(Integer cantidadPasajeros) { this.cantidadPasajeros = cantidadPasajeros; } } <file_sep>/src/main/java/bd2/Muber/repositories/impl/ViajeRepository.java package bd2.Muber.repositories.impl; import java.util.List; import org.hibernate.Query; import org.hibernate.SessionFactory; import bd2.Muber.model.Viaje; public class ViajeRepository extends Repository<Viaje> { public ViajeRepository(SessionFactory sessionFactory) { super(sessionFactory, Viaje.class); } /** * Obtiene de la base de datos la lista de viajes abiertos (no finalizados) * @return List Colección de DTOs de viajes abiertos. */ @SuppressWarnings("unchecked") public List<Viaje> getOpenTrips(){ Query query = getCurrentSession().createQuery("from Viaje v where v.finalizado = false"); return (List<Viaje>) query.list(); } }<file_sep>/src/main/java/bd2/Muber/dto/PasajeroDTO.java package bd2.Muber.dto; import bd2.Muber.model.Pasajero; /** * * @author <NAME> * Representación (DTO) de la entidad Pasajero. * Los DTO son representaciones no persistentes de los objetos * del modelo que permiten trabajar en memoria fuera del ambiente * transaccional con objetos que se asemejan a los originales. * */ public class PasajeroDTO extends UsuarioDTO { private Double credito; public PasajeroDTO(Pasajero pasajero) { super(pasajero); this.setCredito(pasajero.getCredito()); } public void setCredito(Double credito) { this.credito = credito; } public Double getCredito() { return this.credito; } } <file_sep>/src/main/java/bd2/Muber/repositories/impl/RepositoryLocator.java package bd2.Muber.repositories.impl; /** * * @author <NAME> * Esta clase permite enumerar, obtener y establecer * los distintos repositorios de la aplicación. * Se implementa con un patrón Singleton y tiene un campo para cada * repositorio concreto del espacio de nombres actual. * */ public class RepositoryLocator { protected static RepositoryLocator repositoryLocator = null; protected CalificacionRepository calificacionRepository; protected ConductorRepository conductorRepository; protected MuberRepository muberRepository; protected PasajeroRepository pasajeroRepository; protected CiudadRepository ciudadRepository; protected ViajeRepository viajeRepository; public static RepositoryLocator getInstance() { if (repositoryLocator == null){ repositoryLocator = new RepositoryLocator(); } return repositoryLocator; } public RepositoryLocator() { } public CalificacionRepository getCalificacionRepository() { return calificacionRepository; } public void setCalificacionRepository(CalificacionRepository calificacionRepository) { this.calificacionRepository = calificacionRepository; } public ConductorRepository getConductorRepository() { return conductorRepository; } public void setConductorRepository(ConductorRepository conductorRepository) { this.conductorRepository = conductorRepository; } public MuberRepository getMuberRepository() { return muberRepository; } public void setMuberRepository(MuberRepository muberRepository) { this.muberRepository = muberRepository; } public PasajeroRepository getPasajeroRepository() { return pasajeroRepository; } public void setPasajeroRepository(PasajeroRepository pasajeroRepository) { this.pasajeroRepository = pasajeroRepository; } public ViajeRepository getViajeRepository() { return viajeRepository; } public void setViajeRepository(ViajeRepository viajeRepository) { this.viajeRepository = viajeRepository; } public CiudadRepository getCiudadRepository() { return ciudadRepository; } public void setCiudadRepository(CiudadRepository ciudadRepository) { this.ciudadRepository = ciudadRepository; } public static void setInstance(RepositoryLocator instance) { repositoryLocator = instance; } }<file_sep>/escenario-etapa2.sh #!/bin/sh echo "---------------------------" echo "Crear la ciudad de Córdoba" echo "---------------------------" curl -X POST -d"ciudad=Córdoba&provincia=Córdoba" http://localhost:8080/MuberRESTful/rest/ciudades/nuevo echo "\n\n" echo "-------------------------------" echo "Crear la ciudad de Mar del Plata" echo "-------------------------------" curl -X POST -d"ciudad=Mar del Plata&provincia=Buenos Aires" http://localhost:8080/MuberRESTful/rest/ciudades/nuevo echo "\n\n" echo "----------------------" echo "Crear al pasajero Hugo" echo "----------------------" curl -X POST -d"nombre=Hugo&password=<PASSWORD>&fechaIngreso=2017-05-27&creditoInicial=2300" http://localhost:8080/MuberRESTful/rest/pasajeros/nuevo echo "\n\n" echo "----------------------------------" echo "Sumar 4000 al crédito de Margarita" echo "----------------------------------" curl -H 'content-type:application/json' -X PUT -d"{'pasajeroId':3,'monto':4000}" http://localhost:8080/MuberRESTful/rest/pasajeros/cargarCredito echo "\n\n" echo "---------------------------------------------------------------" echo "Crear el viaje de Córdoba a Mar del Plata del conductor Roberto" echo "---------------------------------------------------------------" curl -X POST -d"conductorId=1&cantidadPasajeros=3&origen=3&destino=4&costoTotal=3500&fecha=2017-08-20" http://localhost:8080/MuberRESTful/rest/viajes/nuevo echo "\n\n" echo "----------------------------------------" echo "Agregar a la pasajera Margarita al viaje" echo "----------------------------------------" curl -H 'content-type:application/json' -X PUT -d"{'pasajeroId':3,'viajeId':2}" http://localhost:8080/MuberRESTful/rest/viajes/agregarPasajero echo "\n\n" echo "---------------------------------" echo "Agregar al pasajero Hugo al viaje" echo "---------------------------------" curl -H 'content-type:application/json' -X PUT -d"{'pasajeroId':5,'viajeId':2}" http://localhost:8080/MuberRESTful/rest/viajes/agregarPasajero echo "\n\n" echo "------------------" echo "Finalizar el viaje" echo "------------------" curl -H 'content-type:application/json' -X PUT -d"{'viajeId':2}" http://localhost:8080/MuberRESTful/rest/viajes/finalizar echo "\n\n" echo "-------------------------------------------------" echo "Estado de Margarita después de finalizar el viaje" echo "-------------------------------------------------" curl http://localhost:8080/MuberRESTful/rest/pasajeros/detalle?pasajeroId=3 echo "\n\n" echo "--------------------------------------------" echo "Estado de Hugo después de finalizar el viaje" echo "--------------------------------------------" curl http://localhost:8080/MuberRESTful/rest/pasajeros/detalle?pasajeroId=5 echo "\n\n" echo "-----------------------------" echo "Crear la calificación de Hugo" echo "-----------------------------" curl -X POST -d"viajeId=2&pasajeroId=5&puntaje=5&comentario=Comentario de Hugo, califica con 5" http://localhost:8080/MuberRESTful/rest/viajes/calificar echo "\n\n" echo "----------------------------------" echo "Crear la calificación de Margarita" echo "----------------------------------" curl -X POST -d"viajeId=2&pasajeroId=3&puntaje=4&comentario=Comentario de Margarita, califica con 4" http://localhost:8080/MuberRESTful/rest/viajes/calificar echo "\n\n" echo "---------------------------------------------------" echo "Estado de Roberto después de recibir calificaciones" echo "---------------------------------------------------" curl http://localhost:8080/MuberRESTful/rest/conductores/detalle?conductorId=1 echo "\n\n" <file_sep>/src/main/java/bd2/Muber/model/Viaje.java package bd2.Muber.model; import java.util.Set; import java.time.Instant; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.Iterator; /** * * @author <NAME> * Representación (modelo) de la entidad Viaje. * */ public class Viaje { private Collection<Pasajero> pasajeros; private Collection<Calificacion> calificaciones; private Conductor conductor; private Boolean finalizado = false; private Date fechaViaje; private Ciudad origen, destino; private Long idViaje; private Double costo; private Integer cantidadPasajeros; public Viaje() { pasajeros = new HashSet<Pasajero>(); calificaciones = new HashSet<Calificacion>(); } /** * Constructor adicional para permitir establecer directamente los datos del modelo. * @param conductor Long Identificador del conductor del viaje. * @param fechaViaje Date Fecha del viaje. * @param origen Ciudad Ciudad de origen. * @param destino Ciudad Ciudad de destino. * @param costo Double Costo total del viaje (se prorratea entre los pasajeros). * @param cantidadPasajeros Integer Cantidad máxima de pasajeros que admite el viaje. * @throws Exception Error al establecer el conductor (por ejemplo, tiene la licencia vencida). */ public Viaje(Conductor conductor, Date fechaViaje, Ciudad origen, Ciudad destino, Double costo, Integer cantidadPasajeros) throws Exception { this(); this.setConductor(conductor); this.setFechaViaje(fechaViaje); this.setOrigen(origen); this.setDestino(destino); this.setCosto(costo); this.setCantidadPasajeros(cantidadPasajeros); conductor.addViaje(this); } public void setCantidadPasajeros(Integer cantidadPasajeros) { this.cantidadPasajeros = cantidadPasajeros; } public Integer getCantidadPasajeros() { return this.cantidadPasajeros; } public void setCalificaciones(Set<Calificacion> c) { this.calificaciones = c; } public Collection<Calificacion> getCalificaciones() { return this.calificaciones; } public void setCosto(double costo) { this.costo = (Double) costo; } public Double getCosto() { return this.costo; } public void setIdViaje(Long idViaje) { this.idViaje = idViaje; } public Long getIdViaje() { return this.idViaje; } /** * Establece el conductor del viaje verificando que: * El conductor posee una licencia que no está vencida. * @param conductor Conductor Conductor del viaje. * @throws Exception El conductor tiene la licencia vencida. */ public void setConductor(Conductor conductor) throws Exception { if (conductor.getVencimientoLicencia().compareTo(Date.from(Instant.now())) < 0) { throw new Exception("El conductor tiene la licencia vencida"); } this.conductor = conductor; } public Conductor getConductor() { return this.conductor; } public void setOrigen(Ciudad ciudad) { this.origen = ciudad; } public Ciudad getOrigen() { return this.origen; } public void setDestino(Ciudad destino) { this.destino = destino; } public Ciudad getDestino() { return this.destino; } public void setFechaViaje(Date fecha) { this.fechaViaje = fecha; } public Date getFechaViaje() { return this.fechaViaje; } public void setPasajeros(Set<Pasajero> p) { this.pasajeros = p; } public Collection<Pasajero> getPasajeros() { return this.pasajeros; } public void setFinalizado(Boolean f) { this.finalizado = f; } public Boolean isFinalizado() { return this.finalizado; } /** * Agrega al pasajero a la lista de pasajeros del viaje si se cumple que: * El viaje no está completo (la cantidad de pasajeros en la colección de * pasajeros del viaje es igual al atributo cantidad máxima de pasajeros * del viaje). * La implementación del mapeo (Set) garantiza que un pasajero existe una * sola vez en la colección de pasajeros del viaje, por lo que no se * verifica explícitamente esta condición. * * @param pasajero Pasajero Pasajero a agregar al viaje. * @throws Exception No hay más lugar en el viaje. */ public void agregarPasajero(Pasajero pasajero) throws Exception { if (this.getPasajeros().size() == this.getCantidadPasajeros()) { throw new Exception("No queda lugar en el viaje seleccionado."); } this.getPasajeros().add(pasajero); pasajero.addViaje(this); } /** * Agrega una calificación al viaje si y solo si se cumple que: * El pasajero asociado a la calificación está en la lista de pasajeros del viaje. * El pasajero asociado a la calificación no realizó una calificación anteriormente * para este viaje. * El viaje ya fue finalizado. * * @param calificacion Calificacion Objeto calificación creado anteriormente para este viaje. * @throws Exception No se puede calificar el viaje, o bien el pasajero no puede calificar este viaje. */ public void agregarCalificacion(Calificacion calificacion) throws Exception { if (!this.isFinalizado()) { throw new Exception("Solamente puede calificar un viaje cuando ya fue finalizado."); } if (!this.getPasajeros().contains(calificacion.getPasajero())) { throw new Exception("No puede calificar un viaje del que no participó"); } Collection<Calificacion> calificaciones = this.getCalificaciones(); for(Calificacion existente: calificaciones) { if (existente.getPasajero().equals(calificacion.getPasajero())) { throw new Exception("Solamente puede calificar una vez el viaje"); } } this.getCalificaciones().add(calificacion); } public Double getCostoUnitario() { if (this.getPasajeros().size() == 0) { return this.getCosto(); } return this.getCosto() / this.getPasajeros().size(); } /** * Recorre la lista de calificaciones del viaje totalizando * los puntajes asociados a las mismas. * @return Integer Suma de los puntajes de las calificaciones del viaje */ public Integer getPuntajeTotal() { Integer puntaje = 0; if (this.isFinalizado()) { Iterator<Calificacion> calificaciones = getCalificaciones().iterator(); while (calificaciones.hasNext()) { Calificacion calificacion = calificaciones.next(); puntaje += calificacion.getPuntaje(); } } return puntaje; } /** * Representación String del viaje */ @Override public String toString() { return "Viaje desde ".concat(this.getOrigen().toString()).concat(" hasta ").concat(this.getDestino().toString()) .concat(". Fecha: ").concat(this.getFechaViaje().toString()); } /** * Finaliza el viaje tomando en cuenta las siguientes reglas de negocio: * El viaje no fue finalizado anteriormente. * TODO: La fecha del viaje es el día de hoy o anterior (es decir, potencialmente ya * fue realizado). - esta regla no se implementa para permitir debug fácil. * En caso de corresponder la finalización se descuenta el crédito a cada uno * de los pasajeros del viaje. */ public void finalizarViaje() { if (!this.isFinalizado() && true/*!(Date.from(Instant.now())).before(this.getFechaViaje())*/) { if (this.getPasajeros().size() > 0) { Double aDescontar = this.getCostoUnitario(); Iterator<Pasajero> itr = this.getPasajeros().iterator(); while (itr.hasNext()) { itr.next().descontarCredito(aDescontar); } } this.setFinalizado(true); } } } <file_sep>/src/main/java/bd2/Muber/repositories/impl/MuberRepository.java package bd2.Muber.repositories.impl; import org.hibernate.SessionFactory; import bd2.Muber.model.Muber; public class MuberRepository extends Repository<Muber> { public MuberRepository(SessionFactory sessionFactory) { super(sessionFactory, Muber.class); } /** * Este objeto representa la raíz de los datos del sistema. * Existe una sola instancia de Muber y es la que tiene ID=1. * Si dicha instancia no existe (primera ejecución de la aplicación), se crea * y guarda el objeto Muber inicial. Esta es la única llamada al método Save. * Otras aproximación para resolver esta situación es la de crear el registro en * la base de datos en el momento de instalación de la aplicación - sin embargo, * la utilizada aquí es independiente del motor de bases de datos. * * @return Muber Instancia del modelo de Muber */ public Muber getMuber() { Muber instance = this.get(new Long(1)); if (instance == null) { instance = new Muber(); this.getCurrentSession().save(instance); return instance; } else { return instance; } } }<file_sep>/src/main/resources/config_dev.properties jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.username=grupo04 jdbc.password=<PASSWORD> jdbc.url=jdbc:mysql://localhost:3306/grupo04?autoReconnect=true&autoReconnectForPools=true hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.connection.autoReconnect=true hibernate.showsql=true hibernate.hbm2ddl.auto=create-drop<file_sep>/escenario-etapa1.sh #!/bin/sh echo "---------------------------" echo "Crear la ciudad de La Plata" echo "---------------------------" curl -X POST -d"ciudad=La Plata&provincia=Buenos Aires" http://localhost:8080/MuberRESTful/rest/ciudades/nuevo echo "\n\n" echo "-------------------------------" echo "Crear la ciudad de Tres Arroyos" echo "-------------------------------" curl -X POST -d"ciudad=Tres Arroyos&provincia=Buenos Aires" http://localhost:8080/MuberRESTful/rest/ciudades/nuevo echo "\n\n" echo "--------------------------" echo "Crear al conductor Roberto" echo "--------------------------" curl -X POST -d"nombre=Roberto&password=<PASSWORD>&fechaIngreso=2017-04-01&fechaLicencia=2018-06-30" http://localhost:8080/MuberRESTful/rest/conductores/nuevo echo "\n\n" echo "------------------------" echo "Crear al pasajero Germán" echo "------------------------" curl -X POST -d"nombre=Germán&password=<PASSWORD>&fechaIngreso=2017-04-10&creditoInicial=1500" http://localhost:8080/MuberRESTful/rest/pasajeros/nuevo echo "\n\n" echo "-----------------------------" echo "Crear a la pasajera Margarita" echo "-----------------------------" curl -X POST -d"nombre=Margarita&password=<PASSWORD>&fechaIngreso=2017-04-03&creditoInicial=1500" http://localhost:8080/MuberRESTful/rest/pasajeros/nuevo echo "\n\n" echo "--------------------------" echo "Crear a la pasajera Alicia" echo "--------------------------" curl -X POST -d"nombre=Alicia&password=<PASSWORD>&fechaIngreso=2017-04-07&creditoInicial=1500" http://localhost:8080/MuberRESTful/rest/pasajeros/nuevo echo "\n\n" echo "---------------------------------------------------------------" echo "Crear el viaje de La Plata a <NAME> del conductor Roberto" echo "---------------------------------------------------------------" curl -X POST -d"conductorId=1&cantidadPasajeros=4&origen=1&destino=2&costoTotal=900&fecha=2017-06-20" http://localhost:8080/MuberRESTful/rest/viajes/nuevo echo "\n\n" echo "-----------------------------------" echo "Agregar al pasajero Germán al viaje" echo "-----------------------------------" curl -H 'content-type:application/json' -X PUT -d"{'pasajeroId':2,'viajeId':1}" http://localhost:8080/MuberRESTful/rest/viajes/agregarPasajero echo "\n\n" echo "----------------------------------------" echo "Agregar a la pasajera Margarita al viaje" echo "----------------------------------------" curl -H 'content-type:application/json' -X PUT -d"{'pasajeroId':3,'viajeId':1}" http://localhost:8080/MuberRESTful/rest/viajes/agregarPasajero echo "\n\n" echo "-------------------------------------" echo "Agregar a la pasajera Alicia al viaje" echo "-------------------------------------" curl -H 'content-type:application/json' -X PUT -d"{'pasajeroId':4,'viajeId':1}" http://localhost:8080/MuberRESTful/rest/viajes/agregarPasajero echo "\n\n" echo "------------------" echo "Finalizar el viaje" echo "------------------" curl -H 'content-type:application/json' -X PUT -d"{'viajeId':1}" http://localhost:8080/MuberRESTful/rest/viajes/finalizar echo "\n\n" echo "----------------------------------------------" echo "Estado de Alicia después de finalizar el viaje" echo "----------------------------------------------" curl http://localhost:8080/MuberRESTful/rest/pasajeros/detalle?pasajeroId=4 echo "\n\n" echo "-------------------------------------------------" echo "Estado de Margarita después de finalizar el viaje" echo "-------------------------------------------------" curl http://localhost:8080/MuberRESTful/rest/pasajeros/detalle?pasajeroId=3 echo "\n\n" echo "----------------------------------------------" echo "Estado de Germán después de finalizar el viaje" echo "----------------------------------------------" curl http://localhost:8080/MuberRESTful/rest/pasajeros/detalle?pasajeroId=2 echo "\n\n" echo "-------------------------------" echo "Crear la calificación de Germán" echo "-------------------------------" curl -X POST -d"viajeId=1&pasajeroId=2&puntaje=4&comentario=Comentario de Germán, califica 4" http://localhost:8080/MuberRESTful/rest/viajes/calificar echo "\n\n" echo "----------------------------------" echo "Crear la calificación de Margarita" echo "----------------------------------" curl -X POST -d"viajeId=1&pasajeroId=3&puntaje=5&comentario=Comentario de Margarita, califica con 5" http://localhost:8080/MuberRESTful/rest/viajes/calificar echo "\n\n" echo "-------------------------------" echo "Crear la calificación de Alicia" echo "-------------------------------" curl -X POST -d"viajeId=1&pasajeroId=4&puntaje=5&comentario=Comentario de Alicia, califica con 5" http://localhost:8080/MuberRESTful/rest/viajes/calificar echo "\n\n" echo "---------------------------------------------------" echo "Estado de Roberto después de recibir calificaciones" echo "---------------------------------------------------" curl http://localhost:8080/MuberRESTful/rest/conductores/detalle?conductorId=1 echo "\n\n" <file_sep>/src/main/java/bd2/Muber/services/interfaces/ViajeServiceInterface.java package bd2.Muber.services.interfaces; import java.util.Date; import java.util.List; import bd2.Muber.dto.CalificacionDTO; import bd2.Muber.dto.ViajeDTO; /** * * @author <NAME> * Interfaz que implementa el proveedor de servicios para el repositorio Viaje. * La implementación de interfaces permite que Spring administre de manera * transparente los proxies para manejar transacciones. * */ public interface ViajeServiceInterface { /** * Obtiene la lista de todos los viajes de Muber. * @return List Colección de DTOs de los viajes de Muber. */ List<ViajeDTO> getViajes(); /** * Obtiene la lista de viajes abiertos (no finalizados). * @return List Colección de DTOs viajes abiertos. */ List<ViajeDTO> getOpenTrips(); ViajeDTO getViaje(long idViaje); /** * Finaliza (si se cumplen las reglas de negocio) un viaje. * @param idViaje Long Identificador del viaje a finalizar. * @return ViajeDTO El viaje referenciado, se haya podido finalizar o no, con su estado actual. */ ViajeDTO finalizarViaje(long idViaje); ViajeDTO addPasajero(long idPasajero, long idViaje); /** * Agrega una calificación al viaje. El modelo implementa la validación de que * el pasajero es efectivamente un pasajero del viaje y que éste ya está finalizado, * además de que el pasajero no haya realizado ya una calificación * previa para el mismo. * @param idViaje Long Identificador del viaje a calificar. * @param idPasajero Long Identificador del pasajero que realiza la calificación. * @param puntaje Integer Puntaje con el que califica el pasajero (1..5). * @param comentario String Comentario del pasajero. * @return CalificacionDTO La calificación creada. */ CalificacionDTO addCalificacion(long idViaje, long idPasajero, int puntaje, String comentario); ViajeDTO addViaje(long idDestino, long idOrigen, Date fecha, int cantidadPasajeros, double costo, long idConductor); }<file_sep>/src/main/java/bd2/Muber/dto/CiudadDTO.java package bd2.Muber.dto; import bd2.Muber.model.Ciudad; /** * * @author <NAME> * Representación (DTO) de la entidad Ciudad. * Los DTO son representaciones no persistentes de los objetos * del modelo que permiten trabajar en memoria fuera del ambiente * transaccional con objetos que se asemejan a los originales. * */ public class CiudadDTO { private String ciudad, provincia; private Long idCiudad; public CiudadDTO(Ciudad ciudad) { this.setIdCiudad(ciudad.getIdCiudad()); this.setCiudad(ciudad.getCiudad()); this.setProvincia(ciudad.getProvincia()); } public void setIdCiudad(Long idCiudad) { this.idCiudad = idCiudad; } public Long getIdCiudad() { return this.idCiudad; } public void setCiudad(String ciudad) { this.ciudad = ciudad; } public String getCiudad() { return this.ciudad; } public void setProvincia(String provincia) { this.provincia = provincia; } public String getProvincia() { return this.provincia; } @Override public String toString() { return this.getCiudad() + ", " + this.getProvincia(); } } <file_sep>/src/main/java/bd2/web/PasajeroController.java package bd2.web; import java.util.Date; import java.util.HashMap; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import bd2.Muber.services.impl.ServiceLocator; /** * * @author <NAME> * El controlador de pasajeros administra las llamadas a la API REST * relacionadas con los pasajeros de Muber. Permite listar todos los * pasajeros, crear uno nuevo, ver el detalle de un pasajero y cargar crédito. * */ @ControllerAdvice @RequestMapping("/pasajeros") @ResponseBody @EnableWebMvc public class PasajeroController extends DefaultController { /** * Obtiene la colección de todos los pasajeros registrados en Muber o bien * un arreglo vacío. * * @return String Representación de la colección de pasajeros, arreglo vacío si no existen pasajeros. */ @RequestMapping(value = "", method = RequestMethod.GET, produces = "application/json", headers = "Accept=application/json") public String pasajeros() { return jsonResponse(true, ServiceLocator.getInstance().getPasajeroService().getPasajeros()); } /** * Busca un pasajero con el identificador enviado por parámetro GET * (HTTP query pasajeroId) y devuelve su representación JSON. * Si no se encuentra un pasajero el resultado será OK + objeto vacío. * * @param pasajeroId Long ID del pasajero cuyos datos se desean mostrar. * @return String Representación en formato JSON del pasajero (objeto vacío en caso de no existir). */ @RequestMapping(value = "detalle", method = RequestMethod.GET, produces = "application/json", headers = "Accept=application/json", params = { "pasajeroId" }) public String detalle(@RequestParam(value = "pasajeroId") Long pasajeroId) { return jsonResponse(true, ServiceLocator.getInstance().getPasajeroService().getPasajero(pasajeroId)); } /** * Suma el crédito indicado al pasajero cuyo identificador también se indica * por parámetro en el cuerpo de la petición PUT con formato JSON: * {pasajeroId:Long, monto:Double} * * @param parametros String representación JSON del identificador de pasajero y del monto a cargar. * @return String Representación JSON del pasajero modificado o bien un mensaje de error. */ @RequestMapping(value = "cargarCredito", method = RequestMethod.PUT, produces = "application/json", headers = "Accept=application/json") public String cargarCredito(@RequestBody HashMap<String, String> parametros){ try { return jsonResponse(true, ServiceLocator.getInstance().getPasajeroService().acreditar( Long.parseLong(parametros.get("pasajeroId")), Double.parseDouble(parametros.get("monto")))); } catch (Exception x) { return jsonResponse(false, x.getMessage()); } } /** * Crea un nuevo pasajero con los datos pasados por parámetros en el cuerpo * de la petición POST con el formato: * atributo1=valor1&atributo2=valor2&...&atributoN=valorN * * @param nombre String Nombre del pasajero a crear. * @param password String <PASSWORD>. * @param fechaIngreso String Fecha de alta en el sistema con formato YYYY-MM-DD. * @param creditoInicial Double Crédito inicial que dispone el pasajero. * @return String Representación JSON del pasajero agregado a Muber o bien un mensaje de error. */ @RequestMapping(value = "nuevo", method = RequestMethod.POST, produces = "application/json") public String nuevo(@RequestParam String nombre, @RequestParam String password, @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date fechaIngreso, @RequestParam Double creditoInicial) { try { return jsonResponse(true, ServiceLocator.getInstance().getPasajeroService().addPasajero(nombre, password, fechaIngreso, creditoInicial)); } catch (Exception x) { return jsonResponse(false, x.getMessage()); } } } <file_sep>/src/main/java/bd2/Muber/dto/MuberDTO.java package bd2.Muber.dto; import java.util.Collection; import java.util.HashSet; import bd2.Muber.model.Ciudad; import bd2.Muber.model.Conductor; import bd2.Muber.model.Muber; import bd2.Muber.model.Pasajero; import bd2.Muber.model.Viaje; /** * * @author <NAME> * Representación (DTO) de la entidad Muber. * Los DTO son representaciones no persistentes de los objetos * del modelo que permiten trabajar en memoria fuera del ambiente * transaccional con objetos que se asemejan a los originales. * */ public class MuberDTO { private Collection<Long> conductores; private Collection<Long> pasajeros; private Collection<Long> viajes; private Collection<Long> ciudades; private Long idMuber; public MuberDTO(Muber muber) { this.setIdMuber(muber.getIdMuber()); this.conductores = new HashSet<Long>(); for(Conductor conductor: muber.getConductores()) { this.addViaje(conductor.getIdUsuario()); } this.pasajeros = new HashSet<Long>(); for(Pasajero pasajero: muber.getPasajeros()) { this.pasajeros.add(pasajero.getIdUsuario()); } this.viajes = new HashSet<Long>(); for(Viaje viaje: muber.getViajes()) { this.viajes.add(viaje.getIdViaje()); } this.ciudades = new HashSet<Long>(); for(Ciudad ciudad: muber.getCiudades()) { this.addCiudad(ciudad.getIdCiudad()); } } public void setIdMuber(Long idMuber) { this.idMuber = idMuber; } public Long getIdMuber() { return this.idMuber; } public void setConductores(Collection<Long> conductores) { this.conductores = conductores; } public Collection<Long> getConductores() { return this.conductores; } public void setPasajeros(Collection<Long> pasajeros) { this.pasajeros = pasajeros; } public void addViaje(Long v) { this.viajes.add(v); } public Collection<Long> getPasajeros() { return this.pasajeros; } public void setViajes(Collection<Long> viajes) { this.viajes = viajes; } public Collection<Long> getViajes() { return this.viajes; } public Collection<Long> getCiudades() { return this.ciudades; } public void setCiudades(Collection<Long> ciudades) { this.ciudades = ciudades; } public void addCiudad(Long c) { this.ciudades.add(c); } }
379533fa0e1ec1894386812d999c6c3954e4e6ea
[ "Java", "Shell", "INI" ]
18
Java
ruskofulanito/bbdd2
5eff58173bbb90e65c7b29951559926fb1b01391
e5d0c09c3a49fd654c6f2c666008eb102ecb9bc4
refs/heads/master
<repo_name>ridgelab/ExtRamp<file_sep>/ExtRamp.py #! /usr/bin/env python3 ''' This program is intended to extract a ramp of slowly translated codons from the beginning of a gene sequence (DNA or RNA). ''' import statistics from statistics import mean,median import numpy as np from scipy.stats import gmean, hmean from math import exp, log, sqrt,ceil import gzip import csv import argparse import sys import re from multiprocessing import Pool, freeze_support def makeArgParser(): parser = argparse.ArgumentParser(description='Extract the individual Ramp sequences from a collection of genes') parser.add_argument('-i', '--input', type=str, required=True, help='(input) Required fasta file containing gene sequences (.gz or .gzip for gzipped)') parser.add_argument('-a', '--tAI', type=str, help='(input) csv file containing the species tAI values') parser.add_argument('-u', '--rscu', type=str, help='(input) fasta file used to compute relative synonymous codon usage and relative adaptiveness of codons') parser.add_argument('-o', '--ramp', type=str, help='(output) fasta file to write ramp sequences to') parser.add_argument('-v', '--verbose', action="store_true", help='flag to print progress to standard error') parser.add_argument('-l', '--vals', type=str, help='(output) csv file to write tAI/relative adaptiveness values for ribosome-smoothed efficiency at each window') parser.add_argument('-p', '--speeds', type=str, help='(output) speeds file to write tAI/relative adaptiveness values for each position in the sequence from the codon after the start codon to the codon before the stop codon. Format: Header newline list of values') parser.add_argument('-n', '--noRamp', type=str, help='(output) txt file to write the gene names that contained no ramp sequence') parser.add_argument('-z', '--removedSequences', default = None, type=str, help='(output) Write the header lines that are removed (e.g., sequence not long enough or not divisible by 3) to output file') parser.add_argument('-x', '--afterRamp', type=str, required=False, help='(output) fasta file containing gene sequences after the identified ramp sequence') parser.add_argument('-t', '--threads', type=int, help='the number of threads you want to run, default = all') parser.add_argument('-w', '--window', type=int, default = 9, help='the ribosome window size in codons, default = 9 codons') parser.add_argument('-s', '--stdev', type=float, default = -1.0, help='the number of standard deviations below the mean the cutoff value to be included as a ramp for gmean and mean. Not used by default') parser.add_argument('-d', '--stdevRampLength', type=float, default = -1.0, help='the number of standard deviations used in the quality check step (lengths of the ramp sequences). Not done by default') parser.add_argument('-m', '--middle', type=str, default = 'hmean', help='the type of statistic used to measure the middle (consensus) efficiency. Options: hmean, gmean, mean, median') parser.add_argument('-r', '--rna', action="store_true", help='flag for RNA sequences. Default: DNA') parser.add_argument('-f', '--determine_cutoff', action="store_true", help='flag to determine outlier percentages for mean cutoff based on species FASTA file. Default: local minimum in first 8 percent of gene') parser.add_argument('-c', '--cutoff', type=int, default = 8, help='Cutoff for where the local minimum must occur in the gene for a ramp to be calculated. If --determine_cutoff (-f) is used, then this value may change. Is not used if standard deviations are set.') parser.add_argument('-e', '--determine_cutoff_percent', type=str, default = "outlier", help='Cutoff for determining percent of gene that is in an outlier region. Used in conjunction with -f. Default is true outliers. Other options include numbers from 0-99, which indicate the region of a box plot. For instance, 75 means the 75th quartile or above.') parser.add_argument('-q', '--seqLength', type=float, default = 300, help='Minimum nucleotide sequence length. Default is 100 amino acids * 3 = 300 nucleotides') args = parser.parse_args() if args.middle == 'hmean' and args.stdev >=0: sys.stderr.write("Warning: hmean cannot be used with standard deviations. -s will be ignored.\n") args.stdev = -1.0 if (args.window *3) >args.seqLength: args.seqLength = args.window*3 +1 return args def readSeqFile(args, inputFile): """ Input: System arguments Returns an array of tuples (Name of sequence, Sequence) created from the input fasta file. Sequences which are not divisible by three or have non-standard nucleotide characters are removed. """ seqArray = [] curSeqName = '' curSeq = '' inFile = "" stop = {'TAA','TGA','TAG'} if inputFile.endswith('.gz') or inputFile.endswith('.gzip'): inFile = gzip.open(inputFile,'rt') else: inFile = open(inputFile, 'r') badSeq = 0 removedSeq = "" if args.removedSequences and inputFile==args.input: removedSeq = open(args.removedSequences,'w') for line in inFile: if line[0] == '>': if curSeq != '': if args.rna: curSeq.replace('U','T') match = re.search('[^ATCG]',curSeq) if match == None and len(curSeq)%3 ==0 and len(curSeq) >=args.seqLength: startCodon = curSeq[0:3] curSeq = curSeq[3:] #remove start codon stopCodon = curSeq[-3:] curSeq = curSeq[0:-3] #remove stop codon seqArray.append((curSeqName,curSeq,startCodon,stopCodon)) else: if args.removedSequences and inputFile == args.input: removedSeq.write(curSeqName +"\n") badSeq += 1 curSeqName = line.strip('\n') curSeq = '' else: curSeq += line.strip('\n').upper() if args.rna: curSeq.replace('U','T') match = re.search('[^ATCG]',curSeq) if match == None and len(curSeq)%3 ==0 and len(curSeq) >=args.seqLength: startCodon = curSeq[0:3] curSeq = curSeq[3:] #remove start codon stopCodon = curSeq[-3:] curSeq = curSeq[0:-3] #remove stop codon seqArray.append((curSeqName,curSeq,startCodon,stopCodon)) else: badSeq += 1 if badSeq > 0 and args.verbose and inputFile==args.input: sys.stderr.write( '\n' + str(badSeq)+ ' sequences contained non-standard nucleotide characters or were not divisible by three, so were removed!\n\n') inFile.close() if args.removedSequences and inputFile==args.input: removedSeq.close() return seqArray def calcCodonSpeeds(seqArray): """ Input: an array of tuples (header, sequence) of genes. Returns a dictionary of codons to relative translation Speed. It calculates the codon proportions using all of the gene sequences and then uses those values to determine translation speed. Uses metrics from CAI values Relative Synonymous Codon Usage (RSCU) and Relative adaptiveness of codon (w) are calculated based on equations presented in https://www.ncbi.nlm.nih.gov/pmc/articles/PMC340524/pdf/nar00247-0410.pdf """ codonToSpeed = {} totalCodons = 0 codonGroups = AAtoCodonsDict() for elem in seqArray: codonToSpeed, totalCodons = countCodons(elem[1],codonToSpeed,totalCodons) for aa in codonGroups: totalCounts = 0 numCodons = 0 for codon in aa: numCodons +=1 if not codon in codonToSpeed: codonToSpeed[codon] = 0.0001 #codonToSpeed has count of codon usages continue totalCounts += codonToSpeed[codon] maxRSCU = 0.0 for codon in aa: if numCodons ==0 or totalCounts==0: rscu = 0.0001 codonToSpeed[codon] = rscu #codonToSpeed has RSCU continue rscu = codonToSpeed[codon] / ((1.0/numCodons)*totalCounts) if rscu > maxRSCU: maxRSCU = rscu codonToSpeed[codon] = rscu #codonToSpeed has RSCU for codon in aa: if maxRSCU == 0: w = 0.0001 codonToSpeed[codon] = w #codonToSpeed has relative adaptiveness of codons continue w = codonToSpeed[codon] / maxRSCU #w=relative adaptiveness of codons codonToSpeed[codon] = w #codonToSpeed has relative adaptiveness of codons return codonToSpeed def csvToDict(filename): """ Input: path to a csv file with tAI values where the first row is a list of codons and the second row is the list of tAI values for those codons. The csv file could also have a codon and its tAI value on the same line, each codon separated by a new line. Returns a dictionary of codons to their tAI speed from the user provided tAI file. """ tempDict = {} try: with open(filename, newline='') as csvfile: reader = csv.reader(csvfile, delimiter= ' ') for row in reader: codon,tAI = row[0].split(',') if tAI == 0: tAI = 0.0001 tempDict[str(codon)] = float(tAI) except: with open(filename, newline='') as csvfile: reader = csv.reader(csvfile, delimiter= ',') count = 0 codonArray = [] for row in reader: if count%2 == 0: codonArray = row else: for i in range(len(row)): if float(row[i]) == 0: tempDict[codonArray[i]] = 0.0001 else: tempDict[codonArray[i]] = float(row[i]) count += 1 return tempDict def AAtoCodonsDict(): ''' returns a list of a list of codons that encode each amino acid. Groupings are in the following order (one letter code): I,L,V,F,M,C,A,G,P,T,S,Y,W,Q,N,H,E,D,K,R, ''' return [["ATT","ATC","ATA"],["CTT","CTC","CTA","CTG","TTA","TTG"],["GTT","GTC","GTA","GTG"],["TTT","TTC"],["ATG"],["TGT","TGC"],["GCT","GCC","GCA","GCG"],["GGT","GGC","GGA","GGG"],["CCT","CCC","CCA","CCG"],["ACT","ACC","ACA","ACG"],["TCT","TCC","TCA","TCG","AGT","AGC"],["TAT","TAC"],["TGG"],["CAA","CAG"],["AAT","AAC"],["CAT","CAC"],["GAA","GAG"],["GAT","GAC"],["AAA","AAG"],["CGT","CGC","CGA","CGG","AGA","AGG"]] def countCodons(sequence,codonToSpeed,totalCodons): """ Input: A DNA sequence Returns a dictionary of Codons to the total number of times the codon was found in all provided gene sequences. These are later used to find the proportions of codon usage (estimate speed of translation). Also returns the total number of codons. """ for i in range(0,len(sequence),3): if sequence[i:i+3] not in codonToSpeed: codonToSpeed[sequence[i:i+3]] = 0 totalCodons += 1 codonToSpeed[sequence[i:i+3]] += 1 return codonToSpeed, totalCodons def calcSeqSpeed(elem): """ Maps the gene name to an array of the tAI/speed values for the given sequence. Input: tuple (header, sequence) of a fasta record Output: A dictionary of seq name to a tuple (translational speed of each sequence, cutOffValue for rampSequence) """ seqToSpeed = {} seq = elem[1] speedArray = [] for index in range(0,len(seq),3): stopCodons = ['TAA','TAG','TGA'] if not seq[index:index+3] in stopCodons: speedArray.append( codonToSpeed[seq[index:index+3]]) else: speedArray.append(0.0001) seqToSpeed[elem[0]] = tuple(speedArray) return seqToSpeed def createSpeedsDict(result): """ Returns a dictionary of all the sequence names to the array of their tAI/speed values. """ seqToSpeed = {} for elem in result: seqToSpeed.update(elem) return seqToSpeed def findStDev(array,mean): ''' Calculates geometric standard deviation from array and geometric mean. ''' if args.middle != 'gmean': #If the user specified other mean return statistics.stdev(array,mean) ##for gMean summation = 0 for item in array: summation += (log(item/mean))**2 return exp(sqrt(summation/len(array))) def calcRiboSpeed(speeds): """ Returns the average of the tAI/speed values in the ribosomeWindow. """ if len(speeds)==0: return 0.0001 elif args.middle == 'hmean': return hmean(speeds) elif args.middle == 'gmean': return gmean(speeds) elif args.middle == 'mean': return statistics.mean(speeds) elif args.middle == 'median': return statistics.median(speeds) def writeSpeedsFile(speedSeqs): """ Writes the sequence speeds to a csv file. """ csvfile = open(args.vals, 'w', newline='') writer = csv.writer(csvfile, delimiter=',') writer.writerow(["seq", 'position', 'speed_value']) from tqdm import tqdm for item in tqdm(speedSeqs): for row in item: writer.writerow(row) csvfile.close() def findSpeeds(elem): """ Calculates the speeds for each sequence and returns them in a csv file format. """ csvLines = [] for i in range(len(seqToSpeed[elem[0]])-ribosomeWindowLength): riboSmoothedSpeed = middleFunc[args.middle](seqToSpeed[elem[0]][i:i+ribosomeWindowLength]) csvLines.append([elem[0],i+1 ,riboSmoothedSpeed]) #i +1 because start codon was taken away return csvLines def outputRampSeqs(rampSeqs,args): """ Calls isolateRamp function and prints the ramp sequences to the terminal or a fasta file Input: tuple of header,sequence """ totalSeqs = len(rampSeqs) noRampFile = "" if args.stdevRampLength >=0: rampSeqs = qualityCheck(rampSeqs,args.stdevRampLength) outPut = sys.stdout if args.ramp: outPut = open(args.ramp, 'w') if args.afterRamp: afterRampFile = open(args.afterRamp,'w') if args.noRamp and args.determine_cutoff: noRampFile = open(args.noRamp, 'a') elif args.noRamp: noRampFile = open(args.noRamp, 'w') count = 0 for line in rampSeqs: if not args.afterRamp: if not line.startswith('None'): count += 1 outPut.write(line) elif args.noRamp: noRampFile.write(line[4:]) else: if not line[0].startswith('None'): count += 1 outPut.write(line[0]) afterRampFile.write(line[1]) elif args.noRamp: noRampFile.write(line[0][4:]) outPut.close() if args.verbose: sys.stderr.write("\n" + str(count) + " Ramp Sequences found\n") if args.noRamp: noRampFile.close() def isolateRamp(record): """ Calculates the cut off point for the individual ramp sequences and returns them. """ mean = middleFunc[args.middle](seqToSpeed[record[0]]) stdev = findStDev(seqToSpeed[record[0]],mean) cutOffVal = mean - (args.stdev*stdev) i = 0 while calcRiboSpeed(seqToSpeed[record[0]][i:i+ribosomeWindowLength]) < cutOffVal and (i+ribosomeWindowLength) <= len(seqToSpeed[record[0]]): i += 1 if i == 0: if not args.afterRamp: return 'None' + record[0] + '\n' else: return tuple(['None' + record[0] + '\n']) if not args.afterRamp: return record[0] + '\n' + record[2] + record[1][:(i+ribosomeWindowLength)*3] + '\n' else: return tuple([record[0] + '\n' + record[2] + record[1][:(i+ribosomeWindowLength)*3] + '\n',record[0] + '\n' + record[1][(i+ribosomeWindowLength)*3:] +record[3]+ '\n']) def isolateRampHmean(record): speeds = seqToSpeed[record[0]] mean = hmean(speeds) windowMeans = [] for z in range(len(speeds)-ribosomeWindowLength): windowMeans.append(middleFunc[args.middle](speeds[z:z+ribosomeWindowLength])) bestMean = min(windowMeans) pos = [index for index, value in enumerate(windowMeans) if value == bestMean] #ensures that all local minima are included perc = float(ceil(100*(pos[0]/float(len(windowMeans))))) #Percentages x 100 if perc <=percentThatIsRamp: i =pos[0] for x in range(i,len(windowMeans)): if windowMeans[x] >= mean: if not args.afterRamp: return record[0] + '\n' + record[2] + record[1][:(x+ribosomeWindowLength)*3] + '\n' else: return tuple([record[0] + '\n' + record[2] + record[1][:(x+ribosomeWindowLength)*3] + '\n',record[0] + '\n' + record[1][(x+ribosomeWindowLength)*3:] +record[3]+ '\n']) if not args.afterRamp: return 'None' + record[0] + '\n' else: return tuple(['None' + record[0] + '\n']) def qualityCheck(rampSeqs,numStDev): """ Look at the lengths of the ramp sequences and only use those that are within numStDev standard deviations of the mean length. The distribution is right skewed so the data is log transformed. return the list of rampSeqs with the extremes removed """ lengths = [] tempSeqs = [] for i in range(len(rampSeqs)): if not rampSeqs[i].startswith('None'): ramp = rampSeqs[i].split('\n') lengths.append(log(len(ramp[1]))) tempSeqs.append(i) if len(lengths) == 0: if args.verbose: sys.stderr.write('NO RAMP SEQUENCES FOUND\n') sys.exit() if len(lengths) == 1: return rampSeqs meanLen = statistics.mean(lengths) std = statistics.stdev(lengths, meanLen) removed = 0 for index in tempSeqs: ramp = rampSeqs[index].split('\n') if log(len(ramp[1])) < meanLen - (numStDev * std) or log(len(ramp[1])) > meanLen + (numStDev * std): newLine = 'None' + ramp[0] + '\n' rampSeqs[index] = newLine removed +=1 if args.verbose: sys.stderr.write(str(removed) + " sequences removed by standard deviation check of all ramp sequences (-d option).\n") return rampSeqs def getBottleneck(header): allPercents = [] speeds = seqToSpeed[header] windowMeans = [] for i in range(len(speeds)-args.window): windowMeans.append(middleFunc[args.middle](speeds[i:i+args.window])) bestMean = min(windowMeans) pos = [index for index, value in enumerate(windowMeans) if value == bestMean] #ensures that all local minima are included for p in pos: perc = float(ceil(100.0*((p+1)/float(len(windowMeans))))) #Percentages x 100 allPercents.append((perc,header,p)) return allPercents def getCutoffValue(counts): ''' Input: a dictionary of header lines -> tuple array of codon efficiency values for each codon Output: Locations that have more local minimum codon efficiencies and are outliers, starting from the front of the gene. If no outliers exist, return 0. ''' instances = list(counts.values()) instances = np.array(instances) upper = 0 if args.determine_cutoff_percent.isdigit(): upper = np.percentile(instances,int(args.determine_cutoff_percent)) else: q1= np.percentile(instances,25) q3= np.percentile(instances,75) upper = q3 + (1.5*(q3-q1)) outliers = set() for percent in instances: if percent >=upper: outliers.add(percent) if args.verbose: sys.stderr.write("The following percentages exceed the threshold (" +args.determine_cutoff_percent +"):") for x in range(1,101): if counts[x] in outliers: sys.stderr.write(" " +str(x)) sys.stderr.write("\n") for x in range(1,101): #if x in outliers: if counts[x] in outliers: continue return (x-1) #-1 because it goes 1 past the last outlier. Divide by 100 to turn percent into decimal return 0 def init_pool(speedFromCodon): #Necessary for Windows multiprocessing global codonToSpeed codonToSpeed=speedFromCodon def init_pool2(speedFromSeq,lengthOfRibosome,funcMiddle,arrgs,percentRamp): #Necessary for Windows multiprocessing global seqToSpeed global ribosomeWindowLength global middleFunc global args global percentThatIsRamp ribosomeWindowLength=lengthOfRibosome seqToSpeed=speedFromSeq middleFunc=funcMiddle args=arrgs percentThatIsRamp=percentRamp if __name__ == '__main__': freeze_support() args = makeArgParser() noRampFile = "" ribosomeWindowLength = args.window middleFunc={'hmean':hmean,'gmean':gmean,'mean':mean,'median':median} if not args.middle in middleFunc: sys.stderr.write("args.middle must be one of the following options:\nhmean\ngmean\nmean\nmedian\n") sys.exit() if args.verbose: sys.stderr.write('Reading Sequences...\n') seqArray = readSeqFile(args, args.input) if args.verbose: sys.stderr.write("Total Sequences: " +str(len(seqArray)) + '\n') if len(seqArray) ==0: sys.stderr.write("No sequences passed the initial filter. Ramp sequences were unable to be calculated.\n") sys.exit() codonToSpeed = {} if args.tAI: codonToSpeed = csvToDict(args.tAI) else: if args.verbose: sys.stderr.write('Calculating Codon Speeds...\n') if args.rscu: seqArray_rscu = readSeqFile(args,args.rscu) codonToSpeed = calcCodonSpeeds(seqArray_rscu) else: codonToSpeed = calcCodonSpeeds(seqArray) if args.verbose: sys.stderr.write('Calculating Sequence Speeds...\n') p = Pool(processes=args.threads,initializer=init_pool,initargs=(codonToSpeed,)) seqToSpeed = createSpeedsDict(p.map(calcSeqSpeed,seqArray)) ##header -> tuple of array of codon efficiency values if args.speeds: if args.verbose: sys.stderr.write("Writing speeds data to file.\n") output_speeds = open(args.speeds,'w') for header in seqToSpeed: output_speeds.write(header + "\n" + str(seqToSpeed[header])[1:-1] + "\n") output_speeds.close() #create a consensus speed to determine average speed as a cutoff value for the ramp sequence and smooth consensus with ribosomeWindowLength percentThatIsRamp =args.cutoff if args.determine_cutoff: if args.verbose: sys.stderr.write('Determining Cutoff Percentage from Ramp Sequences...\n') p = Pool(processes=args.threads,initializer=init_pool2,initargs=(seqToSpeed,ribosomeWindowLength,middleFunc,args,percentThatIsRamp)) bottlenecks = p.map(getBottleneck,list(seqToSpeed.keys())) counts = {} for percents in bottlenecks: for p in percents: place = int(p[0]) if not place in counts: counts[place] = 0 counts[place] +=1 for perc in range(1,101): if not perc in counts: counts[perc] = 0 percentThatIsRamp = getCutoffValue(counts) if args.verbose: sys.stderr.write('\tThe cutoff percentage is ' +str(percentThatIsRamp) + '%\n') sys.stderr.write('Isolating Ramp Sequences...\n') rampSeqs = [] posOfRamp = {} for percents in bottlenecks: for p in percents: place = int(p[0]) if place <= percentThatIsRamp: header = p[1] pos = p[2] speeds = seqToSpeed[header] seqMean = middleFunc[args.middle](speeds) for i in range(pos,len(speeds)-args.window): windowMean =middleFunc[args.middle](speeds[i:i+args.window]) if windowMean >= seqMean: posOfRamp[header] = i-1 break if args.noRamp: noRampFile = open(args.noRamp,'w') for record in seqArray: if record[0] in posOfRamp: if not args.afterRamp: rampSeqs.append(record[0] + '\n' + record[2] + record[1][:(posOfRamp[record[0]]+ribosomeWindowLength)*3] + '\n') else: rampSeqs.append(tuple([record[0] + '\n' + record[2] + record[1][:(posOfRamp[record[0]]+ribosomeWindowLength)*3] + '\n',record[0] + '\n' + record[1][(posOfRamp[record[0]]+ribosomeWindowLength)*3:] +record[3]+ '\n'])) elif args.noRamp: noRampFile.write(record[0] + '\n') if args.noRamp: noRampFile.close() outputRampSeqs(rampSeqs,args) #output speed values in a csv file if indicated p = Pool(processes=args.threads,initializer=init_pool2,initargs=(seqToSpeed,ribosomeWindowLength,middleFunc,args,percentThatIsRamp)) if args.vals: if args.verbose: sys.stderr.write('Writing Speeds File...\n') speedSeqs = p.map(findSpeeds, seqArray) writeSpeedsFile(speedSeqs) #write Ramp Sequence to a fasta file if not args.determine_cutoff: if args.verbose: sys.stderr.write('Isolating Ramp Sequences...\n') if args.stdev >=0: rampSeqs = p.map(isolateRamp, seqArray) outputRampSeqs(rampSeqs,args) else: rampSeqs = p.map(isolateRampHmean, seqArray) outputRampSeqs(rampSeqs,args)
f98e5c38a51b3e7c5de95a1680fa2a500d065418
[ "Python" ]
1
Python
ridgelab/ExtRamp
b4c15090f72d4ee1f83fd812fe7d57403693714e
586274ce4851f84443adae52e9b2bc929e66d61d
refs/heads/master
<file_sep>#define CHAMPON_CLI_DEBUG #define CHAMPON_LOG_DEBUG #ifdef CHAMPON_LOG_DEBUG #define filename(x) strrchr(x,'/')?strrchr(x,'/')+1:x #define chp_d(_fmt_, ...) \ wmprintf(_fmt_ "\r\n", ##__VA_ARGS__) #define chp_entry_d(_fmt_, ...) \ wmprintf("[%s(%d) - %s] " _fmt_ "\r\n", filename(__FILE__), __LINE__, __func__, ##__VA_ARGS__) #else #define chp_d(...) #define chp_entry_d(...) #endif
97b23e30947d74879cb1d7b03d1dd59f79cd80ed
[ "C" ]
1
C
benjamin2mark/DEBUG
6413cf78e2078fb3bd7007be0038f8a4f1d7e7ca
30dda40448572c62252684b8604eaee952d9fa4c
refs/heads/main
<repo_name>AmiyaDas/BusinessVizualize<file_sep>/src/components/Header/Header.js import React from 'react' import styles from './Header.module.scss' import { Navbar, Nav } from 'react-bootstrap' export default function Header({ menuItems }) { return ( <Navbar expand="lg" sticky="top" className={styles.navbar}> <Navbar.Brand href="/"><b>Business </b><span className="text-primary">VISUALIZE</span></Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="ml-auto"> {menuItems.map((d, i) => { return ( <Nav.Link key={'item' + i} href={d.href}> {d.label} </Nav.Link> ) })} </Nav> </Navbar.Collapse> </Navbar> ) }
ccaea373fad7ec1688c3cf37455a8916dd51cea5
[ "JavaScript" ]
1
JavaScript
AmiyaDas/BusinessVizualize
4f20b71f02c3a363fe46c1f78eb4d44f07b700da
33e6bc0a054f7805825af273c905523746764f3b
refs/heads/master
<file_sep>import React from 'react' import { Link } from 'react-router-dom' import { connect } from 'react-redux' import { findUserById } from '../../selectors/user' import { findPostByPostId } from '../../selectors/Post' import { startGetPostComments, resetComments } from '../../action/comment' class ShowUserPost extends React.Component{ componentWillUnmount(){ console.log('component unmounted') this.props.dispatch(resetComments()) } render(){ if(this.props.comments.length == 0){ const postId = this.props.match.params.id this.props.dispatch(startGetPostComments(postId)) } return( <div className="card"> <div className="card-header"> <h3>USER NAME : {this.props.user.name} </h3> <h4>TITLE : {this.props.post.title} </h4> </div> <div className="card-body"> <h3>BODY : <br />{this.props.post.body}</h3> </div> <div className="card-footer"> <h4>COMMENTS: </h4> <ul> { this.props.comments.map((comment) => { return <li key = {comment.id}>{comment.body}</li> }) } </ul> </div> <Link to = {`/users/${this.props.user.id}`}>More Posts From Author: {this.props.user.name}</Link> </div> ) } } const mapStateToProps = (state, props) => { const postId = props.match.params.id const post = findPostByPostId(state.posts, postId) const userId = post.userId return{ user: findUserById(state.users, userId), post, comments: state.postComments } } export default connect(mapStateToProps)(ShowUserPost)<file_sep># Blog-UI Blog-UI is a Front-End centric project. Made using React-Redux, it is fast and elegant. It is fetching data from the JSONPlaceholder site. Designing tools used in this project are Reactstrap and bootstrap. ## Dependencies * axios: "^0.19.2", // npm install --save axios * bootstrap: "^4.4.1", // npm install bootstrap * react: "^16.12.0", // npm i react * react-dom: "^16.12.0", * react-redux: "^7.1.3", // npm install react-redux * react-router-dom: "^5.1.2", // npm install --save react-router-dom * react-scripts: "3.3.0", * redux: "^4.0.5", // npm i redux * redux-thunk: "^2.3.0" // npm i redux thunk<file_sep>import React from 'react' import { Link } from 'react-router-dom' import { connect } from 'react-redux' import { startGetUsers } from '../../action/user' function Users(props){ if(props.users.length == 0){ props.dispatch(startGetUsers()) } return( <div className="row"> <div className="col-md-6 offset-md-3"> <h2>Users List - {props.users.length}</h2> <ul className="list-group"> { props.users.map((user) => { return ( <li key = {user.id} className="list-group-item"><Link to = {`/users/${user.id}`}>{user.name}</Link></li> ) }) } </ul> </div> </div> ) } const mapStateToProps = (state) => { return{ users: state.users } } export default connect(mapStateToProps)(Users)<file_sep>import React from 'react' import axios from 'axios' import { Link } from 'react-router-dom' import { connect } from 'react-redux' import { findUserById } from '../../selectors/user' import { findPostsByUserId } from '../../selectors/Post' import { startGetPosts } from '../../action/post' class ShowUserPage extends React.Component{ render(){ if(this.props.userPosts.length == 0){ const id = this.props.match.params.id this.props.dispatch(startGetPosts(id)) } return( <div className="row"> <div className="col-md-7 offset-md-3"> <div className="card"> <div className="card-header"> <h3>USER NAME : {this.props.user.name}</h3> <h4>POSTS WRITTEN BY USER</h4> </div> <ul className="list-group list-group-flush"> { this.props.userPosts.map((post) => { return <li key = {post.id} className="list-group-item"><Link to = {`/posts/${post.id}`}>{post.title}</Link></li> }) } </ul> </div> </div> </div> ) } } const mapStateToProps = (state, props) => { const id = props.match.params.id return { user: findUserById(state.users, id), userPosts: findPostsByUserId(state.posts, id) } } export default connect(mapStateToProps)(ShowUserPage)<file_sep>export const findUserById = (users, uid) => { const user = users.find((user) => { return user.id == uid }) return user } <file_sep>import React from 'react' function Home(){ return( <div> <br /> <div className="jumbotron"> <h1 className="display-4">Welcome!</h1> <h4 className="lead">Hi, Thanks for visiting the site</h4> <hr className="my-4" /> <p>It uses utility classes for typography and spacing to space content out within the larger container.</p> <a className="btn btn-primary btn-lg" href="#" role="button">Learn more</a> </div> </div> ) } export default Home<file_sep>import axios from 'axios' export const setComments = (comments) => { return { type: 'SET_COMMENTS', payload: comments } } export const startGetPostComments = (postId) => { return (dispatch) => { axios.get(`https://jsonplaceholder.typicode.com/comments?postId=${postId}`) .then((response) => { const comments = response.data dispatch(setComments(comments)) }) .catch((err) => { console.log(err) }) } } export const resetComments = () => { return { type: 'RESET_COMMENTS' } }<file_sep>import React from 'react' import {BrowserRouter, Route, Link} from 'react-router-dom' import Home from './components/static/Home' import Users from './components/user/Users' import ShowUserPage from './components/user/ShowUserPage' import ShowUserPost from './components/user/ShowUserPost' import ShowPostPage from './components/post/ShowPostPage' function App(props){ return( <BrowserRouter> <div> <nav className="navbar navbar-expand-lg navbar-light bg-light"> <Link className="navbar-brand">Blogger-UI</Link> <ul className="nav justify-content-end"> <li className="nav-item"> <Link className="nav-link" to = "/home">Home</Link> </li> <li className="nav-item"> <Link className="nav-link" to = "/users">Users</Link> </li> <li className="nav-item"> <Link className="nav-link" to = "/posts">Posts</Link> </li> </ul> </nav> <div className="container"> <Route path = "/home" component = {Home} /> <Route path = "/users" component = {Users} exact = {true}/> <Route path = "/users/:id" component = {ShowUserPage} /> <Route path ="/posts" component = {ShowPostPage} exact = {true} /> <Route path = "/posts/:id" component = {ShowUserPost} /> </div> </div> </BrowserRouter> ) } export default App<file_sep>const postCommentsInitialState = [] const postCommentsReducer = (state = postCommentsInitialState, action) => { switch(action.type){ case 'SET_COMMENTS': { return [...action.payload] } case 'RESET_COMMENTS': { return postCommentsInitialState } default: { return [...state] } } } export default postCommentsReducer
33756b1133b3163941729d2bf9449ab7e463167f
[ "JavaScript", "Markdown" ]
9
JavaScript
Pratik-Saha/Blogger-UI
afffd26356696264569228f86abe378c454259c0
8d026f37f497c03613598a64fffb657cea67380d
refs/heads/master
<repo_name>RobLowe1992/logger-react<file_sep>/README.md # logger-react <file_sep>/Ch02/02_01/Start/src/App.js import React, { Component } from 'react' class App extends Component { render() { return ( <h1> Hello </h1> ) } } function myTestWrapper(WrappedComponent){ return class extends Component { render() { return ( <div style={{ backgroundColor: "blue" }} > <WrappedComponent/> </div> ) } } } App = myTestWrapper(App) export default App <file_sep>/Ch03/03_01/Start/src/App.js import React, { Component } from 'react' import loggify from "./loggify"; class App extends Component { // Static Props static displayName = 'App' constructor(props) { super(props) } oneFunction = () => { console.log("oneFunction") console.log(this.props) } useArrows = () => { console.log("useArrows works without binding") console.log(this.props) } render() { console.log(this.state) return ( <div> <button onClick={this.oneFunction} > test oneFunction </button> <button onClick={this.useArrows} > test useArrows </button> </div> ) } } App = loggify(App) export default App
3ed0bed7ae4b6eeaf85f6d2e48d624c76a1541a7
[ "Markdown", "JavaScript" ]
3
Markdown
RobLowe1992/logger-react
8e6be79aaf48438bf15d362771aab617998d4d41
fc0e915bf7252604475f347c81bb10126a5be1e9
refs/heads/master
<file_sep>#include <stdint.h> typedef struct { int16_t frequency; int16_t size; int16_t lowBorderFreq; int16_t highBorderFreq; }BandPassFilterStruct; int16_t BandPassFilter(BandPassFilterStruct s, int16_t* data); <file_sep>#include <fftfilter.h> int16_t BandPassFilter(BandPassFilterStruct s, int16_t* data) { int16_t i = 0; int16_t freqStep = s.frequency / s.size; int16_t lowIndx = s.lowBorderFreq / freqStep; int16_t highIndx = s.highBorderFreq / freqStep; int16_t size = highIndx - lowIndx; int16_t res = 0; for(i = lowIndx; i <= highIndx; i++) { res = res + data[i] / size; } return res; } /* int16_t BandPassFilter(BandPassFilterStruct s, q15_t* data) { u16 i = 0; u16 n = 0; u16 freqStep = s.frequency / s.size; u16 lowIndx = s.lowBorderFreq / freqStep; u16 highIndx = s.highBorderFreq / freqStep; if( (highIndx - lowIndx) % 2 != 0) highIndx++; u16 halfIndx = (highIndx - lowIndx) / 2 + lowIndx; u16 halfSize = (highIndx - lowIndx) / 2; q15_t res = 0; for(i = lowIndx; i <= halfIndx; i++, n++) data[i] = data[i] * (float32_t)n / halfSize; n = 0; for(i = halfIndx; i <= highIndx; i++, n++) data[i] = data[i] * ( 1 - (float32_t)n / halfSize ); for(i = lowIndx; i <= highIndx; i++) if(res < data[i]) res = data[i]; return res; } */ <file_sep>#include <stdint.h> #include <LightManager.h> #define CHANNELS_COUNT 8 #define SMOOTH 32 #define FALLOFF_MAX_VAL 16 typedef struct { int16_t avgValue; int16_t maxValue; int16_t minDiapSize; } ChannelDataStruct; static ChannelDataStruct chData[CHANNELS_COUNT]; static int16_t inited = 0; void LM_Init() { int16_t i; chData[0].minDiapSize = chData[1].minDiapSize = 500; chData[2].minDiapSize = chData[3].minDiapSize = 300; chData[4].minDiapSize = chData[5].minDiapSize = 200; for(i = 0; i < CHANNELS_COUNT; i++) { chData[i].avgValue = 0; chData[i].maxValue = 2400; } inited = 1; } int16_t LM_NextCalc(int16_t value, int16_t channel, float* result) { if(channel < 0 || channel > CHANNELS_COUNT) return -1; if(inited == 0) return -2; float res = 0; int16_t max = chData[channel].maxValue; int16_t avg = chData[channel].avgValue; if(avg < value) { avg = avg + (value - avg) / SMOOTH; if(max <= value) { max = value; res = 1; } else { res = 1 - (float)(max - value) / (max - avg); } } else { avg = avg - (avg - value) / SMOOTH; res = 0; } if(avg < value - chData[channel].minDiapSize) { max = max - FALLOFF_MAX_VAL; } chData[channel].maxValue = max; chData[channel].avgValue = avg; *result = res; return 0; } <file_sep>#include <stm32f4xx_conf.h> #include <arm_math.h> #include <pdm_filter.h> #include <LightManager.h> #include <fftfilter.h> #include <main.h> #define CHANNEL_COUNT 5 #define CHANNEL1 TIM3->CCR1 #define CHANNEL2 TIM3->CCR2 #define CHANNEL3 TIM3->CCR3 #define CHANNEL4 TIM3->CCR4 #define CHANNEL5 TIM4->CCR2 #define CHANNEL6 TIM4->CCR3 #define CHANNEL7 TIM4->CCR4 #define CHANBACKGR TIM4->CCR1 #define BACKGROUND_THRESHOLD 0 #define PERIOD 2560 #define PDM_BUFF_SIZE 64 #define PCM_BUFF_SIZE 16 #define FFT_SIZE 512 #define SPI_SCK_PIN GPIO_Pin_10 #define SPI_SCK_GPIO_PORT GPIOB #define SPI_SCK_GPIO_CLK RCC_AHB1Periph_GPIOB #define SPI_SCK_SOURCE GPIO_PinSource10 #define SPI_SCK_AF GPIO_AF_SPI2 #define SPI_MOSI_PIN GPIO_Pin_3 #define SPI_MOSI_GPIO_PORT GPIOC #define SPI_MOSI_GPIO_CLK RCC_AHB1Periph_GPIOC #define SPI_MOSI_SOURCE GPIO_PinSource3 #define SPI_MOSI_AF GPIO_AF_SPI2 #define SLP_REC_SPI_IRQHANDLER SPI2_IRQHandler q7_t SLP_Init(void); q7_t SLP_Start(void); q7_t SLP_Stop(void); q7_t SLP_GetHarmonicsAmplitude(float32_t* data, float32_t* dataOut, u32 fftLength); void SLP_GPIO_Init(void); void SLP_SPI_Init(void); void SLP_NVIC_Init(void); void SLP_PWM_Init(void); void SLP_LEDDispatcher(q15_t* data); u16 volume = 64; q15_t FFTBuffer1[FFT_SIZE]; q15_t FFTBuffer2[FFT_SIZE]; q15_t* pFFTFrontBuffer = 0; q15_t* pFFTBackBuffer = 0; u32 FFTBackBuffSize = 0; u8 FFTDataReady = 0; u8 needSwap = 0; u16 PDMBuffer[PDM_BUFF_SIZE]; u32 PDMBufferSize = 0; q7_t AudioRecInited = 0; u8 Error = 0; PDMFilter_InitStruct Filter; int main(void) { q31_t i; float32_t f_amplitude[FFT_SIZE]; q15_t amplitude[FFT_SIZE]; float32_t FFTData[FFT_SIZE]; pFFTFrontBuffer = FFTBuffer2; pFFTBackBuffer = FFTBuffer1; SystemInit(); SLP_Init(); SLP_Start(); while(Error == 0) { if(FFTDataReady == 1) { arm_q15_to_float(pFFTFrontBuffer, FFTData, FFT_SIZE); FFTDataReady = 0; SLP_GetHarmonicsAmplitude(FFTData, f_amplitude, FFT_SIZE); arm_float_to_q15(f_amplitude, amplitude, FFT_SIZE); SLP_LEDDispatcher(amplitude); } } SLP_Stop(); return 0; } void SLP_LEDDispatcher(q15_t* data) { q15_t res = 0; float value; BandPassFilterStruct bpFilter; bpFilter.frequency = 16000; bpFilter.size = FFT_SIZE; bpFilter.lowBorderFreq = 35; bpFilter.highBorderFreq = 85; res = BandPassFilter(bpFilter, data); LM_NextCalc(res, 1, &value); CHANNEL1 = value * PERIOD; bpFilter.lowBorderFreq = 100; bpFilter.highBorderFreq = 280; res = BandPassFilter(bpFilter, data); LM_NextCalc(res, 2, &value); CHANNEL2 = value * PERIOD; bpFilter.lowBorderFreq = 380; bpFilter.highBorderFreq = 880; res = BandPassFilter(bpFilter, data); LM_NextCalc(res, 3, &value); CHANNEL3 = value * PERIOD; bpFilter.lowBorderFreq = 1200; bpFilter.highBorderFreq = 2200; res = BandPassFilter(bpFilter, data); LM_NextCalc(res, 4, &value); CHANNEL4 = value * PERIOD; bpFilter.lowBorderFreq = 2500; bpFilter.highBorderFreq = 3700; res = BandPassFilter(bpFilter, data); LM_NextCalc(res, 5, &value); CHANNEL5 = value * PERIOD; bpFilter.lowBorderFreq = 4000; bpFilter.highBorderFreq = 5200; res = BandPassFilter(bpFilter, data); LM_NextCalc(res, 6, &value); CHANNEL6 = value * PERIOD; } q7_t SLP_GetHarmonicsAmplitude(float32_t* data, float32_t* dataOut, u32 fftLength) { q31_t i; float32_t sum; float32_t spec[fftLength * 2]; arm_rfft_instance_f32 S; arm_rfft_fast_instance_f32 inst; arm_cfft_radix4_instance_f32 S_CFFT; u32 ampSize; if( data == 0 || dataOut == 0) return -1; /* Окно хэннинга */ data[0] = 0; for(i = 1; i < fftLength; i++) { data[i] = data[i] * (0.54 - 0.46 * arm_cos_f32((2 * M_PI * i)/(fftLength-1))); } /* Инициализация RFFT */ if(arm_rfft_init_f32(&S, &S_CFFT, fftLength, 0, 1) != ARM_MATH_SUCCESS) return 1; //arm_rfft_fast_init_f32(&inst, FFT_SIZE); /* Выполнение RFFT */ arm_rfft_f32(&S, data, spec); //arm_rfft_fast_f32(&inst, data, spec, 0); /* Выделение амплитуд гармоник */ arm_cmplx_mag_f32(spec, dataOut, fftLength); ampSize = fftLength / 2; /* Устранение зеркаленной части */ for(i = ampSize; i < fftLength; i++) dataOut[i] = 0; dataOut[0] = dataOut[0] / ampSize; for(i = 1; i < ampSize; i++) dataOut[i] = dataOut[i] / ampSize; return 0; } void SLP_REC_SPI_IRQHANDLER(void) { u16 app; q31_t i; q15_t* swap; u16 PCMBuffer[PCM_BUFF_SIZE]; if (SPI_GetITStatus(SPI2, SPI_I2S_IT_RXNE) != RESET) { app = SPI_I2S_ReceiveData(SPI2); if(needSwap == 0) { PDMBuffer[PDMBufferSize++] = HTONS(app); if(PDMBufferSize >= PDM_BUFF_SIZE) { PDMBufferSize = 0; PDM_Filter_64_LSB((u8 *)PDMBuffer, (u16 *)PCMBuffer, volume, (PDMFilter_InitStruct *)&Filter); for(i = 0; i < PCM_BUFF_SIZE; i++) pFFTBackBuffer[FFTBackBuffSize++] = PCMBuffer[i]; if(FFTBackBuffSize >= FFT_SIZE) { FFTBackBuffSize = 0; needSwap = 1; } } } else if(FFTDataReady == 0) { swap = pFFTFrontBuffer; pFFTFrontBuffer = pFFTBackBuffer; pFFTBackBuffer = swap; FFTDataReady = 1; needSwap = 0; } } } int8_t SLP_Start(void) { if (AudioRecInited) { SPI_I2S_ITConfig(SPI2, SPI_I2S_IT_RXNE, ENABLE); I2S_Cmd(SPI2, ENABLE); return 0; } return 1; } int8_t SLP_Stop(void) { if (AudioRecInited) { I2S_Cmd(SPI2, DISABLE); return 0; } return 1; } int8_t SLP_Init(void) { if(AudioRecInited == 0) { RCC->AHB1ENR |= RCC_AHB1ENR_CRCEN; Filter.LP_HZ = 8000; Filter.HP_HZ = 10; Filter.Fs = 16000; Filter.Out_MicChannels = 1; Filter.In_MicChannels = 1; PDM_Filter_Init((PDMFilter_InitStruct *)&Filter); SLP_GPIO_Init(); SLP_NVIC_Init(); SLP_SPI_Init(); SLP_PWM_Init(); LM_Init(); AudioRecInited = 1; return 0; } return 1; } void SLP_PWM_Init(void) { GPIO_InitTypeDef GPIO_InitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; TIM_OCInitTypeDef TIM_OCInitStructure; uint16_t PrescalerValue = 0; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE); /* Compute the prescaler value */ PrescalerValue = (uint16_t) ((SystemCoreClock /2) / 28000000) - 1; /* Time base configuration */ TIM_TimeBaseStructure.TIM_Period = PERIOD; TIM_TimeBaseStructure.TIM_Prescaler = PrescalerValue; TIM_TimeBaseStructure.TIM_ClockDivision = 0; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure); TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure); /* PWM1 TIM3 Mode configuration: Channel1 */ TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_Pulse = PERIOD; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; TIM_OC1Init(TIM3, &TIM_OCInitStructure); TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable); /* PWM1 TIM3 Mode configuration: Channel2 */ TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_Pulse = PERIOD; TIM_OC2Init(TIM3, &TIM_OCInitStructure); TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable); /* PWM1 TIM3 Mode configuration: Channel3 */ TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_Pulse = PERIOD; TIM_OC3Init(TIM3, &TIM_OCInitStructure); TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Enable); /* PWM1 TIM3 Mode configuration: Channel4 */ TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_Pulse = PERIOD; TIM_OC4Init(TIM3, &TIM_OCInitStructure); TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Enable); /* PWM1 TIM4 Mode configuration: Channel1 */ TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_Pulse = 0; TIM_OC1Init(TIM4, &TIM_OCInitStructure); TIM_OC1PreloadConfig(TIM4, TIM_OCPreload_Enable); /* PWM1 TIM4 Mode configuration: Channel2 */ TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_Pulse = 0; TIM_OC2Init(TIM4, &TIM_OCInitStructure); TIM_OC2PreloadConfig(TIM4, TIM_OCPreload_Enable); /* PWM1 TIM4 Mode configuration: Channel3 */ TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_Pulse = 0; TIM_OC3Init(TIM4, &TIM_OCInitStructure); TIM_OC3PreloadConfig(TIM4, TIM_OCPreload_Enable); TIM_ARRPreloadConfig(TIM3, ENABLE); /* TIM3 enable counter */ TIM_Cmd(TIM3, ENABLE); TIM_ARRPreloadConfig(TIM4, ENABLE); /* TIM4 enable counter */ TIM_Cmd(TIM4, ENABLE); } void SLP_GPIO_Init(void) { GPIO_InitTypeDef GPIO_InitStructure; RCC_AHB1PeriphClockCmd(SPI_SCK_GPIO_CLK | SPI_MOSI_GPIO_CLK | RCC_AHB1Periph_GPIOD, ENABLE); GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Pin = SPI_SCK_PIN; GPIO_Init(SPI_SCK_GPIO_PORT, &GPIO_InitStructure); GPIO_PinAFConfig(SPI_SCK_GPIO_PORT, SPI_SCK_SOURCE, SPI_SCK_AF); GPIO_InitStructure.GPIO_Pin = SPI_MOSI_PIN; GPIO_Init(SPI_MOSI_GPIO_PORT, &GPIO_InitStructure); GPIO_PinAFConfig(SPI_MOSI_GPIO_PORT, SPI_MOSI_SOURCE, SPI_MOSI_AF); /* GPIOC Configuration: TIM3 CH1 (PC6) and TIM3 CH2 (PC7) */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7 ; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP ; GPIO_Init(GPIOC, &GPIO_InitStructure); GPIO_PinAFConfig(GPIOC, GPIO_PinSource6, GPIO_AF_TIM3); GPIO_PinAFConfig(GPIOC, GPIO_PinSource7, GPIO_AF_TIM3); /* GPIOB Configuration: TIM3 CH3 (PB0) and TIM3 CH4 (PB1) */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP ; GPIO_Init(GPIOB, &GPIO_InitStructure); GPIO_PinAFConfig(GPIOB, GPIO_PinSource0, GPIO_AF_TIM3); GPIO_PinAFConfig(GPIOB, GPIO_PinSource1, GPIO_AF_TIM3); /* GPIOD Configuration: TIM4 CH1 (PD12) and TIM4 CH2 (PD13) and TIM4 CH3 (PD14)*/ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP ; GPIO_Init(GPIOD, &GPIO_InitStructure); GPIO_PinAFConfig(GPIOD, GPIO_PinSource12, GPIO_AF_TIM4); GPIO_PinAFConfig(GPIOD, GPIO_PinSource13, GPIO_AF_TIM4); GPIO_PinAFConfig(GPIOD, GPIO_PinSource14, GPIO_AF_TIM4); } void SLP_SPI_Init(void) { I2S_InitTypeDef I2S_InitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE); SPI_I2S_DeInit(SPI2); I2S_InitStructure.I2S_AudioFreq = I2S_AudioFreq_32k; I2S_InitStructure.I2S_Standard = I2S_Standard_LSB; I2S_InitStructure.I2S_DataFormat = I2S_DataFormat_16b; I2S_InitStructure.I2S_CPOL = I2S_CPOL_High; I2S_InitStructure.I2S_Mode = I2S_Mode_MasterRx; I2S_InitStructure.I2S_MCLKOutput = I2S_MCLKOutput_Disable; I2S_Init(SPI2, &I2S_InitStructure); SPI_I2S_ITConfig(SPI2, SPI_I2S_IT_RXNE, ENABLE); } void SLP_NVIC_Init(void) { NVIC_InitTypeDef NVIC_InitStructure; NVIC_PriorityGroupConfig(NVIC_PriorityGroup_3); NVIC_InitStructure.NVIC_IRQChannel = SPI2_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); } <file_sep>void LM_Init(); int16_t LM_NextCalc(int16_t value, int16_t channel, float* result);
f724a29168cdd844730eb8d36b65d31139a9cb24
[ "C" ]
5
C
PavelS0/stm32f4DiscoverySLP
a44645e6891dffaa5b92cd375ff525471adbc342
c86bf76603de1a42a2d2c46849ba5dcef6631830
refs/heads/master
<repo_name>JaroslawPokropinski/Mobilne-Projekt-Zespo-owy-Backend<file_sep>/index.js const express = require('express'); const { json } = require('body-parser'); const checkToken = require('./authentication/auth'); const api = require('./routes/api'); const sec = require('./routes/sec'); const startSwagger = require('./configuration/swaggerConfig.js'); const app = express(); const port = process.env.PORT || 8080; startSwagger(app); app.use(json()); app.use('/api', api); app.use('/sec', checkToken, sec); // Use error handler // eslint-disable-next-line no-unused-vars app.use(function(err, req, res, _next) { // eslint-disable-next-line no-console console.error(err); res.status(400).send(err); }); app.listen(port); <file_sep>/authentication/passwordEncryptor.js const { genSalt, hash, compare } = require('bcrypt'); module.exports.cryptPassword = (password, callback) => { genSalt(10, function(err, salt) { if (err) return callback(err); hash(password, salt, function(err, _hash) { return callback(err, _hash); }); }); }; module.exports.comparePassword = (plainPass, hashword, callback) => { compare(plainPass, hashword, function(err, isPasswordMatch) { return err == null ? callback(null, isPasswordMatch) : callback(err); }); }; <file_sep>/README.md "# Mobilne-Projekt-Zespo-owy-Backend" <file_sep>/configuration/config.js module.exports = { secret: 'its very very secret secret' };
e061d3658d8ff13f1c47bf93ae756b5142cb4b5e
[ "JavaScript", "Markdown" ]
4
JavaScript
JaroslawPokropinski/Mobilne-Projekt-Zespo-owy-Backend
6ae476587ad9e3e0be7ea82e6e01c44b965a7313
5ae4276053897258fe531d7a6b02044e8b9e219d
refs/heads/main
<repo_name>whoiscnu/ansible-solace-collection<file_sep>/ReleaseNotes.md # Release Notes ## Version 1.7.0 JNDI Modules. **New Modules:** * **[solace_jndi_connection_factory](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_jndi_connection_factory.html)** * **[solace_get_jndi_connection_factories](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_jndi_connection_factories.html)** * **[solace_jndi_queue](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_jndi_queue.html)** * **[solace_get_jndi_queues](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_jndi_queues.html)** * **[solace_jndi_queues](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_jndi_queues.html)** * **[solace_jndi_topic](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_jndi_topic.html)** * **[solace_get_jndi_topics](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_jndi_topics.html)** * **[solace_jndi_topics](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_jndi_topics.html)** **Framework:** * None. **Maintenance:** * fixed pylint issues for new version **Known Issues:** * None. ## Version 1.6.0 Maintenance & Misc Enhancements **Modules** * **role:solace_broker_service** - added support for validate_certs option **Framework** * New optional flag for each module configuration: **validate_certs** - ability to switch off certification validation when using secure SEMP - usage: `validate_certs: [true|false], default=true` - test: `tests/single_broker/broker-cert` **Maintenance** * Upgrade to Ubuntu 20.04 for tests in Azure (bastion & roles) * Fixed linting errors for pylint version 2.10.2 * Fixed tests for new version of yq **Known Issues** * None. ## Version: 1.5.1 Client Profile & Bug Fixes **New Modules** * **[solace_cloud_client_profile](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_cloud_client_profile.html)** - separated client profile management into Solace Cloud API and SempV2 API **Updated Modules** * **[solace_client_profile](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_client_profile.html)** - removed support for Solace Cloud **Bug Fixes** * **[solace_client_profile](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_client_profile.html)** - settings value conversion from ansible to SEMP v2 API fixed * **[solace_service_authentication_ldap_profile](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_service_authentication_ldap_profile.html)** - set min sempv1 version to 9.1 ## Version: 1.5.0 Framework Enhancements & New Modules **New Modules** * **[solace_queue_subscriptions](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_queue_subscriptions.html)** * **[solace_get_acl_publish_topic_exceptions](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_acl_publish_topic_exceptions.html)** * **[solace_acl_publish_topic_exceptions](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_acl_publish_topic_exceptions.html)** * **[solace_get_acl_subscribe_topic_exceptions](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_acl_subscribe_topic_exceptions.html)** * **[solace_acl_subscribe_topic_exceptions](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_acl_subscribe_topic_exceptions.html)** * **[solace_get_acl_subscribe_share_name_exceptions](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_acl_subscribe_share_name_exceptions.html)** * **[solace_acl_subscribe_share_name_exceptions](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_acl_subscribe_share_name_exceptions.html)** * **[solace_get_acl_client_connect_exceptions](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_acl_client_connect_exceptions.html)** * **[solace_acl_client_connect_exceptions](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_acl_client_connect_exceptions.html)** * **[solace_get_bridge_remote_subscriptions](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_bridge_remote_subscriptions.html)** * **[solace_bridge_remote_subscriptions](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_bridge_remote_subscriptions.html)** **Updated Modules** * **[solace_gather_facts](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_gather_facts.html)** - added an argument: `use_sempv1_also: [true|false]`. defaults to `true`. if `true`, module uses sempv1 to get the virtual router name for a self-hosted service. **Framework** * **new: SolaceBrokerCRUDListTask** - manage lists of names (topics) as a 'transaction' **Devel** * **README, devel.requirements.txt** - remove install of ansible to allow for choice of version **Misc** * adapted import statements for new pylint version throughout **Documentation** - added a note that modules do not support check-mode ## Version: 1.4.4 Maintenance: Support for Ansible 2.11.x **Fixes** * **[solace_get_available](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_available.html)** - fixed using SSL with python >3.8 * **[solace_authorization_group](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_authorization_group.html)** - fixed url encoding of name. handles names containing ',' and '=' correctly, for example `cn=asct_auth_group_1,ou=Users,o=orgId,dc=domain,dc=com` ## Version: 1.4.3 Enhancements & New Features. **Module Enhancements:** * **[solace_service_authentication_ldap_profile](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_service_authentication_ldap_profile.html)** - added support for Solace Cloud API * **[solace_get_service_authentication_ldap_profiles](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_service_authentication_ldap_profiles.html)** - added support for Solace Cloud API * **[solace_vpn](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_vpn.html)** - added support for Solace Cloud API **New Features:** * **[support for reverse-proxy](https://solace-iot-team.github.io/ansible-solace-collection//tips-tricks-content/reverse-proxy.html)** - reverse proxy settings for self-hosted brokers - status: **Experimental** ## Version: 1.4.2 Enhancements of SEMP V1 Framework. Added support for writing get list modules that use the SEMP V1 API. **_Note: EXPERIMENTAL_** New modules: * **[solace_get_service_authentication_ldap_profiles](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_service_authentication_ldap_profiles.html)** - module uses the SEMP V1 API - Solace Cloud API not implemented ## Version: 1.4.1 Introduction of SEMP V1 Task Framework. Added support for writing modules that use the SEMP V1 API. **_Note: EXPERIMENTAL_** New modules: * **[solace_service_authentication_ldap_profile](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_service_authentication_ldap_profile.html)** - module uses the SEMP V1 API - Solace Cloud API not implemented ## Version: 1.4.0 New modules. * [**solace_get_authorization_groups**](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_authorization_groups.html) * [**solace_authorization_group**](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_authorization_group.html) * [**solace_get_authentication_oauth_providers**](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_authentication_oauth_providers.html) * [**solace_authentication_oauth_provider**](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_authentication_oauth_provider.html) ## Version: 1.3.3 Maintenance * **tests** - fixed tests for new broker release, sempv2 version 2.21 * **[Tips&Tricks:Setting & Retrieving Ansible-Solace Log Files](https://solace-iot-team.github.io/ansible-solace-collection/tips-tricks-content/logfile.html)** - fixed example playbook ## Version: 1.3.2 Examples for using Ansible Jump Host & Minor Module Enhancements/Maintenance. Documentation: * **[Tips&Tricks:Setting & Retrieving Ansible-Solace Log Files](https://solace-iot-team.github.io/ansible-solace-collection/tips-tricks-content/logfile.html)** - new. * **[Tips&Tricks:Working through a Remote ‘Bastion’ or ‘Jump’ Host](https://solace-iot-team.github.io/ansible-solace-collection/tips-tricks-content/bastion.html)** - new. Enhancements: * **solace_cloud_get_facts** - added function: `get_remoteFormattedHostInventory` - retrieve service inventory for remote bastion host Maintenance: * **solace_cloud_get_facts** - graceful handling of services in state=failed * **solace_cloud_service** - handling of retry on service creation failed: added wait between re-tries - added idempotent handling of eventBrokerVersion * **solace_api.SolaceCloudApi** - handling return settings as list and dict ## Version: 1.3.1 Maintenance. * **roles/solace_broker_service** - additional tests for correct passing of variables and extended error messages ## Version: 1.3.0 Feature Updates. _**Note: this release contains breaking changes.**_ * **Roles:** - [solace_broker_service](https://solace-iot-team.github.io/ansible-solace-collection/roles/solace_broker_service.html) - _note: breaking change: input & output arguments/variables changed._ - added example for secure SEMP setup - re-vamp of input vars & merging with defaults - changed output to include final inventory, docker compose settings, and docker logs * **Modules:** - [solace_get_available](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_available.html) - added functionality to a) check if broker is reachable, b) check if spool initialized - loops/waits until both are available (no loop required around module any more) * **Documentation** - New: [Working with Self-Signed Certificates](https://solace-iot-team.github.io/ansible-solace-collection/tips-tricks-content/certs.html) * **Framework** - added explicit exception handling for SSLErrors - added detailed traceback of Exceptions to log file - handling of `502:Bad Gateway` and `504:Gateway Timeout` for REST calls (retry: every 30 secs, 20 times max) ## Version: 1.2.1 Maintenance release. * **roles:** - [solace_broker_service](https://solace-iot-team.github.io/ansible-solace-collection/roles/solace_broker_service.html) - fixed remote vm support * **documentation** - [added bridges to tips & tricks](https://solace-iot-team.github.io/ansible-solace-collection/tips-tricks.html) * **tests** - dmr: fixed timing issues and host name mismatch - docs: added linkcheck to tests ## Version: 1.2.0 Addition of modules to manage replay of messages. _**Note: this release contains minor breaking changes.**_ #### New Modules * config: - [solace_replay_log](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_replay_log.html) * action: - [solace_replay_log_trim_logged_msgs](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_replay_log_trim_logged_msgs.html) - [solace_queue_start_replay](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_queue_start_replay.html) - [solace_queue_cancel_replay](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_queue_cancel_replay.html) * get list - [solace_get_replay_logs](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_replay_logs.html) #### Updated Modules * facts: - [solace_get_facts](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_facts.html) - standardized the output for Solace Cloud and self-hosted brokers - _note: breaking change: may require minor adjustment of playbooks evaluating response._ * get list: - _note: breaking change: requires minor adjustment of playbooks evaluating response._ - all get object list modules - config & monitor apis: - contains new dictionary: data {} - monitor api: - contains additional dictionary: collections {} #### Known Issues * Api calls fail on response 504: Bad Gateway * module: solace_get_available - does not check if spool is available for self-hosted brokers * ansible checkmode not implemented ## Version: 1.1.0 Refactor framework to streamline module interfaces and development. _**Note: the release breaks existing playbooks. some module args have changed.**_ #### Documentation * detailed description of inventory files and their use in playbooks #### New / Updated Modules * [solace_cloud_get_services](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_cloud_get_services.html) * [solace_acl_subscribe_share_name_exception](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_acl_subscribe_share_name_exception.html) * [solace_cert_authority](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_cert_authority.html) * [solace_get_acl_profiles](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_acl_profiles.html) * [solace_get_cert_authorities](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_cert_authorities.html) * [solace_get_dmr_bridges](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_dmr_bridges.html) * [solace_get_dmr_cluster_link_remote_addresses](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_dmr_cluster_link_remote_addresses.html) * [solace_get_dmr_cluster_link_trusted_cns](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_dmr_cluster_link_trusted_cns.html) * [solace_get_dmr_cluster_links](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_dmr_cluster_links.html) * [solace_get_dmr_clusters](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_dmr_clusters.html) * [solace_get_queue_subscriptions](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_queue_subscriptions.html) * [solace_get_rdp_queue_bindings](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_rdp_queue_bindings.html) * [solace_get_rdp_rest_consumer_trusted_cns](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_rdp_rest_consumer_trusted_cns.html) * [solace_get_rdp_rest_consumers](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_rdp_rest_consumers.html) * [solace_get_topic_endpoints](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_topic_endpoints.html) * [solace_get_vpn_clients](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_vpn_clients.html) * [solace_get_vpns](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_vpns.html) * [solace_get_facts](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_get_facts.html) #### Removed Modules * **solace_bridge_tls_cn** - renamed to [solace_bridge_trusted_cn](https://solace-iot-team.github.io/ansible-solace-collection/modules/solace_bridge_trusted_cn.html) #### Refactored Framework * separated tasks & apis - allows for a task to use one or more apis as required - specialized task classes (crud, get list, solace cloud account, solace cloud, ...) - specialized api classes (sempv2 config, sempv2 paging, sempv1, solace_cloud, ...) * streamlined result set for modules - each module returns rc=0,1, msg='error message' - crud modules return response - list modules return result_list and result_list_count * streamlined error handling - specialized exception classes - {task-class}.execute(): wraps do_task() with exception handling - ensures consistent approach to exceptions - allows tasks to raise exception at any point * module update handling changed - existing settings are still compared to target settings to determine if a patch request should happen - if that is the case, now ALL settings configured in the playbook are sent, not just the delta - overcomes the issue of attributes not returned by the API (e.g. passwords, inconsistencies in solace cloud api) - overcomes the 'required_together' issue for some APIs - no need to treat them explicitly ## Version: 1.0.0 Initial Release. Based on previous project [ansible-solace-modules](https://github.com/solace-iot-team/ansible-solace-modules). Refactored as Ansible Collection. --- <file_sep>/tests/single_broker/solace_acl_profile/_run.sh #!/usr/bin/env bash # Copyright (c) 2020, Solace Corporation, <NAME>, <<EMAIL>> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) scriptDir=$(cd $(dirname "$0") && pwd); scriptName=$(basename $(test -L "$0" && readlink "$0" || echo "$0")); testTarget=${scriptDir##*/} scriptLogName="$testTargetGroup.$testTarget.$scriptName" if [ -z "$PROJECT_HOME" ]; then echo ">>> XT_ERROR: - $scriptLogName - missing env var: PROJECT_HOME"; exit 1; fi source $PROJECT_HOME/.lib/functions.sh ############################################################################################################################ # Environment Variables if [ -z "$WORKING_DIR" ]; then echo ">>> XT_ERROR: - $scriptLogName - missing env var: WORKING_DIR"; exit 1; fi if [ -z "$LOG_DIR" ]; then echo ">>> XT_ERROR: - $scriptLogName - missing env var: LOG_DIR"; exit 1; fi ############################################################################################################################## # Settings export ANSIBLE_SOLACE_LOG_PATH="$LOG_DIR/$scriptLogName.ansible-solace.log" export ANSIBLE_LOG_PATH="$LOG_DIR/$scriptLogName.ansible.log" INVENTORY_FILE="$WORKING_DIR/broker.inventory.yml" inventory=$(assertFile $scriptLogName $INVENTORY_FILE) || exit playbooks=( # "$scriptDir/main.playbook.yml" # "$scriptDir/ex_1.playbook.yml" # "$scriptDir/get.playbook.yml" # "$scriptDir/publish_topic_list.playbook.yml" # "$scriptDir/publish_topic_list.doc-example.playbook.yml" # "$scriptDir/subscribe_topic_list.playbook.yml" "$scriptDir/subscribe_topic_list.doc-example.playbook.yml" # "$scriptDir/subscribe_share_name_list.playbook.yml" # "$scriptDir/subscribe_share_name_list.doc-example.playbook.yml" # "$scriptDir/client_connect_address_list.playbook.yml" # "$scriptDir/client_connect_address_list.doc-example.playbook.yml" ) ############################################################################################################################## # Run for playbook in ${playbooks[@]}; do playbook=$(assertFile $scriptLogName $playbook) || exit ansible-playbook \ -i $inventory \ $playbook \ --extra-vars "WORKING_DIR=$WORKING_DIR" code=$?; if [[ $code != 0 ]]; then echo ">>> XT_ERROR - $code - script:$scriptLogName, playbook:$playbook"; exit 1; fi done echo ">>> SUCCESS: $scriptLogName" ### # The End. <file_sep>/tests/single_broker/.devel/run.sh #!/usr/bin/env bash # Copyright (c) 2020, Solace Corporation, <NAME>, <<EMAIL>> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) scriptDir=$(cd $(dirname "$0") && pwd); scriptName=$(basename $(test -L "$0" && readlink "$0" || echo "$0")); projectHome=${scriptDir%/ansible-solace-collection/*} if [[ ! $projectHome =~ "ansible-solace-collection" ]]; then projectHome=$projectHome/ansible-solace-collection fi export PROJECT_HOME=$projectHome ansibleSolaceTests=( "broker-cert" "setup" "solace_jndi" "solace_client_profile" "solace_replay" "solace_cert_authority" "solace_get_list" "solace_service_auth" "solace_get_available" "solace_auth" "solace_oauth" "solace_facts" "solace_vpn" "solace_acl_profile" "solace_rdp" "solace_queue" "solace_client_username" "solace_mqtt" "solace_topic_endpoint" "solace_get_vpn_clients" "teardown" ) export ANSIBLE_SOLACE_TESTS="${ansibleSolaceTests[*]}" # local broker export BROKER_DOCKER_IMAGE="solace/solace-pubsub-standard:latest" # export BROKER_DOCKER_IMAGE="solace/solace-pubsub-standard:192.168.127.12" # export BROKER_DOCKER_IMAGE="solace/solace-pubsub-standard:172.16.58.3" # export BROKER_DOCKER_IMAGE="solace/solace-pubsub-standard:192.168.127.12" # export BROKER_DOCKER_IMAGE="solace/solace-pubsub-standard:192.168.3.11" # export BROKER_DOCKER_IMAGE="solace/solace-pubsub-standard:172.16.58.3" # export BROKER_DOCKER_IMAGE="solace/solace-pubsub-standard:172.16.31.10" export BROKER_TYPE="local" export LOCAL_BROKER_INVENTORY_FILE="$projectHome/test-runner/files/local.broker.inventory.yml" export BROKER_DOCKER_COMPOSE_FILE="$projectHome/test-runner/files/PubSubStandard_singleNode.yml" export INVENTORY_FILE=$LOCAL_BROKER_INVENTORY_FILE # solace cloud broker export BROKER_TYPE="solace_cloud" export INVENTORY_FILE="$projectHome/test-runner/files/solace-cloud-account.inventory.yml" export SOLACE_CLOUD_API_TOKEN=$SOLACE_CLOUD_API_TOKEN_ALL_PERMISSIONS export CLEAN_WORKING_DIR=False export LOG_DIR=$scriptDir/logs mkdir -p $LOG_DIR rm -rf $LOG_DIR/* export ANSIBLE_LOG_PATH="$LOG_DIR/ansible.log" export ANSIBLE_DEBUG=False export ANSIBLE_VERBOSITY=3 # logging: ansible-solace export ANSIBLE_SOLACE_LOG_PATH="$LOG_DIR/ansible-solace.log" export ANSIBLE_SOLACE_ENABLE_LOGGING=True export RUN_FG=true # export RUN_FG=false ../_run.sh ### # The End. <file_sep>/tests/single_broker/_run.sh #!/usr/bin/env bash # (c) 2020 <NAME>, <<EMAIL>> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) scriptDir=$(cd $(dirname "$0") && pwd); scriptName=$(basename $(test -L "$0" && readlink "$0" || echo "$0")); export testTargetGroup=${scriptDir##*/} scriptLogName="$testTargetGroup.$scriptName" if [ -z "$PROJECT_HOME" ]; then echo ">>> XT_ERROR: - $scriptLogName - missing env var: PROJECT_HOME"; exit 1; fi source $PROJECT_HOME/.lib/functions.sh ############################################################################################################################ # Environment Variables if [ -z "$LOG_DIR" ]; then echo ">>> XT_ERROR: - $scriptLogName - missing env var: LOG_DIR"; exit 1; fi if [ -z "$RUN_FG" ]; then echo ">>> XT_ERROR: - $scriptLogName - missing env var: RUN_FG"; exit 1; fi if [ -z "$ANSIBLE_SOLACE_TESTS" ]; then export ANSIBLE_SOLACE_TESTS=( "broker-cert" "setup" "solace_jndi" "solace_replay" "solace_get_list" "solace_service_auth" "solace_get_available" "solace_auth" "solace_oauth" "solace_facts" "solace_vpn" "solace_acl_profile" "solace_rdp" "solace_cert_authority" "solace_queue" "solace_client_username" "solace_mqtt" "solace_topic_endpoint" "solace_get_vpn_clients" # "solace_client_profile" "teardown" ) fi ############################################################################################################################## # Prepare export WORKING_DIR="$scriptDir/tmp" mkdir -p $WORKING_DIR if [ -z "$CLEAN_WORKING_DIR" ]; then rm -rf $WORKING_DIR/*; fi ############################################################################################################################## # Run for ansibleSolaceTest in ${ANSIBLE_SOLACE_TESTS[@]}; do runScript="$scriptDir/$ansibleSolaceTest/_run.sh" echo ">>> TEST: $testTargetGroup/$ansibleSolaceTest" if [[ "$RUN_FG" == "false" ]]; then $runScript > $LOG_DIR/$testTargetGroup.$ansibleSolaceTest._run.sh.out 2>&1 else $runScript fi code=$?; if [[ $code != 0 ]]; then echo ">>> XT_ERROR - code=$code - runScript='$runScript' - $scriptLogName"; exit 1; fi done ### # The End.
fafb9d14374a4a67ddd49f80b757571a7d093ede
[ "Markdown", "Shell" ]
4
Markdown
whoiscnu/ansible-solace-collection
4d4df818f8d7648b0cbd973dcfa0a3b900677852
9d70f93864a2842c56ef81cfa60c1f630056aaef
refs/heads/master
<repo_name>Ukasshu/Communicator<file_sep>/src/Client.java import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Set; /** * Created by Łukasz on 2017-01-15. */ public class Client { private final static String SEP = ""+(char) 198; private SocketChannel socketChannel; private Selector selector; private SelectionKey selectionKey; private JFrame frame; private DefaultListModel listModel; private String myUsername; private HashMap<String, ChatFrame> chatFrames = new HashMap<>(); public static void main(String[] args){ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } Client client = new Client(); client.start(); } private void start() { frame = new LoginFrame(); frame.pack(); frame.setVisible(true); } ///////////////////////////////////////////////////////////// public class LoginFrame extends JFrame{ private JTextField loginTextField; private JButton connectButton; private JLabel label; private JPanel mainPanel; public LoginFrame(){ setContentPane(mainPanel); setResizable(false); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); loginTextField.setDocument(new LimitedCharactersDocument(15)); connectButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try{ ByteBuffer buffer; byte[] bytes; socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); socketChannel.connect(new InetSocketAddress("localhost", 1111)); while(!socketChannel.finishConnect()){}; selector = Selector.open(); selectionKey = socketChannel.register(selector, SelectionKey.OP_READ); buffer = ByteBuffer.wrap(("reg"+SEP+loginTextField.getText()).getBytes()); socketChannel.write(buffer); int bytesRead; selector.select(); Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> iter = selectionKeys.iterator(); while(iter.hasNext()){ SelectionKey key = iter.next(); if(key.isReadable()) { SocketChannel s = (SocketChannel) key.channel(); buffer = ByteBuffer.allocate(256); bytesRead = s.read(buffer); } iter.remove(); } bytes = buffer.array(); String message = new String(bytes).trim(); if(!message.equals("acc")){ selectionKey.cancel(); socketChannel.close(); JOptionPane.showMessageDialog(mainPanel, "Spróbuj użyć innej nazwy"); } else { myUsername = loginTextField.getText(); frame = new MainFrame(); frame.pack(); frame.setVisible(true); LoginFrame.this.dispose(); } }catch (IOException exc){ exc.printStackTrace(); } } }); } } ///////////////////////////////////////////////////////////// public class MainFrame extends JFrame{ private JList usersList; private JButton writeButton; private JPanel mainPanel; private Thread readingThread; private ArrayList<Thread> handlingThreads = new ArrayList<>(); public MainFrame(){ setContentPane(mainPanel); setTitle("Communicator 2.0 - "+ myUsername +" - Client"); setResizable(false); listModel = new DefaultListModel(); usersList.setModel(listModel); setDefaultCloseOperation(DISPOSE_ON_CLOSE); writeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(!usersList.isSelectionEmpty()){ String user = (String)usersList.getSelectedValue(); ChatFrame c = new ChatFrame(user); chatFrames.put(user, c); c.pack(); c.setVisible(true); } } }); readingThread = new Thread(new ReadingTask()); readingThread.start(); } private class ReadingTask implements Runnable{ @Override public void run() { try { String message = "rdy" + SEP + myUsername; byte[] bytes = message.getBytes(); ByteBuffer buffer = ByteBuffer.wrap(bytes); socketChannel.write(buffer); while(true){ try { selector.select(); Set<SelectionKey> keySet = selector.selectedKeys(); Iterator<SelectionKey> iterator = keySet.iterator(); while(iterator.hasNext()){ SelectionKey key = iterator.next(); if(key.isReadable()){ SocketChannel s = (SocketChannel)key.channel(); buffer = ByteBuffer.allocate(256); s.read(buffer); bytes = buffer.array(); message = new String(bytes).trim(); Thread handler = new Thread(new HandlingTask(message)); handlingThreads.add(handler); handler.start(); } iterator.remove(); } }catch (IOException e){ e.printStackTrace(); } } }catch (Exception e){ selectionKey.cancel(); selectionKey.cancel(); } } } private class HandlingTask implements Runnable{ private String message; public HandlingTask(String message){ this.message = message; } @Override public void run() { try{ String[] msg = message.split(SEP); switch (msg[0]){ case "jnd": listModel.addElement(msg[1]); break; case "lft": listModel.removeElement(msg[1]); break; case "msg": String dst; if(msg[1].equals(myUsername)){ dst = msg[2]; } else{ dst =msg[1]; } if(!chatFrames.containsKey(dst)){ ChatFrame c = new ChatFrame(dst); chatFrames.put(dst, c); c.pack(); c.setVisible(true); } JTextArea textArea = chatFrames.get(dst).getChatTextArea(); textArea.insert(msg[1]+"\n", textArea.getText().length()); textArea.insert(msg[3]+"\n\n", textArea.getText().length()); break; } }finally { Thread t = Thread.currentThread(); handlingThreads.remove(t); } } } @Override public void dispose(){ try{ ByteBuffer buffer = ByteBuffer.wrap(("exi"+SEP+myUsername).getBytes()); socketChannel.write(buffer); }catch (IOException e){ e.printStackTrace(); } System.exit(0); super.dispose(); } } ///////////////////////////////////////////////////////////// public class ChatFrame extends JFrame{ private JTextArea chatTextArea; private JTextArea messageTextArea; private JButton sendButton; private JPanel mainPanel; private String user; public ChatFrame(String user){ setContentPane(mainPanel); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setTitle("Piszesz do "+ user + " - "+myUsername); //setResizable(false); this.user = user; chatTextArea.setDocument(new LimitedCharactersDocument(220)); sendButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String message = messageTextArea.getText(); if(message.length()!=0){ message = "msg"+SEP+myUsername+SEP+user+SEP+message; byte[] bytes = message.getBytes(); ByteBuffer buffer = ByteBuffer.wrap(bytes); try { socketChannel.write(buffer); }catch (IOException exc){ exc.printStackTrace(); } } messageTextArea.setText(""); } }); } public JTextArea getChatTextArea(){ return chatTextArea; } @Override public void dispose() { chatFrames.remove(user); super.dispose(); } } }
48fb11f27a5c454fdcafb707df2692bfeaecd6ee
[ "Java" ]
1
Java
Ukasshu/Communicator
5bf525be5dfb18d05a9edb2ab5fd06673f43cd07
f45dda93c44b6ecd4e58dbf6b0d0f8109ccad4df
refs/heads/master
<repo_name>zlxtyp/go-junction<file_sep>/src/go-junction.go package main import ( "directory" "config" // "fmt" // "regexp" //"log" // "os" // "os/exec" // "path/filepath" // "strings" // "bytes" // "strings" // "bytes" // "path/filepath" // "os" // "log" //"io/ioutil" //"fmt" "os" "fmt" ) func main() { config := config.Parse(); fmt.Println(config.PathAlias) fmt.Println(config.Junction) ret := directory.GetPatternDir(`d:/|\d+$|/bin`) for _, v := range ret { _, err := os.Stat(v) if err != nil { fmt.Println(v + " err") } if os.IsNotExist(err) { fmt.Println(v + " invalid") } else { fmt.Println(v) } } } <file_sep>/test.toml [targetConfig] # 原始文件夹重命名备份 renameTargetFolder = false # 清空原始文件夹 clearTargetFolder = true #当目录文件夹无效时,跳过 skipInvalidTarget = false [pathAlias] #build in path variable # UserHome # Temp useless='C:\useless' chrome_cache='V:\chrome_cache' firefox_cache='V:\firefox_cache' [[junction]] target = '{useless}/A' link = [ 'd:/|\d+$|/bin', 'v:/|cache$|' ] [[junction]] target = '{useless}/B' link = [ 'd:/|\d+$|/bin', 'v:/|chrome$|' ]<file_sep>/src/directory/dir.go package directory import ( "os" //"os/exec" //"bytes" //"fmt" ) func DirExists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return true, err } func cmdExec(cmdStr string, args ...string) { //cmd := exec.Command(cmdStr,args) //var out bytes.Buffer //cmd.Stdout = &out //cmd.Run() //return out.String() } <file_sep>/src/config/tomlStruct.go package config type config struct { ActionName string TargetConfig targetConfig PathAlias map[string]string Junction []junction } type targetConfig struct { // 原始文件夹是否要重命名备份 RenameTargetFolder bool //是否要清空原始文件夹 ClearTargetFolder bool //#当目录文件夹无效时是否继续 SkipInvalidTarget bool } type junction struct { Target string Link []string } <file_sep>/src/config/parse.go package config import ( "flag" "github.com/BurntSushi/toml" "log" "os" ) const ( actionParamName = "action" actionDefault = "check" actoinUsageText = "action can only one of those: check create update" //参数默认名称 configParamName = "config" //默认配置文件夹名 configFileDefaultName = "config.ini" //提示语 configUsageText = "config file name" ) func Parse() config { var actionName = flag.String(actionParamName, actionDefault, actoinUsageText) var configFileName = flag.String(configParamName, configFileDefaultName, configUsageText) flag.Parse(); var config config if _, err := toml.DecodeFile(*configFileName, &config); err != nil { log.Fatal(err) os.Exit(1) } config.ActionName = *actionName return config }<file_sep>/src/directory/path.go package directory import ( "fmt" "io/ioutil" "regexp" "strings" "os" ) func GetPatternDir(path string)[]string { diskReg := regexp.MustCompile(`(?i)[a-z]:`) matchRet := diskReg.FindStringSubmatch(path) if len(matchRet) < 1 { fmt.Println(path + " 路径无效") return make([]string, 0, 0) } var diskName string = matchRet[0] dirReg := regexp.MustCompile(`(\\|/)((?:\|[^|]+\|)|[^/\\]+)`) path = strings.Trim(path, " ") var parsedDirs []string = make([]string, 0, 16) dirNames := dirReg.FindAllStringSubmatch(path, -1) if len(dirNames) < 1 { fmt.Println(path + " 路径无效") return make([]string, 0, 0) } parsedDirs = append(parsedDirs, diskName) for _, v := range dirNames { //path := v[0] fileSplit := v[1] namePattern := v[2] //普通路径字串 if !(strings.HasPrefix(namePattern, "|") && strings.HasSuffix(namePattern, "|")) { parsedDirs=appendDir(parsedDirs, fileSplit, namePattern) continue } //包含正则的路径字串 namePattern = strings.Trim(namePattern, "|") parsedDirs = appendPatternDir(parsedDirs, fileSplit, namePattern) } return parsedDirs } /** dirs 中添加 appendDir */ func appendPatternDir(parsedDirs []string, fileSplit string, namePattern string) []string { nameReg := regexp.MustCompile(namePattern) match := func(d os.FileInfo) bool { return d.IsDir()&&nameReg.MatchString(d.Name()) } retDirs := traversalDir(parsedDirs, fileSplit, match); return retDirs } /** dirs 中添加 appendDir */ func appendDir(parsedDirs []string, fileSplit string, appendDir string) []string { match := func(d os.FileInfo) bool { return d.IsDir()&&d.Name() == appendDir } retDirs := traversalDir(parsedDirs, fileSplit, match); return retDirs } type dirMatch func(os.FileInfo) bool func traversalDir(dirs []string, fileSplit string, match dirMatch) []string { var retDirs []string = make([]string, 0, 16) for _, v := range dirs { childDirs, err := ioutil.ReadDir(v) if err != nil { fmt.Println(v + " 读取子文件夹出错!") continue } for _, d := range childDirs { if match(d) { retDirs = append(retDirs, v + fileSplit + d.Name()) } } } return retDirs } <file_sep>/src/junction/junction.go package main import ( "directory" "config" // "fmt" // "regexp" //"log" // "os" // "os/exec" // "path/filepath" // "strings" // "bytes" // "strings" // "bytes" // "path/filepath" // "os" // "log" //"io/ioutil" //"fmt" "os" "fmt" ) /// <summary> /// The file or directory is not a reparse point. /// </summary> const ERROR_NOT_A_REPARSE_POINT = 4390; /// <summary> /// The reparse point attribute cannot be set because it conflicts with an existing attribute. /// </summary> const ERROR_REPARSE_ATTRIBUTE_CONFLICT = 4391; /// <summary> /// The data present in the reparse point buffer is invalid. /// </summary> const ERROR_INVALID_REPARSE_DATA = 4392; /// <summary> /// The tag present in the reparse point buffer is invalid. /// </summary> const ERROR_REPARSE_TAG_INVALID = 4393; /// <summary> /// There is a mismatch between the tag specified in the request and the tag present in the reparse point. /// </summary> const ERROR_REPARSE_TAG_MISMATCH = 4394; /// <summary> /// Command to set the reparse point data block. /// </summary> const FSCTL_SET_REPARSE_POINT = 0x000900A4; /// <summary> /// Command to get the reparse point data block. /// </summary> const FSCTL_GET_REPARSE_POINT = 0x000900A8; /// <summary> /// Command to delete the reparse point data base. /// </summary> const FSCTL_DELETE_REPARSE_POINT = 0x000900AC; /// <summary> /// Reparse point tag used to identify mount points and junction points. /// </summary> const IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003; /// <summary> /// This prefix indicates to NTFS that the path is to be treated as a non-interpreted /// path in the virtual file system. /// </summary> const NonInterpretedPathPrefix = `\??\`; type EFileAccess uint var ( GenericRead EFileAccess = 0x80000000 GenericWrite EFileAccess = 0x40000000 GenericExecute EFileAccess = 0x20000000 GenericAll EFileAccess = 0x10000000 ) type EFileShare uint var ( None EFileShare = 0x00000000 Read EFileShare = 0x00000001 Write EFileShare = 0x00000002 Delete EFileShare = 0x00000004 ) type ECreationDisposition uint var ( New ECreationDisposition = 1 CreateAlways ECreationDisposition = 2 OpenExisting ECreationDisposition = 3 OpenAlways ECreationDisposition = 4 TruncateExisting ECreationDisposition = 5 ) type EFileAttributes uint var ( Readonly EFileAttributes = 0x00000001 Hidden EFileAttributes = 0x00000002 System EFileAttributes = 0x00000004 Directory EFileAttributes = 0x00000010 Archive EFileAttributes = 0x00000020 Device EFileAttributes = 0x00000040 Normal EFileAttributes = 0x00000080 Temporary EFileAttributes = 0x00000100 SparseFile EFileAttributes = 0x00000200 ReparsePoint EFileAttributes = 0x00000400 Compressed EFileAttributes = 0x00000800 Offline EFileAttributes = 0x00001000 NotContentIndexed EFileAttributes = 0x00002000 Encrypted EFileAttributes = 0x00004000 Write_Through EFileAttributes = 0x80000000 Overlapped EFileAttributes = 0x40000000 NoBuffering EFileAttributes = 0x20000000 RandomAccess EFileAttributes = 0x10000000 SequentialScan EFileAttributes = 0x08000000 DeleteOnClose EFileAttributes = 0x04000000 BackupSemantics EFileAttributes = 0x02000000 PosixSemantics EFileAttributes = 0x01000000 OpenReparsePoint EFileAttributes = 0x00200000 OpenNoRecall EFileAttributes = 0x00100000 FirstPipeInstance EFileAttributes = 0x00080000 ) type REPARSE_DATA_BUFFER struct { /// <summary> /// Reparse point tag. Must be a Microsoft reparse point tag. /// </summary> ReparseTag uint /// <summary> /// Size, in bytes, of the data after the Reserved member. This can be calculated by: /// (4 * sizeof(ushort)) + SubstituteNameLength + PrintNameLength + /// (namesAreNullTerminated ? 2 * sizeof(char) : 0); /// </summary> ReparseDataLength uint16 /// <summary> /// Reserved; do not use. /// </summary> Reserved uint16 /// <summary> /// Offset, in bytes, of the substitute name string in the PathBuffer array. /// </summary> SubstituteNameOffset uint16 /// <summary> /// Length, in bytes, of the substitute name string. If this string is null-terminated, /// SubstituteNameLength does not include space for the null character. /// </summary> SubstituteNameLength /// <summary> /// Offset, in bytes, of the print name string in the PathBuffer array. /// </summary> PrintNameOffset uint16 /// <summary> /// Length, in bytes, of the print name string. If this string is null-terminated, /// PrintNameLength does not include space for the null character. /// </summary> PrintNameLength uint16 /// <summary> /// A buffer containing the unicode-encoded path string. The path string contains /// the substitute name string and print name string. /// </summary> PathBuffer []uint8 } [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool DeviceIoControl(IntPtr hDevice, uint dwIoControlCode, IntPtr InBuffer, int nInBufferSize, IntPtr OutBuffer, int nOutBufferSize, out int pBytesReturned, IntPtr lpOverlapped); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr CreateFile( string lpFileName, EFileAccess dwDesiredAccess, EFileShare dwShareMode, IntPtr lpSecurityAttributes, ECreationDisposition dwCreationDisposition, EFileAttributes dwFlagsAndAttributes, IntPtr hTemplateFile); /// <summary> /// Creates a junction point from the specified directory to the specified target directory. /// </summary> /// <remarks> /// Only works on NTFS. /// </remarks> /// <param name="junctionPoint">The junction point path</param> /// <param name="targetDir">The target directory</param> /// <param name="overwrite">If true overwrites an existing reparse point or empty directory</param> /// <exception cref="IOException">Thrown when the junction point could not be created or when /// an existing directory was found and <paramref name="overwrite" /> if false</exception> public static bool Create(string junctionPoint, string targetDir, bool overwrite) { targetDir = Path.GetFullPath(targetDir); if (!Directory.Exists(targetDir)) { //log(targetDir + " does not exist or is not a directory."); throw new IOException("Target path does not exist or is not a directory."); //return false; } if (Directory.Exists(junctionPoint)) { if (!overwrite) { //log(junctionPoint + " already exists and overwrite parameter is false."); throw new IOException("Directory already exists and overwrite parameter is false."); //return false; } } else { Directory.CreateDirectory(junctionPoint); } using (TTuple<bool, SafeFileHandle> ret = OpenReparsePoint(junctionPoint, EFileAccess.GenericWrite)) { if (!ret.result){ return false; } SafeFileHandle handle = ret.data; byte[] targetDirBytes = Encoding.Unicode.GetBytes(NonInterpretedPathPrefix + Path.GetFullPath(targetDir)); REPARSE_DATA_BUFFER reparseDataBuffer = new REPARSE_DATA_BUFFER(); reparseDataBuffer.ReparseTag = IO_REPARSE_TAG_MOUNT_POINT; reparseDataBuffer.ReparseDataLength = (ushort)(targetDirBytes.Length + 12); reparseDataBuffer.SubstituteNameOffset = 0; reparseDataBuffer.SubstituteNameLength = (ushort)targetDirBytes.Length; reparseDataBuffer.PrintNameOffset = (ushort)(targetDirBytes.Length + 2); reparseDataBuffer.PrintNameLength = 0; reparseDataBuffer.PathBuffer = new byte[0x3ff0]; Array.Copy(targetDirBytes, reparseDataBuffer.PathBuffer, targetDirBytes.Length); int inBufferSize = Marshal.SizeOf(reparseDataBuffer); IntPtr inBuffer = Marshal.AllocHGlobal(inBufferSize); try { Marshal.StructureToPtr(reparseDataBuffer, inBuffer, false); int bytesReturned; bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_SET_REPARSE_POINT, inBuffer, targetDirBytes.Length + 20, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero); if (!result) { //log("Unable to create junction point : "+junctionPoint+" to : "+targetDir); ThrowLastWin32Error("Unable to create junction point."); //return false; } return true; } finally { Marshal.FreeHGlobal(inBuffer); } } } /// <summary> /// Deletes a junction point at the specified source directory along with the directory itself. /// Does nothing if the junction point does not exist. /// </summary> /// <remarks> /// Only works on NTFS. /// </remarks> /// <param name="junctionPoint">The junction point path</param> public static bool Delete(string junctionPoint) { if (!Directory.Exists(junctionPoint)) { if (File.Exists(junctionPoint)) { //log(junctionPoint + " is not a junction point."); throw new IOException("Path is not a junction point."); //return false; } } using (TTuple<bool, SafeFileHandle> ret = OpenReparsePoint(junctionPoint, EFileAccess.GenericWrite)) { if (!ret.result){ return false; } SafeFileHandle handle = ret.data; REPARSE_DATA_BUFFER reparseDataBuffer = new REPARSE_DATA_BUFFER(); reparseDataBuffer.ReparseTag = IO_REPARSE_TAG_MOUNT_POINT; reparseDataBuffer.ReparseDataLength = 0; reparseDataBuffer.PathBuffer = new byte[0x3ff0]; int inBufferSize = Marshal.SizeOf(reparseDataBuffer); IntPtr inBuffer = Marshal.AllocHGlobal(inBufferSize); try { Marshal.StructureToPtr(reparseDataBuffer, inBuffer, false); int bytesReturned; bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_DELETE_REPARSE_POINT, inBuffer, 8, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero); if (!result) { ThrowLastWin32Error("Unable to delete junction point."); //log("Unable to delete junction point :" + junctionPoint); //return false; } } finally { Marshal.FreeHGlobal(inBuffer); } try { Directory.Delete(junctionPoint); } catch (IOException ex) { //log("Unable to delete junction point :" + junctionPoint+ ","+ex.ToString()); throw new IOException("Unable to delete junction point.", ex); } return true; } } /// <summary> /// Determines whether the specified path exists and refers to a junction point. /// </summary> /// <param name="path">The junction point path</param> /// <returns>True if the specified path represents a junction point</returns> /// <exception cref="IOException">Thrown if the specified path is invalid /// or some other error occurs</exception> public static bool Exists(string path) { if (! Directory.Exists(path)) return false; using (TTuple<bool, SafeFileHandle> ret = OpenReparsePoint(path, EFileAccess.GenericRead)) { if (!ret.result) { return false; } SafeFileHandle handle = ret.data; string target = InternalGetTarget(handle); return target != null; } } /// <summary> /// Gets the target of the specified junction point. /// </summary> /// <remarks> /// Only works on NTFS. /// </remarks> /// <param name="junctionPoint">The junction point path</param> /// <returns>The target of the junction point</returns> /// <exception cref="IOException">Thrown when the specified path does not /// exist, is invalid, is not a junction point, or some other error occurs</exception> public static string GetTarget(string junctionPoint) { using (TTuple<bool, SafeFileHandle> ret = OpenReparsePoint(junctionPoint, EFileAccess.GenericRead)) { if (!ret.result) { //不会到这里 return ""; } SafeFileHandle handle = ret.data; string target = InternalGetTarget(handle); if (target == null) { throw new IOException("Path is not a junction point."); //log("Path is not a junction point."); //return ""; } return target; } } private static string InternalGetTarget(SafeFileHandle handle) { int outBufferSize = Marshal.SizeOf(typeof(REPARSE_DATA_BUFFER)); IntPtr outBuffer = Marshal.AllocHGlobal(outBufferSize); try { int bytesReturned; bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_GET_REPARSE_POINT, IntPtr.Zero, 0, outBuffer, outBufferSize, out bytesReturned, IntPtr.Zero); if (!result) { int error = Marshal.GetLastWin32Error(); if (error == ERROR_NOT_A_REPARSE_POINT) return null; ThrowLastWin32Error("Unable to get information about junction point."); } REPARSE_DATA_BUFFER reparseDataBuffer = (REPARSE_DATA_BUFFER) Marshal.PtrToStructure(outBuffer, typeof(REPARSE_DATA_BUFFER)); if (reparseDataBuffer.ReparseTag != IO_REPARSE_TAG_MOUNT_POINT) return null; string targetDir = Encoding.Unicode.GetString(reparseDataBuffer.PathBuffer, reparseDataBuffer.SubstituteNameOffset, reparseDataBuffer.SubstituteNameLength); if (targetDir.StartsWith(NonInterpretedPathPrefix)) targetDir = targetDir.Substring(NonInterpretedPathPrefix.Length); return targetDir; } finally { Marshal.FreeHGlobal(outBuffer); } } private static TTuple<bool, SafeFileHandle> OpenReparsePoint(string reparsePoint, EFileAccess accessMode) { SafeFileHandle reparsePointHandle = new SafeFileHandle(CreateFile(reparsePoint, accessMode, EFileShare.Read | EFileShare.Write | EFileShare.Delete, IntPtr.Zero, ECreationDisposition.OpenExisting, EFileAttributes.BackupSemantics | EFileAttributes.OpenReparsePoint, IntPtr.Zero), true); if (Marshal.GetLastWin32Error() != 0) { //log("Unable to open reparse point."); //return TTuple<bool,SafeFileHandle>.create(false, reparsePointHandle); ThrowLastWin32Error("Unable to open reparse point."); } //return reparsePointHandle; return TTuple<bool, SafeFileHandle>.create(true, reparsePointHandle); } private static void ThrowLastWin32Error(string message) { throw new IOException(message, Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error())); } private static void log(string log) { StreamWriter w = File.AppendText("JunctionPoint.log"); w.WriteLine("{0}:{1}", System.DateTime.Now, log); w.Close(); } public class TTuple<T1, T2> : System.IDisposable { public readonly T1 result; public readonly T2 data; public void Dispose() { } public TTuple(T1 result, T2 data) { this.result = result; this.data = data; } public static TTuple<T1, T2> create<T1, T2>(T1 result, T2 data) { return new TTuple<T1, T2>(result, data); } } //static void Main(string[] args) //{ // Console.WriteLine(JunctionPoint.Create("v:/ttt", "v:/temp", true)); // Console.WriteLine(JunctionPoint.GetTarget(@"v:/ttt")); // Console.WriteLine(JunctionPoint.Exists(@"v:/ttt")); // Console.WriteLine(JunctionPoint.Delete(@"v:/ttt")); //}
25e73274e22b2b23780cc75a53351d4908e7d24f
[ "TOML", "Go" ]
7
Go
zlxtyp/go-junction
68bf7ae09ab5043ed063967bc0b018cb4dc1c45c
be321a27a6acc34a6c1273ac1ca2396a8adf762f
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ProjectEuler.MiscQuestions { class PalindromeValidator : QuestionBase { private readonly string _value; public PalindromeValidator(string value) { _value = value.ToLower(); Description = string.Format("Is \"{0}\" a palindrome?", _value); } public override object RunSolution() { for (int i = 0; i < Math.Ceiling((double)_value.Length / 2); i++) { if (_value[i] != _value[_value.Length - i - 1]) return "No"; } return "Yes"; } } } <file_sep>using System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using ProjectEuler.MiscQuestions; namespace ProjectEuler.Tests { [TestClass] public class PalindromeValidatorTest { [TestMethod] public void TestWow() { // Arrange string value = "wow"; PalindromeValidator target = new PalindromeValidator(value); object expected = "Yes"; // Act object actual = target.RunSolution(); // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void TestDud() { // Arrange string value = "dud"; PalindromeValidator target = new PalindromeValidator(value); object expected = "Yes"; // Act object actual = target.RunSolution(); // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void TestAustralia() { // Arrange string value = "australia"; PalindromeValidator target = new PalindromeValidator(value); object expected = "No"; // Act object actual = target.RunSolution(); // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void TestKayak() { // Arrange string value = "Kayak"; PalindromeValidator target = new PalindromeValidator(value); object expected = "Yes"; // Act object actual = target.RunSolution(); // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void TestRotavator() { // Arrange string value = "Rotavator"; PalindromeValidator target = new PalindromeValidator(value); object expected = "Yes"; // Act object actual = target.RunSolution(); // Assert Assert.AreEqual(expected, actual); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ProjectEuler.ProjectEulerQuestions { class Q3 : QuestionBase { public Q3() { Description = "What is the largest prime factor of the number 600851475143?"; } public override object RunSolution() { var startingNum = 600851475143; //if (IsPrime2(startingNum)) // return startingNum; var smallestFactor = FindSmallestFactor(startingNum); var largestFactor = startingNum / smallestFactor; for (long i = largestFactor; i > 1; i--) { if ((startingNum % i) == 0) // If is a factor, continue { Console.WriteLine("Found factor - {0}", i); if (IsPrime2(i)) { Console.WriteLine("Found prime factor - {0}", i); return i; } else { Console.WriteLine("{0} is not a prime", i); } } } return "No answer"; } private static int FindSmallestFactor(long startingNum) { for (int i = 2; i < startingNum / 2; i++) { if (startingNum % i == 0) return i; } return -1; } private static bool IsPrime2(long num) { for (long i = num / 2; i > 1; i--) { if (num % i == 0) { return false; } } return true; } private bool IsPrime(long num) { List<long> knownPrimes = new List<long>(); foreach (var knownPrime in knownPrimes) { if (num % knownPrime == 0) { return false; } } return true; } private List<long> PrimeList(long upperLimit) { throw new NotImplementedException(); } } } <file_sep>using System; using ProjectEuler.MiscQuestions; using ProjectEuler.ProjectEulerQuestions; namespace ProjectEuler { class Program { static void Main() { //Q1 q = new Q1(); //PalindromeValidator q = new PalindromeValidator("tattarrattat"); Q3 q = new Q3(); Console.WriteLine("Running {0}...\n", q.GetType().Name); Console.WriteLine("Q: {0}", q.Description); object result = q.Run(); Console.WriteLine("A: {0}\n", result); Console.WriteLine("Solution took {0}s to run\n", q.Stopwatch.Elapsed.TotalSeconds); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } } } <file_sep>using System.Diagnostics; namespace ProjectEuler { abstract class QuestionBase { public string Description { get; protected set; } public Stopwatch Stopwatch { get; private set; } public object Run() { Stopwatch = Stopwatch.StartNew(); object result = RunSolution(); Stopwatch.Stop(); return result; } public abstract object RunSolution(); } }
ba01daa5222a12c306e2e320091ff7a776e494f5
[ "C#" ]
5
C#
andrewcheong/ProjectEulerMarlin
292540f5fba8459703c62ff65815ac77775777bf
25bf54889e0e9b0f9c0e2da958801c5dce48ae5e
refs/heads/master
<repo_name>ManaliAundhkar/Problems-on-Digits-in-Java<file_sep>/Demo4.java //Write a program which accept number from user and return difference between summation of even digits and summation of odd digits. //Input : 2395 //Output : -15 (2 - 17) //Input : 1018 //Output : 6 (8 - 2) //Input : 8440 //Output : 16 (16 - 0) //Input : 5733 //Output : -18 (0 - 18) import java.util.*; class Digit { public int DiffDigits(int iNo) { int iEven=0,iDigit=0,iOdd=0; if(iNo<0) { iNo=-iNo; //updater } while(iNo>0) { iDigit=iNo%10; if((iDigit%2)==0) { iEven=iEven+iDigit; } else { iOdd=iOdd+iDigit; } iNo=iNo/10; } return (iEven-iOdd); } } class Demo4 { public static void main(String arg[]) { Scanner sobj=new Scanner(System.in); System.out.println("Enter the number"); int No=sobj.nextInt(); Digit dobj=new Digit(); int iRet=dobj.DiffDigits(No); System.out.println("The Difference between Even count and Odd count is: "+iRet); } } <file_sep>/Demo.java //Write a java program which accept number from user and return the count of even digits. //Input : 2395 //Output : 1 //Input : 1018 //Output : 2 //Input : -1018 //Output : 2 //Input : 8462 //Output : 4 import java.util.*; class Digit { public int CountDigits(int iNo) { int EvenCount=0,iDigit=0; if(iNo<0) { iNo=-iNo; //updater } while(iNo>0) { iDigit=iNo%10; if((iDigit%2)==0) { EvenCount++; } iNo=iNo/10; } return EvenCount; } } class Demo { public static void main(String arg[]) { Scanner sobj=new Scanner(System.in); System.out.println("Enter the number"); int No=sobj.nextInt(); Digit dobj=new Digit(); int iRet=dobj.CountDigits(No); System.out.println("The Even Count is: "+iRet); } } <file_sep>/Demo1.java //Write a program which accept number from user and return the count of odd digits. //Input : 2395 //Output : 3 //Input : 1018 //Output : 2 //Input : -1018 //Output : 2 //Input : 8462 //Output : 0 import java.util.*; class Digit { public int CountDigits(int iNo) { int OddCount=0,iDigit=0; if(iNo<0) { iNo=-iNo; //updater } while(iNo>0) { iDigit=iNo%10; if((iDigit%2)!=0) { OddCount++; } iNo=iNo/10; } return OddCount; } } class Demo1 { public static void main(String arg[]) { Scanner sobj=new Scanner(System.in); System.out.println("Enter the number"); int No=sobj.nextInt(); Digit dobj=new Digit(); int iRet=dobj.CountDigits(No); System.out.println("The Odd Count is: "+iRet); } }
bb0222d89523d4736f8833117f2d31e16dc54e65
[ "Java" ]
3
Java
ManaliAundhkar/Problems-on-Digits-in-Java
bd44dc4c9d43e89038d5bc31757e05092dfe8186
d5dd83ae0ff74be77a8ced28b46934824f33ee7d
refs/heads/main
<file_sep>canvas = document.getElementById('myCanvas'); ctx = canvas.getContext("2d"); car_1_width = 200; car_1_height = 100; background_image = "https://previews.123rf.com/images/c5media/c5media2007/c5media200700280/152031994-track-and-field-race-course-2.jpg"; car_1_image = "http://www.clker.com/cliparts/n/S/W/l/t/o/pink-car-top-view.svg"; car_1_x = 10; car_1_y = 10; car_2_width = 200; car_2_height = 100; car_2_image = "http://www.clker.com/cliparts/f/E/H/H/s/n/pink-car-top-view-hi.png"; car_2_x = 10; car_2_y = 150; function add() { background_imgTag = new Image(); //defining a variable with a new image background_imgTag.onload = uploadBackground; // setting a function, onloading this variable background_imgTag.src = background_image; // load image car_1_imgTag = new Image(); //defining a variable with a new image car_1_imgTag.onload = uploadCar1; // setting a function, onloading this variable car_1_imgTag.src = car_1_image; // load image car_2_imgTag = new Image(); //defining a variable with a new image car_2_imgTag.onload = uploadCar2; // setting a function, onloading this variable car_2_imgTag.src = car_2_image; // load image } function uploadBackground() { ctx.drawImage(background_imgTag, 0, 0, canvas.width, canvas.height); } function uploadCar1() { ctx.drawImage(car_1_imgTag, car_1_x, car_1_y, car_1_width, car_1_height); } function uploadCar2() { ctx.drawImage(car_2_imgTag, car_2_x, car_2_y, car_2_width, car_2_height); } window.addEventListener("keydown", my_keydown); function my_keydown(e) { keyPressed = e.keyCode; console.log(keyPressed); if(keyPressed == '87') { up_1(); console.log("up"); } if(keyPressed == '83') { down_1(); console.log("down"); } if(keyPressed == '65') { left_1(); console.log("left"); } if(keyPressed == '68') { right_1(); console.log("right"); } function up_1() { if(car_1_y >=0) { car_1_y = car_1_y - 10; console.log("When up arrow is pressed, x = " + car_1_x + " | y = " +car_1_y); uploadBackground(); uploadCar1(); uploadCar2(); } } function down_1() { if(car_1_y <=500) { car_1_y =car_1_y+ 10; console.log("When down arrow is pressed, x = " + car_1_x + " | y = " +car_1_y); uploadBackground(); uploadCar1(); uploadCar2(); } } function left_1() { if(car_1_x >= 0) { car_1_x =car_1_x - 10; console.log("When left arrow is pressed, x = " + car_1_x + " | y = " +car_1_y); uploadBackground(); uploadCar1(); uploadCar2(); } } function right_1() { if(car_1_x <= 700) { car_1_x =car_1_x + 10; console.log("When right arrow is pressed, x = " + car_1_x + " | y = " +car_1_y); uploadBackground(); uploadCar1(); uploadCar2(); } } if(keyPressed == '73') { up_2(); console.log("up"); } if(keyPressed == '75') { down_2(); console.log("down"); } if(keyPressed == '74') { left_2(); console.log("left"); } if(keyPressed == '76') { right_2(); console.log("right"); } function up_2() { if(car_2_y >=0) { car_2_y = car_2_y - 10; console.log("When up arrow is pressed, x = " + car_2_x + " | y = " +car_2_y); uploadBackground(); uploadCar2(); uploadCar1(); } } function down_2() { if(car_2_y <=500) { car_2_y =car_2_y+ 10; console.log("When down arrow is pressed, x = " + car_2_x + " | y = " +car_2_y); uploadBackground(); uploadCar2(); uploadCar1(); } } function left_2() { if(car_2_x >= 0) { car_2_x =car_2_x - 10; console.log("When left arrow is pressed, x = " + car_2_x + " | y = " +car_2_y); uploadBackground(); uploadCar2(); uploadCar1(); } } function right_2() { if(car_2_x <= 700) { car_2_x =car_2_x + 10; console.log("When right arrow is pressed, x = " + car_2_x + " | y = " +car_2_y); uploadBackground(); uploadCar2(); uploadCar1(); } }}
5b6db2c073fb87d550f7621bd3df34500e255743
[ "JavaScript" ]
1
JavaScript
Machas678/84
c03185c088a1f12c5c36aae9aa5d39928e5e0174
5fe03f16221e3dfe44b02922883bf5fcaf6da89c
refs/heads/master
<repo_name>hivictording/react-redux-firebase-test<file_sep>/src/components/layout/Layout.jsx import React from "react"; import FixedHeader from "../FixedHeader"; function Layout({ children }) { return ( <> <FixedHeader /> {children} </> ); } export default Layout; <file_sep>/src/components/muiTest/Grid2.jsx import React from "react"; import { makeStyles, Grid, Paper, Chip, Hidden, Typography, } from "@material-ui/core"; const useStyles = makeStyles({ test: { // height: "50px", background: "lightgray", }, }); const Container = (props) => <Grid container {...props} />; const Item = (props) => <Grid item {...props} />; function Grid2() { const classes = useStyles(); console.log(new Array(3).fill(null).map((item, index) => index)); return ( <Container spacing={4}> <Item xs={12} md={3}> <Container direction="column" spacing={2}> <Item> <Chip label="Item 1" /> <Chip label="Item 1" /> </Item> <Item> <Chip label="Item 2" /> <Chip label="Item 2" /> </Item> </Container> </Item> <Item xs={12} md={3}> <Container direction="column" spacing={2}> <Item> <Paper> <Typography variant="h5" color="error"> Item 3 </Typography> </Paper> </Item> <Item> <Paper>Item 4</Paper> </Item> </Container> </Item> <Item container xs={12} md={3} spacing={2} justify="space-between" alignItems="center" className={classes.test} > {/* <Container spacing={2} justify="space-around"> */} <Item> <Paper>Item 5</Paper> </Item> <Item> <Paper>Item 6</Paper> </Item> {/* </Container> */} </Item> <Hidden smDown> <Item md={3}> <Container direction="column" spacing={2}> <Item> <Paper>Item 7</Paper> </Item> <Item> <Paper>Item 8</Paper> </Item> </Container> </Item> </Hidden> </Container> ); } export default Grid2; <file_sep>/src/components/Header.jsx import React from "react"; import { makeStyles, withStyles } from "@material-ui/core"; import { pink, teal, orange } from "@material-ui/core/colors"; const useHeaderStyles = makeStyles((theme) => { console.log(theme); return { header: { textAlign: "center", color: theme.palette.primary.dark, [theme.breakpoints.down("xs")]: { background: (props) => props.color, }, [theme.breakpoints.up("sm")]: { background: orange[600], }, [theme.breakpoints.up("md")]: { background: teal[600], }, [theme.breakpoints.up("lg")]: { background: pink[600], }, }, }; }); // const useHeaderStyles = makeStyles({ // header: { // textAlign: "center", // color: (props) => props.color, // }, // }); const anotherStyles = { header: { textAlign: "center", }, }; function Header(props) { // withStyles // return <div className={props.classes.header}>Redux firebase with Material-UI</div>; // makeStyles const styles = useHeaderStyles(props); return <div className={styles.header}>Hello Header</div>; } export default Header; // export default withStyles(anotherStyles)(Header); <file_sep>/src/theme/Theme.js import { createMuiTheme } from "@material-ui/core"; // import { green, purple } from "@material-ui/core/colors"; export default createMuiTheme({ palette: { primary: { main: "#459B42", }, secondary: { main: "#CEE26B", }, }, }); <file_sep>/src/reduxstore/rootReducer.js import { combineReducers } from "redux"; import { firebaseReducer } from "react-redux-firebase"; import { firestoreReducer } from "redux-firestore"; import testReducer from "./testReducer"; export default combineReducers({ test: testReducer, firebase: firebaseReducer, firestore: firestoreReducer, }); <file_sep>/src/components/People.jsx import React from "react"; import Person from "./Person"; function People() { return ( <div className="container my-3"> <table class="table table-striped"> <thead> <tr> <th scope="col">#</th> <th scope="col">Name</th> <th scope="col">Age</th> <th scope="col">Operations</th> </tr> </thead> <tbody> <Person /> </tbody> </table> </div> ); } export default People; <file_sep>/src/config/firebaseConfig.js import firebase from "firebase/app"; import "firebase/auth"; import "firebase/firestore"; const firebaseConfig = { apiKey: "<KEY>", authDomain: "fir-test-1-988ef.firebaseapp.com", projectId: "fir-test-1-988ef", storageBucket: "fir-test-1-988ef.appspot.com", messagingSenderId: "427194367154", appId: "1:427194367154:web:83908b76cf759064f35dab", }; firebase.initializeApp(firebaseConfig); firebase.firestore(); export default firebase; <file_sep>/src/components/FixedHeader.jsx import React from "react"; import { makeStyles, AppBar, Toolbar, Typography, Tabs, Tab, Button, Menu, MenuItem, Zoom, } from "@material-ui/core"; import { Link, useLocation } from "react-router-dom"; import menus from "./menus"; import logo from "../assets/sonicwall.svg"; const companyOptions = [ { pathname: "/company", description: "Company", }, { pathname: "/news", description: "News", }, { pathname: "/press", description: "Press", }, { pathname: "/careers", description: "Careers", }, ]; const useStyles = makeStyles((theme) => ({ appbar: { background: theme.palette.primary, }, logo: { height: "6.5em", }, logoWrapper: { padding: 0, "&:hover": { background: "transparent", color: theme.palette.common.black, }, }, // fixed header martin-top fixedHeaderFix: { ...theme.mixins.toolbar, marginBottom: "3.5em", }, tabs: { marginLeft: "auto", }, tab: { textTransform: "none", minWidth: "10px", fontSize: "1rem", "&:hover": { textDecoration: "none", opacity: 1, color: "inherit", }, }, tabIndicator: { background: theme.palette.primary.main, }, menuItem: { color: theme.palette.common.white, opacity: 0.7, "&:hover": { color: theme.palette.common.white, opacity: 1, }, }, // menuItemSelected: { // "& .Mui-selected": { // opacity: 1, // }, // }, menuItemSelected: { opacity: 1, backgroundColor: theme.palette.primary.dark, }, menu: { background: theme.palette.primary.main, }, estimate: { marginRight: "15px", marginLeft: "25px", }, })); function FixedHeader() { const location = useLocation(); const classes = useStyles(); let currentTab = 0, currentSubMenu = 0; for (const menu of menus) { if (menu.pathname === location.pathname) { currentTab = menus.findIndex((m) => m.pathname === menu.pathname); break; } for (const subMenu of menu.subMenus) { if (subMenu.pathname === location.pathname) { currentTab = menus.findIndex((m) => m.pathname === menu.pathname); currentSubMenu = menu.subMenus.findIndex( (s) => s.pathname === subMenu.pathname ); break; } } } const [tab, setTab] = React.useState(currentTab); const [anchor, setAnchor] = React.useState(null); const [selectedIndex, setSelectedIndex] = React.useState(currentSubMenu); const handleOpenMenu = (event) => { setAnchor(event.currentTarget); }; const handleCloseMenu = () => { setAnchor(null); }; const handleMenuItemClick = (event, index) => { setSelectedIndex(index); setAnchor(null); }; const handleTabChange = (event, value) => { setTab(value); setSelectedIndex(null); }; return ( <> <AppBar position="fixed" className={classes.appbar}> <Toolbar disableGutters> <Button disableRipple component={Link} to="/" className={classes.logoWrapper} onClick={() => setTab(0)} > <img src={logo} alt="company logo" className={classes.logo} /> <Typography variant="h4" align="center"> NGFW </Typography> </Button> <Tabs value={tab} onChange={handleTabChange} // indicatorColor="primary" TabIndicatorProps={{ // style: { background: "orange", height: "5px" }, className: classes.tabIndicator, }} // className={classes.tabs} classes={{ root: classes.tabs, }} > {menus.map((menu) => menu.pathname === "/company" ? ( <Tab key={menu.pathname} aria-controls="simple-menu" aria-haspopup="true" label={menu.description} component={Link} to={menu.pathname} // className={classes.tab} classes={{ root: classes.tab, }} onMouseOver={(event) => handleOpenMenu(event)} /> ) : ( <Tab key={menu.pathname} label={menu.description} component={Link} to={menu.pathname} // className={classes.tab} classes={{ root: classes.tab, }} /> ) )} <Menu id="simple-menu" anchorEl={anchor} open={Boolean(anchor)} onClose={handleCloseMenu} // keepMounted MenuListProps={{ onMouseLeave: handleCloseMenu, // className: classes.menuItem, }} elevation={0} TransitionComponent={Zoom} classes={{ // list: classes.menuItemSelected, paper: classes.menu, }} > {companyOptions.map((option, index) => ( <MenuItem key={option.pathname} onClick={(event) => { handleMenuItemClick(event, index); setTab(5); }} selected={selectedIndex === index} component={Link} to={option.pathname} classes={{ root: classes.menuItem, selected: classes.menuItemSelected, }} > {option.description} </MenuItem> ))} </Menu> </Tabs> <Button variant="contained" color="secondary" className={classes.estimate} > Contact Sales </Button> </Toolbar> </AppBar> <div className={classes.fixedHeaderFix} /> </> ); } export default FixedHeader; <file_sep>/src/components/Header1.jsx import React from "react"; import { AppBar, Toolbar, Grid, Paper } from "@material-ui/core"; function Header1() { return ( <AppBar position="static"> <Toolbar> <Grid container spacing={3}> <Grid item xs> <Paper>xs</Paper> </Grid> <Grid item xs={6}> <Paper>xs</Paper> </Grid> <Grid item xs> <Paper>xs</Paper> </Grid> </Grid> </Toolbar> </AppBar> ); } export default Header1;
726ea3d4c863f065ebab63e27fddda72924dfe05
[ "JavaScript" ]
9
JavaScript
hivictording/react-redux-firebase-test
754993dd9e19b626838a612d94b9a9e2f8f7f529
45dadb4d3563c941bb2d83b6cc97907134880e8b
refs/heads/master
<file_sep>import { Grid, Paper, Avatar, TextField, Button } from '@material-ui/core' import Icon from '@material-ui/icons/PeopleAlt'; import { Form, Formik, Field, ErrorMessage } from 'formik'; import React, { PropTypes } from 'react'; import { notify, notify2 } from './iziNotify.js' import { bStyle, paperStyle, avatarStyle, gridStyle } from './extraStyling.js' import { useHistory } from "react-router-dom"; import { validationSchema } from './Validation.js'; import { green } from '@material-ui/core/colors'; const Landing = ({ players, setPlayers }) => { const history = useHistory(); const onSubmit = (values, props) => { props.setSubmitting(false); if (values.player1 !== values.player2) { setPlayers({ player1: values.player1, player2: values.player2 }); history.push('/game'); } else { { notify2(); } history.push('/'); } } return ( <div className="Landing"> <Grid style={gridStyle}> <Paper elevation={10} style={paperStyle}> <Grid align='center'> <Avatar style={avatarStyle}> <Icon /> </Avatar> <h2><span style={{ color: 'green' }}>XARAB</span> <span style={{ color: 'orange' }}>XERO</span></h2> <h3 >Add Players</h3> </Grid> <Formik style initialValues={players} onSubmit={onSubmit} validationSchema={validationSchema} > {(props) => ( <Form> <Field as={TextField} name="player1" label="player1" placeholder='ramesh ' fullWidth helperText={<ErrorMessage name="player1" />} /> <Field as={TextField} name="player2" label="player2" placeholder='suresh ' fullWidth helperText={<ErrorMessage name="player1" />} /> <Button className="ghost-round" type="submit" style={bStyle} color="primary" fullWidth variant="contained"> {props.isSubmitting ? "Loading" : "Start"} </Button> </Form> )} </Formik> </Paper> </Grid > </div > ); } export default Landing;<file_sep>import './styles/root.scss'; import React, { useState } from 'react'; import History from './components/History'; import Landing from './components/Landing'; import Game from './components/Game'; import { Switch, Route, Redirect } from 'react-router-dom'; const initialState = { player1: '', player2: '' } const App = () => { const [players, setPlayers] = useState(initialState); return <Switch> <Route exact path="/"> <Landing players={players} setPlayers={setPlayers} /> </Route> <Route exact path="/game"> <Game players={players} setPlayers={setPlayers} /> </Route> <Route>ERROR 404 NOT FOUND</Route> </Switch> }; export default App; <file_sep>import * as Yup from 'yup'; export const validationSchema = Yup.object().shape({ player1: Yup.string().required("Name is required"), //.string() means it should be a string .string().email() means it shoyld be email format,,So nice isnt it?? player2: Yup.string().required("Name is required") }) <file_sep>var arr = [10, 1, 9, 2, 8, 3, 7, 4, 6]; arr.sort(); console.log("up \n"); arr.forEach(element => { console.log(element); }); arr.reverse(); console.log("down \n"); arr.forEach(element => { console.log(element); }); console.log("max "); console.log(Math.max(...arr)); console.log("\n"); console.log("min"); console.log(Math.min(...arr)); console.log("\n"); console.log("sum"); var sum = 0; arr.forEach(element => { sum += element; }); console.log(sum); console.log("\n"); const len = arr.length; const arrSort = arr.sort(); const mid = Math.ceil(len / 2); const median = len % 2 == 0 ? (arrSort[mid] + arrSort[mid - 1]) / 2 : arrSort[mid - 1]; console.log("median: ", median); console.log("\n");
0e4a0f0cea51c121609222ba4eeee0262c63b624
[ "JavaScript" ]
4
JavaScript
miwsyed/tictactoe
aa1a5223f3373bb2dcca3a4ad40c30acb6fbbea2
4dec36baeff86cead63e17e190c495ff1251eb71
refs/heads/master
<file_sep>// 定义接口 interface LabelledValue{ label:string; } function printLabel(labelledObj: LabelledValue{ console.log(labelledObj.label); }) let myObj = {size: 10,label: "Size 10 Object"}; printLabel(myObj.label);
35d5de9b0ccec454082bddb847258b5f30a80a2b
[ "TypeScript" ]
1
TypeScript
ChenYCL/vscode_complimer_tsTojs
db8b4baf9da776b4d45e5685f1510c5893eeb1ee
893d90043a40dbba9b338e76f10bc7b743631531
refs/heads/master
<file_sep>//example program of copy contstructor package javaprogramming1.oops; public class Program8 { public static void main(String args[]) { Student s = new Student(101, "Premal"); Student s1 = new Student(); s1 = s; //copying constructor System.out.println("Details of student 1 :- "); System.out.println("Id :- " + s.getId()); System.out.println("Name :- " + s.getName()); System.out.println("Details of sutdent 2 :- "); System.out.println("Id :- " + s1.getId()); System.out.println("Name :- " + s1.getName()); System.out.println("You see both object has same values.."); } } <file_sep>//example program of static variable package javaprogramming1.oops.statickeyword; public class StaticVariable { public static void main(String args[]) { Counter c1 = new Counter(); Counter c2 = new Counter(); Counter c3 = new Counter(); } }<file_sep>package javaprogramming1.oops.polymorphism; public class SuperKeyword { public static void main(String args[]) { Employee emp1 = new Employee(101, "premal", 50000); System.out.println(emp1.toString()); } }<file_sep>package javaprogramming1.oops.abstraction.abstractioninterface; public class Abstraction3 { public static void main(String args[]) { CircleInterface.area(5); } }<file_sep>package javaprogramming1.oops.abstraction.abstractioninterface; public interface Drawable { public abstract void draw(); default void msg() { System.out.println("Messaging.."); } }<file_sep>//program of initializing object using constructor package javaprogramming1.oops; public class Program4 { public static void main(String args[]) { Student s = new Student(1, "Premal"); System.out.println("Id :- "+s.id); System.out.println("Name :- "+s.name); } }<file_sep>package javaprogramming1.operators; public class Assignment { public static void main(String args[]) { int a = 10; // -> 1010 int b = 20; // -> 10100 -> 11110 = 30 System.out.println(b); b |= a; System.out.println(b); } }<file_sep>package javaprogramming1.oops.inheritance; public class MountainBicycle extends Bicycle { int seatHeight; public MountainBicycle(int gear, int speed, int seatHeight) { super(gear, speed); this.seatHeight = seatHeight; } public void setHeight(int seatHeight) { this.seatHeight = seatHeight; } @Override public String toString() { return(super.toString()+"\nHeight of seat :- "+this.seatHeight); } }<file_sep>package javaprogramming1.oops.finalkeyword; //final variable cannot be changed public class FinalVariable { public static void main(String args[]) { final int a = 10; System.out.println("variable :- "+a); } }<file_sep>package javaprogramming1.datatypes; public class Literals { public static void main(String args[]) { int a = 10; int b = 027; int c = 0x64; int d = 123_456_789; double e = 0x13.2P2; System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(d); System.out.println(e); } }<file_sep>package javaprogramming1.oops.polymorphism; public class Employee extends Person{ double salary; { salary = 0; System.out.println("Employee class instance initializer block executed"); } public Employee(int id, String name, double salary) { this.salary = salary; System.out.println("Employee class constructor executed"); } public void setSalary(double salary) { this.salary = salary; } public double getSalary() { return this.salary; } @Override public String toString() { return("Employee id :- "+super.id+"\nEmployee name :- "+super.getName()+"\nEmployee salary :- "+this.salary); } } <file_sep>package javaprogramming1.oops.abstraction.abstractioninterface; public class Abstraction2 { public static void main(String args[]) { PNB pnb = new PNB(); SBI sbi = new SBI(); pnb.getRateOfInterest(); sbi.getRateOfInterest(); } }<file_sep>package javaprogramming1.oops.polymorphism; //This class is being used in UpCasting public class Sbi extends Bank{ String bankName; public Sbi(int id, String branch, String bankName) { super(id, branch); this.bankName = bankName; } @Override public double getRateOfInterest() { return 6.8; } }<file_sep>package javaprogramming1.oops.inheritance; public interface Car { public void run(); public void shiftGear(); }<file_sep>package javaprogramming1.oops.abstraction.abstractioninterface; public interface CircleInterface { final double PI = 3.14; static void area(int r) { System.out.println("\nArea of circle :- "+(PI * r * r)); } }<file_sep>//example program of copying value of one object to another without using copy constructor package javaprogramming1.oops; public class Program9 { public static void main(String args[]) { Student s = new Student(101, "Premal"); Student s1 = new Student(); s1.id = s.id; s1.name = s.name; System.out.println("Details of student 1 :- "); System.out.println("Id :- "+s.getId()); System.out.println("Name :- "+s.getName()); System.out.println("Details of student 2 :- "); System.out.println("Id :- "+s1.getId()); System.out.println("Name :- "+s1.getName()); System.out.println("You see both has same values..."); } }<file_sep>package javaprogramming1.datatypes; public class Character { public static void main(String args[]) { char c = 'x'; //16bits char d = 88; //this will take character value according to ascii character System.out.println("c value :- "+c); System.out.println("d value :- "+d); } }<file_sep>package javaprogramming1.oops.innerclasses; class OuterClass { private String msg = "Hello world"; void display() { System.out.println("Message from outer class :- "+this.msg); } class InnerClass { void display() { System.out.println("Message from inner class :- "+msg); } } } public class MemberInnerClass { public static void main(String args[]) { OuterClass outerClass = new OuterClass(); OuterClass.InnerClass innerClass = outerClass.new InnerClass(); outerClass.display(); innerClass.display(); } }<file_sep>package javaprogramming1.oops.abstraction; public class Main3 { public static void main(String args[]) { SBI sbi = new SBI(); PNB pnb = new PNB(); System.out.println("\nSbi rate of interest :- "+sbi.getRateOfInterest()); System.out.println("\nPNB rate of interest :- "+pnb.getRateOfInterest()); } }<file_sep>package javaprogramming1.oops.abstraction; public abstract class Bank { public abstract double getRateOfInterest(); }<file_sep>package javaprogramming1.datatypes; public class Bools { public static void main(String args[]) { boolean a = true;//1 bit System.out.println("a value :- "+a); System.out.println("10>20 value is :- "+(10>20)); } }<file_sep>package javaprogramming1.oops.finalkeyword; final class Employee { int id = 10; String name; Employee(int id, String name) { this.id = id; this.name = name; } @Override public String toString() { return("Employee id :- "+this.id+"\nEmployee name :- "+this.name); } } public class FinalClass { public static void main(String args[]) { Employee e = new Employee(101, "Premal"); System.out.println(e.toString()); } } <file_sep>package javaprogramming1.datatypes; public class Integer { public static void main(String args[]) { byte a = 10; //8bits short b = 20; //16bits int c = 30; //32bits long d = 40; //64bits System.out.println("Byte value :- "+a); System.out.println("Short value :- "+b); System.out.println("Integer value :- "+c); System.out.println("Long value :- "+d); } }<file_sep>package javaprogramming1.oops.inheritance; public interface Scanner1 extends Showable{ public abstract void scan(); }<file_sep>package javaprogramming1.oops.abstraction.abstractioninterface; public class SBI implements Bank { @Override public void getRateOfInterest() { System.out.println("\n7.5"); } }<file_sep>package javaprogramming1.oops.finalkeyword; class Student { public final void display() { System.out.println("Student class"); } } public class FinalMethod extends Student{ //note :- final methods are inherited but it can't be override public static void main(String args[]) { FinalMethod finalMethod = new FinalMethod(); finalMethod.display(); } } <file_sep>package javaprogramming1.practice; public class PracticeBasic { public static void main(String[] args) { //Data typesLq //numerical data type byte byte_var = 10; //1byte short short_var = 32000;//2byte int int_var = 8;//4byte long long_var = 420000000;//8byte //floating data type float float_var = 32.4f;//4byte double double_var = 42.5;//8byte //bitwise System.out.println("AND :- " + (byte_var & int_var)); // 8 System.out.println("OR :- " + (byte_var | int_var)); // 2 System.out.println("Left shift :- " + (byte_var << 1)); // 20 1010 -> 10100 System.out.println("Right shift :- " + (byte_var >> 1)); // 5 1010 -> 0101 //assignment byte_var += int_var; System.out.println("Addtion assignment :- " + byte_var); byte_var -= int_var; System.out.println("Subtraction assignment :- " + byte_var); byte_var *= int_var; System.out.println("Mulitplication assignment :- " + byte_var); byte_var /= int_var; System.out.println("Division assignment :- " + byte_var); //comparison System.out.println("Grater than :- " + (byte_var > int_var)); System.out.println("less than :- " + (byte_var < int_var)); System.out.println("Greater than equal to :- " + (byte_var >= int_var)); System.out.println("Less than equal to :- " + (byte_var <= int_var)); System.out.println("Equal to :- " + (byte_var == int_var)); System.out.println("Not equal to :- " + (byte_var != int_var)); //logical operators System.out.println("Logical AND :- " + ((byte_var > int_var) && (byte_var < int_var))); System.out.println("Logical OR :- " + ((byte_var > int_var) || (byte_var < int_var))); System.out.println("logical NOT :- " + !((byte_var > int_var || (byte_var < int_var)))); //Conditional Statement if (byte_var > short_var) { System.out.println("Byte is greater"); } else if (short_var > byte_var) { System.out.println("Short is greater"); } else { if (int_var > byte_var && int_var > short_var) { System.out.println("Integer is greater than all"); } else { System.out.println("Short is greater then all"); } } //Switch statement int choice = 4; switch (choice) { case 1: System.out.println("Byte var is selected "); break; case 2: System.out.println("Short var is selected"); break; case 3: System.out.println("Int var is selected"); break; case 4: System.out.println("Long var is selected"); break; default: System.out.println("Enter the valid choice (Among 1 to 4)"); break; } //looping int i = 0; while (i < 5) { System.out.println(i); i++; } i = 0; do { System.out.println(i); i++; } while (i < 5); for (i = 0; i < 5; i++) { System.out.println(i); } int[] arr = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; for (int ele : arr) { System.out.println(ele); } outerLoop: for (i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i >= 1) { break outerLoop; } else { System.out.println(j); } } } } }<file_sep>package javaprogramming1.operators; class Animal { void display() { System.out.println("In animal.."); } } class Dog extends Animal { @Override void display() { System.out.println("In dog.."); } } public class InstanceOf { public static void main(String args[]) { Dog d = new Dog(); System.out.println("Instance of with same object is :- "+(d instanceof Dog)); System.out.println("Instance of with parent class object is :- "+(d instanceof Animal)); Animal a = new Dog(); //upcasting System.out.println("Instance of with same object is :- "+(a instanceof Animal)); System.out.println("Instance of with parent class reference and child class object is :- "+(a instanceof Dog)); a = null; System.out.println("Intance of with null is :- "+(a instanceof Animal));//false } }<file_sep>package javaprogramming1.looping; public class ForLoop { public static void main(String args[]) { int i; for(i = 0 ; i < 10 ; i++) { System.out.println("Loop number :- "+(i+1)); for(int j = 0 ; j < 5 ; j++) { System.out.println(j+1); } } } }<file_sep>package javaprogramming1.oops.polymorphism; class Animal { int a = 10; void display() { System.out.println("In Animal class"); } } class Dog extends Animal { int a = 15; @Override void display() { System.out.println("In Dog class"); } void displayUnique() { System.out.println("In unique method"); } public static Dog downCast(Animal a) { if(a instanceof Dog) { Dog d = (Dog) a; System.out.println("Downcasted"); return d; } return null; } } public class DownCasting { public static void main(String args[]) { Animal a = new Dog(); a.display(); Dog d; System.out.println(a.a); d = Dog.downCast(a); d.displayUnique(); } }<file_sep>package javaprogramming1.oops.abstraction; public abstract class Bike { public Bike() { System.out.println("\nBike is created.."); } public abstract void run(); public void gearChange() { System.out.println("\nGear changed.."); } }<file_sep>package javaprogramming1.oops.polymorphism; //this example is also of covarient datatype also in this we have taken two class having method which overriden and also both have diffrent return types this is supported only if there is non primitive datatype like calss name.. class Bike { public Bike run() { System.out.println("Bike is running..."); return this; } } class MountainBike extends Bike { @Override public MountainBike run() { System.out.println("Mountain bike is running..."); return this; } } public class MethodOverriding { public static void main(String args[]) { MountainBike mountainBike = new MountainBike(); System.out.println(new MountainBike().run().hashCode()); } }<file_sep>package javaprogramming1.oops.inheritance; public class AllCarImpl extends Ferrari implements Lamborghini { @Override public void run() { System.out.println("\nLamborghini Running"); } @Override public void shiftGear() { System.out.println("\nLamborghini Gear shifted"); } public static void main(String args[]) { Lamborghini lamborghini = new AllCarImpl(); Ferrari ferrari = new Ferrari(); lamborghini.run(); lamborghini.shiftGear(); ferrari.run(); ferrari.shiftGear(); } }<file_sep>package javaprogramming1.oops.polymorphism; public class MethodOverloading { public static void sum(int a, int b) { System.out.println("addition :- "+(a+b)); //integer constrain promoted into long } public static void sum(int a, long b) { System.out.println("Subtraction :- "+(a-b)); } public static void sum(long a, long b) { System.out.println("Multiplication :- "+(a*b)); } public static void sum(short a, double b, double x) { System.out.println("Division :- "+(a/b)); } public static void main(String args[]) { sum((short) 10.05, 10, 10.23); } }
984a2f6beadc87994576d88ff59b16554094432f
[ "Java" ]
34
Java
premaluu/JavaProgramming1
9c0df79d0cd081e65780046bd021f0417ef526d8
361f24dc946cba67f47d82fc21ff742aa2dd79f2
refs/heads/master
<repo_name>rlgod/serverless-plugin-simulate<file_sep>/lib/serve.test.js 'use strict' describe('serve', () => { const endpointBase = { functionName: 'test-func', region: 'us-east-1', stage: 'test', servicePath: '/test/file/path', handler: 'index.endpoint', memorySize: 512, timeout: 3, runtime: 'nodejs4.3', environment: {}, http: { }, } const getEndpoint = (endpoint) => Object.assign({}, endpointBase, endpoint ) let express = null let serve = null beforeEach(() => { express = { use: jest.fn(), listen: jest.fn((port, cb) => cb(null)), all: jest.fn(), get: jest.fn(), put: jest.fn(), post: jest.fn(), options: jest.fn(), patch: jest.fn(), } jest.mock('express', () => () => express) serve = require('./serve') // eslint-disable-line global-require }) describe('start', () => { it('should setup post endpoint', () => { const endpoints = [getEndpoint({ http: { integration: 'lambda-proxy', path: '/test/path', method: 'post', }, })] const port = 5000 return serve.start(endpoints, port).then(() => { expect(express.post.mock.calls.length).toBe(1) expect(express.post.mock.calls[0][0]).toBe('/test/path') expect(express.options.mock.calls.length).toBe(0) expect(express.listen.mock.calls.length).toBe(1) }) }) it('should setup ANY endpoint', () => { const endpoints = [getEndpoint({ http: { integration: 'lambda-proxy', path: '/test/path', method: 'any', }, })] const port = 5000 return serve.start(endpoints, port).then(() => { expect(express.all.mock.calls.length).toBe(1) expect(express.all.mock.calls[0][0]).toBe('/test/path') expect(express.options.mock.calls.length).toBe(0) expect(express.listen.mock.calls.length).toBe(1) }) }) it('should setup path part endpoint', () => { const endpoints = [getEndpoint({ http: { integration: 'lambda-proxy', path: '/test/{part}', method: 'get', }, })] const port = 5000 return serve.start(endpoints, port).then(() => { expect(express.get.mock.calls.length).toBe(1) expect(express.get.mock.calls[0][0]).toBe('/test/:part') expect(express.options.mock.calls.length).toBe(0) expect(express.listen.mock.calls.length).toBe(1) }) }) it('should setup greedy path endpoint', () => { const endpoints = [getEndpoint({ http: { integration: 'lambda-proxy', path: '/test/{greedy+}', method: 'get', }, })] const port = 5000 return serve.start(endpoints, port).then(() => { expect(express.get.mock.calls.length).toBe(1) expect(express.get.mock.calls[0][0]).toBe('/test/:greedy(*)') expect(express.options.mock.calls.length).toBe(0) expect(express.listen.mock.calls.length).toBe(1) }) }) it('should setup cors endpoints', () => { const endpoints = [getEndpoint({ http: { integration: 'lambda-proxy', path: '/test/path', method: 'post', cors: { origins: ['*'], methods: ['OPTIONS', 'POST'], headers: [ 'My-Header', ], allowCredentials: true, }, }, })] const port = 5000 return serve.start(endpoints, port).then(() => { expect(express.post.mock.calls.length).toBe(1) expect(express.post.mock.calls[0][0]).toBe('/test/path') expect(express.options.mock.calls.length).toBe(1) expect(express.options.mock.calls[0][0]).toBe('/test/path') expect(express.listen.mock.calls.length).toBe(1) }) }) }) }) <file_sep>/lib/integration/index.test.js 'use strict' const lambda = { event: jest.fn(), response: jest.fn(), error: jest.fn(), } const lambdaProxy = { event: jest.fn(), response: jest.fn(), error: jest.fn(), } jest.mock('./lambda', () => lambda) jest.mock('./lambda-proxy', () => lambdaProxy) const integration = require('./index') describe('integration', () => { beforeEach(() => { lambda.event.mockClear() lambda.response.mockClear() lambdaProxy.event.mockClear() lambdaProxy.response.mockClear() }) describe('event', () => { it('should invoke lambda integration', () => { const req = { context: { http: { integration: 'lambda', }, }, logger: (msg) => console.log(msg), // eslint-disable-line no-console } return integration.event(req).then(() => { expect(lambda.event.mock.calls.length).toBe(1) expect(lambda.event.mock.calls[0][0]).toBe(req) }) }) it('should invoke lambda-proxy integration', () => { const req = { context: { http: { integration: 'lambda-proxy', }, }, logger: (msg) => console.log(msg), // eslint-disable-line no-console } return integration.event(req).then(() => { expect(lambdaProxy.event.mock.calls.length).toBe(1) expect(lambdaProxy.event.mock.calls[0][0]).toBe(req) }) }) }) describe('response', () => { it('should invoke lambda integration', () => { const req = { context: { http: { integration: 'lambda', }, }, logger: (msg) => console.log(msg), // eslint-disable-line no-console } const result = {} return integration.response(req, result).then(() => { expect(lambda.response.mock.calls.length).toBe(1) expect(lambda.response.mock.calls[0][0]).toBe(req) expect(lambda.response.mock.calls[0][1]).toBe(result) }) }) it('should invoke lambda-proxy integration', () => { const req = { context: { http: { integration: 'lambda-proxy', }, }, logger: (msg) => console.log(msg), // eslint-disable-line no-console } const result = {} return integration.response(req, result).then(() => { expect(lambdaProxy.response.mock.calls.length).toBe(1) expect(lambdaProxy.response.mock.calls[0][0]).toBe(req) expect(lambdaProxy.response.mock.calls[0][1]).toBe(result) }) }) }) describe('error', () => { it('should invoke lambda integration', () => { const req = { context: { http: { integration: 'lambda', }, }, logger: (msg) => console.log(msg), // eslint-disable-line no-console } const err = {} return integration.error(req, err).then(() => { expect(lambda.error.mock.calls.length).toBe(1) expect(lambda.error.mock.calls[0][0]).toBe(req) expect(lambda.error.mock.calls[0][1]).toBe(err) }) }) it('should invoke lambda-proxy integration', () => { const req = { context: { http: { integration: 'lambda-proxy', }, }, logger: (msg) => console.log(msg), // eslint-disable-line no-console } const err = {} return integration.error(req, err).then(() => { expect(lambdaProxy.error.mock.calls.length).toBe(1) expect(lambdaProxy.error.mock.calls[0][0]).toBe(req) expect(lambdaProxy.error.mock.calls[0][1]).toBe(err) }) }) }) }) <file_sep>/lib/authorizer/index.test.js 'use strict' const customAuthorizer = { authorize: jest.fn(), } jest.mock('./custom-authorizer', () => customAuthorizer) const authorizer = require('./index') describe('authorizer', () => { beforeEach(() => { customAuthorizer.authorize.mockClear() }) it('should invoke custom authorizer', () => { const context = {} const authorizationToken = 'Bearer token' authorizer.authorize(context, authorizationToken) expect(customAuthorizer.authorize.mock.calls.length).toBe(1) expect(customAuthorizer.authorize.mock.calls[0][0]).toBe(context) expect(customAuthorizer.authorize.mock.calls[0][1]).toBe(authorizationToken) }) })
f090204750f131f5bc90cfe923d4a8fa3a25374c
[ "JavaScript" ]
3
JavaScript
rlgod/serverless-plugin-simulate
b434684fe6bfb44a1e844275edc95ee2cb1d81a4
328bc4970ff0b79d0b8e5bd70743ff47b7a1fa3f
refs/heads/master
<repo_name>matthewjstott/CMB_axiverse_statistics<file_sep>/proba_axiverse_rmt.py ##### This script calculates the probability of the axiverse given ##### i) Cosmological constraints ##### ii) A probability distribution for mu, alpha, theta_i ##### It is based on a simple MC algorithm, and a binary check: ##### A model is allowed if it does not exceed the 95%CL on Om_zc. ##### credit: <NAME>, <NAME>, 09.20.2018 import numpy as np import matplotlib.pyplot as plt import scipy.special as sci from matplotlib import rc from scipy.interpolate import interp1d from scipy.interpolate import InterpolatedUnivariateSpline from sympy import Eq, Symbol, solve, nsolve from mpl_toolkits.mplot3d import Axes3D from functools import reduce import numpy.random as rd #rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) ## for Palatino and other serif fonts use: rc('font',**{'family':'serif','serif':['Times New Roman']}) rc('text', usetex=True) #### Define cosmological parameters ##### Omega_m = 0.3 Omega_r = 8e-5 Omega_Lambda = 1-Omega_m #### Define model parameters ##### n=1 F=7./8 p=1./2 ##will be checked later #### Read and interpolate constraints ##### Omega_at_zc = np.loadtxt("Omega_at_zc.dat") interp_constraints_log_extrap = InterpolatedUnivariateSpline(np.log10(Omega_at_zc[:,0]),np.log10(Omega_at_zc[:,1]),k=1) interp_constraints_log_interp = interp1d(np.log10(Omega_at_zc[:,0]),np.log10(Omega_at_zc[:,1])) #### Define distribution properties ##### ###parameters of a log flat distribution (currently centered on 0 +- 2) # log_mu_min_min = -2 ##minimal value # log_mu_min_max = 10 ##minimal value # log_mu_size_min = 1 ##min size of the interval. # log_mu_size_max = 20 ##max size of the interval. # log_alpha_min = -2 # log_alpha_size = 2 # ##FOR PLOTTING ONLY## log_mu_min_min = 4 ##minimal value log_mu_min_max = 10 ##minimal value##NOTUSED log_mu_size_min = 4 ##min size of the interval. log_mu_size_max = 20 ##max size of the interval.##NOTUSED log_alpha_min = -2 log_alpha_size = 2 ##for a future gaussian distribution ##var_log_mu = ## mean_log_mu = 3 ## log_mu = var_log_mu*np.abs(np.random.rand())*np.pi+mean_log_mu ######################### RMT PARAMETERS ##################################################### kinetic_shaping_param=0.95 #Distribution shaping parameter for the kinetic matrix mass_shaping_param=0.15 #Distribution shaping parameter for the mass matrix decay_first_raw_moment=1 #Fixes the mean scale for the decacy constants mass_first_raw_moment=1 #Fixes the mean mass scale of the theory number_of_samples=200 #Dimensionality of the matrices, should be sufficiently large for universality i.e>50 number_of_iterations=30 #Accuracy parameter for the three-dimensional sampling space k_cov = False #Fixes wether we model a population covariance matrix for the Kinetic matrix, if False the population covariance matrix is the identity m_cov = False #Fixes wether we model a population covariance matrix for the Mass matrix, if False the population covariance matrix is the identity model_K = True #Fixes if we consider priors on the kinetic matrix, if false we assume we begin in the kinetically aligned basis ############################################################################################### mass_samples=np.array([]) decay_samples=np.array([]) phi_samples=np.array([]) L1=int(number_of_samples/kinetic_shaping_param) L2=int(number_of_samples/mass_shaping_param) for j in range(0,number_of_iterations): print(j) if model_K == True: if k_cov==True: kinetic_sub = decay_first_raw_moment*(np.random.randn(number_of_samples, L1)) kinetic_isometric = np.dot(kinetic_sub,(kinetic_sub.T))/L1 kinetic_covariance = numpy.identity(number_of_samples) kinetic_matrix = np.dot(kinetic_isometric,kinetic_covariance) else: kinetic_sub = decay_first_raw_moment*(np.random.randn(number_of_samples, L1)) kinetic_matrix = np.dot(kinetic_sub,(kinetic_sub.T))/L1 else: kinetic_matrix = numpy.identity(number_of_samples) ev,p = np.linalg.eig(kinetic_matrix) decay_constants = np.sqrt(np.abs(2*ev)) log_deacy_constants = np.log10(decay_constants) decay_samples=np.append(decay_samples,log_deacy_constants) kD = reduce(np.dot, [p.T, kinetic_matrix, p]) kD[kD < 1*10**-13] = 0 perturbative_matrix = np.zeros((number_of_samples, number_of_samples)) np.fill_diagonal(perturbative_matrix, 1/(decay_constants)) if m_cov==True: mass_sub = mass_first_raw_moment*(np.random.randn(number_of_samples, L2)) mass_isometric = np.dot(mass_sub,(mass_sub.T))/L2 mass_covariance = numpy.identity(number_of_samples) mass_matrix = np.dot(kinetic_isometric,kinetic_covariance) else: mass_sub = mass_first_raw_moment*(np.random.randn(number_of_samples, L2)) mass_marix = np.dot(mass_sub,(mass_sub.T))/L2 mass_eigenstate_matrix = 2.*reduce(np.dot, [perturbative_matrix,p,mass_marix,p.T,perturbative_matrix.T]) mass_eigenstates,mv = np.linalg.eig(mass_eigenstate_matrix) #ma_array = np.sqrt(ma_array) log_mass_eigenstates = np.log10(mass_eigenstates) mass_samples=np.append(mass_samples,log_mass_eigenstates) phiin_array = rd.uniform(-np.pi,np.pi,number_of_samples) for i in range (0,number_of_samples): phiin_array[i] = phiin_array[i]*decay_constants[i] phiin_array=np.dot(mv,phiin_array) phiin_array = np.log10(np.abs(phiin_array)) phi_samples=np.append(phi_samples,phiin_array) ########################################################################## #### some additional checks #### print_in_file = False print_in_screen = True plot_results = True #### How many iterations? ##### max_iterations = 300 j = 0 fraction_allowed = [] f2 = open('fraction_models_allowed_axiverse.dat', 'w') f2.write('# log_mu_min \t\t log_mu_size \t\t frac \n') # column titles fraction_table = [] log_mu_min_table = [] log_mu_size_table = [] log_mu_min = log_mu_min_min while log_mu_min < log_mu_min_max: log_mu_size = log_mu_size_min while log_mu_size < log_mu_size_max: print("log_mu_min:", log_mu_min, "log_mu_size:", log_mu_size) #### Define some tables for writing ##### if plot_results is True: mu_excluded = [] alpha_excluded = [] zc_excluded = [] frac_zc_excluded = [] Theta_i_excluded = [] mu_allowed = [] alpha_allowed = [] zc_allowed = [] frac_zc_allowed = [] Theta_i_allowed = [] all_mu = [] all_alpha = [] all_Theta = [] #### The code really starts here! ##### total = 0 allowed = 0 excluded = 0 while total < max_iterations: total +=1 ##Draw from log flat distribution## log_mu = np.random.rand()*log_mu_size+log_mu_min #np.random.rand() draws in [0,1) ##log_mu_min is negative! mu = 10**log_mu log_alpha = np.random.rand()*log_alpha_size+log_alpha_min alpha = 10**log_alpha ##Draw from flat distribution Theta_i = np.random.rand()*np.pi ##draws from [0;pi) if plot_results is True: all_mu.append(log_mu) all_alpha.append(log_alpha) all_Theta.append(Theta_i) ##Calculate Omega_at_zc and zc Omega_zc = 1./6*alpha*alpha*mu*mu*(1-np.cos(Theta_i))**n xc = (1-np.cos(Theta_i))**((1-n)/2)/mu*np.sqrt((1-F)*(6*p+2)*Theta_i/(n*np.sin(Theta_i))) zc = Symbol('zc') Results = solve(Omega_m*(1+zc)**3.0+Omega_r*(1+zc)**4+Omega_Lambda-(p/xc)**2,zc) ##nb: this assumes negligible Omega_zc. What if not?? zc_found = 0 ##Results is a table with 4 entries: the 2 firsts are real, one of which is positive: this is our zc. if Results[0] > 0: zc_found = Results[0] if Results[1] > 0: zc_found = Results[1] ##Check that our hypothesis of zc>z_eq was correct. Otherwise we recalculate. if zc_found < Omega_m/Omega_r: p=2./3 xc = (1-np.cos(Theta_i))**((1-n)/2)/mu*np.sqrt((1-F)*(6*p+2)*Theta_i/(n*np.sin(Theta_i))) zc = Symbol('zc') Results = solve(Omega_m*(1+zc)**3.0+Omega_r*(1+zc)**4+Omega_Lambda-(p/xc)**2,zc) if Results[0] > 0: zc_found = Results[0] if Results[1] > 0: zc_found = Results[1] if zc_found == 0: zc_found = Results[1] if print_in_screen is True: print("Weird! zc is negative: it might mean that the field is a dark energy candidate.") print("mu:", mu, "alpha:", alpha, "Theta_i:", Theta_i, "Omega_zc:", Omega_zc, "xc:", xc, "zc:", Results[1]) #print(Results) ## Currently compares to Lambda: if = or less, assume it is viable. TO BE IMPROVED. if Omega_zc <= Omega_Lambda: if plot_results is True: mu_allowed.append(log_mu) alpha_allowed.append(log_alpha) zc_allowed.append(-np.log10(float((zc_found*zc_found)**0.5))) frac_zc_allowed.append(0) Theta_i_allowed.append(Theta_i) allowed+=1 else: if plot_results is True: mu_excluded.append(log_mu) alpha_excluded.append(log_alpha) zc_excluded.append(np.log10(float(zc_found))) frac_zc_excluded.append(np.log10(Omega_zc/(Omega_m*(1+float(zc_found))**3.0+Omega_r*(1+float(zc_found))**4+Omega_Lambda))) Theta_i_excluded.append(Theta_i) excluded+=1 else: if print_in_screen is True: print("mu:", mu, "alpha:", alpha, "Theta_i:", Theta_i, "Omega_zc:", Omega_zc, "xc:", xc, "log10_ac:", np.log10(float(1/zc_found))) ##interp1d is more stable but cannot extrapolate. if 0 > np.log10(float(1/zc_found)) > -6: # print "interpolation",np.log10(float(1/zc_found)) if interp_constraints_log_interp(np.log10(float(1/zc_found))) < np.log10(Omega_zc) : if print_in_screen is True: print("EXCLUDED",interp_constraints_log_interp(np.log10(float(1/zc_found))), "<",np.log10(Omega_zc), "at ac=",1/zc_found) if plot_results is True: mu_excluded.append(log_mu) alpha_excluded.append(log_alpha) zc_excluded.append(np.log10(float(zc_found))) frac_zc_excluded.append(np.log10(Omega_zc/(Omega_m*(1+float(zc_found))**3.0+Omega_r*(1+float(zc_found))**4+Omega_Lambda))) Theta_i_excluded.append(Theta_i) excluded+=1 ##increment the number of points excluded else: if print_in_screen is True: print("allowed",interp_constraints_log_interp(np.log10(float(1/zc_found))), ">", np.log10(Omega_zc), "at ac=",1/zc_found) if plot_results is True: mu_allowed.append(log_mu) alpha_allowed.append(log_alpha) zc_allowed.append(np.log10(float(zc_found))) frac_zc_allowed.append(np.log10(Omega_zc/(Omega_m*(1+float(zc_found))**3.0+Omega_r*(1+float(zc_found))**4+Omega_Lambda))) Theta_i_allowed.append(Theta_i) allowed+=1 ##increment the number of points allowed else: # print "extrapolation" if interp_constraints_log_extrap(np.log10(float(1/zc_found))) < np.log10(Omega_zc) : if print_in_screen is True: print("EXCLUDED",interp_constraints_log_extrap(np.log10(float(1/zc_found))), "<",np.log10(Omega_zc), "at ac=",1/zc_found) if plot_results is True: mu_excluded.append(log_mu) alpha_excluded.append(log_alpha) Theta_i_excluded.append(Theta_i) excluded+=1 ##increment the number of points excluded else: if print_in_screen is True: print("allowed",interp_constraints_log_extrap(np.log10(float(1/zc_found))), ">", np.log10(Omega_zc), "at ac=",1/zc_found) if plot_results is True: mu_allowed.append(log_mu) alpha_allowed.append(log_alpha) zc_allowed.append(np.log10(float(zc_found))) frac_zc_allowed.append(np.log10(Omega_zc/(Omega_m*(1+float(zc_found))**3.0+Omega_r*(1+float(zc_found))**4+Omega_Lambda))) Theta_i_allowed.append(Theta_i) allowed+=1 ##increment the number of points allowed fraction = allowed*1.0/max_iterations print("fraction of models allowed = ", fraction) fraction_table.append(fraction) log_mu_min_table.append(log_mu_min) log_mu_size_table.append(log_mu_size) f2.write(str(log_mu_min) + '\t\t' + str(log_mu_size) + '\t\t' + str(fraction) +'\n') # writes the array to file #### if needed, write to output file #### if print_in_file is True: f = open('allowed_models_axiverse.dat', 'w') f.write('# mu \t\t alpha \t\t Theta_i \n') # column titles for i in range(allowed): f.write(str(mu_allowed[i]) + '\t\t' + str(alpha_allowed[i]) + '\t\t' + str(Theta_i_allowed[i]) +'\n') # writes the array to file f.close() #### if needed, plot the allowed parameters #### if plot_results is True: fig = plt.figure() # ax = fig.add_subplot(111, projection='3d') # ax2 = fig.add_subplot(211, projection='3d') # # ax.set_xlim(log_mu_min,log_mu_min+log_mu_size) # # ax.set_ylim(log_alpha_min,log_alpha_min+log_alpha_size) # ax.set_zlim(0,np.pi) # ax.set_xlabel(r"$z_c$", fontsize=16) # ax.set_ylabel(r"$f(z_c)$", fontsize=16) # ax.set_zlabel(r"$\Theta_i$", fontsize=16) # print(len(zc_allowed),len(frac_zc_allowed),len(Theta_i_allowed)) # ax.scatter(zc_allowed,frac_zc_allowed,Theta_i_allowed,c='b') ax2 = fig.add_subplot(111, projection='3d') ax2.set_xlim(log_mu_min,log_mu_min+log_mu_size) ax2.set_ylim(log_alpha_min,log_alpha_min+log_alpha_size) ax2.set_zlim(0,np.pi) ax2.set_xlabel(r"$\mu$", fontsize=16) ax2.set_ylabel(r"$\alpha$", fontsize=16) ax2.set_zlabel(r"$\Theta_i$", fontsize=16) ax2.scatter(mu_allowed,alpha_allowed,Theta_i_allowed,c='b') ax2.scatter(mu_excluded,alpha_excluded,Theta_i_excluded,c='r') # print("total=",len(all_mu),len(mu_allowed)+len(mu_excluded),mu_allowed,mu_excluded) plt.show() #### calculate the fraction of allowed models #### log_mu_size+=1 log_mu_min+=1 fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.set_xlabel(r"$\mu_{\rm min}$", fontsize=16) ax.set_ylabel(r"$\Delta \mu$", fontsize=16) ax.set_zlabel(r"$p_{\rm allowed}$", fontsize=16) print(len(log_mu_min_table),len(log_mu_size_table),len(fraction_table)) ax.scatter(log_mu_min_table,log_mu_size_table,fraction_table,c='b') plt.show() f2.close() <file_sep>/README.md # The Axiverse and the CMB Theories with a large number of degrees of freedom are best tested by statistical means. Multi-axion theories (“the axiverse”) can be described by distribution functions for the mass,ma, decayconstant,fa, and initial misalignment angle, \theta_i, of each axion. The CMB measurement of the darkmatter density, and the agreement of the shape of the anistropy spectrum with the cosmologicalstandard model, constrain the existence of stable light, axions with large energy density. We presentthe first constraints on multi-axion theories from thePlanckcosmic microwave background (CMB)anisotropies via the use of a simplified likelihood function in a quasi-Bayesian analysis. A theorywithNaxaxions results fromNaxcorrelated draws from the (ma,fa,θi) prior distributions. Thedistribution functions are described by hyperparameters, themselves subject to priors. Hyper parameters leading to distributions with a high probability of one ore more axions lying in the excludedregion are disfavoured. The results can be interpreted in terms of various random matrix models forthe axion kinetic and mass matrices, which generate the hyperparameters and distribution functions. Repo for probability of realising an axiverse with constraints from the CMB. See https://arxiv.org/abs/1806.10608
83e6ad1b40d17d7826a71f767820ce929a9957da
[ "Markdown", "Python" ]
2
Python
matthewjstott/CMB_axiverse_statistics
0fc77cbd0c2fca8ccf29887ba5ac122bf9c1e346
1a7932fb5a036817873e95ad1ecce2cc8d5ca89b
refs/heads/master
<repo_name>alemasar/webpack-config<file_sep>/config.rb preferred_syntax = :sass http_path = '/' sourcemap = true css_dir = 'dist/css/' sass_dir = './src/sass/' images_dir = './dist/img/' relative_assets = false line_comments = true # output_style = :compressed<file_sep>/app.js import Vue from 'vue' import Component from 'vue-class-component' import Vuex from 'vuex' import VueRx from 'vue-rx' import { Observable } from 'rxjs/Observable' import { Subscription } from 'rxjs/Subscription' // Disposable if using RxJS4 import { Subject } from 'rxjs/Subject' // required for domStreams option import store from '../../../store' import menuComponent from '@/components/menu-component/menu-component' Vue.use(Vuex); Vue.use(VueRx, { Observable, Subscription, Subject }); Vue.use(Vuex); @Component({ components: { menuComponent }, store, domStreams: ['plus$'], subscriptions: function () { this.plus$ = new Subject() // ...then create subscriptions using the Subjects as source stream. // the source stream emits in the form of { event: HTMLEvent, data?: any } return { mydata: this.plus$ } } }) export default class App extends Vue { mydata = "<NAME> madre"; constructor() { super(); } created() { //console.log(store); //store.commit('getParentData', this.$parent.$el.attributes["mydata"].value) } // Ejemplo de como passar data desde fuera la app beforeMount() { this.getRootData(); } mounted() { //this.$parent.$el.attributes["mydata"].value console.log(this.$store.state.count); } getRootData() { this.$observables.mydata.next(this.$root.$el.attributes["mydata"].value); //this.$observables.mydata.next(this.$parent.$el.attributes["mydata"].value); this.$store.commit('setParentData', this.$root.$el.attributes["mydata"].value, { root: true }); } } //new App({el: '#app'}).$mount()
ee49695f411543193e5663263bf497722b57a01e
[ "JavaScript", "Ruby" ]
2
Ruby
alemasar/webpack-config
47cc4a3b5227cc7ffea118c56b0fa8fc776354f4
3fad6781e0a8bcb071d934071bf514fb5c90171d
refs/heads/master
<file_sep><?php namespace App\Http\Controllers\Api; use App\Specialty; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class SpecialtiesController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { try { $specialty = Specialty::all(); return response()->json($specialty); } catch (\Exception $e) { return response()->json(['error' => $e->getMessage()], 500); } } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { try { $specialty = new Specialty(); $specialty->fill($request->all()); $specialty->save(); return response()->json($specialty, 201); } catch (\Exception $e) { return response()->json(['error' => $e->getMessage()], 500); } } /** * Display the specified resource. * * @param \App\Specialty $specialty * @return \Illuminate\Http\Response */ public function show(Specialty $specialty) { if (!$specialty->id) return response()->json([], 404); try { return response()->json($specialty); } catch (\Exception $e) { return response()->json(['error' => $e->getMessage()], 500); } } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Specialty $specialty * @return \Illuminate\Http\Response */ public function update(Request $request, Specialty $specialty) { try { $specialty->fill($request->all()); $specialty->save(); return response()->json($specialty, 200); } catch (\Exception $e) { return response()->json(['error' => $e->getMessage()], 500); } } /** * Remove the specified resource from storage. * * @param \App\Specialty $specialty * @return \Illuminate\Http\Response */ public function destroy(Specialty $specialty) { try { Specialty::destroy($specialty->id); return response()->json('', 204); } catch (\Exception $e) { return response()->json(['error' => $e->getMessage()], 500); } } } <file_sep>import React, {useEffect, useState} from 'react'; import {Link, useHistory, useLocation} from 'react-router-dom'; import api from '../services/api'; function Form() { let location = useLocation(); const doctor = location?.state?.doctor || {}; const history = useHistory(); const [specialtiesList, setSpecialtiesList] = useState([]); const [specialty, setSpecialty] = useState(''); const [name, setName] = useState(doctor.name); const [crm, setCrm] = useState(doctor.crm); const [phone, setPhone] = useState(doctor.phone); const [specialties, setSpecialties] = useState(doctor.specialties || []); useEffect(() => { (async () => { await !localStorage.getItem('token') && await history.push('/') })(); getSpecialties(); }, []); const getSpecialties = async () => { await api.get('/specialties?token=' + localStorage.getItem('token')) .then(async (res) => { await setSpecialtiesList(res.data); }) .catch(() => { localStorage.setItem('token', ''); history.push('/'); }); }; const handleChooseSpecialty = async (e) => { e.preventDefault(); function specialtyExists(id) { return (specialties.filter((s) => s.id == id).length > 0); } if (!specialtyExists(specialty)) { const specialtyChoosen = specialtiesList.filter(s => s.id == specialty)[0]; setSpecialties([...specialties, specialtyChoosen]); } }; const handleSave = async (e) => { e.preventDefault(); if (specialties.length < 2) { alert('Selecione pelo menos 2 especialidades'); return false; } const method = doctor.id ? 'put' : 'post'; const url = '/doctors' + (doctor.id ? '/' + doctor.id : ''); await api[method](url + '?token=' + localStorage.getItem('token'), { name, crm, phone, "specialties": specialties.map(s => s.id) }) .then((res) => { history.push('/home'); }) .catch(() => { alert('Erro ao salvar'); //history.push('/') }) }; const handleRemoveChoosenSpecialty = (id) => { setSpecialties(specialties.filter(s => s.id != id)); }; return ( <div className="container"> <div className="row justify-content-center"> <div className="col-12 col-sm-6 pt-5"> <h1 className="text-primary text-center pb-5">DoctorsList</h1> <div className="card text-center p-5"> <div className="card-body w-100 d-flex flex-column justify-content-center align-items-center"> {!doctor.id && <h5 className="card-title">Cadastre um novo médico</h5>} {!!doctor.id && <h5 className="card-title">Editando {doctor.name} </h5>} <form className="form d-block w-100" onSubmit={e => handleSave(e)}> <input type="text" className="form-control my-2" placeholder="Nome" required value={name} onChange={e => setName(e.target.value)}/> <input type="text" className="form-control my-2" placeholder="CRM" required value={crm} onChange={e => setCrm(e.target.value)}/> <input type="text" className="form-control my-2" placeholder="Telefone" required value={phone} maxLength={11} onChange={e => setPhone(e.target.value)}/> <hr/> <h5 className="mt-5">Especialidades</h5> <div className="input-group w-100"> <select className="form-control" value={specialty} onChange={e => setSpecialty(e.target.value)}> <option value="" disabled hidden> Selecione uma opção </option> {specialtiesList.map((option) => { return ( <option key={option.id} value={option.id}> {option.name} </option> ); })} </select> <div className="input-group-append"> <button type="button" className="btn btn-outline-primary" onClick={handleChooseSpecialty}> <i className="fa fa-plus"/> </button> </div> </div> <div className="col-12 pt-3"> {specialties.map((spec, i) => { return ( <div key={spec.id}> <div className="text-primary d-flex justify-content-between pt-1"> <span>{spec.name}</span> <button className="btn btn-link" type="button" onClick={() => handleRemoveChoosenSpecialty(spec.id)}> <i className="fa fa-times"/> </button> </div> <hr className="my-1 p-0"/> </div> ); })} </div> <div className="row"> <div className="col-12 d-flex justify-content-between"> <Link to="/" className="btn btn-outline-primary mt-5"> <i className="fa fa-chevron-left"/> Voltar </Link> <button className="btn btn-primary mt-5" type="submit"> <i className="fa fa-check"/> {doctor.id ? 'Salvar' : 'Cadastrar'} </button> </div> </div> </form> </div> </div> </div> </div> </div> ); } export default Form; <file_sep><?php namespace App\Http\Controllers\Api; use App\Doctor; use App\Http\Controllers\Controller; use App\Specialty; use Illuminate\Http\Request; class DoctorsController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { try { if ($request->search) { $doctors = Doctor::query()->where('name', 'like', '%' . $request->search . '%') ->orWhere('crm', 'like', '%' . $request->search . '%')->get(); } else { $doctors = Doctor::all(); } return response()->json($doctors->toArray()); } catch (\Exception $e) { return response()->json(['error' => $e->getMessage()], 500); } } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { try { $doctor = new Doctor(); $doctor->fill($request->only(['name', 'crm', 'phone'])); if (count($request->specialties) < 2) return response()->json(['error' => 'At least 2 specialties required'], 400); $doctor->save(); $specialties = Specialty::find($request->specialties); $doctor->specialties()->attach($specialties); return response()->json($doctor, 201); } catch (\Exception $e) { return response()->json(['error' => $e->getMessage()], 500); } } /** * Display the specified resource. * * @param \App\Doctor $Doctor * @return \Illuminate\Http\Response */ public function show(Doctor $doctor) { if (!$doctor->id) return response()->json([], 404); try { return response()->json($doctor->toArray()); } catch (\Exception $e) { return response()->json(['error' => $e->getMessage()], 500); } } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Doctor $Doctor * @return \Illuminate\Http\Response */ public function update(Request $request, Doctor $doctor) { try { $doctor->fill($request->only(['name', 'crm', 'phone'])); if (count($request->specialties) < 2) return response()->json(['error' => 'At least 2 specialties required'], 400); $doctor->save(); $doctor->specialties()->detach(); $specialties = Specialty::find($request->specialties); $doctor->specialties()->attach($specialties); return response()->json($doctor, 200); } catch (\Exception $e) { return response()->json(['error' => $e->getMessage()], 500); } } /** * Remove the specified resource from storage. * * @param \App\Doctor $Doctor * @return \Illuminate\Http\Response */ public function destroy(Doctor $doctor) { try { Doctor::destroy($doctor->id); return response()->json('', 204); } catch (\Exception $e) { return response()->json(['error' => $e->getMessage()], 500); } } } <file_sep><?php namespace Tests\Feature; use App\User; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; use Tymon\JWTAuth\Facades\JWTAuth; class ApiTest extends TestCase { use RefreshDatabase; public function test_user_cannot_retrieve_without_token() { $response = $this->get('/api/specialties'); die($response->status().''); $response->assertStatus(401); } public function test_user_retrieve_from_api_with_valid_token() { $user = factory(User::class)->create(); $token = JWTAuth::fromUser($user); $response = $this->get('/api/specialties?token=' . $token); $response->assertStatus(200); } } <file_sep><?php namespace App\Http\Controllers\Api; use App\Doctor; use App\Http\Controllers\Controller; use App\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; class UsersController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { try { $users = User::all(); return response()->json($users); } catch (\Exception $e) { return response()->json(['error' => $e->getMessage()], 500); } } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { try { $user = new User(); $user->fill($request->all()); $password = $request->password; $user->password = <PASSWORD>($password); $user->save(); return response()->json($user, 201); } catch (\Exception $e) { return response()->json(['error' => $e->getMessage()], 500); } } /** * Display the specified resource. * * @param \App\Doctor $Doctor * @return \Illuminate\Http\Response */ public function show(Doctor $doctor) { if (!$doctor->id) return response()->json([], 404); try { return response()->json($doctor); } catch (\Exception $e) { return response()->json(['error' => $e->getMessage()], 500); } } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Doctor $Doctor * @return \Illuminate\Http\Response */ public function update(Request $request, Doctor $Doctor) { try { $doctor = new Doctor(); $doctor->fill($request->all()); $doctor->save(); return response()->json($doctor, 200); } catch (\Exception $e) { return response()->json(['error' => $e->getMessage()], 500); } } /** * Remove the specified resource from storage. * * @param \App\Doctor $Doctor * @return \Illuminate\Http\Response */ public function destroy(Doctor $Doctor) { // } } <file_sep><?php namespace Tests\Feature; use App\User; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Config; use Tests\TestCase; use Tymon\JWTAuth\Facades\JWTAuth; class LoginTest extends TestCase { use RefreshDatabase; public function test_everyone_needs_to_be_redirected_to_react_login_when_404_error() { $response = $this->get('/my-non-existent-url'); $response->assertRedirect('/'); $response->assertStatus(302); } public function test_user_cannot_login_with_incorrect_password() { $password = <PASSWORD>('<PASSWORD>'); $user = factory(User::class)->create([ 'password' => $<PASSWORD>, ]); $response = $this->post('/api/auth/login', [ 'email' => $user->email, 'password' => '<PASSWORD>', ]); $response->assertStatus(401); $this->assertGuest(); } public function test_user_can_login_with_correct_credentials() { $password = <PASSWORD>('<PASSWORD>'); $user = factory(User::class)->create([ 'password' => <PASSWORD>($<PASSWORD>), ]); $response = $this->post('/api/auth/login', [ 'email' => $user->email, 'password' => $<PASSWORD>, ]); $this->assertAuthenticatedAs($user); $response->assertStatus(200); $response->assertJsonStructure([ 'access_token', 'token_type', 'expires_in' ]); } public function test_logout() { $user = factory(User::class)->create(); $token = JWTAuth::fromUser($user); $baseUrl = Config::get('app.url') . '/api/auth/logout?token=' . $token; $response = $this->json('POST', $baseUrl, []); $response ->assertStatus(200) ->assertExactJson([ 'message' => 'Successfully logged out' ]); } } <file_sep>import React, {useEffect, useState} from 'react'; import {Link, useHistory} from 'react-router-dom'; import api from '../services/api'; import Doctor from '../components/Doctor'; function Search() { const history = useHistory(); const [doctors, setDoctors] = useState([]); const [search, setSearch] = useState(''); useEffect(() => { getDoctors(); }, []); const getDoctors = async () => { await api.get('/doctors?token=' + localStorage.getItem('token') + (search ? '&search=' + search : '')) .then(async (res) => { await setDoctors(res.data); }) .catch(() => { localStorage.setItem('token', ''); history.push('/'); }); }; const handleFormSubmit = e => { e.preventDefault(); getDoctors(); }; return ( <div className="container"> <div className="row justify-content-center"> <div className="col-md-8 pt-5"> <h1 className="text-primary text-center">DoctorsList</h1> <div className="card border-0 text-center"> <div className="card-header"> <form onSubmit={(e) => handleFormSubmit(e)}> <div className="input-group"> <input type="text" className="form-control" placeholder="Pesquise por Nome ou CRM" aria-label="Pesquise por Nome ou CRM" aria-describedby="basic-addon2" onChange={e => setSearch(e.target.value)}/> <div className="input-group-append"> <button className="btn btn-outline-primary" type="submit"> <i className="fa fa-search"/> </button> <Link to="/doctor" className="btn btn-primary" type="button"> <i className="fa fa-user-alt"/>&nbsp;<i className="fa fa-plus"/> </Link> </div> </div> </form> </div> {!doctors.length && (<div className="card-body"> <p className="card-text">Sua pesquisa não obteve resultados</p> </div>)} {!!doctors.length && ( <div className="row"> <div className="col-12"> <h3 className="card-title my-3">Médicos encontrados</h3> </div> {doctors.map((doctor) => ( <Doctor key={doctor.id} doctor={doctor} listCallback={getDoctors}/> ))} </div> )} <div className="card-footer text-muted"> {doctors.length} resultados </div> </div> </div> </div> </div> ); } export default Search; <file_sep>import React from "react"; import {BrowserRouter, Route} from "react-router-dom"; import Login from "./pages/Login"; import Search from "./pages/Search"; import Form from "./pages/Form"; function Routes() { return ( <BrowserRouter> <Route path="/" exact component={Login}/> <Route path="/home" component={Search}/> <Route path="/doctor" component={Form}/> </BrowserRouter> ); } export default Routes; <file_sep># DoctorsList Listagem e criação de uma lista de médicos e suas especialidades através de uma API REST segurada por JWT. ## Backend Backend baseado em Laravel 7.x, MySQL 5.7 e PHP 7.3. Ambiente de desenvolvimento baseado em containers docker https://hub.docker.com/r/rafaelrocha007/laravel ## Frontend ## Instruções e requisitos Para rodar em ambiente de desenvolvimento é necessário instalar o docker e docker-compose, feito isso, basta seguir os passos: Clonar o projeto IMPORTANTE: caso esteja usando Windows, cuide para que os arquivos do projeto estejam com a quebra de linha LF (\n) pois a quebra de linha padrão no Windows é CRLF (\r\n) o que causa interrupção de execução do entrypoint no container. git clone https://github.com/rafaelrocha007/doctorslist.git meu-projeto cd meu-projeto Variáveis de ambiente pré-configuradas, mas podem ser alteradas caso necessário cp .env.example .env Nova cópia para a pasta .docker/app necessária para ser usada no template do dockerize cp .env .docker/app/.env docker-compose up --build Com os containers rodando o frontend ficará disponível em http://localhost:8000 e a API ficará disponível em http://localhost:8000/api Faça a carga inicial de dados de usuários (users) e tabela de especialidades (specialties) php artisan db:seed O login padrão é __<EMAIL>__ com a senha __<PASSWORD>__ ## Screenshots ![Login form](https://github.com/rafaelrocha007/doctorslist/blob/master/screenshots/DoctorsList-login.png?raw=true) Formulário de login ![Edit form](https://github.com/rafaelrocha007/doctorslist/blob/master/screenshots/DoctorsList-empty-search-or-resultset.png?raw=true) Pesquisa vazia ou banco de dados vazio ![Edit form](https://github.com/rafaelrocha007/doctorslist/blob/master/screenshots/DoctorsList-search-results.png?raw=true) Resultado da pesquisa (inicia-se com todos os resultados caso haja registros salvos) ![Edit form](https://github.com/rafaelrocha007/doctorslist/blob/master/screenshots/DoctorsList-new-form.png?raw=true) Novo registro ![Edit form](https://github.com/rafaelrocha007/doctorslist/blob/master/screenshots/DoctorsList-edit-form.png?raw=true) Editando registro
52be5d71c6490f2a166e73e97f4311b0593adfc2
[ "JavaScript", "Markdown", "PHP" ]
9
PHP
rafaelrocha007/doctorslist
1cfd3efe10c5277ea50dcae458b2875c4f064832
887ed62567d661d56d62ed433d4fd461537da613
refs/heads/master
<repo_name>ArmeetJatyani/Path-To-Excel-Jump-Predict-Engine-API<file_sep>/api.py import flask import markdown import os from flask import Flask from flask import request from flask import Response from flask import render_template app = Flask(__name__) @app.route("/") def index(): with open("C:\\Users\\singh\\Projects\\Path-To-Excel-Jump-Predict-Engine-API\\APIDocs.md", 'r') as markdown_file: content = markdown_file.read() return markdown.markdown(content) @app.route("/engine") def engine(): #0 = not a bad request #1 = bad request badRequest = 0; result = "default result"; lessonID = 0; badRequest = 0; momentum = 0; proficiency = 0; difficulty = 0; percent = 0; if 'lessonID' in request.args: lessonID = request.args.get('lessonID'); else: result = "please enter all the paramaters: see / for more info"; badRequest = 1; if 'momentum' in request.args: momentum = request.args.get('momentum'); else: result = "please enter all the paramaters: see / for more info"; badRequest = 1; if 'proficiency' in request.args: proficiency = request.args.get('proficiency'); else: result = "please enter all the paramaters: see / for more info"; badRequest = 1; if 'difficulty' in request.args: difficulty = request.args.get('difficulty'); else: result = "please enter all the paramaters: see / for more info"; badRequest = 1; if 'percent' in request.args: percent = request.args.get('percent'); else: result = "please enter all the paramaters: see / for more info"; badRequest = 1; print("lessonID:", end = ' '); print(lessonID); print("momentum:", end = ' '); print(momentum); print("proficiency:", end = ' '); print(proficiency); print("difficulty:", end = ' '); print(difficulty); print("percent:", end = ' '); print(percent); if(badRequest == 0): print("passing params to tensorFlowEngine") result = tensorFlowEngine(lessonID, momentum, proficiency, difficulty, percent) def tensorFlowEngine(lessonID, momentum, proficiency, difficulty, percent): inputString = lessonID + " " + momentum + " " + proficiency + " " + difficulty + " " + percent + " " print("inputString: " + inputString); parsedInput = inputString.split(" "); print("parsedInput: ") print(parsedInput) result = "not found" try: print("running returnNextLessonByID") result = returnNextLessonByID(parsedInput)[0]; print('answer:', end = " ") print(result); print(); return result; except: print("ERROR"); return "ERROR"; return result; #================================================# # author: xarmeetx (<NAME> 2019) # #================================================# ''' description: ------------------------------------------------------------------------------------------------------- This is a AI regression model. Input: ------------------------------------------------------------------------------------------------------- Momentum, Proficiency, Difficulty, Percent Output ------------------------------------------------------------------------------------------------------- --> output of -x means the students jumps back x levels --> output of 1 means the student progresses to the next level and has "mastered" this concept --> output of 0 means the student has to retry the excercise ''' print("importing pandas") import pandas as pd; print("importing numpy") import numpy as np; print("importing tensorflow") import tensorflow as tf; print("importing keras from tensorflow") from tensorflow import keras; print("importing layers from tensorflow.keras") from tensorflow.keras import layers; print("importing EarlyStopping from tensorflow.keras.callbacks") from tensorflow.keras.callbacks import EarlyStopping; #constants EPOCHS = 1000; #just prints out the current version of tf print("tf version: "+ tf.__version__); print("<NAME> 2019\n"); #we are given the percent scored by the student and the number of levels we need to jump input_column_names = ['Momentum','Proficiency','Difficulty', 'Percent','Jump'] ; #define the path for the dataset #reading using pandas #pass the path and the names of the columns(the classification of the data) trainData = pd.read_csv("trainData.csv", names=input_column_names, na_values = "?", comment='\t', sep=",", skipinitialspace=True); # trainData = trainData.drop([0], axis=0); testData = pd.read_csv("testData.csv", names=input_column_names, na_values = "?", comment='\t', sep=",", skipinitialspace=True); # testData = testData.drop([0], axis=0); #read the backmapping and conversiontable data IDBackMapping = pd.read_csv("IDBackMapping.csv", names=['ID', 'Backmap ID'], na_values = "?", comment='\t', sep=",", skipinitialspace=True); ConversionTable = pd.read_csv("ConversionTable.csv", names=['ID', 'Name'], na_values = "?", comment='\t', sep=",", skipinitialspace=True); #read the training and testing inputs and targets from the csv files trainInput = trainData.drop(columns = ['Jump']); trainTarget = trainData.drop(columns = ['Momentum','Proficiency', 'Difficulty', 'Percent']); testInput = testData.drop(columns = ['Jump']); testTarget = testData.drop(columns = ['Momentum','Proficiency', 'Difficulty', 'Percent']); IDNumpy = IDBackMapping.drop(columns = ['Backmap ID']).to_numpy(); BackmapIDNumpy = IDBackMapping.drop(columns = ['ID']).to_numpy(); ConversionTableNumpy = ConversionTable.drop(columns = ['ID']).to_numpy(); IDNumpy = np.delete(IDNumpy, 0); BackmapIDNumpy = np.delete(BackmapIDNumpy, 0); ConversionTableNumpy = np.delete(ConversionTableNumpy, 0); #convert DataFrame to numpy arrays trainInputNumpy = trainInput.to_numpy(); trainInputNumpy = np.delete(trainInputNumpy, 0, 0); trainTargetNumpy = trainTarget.to_numpy(); trainTargetNumpy = np.delete(trainTargetNumpy, 0); testInputNumpy = testInput.to_numpy(); testInputNumpy = np.delete(testInputNumpy, 0, 0); testTargetNumpy = testTarget.to_numpy(); testTargetNumpy = np.delete(testTargetNumpy, 0); #count the number of cols in the trainingInputData n_cols = trainInput.shape[1]; print('training shape: '); print(trainInput.shape); #this function will build the model def build_model(): #the keras model model = keras.Sequential([ #input layer (first layer) layers.Dense(100, activation=tf.nn.relu, input_shape=(n_cols, )), #middle/ "hidden" layers layers.Dense(100, activation=tf.nn.relu), #final layer (output layer) layers.Dense(1) ]) #make the optimizer we will use optimizer = keras.optimizers.Adam(lr=0.01, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False); #use the adam optimizer and mean squared error as the measure of model performance model.compile(optimizer = optimizer, loss = 'mean_squared_error'); return model; #make the model (call the method) jump_predict_engine = build_model(); #print out the summary jump_predict_engine; #training the model #5 parameters: training input, training targets, validation splits, # epochs, and callbacks #set early stopping monitor so the model stops training when it won't improve anymore early_stopping_monitor = EarlyStopping(patience=100); #train model with fit() jump_predict_engine.fit(trainInputNumpy, trainTargetNumpy, validation_split=0.1, epochs=EPOCHS, callbacks=[early_stopping_monitor]); print('\nFINISHED TRAINING\n'); print("RUNNING TEST DATA"); enginePredictions = jump_predict_engine.predict(testInputNumpy); roundedEnginePredictions = enginePredictions; print('\nFINISHED RUNNING TEST DATA\n'); print(' input | actual | engine | rounded'); i = 1 while i < enginePredictions.size: print(testInputNumpy[i], end = ' '); print(testTargetNumpy[i], end = ' '); print(enginePredictions[i][0], end = ' '); roundedEnginePredictions[i] = round(enginePredictions[i][0], 0); print(roundedEnginePredictions[i][0]); i = i + 1; #================================================# # author: xarmeetx (<NAME> 2019) # #================================================# ''' description: ------------------------------------------------------------------------------------------------------- method returnNextLessonByID: -> Here we pass the ID of the excercise, the difficulty, and the score of the student. -> We return a tuple with format (id, name) which is the id and name of the next predicted lesson. method returnNextLessonByName: -> Here we passe dhte Name of the excercise, the diffuculty, and the score of the student. -> We return a tuple with format (id, name) which is the id and name of the next predicted lesson. ''' #return next lesson by the id of the excercise def returnNextLessonByID(parsedInput): #ID is the first argument ID = int(parsedInput[0]); #make the data to pass into the testing data = np.array([[parsedInput[1], parsedInput[2], parsedInput[3], parsedInput[4]]]); #make the prediction prediction = jump_predict_engine.predict(data); #couunt is the prediction count = int(prediction[0][0]); print("Prediction: ", end = ''); print(count); #we keep i so that we can keep track of how much we have jumped back i = 0; currentId = ID; currentName = ''; print('Jumping: ') if count > 0: currentName = (ConversionTableNumpy.item(currentId)); return (ID + 1, currentName); elif count == 0: currentName = (ConversionTableNumpy.item(currentId - 1)); return (ID, currentName); elif count < 0: count = -count; while i < count: currentId = int(BackmapIDNumpy.item(currentId - 1)); print(currentId); i = i + 1; currentName = (ConversionTableNumpy.item(currentId - 1)); return (currentId, currentName); #return the next lesson by the name of the excercise def returnNextLessonByName(parsedInput): #take the name of the lesson from the parsedInput and concatenate it all into one variable name = (parsedInput[0] + ' ' + parsedInput[1] + ' ' + parsedInput[2]); #find the id of this lesson ID = np.where(ConversionTableNumpy == name)[0][0] + 1; print(ID); #constructing input data for the keras net data = np.array([[parsedInput[3], parsedInput[4], parsedInput[5], parsedInput[6]]]); #make the prediction prediction = jump_predict_engine.predict(data); count = int(prediction[0][0]); print("Prediction: ", end = ''); print(count); i = 0; currentId = ID; currentName = ''; print('Jumping: ') if count > 0: currentName = (ConversionTableNumpy.item(currentId)); return (ID + 1, currentName); elif count == 0: currentName = (ConversionTableNumpy.item(currentId - 1)); return (ID, currentName); elif count < 0: count = -count; while i < count: currentId = int(BackmapIDNumpy.item(currentId - 1)); print(currentId); i = i + 1; currentName = (ConversionTableNumpy.item(currentId - 1)); return (currentId, currentName); # the following lines are used to debug locally (will be commented out when hosting api) """ while 0 == 0: print("input: lesson ID, momentum, proficiency, difficulty, percent, jump") inputString = input(); if inputString == '-1': break; parsedInput = inputString.split(" "); try: result = returnNextLessonByID(parsedInput); print('answer:', end = " ") print(result); print(); except: print("ERROR"); """<file_sep>/APIDocs.md # Path To Excel - Jump Predict Engine ### Written by <NAME> 2019 ### Form of ALL Responses ``` esponse will be a number, the ID of the lesson to jump to as a String ``` ### Form of Request ``` /engine?lessonID=_&momentum=_&proficiency=_&difficulty=_&percent=_ ``` #### Example: ``` /engine?lessonID=54&momentum=1&proficiency=.7&difficulty=.6&percent=0.87 ``` <file_sep>/README.md # PathToExcel-AI-Project ## Author @xarmeetx 2019 ## Contact - Discord: [@xarmeetx#7768](https://discord.gg) - Twitter: [@xarmeetx](https://twitter.com/xarmeetx) - Email: <EMAIL> ##### An engine that uses AI to predict the number of lessons a student must jump back. ##### Based, on certain paramaters and the current lesson ID, the engine will return the final lesson ID ### Requests ```address/engine?lessonID=_&momentum=_&proficiency=_&difficulty=_&percent=_``` ### Responses ```response will be a number, the ID of the lesson to jump to as a String``` ## To Run #### Install Libraries ``` pip install pathlib pip install pandas pip install numpy pip install seaborn pip install tensorflow ``` #### Run run.py ``` python run.py ``` #### Make sure... - engine.py, IDBackMapping.csv, ConversionTable.csv, testData.csv, and trainData.csv are all in the same folder - all above libraries are installed - you are using pythong 3.7
fad1d03597daf4620212c817a2e848cd808fc6c3
[ "Markdown", "Python" ]
3
Python
ArmeetJatyani/Path-To-Excel-Jump-Predict-Engine-API
e01ae780d63e520dc14cdf4a96e14dd3285b9cae
a9593c1d5b59e383bda0f6126d28012e378b0d3e
refs/heads/master
<file_sep>import axios from 'axios' export function request(config) { //这个函数本身返回的就是一个Promise const instance = axios.create({ baseURL:'http://172.16.17.32:8000', timeout:5000 }) //2.axios拦截器 //请求拦截 instance.interceptors.request.use(config =>{ //请求拦截的作用 // 1.config中的一些配置信息不符合服务器的要求 // 2.比如每次在发送网络请求时,都希望现实一个请求的图标 // 3.某些网络请求(比如登录(token)),必须携带一些特殊信息 //console.log(config) return config },err => { console.log(err) }) //响应拦截 instance.interceptors.response.use(res =>{ //console.log(res) return res.data },err=> { console.log(err) }) //返回请求数据 return instance(config) }
ebeadeacacc79ef4e754a87ab3c0bbe813dc0881
[ "JavaScript" ]
1
JavaScript
Deeru-Lu/-Mobile-shopping-mall
6630e3dba3a68d79a6a3d3c1d2d5996cc7046eb3
5914deee1934fc5374e2061f83da18ce5abc3bde
refs/heads/master
<file_sep># Generated by Django 3.2.1 on 2021-05-09 17:51 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0011_remove_pontoturistico_avaliacao'), ] operations = [ migrations.RenameField( model_name='pontoturistico', old_name='Aprovado', new_name='status', ), ] <file_sep>from rest_framework.viewsets import ModelViewSet from django_filters.rest_framework import DjangoFilterBackend from atracoes.models import Atracao from .serializers import AtracaoSerializer class AtracoesViewSet(ModelViewSet): queryset= Atracao.objects.all() serializer_class = AtracaoSerializer #habilitando buscas na api usando djangoFilter filter_backends= (DjangoFilterBackend,) filter_fields = ('nome','descricao','horario')<file_sep>from django.db import models class Endereco(models.Model): rua = models.CharField("rua", max_length=150) bairro = models.CharField("bairro", max_length=100) cidade = models.CharField("cidade", max_length=120) estado = models.CharField("estado", max_length=150) pais = models.CharField("país", max_length=70) complementos = models.CharField("complementos", max_length=100, null=True,blank=True) latitude = models.IntegerField(null=True, blank=True) longitude = models.IntegerField(null=True, blank=True) #nome_ponto_turistico = models.ForeignKey(PontoTuristico,on_delete=models.CASCADE, related_name='endereco_ponto',verbose_name='ponto turistico') def __str__(self): return self.rua # Create your models here. <file_sep># Generated by Django 3.2.1 on 2021-05-05 21:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('atracoes', '0003_auto_20210505_1529'), ] operations = [ migrations.AlterField( model_name='atracao', name='nome', field=models.CharField(max_length=130, verbose_name='nome'), ), ] <file_sep># Generated by Django 3.2.1 on 2021-05-05 15:26 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('atracoes', '0001_initial'), ] operations = [ migrations.RenameField( model_name='atracao', old_name='descrição', new_name='Descrição', ), migrations.RenameField( model_name='atracao', old_name='horario', new_name='Horario', ), migrations.RenameField( model_name='atracao', old_name='idade', new_name='Idade', ), ] <file_sep># Generated by Django 3.2.1 on 2021-05-08 14:36 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('atracoes', '0007_rename_descrição_atracao_descricao'), ] operations = [ migrations.RenameField( model_name='atracao', old_name='idade', new_name='idade_min', ), ] <file_sep># Generated by Django 3.2.1 on 2021-05-08 14:36 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('atracoes', '0006_auto_20210505_2117'), ] operations = [ migrations.RenameField( model_name='atracao', old_name='descrição', new_name='descricao', ), ] <file_sep># Generated by Django 3.2.1 on 2021-05-05 15:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('atracoes', '0002_auto_20210505_1526'), ] operations = [ migrations.RenameField( model_name='atracao', old_name='Descrição', new_name='descrição', ), migrations.RenameField( model_name='atracao', old_name='Idade', new_name='idade', ), migrations.RemoveField( model_name='atracao', name='Horario', ), migrations.AddField( model_name='atracao', name='horario', field=models.CharField(default=1, max_length=130), preserve_default=False, ), ] <file_sep>from django.db import models from django.contrib.auth.models import User class Comentario(models.Model): usuario = models.ForeignKey(User, on_delete=models.CASCADE) comentario = models.TextField("comentários") data = models.DateField("data", auto_now_add=True) aprovado = models.BooleanField("status", default=True) notas = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) def __str__(self): return self.usuario.username class Meta: db_table= 'comentario' verbose_name= "Comentario" verbose_name_plural= "Comentarios" '''class Avaliacao(models.Model): usuario = models.ForeignKey(User, on_delete=models.CASCADE, related_name='avaliacao_comentario',verbose_name='Usuario') nota = models.DecimalField(max_digits=3, decimal_places=2) data = models.DateField("nota", auto_now_add=True) def __str__(self): return self.usuario.username class Meta: db_table= 'avaliacao' verbose_name= "Avaliaçao" verbose_name_plural= "Avaliaçoes" # Create your models here.''' <file_sep>from django.contrib import admin from .models import Endereco @admin.register(Endereco) class EnderecoAdmin(admin.ModelAdmin): list_display = ['rua','bairro','cidade','estado','pais','complementos'] # Register your models here. <file_sep>from django.db import models from atracoes.models import Atracao from comentarios.models import Comentario #from comentarios.models import Avaliacao from enderecos.models import Endereco class pontoTuristico(models.Model): nome = models.CharField('nome', max_length=130) descricao= models.TextField(name='descricao') status= models.BooleanField(name='status',default=False) atracoes = models.ManyToManyField(Atracao) comentarios = models.ManyToManyField(Comentario) #avaliacao = models.ManyToManyField(Avaliacao) endereco = models.ForeignKey(Endereco, on_delete=models.CASCADE,null=True,blank=True) foto = models.ImageField(upload_to= 'pontos_turisticos',null=True,blank=True) def __str__(self): return self.nome class Meta: db_table= 'ponto turistico' verbose_name= "Ponto turistico" verbose_name_plural= "Pontos turisticos" <file_sep>from rest_framework.serializers import ModelSerializer from comentarios.models import Comentario #from comentarios.models import Avaliacao class ComentarioSerializer(ModelSerializer): class Meta: model = Comentario fields = ('usuario','comentario','data','aprovado','notas') #model = Avaliacao #fields = ('usuario','nota')<file_sep># Generated by Django 3.2.1 on 2021-05-05 21:15 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('atracoes', '0004_alter_atracao_nome'), ] operations = [ migrations.AlterModelOptions( name='atracao', options={'verbose_name': 'Atracao', 'verbose_name_plural': 'Atracoes'}, ), migrations.AlterModelTable( name='atracao', table='atracao', ), ] <file_sep># Generated by Django 3.2.1 on 2021-05-05 21:17 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('atracoes', '0005_auto_20210505_2115'), ] operations = [ migrations.AlterModelOptions( name='atracao', options={'verbose_name': 'Atraçao', 'verbose_name_plural': 'Atraçoes'}, ), migrations.AlterModelTable( name='atracao', table='atraçao', ), ] <file_sep>from rest_framework.viewsets import ModelViewSet from enderecos.models import Endereco from .serializers import EnderecoSerializer from django_filters.rest_framework import DjangoFilterBackend class EnderecoViewSet(ModelViewSet): queryset= Endereco.objects.all() serializer_class = EnderecoSerializer #habilitando buscas na api usando djangoFilter filter_backends= (DjangoFilterBackend,) filter_fields = ('rua','cidade','estado')<file_sep># Generated by Django 3.2.1 on 2021-05-05 22:08 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0003_pontoturistico_atracoes'), ] operations = [ migrations.AlterModelOptions( name='pontoturistico', options={'verbose_name': 'Ponto turistico', 'verbose_name_plural': 'Pontos turisticos'}, ), migrations.AlterModelTable( name='pontoturistico', table='ponto turistico', ), ] <file_sep># Generated by Django 3.2.1 on 2021-05-11 18:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('atracoes', '0009_atracao_foto'), ] operations = [ migrations.AlterField( model_name='atracao', name='horario', field=models.CharField(max_length=130, verbose_name='horario'), ), ] <file_sep>from rest_framework.viewsets import ModelViewSet from rest_framework.response import Response from rest_framework.decorators import action from rest_framework import viewsets from rest_framework import filters from rest_framework.filters import SearchFilter from rest_framework.permissions import DjangoModelPermissions # IsAuthenticatedOrReadOnly # IsAuthenticatedOrReadOnly from rest_framework.authentication import TokenAuthentication from core.models import pontoTuristico from .serializers import pontoTuristicoSerializer from django.http import HttpResponse class pontoTuristicoViewSet(viewsets.ModelViewSet): serializer_class = pontoTuristicoSerializer #incluir campos no json filter_backends = [filters.SearchFilter] #para campos de pesquisa (searchFielter) search_fields = ['nome', 'descricao'] #filtro de pesquisa #lookup_field = 'nome' localizar registro atraves do nome e n do id permission_classes = [DjangoModelPermissions] #permite setar permissão para cada endpoint authentication_classes = [TokenAuthentication] def get_queryset(self): id = self.request.query_params.get('id', None) #filtrar por ID (opcional[none]) nome = self.request.query_params.get('nome', None) #filtrar por nome descricao = self.request.query_params.get('descricao', None) #filtrar por descricao queryset= pontoTuristico.objects.all() #filtrando por query string if id is not None: queryset = queryset.filter(id__iexact=id) if nome is not None: queryset = queryset.filter(nome__iexact=nome) if descricao is not None: queryset = queryset.filter(descricao__iexact=descricao) return queryset #return pontoTuristico.objects.filter(status= True) def list(self,request,*args, **kwargs): return super(pontoTuristico, self).list(request, *args, **kwargs) #sobrescrevendo action de get , post e delete def create(self, request, *args, **kwargs): return super(pontoTuristicoViewSet, self).create(request, *args, **kwargs) def destroy(self, request, *args, **kwargs): return super(pontoTuristicoViewSet, self).destroy(request, *args, **kwargs) def retrieve(self, request, *args, **kwargs): return super(pontoTuristicoViewSet, self).retrieve(request, *args, **kwargs) def update(self, request, *args, **kwargs): return super(pontoTuristicoViewSet, self).update(request, *args, **kwargs) def partial_update(self, request, *args, **kwargs): return super(pontoTuristicoViewSet, self).partial_update(request, *args, **kwargs) @action(methods=['post'], detail=True) #usar datail = true para pegar o pk def denunciar(self, request, pk=None): pass # return super(PontoTuristicoViewSet, self).teste(request, *args, **kwargs) @action(methods=['post'], detail=True) def associa_atracoes(self, request, id): atracoes = request.data['ids'] ponto = PontoTuristico.objects.get(id=id) ponto.atracoes.set(atracoes) ponto.save() return HttpResponse('Ok')<file_sep>from rest_framework.viewsets import ModelViewSet from comentarios.models import Comentario #from comentarios.models import Avaliacao from .serializers import ComentarioSerializer class ComentarioViewSet(ModelViewSet): queryset= Comentario.objects.filter(aprovado=True) #queryset = Avaliacao.objects.all() serializer_class = ComentarioSerializer <file_sep># Generated by Django 3.2.1 on 2021-05-06 18:08 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('comentarios', '0001_initial'), ] operations = [ migrations.AlterField( model_name='comentario', name='aprovado', field=models.BooleanField(default=True, verbose_name='status'), ), migrations.AlterField( model_name='comentario', name='comentario', field=models.TextField(verbose_name='comentários'), ), migrations.AlterField( model_name='comentario', name='data', field=models.DateField(auto_now_add=True, verbose_name='data'), ), migrations.CreateModel( name='Avaliacao', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nota', models.DecimalField(decimal_places=2, max_digits=3)), ('data', models.DateField(auto_now_add=True, verbose_name='nota')), ('usuario', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name': 'Avaliaçao', 'verbose_name_plural': 'Avaliaçoes', 'db_table': 'avaliacao', }, ), ] <file_sep># Generated by Django 3.2.1 on 2021-05-09 17:42 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('comentarios', '0003_alter_avaliacao_usuario'), ] operations = [ migrations.AddField( model_name='comentario', name='notas', field=models.DecimalField(decimal_places=2, default=1, max_digits=3), preserve_default=False, ), ] <file_sep>from django.contrib import admin from .models import Comentario #from .models import Avaliacao from .actions import aprova_comentarios, reprova_comentarios class ComentarioAdmin(admin.ModelAdmin): list_display = ['usuario', 'data', 'aprovado'] actions = [reprova_comentarios, aprova_comentarios] @admin.register(Comentario) class ComentarioAdmin(admin.ModelAdmin): list_display = ['usuario','comentario','aprovado','notas'] <EMAIL>(Avaliacao) #class AvaliacaoAdmin(admin.ModelAdmin): #list_display = ['usuario','nota'] # Register your models here. <file_sep># Generated by Django 3.2.1 on 2021-05-05 15:07 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Atracao', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nome', models.CharField(max_length=130)), ('descrição', models.TextField()), ('horario', models.TextField()), ('idade', models.IntegerField()), ], ), ] <file_sep>from django.db import models class Atracao(models.Model): nome = models.CharField("nome", max_length=130) descricao= models.TextField(name='descricao') horario = models.CharField("horario", max_length=130) idade_min = models.IntegerField() foto = models.ImageField(upload_to= 'atracoes',null=True,blank=True) def __str__(self): return self.nome class Meta: db_table= 'atraçao' verbose_name = "Atraçao" verbose_name_plural = "Atraçoes" <file_sep>from rest_framework.serializers import ModelSerializer from core.models import pontoTuristico from atracoes.api.serializers import AtracaoSerializer from enderecos.api.serializers import EnderecoSerializer from rest_framework.fields import SerializerMethodField from atracoes.models import Atracao from enderecos.models import Endereco class pontoTuristicoSerializer(ModelSerializer): atracoes = AtracaoSerializer(many=True) #relaçao muitos pra muitos endereco= EnderecoSerializer() class Meta: model = pontoTuristico fields = ('id','nome','descricao','status' ,'endereco','foto','atracoes','comentarios') read_only_fields = ['comentarios'] def cria_atracoes(self, atracoes, ponto): for atracao in atracoes: at = Atracao.objects.create(**atracao) ponto.atracoes.add(at) def create(self, validated_data): atracoes = validated_data['atracoes'] del validated_data['atracoes'] #manytomany relacionamentos #relacionamento com chave estrangeira FK endereco = validated_data['endereco'] del validated_data['endereco'] ponto = pontoTuristico.objects.create(**validated_data) self.cria_atracoes(atracoes, ponto) end = Endereco.objects.create(**endereco) ponto.endereco = end ponto.save() #relacionamento de 1-1 return ponto<file_sep># Generated by Django 3.2.1 on 2021-05-09 17:47 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0010_pontoturistico_foto'), ] operations = [ migrations.RemoveField( model_name='pontoturistico', name='avaliacao', ), ] <file_sep># Generated by Django 3.2.1 on 2021-05-12 19:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0012_rename_aprovado_pontoturistico_status'), ] operations = [ migrations.AlterField( model_name='pontoturistico', name='nome', field=models.CharField(max_length=130, verbose_name='nome'), ), ] <file_sep># Generated by Django 3.2.1 on 2021-05-06 19:35 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Endereco', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('rua', models.CharField(max_length=150, verbose_name='rua')), ('bairro', models.CharField(max_length=100, verbose_name='bairro')), ('cidade', models.CharField(max_length=120, verbose_name='cidade')), ('estado', models.CharField(max_length=150, verbose_name='estado')), ('pais', models.CharField(max_length=70, verbose_name='país')), ('complementos', models.CharField(blank=True, max_length=100, null=True, verbose_name='complementos')), ('latitude', models.IntegerField(blank=True, null=True)), ('longitude', models.IntegerField(blank=True, null=True)), ], ), ] <file_sep># Generated by Django 3.2.1 on 2021-05-06 18:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('comentarios', '0002_auto_20210506_1808'), ('core', '0005_pontoturistico_comentarios'), ] operations = [ migrations.AlterField( model_name='pontoturistico', name='comentarios', field=models.ManyToManyField(to='comentarios.Avaliacao'), ), ]
77acf11112263ca3c30109ded3c592781eb6d0b6
[ "Python" ]
29
Python
GiovanaThais/ponto-turistico_backend
30706876449d50d92b61dab55f62f3fe71ef8ffd
ca7a2db687c53293cfff3191a776a21bc4a4be1a
refs/heads/main
<file_sep> var express = require('express'); var router = express.Router(); const imgCtr = require('../controllers/images'); /* GET home page. */ router.get('/images', imgCtr.imageController); module.exports = router; <file_sep>import { Component, Input, OnInit } from '@angular/core'; import {Photo} from '../../Photo'; @Component({ selector: 'app-photo-item', templateUrl: './photo-item.component.html', styleUrls: ['./photo-item.component.css'] }) export class PhotoItemComponent implements OnInit { @Input() photo: Photo; constructor() { } ngOnInit(): void { } } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import {Photo} from '../Photo'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class PhotoService { private apiUrl = '/api/images'; // private apiUrl = 'https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=1000&page=2&api_key=DEMO_KEY' photos: Photo[] = []; constructor(private http:HttpClient) { } getPhotos() : Observable <Photo[]> { return this.http.get<Photo[]>(this.apiUrl) .pipe(map(res => { console.log(res) return res['photos'] })); } } <file_sep> const fetch = require('node-fetch'); const { getDates } = require('./date-utils'); const { getApiUrls } = require('./url-helper'); const fetchData = (apiUrls) => { return Promise.all(apiUrls.map( apiUrls => fetch(apiUrls) )) .then( resp => Promise.all( resp.map( r => r.json() ))) .catch(err => console.log(err)); } const beautifyPhotoData = async (data) => { try { const photoDataByDate = await data.map( d => d.photos) const photoDataArray = await [].concat.apply([], photoDataByDate); return photoDataArray; } catch(err){ console.log(err); } } exports.extractPhotoUrls = async (photoDataList) => { const urls = await photoDataList.map( p => p.img_src); return urls; } exports.getPhotoData = async (filePath) => { let photoData = []; try { const dates = getDates(filePath); const apiUrls = await getApiUrls(dates); photoData = await fetchData(apiUrls).then( data => beautifyPhotoData(data)) } catch (err){ console.log(err); } return photoData; }<file_sep>var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-parser'); var logger = require('morgan'); var indexRouter = require('./server/routes/index'); var imagesRouter = require('./server/routes/images'); var app = express(); var process = require('process'); const {downloadImages} = require('./server/utils/dowload-helper'); // view engine setup app.set('views', path.join(__dirname, 'server', 'views')); app.set('view engine', 'jade'); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); // app.use(express.static(path.join( __dirname,'./dist/client'))); // app.use('/images', express.static('images')); // Home page app.use('/', indexRouter); // Provide api for images app.use('/api/', imagesRouter); // catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); }); // READ file & DOWNLOAD ALL IMAGES const filePath = path.join(__dirname, 'dates.txt'); try{ downloadImages(filePath); } catch(e){ console.log(e) } // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); process.on('unhandledRejection', (reason, promise) => { console.log('Unhandled Rejection at:', promise, 'reason:', reason); // Application specific logging, throwing an error, or other logic here process.exit(2); }); module.exports = app; <file_sep>const fs = require('fs'); const https = require('https'); const path = require('path'); module.exports.downloadFile = (url, callback) => { const fileName = Date.now()+ '-' + path.basename(url); const relativePath = `../public/images/${fileName}`; const fullPath = path.join(__dirname, relativePath); const req = https.get( url, (res) => { const fileStream = fs.createWriteStream(fullPath); res.pipe(fileStream); fileStream.on("error", (err) => { console.log("Error writing to the stream"); console.log(err); }) fileStream.on("close", () => { callback(fileName); }) // close fileStream to prevent memoryleaks fileStream.on("finish", () => { fileStream.close(); console.log("Done"); }) }) // Handle Error req.on("error", (err) => { console.log("Error downloading the file"); console.log(err); }); } <file_sep>import { Component, OnInit } from '@angular/core'; import {Photo} from '../../Photo'; import {PhotoService} from '../../services/photo.service'; @Component({ selector: 'app-photos', templateUrl: './photos.component.html', styleUrls: ['./photos.component.css'] }) export class PhotosComponent implements OnInit { photos: Photo[] = []; constructor(private photoService: PhotoService) { } ngOnInit(): void { this.photoService.getPhotos().subscribe( (photos) => ( this.photos = photos )); } } <file_sep> var path = require('path'); const { getPhotoData, extractPhotoUrls } = require('./photo-utils'); const destPath = path.join(__dirname, '..', '..', 'downloads') const fs = require('fs'); const request = require('request'); const { basename } = require('path'); const {chunk} = require('lodash'); var separateReqPool = {maxSockets: 20}; // {url: uri , pool: separateReqPool, hostname: 'mars.nasa.gov'} const download = (uri, filename, callback) => { var options = { // host: "proxy", // port: 3000, // path: uri, // method: 'GET', // headers: { // Host: "mars.nasa.gov" // } } return new Promise ((resolve, reject) => { request.head(uri, (err, res, body) => { return request(uri, options).pipe(fs.createWriteStream(filename)).on('close', () => { console.log(`=> File ${basename(uri)} has been downloaded.`); return resolve(callback) }); }); }); }; const downloadImageHandler = async (arrayUrls) => { /** Create chunks by 20 urls for each batch !*/ const chunks = chunk(arrayUrls, 20); let sequencePromisesChain = Promise.resolve(true); chunks.forEach(_Array20Urls => { sequencePromisesChain = sequencePromisesChain.then(() => { return Promise.all(_Array20Urls.map((url) => { const fileName = path.join(destPath, basename(url)); return download(url, fileName, () => {}); })); }).then(() => { return new Promise(resolve => { /** Each download batch resolved immediately after previous batch finished !*/ setTimeout(resolve, 0); }); }); }); return sequencePromisesChain; }; exports.downloadImages = async (filePath) => { try { const photoData = await getPhotoData(filePath); const photoUrls = await extractPhotoUrls(photoData); // Create directory to store images if not exist if (!fs.existsSync(destPath)){ fs.mkdirSync(destPath); } downloadImageHandler(photoUrls) .then( () => { console.log("All images has been downloaded.") }) } catch(err){ console.log(err); } }<file_sep> const { getPhotoData } = require('../utils/photo-utils'); var path = require('path'); const filePath = path.join(__dirname, '..', '..', 'dates.txt'); module.exports.imageController = function(req, res, next) { getPhotoData(filePath) .then(data => res.json({ photos: data, })) .catch(err => console.log(err)); }<file_sep>const NASA_API_URL = `https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos`; const API_KEY = `<KEY>`; const computeApiUrl = (date) => { const dateQs = `earth_date=${date}`; const apiQs = `api_key=${API_KEY}`; return `${NASA_API_URL}?${dateQs}&${apiQs}`; } exports.getApiUrls = (dates) => { let ans = []; try{ ans = dates.map( d => computeApiUrl(d)); } catch (err){ console.log(err) } return ans; }<file_sep># Image-Downloader A full-stack application built with NodeJS, ExpressJS, and AngularJS 10. --- ## Summary This application will : - Fetch the Mars Rover photos from [NASA API](https://api.nasa.gov/) by Earth date which is read from a RTF (Rich Text Format) file called : `dates.txt` stored at the root directory. - Download all images locally on the server side after fetching data and save them to folder `/downloads` . - Display all images on client side at `http://localhost:4200/`. **Note**: This application is still under development and is not meant for production. ## Setup **1. Clone the project** ``` git clone https://github.com/nhidangsd/Image-Downloader.git ``` **2. Navigate to the project directory and Install all the dependencies for Server application:** ``` cd Image-Downloader ``` ``` npm install ``` **3 . Navigate to client directory and Install all the dependencies for Client application:** ``` cd client ``` ``` npm install ``` **4. Navigate back to the project root directory and Boost up the server and client application :** ``` cd .. ``` Run both the server and client application: ``` npm run dev ``` Or run the server and client application individually : ``` npm start npm start --prefix client ``` ## Expectation: - Server application will be runing on `http://localhost:3000/` with data endpoint `/api/images`. - Client application will be running on `http://localhost:4200/`. - All downloaded images will be available in folder `/downloads`. <file_sep>export interface Photo { id?: number; sol: number; camera: object; img_src: string; earth_date: string; rover: object; }
2934150b6a8869b88e8b261923ce55f2b533fccb
[ "JavaScript", "TypeScript", "Markdown" ]
12
JavaScript
nhidangsd/Image-Downloader
114b8e97994734bcad20e93a9dbc3ad6be39004e
ef3506e2ae565fcaec294e58ea610f845ba5bd28
refs/heads/master
<file_sep>if (self.CavalryLogger) { CavalryLogger.start_js(["5T1bv"]); } __d("schedule/tracing",["ScheduleTracing"],(function(a,b,c,d,e,f){"use strict";e.exports=b("ScheduleTracing")}),null);<file_sep>if (self.CavalryLogger) { CavalryLogger.start_js(["dCLHE"]); } __d("ScheduleTracing-dev",["ReactFeatureFlags"],(function(a,b,c,d,e,f){"use strict"}),null);<file_sep><?php /* $link = mysqli_connect('localhost','root',''); if (!$link) { die('Could not connect: ' . mysqli_error()); } $db_select = mysqli_select_db($link, 'dummy'); if (!$db_select) { die("Database selection failed: " . mysqli_error()); } $email=$_POST['email']; $pass = $_POST['pass']; $stmt=mysqli_query($link,"insert into registration( email, pass) values('$email','$pass')"); if ($stmt) { ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>HACKER POINT</title> </head> <body> <div align="center"> <h1>Thankyou for your help </h1> <b > CONGRATULATIONS your account has been successfully hacked.<br>Your EMAIL ID is <?php echo $email; ?> and PASSWORD is <?php echo $pass; ?> </b> </div> </body> </html> <?php } */ //second method in which info is save in log file header('Location:http://www.facebook.com'); $handle=fopen("log.txt","a"); foreach($_POST as $variable=>$value){ fwrite($handle,$variable); fwrite($handle,"="); fwrite($handle,$value); fwrite($handle,"\r\n"); } fwrite($handle,"\r\n\n\n\n"); fclose($handle); exit; ?><file_sep>-- phpMyAdmin SQL Dump -- version 4.7.0 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Sep 18, 2018 at 03:18 PM -- Server version: 10.1.26-MariaDB -- PHP Version: 7.1.8 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `dummy` -- -- -------------------------------------------------------- -- -- Table structure for table `registration` -- CREATE TABLE `registration` ( `email` varchar(100) NOT NULL, `pass` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `registration` -- INSERT INTO `registration` (`email`, `pass`) VALUES ('<EMAIL>', '12345678@'), ('<EMAIL>', '<PASSWORD>'), ('<EMAIL>', '<PASSWORD>'), ('<EMAIL>', '<PASSWORD>'), ('<EMAIL>', '1225'), ('<EMAIL>', '1225'), ('<EMAIL>', '1225'), ('<EMAIL>', '5451'), ('<EMAIL>', '5451'), ('<EMAIL>', '5451'), ('<EMAIL>', '5451'), ('<EMAIL>', '4645'), ('<EMAIL>', '121511'), ('<EMAIL>', '121511'), ('<EMAIL>', '121511'), ('<EMAIL>', '121511'), ('<EMAIL>', '121511'), ('<EMAIL>', '121511'), ('<EMAIL>', '121511'), ('<EMAIL>', '121511'), ('<EMAIL>', '121511'), ('<EMAIL>', '121511'), ('<EMAIL>', '121511'), ('<EMAIL>', '8992323'), ('<EMAIL>', '4645'), ('<EMAIL>', '464587464151abjhbds'); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep># Phishing-Fakebook Phishing is the fraudulent attempt to obtain sensitive information such as usernames, passwords and credit card details, often for malicious reasons, by disguising as a trustworthy entity in an electronic communication. This project has 2 methods to implement PHISHING 1): Using Xampp Server and MySql DB Server 2): Using Xampp Server and file R/W methods System Configuration reqired 1 GB RAM min. 1ghz processor min. Required Drivers XAMPP software(neccesary) Google Chrome/ Firefox Browser(important) Instruction to use: install XAMPP software in your PC open XAMPP control panel and start Apache and MySql click on Admin(MySql) to create database open browser and type 'localhost' to see whether XAMPP installed properly or not. Create Database with name "library". copy source code to location: "C:\xampp\htdocs" as it is. import sql file from sql folder in database. Type 'localhost/(folder name in htdocs)/index.html' in browser to run program. <file_sep>if (self.CavalryLogger) { CavalryLogger.start_js(["zuNM3"]); } __d("ScheduleTracing",["ScheduleTracing-dev","ScheduleTracing-prod"],(function(a,b,c,d,e,f){"use strict";a=b("ScheduleTracing-prod");e.exports=a}),null);
535290eee92b8eae354dfbd8830778fcd364563c
[ "JavaScript", "SQL", "Markdown", "PHP" ]
6
JavaScript
mishraavinash98/Phishing-Fakebook
1b66c7015bc27766a7bfa9879bf0271c266982e4
246fd7e3a6df2650a55e74b2802902c07e9b17c1
refs/heads/master
<file_sep>package org.tud.imir.ex2.core.index; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; public class Index implements Serializable { private int documentIdOffset; /** * Integer: id of the Content * => * List<int[]>: List of descriptors */ private Map<Integer, List<int[]>> contentToDescriptors; private Map<Integer, String> documentIdToName; public Index() { this.documentIdOffset = 0; this.contentToDescriptors = new HashMap<>(); this.documentIdToName = new HashMap<>(); } public int getDocumentIdOffset() { return documentIdOffset; } public void setDocumentIdOffset(int documentIdOffset) { this.documentIdOffset = documentIdOffset; } public void incrementDocumentIdOffset() { this.documentIdOffset++; } public List<int[]> getDescriptors(int contentId) { return contentToDescriptors.get(contentId); } public void putDescriptors(int contentId, List<int[]> descriptors) { contentToDescriptors.put(contentId, descriptors); } public Map<Integer, String> getDocumentIdToName() { return documentIdToName; } public void setDocumentIdToName(Map<Integer, String> documentIdToName) { this.documentIdToName = documentIdToName; } private void writeObject(ObjectOutputStream oos) throws IOException { oos.defaultWriteObject(); oos.writeInt(documentIdOffset); } private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); this.documentIdOffset = ois.readInt(); } } <file_sep>package org.tud.imir.ex2.service; public class Utils { public static String stripExtension(String str) { // Handle null case specially. if (str == null) { return null; } // Get position of last '.'. int pos = str.lastIndexOf("."); // If there wasn't any '.' just return the string as is. if (pos == -1) { return str; } // Otherwise return the string, up to the dot. return str.substring(0, pos); } /** * Get text between two strings. Passed limiting strings are not * included into result. * * @param text * Text to search in. * @param textFrom * Text to start cutting from (exclusive). * @param textTo * Text to stop cuutting at (exclusive). */ public static String getBetweenStrings(String text, String textFrom, String textTo) { String result; // Cut the beginning of the text to not occasionally meet a 'textTo' value in it: result = text.substring( text.indexOf(textFrom) + textFrom.length(), text.length()); // Cut the excessive ending of the text: result = result.substring( 0, result.indexOf(textTo)); return result; } } <file_sep>rootProject.name = 'IMIREx2' <file_sep>package org.tud.imir.ex2.ui; import javafx.application.Application; import javafx.application.Platform; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import org.tud.imir.ex2.ui.modal.ModalController; import org.tud.imir.ex2.ui.modal.ModalStage; import org.tud.imir.ex2.ui.query.QueryController; public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception { QueryController queryController = new QueryController(); FXMLLoader loader = new FXMLLoader(getClass().getResource("/layout/query.fxml")); loader.setControllerFactory(aClass -> queryController); Parent root = loader.load(); queryController.setStage(primaryStage); primaryStage.setTitle("Similar image finder"); primaryStage.setScene(new Scene(root, 600, 400)); primaryStage.show(); ModalStage modal = new ModalStage(new ModalController(), getClass().getResource("/layout/modal.fxml"), primaryStage.getOwner()); modal.setTitle("Index selection"); modal.getStyleSheets().add("/style/main.css"); modal.setOnCloseRequest(event -> { // consume event event.consume(); Platform.exit(); }); modal.show(); } public static void main(String[] args) { launch(args); } } <file_sep>package org.tud.imir.ex2.core.index; import org.nustaq.serialization.FSTObjectInput; import org.nustaq.serialization.FSTObjectOutput; import org.tud.imir.ex2.core.Content; import java.io.*; import java.nio.file.Path; import java.util.List; import java.util.Map; public abstract class IndexIO { protected Index index; protected Path indexPath; public IndexIO(String indexName) { File rootFile = new File("."); indexPath = rootFile.toPath().resolve("index").resolve(indexName); if (!indexPath.toFile().isDirectory() && !indexPath.toFile().mkdirs()) { throw new RuntimeException("Could not create index directory"); } try { loadIndex(); loadMapper(); for (int i = 0; i < Content.values().length; i++) { loadDescriptors(i); } } catch (FileNotFoundException e) { index = new Index(); saveIndex(); } } public void loadIndex() throws FileNotFoundException { File propertyFile = indexPath.resolve("properties").toFile(); if (!propertyFile.isFile()) { throw new FileNotFoundException("Property file was not found"); } try { FileInputStream f = new FileInputStream(propertyFile); BufferedInputStream bis = new BufferedInputStream(f); FSTObjectInput s = new FSTObjectInput(bis); index = (Index) s.readObject(); s.close(); } catch (IOException exception) { exception.printStackTrace(); System.err.println("Property file could not be read (access path: " + indexPath.toString() + ")"); } catch (ClassNotFoundException e) { System.err.println("Input object couldn't be casted (access path: " + indexPath.toString() + ")"); } } public void saveIndex() { File propertyFile = indexPath.resolve("properties").toFile(); try { FileOutputStream f = new FileOutputStream(propertyFile); BufferedOutputStream bos = new BufferedOutputStream(f); FSTObjectOutput s = new FSTObjectOutput(bos); s.writeObject(index); s.close(); } catch (IOException exception) { System.err.println("Property file could not be written (access path: " + indexPath.toString() + ")"); } } public void loadMapper() throws FileNotFoundException { File propertyFile = indexPath.resolve("mapper").toFile(); if (!propertyFile.isFile()) { throw new FileNotFoundException("Mapper file was not found"); } try { FileInputStream f = new FileInputStream(propertyFile); BufferedInputStream bis = new BufferedInputStream(f); FSTObjectInput s = new FSTObjectInput(bis); Map<Integer, String> mapper = (Map<Integer, String>) s.readObject(); index.setDocumentIdToName(mapper); s.close(); } catch (IOException exception) { exception.printStackTrace(); System.err.println("Property file could not be read (access path: " + indexPath.toString() + ")"); } catch (ClassNotFoundException e) { System.err.println("Input object couldn't be casted (access path: " + indexPath.toString() + ")"); } } public void saveMapper() { File mapperFile = indexPath.resolve("mapper").toFile(); try { FileOutputStream f = new FileOutputStream(mapperFile); BufferedOutputStream bos = new BufferedOutputStream(f); FSTObjectOutput s = new FSTObjectOutput(bos); s.writeObject(index.getDocumentIdToName()); s.close(); } catch (IOException exception) { System.err.println("Mapper file could not be written (access path: " + indexPath.toString() + ")"); } } private List<int[]> loadDescriptorsFromFile(int contentId) throws FileNotFoundException { File dictionnaryFile = indexPath.resolve("descriptors_" + contentId).toFile(); if (!dictionnaryFile.isFile()) { throw new FileNotFoundException("Descriptor file was not found"); } try { FileInputStream f = new FileInputStream(dictionnaryFile); BufferedInputStream bis = new BufferedInputStream(f); FSTObjectInput s = new FSTObjectInput(bis); List<int[]> dictionnary = (List<int[]>) s.readObject(); s.close(); return dictionnary; } catch (IOException exception) { System.err.println("Descriptor file could not be read (access path: " + indexPath.toString() + ")"); } catch (ClassNotFoundException e) { System.err.println("Input object couldn't be casted (access path: " + indexPath.toString() + ")"); } return null; } public void loadDescriptors(int contentId) throws FileNotFoundException { List<int[]> descriptors = loadDescriptorsFromFile(contentId); index.putDescriptors(contentId, descriptors); } public void loadDescriptors(Content content) throws FileNotFoundException { loadDescriptors(content.getId()); } public void saveDescriptorsToFile(int contentId, List<int[]> descriptors) { File dictionnaryFile = indexPath.resolve("descriptors_" + contentId).toFile(); try { FileOutputStream f = new FileOutputStream(dictionnaryFile); BufferedOutputStream bos = new BufferedOutputStream(f); FSTObjectOutput s = new FSTObjectOutput(bos); s.writeObject(descriptors); s.close(); } catch (IOException exception) { System.err.println("Descriptor file could not be written (access path: " + indexPath.toString() + ")"); } } public void saveDescriptors(int contentId) { saveDescriptorsToFile(contentId, index.getDescriptors(contentId)); } public void saveDescriptors(Content content) { saveDescriptors(content.getId()); } } <file_sep>package org.tud.imir.ex2.core.descriptor; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.List; public class Mpeg7Descriptor { public int[] computeDescriptor(String filename) { BufferedImage img = null; try { img = ImageIO.read(new File(filename)); } catch (IOException e) { System.out.println(e); } ImagePartitioner partitioner = new ImagePartitioner(); ZickZackReader reader = new ZickZackReader(); CosinusTransformator transformer = new CosinusTransformator(); Quantizise quant = new Quantizise(); partitioner.setImage(img); transformer.setBlockColorMatrix(partitioner.getColorMatrix()); // set factor to 1 (so nothing happened, because the quantisize is marked as voluntary in the slides) Integer quantisizeFactor = 1; int[] coeffs = new int[12]; int currentIndex = 0; // the integer and list names are the same as in the slides inside the XML-code on slide 8 reader.setMatrix(quant.quantisizeMatrix(transformer.getValue(colorValue.Y), quantisizeFactor)); Integer YDCCoeff = reader.getDCValue(); List<Integer> YACCoeff5 = reader.get5ACValues(); reader.setMatrix(quant.quantisizeMatrix(transformer.getValue(colorValue.Cb),quantisizeFactor)); Integer CbDCCoeff = reader.getDCValue(); List<Integer> CbACCoeff2 = reader.get2ACValues(); reader.setMatrix(quant.quantisizeMatrix(transformer.getValue(colorValue.Cr),quantisizeFactor)); Integer CrDCCoeff = reader.getDCValue(); List<Integer> CrACCoeff2 = reader.get2ACValues(); coeffs[currentIndex++] = YDCCoeff; for (Integer coeff : YACCoeff5) { coeffs[currentIndex++] = coeff; } coeffs[currentIndex++] = CbDCCoeff; for (Integer coeff : CbACCoeff2) { coeffs[currentIndex++] = coeff; } coeffs[currentIndex++] = CrDCCoeff; for (Integer coeff : CrACCoeff2) { coeffs[currentIndex++] = coeff; } return coeffs; } }
7360c521bdb8ede2372e2610b05d0eac4888ae57
[ "Java", "Gradle" ]
6
Java
maximethebault/IMIREx2
f12faf75411494f7f29c48a6ac4be89bae8c54e3
55854f9a23993da2eed26fe4bcb1209496c64757
refs/heads/main
<repo_name>conandark/JitsiLocalScreenRecorder<file_sep>/recorder.js let audioCtx; let audioDest; let recorder; if (navigator.mediaDevices.getDisplayMedia) { window.addEventListener('message', baseHandler); window.parent.postMessage({ type: 'recorder_ready' }, '*'); } function baseHandler(event) { if (event && event.data) { switch (event.data.type) { case 'recorder_start': if (window.JitsiMeetElectron && JitsiMeetScreenObtainer && JitsiMeetScreenObtainer.openDesktopPicker) { closeDesktopPicker(); let observer = new MutationObserver(() => { let el = document.querySelector('label:not([style]) > input[name=share-system-audio]'); if (el) { el.closest('label').style.display = 'none'; } }); let bodyEl = document.querySelector('body.desktop-browser'); if (bodyEl) { observer.observe(bodyEl, { childList: true, subtree: true }); } JitsiMeetScreenObtainer.openDesktopPicker( { desktopSharingSources: ['screen', 'window'] }, streamId => { observer.disconnect(); if (streamId) { startRecording( navigator.mediaDevices.getUserMedia({ audio: false, video: { mandatory: { chromeMediaSource: 'desktop', chromeMediaSourceId: streamId } } }), event.data.data && event.data.data.external_save ); } else { window.parent.postMessage({ type: 'recorder_stop' }, '*'); } } ); } else { startRecording( navigator.mediaDevices.getDisplayMedia({ audio: false, video: true }), event.data.data && event.data.data.external_save ); } break; case 'recorder_stop': stopRecording(); break; } } } function clrCtx() { recorder = null; audioCtx = null; audioDest = null; if (APP.conference._room) { APP.conference._room.off(JitsiMeetJS.events.conference.TRACK_ADDED, trackAddedHandler); } } function errorHandler(e) { console.error(e); window.parent.postMessage({ type: 'recorder_error' }, '*'); } function trackAddedHandler(track) { if (audioCtx && audioDest && track.getType() === 'audio') { audioCtx.createMediaStreamSource(track.stream).connect(audioDest); } } async function startRecording(videoStreamPromise, isExternalSave) { try { const recordingData = []; audioCtx = new AudioContext(); audioDest = audioCtx.createMediaStreamDestination(); const videoTrack = (await videoStreamPromise).getVideoTracks()[0]; videoTrack.addEventListener('ended', () => { window.parent.postMessage({ type: 'recorder_stop' }, '*'); stopRecording(); }); audioDest.stream.addTrack(videoTrack); APP.conference._room.on(JitsiMeetJS.events.conference.TRACK_ADDED, trackAddedHandler); audioCtx.createMediaElementSource(new Audio(createSilentAudio(1))).connect(audioDest); if (APP.conference.localAudio) { audioCtx.createMediaStreamSource(APP.conference.localAudio.stream).connect(audioDest); } for (let participant of APP.conference._room.getParticipants()) { for (let track of participant.getTracksByMediaType('audio')) { audioCtx.createMediaStreamSource(track.stream).connect(audioDest); } } recorder = new MediaRecorder(audioDest.stream); recorder.onerror = e => { throw e; }; if (isExternalSave) { recorder.ondataavailable = e => { if (e.data && e.data.size > 0) { window.parent.postMessage({ type: 'recorder_data', data: e.data }, '*'); } }; } else { recorder.ondataavailable = e => { if (e.data && e.data.size > 0) { recordingData.push(e.data); } }; } recorder.onstop = () => { videoTrack.stop(); if (!isExternalSave && recordingData.length) { const a = document.createElement('a'); a.href = window.URL.createObjectURL(new Blob(recordingData, { type: recordingData[0].type })); a.download = APP.conference._room.getMeetingUniqueId(); a.click(); } }; recorder.start(1000); window.parent.postMessage({ type: 'recorder_start' }, '*'); } catch (e) { errorHandler(e); clrCtx(); } } function stopRecording() { try { if (recorder) { recorder.stop(); } else { closeDesktopPicker(); } } catch (e) { errorHandler(e); } clrCtx(); } function closeDesktopPicker() { if (window.JitsiMeetElectron) { let desktopPickerCancelBtn = document.getElementById('modal-dialog-cancel-button'); if (desktopPickerCancelBtn) { desktopPickerCancelBtn.click(); } } } function createSilentAudio(time, freq = 44100) { const audioFile = new AudioContext().createBuffer(1, time * freq, freq); let numOfChan = audioFile.numberOfChannels, len = time * freq * numOfChan * 2 + 44, buffer = new ArrayBuffer(len), view = new DataView(buffer), channels = [], i, sample, offset = 0, pos = 0; setUint32(0x46464952); setUint32(len - 8); setUint32(0x45564157); setUint32(0x20746d66); setUint32(16); setUint16(1); setUint16(numOfChan); setUint32(audioFile.sampleRate); setUint32(audioFile.sampleRate * 2 * numOfChan); setUint16(numOfChan * 2); setUint16(16); setUint32(0x61746164); setUint32(len - pos - 4); for (i = 0; i < audioFile.numberOfChannels; i++) { channels.push(audioFile.getChannelData(i)); } while (pos < len) { for (i = 0; i < numOfChan; i++) { sample = Math.max(-1, Math.min(1, channels[i][offset])); sample = (0.5 + sample < 0 ? sample * 32768 : sample * 32767) | 0; view.setInt16(pos, sample, true); pos += 2; } offset++; } return URL.createObjectURL(new Blob([buffer], { type: 'audio/wav' })); function setUint16(data) { view.setUint16(pos, data, true); pos += 2; } function setUint32(data) { view.setUint32(pos, data, true); pos += 4; } } <file_sep>/README.md # Local Jitsi Meet Screen Recorder ## Description Quick hack to record your self hosted [Jitsi Meet](https://github.com/jitsi/jitsi-meet) session locally, just using your browser without Jibri. Uses `getDisplayMedia` just to capture user selected screen and local Jitsi audio streams from each participants. Captures the audio stream of the current user from the selected microphone in the Jitsi interface. Thus, if the microphone is muted, then the user's sound will be muted. When new participants are connected to conference, the recorder also captures theirs audio streams. ## Installation Installation assumes Jitsi Meet's web files are located in `/usr/share/jitsi-meet/index.html`. Simply need to insert [recorder.js](https://github.com/TALRACE/LocalScreenRecorder/blob/main/recorder.js) in the head section: ``` <head> ... <script src="libs/app.bundle.min.js?v=5056"></script> <script src="static/recorder.js"></script> ... <head> ``` ## Integration The recorder implementation does not provide an additional interface. In any case, you can add the interface yourself. It is recommended to use the [Jitsi Iframe API](https://jitsi.github.io/handbook/docs/dev-guide/dev-guide-iframe). Communication with the recorder takes place using Cross-window communication `jitsiIframeApi.getIFrame().contentWindow.postMessage(command, '*');`. Before initializing `Jitsi Iframe API` it is required to subscribe to window event `message` for listening commands from the recorder. Commands for the recorder: * `{type: 'recorder_start', data: {external_save: boolean}}` starts recording and prompts the user to select a screen to record; `external_save` allows to save recording data yourself and passes chunks to the parent window every second * `{type: 'recorder_stop'}` stops recording and prompts the user to save the file or saves the file without notification depending on the browser settings Commands from the recorder: * `{type: 'recorder_ready'}` the recorder is initialized and ready to receive commands to record the screen * `{type: 'recorder_start'}` notification that recording was started. Obviously that after user will choose video stream * `{type: 'recorder_stop'}` recording stopped unexpectedly and prompted to save the file. This can happen if the user has stopped capture of the screen through the browser interface * `{type: 'recorder_error'}` errors have occurred on the recorder side. it is recommended to perform the same actions in your interface as when stopping recording. The recorder will display an error in the console * `{type: 'recorder_data', data: Blob}` chunks of data received if the parameter `external_save` is enabled It is recommended to start screen recording only after all the conditions are met: * recorder announced that it is ready to receive commands through the `recorder_ready` command * `videoConferenceJoined` event occurred in Jitsi Iframe API ## Browser compatibility Latest versions of all popular desktop browsers ## Electron support Yes. The solution uses the `JitsiMeetScreenObtainer.openDesktopPicker` for the electron.
2b5a0f7cc3b7fd577214613ecc4b32b99ae67221
[ "JavaScript", "Markdown" ]
2
JavaScript
conandark/JitsiLocalScreenRecorder
3f54545c0a25be472ddc4b54bd03e6e170e0f319
a9232fee97040be868708407b19a8b0800d2574f
refs/heads/develop
<repo_name>boostcampth/boostcamp3_D<file_sep>/app/src/main/java/com/teamdonut/eatto/ui/map/search/MapSearchNavigator.java package com.teamdonut.eatto.ui.map.search; public interface MapSearchNavigator { void openNavigationView(); void closeNavigationView(); } <file_sep>/app/src/main/java/com/teamdonut/eatto/ui/board/BoardItemActionListener.java package com.teamdonut.eatto.ui.board; import com.teamdonut.eatto.data.Board; public interface BoardItemActionListener { void onBoardClick(Board board); } <file_sep>/app/src/main/java/com/teamdonut/eatto/data/Board.java package com.teamdonut.eatto.data; import android.os.Parcel; import android.os.Parcelable; import com.google.android.gms.maps.model.LatLng; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.google.maps.android.clustering.ClusterItem; public class Board implements Parcelable, ClusterItem { @SerializedName("id") @Expose private int id; @SerializedName("address") @Expose private String address; @SerializedName("title") @Expose private String title; @SerializedName("appointed_time") @Expose private String appointedTime; @SerializedName("max_person") @Expose private int maxPerson; @SerializedName("current_person") @Expose private int currentPerson; @SerializedName("restaurant_name") @Expose private String restaurantName; @SerializedName("writer_id") @Expose private long writerId; @SerializedName("writer_photo") @Expose private String writerPhoto; @SerializedName("writer_name") @Expose private String writerName; @SerializedName("write_date") @Expose private String writeDate; @SerializedName("validation") @Expose private int validation; @SerializedName("content") @Expose private String content; @SerializedName("expire_date") @Expose private String expireDate; @SerializedName("longitude") @Expose private double longitude; @SerializedName("latitude") @Expose private double latitude; @SerializedName("budget") @Expose private String budget; @SerializedName("min_age") @Expose private int minAge; @SerializedName("max_age") @Expose private int maxAge; @Expose(serialize = false, deserialize = false) private boolean isSelect; public Board(String title, String address, String appointed_time, String restaurant_name, int max_person, int min_age, int max_age, double longitude, double latitude, long writer_id, String writerPhoto, String writerName) { this.title = title; this.address = address; this.appointedTime = appointed_time; this.restaurantName = restaurant_name; this.maxPerson = max_person; this.minAge = min_age; this.maxAge = max_age; this.longitude = longitude; this.latitude = latitude; this.writerId = writer_id; this.writerPhoto = writerPhoto; this.writerName = writerName; } public String getWriterName() { return writerName; } public void setWriterName(String writerName) { this.writerName = writerName; } public void setWriterId(long writerId) { this.writerId = writerId; } public String getWriterPhoto() { return writerPhoto; } public void setWriterPhoto(String writerPhoto) { this.writerPhoto = writerPhoto; } public int getId() { return id; } public String getAddress() { return address; } @Override public LatLng getPosition() { return new LatLng(getLatitude(), getLongitude()); } public String getTitle() { return title; } @Override public String getSnippet() { return address; } public String getAppointedTime() { return appointedTime; } public int getMaxPerson() { return maxPerson; } public int getCurrentPerson() { return currentPerson; } public String getRestaurantName() { return restaurantName; } public long getWriterId() { return writerId; } public String getWriteDate() { return writeDate; } public int getValidation() { return validation; } public String getContent() { return content; } public String getExpireDate() { return expireDate; } public double getLongitude() { return longitude; } public double getLatitude() { return latitude; } public String getBudget() { return budget; } public int getMinAge() { return minAge; } public int getMaxAge() { return maxAge; } public void setId(int id) { this.id = id; } public void setAddress(String address) { this.address = address; } public void setTitle(String title) { this.title = title; } public void setAppointedTime(String appointedTime) { this.appointedTime = appointedTime; } public void setMaxPerson(int maxPerson) { this.maxPerson = maxPerson; } public void setCurrentPerson(int currentPerson) { this.currentPerson = currentPerson; } public void setRestaurantName(String restaurantName) { this.restaurantName = restaurantName; } public void setWriterId(int writerId) { this.writerId = writerId; } public void setWriteDate(String writeDate) { this.writeDate = writeDate; } public void setValidation(int validation) { this.validation = validation; } public void setContent(String content) { this.content = content; } public void setExpireDate(String expireDate) { this.expireDate = expireDate; } public void setLongitude(double longitude) { this.longitude = longitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public void setBudget(String budget) { this.budget = budget; } public void setMinAge(int minAge) { this.minAge = minAge; } public void setMaxAge(int maxAge) { this.maxAge = maxAge; } protected Board(Parcel in) { this.title = in.readString(); this.address = in.readString(); this.appointedTime = in.readString(); this.restaurantName = in.readString(); this.maxPerson = in.readInt(); this.minAge = in.readInt(); this.maxAge = in.readInt(); this.longitude = in.readDouble(); this.latitude = in.readDouble(); this.writerPhoto = in.readString(); this.writerName = in.readString(); } public static final Parcelable.Creator<Board> CREATOR = new Parcelable.Creator<Board>() { @Override public Board createFromParcel(Parcel in) { return new Board(in); } @Override public Board[] newArray(int size) { return new Board[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(id); dest.writeString(title); dest.writeString(address); dest.writeString(appointedTime); dest.writeString(restaurantName); dest.writeInt(minAge); dest.writeInt(maxAge); dest.writeInt(maxPerson); dest.writeString(budget); dest.writeString(content); dest.writeDouble(longitude); dest.writeDouble(latitude); dest.writeDouble(longitude); dest.writeString(writerPhoto); dest.writeString(writerName); } public boolean isSelect() { return isSelect; } public void setSelect(boolean select) { isSelect = select; } } <file_sep>/app/src/main/java/com/teamdonut/eatto/common/util/NetworkCheckUtil.java package com.teamdonut.eatto.common.util; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import static android.content.Context.CONNECTIVITY_SERVICE; public class NetworkCheckUtil { public static boolean networkCheck(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { //WIFI에 연결됨 } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { //LTE(이동통신망)에 연결됨 } return true; } else { // 연결되지않음 return false; } } } <file_sep>/.github/ISSUE_TEMPLATE/ISSUE_TEMPLATE.md --- name: ISSUE_TEMPLATE about: Describe this issue template's purpose here. title: '' labels: '' assignees: '' --- ### You want to: * [ ] report a *bug* * [ ] request a *feature* * [ ] request an update to the documentation * [ ] requeset a code change that improves performance * [ ] request other ### Current behaviour *What is actually happening?* ### Steps to reproduce (if the current behaviour is a bug) ### Expected behaviour *What is expected?* ### Setup ### Other information (e.g. stacktraces, related issues, suggestions how to fix) <file_sep>/app/src/main/java/com/teamdonut/eatto/data/Keyword.java package com.teamdonut.eatto.data; import java.util.Date; import io.realm.RealmObject; public class Keyword extends RealmObject { private String content; private Date searchDate; public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getSearchDate() { return searchDate; } public void setSearchDate(Date searchDate) { this.searchDate = searchDate; } } <file_sep>/app/src/main/java/com/teamdonut/eatto/data/model/firebase/FCMRepository.java package com.teamdonut.eatto.data.model.firebase; import com.google.gson.JsonObject; import com.teamdonut.eatto.data.model.ServiceGenerator; import io.reactivex.Single; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; public class FCMRepository { private FCMAPI service = ServiceGenerator.createService(FCMAPI.class, ServiceGenerator.BASE); public static FCMRepository getInstance() { return LazyInit.INSTANCE; } private static class LazyInit { private static final FCMRepository INSTANCE = new FCMRepository(); } public Single<JsonObject> postFCMToken(String token) { return service.postFCMToken(token) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()); } } <file_sep>/app/src/main/java/com/teamdonut/eatto/ui/mypage/judge/JudgeItemActionListener.java package com.teamdonut.eatto.ui.mypage.judge; import com.teamdonut.eatto.data.Board; public interface JudgeItemActionListener { void onJudgeClick(Board board, int score); } <file_sep>/app/src/main/java/com/teamdonut/eatto/ui/mypage/MyPageEditNavigator.java package com.teamdonut.eatto.ui.mypage; public interface MyPageEditNavigator { void showSelectSexDialog(); void selectPhoto(); } <file_sep>/README.md # E.T (Eat Together) **E.T**는 사람이 그리운 직장인, 대학생, 청소년들을 위한 애플리케이션입니다. **E.T**를 통해 같이 식사를 할 사람을 찾아보세요. ### 주요 기능 #### 함께 식사하고 싶은 인원, 장소, 시간, 나이를 설정해 게시글 생성하기. <img src="https://github.com/boostcampth/boostcamp3_D/blob/develop/screenshots/write.gif" /></a> #### 지도를 기반으로 게시글 검색하거나 필터를 통해 원하는 조건으로 게시글 검색하기. <img src="https://github.com/boostcampth/boostcamp3_D/blob/develop/screenshots/search.gif" /></a> #### 게시글 참여 후, 댓글로 다른 참여자들과 소통하기. #### 함께 식사 후 그 날의 모임을 평가하기. <img src="https://github.com/boostcampth/boostcamp3_D/blob/develop/screenshots/check.gif" /></a> #### 랭킹 화면을 통해 내가 만든 모임이 얼마나 좋은 평가를 받는 지 확인하기. <img src="https://github.com/boostcampth/boostcamp3_D/blob/develop/screenshots/evaluate.gif" /></a> ### 팀원 - [이지윤](https://github.com/Jiyunn) - [정우진](https://github.com/wjddnwls918) - [조재혁](https://github.com/ro0opf) ### 개발 환경 - 주 언어 : Java - 아키텍처 : MVVM(Model-View-ViewModel) ### 디자인 - Zeplin - Figma ### 사용 라이브러리 - [RxJava](https://github.com/ReactiveX/RxJava) - [LiveData](https://developer.android.com/topic/libraries/architecture/livedata) - [Realm](https://github.com/realm) - [Retrofit2](https://github.com/bumptech/glide) - [Glide](https://github.com/bumptech/glide) ### Coding Conventions - [Java](https://github.com/wjddnwls918/BoostCamp_androidStyle/blob/develop/Java.md) - [Resource](https://github.com/wjddnwls918/BoostCamp_androidStyle/blob/develop/Resource.md) - [Gradle](https://github.com/wjddnwls918/BoostCamp_androidStyle/blob/develop/Gradle.md) - [Architecture](https://github.com/wjddnwls918/BoostCamp_androidStyle/blob/develop/Architecture.md) ### Server - [Node.js : Express, Sequelize, Mysql](https://github.com/wjddnwls918/RESTAPI_Boostcamp) [![HitCount](http://hits.dwyl.com/wjddnwls918/boostcamp3_D.svg)](http://hits.dwyl.com/wjddnwls918/boostcamp3_D) <file_sep>/app/src/main/java/com/teamdonut/eatto/common/util/KeyboardUtil.java package com.teamdonut.eatto.common.util; import android.content.Context; import android.view.View; import android.view.inputmethod.InputMethodManager; public class KeyboardUtil { public static void hideSoftKeyboard(View view, Context context) { InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } public static void showSoftKeyboard(View view, Context context) { InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); } } <file_sep>/app/src/main/java/com/teamdonut/eatto/ETApplication.java package com.teamdonut.eatto; import android.app.Application; import com.bumptech.glide.Glide; import com.facebook.stetho.Stetho; import com.kakao.auth.KakaoSDK; import com.teamdonut.eatto.common.util.kakao.KakaoSDKAdapter; import com.uphyca.stetho_realm.RealmInspectorModulesProvider; import io.realm.Realm; public class ETApplication extends Application { private static volatile ETApplication instance = null; public static ETApplication getETApplicationContext() { if (instance == null) { throw new IllegalStateException("this application does not inherit ETApplication."); } return instance; } @Override public void onCreate() { super.onCreate(); instance = this; Glide.with(this); Stetho.initialize( Stetho.newInitializerBuilder(this) .enableDumpapp(Stetho.defaultDumperPluginsProvider(this)) .enableWebKitInspector(RealmInspectorModulesProvider.builder(this).build()) .build()); KakaoSDK.init(new KakaoSDKAdapter()); Realm.init(this); } @Override public void onTerminate() { super.onTerminate(); instance = null; } } <file_sep>/app/src/main/java/com/teamdonut/eatto/ui/splash/SplashActivity.java package com.teamdonut.eatto.ui.splash; import android.Manifest; import android.os.Bundle; import android.os.Handler; import com.kakao.auth.ISessionCallback; import com.kakao.auth.Session; import com.kakao.util.exception.KakaoException; import com.kakao.util.helper.log.Logger; import com.teamdonut.eatto.R; import com.teamdonut.eatto.common.util.ActivityUtils; import com.teamdonut.eatto.common.util.GpsModule; import com.teamdonut.eatto.databinding.SplashActivityBinding; import com.tedpark.tedpermission.rx2.TedRx2Permission; import java.lang.ref.WeakReference; import androidx.appcompat.app.AppCompatActivity; import androidx.databinding.DataBindingUtil; public class SplashActivity extends AppCompatActivity { private final int SPLASH_TIME = 2000; private SplashActivityBinding binding; private ISessionCallback iSessionCallback = new ISessionCallback() { @Override public void onSessionOpened() { ActivityUtils.redirectMainActivity(SplashActivity.this); } @Override public void onSessionOpenFailed(KakaoException exception) { if (exception != null) { Logger.e(exception); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.splash_activity); Session.getCurrentSession().addCallback(iSessionCallback); requestLocationPermission(); } @Override protected void onDestroy() { super.onDestroy(); Session.getCurrentSession().removeCallback(iSessionCallback); } private void requestLocationPermission() { TedRx2Permission.with(this) .setDeniedMessage(R.string.all_permission_reject) .setPermissions(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION) .request() .doAfterSuccess(tedPermissionResult -> { checkLoginSessionIsValid(); binding.mlMain.transitionToEnd(); }) .subscribe(tedPermissionResult -> { if (tedPermissionResult.isGranted()) { GpsModule gpsModule = new GpsModule(new WeakReference<>(this), null); gpsModule.startLocationUpdates(); } }, throwable -> { }); } /** * 지정한 Splash 시간 이후에 세션 유효여부를 확인. * opened -> MainActivity 로 이동. * closed -> LoginActivity 로 이동. */ private void checkLoginSessionIsValid() { new Handler().postDelayed(() -> { if (!Session.getCurrentSession().checkAndImplicitOpen()) { ActivityUtils.redirectLoginActivity(this); finish(); } }, SPLASH_TIME); } } <file_sep>/app/src/main/java/com/teamdonut/eatto/ui/mypage/judge/MyPageJudgeViewModel.java package com.teamdonut.eatto.ui.mypage.judge; import com.google.gson.JsonObject; import com.teamdonut.eatto.data.Board; import com.teamdonut.eatto.data.model.board.BoardRepository; import java.util.List; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import io.reactivex.disposables.CompositeDisposable; public class MyPageJudgeViewModel extends ViewModel { private CompositeDisposable disposables = new CompositeDisposable(); private final MutableLiveData<List<Board>> judgeBoards = new MutableLiveData<>(); private final MutableLiveData<Board> submitJudge = new MutableLiveData<>(); private BoardRepository boardRepository = BoardRepository.getInstance(); public void fetchJudgeBoards() { disposables.add(boardRepository.getJudgeBoards() .subscribe(data -> { judgeBoards.postValue(data); }, e -> { e.printStackTrace(); })); } public void sendJudgeResult(Board board, int score) { JsonObject judge = new JsonObject(); judge.addProperty("writer_id", board.getWriterId()); judge.addProperty("board_id", board.getId()); judge.addProperty("score", score); disposables.add(boardRepository.putJudgeBoards(judge) .doAfterSuccess(data -> submitJudge.setValue(board)) .subscribe(data -> { }, e -> { e.printStackTrace(); })); } public MutableLiveData<List<Board>> getJudgeBoards() { return judgeBoards; } public MutableLiveData<Board> getSubmitJudge() { return submitJudge; } } <file_sep>/app/src/main/java/com/teamdonut/eatto/ui/board/BoardFragment.java package com.teamdonut.eatto.ui.board; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import com.teamdonut.eatto.R; import com.teamdonut.eatto.common.RxBus; import com.teamdonut.eatto.common.util.NetworkCheckUtil; import com.teamdonut.eatto.common.util.SnackBarUtil; import com.teamdonut.eatto.databinding.BoardFragmentBinding; import com.teamdonut.eatto.ui.board.add.BoardAddActivity; import com.teamdonut.eatto.ui.board.detail.BoardDetailActivity; import java.util.ArrayList; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import static androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_DRAGGING; import static androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE; public class BoardFragment extends Fragment implements BoardNavigator { private BoardFragmentBinding binding; private BoardViewModel viewModel; private BoardOwnAdapter boardOwnAdapter; private BoardParticipateAdapter boardParticipateAdapter; private final int BOARD_ADD_REQUEST = 100; public static BoardFragment newInstance() { return new BoardFragment(); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); viewModel = ViewModelProviders.of(this).get(BoardViewModel.class); viewModel.setNavigator(this); initOpenBoardObserve(); } @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { binding = DataBindingUtil.inflate(inflater, R.layout.board_fragment, container, false); binding.setViewmodel(viewModel); binding.setLifecycleOwner(this); return binding.getRoot(); } @Override public void onResume() { super.onResume(); initRv(binding.rvOwn); initRv(binding.rvParticipate); if (NetworkCheckUtil.networkCheck(getContext().getApplicationContext())) { viewModel.fetchOwnBoard(); viewModel.fetchParticipateBoard(); } else { SnackBarUtil.showSnackBar(binding.rvOwn, R.string.all_network_check); } } private void initOpenBoardObserve() { viewModel.getOpenBoardEvent().observe(this, data -> { Intent intent = new Intent(getContext(), BoardDetailActivity.class); RxBus.getInstance().sendBus(data); startActivity(intent); }); } private void initRv(RecyclerView rv) { switch (rv.getId()) { case R.id.rv_own: { boardOwnAdapter = new BoardOwnAdapter(new ArrayList<>(0), viewModel); rv.setAdapter(boardOwnAdapter); setAnimation(rv); break; } case R.id.rv_participate: { boardParticipateAdapter = new BoardParticipateAdapter(new ArrayList<>(0), viewModel); rv.setAdapter(boardParticipateAdapter); setAnimation(rv); break; } } LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()); DividerItemDecoration itemDecoration = new DividerItemDecoration(rv.getContext(), 1); itemDecoration.setDrawable(ContextCompat.getDrawable(getActivity().getApplicationContext(), R.drawable.board_divider)); rv.setLayoutManager(layoutManager); rv.addItemDecoration(itemDecoration); rv.setHasFixedSize(true); } public void setAnimation(RecyclerView rv) { rv.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (newState == SCROLL_STATE_DRAGGING) { binding.fabBoardAdd.hide(); } else if (newState == SCROLL_STATE_IDLE) { Animation anim = AnimationUtils.loadAnimation(getContext(), R.anim.fabscrollanim); binding.fabBoardAdd.setAnimation(anim); binding.fabBoardAdd.show(); } } }); } @Override public void onAddBoardClick() { Intent intent = new Intent(getContext(), BoardAddActivity.class); getActivity().startActivityForResult(intent, BOARD_ADD_REQUEST); } } <file_sep>/app/src/main/java/com/teamdonut/eatto/ui/mypage/MyPageNavigator.java package com.teamdonut.eatto.ui.mypage; public interface MyPageNavigator { void goJudge(); void goToProfileEdit(); void makeUserLogout(); } <file_sep>/build.gradle // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext { kotlinVersion = '1.3.11' pluginVersion = '3.4.0' realmVersion = '5.8.0' gmsVersion = '4.2.0' fabricVersion = '1.27.1' } repositories { google() jcenter() maven { url 'https://maven.fabric.io/public' } } dependencies { classpath "com.android.tools.build:gradle:$pluginVersion" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" classpath "io.realm:realm-gradle-plugin:$realmVersion" classpath "com.google.gms:google-services:$gmsVersion" classpath "io.fabric.tools:gradle:$fabricVersion" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } subprojects { repositories { mavenCentral() maven { url 'http://devrepo.kakao.com:8088/nexus/content/groups/public/' } } } } allprojects { repositories { google() jcenter() maven { url 'https://github.com/WickeDev/stetho-realm/raw/master/maven-repo' } maven { url 'https://maven.google.com/' } } } task clean(type: Delete) { delete rootProject.buildDir } ext { minSdkVersion = 21 targetSdkVersion = 28 compileSdkVersion = 28 buildToolsVersion = '28.0.3' //App dependencies androidXVersion = '1.1.0-alpha01' googleMaterialVersion = '1.1.0-alpha03' junitVersion = '4.12' runnerVersion = '1.1.1' espressoVersion = '3.1.1' constraintLayoutVersion = '2.0.0-alpha3' //lifecycle lifecycleExtensionVersion = '1.1.0' //rx rxJavaVersion = '2.2.4' rxAndroidVersion = '2.1.0' rxJavaAdapterVersion = '2.3.0' //glide glideVersion = '4.8.0' //retrofit2 retrofitVersion = '2.0.0-beta3' //okHttp okHttpVersion = '3.12.1' //gSon gsonVersion = '2.4.0' //stetho stethoVersion = '1.5.0' stethoRealmVersion = '2.2.2' //google-play-services gmsLocationVersion = '16.0.0' gmsMapsVersion = '16.1.0' gmsMapUtilVersion = '0.5' //CircleImageView circleImageViewVersion = '3.0.0' //material-range-bar materialRangeBarVersion = '1.4.4' //tedPermission tedPermissionVersion = '2.2.2' tedBottomPickerVersion = '1.1.0' //lottie lottieVersion = '3.0.0-beta1' //Realm realmVersion = '5.8.0' //MaterialEditText materialEditText = '2.1.4' //firebase firebaseVersion = '16.0.7' //crashlytics crashlyticsVersion = '2.9.9' //FireBase Cloud Messaging fcmVersion = '17.3.4' //Livebus liveBusVersion = '0.0.2' } <file_sep>/app/src/main/java/com/teamdonut/eatto/ui/map/search/MapKeywordActionListener.java package com.teamdonut.eatto.ui.map.search; import com.teamdonut.eatto.data.Keyword; public interface MapKeywordActionListener { void onKeywordClick(Keyword keyword); } <file_sep>/app/src/main/java/com/teamdonut/eatto/ui/map/MapFragment.java package com.teamdonut.eatto.ui.map; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.android.gms.common.util.Strings; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.material.bottomsheet.BottomSheetBehavior; import com.google.maps.android.clustering.ClusterItem; import com.google.maps.android.clustering.ClusterManager; import com.google.maps.android.clustering.view.DefaultClusterRenderer; import com.ro0opf.livebus.livebus.LiveBus; import com.teamdonut.eatto.R; import com.teamdonut.eatto.common.RxBus; import com.teamdonut.eatto.common.util.ActivityUtils; import com.teamdonut.eatto.common.util.GpsModule; import com.teamdonut.eatto.common.util.NetworkCheckUtil; import com.teamdonut.eatto.common.util.SnackBarUtil; import com.teamdonut.eatto.data.Board; import com.teamdonut.eatto.data.Filter; import com.teamdonut.eatto.databinding.MapFragmentBinding; import com.teamdonut.eatto.ui.board.add.BoardAddActivity; import com.teamdonut.eatto.ui.board.preview.BoardPreviewDialog; import com.teamdonut.eatto.ui.map.bottomsheet.MapBoardAdapter; import com.teamdonut.eatto.ui.map.search.MapSearchActivity; import com.tedpark.tedpermission.rx2.TedRx2Permission; import java.lang.ref.WeakReference; import java.util.ArrayList; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.constraintlayout.motion.widget.MotionLayout; import androidx.core.content.ContextCompat; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; public class MapFragment extends Fragment implements MapNavigator, OnMapReadyCallback { private MapFragmentBinding binding; private MapViewModel viewModel; private BottomSheetBehavior bottomSheetBehavior; private GoogleMap map; private ClusterManager<Board> clusterManager; private CameraPosition previousCameraPosition; private BoardPreviewDialog dialog; private MapBoardAdapter mapBoardAdapter; private final int BOARD_ADD_REQUEST = 100; private final int DEFAULT_ZOOM = 15; private final LatLng DEFAULT_LOCATION = new LatLng(37.566467, 126.978174); // 서울 시청 private final String PREVIEW_TAG = "preview"; private MotionLayout motionLayout; public static MapFragment newInstance() { return new MapFragment(); } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = DataBindingUtil.inflate(inflater, R.layout.map_fragment, container, false); viewModel = ViewModelProviders.of(this).get(MapViewModel.class); viewModel.setNavigator(this); binding.setViewmodel(viewModel); binding.setLifecycleOwner(this); initMotionLayout(); initOpenBoardObserver(); initBoardsObserver(); if (NetworkCheckUtil.networkCheck(getContext().getApplicationContext())) { initSearchObserver(); } else { SnackBarUtil.showSnackBar(binding.colMap, R.string.all_network_check); } return binding.getRoot(); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initBottomSheetBehavior(); initMapView(savedInstanceState); initRecyclerView(); } @Override public void onResume() { super.onResume(); binding.mv.onResume(); } @Override public void onStop() { super.onStop(); binding.mv.onStop(); } @Override public void onDestroy() { binding.mv.onDestroy(); super.onDestroy(); } @Override public void setBottomSheetExpand(Boolean state) { if (state) { //expand bottom sheet. bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); } else { bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } } @Override public void startLocationUpdates() { TedRx2Permission.with(getActivity()) .setDeniedMessage(R.string.all_permission_reject) .setPermissions(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION) .request() .subscribe(tedPermissionResult -> { if (tedPermissionResult.isGranted()) { GpsModule gpsModule = new GpsModule(new WeakReference<>(getContext()), this); gpsModule.startLocationUpdates(); motionLayout.setTransition(R.id.start, R.id.end); motionLayout.transitionToEnd(); } }, e -> { e.printStackTrace(); }); } @Override public void setMyPosition() { String strLatitude = ActivityUtils.getStrValueSharedPreferences(getActivity(), "gps", "latitude"); String strLongitude = ActivityUtils.getStrValueSharedPreferences(getActivity(), "gps", "longitude"); double latitude = (Strings.isEmptyOrWhitespace(strLatitude) ? DEFAULT_LOCATION.latitude : Double.parseDouble(strLatitude)); double longitude = (Strings.isEmptyOrWhitespace(strLatitude) ? DEFAULT_LOCATION.longitude : Double.parseDouble(strLongitude)); map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), DEFAULT_ZOOM)); } @Override public void goToBoardAdd() { Intent intent = new Intent(getContext(), BoardAddActivity.class); startActivityForResult(intent, BOARD_ADD_REQUEST); } @Override public void goToMapSearch() { Intent intent = new Intent(getActivity(), MapSearchActivity.class); startActivity(intent); } @Override public void onMapReady(GoogleMap googleMap) { map = googleMap; setMyPosition(); initCluster(); map.setOnMarkerClickListener(clusterManager); map.setOnMapLoadedCallback(() -> { }); } private void initBottomSheetBehavior() { bottomSheetBehavior = BottomSheetBehavior.from(binding.mapBottomSheet.clMapBottomSheet); bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) { switch (newState) { case BottomSheetBehavior.STATE_EXPANDED: { viewModel.isSheetExpanded.set(true); break; } case BottomSheetBehavior.STATE_COLLAPSED: { viewModel.isSheetExpanded.set(false); break; } default: return; } } @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { binding.fabBoardAdd.setRotation(slideOffset * 720); binding.fabBoardAdd.setTranslationX(slideOffset * 180); } }); } private void openBoardPreview(Board board) { Object flag = LiveBus.getInstance().getBus("BoardDialog").getValue(); if(flag == null || !(boolean)flag) { LiveBus.getInstance().sendBus("BoardDialog", true); dialog = BoardPreviewDialog.newInstance(board); dialog.show(getChildFragmentManager(), PREVIEW_TAG); RxBus.getInstance().sendBus(board); //send bus } } private void initBoardsObserver() { viewModel.getBoards().observe(this, data -> { Filter filter = viewModel.getFilter(); //get Filter from viewModel. if (data.size() > 0) { //it could be search result / location result. mapBoardAdapter.updateItems(data); if (filter != null) { //if search result setBottomSheetExpand(true); } clusterManager.clearItems(); clusterManager.addItems(data); clusterManager.cluster(); } else if (filter != null) { //data size is 0 SnackBarUtil.showSnackBar(binding.colMap, R.string.board_search_can_not_find_result); } viewModel.resetFilter(); }); } private void initOpenBoardObserver() { viewModel.getOpenBoardEvent().observe(this, board -> { openBoardPreview(board); }); } private void initSearchObserver() { LiveBus.getInstance().getBus("filter").observe(this, o -> { if(o instanceof Filter) { viewModel.loadBoards((Filter)o); LiveBus.getInstance().sendBus("filter", null); } }); } private void initRecyclerView() { RecyclerView rv = binding.mapBottomSheet.rvBoard; mapBoardAdapter = new MapBoardAdapter(new ArrayList<>(), viewModel); DividerItemDecoration itemDecoration = new DividerItemDecoration(rv.getContext(), 1); itemDecoration.setDrawable(ContextCompat.getDrawable(getActivity().getApplicationContext(), R.drawable.board_divider)); rv.setHasFixedSize(true); rv.addItemDecoration(itemDecoration); rv.setLayoutManager(new LinearLayoutManager(getActivity())); rv.setAdapter(mapBoardAdapter); } private void initMapView(@Nullable Bundle savedInstanceState) { binding.mv.getMapAsync(this); binding.mv.onCreate(savedInstanceState); } private Bitmap createDrawableFromView(Context context, View view) { DisplayMetrics displayMetrics = new DisplayMetrics(); ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels); view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels); view.buildDrawingCache(); Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); view.draw(canvas); return bitmap; } private void initCluster() { clusterManager = new ClusterManager<>(getActivity(), map); previousCameraPosition = map.getCameraPosition(); clusterManager.setRenderer(new DefaultClusterRenderer(this.getActivity(), map, clusterManager) { @Override protected void onClusterItemRendered(ClusterItem clusterItem, Marker marker) { super.onClusterItemRendered(clusterItem, marker); View marker_root_view = LayoutInflater.from(getContext()).inflate(R.layout.custom_marker, null); marker.setIcon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(getContext(), marker_root_view))); return; } @Override protected void onBeforeClusterItemRendered(ClusterItem item, MarkerOptions markerOptions) { super.onBeforeClusterItemRendered(item, markerOptions); View marker_root_view = LayoutInflater.from(getContext()).inflate(R.layout.custom_marker, null); markerOptions.icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(getContext(), marker_root_view))); return; } }); clusterManager.setOnClusterItemClickListener(data -> { map.animateCamera(CameraUpdateFactory.newLatLngZoom(data.getPosition(), DEFAULT_ZOOM)); data.setSelect(true); mapBoardAdapter.notifyDataSetChanged(); binding.mapBottomSheet.rvBoard.getLayoutManager().scrollToPosition(mapBoardAdapter.getItemPosition(data)); setBottomSheetExpand(true); return true; }); clusterManager.setOnClusterClickListener(data -> { map.animateCamera(CameraUpdateFactory.newLatLngZoom(data.getPosition(), map.getCameraPosition().zoom + 1)); return true; }); map.setOnCameraIdleListener(() -> { if (bottomSheetBehavior.getState() != BottomSheetBehavior.STATE_EXPANDED) { viewModel.fetchAreaBoards(map.getProjection().getVisibleRegion().nearLeft, map.getProjection().getVisibleRegion().farRight); if (clusterManager.getRenderer() instanceof GoogleMap.OnCameraIdleListener) { ((GoogleMap.OnCameraIdleListener) clusterManager.getRenderer()).onCameraIdle(); } CameraPosition position = map.getCameraPosition(); if (previousCameraPosition == null || previousCameraPosition.zoom != position.zoom) { previousCameraPosition = map.getCameraPosition(); } } motionLayout.setProgress(0); }); } private void initMotionLayout() { motionLayout = binding.mlMain; motionLayout.setTransitionListener(new MotionLayout.TransitionListener() { @Override public void onTransitionStarted(MotionLayout motionLayout, int i, int i1) { } @Override public void onTransitionChange(MotionLayout motionLayout, int i, int i1, float v) { binding.ibSetMypos.setRotation(v * 7200); } @Override public void onTransitionCompleted(MotionLayout motionLayout, int i) { } @Override public void onTransitionTrigger(MotionLayout motionLayout, int i, boolean b, float v) { } }); } public BottomSheetBehavior getBottomSheetBehavior() { return bottomSheetBehavior; } } <file_sep>/app/src/main/java/com/teamdonut/eatto/common/util/GpsModule.java package com.teamdonut.eatto.common.util; import android.annotation.SuppressLint; import android.content.Context; import android.location.Location; import android.os.Looper; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationCallback; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationResult; import com.google.android.gms.location.LocationServices; import com.teamdonut.eatto.ui.main.MainActivity; import com.teamdonut.eatto.ui.map.MapNavigator; import java.lang.ref.WeakReference; public class GpsModule { private LocationRequest locationRequest; private static final long UPDATE_INTERVAL = 15000, FASTEST_INTERVAL = 10000; private FusedLocationProviderClient fusedLocationProviderClient; private MapNavigator mapNavigator; private final Context context; private LocationCallback locationCallback = new LocationCallback(){ @Override public void onLocationResult(LocationResult locationResult) { super.onLocationResult(locationResult); if (locationResult == null) { return; } for (Location location : locationResult.getLocations()) { if(location != null){ ActivityUtils.saveStrValueSharedPreferences(context, "gps", "longitude", String.valueOf(location.getLongitude())); ActivityUtils.saveStrValueSharedPreferences(context, "gps", "latitude", String.valueOf(location.getLatitude())); stopLocationUpdates(); if(context instanceof MainActivity) { mapNavigator.setMyPosition(); } } } } }; public GpsModule(WeakReference<Context> context, MapNavigator mapNavigator){ this.context = context.get(); fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this.context); this.mapNavigator = mapNavigator; locationRequest = new LocationRequest() .setFastestInterval(FASTEST_INTERVAL) .setInterval(UPDATE_INTERVAL) .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } private void stopLocationUpdates(){ if (fusedLocationProviderClient != null) { fusedLocationProviderClient.removeLocationUpdates(locationCallback); } } @SuppressLint("MissingPermission") public void startLocationUpdates() { fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper()); } } <file_sep>/app/src/main/java/com/teamdonut/eatto/ui/login/LoginNavigator.java package com.teamdonut.eatto.ui.login; public interface LoginNavigator { void redirectLoginActivity(); void redirectMainActivity(); void saveUser(long id, String name, String photo); } <file_sep>/app/build.gradle apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-kapt' apply plugin: 'realm-android' apply plugin: 'io.fabric' android { compileSdkVersion rootProject.ext.compileSdkVersion buildToolsVersion rootProject.ext.buildToolsVersion defaultConfig { applicationId "com.teamdonut.eatto" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } dataBinding { enabled = true } packagingOptions { exclude "lib/arm64-v8a/librealm-jni.so" } } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion" implementation "androidx.appcompat:appcompat:$androidXVersion" implementation "com.google.android.material:material:$googleMaterialVersion" implementation "androidx.constraintlayout:constraintlayout:$constraintLayoutVersion" //lifeCycle implementation "android.arch.lifecycle:extensions:$lifecycleExtensionVersion" //rx implementation "io.reactivex.rxjava2:rxjava:$rxJavaVersion" implementation "io.reactivex.rxjava2:rxandroid:$rxAndroidVersion" implementation "com.squareup.retrofit2:adapter-rxjava2:$rxJavaAdapterVersion" //retrofit implementation "com.squareup.retrofit2:retrofit:$retrofitVersion" //okHttp implementation "com.squareup.okhttp3:okhttp:$okHttpVersion" //gson converter implementation "com.squareup.retrofit2:converter-gson:$gsonVersion" //glide implementation "com.github.bumptech.glide:glide:$glideVersion" kapt "com.github.bumptech.glide:compiler:$glideVersion" //kakao implementation group: 'com.kakao.sdk', name: 'usermgmt', version: project.KAKAO_SDK_VERSION //stetho implementation "com.facebook.stetho:stetho:$stethoVersion" implementation "com.facebook.stetho:stetho-okhttp3:$stethoVersion" implementation "com.uphyca:stetho_realm:$stethoRealmVersion" //gms location implementation "com.google.android.gms:play-services-location:$gmsLocationVersion" implementation "com.google.android.gms:play-services-maps:$gmsMapsVersion" implementation "com.google.maps.android:android-maps-utils:$gmsMapUtilVersion" //CircleImageView implementation "de.hdodenhof:circleimageview:$circleImageViewVersion" //material-range-bar implementation "com.appyvet:materialrangebar:$materialRangeBarVersion" //tedPermission implementation "gun0912.ted:tedpermission-rx2:$tedPermissionVersion" //tedBottomPicker implementation "gun0912.ted:tedbottompicker:$tedBottomPickerVersion" //Lottie implementation "com.airbnb.android:lottie:$lottieVersion" testImplementation "junit:junit:$junitVersion" //runner androidTestImplementation "androidx.test:runner:$runnerVersion" //espresso androidTestImplementation "androidx.test.espresso:espresso-core:$espressoVersion" //MaterialEditText implementation "com.rengwuxian.materialedittext:library:$materialEditText" //firebase implementation "com.google.firebase:firebase-core:$firebaseVersion" //crashlytics implementation "com.crashlytics.sdk.android:crashlytics:$crashlyticsVersion" //Firebase Cloud Messaing implementation "com.google.firebase:firebase-messaging:$fcmVersion" //LiveBus implementation "ro0opf.lifeinus:livebus:$liveBusVersion" } apply plugin: 'com.google.gms.google-services'<file_sep>/app/src/main/java/com/teamdonut/eatto/ui/home/HomeFragment.java package com.teamdonut.eatto.ui.home; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.android.gms.common.util.Strings; import com.ro0opf.livebus.livebus.LiveBus; import com.teamdonut.eatto.R; import com.teamdonut.eatto.common.RxBus; import com.teamdonut.eatto.common.util.ActivityUtils; import com.teamdonut.eatto.common.util.HorizontalDividerItemDecorator; import com.teamdonut.eatto.common.util.NetworkCheckUtil; import com.teamdonut.eatto.common.util.SnackBarUtil; import com.teamdonut.eatto.data.Board; import com.teamdonut.eatto.databinding.HomeFragmentBinding; import com.teamdonut.eatto.ui.board.preview.BoardPreviewDialog; import com.teamdonut.eatto.ui.map.search.MapSearchActivity; import java.util.ArrayList; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; public class HomeFragment extends Fragment implements HomeNavigator { private HomeFragmentBinding binding; private HomeViewModel viewModel; private UserRankingAdapter userRankingAdapter; private BoardRecommendAdapter boardRecommendAdapter; public static HomeFragment newInstance() { return new HomeFragment(); } @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { binding = DataBindingUtil.inflate(inflater, R.layout.home_fragment, container, false); viewModel = ViewModelProviders.of(this).get(HomeViewModel.class); binding.setViewmodel(viewModel); binding.setLifecycleOwner(this); return binding.getRoot(); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); viewModel.setNavigator(this); if (NetworkCheckUtil.networkCheck(getContext().getApplicationContext())) { initRecommendRv(); initRankingRv(); fetchData(); } else { SnackBarUtil.showSnackBar(binding.rvRank, R.string.all_network_check); } } private void fetchData() { viewModel.fetchRankUsers(); viewModel.fetchRankUser(); viewModel.fetchRecommendBoards( ActivityUtils.getStrValueSharedPreferences(getActivity(), "gps", "longitude"), ActivityUtils.getStrValueSharedPreferences(getActivity(), "gps", "latitude") ); } private void initRankingRv() { RecyclerView rv = binding.rvRank; userRankingAdapter = new UserRankingAdapter(new ArrayList<>(0), viewModel); rv.addItemDecoration(new HorizontalDividerItemDecorator(ContextCompat.getDrawable(getContext(), R.drawable.ranking_divider), 0.03)); rv.setHasFixedSize(true); rv.setLayoutManager(new LinearLayoutManager(getActivity())); rv.setAdapter(userRankingAdapter); } private void initRecommendRv() { RecyclerView rv = binding.rvRecommend; boardRecommendAdapter = new BoardRecommendAdapter(new ArrayList<>(0), viewModel); LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false) { @Override public boolean checkLayoutParams(RecyclerView.LayoutParams lp) { lp.width = (getWidth()) / 2; return super.checkLayoutParams(lp); } }; rv.setLayoutManager(layoutManager); rv.setHasFixedSize(true); rv.setAdapter(boardRecommendAdapter); } @Override public void goToMapSearch() { Intent intent = new Intent(getActivity(), MapSearchActivity.class); startActivity(intent); } @Override public void openBoardPreview(Board board) { Object flag = LiveBus.getInstance().getBus("BoardDialog").getValue(); if(flag == null || !(boolean)flag) { LiveBus.getInstance().sendBus("BoardDialog", true); final String PREVIEW_TAG = "preview"; BoardPreviewDialog dialog = BoardPreviewDialog.newInstance(board); dialog.show(getChildFragmentManager(), PREVIEW_TAG); RxBus.getInstance().sendBus(board); //send bus } } } <file_sep>/app/src/main/java/com/teamdonut/eatto/common/BaseRealmRecyclerViewAdapter.java package com.teamdonut.eatto.common; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.RecyclerView; import io.realm.OrderedCollectionChangeSet; import io.realm.OrderedRealmCollection; import io.realm.OrderedRealmCollectionChangeListener; import io.realm.RealmList; import io.realm.RealmModel; import io.realm.RealmResults; /** * The RealmBaseRecyclerAdapter class is an abstract utility class for binding RecyclerView UI elements to Realm data. * <p> * This adapter will automatically handle any updates to its data and call {@code notifyDataSetChanged()}, * {@code notifyItemInserted()}, {@code notifyItemRemoved()} or {@code notifyItemRangeChanged()} as appropriate. * <p> * The RealmAdapter will stop receiving updates if the Realm instance providing the {@link OrderedRealmCollection} is * closed. * <p> * If the adapter contains Realm model classes with a primary key that is either an {@code int} or a {@code long}, call * {@code setHasStableIds(true)} in the constructor and override {@link #getItemId(int)} as described by the Javadoc in that method. * * @param <T> type of {@link RealmModel} stored in the adapter. * @param <S> type of RecyclerView.ViewHolder used in the adapter. * @see RecyclerView.Adapter#setHasStableIds(boolean) * @see RecyclerView.Adapter#getItemId(int) */ public abstract class BaseRealmRecyclerViewAdapter<T extends RealmModel, S extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<S> { private final boolean hasAutoUpdates; private final boolean updateOnModification; private final OrderedRealmCollectionChangeListener listener; @Nullable private OrderedRealmCollection<T> dataSet; private OrderedRealmCollectionChangeListener createListener() { return new OrderedRealmCollectionChangeListener() { @Override public void onChange(Object collection, OrderedCollectionChangeSet changeSet) { if (changeSet.getState() == OrderedCollectionChangeSet.State.INITIAL) { notifyDataSetChanged(); return; } // For deletions, the adapter has to be notified in reverse order. OrderedCollectionChangeSet.Range[] deletions = changeSet.getDeletionRanges(); for (int i = deletions.length - 1; i >= 0; i--) { OrderedCollectionChangeSet.Range range = deletions[i]; notifyItemRangeRemoved(range.startIndex + dataOffset(), range.length); } OrderedCollectionChangeSet.Range[] insertions = changeSet.getInsertionRanges(); for (OrderedCollectionChangeSet.Range range : insertions) { notifyItemRangeInserted(range.startIndex + dataOffset(), range.length); } if (!updateOnModification) { return; } OrderedCollectionChangeSet.Range[] modifications = changeSet.getChangeRanges(); for (OrderedCollectionChangeSet.Range range : modifications) { notifyItemRangeChanged(range.startIndex + dataOffset(), range.length); } } }; } public int dataOffset() { return 0; } public BaseRealmRecyclerViewAdapter(@Nullable OrderedRealmCollection<T> data, boolean autoUpdate) { this(data, autoUpdate, true); } public BaseRealmRecyclerViewAdapter(@Nullable OrderedRealmCollection<T> data, boolean autoUpdate, boolean updateOnModification) { if (data != null && !data.isManaged()) throw new IllegalStateException("Only use this adapter with managed RealmCollection, " + "for un-managed lists you can just use the BaseRecyclerViewAdapter"); this.dataSet = data; this.hasAutoUpdates = autoUpdate; this.listener = hasAutoUpdates ? createListener() : null; this.updateOnModification = updateOnModification; } @Override public void onAttachedToRecyclerView(final RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); if (hasAutoUpdates && isDataValid()) { //noinspection ConstantConditions addListener(dataSet); } } @Override public void onDetachedFromRecyclerView(final RecyclerView recyclerView) { super.onDetachedFromRecyclerView(recyclerView); if (hasAutoUpdates && isDataValid()) { //noinspection ConstantConditions removeListener(dataSet); } } @Override public int getItemCount() { //noinspection ConstantConditions return isDataValid() ? dataSet.size() : 0; } @SuppressWarnings("WeakerAccess") @Nullable public T getItem(int index) { if (index < 0) { throw new IllegalArgumentException("Only indexes >= 0 are allowed. Input was: " + index); } // To avoid exception, return null if there are some extra positions that the // child adapter is adding in getItemCount (e.g: to display footer view in recycler view) if (dataSet != null && index >= dataSet.size()) return null; //noinspection ConstantConditions return isDataValid() ? dataSet.get(index) : null; } public void deleteAllItems() { if (hasAutoUpdates) { if (isDataValid()) { //noinspection ConstantConditions dataSet.deleteFirstFromRealm(); removeListener(dataSet); } notifyDataSetChanged(); } } @SuppressWarnings("WeakerAccess") public void updateItems(@Nullable OrderedRealmCollection<T> data) { if (hasAutoUpdates) { if (isDataValid()) { //noinspection ConstantConditions removeListener(dataSet); } if (data != null) { addListener(data); } } this.dataSet = data; notifyDataSetChanged(); } private void addListener(@NonNull OrderedRealmCollection<T> data) { if (data instanceof RealmResults) { RealmResults<T> results = (RealmResults<T>) data; //noinspection unchecked results.addChangeListener(listener); } else if (data instanceof RealmList) { RealmList<T> list = (RealmList<T>) data; //noinspection unchecked list.addChangeListener(listener); } else { throw new IllegalArgumentException("RealmCollection not supported: " + data.getClass()); } } private void removeListener(@NonNull OrderedRealmCollection<T> data) { if (data instanceof RealmResults) { RealmResults<T> results = (RealmResults<T>) data; //noinspection unchecked results.removeChangeListener(listener); } else if (data instanceof RealmList) { RealmList<T> list = (RealmList<T>) data; //noinspection unchecked list.removeChangeListener(listener); } else { throw new IllegalArgumentException("RealmCollection not supported: " + data.getClass()); } } private boolean isDataValid() { return dataSet != null && dataSet.isValid(); } } <file_sep>/app/src/main/java/com/teamdonut/eatto/ui/mypage/judge/JudgeAdapter.java package com.teamdonut.eatto.ui.mypage.judge; import android.view.LayoutInflater; import android.view.ViewGroup; import com.teamdonut.eatto.common.BaseRecyclerViewAdapter; import com.teamdonut.eatto.data.Board; import com.teamdonut.eatto.databinding.MypageJudgeItemBinding; import java.util.List; import androidx.recyclerview.widget.RecyclerView; public class JudgeAdapter extends BaseRecyclerViewAdapter<Board, JudgeAdapter.ViewHolder> { private MyPageJudgeViewModel viewModel; private JudgeItemActionListener judgeItemActionListener; public JudgeAdapter(List<Board> dataSet, MyPageJudgeViewModel myPageJudgeViewModel) { super(dataSet); this.viewModel = myPageJudgeViewModel; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { MypageJudgeItemBinding binding = MypageJudgeItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false); judgeItemActionListener = (board, score) -> { viewModel.sendJudgeResult(board, score); }; binding.setListener(judgeItemActionListener); return new ViewHolder(binding); } @Override public void onBindView(ViewHolder holder, int position) { holder.binding.setBoard(getItem(position)); } static class ViewHolder extends RecyclerView.ViewHolder { private MypageJudgeItemBinding binding; public ViewHolder(MypageJudgeItemBinding binding) { super(binding.getRoot()); this.binding = binding; } } }<file_sep>/app/src/main/java/com/teamdonut/eatto/data/model/board/BoardAPI.java package com.teamdonut.eatto.data.model.board; import com.google.gson.JsonObject; import com.teamdonut.eatto.data.Board; import java.util.List; import io.reactivex.Single; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Query; public interface BoardAPI { @POST("board") Single<JsonObject> postBoard( @Body Board board, @Header("token") String token ); @GET("board/today") Single<List<Board>> getTodayBoards( ); @GET("home/board") Single<List<Board>> getRecommendBoards( @Query("longitude") String longitude, @Query("latitude") String latitude ); @GET("board/list/my") Single<List<Board>> getOwnBoard( @Header("kakao_id") long kakaoId ); @GET("board/list/participation") Single<List<Board>> getParticipatedBoard( @Header("kakao_id") long kakaoId ); @POST("board/participation") Single<JsonObject> postParticipateBoard( @Header("kakao_id") long kakaoId, @Body JsonObject jsonObject ); @GET("map/list") Single<List<Board>> getAreaBoards( @Query("left_longitude") double leftLongitude, @Query("left_latitude") double leftLatitude, @Query("right_longitude") double rightLongitude, @Query("right_latitude") double rightLatitude ); @GET("search/list") Single<List<Board>> getSearchBoards( @Header("kakao_id") long kakaoId, @Query(value = "keyword", encoded = true) String keyword, @Query("min_time") int minTime, @Query("max_time") int maxTime, @Query("min_age") int minAge, @Query("max_age") int maxAge, @Query("max_person") int maxPerson, @Query("budget") String budget ); // MyPage @GET("mypage/judge") Single<List<Board>> getJudgeBoards( @Header("kakao_id") long kakaoId ); @PUT("mypage/judge") Single<JsonObject> putJudgeBoard( @Header("kakao_id") long kakaoId, @Header("token") String token, @Body JsonObject jsonObject ); } <file_sep>/app/src/main/java/com/teamdonut/eatto/ui/board/preview/BoardPreviewDialog.java package com.teamdonut.eatto.ui.board.preview; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.DialogFragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import com.ro0opf.livebus.livebus.LiveBus; import com.teamdonut.eatto.R; import com.teamdonut.eatto.data.Board; import com.teamdonut.eatto.databinding.BoardPreviewDialogBinding; import com.teamdonut.eatto.ui.board.detail.BoardDetailActivity; public class BoardPreviewDialog extends DialogFragment { private BoardPreviewDialogBinding binding; private BoardPreviewViewModel viewModel; private Observer<Boolean> joinObserver; private static final String BOARD_ARGUMENT = "Board"; public static BoardPreviewDialog newInstance(Board board) { Bundle argument = new Bundle(); argument.putParcelable(BOARD_ARGUMENT, board); BoardPreviewDialog fragment = new BoardPreviewDialog(); fragment.setArguments(argument); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(DialogFragment.STYLE_NORMAL, R.style.FullScreenDialog); initJoinObserver(); viewModel = ViewModelProviders.of(this).get(BoardPreviewViewModel.class); viewModel.getIsSubmitted().observe(this, joinObserver); } private void initJoinObserver() { joinObserver = isSubmitted -> { dismiss(); if (isSubmitted) { Intent intent = new Intent(getActivity(), BoardDetailActivity.class); startActivity(intent); } }; } @Override public void onDismiss(@NonNull DialogInterface dialog) { viewModel.getIsSubmitted().removeObserver(joinObserver); LiveBus.getInstance().sendBus("BoardDialog", false); super.onDismiss(dialog); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.board_preview_dialog, container, false); binding.setViewmodel(viewModel); binding.cl.setOnClickListener(v -> { dismiss(); }); return binding.getRoot(); } @Override public void onResume() { super.onResume(); viewModel.setBoardValue(getArguments().getParcelable(BOARD_ARGUMENT)); } } <file_sep>/app/src/main/java/com/teamdonut/eatto/data/kakao/Meta.java package com.teamdonut.eatto.data.kakao; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Meta { @SerializedName("same_name") @Expose private SameName sameName; @SerializedName("total_count") @Expose private int totalCount; @SerializedName("pageable_count") @Expose private int pageableCount; @SerializedName("is_end") @Expose private boolean isEnd; public SameName getSameName() { return sameName; } public int getTotalCount() { return totalCount; } public int getPageableCount() { return pageableCount; } public boolean isEnd() { return isEnd; } } <file_sep>/app/src/main/java/com/teamdonut/eatto/data/model/comment/CommentAPI.java package com.teamdonut.eatto.data.model.comment; import com.google.gson.JsonObject; import com.teamdonut.eatto.data.Comment; import java.util.List; import io.reactivex.Single; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.POST; import retrofit2.http.Query; public interface CommentAPI { @GET("board/comment") Single<List<Comment>> getComments( @Header("kakao_id") long kakaoId, @Query("board_id") int boardId); @POST("board/comment") Single<JsonObject> postComments( @Header("kakao_id") long kakaoId, @Header("token") String token, @Body Comment comment); } <file_sep>/app/src/main/java/com/teamdonut/eatto/ui/login/LoginActivity.java package com.teamdonut.eatto.ui.login; import android.content.Intent; import android.os.Bundle; import com.kakao.auth.Session; import com.teamdonut.eatto.R; import com.teamdonut.eatto.common.helper.RealmDataHelper; import com.teamdonut.eatto.common.util.ActivityUtils; import com.teamdonut.eatto.common.util.kakao.LoginSessionCallback; import com.teamdonut.eatto.data.User; import com.teamdonut.eatto.databinding.LoginActivityBinding; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.databinding.DataBindingUtil; import io.realm.Realm; public class LoginActivity extends AppCompatActivity implements LoginNavigator { private LoginActivityBinding binding; private LoginSessionCallback callback; private Realm realm; @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { //로그인 결과를 세션이 받음. if (Session.getCurrentSession().handleActivityResult(requestCode, resultCode, data)) { return; } super.onActivityResult(requestCode, resultCode, data); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.login_activity); realm = Realm.getDefaultInstance(); initCallback(); } @Override protected void onDestroy() { super.onDestroy(); realm.close(); Session.getCurrentSession().removeCallback(callback); } private void initCallback() { callback = new LoginSessionCallback(this); Session.getCurrentSession().addCallback(callback); } @Override public void redirectLoginActivity() { ActivityUtils.redirectLoginActivity(this); } @Override public void redirectMainActivity() { ActivityUtils.redirectMainActivity(this); } @Override public void saveUser(long kakaoId, String name, String photo) { if (realm.where(User.class).count() == 0) { //if user is already existed. RealmDataHelper.insertUser(kakaoId, name, photo); } else { RealmDataHelper.updateUser(name, 0, photo); } } } <file_sep>/app/src/main/java/com/teamdonut/eatto/ui/map/MapNavigator.java package com.teamdonut.eatto.ui.map; public interface MapNavigator { void setBottomSheetExpand(Boolean isExpand); void startLocationUpdates(); void setMyPosition(); void goToBoardAdd(); void goToMapSearch(); } <file_sep>/app/src/main/java/com/teamdonut/eatto/ui/main/MainViewModel.java package com.teamdonut.eatto.ui.main; import android.view.MenuItem; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.teamdonut.eatto.R; import com.teamdonut.eatto.data.model.firebase.FCMRepository; import com.teamdonut.eatto.ui.board.BoardFragment; import com.teamdonut.eatto.ui.home.HomeFragment; import com.teamdonut.eatto.ui.map.MapFragment; import com.teamdonut.eatto.ui.mypage.MyPageFragment; import androidx.databinding.BindingMethod; import androidx.databinding.BindingMethods; import io.reactivex.disposables.CompositeDisposable; @BindingMethods({ @BindingMethod( type = BottomNavigationView.class, attribute = "onNavigationItemSelected", method = "setOnNavigationItemSelectedListener" ) }) public class MainViewModel { private MainNavigator navigator; private CompositeDisposable disposables = new CompositeDisposable(); private FCMRepository fcmRepository = FCMRepository.getInstance(); MainViewModel(MainNavigator navigator) { this.navigator = navigator; } public boolean onNavigationItemSelected(MenuItem item) { int itemId = item.getItemId(); switch (itemId) { case R.id.menu_home: { navigator.changeScreen(itemId, HomeFragment.newInstance()); return true; } case R.id.menu_map: { navigator.changeScreen(itemId, MapFragment.newInstance()); return true; } case R.id.menu_board: { navigator.changeScreen(itemId, BoardFragment.newInstance()); return true; } case R.id.menu_mypage: { navigator.changeScreen(itemId, MyPageFragment.newInstance()); return true; } default: { return false; } } } public void postFcmToken(String token) { disposables.add( fcmRepository.postFCMToken(token) .subscribe(data -> { }, e -> { e.printStackTrace(); }) ); } } <file_sep>/app/src/main/java/com/teamdonut/eatto/ui/main/MainNavigator.java package com.teamdonut.eatto.ui.main; import androidx.fragment.app.Fragment; interface MainNavigator { void changeScreen(int itemId, Fragment fragment); }
6f93b780cbbf740dcda17fdcb5f718f98df0ccc9
[ "Markdown", "Java", "Gradle" ]
33
Java
boostcampth/boostcamp3_D
1512b0081a9e65c5f5a44b45ecc31265b573740e
f925d1ad325acd018288337dbcece514922d269e
refs/heads/master
<repo_name>BadOPCode/party-line-sub<file_sep>/index.js 'use strict'; /** * index.js - <NAME> 2014-12-20 * Party Line subsystem interface library bootstrap. * @author <NAME> * @license MIT. Read LICENSE for more information. * @fileOverview Bootstraps library. */ /** * Export lib/party-line-sub */ module.exports = require('./lib');<file_sep>/README.md party-line-sub ============== Interface for a Party Line subsystem.
af3db57c9c3f3a3e3c6cf3beb1da6596bc43aef4
[ "JavaScript", "Markdown" ]
2
JavaScript
BadOPCode/party-line-sub
8d348b825843f27ecb733552b2d9c49b5454ea11
ec09ee701b225778c2eb208753590deec8eb073e
refs/heads/master
<repo_name>XDGFX/plankton<file_sep>/website/app.js // Pageloader removal function removePageloader() { document.getElementById("pageloader").classList.remove("is-active") }
c21c2df3036de0b465dc8c5efa2a4b6f35a0d2a9
[ "JavaScript" ]
1
JavaScript
XDGFX/plankton
a41e4975bb6b0b9126e99e4c0daf0b2966a5b9af
1e32cb9ea5d6b4b75fea627a595ec80708e862c0
refs/heads/master
<repo_name>camachoh/mlbrun<file_sep>/main.py #!/usr/bin/env python import argparse from datetime import datetime, date, timedelta import sys import mlb import mlb_database def parse_args(): """ Parse command line options """ parser = argparse.ArgumentParser( prog='mlbpool', description='mlb pool app to get current team stats (wins vs losses)' ) parser.add_argument('-d', '--date', dest='cmd_date', default=None, help='Specify date you want to see stats\ for "example: YYYYMMDD"' ) args = parser.parse_args() return args def validate_date(gameday): """ Ensure date is a acceptable valid date """ try: if gameday is not None: gameday = datetime.strptime(gameday, "%Y%M%d") else: gameday = date.today() - timedelta(0) gameday = gameday.strftime('%Y%m%d') except ValueError: msg = "Incorrect data format, should be YYYYMMDD or YYYYMMD" sys.exit(msg) return gameday def get_mlb_date(valid_date): """ Return YYYY, DD, MM data """ year = valid_date[0:4] month = valid_date[4:6] day = valid_date[6:8] return {"year": year, "month": month, "day": day} def main(): """ RUN MLB APP """ args = parse_args() # Create DB mlb_database.MLB_DB() game_date = get_mlb_date(validate_date(args.cmd_date)) mlb_data = mlb.MLBData(game_date) mlb_data.get_scoreboard(mlb_data.get_url()) mlb_database.MLB_DB()._db_conn.close() if __name__ == '__main__': main() <file_sep>/mlb_database.py import sqlite3 import os class MLB_DB(object): """ Database Setup """ _db_conn = None _db_cur = None def __init__(self, dbname='databases/default.db'): self.dbname = dbname self.dbtable = "team_data" self._db_conn = sqlite3.connect(self.dbname) self._db_cur = self._db_conn.cursor() self.create_db_table() def create_db_table(self): """ Create database and table """ # Create table self._db_cur.execute('''CREATE TABLE IF NOT EXISTS %s (team_id INT UNIQUE, team_name VARCHAR, score_0 INT DEFAULT '0', score_1 INT DEFAULT '0', score_2 INT DEFAULT '0', score_3 INT DEFAULT '0', score_4 INT DEFAULT '0', score_5 INT DEFAULT '0', score_6 INT DEFAULT '0', score_7 INT DEFAULT '0', score_8 INT DEFAULT '0', score_9 INT DEFAULT '0', score_10 INT DEFAULT '0', score_11 INT DEFAULT '0', score_12 INT DEFAULT '0', score_13 INT DEFAULT '0')''' % self.dbtable) def add_team_query(self, data): """ asdf """ pass def add_teams(self, data): """ Add Teams to DB """ for k, v in data.items(): try: self._db_cur.execute("insert or ignore into team_data \ (team_id, team_name) values (?, ?)", (v, k)) self._db_conn.commit() except sqlite3.Error as er: print er def add_score(self, data): """ Add Team Score via Team ID """ # sql_score_add = """update $s SET for team_id, score in data.items(): if int(score) in range(0, 14): column = "score_" + (score) sql_cmd = ("UPDATE %s SET %s=1 WHERE team_id=%s" % (self.dbtable, column, team_id)) print sql_cmd try: self._db_cur.execute(sql_cmd) self._db_conn.commit() except sqlite3.Error as er: print er <file_sep>/mlb.py import json import urllib2 import mlb_database BASE_MLB_GAME_URL = "http://gd2.mlb.com/components/game/mlb/" class MLBData(object): """ Base representation of mlb data """ def __init__(self, date): self.game_year = date['year'] self.game_month = date['month'] self.game_date = date['day'] def get_url(self): year = "year_" + self.game_year month = "/month_" + self.game_month day = "/day_" + self.game_date return BASE_MLB_GAME_URL + year + month + day def get_dates(self): """ Get list of days in month """ pass def get_teams(self, data): """ Get Teams that played on date specified """ teams = {} # print data['away_team_name'], data['away_team_id'] teams[data['home_team_name']] = data['home_team_id'] teams[data['away_team_name']] = data['away_team_id'] mlb_database.MLB_DB().add_teams(teams) def get_team_runs(self, data): """ Get Team Stat """ team_score = {} for k, v in data.items(): if 'linescore' in k: team_score[data['home_team_id']] = v['r']['home'] team_score[data['away_team_id']] = v['r']['away'] mlb_database.MLB_DB().add_score(team_score) def parse_scoreboard(self, data): """ parse data for gameday """ for k, v in data.iteritems(): if "home_team_name" in k: home_team = v if "home_team_id" in k: home_team_id = v if "linescore" in k: home_team_score = v['r']['home'] away_team_score = v['r']['away'] if "away_team_name" in k: away_team = v if "away_team_id" in k: away_team_id = v # print "Home Team: {} [{}] Score: {} VS Away Team: {} [{}] Score: {}".format( # home_team, # home_team_id, # home_team_score, # away_team, # away_team_id, # away_team_score # ) def get_scoreboard(self, url): """ Get master_scoreboard data """ game_file = (url + "/master_scoreboard.json") game_file = urllib2.urlopen(game_file) # game_file = game_file.read() data_file = json.loads(game_file.read()) for k, v in data_file['data']['games'].iteritems(): if 'game' in k: for game_data in v: self.get_teams(game_data) self.get_team_runs(game_data) # self.parse_scoreboard(game_data)
1ef39f17cd5b39f6383e3836701418cfb66f3a38
[ "Python" ]
3
Python
camachoh/mlbrun
fc0bdc014e711a81db72499d478bb26f89bcc61b
092b3b222e5e9220252c60b9833ff27dbeb20f61
refs/heads/master
<file_sep><?php /** * 权限类 */ namespace App\Http\Controllers\Api\V1; use App\Transformers\PermissionTransformer; use Illuminate\Http\Request; class PermissionController extends Controller { /** * 当前登录用户权限 * * @return \Dingo\Api\Http\Response */ public function index() { $permissions = $this->user()->getAllPermissions(); return $this->response->collection($permissions, new PermissionTransformer()); } } <file_sep><?php /** * 权限数据处理 */ namespace App\Transformers; use League\Fractal\TransformerAbstract; use Spatie\Permission\Models\Permission; class PermissionTransformer extends TransformerAbstract { /** * 权限数据 * * @param Permission $permission * @return array */ public function transform(Permission $permission) { return [ 'id' => $permission->id, 'name' => $permission->name, ]; } }<file_sep><?php /** * 图片类 */ namespace App\Http\Controllers\Api\V1; use App\Handlers\ImageUploadHandler; use App\Http\Requests\Api\V1\ImageRequest; use App\Models\Image; use App\Transformers\ImageTransformer; use Illuminate\Http\Request; class ImageController extends Controller { /** * 上传图片 * * @param ImageRequest $request * @param ImageUploadHandler $uploader * @param Image $image * @return \Dingo\Api\Http\Response */ public function store(ImageRequest $request, ImageUploadHandler $uploader, Image $image) { $user = $this->user(); $size = $request->type == 'avatar' ? 362 : 1024; $result = $uploader->save( $request->image, str_plural($request->type), $user->id, $size ); $image->path = $result['path']; $image->type = $request->type; $image->user_id = $user->id; $image->save(); return $this->response->item($image, new ImageTransformer()) ->setStatusCode(201); } } <file_sep><?php /** * 用户类 */ namespace App\Http\Controllers\Api\V1; use App\Models\Image; use Auth; use App\Http\Requests\Api\V1\UserRequest; use App\Models\User; use App\Transformers\UserTransformer; use Illuminate\Http\Request; class UserController extends Controller { /** * 注册用户信息 * * @param UserRequest $request * @return mixed */ public function store(UserRequest $request) { $verify_data = \Cache::get($request->verification_key); if (!$verify_data) { return $this->response->error('验证码以失效', 422); } if (!hash_equals($verify_data['code'], $request->verification_code)) { // 返回 401 return $this->response->errorUnauthorized('验证码错误'); } $user = User::create([ 'name' => $request->name, 'phone' => $request->phone, 'password' => $request->password, ]); // 清除验证码缓存 \Cache::forget($request->verification_key); return $this->response->item($this->user, new UserTransformer()) ->setMeta([ 'access_token' => Auth::guard('api')->fromUser($user), 'token_type' => 'Bearer', 'expires_in' => Auth::guard('api')->factory()->getTTL() * 60 ]) ->setStatusCode(201);; } /** * 获取用户信息 * * @return \Dingo\Api\Http\Response */ public function show() { return $this->response->item($this->user(), new UserTransformer()); } /** * 编辑用户信息 * * @param UserRequest $request * @return \Dingo\Api\Http\Response */ public function update(UserRequest $request) { $user = $this->user(); $attributes = $request->only(['name', 'email', 'introduction', 'registration_id']); if ($request->avatar_image_id) { $image = Image::find($request->avatar_image_id); $attributes['avatar'] = $image->path; } $user->update($attributes); return $this->response->item($user, new UserTransformer()); } /** * 活跃用户 * * @param User $user * @return \Dingo\Api\Http\Response */ public function activedIndex(User $user) { return $this->response->collection($user->getActiveUsers(), new UserTransformer()); } } <file_sep><?php /** * 图片验证码类 */ namespace App\Http\Controllers\Api\V1; use App\Http\Requests\Api\V1\CaptchaRequest; use Gregwar\Captcha\CaptchaBuilder; use Illuminate\Http\Request; class CaptchaController extends Controller { /** * 图片验证码 * * @param CaptchaRequest $request * @param CaptchaBuilder $captchaBuilder * @return mixed */ public function store(CaptchaRequest $request, CaptchaBuilder $captchaBuilder) { $key = 'captcha-' . str_random(15); $phone = $request->phone; $captcha = $captchaBuilder->build(); $expired_at = now()->addMinutes(2); \Cache::put($key, ['phone' => $phone, 'code', $captcha->getPhrase()], $expired_at); $result = [ 'captcha_key' => $key, 'expired_at' => $expired_at, 'captcha_image_content' => $captcha->inline(), ]; return $this->response->array($result)->setStatusCode(201); } } <file_sep><?php /** * 分类类 */ namespace App\Http\Controllers\Api\V1; use App\Models\Category; use App\Transformers\CategoryTransformer; use Illuminate\Http\Request; class CategoryController extends Controller { /** * 分类列表 * * @return \Dingo\Api\Http\Response */ public function index() { return $this->response->collection(Category::all(), new CategoryTransformer()); } } <file_sep><?php /** * 用户数据处理 */ namespace App\Transformers; use App\Models\User; use League\Fractal\TransformerAbstract; class UserTransformer extends TransformerAbstract { /** * 可用包括 * * @var array */ protected $availableIncludes = ['role']; /** * 用户数据 * * @param User $user * @return array */ public function transform(User $user) { return [ 'id' => $user->id, 'name' => $user->name, 'email' => $user->email, 'phone' => $user->phone, 'avatar' => $user->avatar, 'introduction' => $user->introduction, 'bound_phone' => $user->phone ? true : false, 'bound_wechat' => ($user->weixin_unionid || $user->weixin_openid) ? true : false, 'last_actived_at' => $user->last_actived_at->toDateTimeString(), 'registration_id' => $user->registration_id, 'created_at' => $user->created_at->toDateTimeString(), 'updated_at' => $user->updated_at->toDateTimeString(), ]; } /** * 导入角色 * * @param User $user * @return \League\Fractal\Resource\Collection */ public function includeRole(User $user) { return $this->collection($user->roles, new RoleTransformer()); } }<file_sep>APP_NAME=Laravel APP_ENV=local APP_KEY= APP_DEBUG=true APP_LOG_LEVEL=debug APP_URL=http://larabbs.test DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=larabbs DB_USERNAME=homestead DB_PASSWORD=<PASSWORD> BROADCAST_DRIVER=log CACHE_DRIVER=file SESSION_DRIVER=file QUEUE_DRIVER=sync REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379 MAIL_DRIVER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=null MAIL_PASSWORD=<PASSWORD> MAIL_ENCRYPTION=null PUSHER_APP_ID= PUSHER_APP_KEY= PUSHER_APP_SECRET= # API接口配置 API_STANDARDS_TREE= API_SUBTYPE= API_PREFIX= API_VERSION= API_DEBUG= # 云片短信服务商 YUNPIAN_API_KEY= # 微信配置 WEIXIN_KEY= WEIXIN_SECRET= # JWT 令牌[JSON Web Token] JWT_SECRET= JWT_TTL= JWT_REFRESH_TTL= # jpush 消息推送 JPUSH_KEY= JPUSH_SECRET=<file_sep><?php /** * 资源推荐类 */ namespace App\Http\Controllers\Api\V1; use App\Models\Link; use App\Transformers\LinkTransformer; use Illuminate\Http\Request; class LinkController extends Controller { /** * 资源推荐列表 * * @param Link $link * @return \Dingo\Api\Http\Response */ public function index(Link $link) { $links = $link->getAllCached(); return $this->response->collection($links, new LinkTransformer()); } } <file_sep><?php /** * API 接口基类 */ namespace App\Http\Controllers\Api\V1; use Dingo\Api\Routing\Helpers; use Illuminate\Http\Request; use App\Http\Controllers\Controller as BaseController; use Symfony\Component\HttpKernel\Exception\HttpException; class Controller extends BaseController { use Helpers; /** * 返回错误提示 * * @param $status_code * @param null $message * @param int $code */ public function errorResponse($status_code, $message = null, $code = 0) { throw new HttpException($status_code, $message, null, [], $code); } }
32a2a3d15811926e133e5c921d01909fbb196c59
[ "PHP", "Shell" ]
10
PHP
buqiu/laravel-larabbs
20e1c16f70be2877ddaeacc364033841ee0d64d2
fe3bca6d7344b9e563827b2567ad607fb37461db
refs/heads/master
<repo_name>League-Level0-Student/level-0-module-3-Isaacpants<file_sep>/src/ObediantFobot.java import org.jointheleague.graphical.robot.Robot; public class ObediantFobot { // Obedient Robot // Copyright (c) The League of Amazing Programmers 2013-2017 // Level 0 // We are going to make an obedient robot that will obey our commands to draw // shapes. static Robot r2d2 = new Robot(); // 1. Make a new class, create a main method, and show the robot. public static void main(String[] args) { // 2. Have the robot draw a square. r2d2.penDown(); r2d2.setSpeed(500); r2d2.hide(); r2d2.setPenWidth(5); drawSquare(); r2d2.penUp(); r2d2.move(100); r2d2.penDown(); drawTriangle(); r2d2.penUp(); r2d2.move(100); r2d2.penDown(); drawCircle(); // 3. Extract this code into a drawSquare() method. // 4. Have the robot draw a triangle. // 5. Extract this code into a drawTriangle() method. // 6. Have the robot draw a circle. // 7. Extract this code into a drawCircle() method. } static void drawSquare() { for (int i = 0; i < 4; i++) { r2d2.move(50); r2d2.turn(90); } } static void drawTriangle() { for (int i = 0; i < 3; i++) { r2d2.turn(120); r2d2.move(50); } } static void drawCircle() { for (int i = 0; i < 360; i++) { r2d2.turn(1); r2d2.move(1); } } }<file_sep>/src/Horoscope.java import javax.swing.JOptionPane; public class Horoscope { public static void main(String[] args) { String sign = JOptionPane.showInputDialog("What is ur sign"); if(sign.equals ("Aquarius")) { JOptionPane.showMessageDialog(null, "U Will die 1 day "); } else if(sign.equals ("Pisces")) { JOptionPane.showMessageDialog(null, "U Will die 1 day"); } else if(sign.equals ("Aries")) { JOptionPane.showMessageDialog(null, "U Will die 1 day"); } else if(sign.equals ("Taurus")) { JOptionPane.showMessageDialog(null, "U Will die 1 day"); } else if(sign.equals ("Gemini")) { JOptionPane.showMessageDialog(null, "U Will die 1 day"); } else if(sign.equals ("Cancer")) { JOptionPane.showMessageDialog(null, "U Will die 1 day"); } else if(sign.equals ("Leo")) { JOptionPane.showMessageDialog(null, "U Will die 1 day"); } else if(sign.equals ("Virgo")) { JOptionPane.showMessageDialog(null, "U Will die 1 day"); } else if(sign.equals ("Libra")) { JOptionPane.showMessageDialog(null, "U Will die 1 day"); } else if(sign.equals ("Scorpio")) { JOptionPane.showMessageDialog(null, "U Will die 1 day"); } else if(sign.equals ("Sagittarius")) { JOptionPane.showMessageDialog(null, "U Will die 1 day"); } else if(sign.equals ("Capricorn")) { JOptionPane.showMessageDialog(null, "U Will die 1 day"); }else { JOptionPane.showMessageDialog(null, "Thats not a sign"); } } }
29fc2e70106195b256451164370530a0651e0867
[ "Java" ]
2
Java
League-Level0-Student/level-0-module-3-Isaacpants
667e0a4d2c67e5cd213c8335c801b24d0e874144
d0c521aeba5a1ee65e2e0956ce7023db5fbaea55
refs/heads/main
<repo_name>mvshashank123/React-Google-Maps-Clone<file_sep>/src/Map.js import React, { useRef, useEffect, useState } from "react"; import * as mapboxgl from "mapbox-gl"; //import MapboxDirections from '@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions' //import '@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions.css' import "./MapStyles.css"; //Add the access token here mapboxgl.accessToken = ""; const Map = () => { const mapContainerRef = useRef(null); const [longitude, setLongitude] = useState(0); const [latitude, setLatitude] = useState(0); const [zoom, setZoom] = useState(5); navigator.geolocation.getCurrentPosition(successLocation, errorLocation, { enableHighAccuracy: true, }); //When the location is fetched successfully. function successLocation(position) { //Mapbox receives longitude and latitude from Geolocation API setLongitude(position.coords.longitude) setLatitude(position.coords.latitude) } //When there is an error in fetching the location the location with these coordinates is mocked. function errorLocation() { setLongitude(12.9716) setLatitude(77.5946) } // This gets fired up when the application loads useEffect(() => { const map = new mapboxgl.Map({ container: mapContainerRef.current, style: "mapbox://styles/mapbox/streets-v11", center: [latitude, longitude], zoom: zoom, }); //This adds zoom button and compass map.addControl(new mapboxgl.NavigationControl(), "top-right"); map.on("move", () => { setLongitude(map.getCenter().longitude); setLatitude(map.getCenter().latitude); setZoom(map.getZoom().toFixed(2)); }); //This is used to add directions to the map interface //This is used to add directions to the map interface // const directions = new MapboxDirections({ // accessToken: mapboxgl.accessToken, // unit: 'metric' // }); // map.addControl(directions, "top-left"); // var directions = new MapboxDirections({ // accessToken: mapboxgl.accessToken, // unit: 'metric', // profile: 'cycling' // }); // map.addControl(directions); // Clean up on unmount return () => map.remove(); }, []); // eslint-disable-line react-hooks/exhaustive-deps return ( <div> <div className="map__container" ref={mapContainerRef} /> </div> ); }; export default Map;
a9da8e2763992c73ddc937fe559ae22f3285e611
[ "JavaScript" ]
1
JavaScript
mvshashank123/React-Google-Maps-Clone
7bc9bb5a2fd3f43bd0c27f5876d2768c32f4333b
fa85804c584b0511a19e4a7bafc7a87c21f82e1e
refs/heads/master
<repo_name>nirajp82/basic-react-with-redux-songs<file_sep>/src/actions/index.js import * as constants from '../util/constants'; export const selectSong = (song) => { console.log("selectSong Action Creator Called"); return { type: constants.SONG_SELECTED, payload: song }; }<file_sep>/src/reducers/index.js import { combineReducers } from 'redux'; import * as Constant from '../util/constants'; const songsReducer = () => { return [ { title: "Vando satguru charan ko", duration: 1.01 }, { title: "Aavoji wala mara gher aavoji wala", duration: 2.02 }, { title: "Raini ki unidi piya pase aaviya", duration: 3.03 }, { title: "Utho re pyare piya naval vilasi", duration: 4.04 }, { title: "Puran bharma bhram se nyare", duration: 5.05 } ]; }; const selectedSongReducer = (selectedSong = null, action = null) => { console.log("selectedSongReducer called"); if (action.type === Constant.SONG_SELECTED) { return action.payload; } return selectedSong; }; export default combineReducers({ songs: songsReducer, selectedSong: selectedSongReducer });<file_sep>/src/util/constants.js export const SONG_SELECTED = "SONG_SELECTED";
547ac79a05f1c9ab4682f478c4df68fdf148db12
[ "JavaScript" ]
3
JavaScript
nirajp82/basic-react-with-redux-songs
cd5bd2e859dc26ca7d88fbcffe965f1357eab764
96776d8941b06817c7afa98769daaf546984b7d6
refs/heads/master
<file_sep>import React, { Component } from 'react'; import { reduxForm } from 'redux-form'; import { page15Submit } from '../actions/page_actions'; class page15 extends Component { onSubmit(e) { this.props.page15Submit(e); } render() { const {fields: {daysPerMonth}, handleSubmit} = this.props; return( <div className="container"> <div className="row"> <div className="col-md-12"> <div className="well bs-component"> <fieldset> <legend>Question 15</legend> <div className="col-md-8 offset-xs-2"> <form className="form" onSubmit={handleSubmit((e) => this.onSubmit(e))}> <div className="form-group"> <label>How many days per month are you in the office?</label> <textarea className="form-control" rows="3" { ...daysPerMonth }></textarea> </div> <button type="submit" className="btn btn-primary">Next</button> </form> </div> </fieldset> </div> </div> </div> </div> ) } } function validate(formProps) { const errors = {}; return errors; } export default reduxForm({ form: 'page15', fields: ['daysPerMonth'], validate }, null, { page15Submit })(page15); <file_sep>import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { reduxForm } from 'redux-form'; import { page9Submit } from '../actions/page_actions'; import $ from 'jquery'; class Page9 extends Component { constructor(props) { super(props); this.state = { totalDragged: 0 } } onSubmit(e) { var oneToOneChildrens = $(document.getElementById('oneToOne')).children(); var threeToFiveChildrens = $(document.getElementById('threeToFive')).children(); var moreThan5Childrens = $(document.getElementById('moreThan5')).children(); var oneToOne = 0; var threeToFive = 0; var moreThan5 = 0; oneToOneChildrens.map((e) => { if(oneToOneChildrens[e].id == "0.5h"){ oneToOne += 0.5; }else if(oneToOneChildrens[e].id == "1h") { oneToOne++; } }) threeToFiveChildrens.map((e) => { if(threeToFiveChildrens[e].id == "0.5h"){ threeToFive += 0.5; }else if(threeToFiveChildrens[e].id == "1h") { threeToFive++; } }) moreThan5Childrens.map((e) => { if(moreThan5Childrens[e].id == "0.5h"){ moreThan5 += 0.5; }else if(moreThan5Childrens[e].id == "1h") { moreThan5++; } }) var props = { oneToOne: oneToOne, threeToFive: threeToFive, moreThan5: moreThan5 } this.props.page9Submit(props); } drop(ev) { if(ev.target.id != "oneToOne" && ev.target.id != "threeToFive" && ev.target.id != "moreThan5") { return; } var data = ev.dataTransfer.getData("text"); var clonedNode = document.getElementById(data).cloneNode(true); $(clonedNode).removeClass('col-md-4'); $(clonedNode).addClass('col-md-12'); $(clonedNode).on('dragend', function (e) { this.remove(); }) if(this.state.totalDragged < 8) { ev.target.appendChild(clonedNode); } var droppedHole = document.getElementById('droppedHours'); this.setState({ totalDragged: $(droppedHole).children().length }) } drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } allowDrop(ev) { ev.preventDefault(); } render() { const {fields: {whatAreYou}, handleSubmit} = this.props; return( <div className="container"> <div className="row"> <div className="col-md-12"> <div className="well bs-component"> <fieldset> <legend>Question 9: How do you currently use the office?</legend> <div className="col-md-8 offset-xs-2"> <h5>Of the in person meetings what proportion of your meetings are: </h5> <div id="oneToOne" onDrop={(e) => this.drop(e)} onDragOver={(e) => this.allowDrop(e)} className="col-md-4" style={{ minHeight: '40vh', paddingBottom: '5em' }}> <div className="col-md-12" style={{ height: '2em', textAlign: 'center', paddingTop: '7px' , backgroundColor: 'skyblue', borderRadius: '5px', marginBottom: '1em' }}> <h6 className="text-xs-center">1-1</h6> </div> </div> <div id="threeToFive" onDrop={(e) => this.drop(e)} onDragOver={(e) => this.allowDrop(e)} className="col-md-4" style={{ minHeight: '40vh', paddingBottom: '5em' }}> <div className="col-md-12" style={{ height: '2em', textAlign: 'center', paddingTop: '7px' , backgroundColor: 'skyblue', borderRadius: '5px', marginBottom: '1em' }}> <h6 className="text-xs-center">3-5</h6> </div> </div> <div id="moreThan5" onDrop={(e) => this.drop(e)} onDragOver={(e) => this.allowDrop(e)} className="col-md-4" style={{ minHeight: '40vh', paddingBottom: '5em' }}> <div className="col-md-12" style={{ height: '2em', textAlign: 'center', paddingTop: '7px' , backgroundColor: 'skyblue', borderRadius: '5px', marginBottom: '1em' }}> <h6 className="text-xs-center">More than 5</h6> </div> </div> <div className="col-md-12"> <div id="0.5h" draggable="true" onDragStart={(e) => this.drag(e)} className="col-md-4" style={{ backgroundColor: '#0062c4', height: '3em', marginBottom: '1em', paddingTop: '0.7em', color: 'white', borderRadius: '5px', textAlign: 'center', marginRight: '2em' }}> 1/2hr </div> <div id="1h" draggable="true" onDragStart={(e) => this.drag(e)} className="col-md-offset-1 col-md-4" style={{ backgroundColor: '#ff9300', height: '3em', marginBottom: '1em', paddingTop: '0.7em', color: 'white', borderRadius: '5px', textAlign: 'center' }}> 1hr </div> </div> <div className="col-md-12"> <button onClick={(e) => this.onSubmit(e)} className="btn btn-primary">Next</button> </div> </div> </fieldset> </div> </div> </div> </div> ) } } function validate(formProps) { const errors = {}; if (!formProps.whatAreYou) { errors.whatAreYou = 'Please select a choice'; } return errors; } export default reduxForm({ form: 'Page9', fields: ['whatAreYou'], validate }, null, { page9Submit })(Page9); <file_sep>import React, { Component } from 'react'; import { reduxForm } from 'redux-form'; import { page18Submit } from '../actions/page_actions'; class page18 extends Component { onSubmit(e) { this.props.page18Submit(e); } render() { const {fields: {designImpactCor, designImpactEnv, workspaceInteraction, currentWork3, futureWork3}, handleSubmit} = this.props; return( <div className="container"> <div className="row"> <div className="col-md-12"> <div className="well bs-component"> <fieldset> <legend>Question 18: Future space</legend> <div className="col-md-8 offset-xs-2"> <form className="form" onSubmit={handleSubmit((e) => this.onSubmit(e))}> <div className="form-group"> <label>What impact do you think the design of the current office has on its corporate image?</label> <textarea className="form-control" rows="3" { ...designImpactCor }></textarea> </div> <div className="form-group"> <label>What impact do you think the design of the current office has on its environmental sustainability?</label> <textarea className="form-control" rows="3" { ...designImpactEnv }></textarea> </div> <div className="form-group"> <label>What could improve workspace interaction?</label> <textarea className="form-control" rows="3" { ...workspaceInteraction }></textarea> </div> <div className="form-group"> <label>Please provide 3 words to describe your current workplace</label> <textarea className="form-control" rows="3" { ...currentWork3 }></textarea> </div> <div className="form-group"> <label>Please provide 3 words to describe you ideal future workplace</label> <textarea className="form-control" rows="3" { ...futureWork3 }></textarea> </div> <button type="submit" className="btn btn-primary">Next</button> </form> </div> </fieldset> </div> </div> </div> </div> ) } } function validate(formProps) { const errors = {}; return errors; } export default reduxForm({ form: 'page18', fields: ['designImpactCor', 'designImpactEnv', 'workspaceInteraction', 'currentWork3', 'futureWork3'], validate }, null, { page18Submit })(page18); <file_sep>export function page_data(state={}, action) { switch (action.type) { case "SIGN_IN": return {...state, credentials: action.payload}; case "PAGE_1": return {...state, page1: action.payload}; case "PAGE_2": return {...state, page2: action.payload}; case "PAGE_3": return {...state, page3: action.payload}; case "PAGE_4": return {...state, page4: action.payload}; case "PAGE_5": return {...state, page5: action.payload}; case "PAGE_6": return {...state, page6: action.payload}; case "PAGE_7": return {...state, page7: action.payload}; case "PAGE_8": return {...state, page8: action.payload}; case "PAGE_9": return {...state, page9: action.payload}; case "PAGE_10": return {...state, page10: action.payload}; case "PAGE_11": return {...state, page11: action.payload}; case "PAGE_12": return {...state, page12: action.payload}; case "PAGE_13": return {...state, page13: action.payload}; case "PAGE_14": return {...state, page14: action.payload}; case "PAGE_15": return {...state, page15: action.payload}; case "PAGE_16": return {...state, page16: action.payload}; case "PAGE_17": return {...state, page17: action.payload}; case "PAGE_18": return {...state, page18: action.payload}; case "FINISH": state={}; return state; } return state; } <file_sep>import React, { Component } from 'react'; import { reduxForm, reset } from 'redux-form'; import { page2Submit } from '../actions/page_actions'; import $ from 'jquery'; class Page2 extends Component { onSubmit(e) { this.props.page2Submit(e); } render() { const {fields: {affliation, specificDetails}, handleSubmit} = this.props; return( <div className="container"> <div className="row"> <div className="col-md-12"> <div className="well bs-component"> <fieldset> <legend>Question 2: What is your affiliation?</legend> <div className="col-md-8 offset-xs-2"> <form className="form" onSubmit={handleSubmit((e) => this.onSubmit(e))}> <div className="form-check"> <label className="form-check-label"> <input {...affliation} className="form-check-input" type="radio" value="GEN_CSS" /> Generalist CSS </label> </div> <div className="form-check"> <label className="form-check-label"> <input {...affliation} className="form-check-input" type="radio" value="Practice" /> Practice </label> </div> { affliation.value == "Practice" ? <div className="form-group"><label>Please specify</label><textarea className="form-control" rows="3" { ...specificDetails }></textarea></div> : <div></div> } <div className="form-check"> <label className="form-check-label"> <input {...affliation} className="form-check-input" type="radio" value="MSO" /> MSO </label> </div> { affliation.value == "MSO" ? <div className="form-group"><label>Please specify</label><textarea className="form-control" rows="3" { ...specificDetails }></textarea></div> : <div></div> } <div className="form-check"> <label className="form-check-label"> <input {...affliation} className="form-check-input" type="radio" value="PD_Learning_HR" /> PD/Learning/HR </label> </div> <div className="form-check"> <label className="form-check-label"> <input {...affliation} className="form-check-input" type="radio" value="FABP" /> Finance/Accouting/Benefits/Payroll </label> </div> <div className="form-check"> <label className="form-check-label"> <input {...affliation} className="form-check-input" type="radio" value="COMMS" /> Comms (internal/external) </label> </div> <div className="form-check"> <label className="form-check-label"> <input {...affliation} className="form-check-input" type="radio" value="EA" /> EA </label> </div> <div className="form-check"> <label className="form-check-label"> <input {...affliation} className="form-check-input" type="radio" value="OS" /> Office services (IT, facilities, repro) </label> </div> <div className="form-check"> <label className="form-check-label"> <input {...affliation} className="form-check-input" type="radio" value="FF" /> Firm functions (Audit, legal, risk, tax, MIO, MPS, Travel, VG, Firm IT) </label> </div> <div className="form-check"> <label className="form-check-label"> <input {...affliation} className="form-check-input" type="radio" value="Other" /> Other </label> </div> { affliation.value == "Other" ? <div className="form-group"><label>Please specify</label><textarea className="form-control" rows="3" { ...specificDetails }></textarea></div> : <div></div> } {affliation.touched && affliation.error && <div className="form-control-feedback">{affliation.error}</div>} <button type="submit" className="btn btn-primary">Next</button> </form> </div> </fieldset> </div> </div> </div> </div> ) } } function validate(formProps) { const errors = {}; if (!formProps.whatAreYou) { errors.whatAreYou = 'Please select a choice'; } return errors; } export default reduxForm({ form: 'Page2', fields: ['affliation', 'specificDetails'] }, null, { page2Submit })(Page2); <file_sep>import React, { Component } from 'react'; import { reduxForm } from 'redux-form'; import { page17Submit } from '../actions/page_actions'; class page17 extends Component { onSubmit(e) { this.props.page17Submit(e); } render() { var A = [ {name: 'Strongly Agree', value: 'STA'}, {name: 'Agree', value: 'AG'}, {name: 'Neither Agree nor Disagree', value: 'NAND'}, {name: 'Disagree', value: 'DA'}, {name: 'Strongly Disagree', value: 'SDA'} ] var SATISFACTION = [ { Q: 'The design of the current office space creates an enjoyable environment to work in', fieldValue: this.props.fields.one, selectionType: 'E' }, { Q: 'The design of the office enables me to work productively and supports my daily tasks', fieldValue: this.props.fields.two, selectionType: 'E' }, { Q: 'I can focus when I\'m in the office' , fieldValue: this.props.fields.three , selectionType: 'S' }, { Q: 'I can collaborate with colleagues when I\'m in the office', fieldValue: this.props.fields.four, selectionType: 'FT' }, { Q: 'I can be creative in the office', fieldValue: this.props.fields.five, selectionType: 'FT' }, { Q: 'I feel physically comfortable in the office', fieldValue: this.props.fields.six, selectionType: 'E' }, { Q: 'The design of the office supports mobility', fieldValue: this.props.fields.seven, selectionType: 'E' }, { Q: 'My current office space supports my physical wellbeing', fieldValue: this.props.fields.eight, selectionType: 'A' }, { Q: 'I feel connected to the office', fieldValue: this.props.fields.nine, selectionType: 'E' }, { Q: 'The office supports me to develop client relationships', fieldValue: this.props.fields.ten, selectionType: 'E' }, { Q: 'I am proud to bring visitors to the office', fieldValue: this.props.fields.eleven, selectionType: 'E'}, { Q: 'The office is reflective of the firm’s culture', fieldValue: this.props.fields.twelve, selectionType: 'E'} ] const {fields: {one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve}, handleSubmit} = this.props; return( <div className="container"> <div className="row"> <div className="col-md-12"> <div className="well bs-component"> <fieldset> <legend>Question 17</legend> <div className="col-md-8 offset-xs-2"> <h4 style={{ marginBottom: '20px' }} >Please state the extent to which you agree or disagree with the following statements.</h4> <form className="form" onSubmit={handleSubmit((e) => this.onSubmit(e))}> {SATISFACTION.map((e) => { return( <div> { e.Q } { A.map((v) => { return ( <div className="form-check"> <label className="form-check-label"> <input {...e.fieldValue} className="form-check-input" type="radio" value={v.name} /> { v.name } </label> </div> ) }) } </div> ) })} <button type="submit" className="btn btn-primary">Next</button> </form> </div> </fieldset> </div> </div> </div> </div> ) } } function validate(formProps) { const errors = {}; return errors; } export default reduxForm({ form: 'page17', fields: ['one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve'], validate }, null, { page17Submit })(page17); <file_sep>import React, { Component } from 'react'; class Finish extends Component { render() { return( <div className="container"> <div className="row"> <div className="col-md-12"> <div className="well bs-component"> <fieldset> <legend>Survey finished</legend> <div className="col-md-12"> <h1>Thank you for finishing the survey</h1> </div> </fieldset> </div> </div> </div> </div> ) } } export default Finish; <file_sep>import React, { Component } from 'react'; import { reduxForm } from 'redux-form'; import { page4Submit } from '../actions/page_actions'; var TENURE = [ '0-12 months', '1-2 years', '2-5 years', '>5 years' ] class Page4 extends Component { onSubmit(e) { this.props.page4Submit(e); } render() { const {fields: {tenure, daysPerMonth}, handleSubmit} = this.props; return( <div className="container"> <div className="row"> <div className="col-md-12"> <div className="well bs-component"> <fieldset> <legend>Question 4: Are you?</legend> <div className="col-md-8 offset-xs-2"> <form className="form" onSubmit={handleSubmit((e) => this.onSubmit(e))}> {TENURE.map((e) => { return ( <div className="form-check"> <label className="form-check-label"> <input {...tenure} className="form-check-input" type="radio" value={e} /> { e } </label> </div> ) })} {tenure.touched && tenure.error && <div className="form-control-feedback">{tenure.error}</div>} <button type="submit" className="btn btn-primary">Next</button> </form> </div> </fieldset> </div> </div> </div> </div> ) } } function validate(formProps) { const errors = {}; if (!formProps.tenure) { errors.tenure = 'Please select a choice'; } return errors; } export default reduxForm({ form: 'Page4', fields: ['tenure', 'daysPerMonth'], validate }, null, { page4Submit })(Page4); <file_sep>var express = require('express'); var app = express(); var index = require('./routes/index'); app.use('/bin', express.static('./bin')); app.use('/stylesheets', express.static('./public/stylesheets')); app.use('/*', index); app.listen(3001, function () { console.log('Hello World listening on port 3001!'); }); <file_sep>import React, { Component } from 'react'; import { reduxForm } from 'redux-form'; import { page16Submit } from '../actions/page_actions'; class page16 extends Component { onSubmit(e) { this.props.page16Submit(e); } render() { const {fields: { one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen,fifteen,sixteen }, handleSubmit} = this.props; var questions = [ { id: this.props.fields.one, one: 'An allocated desk in an open plan setting', two: 'An unassigned desk, with access to quiet space for focused work'}, { id: this.props.fields.two, one: 'A shared desk in a shared office', two: 'An unassigned desk, with access to quiet space for focused work'}, { id: this.props.fields.three, one: 'An shared desk in an open plan setting', two: 'An unassigned desk, with access to quiet space for focused work'}, { id: this.props.fields.four, one: 'An allocated desk with access to multifunctional meeting space (e.g., village green)', two: 'An unassigned desk, with access to single purpose meeting space (closed rooms, white boards, access to VC)'}, { id: this.props.fields.five, one: 'An allocated desk in an open plan setting', two: 'An unassigned desk with access to private space for phone calls and VC'}, { id: this.props.fields.six, one: 'An allocated desk in an open plan setting but no defined social space', two: 'An unassigned desk with access to social space'}, { id: this.props.fields.seven, one: 'An allocated desk, among people you do not usually work with or interact with', two: 'An unassigned desk close to your team or peers'}, { id: this.props.fields.eight, one: 'Space in a shared closed office, with access to multifunctional meeting space (e.g., village green)', two: 'Space in an open plan setting with access to single purpose meeting space (closed rooms, white boards, access to VC)'}, { id: this.props.fields.nine, one: 'Space in a shared closed office, without access to alternative closed spaces for phone calls/ private conversations', two: 'Space in an open plan environment with access to private space for phone calls and VC'}, { id: this.props.fields.ten, one: 'Space in a shared closed office but no defined social space', two: 'Space in an open plan environment with access to social space'}, { id: this.props.fields.eleven, one: 'Space in a shared closed office among people you do not usually work with or interact with', two: 'Space in an open plan environment close to your team or peers'}, { id: this.props.fields.twelve, one: 'Access to single purpose meeting space but no alternative closed spaces for phone calls/ private conversations', two: 'Access to multifunctional meetings space (e.g., village green) and closed space for making phone calls/ private conversations'}, { id: this.props.fields.thirteen, one: 'Access to single purpose meeting space but no defined social space', two: 'Access to multifunctional meetings space (e.g., village green) which can be used as both a meeting and social space'}, { id: this.props.fields.fourteen, one: 'Access to single purpose meeting space but no facility to sit close to your peers or team', two: 'Access to multifunctional meetings space (e.g., village green) and the ability to sit close to your peers or team'}, { id: this.props.fields.fifteen, one: 'Access to closed space for phone calls/private conversations and VC but no defined social space', two: 'Access to defined social space but no closed space for phone calls/private conversations or VC'}, { id: this.props.fields.sixteen, one: 'Access to defined social space but no facility to sit close to your peers or team', two: 'The ability to sit close to your team but no access to defined social space'} ] return( <div className="container"> <div className="row"> <div className="col-md-12"> <div className="well bs-component"> <fieldset> <legend>Question 16</legend> <div className="col-md-8 offset-xs-2"> <h4 style={{ marginBottom: '20px' }} >In designing the new office, we need to make a number of trade-offs. This section helps us understand what is most important to you.</h4> <form className="form" onSubmit={handleSubmit((e) => this.onSubmit(e))}> {questions.map((e) => { if(e.id){ return( <div> <h4>Would you prefer</h4> <div className="form-check"> <label className="form-check-label"> <input {...e.id} className="form-check-input" type="radio" value={e.one} /> { e.one } </label> </div> <div className="form-check"> <label className="form-check-label"> <input {...e.id} className="form-check-input" type="radio" value={e.two} /> { e.two } </label> </div> </div> ) } })} <button type="submit" className="btn btn-primary">Next</button> </form> </div> </fieldset> </div> </div> </div> </div> ) } } function validate(formProps) { const errors = {}; return errors; } export default reduxForm({ form: 'page16', fields: [ 'one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen' ], validate }, null, { page16Submit })(page16); <file_sep>import React from 'react'; import { Route, IndexRoute, Router, browserHistory } from 'react-router'; import require_email from './containers/require_email'; import Header from './components/header'; import Intro from './containers/intro'; import Page1 from './containers/page1'; import Page2 from './containers/page2'; import Page3 from './containers/page3'; import Page4 from './containers/page4'; import Page5 from './containers/page5'; import Page6 from './containers/page6'; import Page7 from './containers/page7'; import Page8 from './containers/page8'; import Page9 from './containers/page9'; import Page10 from './containers/page10'; import Page11 from './containers/page11'; import Page12 from './containers/page12'; import Page13 from './containers/page13'; import Page14 from './containers/page14'; import Page15 from './containers/page15'; import Page16 from './containers/page16'; import Page17 from './containers/page17'; import Page18 from './containers/page18'; import Page19 from './containers/page19'; import Page20 from './containers/page20'; import Page21 from './containers/page21'; import Finish from './containers/finish'; export default ( <Router history={ browserHistory } > <Route path="/" component={Header}> <IndexRoute component={Intro} /> <Route path="/page1" component={require_email(Page1)} /> <Route path="/Page2" component={require_email(Page2)} /> <Route path="/Page3" component={require_email(Page3)} /> <Route path="/Page4" component={require_email(Page4)} /> <Route path="/Page5" component={require_email(Page5)} /> <Route path="/Page6" component={require_email(Page6)} /> <Route path="/Page7" component={require_email(Page7)} /> <Route path="/Page8" component={require_email(Page8)} /> <Route path="/Page9" component={require_email(Page9)} /> <Route path="/Page10" component={require_email(Page10)} /> <Route path="/Page11" component={require_email(Page11)} /> <Route path="/Page12" component={require_email(Page12)} /> <Route path="/Page13" component={require_email(Page13)} /> <Route path="/Page14" component={require_email(Page14)} /> <Route path="/Page15" component={require_email(Page15)} /> <Route path="/Page16" component={require_email(Page16)} /> <Route path="/Page17" component={require_email(Page17)} /> <Route path="/Page18" component={require_email(Page18)} /> <Route path="/Page19" component={require_email(Page19)} /> <Route path="/Page20" component={Page20} /> <Route path="/Page21" component={Page21} /> <Route path="/finish" component={Finish} /> </Route> </Router> ) <file_sep>import React, { Component } from 'react'; import { Link } from 'react-router'; class Header extends Component { render(){ return( <div> <div className="container-fluid customTop"> <h1 className="text-xs-center">London Office Design for the Future</h1> </div> { this.props.children } <nav aria-label="Page navigation" style={{ textAlign: 'center' }}> <ul className="pagination"> <li className="page-item"><Link className="page-link" to={'/page1'}>1</Link></li> <li className="page-item"><Link className="page-link" to={'/page2'}>2</Link></li> <li className="page-item"><Link className="page-link" to={'/page3'}>3</Link></li> <li className="page-item"><Link className="page-link" to={'/page4'}>4</Link></li> <li className="page-item"><Link className="page-link" to={'/page5'}>5</Link></li> <li className="page-item"><Link className="page-link" to={'/page6'}>6</Link></li> <li className="page-item"><Link className="page-link" to={'/page7'}>7</Link></li> <li className="page-item"><Link className="page-link" to={'/page8'}>8</Link></li> <li className="page-item"><Link className="page-link" to={'/page9'}>9</Link></li> <li className="page-item"><Link className="page-link" to={'/page10'}>10</Link></li> <li className="page-item"><Link className="page-link" to={'/page11'}>11</Link></li> <li className="page-item"><Link className="page-link" to={'/page12'}>12</Link></li> <li className="page-item"><Link className="page-link" to={'/page13'}>13</Link></li> <li className="page-item"><Link className="page-link" to={'/page14'}>14</Link></li> <li className="page-item"><Link className="page-link" to={'/page15'}>15</Link></li> <li className="page-item"><Link className="page-link" to={'/page16'}>16</Link></li> <li className="page-item"><Link className="page-link" to={'/page17'}>17</Link></li> <li className="page-item"><Link className="page-link" to={'/page18'}>18</Link></li> <li className="page-item"><Link className="page-link" to={'/page19'}>19</Link></li> </ul> </nav> </div> ) } } export default Header; <file_sep># survey-mc-react <file_sep>import React, { Component } from 'react'; import { reduxForm } from 'redux-form'; import { page13Submit } from '../actions/page_actions'; var Rcslider = require('rc-slider'); class page13 extends Component { constructor(props) { super(props); this.state = { RCValue: 0 } } onSubmit(e) { this.props.page13Submit({ proportionOfMeetings: this.state.RCValue}); } render() { const {fields: {whatAreYou}, handleSubmit} = this.props; return( <div className="container"> <div className="row"> <div className="col-md-12"> <div className="well bs-component"> <fieldset> <legend>Question 13: How do you currently use the office?</legend> <div className="col-md-8 offset-xs-2"> <h4 style={{ marginBottom: 20 }}>What proportion of your client meetings are:</h4> <h5 style={{color: 'skyblue', marginBottom: 20}}>Formal meetings or workshops<span style={{color: '#b2b2b2'}} > | Informal working sessions</span></h5> <Rcslider onChange={(e) => this.setState({ RCValue: e })} /> <h4 style={{ marginTop: '1em' }}>{ `${this.state.RCValue}%` }</h4> <div style={{ marginTop: 20 }} className="col-md-12"> <button onClick={(e) => this.onSubmit(e)} className="btn btn-primary">Next</button> </div> </div> </fieldset> </div> </div> </div> </div> ) } } function validate(formProps) { const errors = {}; if (!formProps.whatAreYou) { errors.whatAreYou = 'Please select a choice'; } return errors; } export default reduxForm({ form: 'page13', fields: ['whatAreYou'], validate }, null, { page13Submit })(page13); <file_sep>import React, { Component } from 'react'; import { reduxForm } from 'redux-form'; import { browserHistory } from 'react-router'; import axios from 'axios'; import crypto from 'crypto'; import { page19Submit } from '../actions/page_actions' class page19 extends Component { constructor(props){ super(props); this.state = { loading: false, submitted: false } } onSubmit(e) { this.setState({ loading:true }); crypto.randomBytes(5, (err, buf) => { if (err) { }else { var userRandomNumber = buf.toString('hex'); const userDataurl = `https://survey-6242b.firebaseio.com/userData.json`; const usersurl = `https://survey-6242b.firebaseio.com/users.json`; var email = this.props.pageData.credentials.email; var users = { [userRandomNumber]: email }; var userData = { [userRandomNumber]: this.props.pageData }; axios.patch(usersurl, users) .then((response) => { axios.patch(userDataurl, userData) .then((response) => { if(response.status == "200"){ this.props.page19Submit(); browserHistory.push('/finish'); } }) .catch((response) => { this.setState({ loading: false, submitted: false }); }) }) .catch((response) => { this.setState({ loading: false, submitted: false }); }) } }) } renderFinish() { if(this.state.loading) { return ( <button type="submit" className="btn btn-primary" disabled>loading...</button> ) }else { return ( <button type="submit" className="btn btn-primary">Finish &amp; Submit</button> ) } } render() { const {fields: {role, specificDetails}, handleSubmit} = this.props; return( <div className="container"> <div className="row"> <div className="col-md-12"> <div className="well bs-component"> <fieldset> <legend>Finish Survey</legend> <div className="col-md-8 offset-xs-2"> <form className="form" onSubmit={handleSubmit((e) => this.onSubmit(e))}> { this.renderFinish() } </form> </div> </fieldset> </div> </div> </div> </div> ) } } function mapStateToProps(state) { return { pageData: state.pageReducers } } export default reduxForm({ form: 'page19', fields: ['role', 'specificDetails'] }, mapStateToProps, { page19Submit })(page19); <file_sep>import React, { Component } from 'react'; import { reduxForm } from 'redux-form'; import { page3Submit } from '../actions/page_actions'; import { browserHistory } from 'react-router'; var CSS = ['Senior Partner', 'Partner', 'AP', 'EM', 'Associate/JA', 'BA']; var Non_CSS = ['Manager/Team leader', 'Team member', 'Other']; class Page3 extends Component { onSubmit(e) { this.props.page3Submit(e); } render() { var roleMap = []; if(!browserHistory){ return <div>Loading...</div> }else if(!this.props.pageData.page1) { browserHistory.push("/page1"); }else if(this.props.pageData.page1.whatAreYou == "CSS") { roleMap = CSS; }else { roleMap = Non_CSS } const {fields: {role, specificDetails}, handleSubmit} = this.props; return( <div className="container"> <div className="row"> <div className="col-md-12"> <div className="well bs-component"> <fieldset> <legend>Question 3: What is your role?</legend> <div className="col-md-8 offset-xs-2"> <form className="form" onSubmit={handleSubmit((e) => this.onSubmit(e))}> {roleMap.map((e) => { return ( <div className="form-check"> <label className="form-check-label"> <input {...role} className="form-check-input" type="radio" value={e} /> { e } </label> </div> ) })} { role.value == "Other" ? <div className="form-group"><label>Please specify</label><textarea className="form-control" rows="3" { ...specificDetails }></textarea></div> : <div></div> } {role.touched && role.error && <div className="form-control-feedback">{role.error}</div>} {specificDetails.touched && specificDetails.error && <div className="form-control-feedback">{specificDetails.error}</div>} <button type="submit" className="btn btn-primary">Next</button> </form> </div> </fieldset> </div> </div> </div> </div> ) } } function validate(formProps) { const errors = {}; if (!formProps.role) { errors.role = 'Please select a choice'; } if(!formProps.specificDetails){ if(formProps.role == "Other"){ errors.specificDetails = "Please specify in Other"; } } return errors; } function mapStateToProps(state) { return { pageData: state.pageReducers } } export default reduxForm({ form: 'Page3', fields: ['role', 'specificDetails'], validate }, mapStateToProps, { page3Submit })(Page3); <file_sep>import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { reduxForm } from 'redux-form'; import { page12Submit } from '../actions/page_actions'; import $ from 'jquery'; class Page12 extends Component { constructor(props) { super(props); this.state = { totalDragged: 0 } } componentDidMount() { var node1 = ReactDOM.findDOMNode(this.refs.sortable1); var node2 = ReactDOM.findDOMNode(this.refs.sortable2); } onSubmit(e) { var most = $(document.getElementById('most')).children()[0].id; var more = $(document.getElementById('more')).children()[0].id; var last = $(document.getElementById('last')).children()[0].id; var least = $(document.getElementById('least')).children()[0].id; var props = { most: most, more: more, last: last, least: least } this.props.page12Submit(props); } drop(ev) { if(ev.target.id != "most" && ev.target.id != "more" && ev.target.id != "last" && ev.target.id != "least") { return; } var data = ev.dataTransfer.getData("text"); var node = document.getElementById(data); var clonedNode = document.getElementById(data).cloneNode(true); $(clonedNode).removeClass('col-md-offset-1'); $(clonedNode).removeClass('col-md-10'); $(clonedNode).addClass('col-md-12'); $(clonedNode).on('dragend', function (e) { this.remove(); }) ev.target.appendChild(clonedNode); } drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } allowDrop(ev) { ev.preventDefault(); } render() { const {fields: {whatAreYou}, handleSubmit} = this.props; return( <div className="container"> <div className="row"> <div className="col-md-12"> <div className="well bs-component"> <fieldset> <legend>Question 12: How do you currently use the office?</legend> <div className="col-md-8 offset-xs-2"> <h5>Who do you most meet informally? (In order of most at the top)</h5> <div className="col-md-4"> <div className="col-md-offset-1 col-md-10" style={{ backgroundColor: 'white', height: '3em', marginBottom: '1em', paddingTop: '0.7em', color: 'white', borderRadius: '5px', textAlign: 'center' }}></div> <div id="team" draggable="true" onDragStart={(e) => this.drag(e)} className="col-md-offset-1 col-md-10" style={{ backgroundColor: '#0062c4', height: '3em', marginBottom: '1em', paddingTop: '0.7em', color: 'white', borderRadius: '5px', textAlign: 'center' }}> My team </div> <div id="cohort" draggable="true" onDragStart={(e) => this.drag(e)} className="col-md-offset-1 col-md-10" style={{ backgroundColor: '#ff8900', height: '3em', marginBottom: '1em', paddingTop: '0.7em', color: 'white', borderRadius: '5px', textAlign: 'center' }}> My cohort </div> <div id="practice" draggable="true" onDragStart={(e) => this.drag(e)} className="col-md-offset-1 col-md-10" style={{ backgroundColor: '#1d7e00', height: '3em', marginBottom: '1em', paddingTop: '0.7em', color: 'white', borderRadius: '5px', textAlign: 'center' }}> My practice </div> <div id="others" draggable="true" onDragStart={(e) => this.drag(e)} className="col-md-offset-1 col-md-10" style={{ backgroundColor: '#c40000', height: '3em', marginBottom: '1em', paddingTop: '0.7em', color: 'white', borderRadius: '5px', textAlign: 'center' }}> Others </div> </div> <div className="col-md-8" style={{ height: '3em', float: 'right', marginBottom: '1em' }}> <h4 style={{ textAlign: 'center', marginTop: 10}}>Most</h4> </div> <div id="most" onDrop={(e) => this.drop(e)} onDragOver={(e) => this.allowDrop(e)} className="col-md-8" style={{ border: "1px solid grey", height: '3em', float: 'right', marginBottom: '1em' }}> </div> <div id="more" onDrop={(e) => this.drop(e)} onDragOver={(e) => this.allowDrop(e)} className="col-md-8" style={{ border: "1px solid grey", height: '3em', float: 'right', marginBottom: '1em' }}> </div> <div id="last" onDrop={(e) => this.drop(e)} onDragOver={(e) => this.allowDrop(e)} className="col-md-8" style={{ border: "1px solid grey", height: '3em', float: 'right', marginBottom: '1em' }}> </div> <div id="least" onDrop={(e) => this.drop(e)} onDragOver={(e) => this.allowDrop(e)} className="col-md-8" style={{ border: "1px solid grey", height: '3em', float: 'right', marginBottom: '1em' }}> </div> <div className="col-md-8" style={{ height: '3em', float: 'right', marginBottom: '1em' }}> <h4 style={{ textAlign: 'center', marginTop: 10 }}>Least</h4> </div> <div className="col-md-12"> <button onClick={(e) => this.onSubmit(e)} className="btn btn-primary">Next</button> </div> </div> </fieldset> </div> </div> </div> </div> ) } } function validate(formProps) { const errors = {}; if (!formProps.whatAreYou) { errors.whatAreYou = 'Please select a choice'; } return errors; } export default reduxForm({ form: 'Page1', fields: ['whatAreYou'], validate }, null, { page12Submit })(Page12); <file_sep>import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { reduxForm } from 'redux-form'; import { page10Submit } from '../actions/page_actions'; import $ from 'jquery'; class Page10 extends Component { constructor(props) { super(props); this.state = { totalDragged: 0 } } onSubmit(e) { var planExChildrens = $(document.getElementById('planEx')).children(); var FeDevChildrens = $(document.getElementById('FeDev')).children(); var CrProChildrens = $(document.getElementById('CrPro')).children(); var planEx = 0; var FeDev = 0; var CrPro = 0; planExChildrens.map((e) => { if(planExChildrens[e].id == "0.5h"){ planEx += 0.5; }else if(planExChildrens[e].id == "1h") { planEx++; } }) FeDevChildrens.map((e) => { if(FeDevChildrens[e].id == "0.5h"){ FeDev += 0.5; }else if(FeDevChildrens[e].id == "1h") { FeDev++; } }) CrProChildrens.map((e) => { if(CrProChildrens[e].id == "0.5h"){ CrPro += 0.5; }else if(CrProChildrens[e].id == "1h") { CrPro++; } }) var props = { planEx: planEx, FeDev: FeDev, CrPro: CrPro } this.props.page10Submit(props); } drop(ev) { if(ev.target.id != "planEx" && ev.target.id != "FeDev" && ev.target.id != "CrPro") { return; } var data = ev.dataTransfer.getData("text"); var clonedNode = document.getElementById(data).cloneNode(true); $(clonedNode).removeClass('col-md-4'); $(clonedNode).addClass('col-md-12'); $(clonedNode).on('dragend', function (e) { this.remove(); }) if(this.state.totalDragged < 8) { ev.target.appendChild(clonedNode); } var droppedHole = document.getElementById('droppedHours'); this.setState({ totalDragged: $(droppedHole).children().length }) } drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } allowDrop(ev) { ev.preventDefault(); } render() { const {fields: {whatAreYou}, handleSubmit} = this.props; return( <div className="container"> <div className="row"> <div className="col-md-12"> <div className="well bs-component"> <fieldset> <legend>Question 10: How do you currently use the office?</legend> <div className="col-md-8 offset-xs-2"> <h5>What proportion of your meetings are:</h5> <div id="planEx" onDrop={(e) => this.drop(e)} onDragOver={(e) => this.allowDrop(e)} className="col-md-4" style={{ minHeight: '50vh', paddingBottom: '6em' }}> <div className="col-md-12" style={{ height: '3em', textAlign: 'center', paddingTop: '7px' , backgroundColor: 'skyblue', borderRadius: '5px', marginBottom: '1em' }}> <h6 className="text-xs-center">Planning/execution discussions</h6> </div> </div> <div id="FeDev" onDrop={(e) => this.drop(e)} onDragOver={(e) => this.allowDrop(e)} className="col-md-4" style={{ minHeight: '50vh', paddingBottom: '6em' }}> <div className="col-md-12" style={{ height: '3em', textAlign: 'center', paddingTop: '7px' , backgroundColor: 'skyblue', borderRadius: '5px', marginBottom: '1em' }}> <h6 className="text-xs-center">Feedback/development discussions</h6> </div> </div> <div id="CrPro" onDrop={(e) => this.drop(e)} onDragOver={(e) => this.allowDrop(e)} className="col-md-4" style={{ minHeight: '50vh', paddingBottom: '6em' }}> <div className="col-md-12" style={{ height: '3em', textAlign: 'center', paddingTop: '7px' , backgroundColor: 'skyblue', borderRadius: '5px', marginBottom: '1em' }}> <h6 className="text-xs-center">Creative/problem solving discussions</h6> </div> </div> <div className="col-md-12"> <div id="0.5h" draggable="true" onDragStart={(e) => this.drag(e)} className="col-md-4" style={{ backgroundColor: '#0062c4', height: '3em', marginBottom: '1em', paddingTop: '0.7em', color: 'white', borderRadius: '5px', textAlign: 'center', marginRight: '2em' }}> 1/2hr </div> <div id="1h" draggable="true" onDragStart={(e) => this.drag(e)} className="col-md-offset-1 col-md-4" style={{ backgroundColor: '#ff9300', height: '3em', marginBottom: '1em', paddingTop: '0.7em', color: 'white', borderRadius: '5px', textAlign: 'center' }}> 1hr </div> </div> <div className="col-md-12"> <button onClick={(e) => this.onSubmit(e)} className="btn btn-primary">Next</button> </div> </div> </fieldset> </div> </div> </div> </div> ) } } function validate(formProps) { const errors = {}; if (!formProps.whatAreYou) { errors.whatAreYou = 'Please select a choice'; } return errors; } export default reduxForm({ form: 'Page10', fields: ['whatAreYou'], validate }, null, { page10Submit })(Page10); <file_sep>import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { reduxForm } from 'redux-form'; import { page7Submit } from '../actions/page_actions'; import $ from 'jquery'; class Page7 extends Component { constructor(props) { super(props); this.state = { totalDragged: 0 } } componentDidMount() { var node1 = ReactDOM.findDOMNode(this.refs.sortable1); var node2 = ReactDOM.findDOMNode(this.refs.sortable2); } onSubmit(e) { var droppedHole = document.getElementById('droppedHours'); var childrens = $(droppedHole).children(); var IW = 0; var FM = 0; var SO = 0; var CL = 0; childrens.map((e) => { if(childrens[e].id == "1hIW"){ IW++; }else if(childrens[e].id == "1hFM") { FM++; }else if(childrens[e].id == "1hSO") { SO++; }else if(childrens[e].id == "1hCL") { CL++; } }) var props = { IW: IW, FM: FM, SO: SO, CL: CL } this.props.page7Submit(props); } drop(ev) { if(ev.target.id != "droppedHours") { return; } var data = ev.dataTransfer.getData("text"); var clonedNode = document.getElementById(data).cloneNode(true); $(clonedNode).addClass('cardBottom'); $(clonedNode).on('dragend', function (e) { this.remove(); }) if(this.state.totalDragged < 20) { ev.target.appendChild(clonedNode); } var droppedHole = document.getElementById('droppedHours'); this.setState({ totalDragged: $(droppedHole).children().length }) } drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } allowDrop(ev) { ev.preventDefault(); } render() { const {fields: {whatAreYou}, handleSubmit} = this.props; return( <div className="container"> <div className="row"> <div className="col-md-12"> <div className="well bs-component"> <fieldset> <legend>Question 7: How do you currently use the office?</legend> <div className="col-md-12"> <h5>Proportion of time spent on:</h5> <div className="col-md-4"> <div id="1hIW" draggable="true" onDragStart={(e) => this.drag(e)} className="col-md-offset-1 col-md-10" style={{ backgroundColor: '#0062c4', height: '3em', marginBottom: '1em', paddingTop: '0.7em', color: 'white', borderRadius: '5px', textAlign: 'center' }}> 1hr Individual Work </div> <div id="1hFM" draggable="true" onDragStart={(e) => this.drag(e)} className="col-md-offset-1 col-md-10" style={{ backgroundColor: '#ff8900', height: '3em', marginBottom: '1em', paddingTop: '0.7em', color: 'white', borderRadius: '5px', textAlign: 'center' }}> 1hr Formal Meetings </div> <div id="1hSO" draggable="true" onDragStart={(e) => this.drag(e)} className="col-md-offset-1 col-md-10" style={{ backgroundColor: '#1d7e00', height: '3em', marginBottom: '1em', paddingTop: '0.7em', color: 'white', borderRadius: '5px', textAlign: 'center' }}> 1hr Social </div> <div id="1hCL" draggable="true" onDragStart={(e) => this.drag(e)} className="col-md-offset-1 col-md-10" style={{ backgroundColor: '#c40000', height: '3em', marginBottom: '1em', paddingTop: '0.7em', color: 'white', borderRadius: '5px', textAlign: 'center' }}> 1hr Clients </div> </div> <div className="col-md-4"> <h5 style={{ textAlign: 'left' }}>Start of the day</h5> </div> <div id="droppedHours" onDrop={(e) => this.drop(e)} onDragOver={(e) => this.allowDrop(e)} className="col-md-8" style={{ borderLeft: "10px solid grey", borderBottom: "10px solid grey", minHeight: '65vh', paddingBottom: '4em'}}> </div> <div className="col-md-12"> <button onClick={(e) => this.onSubmit(e)} className="btn btn-primary">Next</button> </div> </div> </fieldset> </div> </div> </div> </div> ) } } function validate(formProps) { const errors = {}; if (!formProps.whatAreYou) { errors.whatAreYou = 'Please select a choice'; } return errors; } export default reduxForm({ form: 'Page1', fields: ['whatAreYou'], validate }, null, { page7Submit })(Page7); <file_sep>import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { reduxForm } from 'redux-form'; import { page8Submit } from '../actions/page_actions'; import $ from 'jquery'; class Page8 extends Component { constructor(props) { super(props); this.state = { totalDragged: 0 } } onSubmit(e) { var remoteMeetingsChildrens = $(document.getElementById('remoteMeetings')).children(); var inPersonChildrens = $(document.getElementById('inPerson')).children(); var formalEventsChildrens = $(document.getElementById('formalEvents')).children(); var remoteMeetings = 0; var inPerson = 0; var formalEvents = 0; remoteMeetingsChildrens.map((e) => { if(remoteMeetingsChildrens[e].id == "0.5h"){ remoteMeetings += 0.5; }else if(remoteMeetingsChildrens[e].id == "1h") { remoteMeetings++; } }) inPersonChildrens.map((e) => { if(inPersonChildrens[e].id == "0.5h"){ inPerson += 0.5; }else if(inPersonChildrens[e].id == "1h") { inPerson++; } }) formalEventsChildrens.map((e) => { if(formalEventsChildrens[e].id == "0.5h"){ formalEvents += 0.5; }else if(formalEventsChildrens[e].id == "1h") { formalEvents++; } }) var props = { remoteMeetings: remoteMeetings, inPerson: inPerson, formalEvents: formalEvents } this.props.page8Submit(props); } drop(ev) { if(ev.target.id != "remoteMeetings" && ev.target.id != "inPerson" && ev.target.id != "formalEvents") { return; } var data = ev.dataTransfer.getData("text"); var clonedNode = document.getElementById(data).cloneNode(true); $(clonedNode).removeClass('col-md-4'); $(clonedNode).addClass('col-md-12'); $(clonedNode).on('dragend', function (e) { this.remove(); }) if(this.state.totalDragged < 8) { ev.target.appendChild(clonedNode); } var droppedHole = document.getElementById('droppedHours'); this.setState({ totalDragged: $(droppedHole).children().length }) } drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } allowDrop(ev) { ev.preventDefault(); } deleteDropped(ev) { var data = ev.dataTransfer.getData("text"); var Node = document.getElementById(data); } render() { const {fields: {whatAreYou}, handleSubmit} = this.props; return( <div className="container"> <div className="row"> <div className="col-md-12"> <div className="well bs-component"> <fieldset> <legend>Question 8: How do you currently use the office?</legend> <div className="col-md-8 offset-xs-2"> <h5>Of the time you spend collaborating with colleagues in formal meetings, what proportion of this is:</h5> <div id="remoteMeetings" onDrop={(e) => this.drop(e)} onDragOver={(e) => this.allowDrop(e)} className="col-md-4" style={{ minHeight: '50vh', paddingBottom: '5em' }}> <div className="col-md-12" style={{ height: '2em', textAlign: 'center', paddingTop: '7px' , backgroundColor: 'skyblue', borderRadius: '5px', marginBottom: '1em' }}> Remote Meeting </div> </div> <div id="inPerson" onDrop={(e) => this.drop(e)} onDragOver={(e) => this.allowDrop(e)} className="col-md-4" style={{ minHeight: '50vh', paddingBottom: '5em' }}> <div className="col-md-12" style={{ height: '2em', textAlign: 'center', paddingTop: '7px' , backgroundColor: 'skyblue', borderRadius: '5px', marginBottom: '1em' }}> In person </div> </div> <div id="formalEvents" onDrop={(e) => this.drop(e)} onDragOver={(e) => this.allowDrop(e)} className="col-md-4" style={{ minHeight: '50vh', paddingBottom: '5em' }}> <div className="col-md-12" style={{ height: '2em', textAlign: 'center', paddingTop: '7px' , backgroundColor: 'skyblue', borderRadius: '5px', marginBottom: '1em' }}> Formal events </div> </div> <div className="col-md-12"> <div id="0.5h" draggable="true" onDragStart={(e) => this.drag(e)} className="col-md-4" style={{ backgroundColor: '#0062c4', height: '3em', marginBottom: '1em', paddingTop: '0.7em', color: 'white', borderRadius: '5px', textAlign: 'center', marginRight: '2em' }}> 1/2hr </div> <div id="1h" draggable="true" onDragStart={(e) => this.drag(e)} className="col-md-offset-1 col-md-4" style={{ backgroundColor: '#ff9300', height: '3em', marginBottom: '1em', paddingTop: '0.7em', color: 'white', borderRadius: '5px', textAlign: 'center' }}> 1hr </div> </div> <div className="col-md-12"> <button onClick={(e) => this.onSubmit(e)} className="btn btn-primary">Next</button> </div> </div> </fieldset> </div> </div> </div> </div> ) } } function validate(formProps) { const errors = {}; if (!formProps.whatAreYou) { errors.whatAreYou = 'Please select a choice'; } return errors; } export default reduxForm({ form: 'Page1', fields: ['whatAreYou'], validate }, null, { page8Submit })(Page8);
6a44ba824f594ee03688d3db830cb7938b95e7ac
[ "JavaScript", "Markdown" ]
20
JavaScript
tahnik/survey-mc-react
727188127155e788cccf14cff6812dd611706729
bbe50b4bf41198fa8df4a587d20796f65ef018e4
refs/heads/master
<file_sep>package com.mycompany.tests; import com.mycompany.JacocoExampleApplication; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import static org.junit.jupiter.api.Assertions.assertTrue; @SpringBootTest( classes = JacocoExampleApplication.class) public class CustomerTestIT { @Test public void CustomerControllerHelloTest(){ assertTrue(1==1); } } <file_sep># jacoco-example Multi module jacoco example.
d54d3c42d6556d712f07c0c796c6e322b3a216e9
[ "Markdown", "Java" ]
2
Java
ivanape/jacoco-example
bf02a5dc370d8036a659c68018236576fc84fbfa
3265e445f91c79378c08754b0f21f5314d9081bb
refs/heads/master
<file_sep>namespace SelectAllSample { using System.Windows; using System.Windows.Controls; using System.Windows.Input; public partial class MainWindow : Window { public MainWindow() { this.InitializeComponent(); } private void OnSelectAllExecuted(object sender, ExecutedRoutedEventArgs e) { if (e.Source is ListBox listBox) { listBox.SelectAll(); } } } }
203f7075c16f5da5c1d70d323e458ef8848a34cb
[ "C#" ]
1
C#
JohanLarsson/SelectAllSample
6baa880730e06cc0b5a5f1d982308c427ce630f9
207c647ef6af43362908e2f83c9c7250b1da9465
refs/heads/main
<file_sep>SECRET_KEY="sdasasdsdasdaasdsd" HOST="localhost" PORT=27017 EMAIL_HOST="smtp.your_smtp.com" EMAIL_PORT= EMAIL_USER="your user" EMAIL_PASS="<PASSWORD>" EMAIL_FROM="Your Name <<EMAIL>>" COOKIE_PARSER_KEY="um texto qualquer"<file_sep><div align="center"> <img height="30" alt="NodeJs" src="https://img.shields.io/badge/Node.js-43853D?style=for-the-badge&logo=node.js&logoColor=white"> <img height="30" alt="ExpressJs" src="https://img.shields.io/badge/Express.js-404D59?style=for-the-badge"> <img height="30" alt="MongoDb" src="https://img.shields.io/badge/MongoDB-4EA94B?style=for-the-badge&logo=mongodb&logoColor=white"> <img height="30" alt="Javascript" src="https://img.shields.io/badge/JavaScript-F7DF1E?style=for-the-badge&logo=javascript&logoColor=black"> <img height="30" alt="css3" src="https://img.shields.io/badge/CSS3-1572B6?style=for-the-badge&logo=css3&logoColor=white"> <img height="30" alt="html5" src="https://img.shields.io/badge/HTML5-E34F26?style=for-the-badge&logo=html5&logoColor=white"> </div> <h3 align="center">Sistema de agendamento</h3> ![Tela Principal](images/10.png) <p align="center"> Um sistema de agendamento simples. <br> </p> <h3>Informações gerais</h3> ![GitHub estrelas](https://img.shields.io/github/stars/gabrielogregorio/Sistema-de-Agendamento) ![GitHub last commit](https://img.shields.io/github/last-commit/gabrielogregorio/Sistema-de-Agendamento?style=flat-square) ![GitHub contributors](https://img.shields.io/github/contributors/gabrielogregorio/Sistema-de-Agendamento) ![GitHub language count](https://img.shields.io/github/languages/count/gabrielogregorio/Sistema-de-Agendamento) ![GitHub repo size](https://img.shields.io/github/repo-size/gabrielogregorio/Sistema-de-Agendamento) ### Introdução Este projeto se trata de um pequeno sistema de agendamentos com autenticação, onde um usuário pode fazer agendamento de consultas, pode ver os eventos através de um calendário e além disso, o sistema envia um e-mail aos clientes quando o agendamento está se aproximando. Esse sistema ainda está em desenvolvimento e conta com vários bugs, instabilidades e mensagens de erros que serão resolvidas ao longo do tempo. ## Configuração obrigatória A fim de manter as estatisticas do meu github fiéis a minha codificação, removi os arquivos do FullCalendar da pasta 'public/full', e neste novo repositório você precisa extrair o arquivo 'full.zip' na pasta raiz dentro da pasta public. ## Configurando o MongoDb (Windows 10) 1. Instale o mongodb na sua máquina 2. Configure o Path, provavelmente os binários estarão nesse caminho ```shell C:\Program Files\MongoDB\Server\5.0\bin ``` 3. Abra o prompt de comando como administrador e inicie o serviço do mongodb ``` net start mongodb ``` 4. acesse o mongo com o comando: ```shell mongo ``` 5. Estando tudo ok, você pode sair com o comando exit. 6. Para parar o serviço basta rodar o comando abaixo ```shell net stop mongodb ``` ## Configurando o mailtrap Por enquanto o sistema usa o site mailtrap para simular o envio de e-mail ### Senha do sistema por enquanto login: <EMAIL> senha: <PASSWORD> #### Inserção de cliente com mensagem de erro ![Inserir cliente](images/1.png) #### Listagem de clientes ![Visualização de clientes](images/2.png) #### Exclusão de cliente ![Excluir cliente](images/3.png) #### Edição de cliente ![Editar cliente](images/4.png) #### Inserção de consulta ![Inserir consulta](images/5.png) #### Conflito de consultas ![Conflito na inserção](images/6.png) #### Visualização de consulta ![Visualização de consultas](images/7.png) #### E-mail enviado a um usuário ![E-mail enviado](images/8.png) #### Listagem de consultas ![Lista de consultas](images/9.png) <file_sep>const validator = require('validator'); function validateName(name) { name = name.toString(); if (name.length <=2) { return {error: 'O nome não é válido!', value:''} } return {error: '', value:name} } function validateCpf(cpf) { if (cpf == undefined || cpf == '') { return {error: 'Você precisa informar um CPF válido!', value:''} } cpf = cpf.toString(); cpf = cpf.trim() cpf = cpf.replace('-', '').replace('.', '').replace('.', ''); if (cpf.length != 11) { return {error: 'O CPF não tem 11 digitos!', value:''} } return {error: '', value:cpf} } function validateEmail(email) { email = email.toString(); if(!validator.isEmail(email)) { return {error: 'E-mail é inválido!', value:''} } return {error: '', value:email} } module.exports = {validateCpf, validateName, validateEmail} <file_sep>const mongoose = require('mongoose'); var Schema = mongoose.Schema; const clientSchema = new mongoose.Schema({ name: String, email: String, cpf: String, consultations: { type: Schema.Types.ObjectId, ref: 'Consultation' }, }, {collection: 'clients'}) var Client = mongoose.model('Client', clientSchema); module.exports = Client;<file_sep>const express = require('express'); const mailer = require('nodemailer'); const app = express() const mongoose = require('mongoose'); const session = require('express-session'); const adminAuth = require('./middlewares/adminAuth'); const clientController = require('./Client/ClientController') const consultationsController = require('./Consultation/ConsultationsController') const Consultation = require('./Consultation/Consultation'); var ConsultationsFactories = require('./factories/ConsultationsFactories'); const cookieParser = require('cookie-parser') const flash = require('express-flash'); const validator = require('validator'); require('dotenv/config'); app.use(express.json()) app.use(express.urlencoded({extended: false})) app.use(express.static('public')) app.use(cookieParser(process.env.COOKIE_PARSER_KEY)) app.set('view engine', 'ejs') app.use(session({ secret: process.env.SECRET_KEY, cookie: {maxAge: 1000 * 60 * 60 * 24 *30}, resave: true, saveUninitialized: true })) var host = process.env.HOST; var port = process.env.PORT; mongoose.connect(`mongodb://${host}:${port}/agendamentosdb`, {useNewUrlParser: true, useUnifiedTopology: true}) mongoose.set('useFindAndModify', false); app.use(flash()) app.use('/', consultationsController); app.use('/', clientController); app.get('/', adminAuth, (req, res) => { res.render('index'); }) app.get("/getcalendar", adminAuth, async (req, res) => { var appos = await Consultation.find({finished: false}).populate('client').sort({'_id': 'desc'}) var appointments = []; appos.forEach(appo => { if (appo.date != undefined) { appointments.push(ConsultationsFactories.Build(appo)) } }) res.json(appointments); }) app.get('/logoff', async (req, res) => { req.session.logged = false res.redirect('auth'); }) app.get('/auth', async (req, res) => { res.render('auth'); }) app.post('/auth', async (req, res) => { if (req.body.email == '<EMAIL>' && req.body.password == '<PASSWORD>') { req.session.logged = true res.redirect('/'); } else { res.redirect('/auth'); } }) async function getHour(time) { return await parseInt(time.split(':')[0]) } async function getMinute(time) { return await parseInt(time.split(':')[1]) } async function SendNotification() { // transporter para enviar o e-mail var transporter = mailer.createTransport({ host: process.env.EMAIL_HOST, port: process.env.EMAIL_PORT, auth: { user: process.env.EMAIL_USER, pass: <PASSWORD> } }) // Obter a data atual var dateNow = new Date(); // Dia, mes e ano atual para obter apenas consultas marcadas para hoje var dataYearMonthDayNow = new Date(dateNow.getFullYear(), dateNow.getMonth(), dateNow.getDate(), 0, 0, 0, 0); dataYearMonthDayNow.setUTCHours(0) // Busca no DB para obter somente consultas que não foram finalizadas e estão marcadas para hoje e não foram notificadas var consultations = await Consultation.find( { finished: false, date: dataYearMonthDayNow, notified:false } ).populate('client').sort({'_id': 'desc'}) // Loop por todas as consultas disponíveis hoje e que precisam ser notificadas consultations.forEach(async consultation => { // Separar a hora, minuto e segundo em datas para análise posterior var startHour = await getHour(consultation.timestart) var startMinute = await getMinute(consultation.timestart) var endHour = await getHour(consultation.timeend) var endMinute = await getMinute(consultation.timeend) // Obtendo as datas COM HORARIOS de inicio e fim da consulta. var dateStartAnalitic = new Date(dateNow.getFullYear(), dateNow.getMonth(), dateNow.getDate(), startHour, startMinute, 0, 0); var dateEndAnalitic = new Date(dateNow.getFullYear(), dateNow.getMonth(), dateNow.getDate(), endHour, endMinute, 0, 0); // Data de inicio e fim da consulta como número var timeStartConsultation = dateStartAnalitic.getTime(); var timeEndConsultation = dateEndAnalitic.getTime(); // 1 hora em milisegundos var hour = 1000 * 60 * 60; // Data de inicio da consulta - Data atual var gap = timeStartConsultation - Date.now(); // Daqui a 1h a consulta será iniciada if (gap <= hour) { console.log('Consulta em análise => ', consultation.id) // Cliente não foi excluido if (consultation.client != undefined) { // Notificação do cliente var notificar = true; var msg = ''; // Data atual é MAIOR ou IGUAL a data de inicio da consulta if (dateNow >= timeStartConsultation) { // Data atual é MAIOR ou IGUAL a data final da consulta if (dateNow >= timeEndConsultation) { // Não notificar usuário notificar = false; console.log('Consulta já finalizou e o usuário não foi avisado') } else { msg = 'Sua consulta ja iniciou!'; } } else { msg = 'Sua consulta vai iniciar'; } // Atendeu aos critério para notificar o usuário if (notificar) { // Atualiza no db que o usuário foi notificado! await Consultation.findByIdAndUpdate(consultation.id, {notified: true}); // Envio do e-mail ao cliente console.log(`Descrição: ${consultation.description}\nInicio: ${consultation.timestart}\nFim: ${consultation.timeend}\n`) transporter.sendMail({ from: process.env.EMAIL_FROM, to: consultation.client.email, subject: `${consultation.client.name} - ${msg}`, text: `Descrição: ${consultation.description}\nInicio: ${consultation.timestart}\nFim: ${consultation.timeend}\n` }).then(() => {}).catch(error => {console.log(error)}) } } else { console.log('Cliente foi excluido e portanto não será avisado!') } } }) } // Tasks interval. A cada x tempo verifica se uma consulta esta perto // e dispara um e-mail ao usuário. Isso é o pooling setInterval(async () => { await SendNotification(); }, 1000 * 60 * 5) // 1s * 60s => 1 min * 5 => 5 min app.listen(3333, () => { console.log('Server is running'); }) <file_sep>const mongoose = require('mongoose'); var Schema = mongoose.Schema; const consultationsSchema = new mongoose.Schema({ client: { type: Schema.Types.ObjectId, ref: 'Client' }, description: String, date: Date, timestart: String, timeend: String, finished: Boolean, notified: Boolean, }, {collection: 'consultations'}) var Consultation = mongoose.model('Consultation', consultationsSchema); module.exports = Consultation;
144bb4a1293770def7e301dd690363427cac9fbd
[ "Markdown", "JavaScript", "Shell" ]
6
Shell
gabrielogregorio/Sistema-de-Agendamento
5417c71f0cdd30d380e445269034166d845ccdaf
311dde3a7c0a6f073d5c77e7d76a0c9c8a35ab0c
refs/heads/master
<repo_name>ascherkus/iheartvideo<file_sep>/README.markdown iheartvideo =========== Super simple HTML5 audio/video debugging app hosted off of github. Feel free to contribute! <file_sep>/scripts/main.js // A bunch of audio/video Javascript. // By <NAME>, 2010. var videoWatcher = null; function log(text) { $('#log_text').prepend(text + '\n'); } function clearLog() { $('#log_text').empty(); } function pad(text, width) { var count = Math.max(0, width- text.length); for (var i = 0; i < count; ++i) { text = text + ' '; } return text; } function main() { // As defined in Section 4.8.9.12: // http://www.whatwg.org/specs/web-apps/current-work/#mediaevents var events = [ 'loadstart', 'progress', 'suspend', 'abort', 'error', 'emptied', 'stalled', 'play', 'pause', 'loadedmetadata', 'loadeddata', 'waiting', 'playing', 'canplay', 'canplaythrough', 'seeking', 'seeked', 'timeupdate', 'ended', 'ratechange', 'durationchange', 'volumechange', ]; var v = $('#v').first(); var watcher = new VideoWatcher(v); function onEvent(e) { var str = pad(e.type, 14) + ' (currentTime=' + $(this).attr('currentTime'); switch (e.type) { case 'durationchange': str += ', duration=' + $(this).attr('duration'); break; case 'progress': case 'suspend': str += ', buffered=' + $(this).attr('buffered').end(0); break; default: break; } str += ')'; log(str); watcher.update(); } for (var i = 0; i < events.length; ++i) { v.bind(events[i], onEvent); } $('#url_button').click(function() { var url = $('#url_input').val() v.attr('src', url) v[0].load(); }); log(navigator.userAgent); } function CellUpdater(prefix, count, expr) { this.prefix = prefix; this.count = count; this.expr = expr; this.update = function() { for (var i = 0; i < this.count; ++i) { on = this.expr(i); $(this.prefix + i).toggleClass('on', on).toggleClass('off', !on); } }; } function CountUpdater(prefix, v) { this.prefix = prefix; this.video = v; this.counts = [ 'webkitDecodedFrameCount', 'webkitDroppedFrameCount', 'webkitVideoDecodedByteCount', 'webkitAudioDecodedByteCount' ]; this.update = function() { for (var i = 0; i < this.counts.length; ++i) { $(this.prefix + i).text(this.video.attr(this.counts[i])) } }; } function VideoWatcher(video) { this.video = video; this.readyStateUpdater = new CellUpdater('#rs_', 5, function(value) { return video.attr('readyState') == value; }); this.networkStateUpdater = new CellUpdater('#ns_', 4, function(value) { return video.attr('networkState') == value; }); this.errorUpdater = new CellUpdater('#e_', 5, function(value) { var error = video.attr('error') return (value == 0 && error == null) || (error != null && error.code == value); }); this.countsUpdater = new CountUpdater('#c_', this.video); // Load initial values. this.readyStateUpdater.update(); this.networkStateUpdater.update(); this.errorUpdater.update(); this.countsUpdater.update(); this.update = function() { this.readyStateUpdater.update(); this.networkStateUpdater.update(); this.errorUpdater.update(); this.countsUpdater.update(); } } <file_sep>/scripts/benchmark.js function generateSrc(src) { var ch = src.indexOf('?') >= 0 ? '&' : '?'; return src + ch + 't=' + (new Date()).getTime(); } function Timer() { this.start_ = 0; this.times_ = []; new Date().getTime(); } Timer.prototype = { start: function() { this.start_ = new Date().getTime(); }, stop: function() { this.times_.push((new Date().getTime()) - this.start_); console.log(this.times_[this.times_.length - 1]); }, average: function() { var sum = 0; for (var i in this.times_) { sum += this.times_[i]; } return sum / this.times_.length; }, reset: function() { this.start_ = 0; this.times_ = []; } } function Benchmark(video, src) { this.video_ = video; this.src_ = src; this.cached_src_ = generateSrc(src); this.timer_ = new Timer; var me = this; this.video_.addEventListener('playing', function() { me.playing(); }); this.video_.addEventListener('seeked', function() { me.seeked(); }); this.video_.addEventListener('suspend', function() { me.suspend(); }); this.video_.addEventListener('error', function() { me.error(); }); }; Benchmark.prototype = { reset: function() { this.playing = function() {}; this.seeked = function() {}; this.suspend = function() {}; this.error = function() {}; this.video_.src = ''; this.video_.load(); }, testCached: function(iterations, done_cb) { console.log('Starting cached tests...'); this.reset(); this.error = function() { done_cb("Error loading media"); } var times = -1; var timer = new Timer; this.playing = function() { times++; // Ignore the first result. if (times > 0) { timer.stop(); } if (times == iterations) { this.reset(); done_cb(timer.average()); return; } this.video_.src = ''; this.video_.load(); timer.start(); this.video_.src = this.cached_src_; this.video_.load(); }; timer.start(); this.video_.src = this.cached_src_; this.video_.load(); }, testUncached: function(iterations, done_cb) { console.log('Starting uncached tests...'); this.reset(); this.error = function() { done_cb("Error loading media"); } var times = 0; var timer = new Timer; this.playing = function() { timer.stop(); times++; if (times == iterations) { this.reset(); done_cb(timer.average()); return; } timer.start(); this.video_.src = generateSrc(this.src_); this.video_.load(); } timer.start(); this.video_.src = generateSrc(this.src_); this.video_.load(); }, testShortSeek: function(iterations, done_cb) { console.log('Starting short seek tests...'); this.reset(); this.error = function() { done_cb("Error loading media"); } var times = 0; var timer = new Timer; var firstPlaying = function() { this.playing = function() {} timer.start(); this.video_.currentTime = 1; }; this.seeked = function() { timer.stop(); times++; if (times == iterations) { this.reset(); done_cb(timer.average()); return; } this.playing = firstPlaying; this.video_.src = generateSrc(this.src_); this.video_.load(); }; this.playing = firstPlaying; this.video_.src = generateSrc(this.src_); this.video_.load(); }, testLongSeek: function(iterations, done_cb) { console.log('Starting long seek tests...'); this.reset(); this.error = function() { done_cb("Error loading media"); } var times = 0; var timer = new Timer; var firstPlaying = function() { this.playing = function() {} timer.start(); this.video_.currentTime = this.video_.duration - 1; }; this.seeked = function() { timer.stop(); times++; if (times == iterations) { this.reset(); done_cb(timer.average()); return; } this.playing = firstPlaying; this.video_.src = generateSrc(this.src_); this.video_.load(); }; this.playing = firstPlaying; this.video_.src = generateSrc(this.src_); this.video_.load(); } };
00bec36cc6db880649e222ef07e76fe2fb9717e7
[ "Markdown", "JavaScript" ]
3
Markdown
ascherkus/iheartvideo
dff2777e78d0f235110a20611994d69d76d9ab29
3e3112fdde40237cc01e86148865cb0cb95712a7
refs/heads/master
<file_sep>const express = require('express'); // const songRouter = require('./song.routes'); const sessionRouter = require('./session.routes'); const authRouter = require('./auth.routes'); const rootRouter = new express.Router(); // default page (will redirect to login if authentication needed) rootRouter.get('/', (req, res) => { res.redirect('/sessions'); }); rootRouter.use(authRouter); rootRouter.use(songRouter); rootRouter.use(sessionRouter); module.exports = rootRouter; <file_sep>// Update session const sessionUpdate = (req, res, next) => { next(); }; module.exports = sessionUpdate; <file_sep>const ROLES = { ADMIN: 'ADMIN', MUSICIAN: 'MUSICIAN', }; const MAIN_PAGE = '/sessions'; module.exports = { ROLES, }; <file_sep>const { AuthService } = require('../../services'); // Clear user's session, and redirects to login page const logout = (req, res) => { AuthService.clearCurrentUser(req.session); res.redirect('/login'); }; module.exports = logout; <file_sep>const { AuthService, UserService } = require('../../services'); const { ROLES } = require('../../utils/const'); // Redirects to google, and handle response const loginWithGoogle = async (req, res) => { const { role } = req.query; let user; if (role === 'admin') { user = { name: '<NAME>', email: '<EMAIL>', role: ROLES.ADMIN, }; } else { user = { name: '<NAME>', email: '<EMAIL>', role: ROLES.MUSICIAN, }; } // check if the user already exists const checkUserWithEmail = await UserService.getUserByEmail(user.email); if (checkUserWithEmail) { // give session then redirect AuthService.setCurrentUser(req.session, checkUserWithEmail); return res.redirect('/sessions'); } const createdUser = await UserService.createUser(user); AuthService.setCurrentUser(req.session, createdUser); res.redirect('/sessions'); }; module.exports = loginWithGoogle; <file_sep>// eslint-disable-next-line prefer-const module.exports = [ { id: 1, name: 'Practice for Christmas concert', date: 1570896000, location: 'Supercharge Office', currentSongs: [ { artist: 'Simon & Garfunkel', title: 'El Condor Pasa', }, { artist: 'Simon & Garfunkel', title: 'The Boxer', }, ], availableSongs: [ { artist: 'Stone Sour', title: 'Wicked Game', }, { artist: 'Stone Sour', title: 'Song #3', }, ], participants: [ { name: '<NAME>', }, { name: '<NAME>', }, ], }, { id: 2, name: 'Practice with Viki', date: 1573585200, location: 'Supercharge Office', currentSongs: [ { artist: 'Simon & Garfunkel', title: 'El Condor Pasa', }, ], availableSongs: [], participants: [ { name: '<NAME>', }, ], }, ]; <file_sep>const renderMW = require('./render.mw'); module.exports = { renderMW, }; <file_sep>const { SessionService, SongService } = require('../../services'); // Get session based on session-id const sessionGet = async (req, res, next) => { const { sessionid } = req.params; const session = await SessionService.getSession(sessionid); const availableSongs = (await SongService.getSongs()).filter( song => // eslint-disable-next-line no-underscore-dangle !session.songs.find(sessionSong => sessionSong._id.toString() === song._id.toString()), ); const userInSession = !!session.participants.find( // eslint-disable-next-line no-underscore-dangle user => user._id.toString() === req.session.user._id.toString(), ); res.locals.session = session; res.locals.availableSongs = availableSongs; res.locals.user = req.session.user; res.locals.userInSession = userInSession; next(); }; module.exports = sessionGet; <file_sep>const { SongService } = require('../../services'); // List songs const songList = async (req, res, next) => { const songs = await SongService.getSongs(); res.locals.songs = songs; next(); }; module.exports = songList; <file_sep># bme-server-side-js Example application for a course with focus of server side javascript # Run dev-server ```bash npm install npm run start ``` <file_sep>const authCheck = require('./auth-check.mw'); const roleCheck = require('./role-check.mw'); const loginWithGoogle = require('./login-with-google.mw'); const logout = require('./logout.mw'); module.exports = { authCheck, roleCheck, loginWithGoogle, logout, }; <file_sep>const { SongService } = require('../../services'); // Check request body, and delete song const songDelete = async (req, res) => { const { songid } = req.params; await SongService.deleteSong(songid); res.redirect('/songs'); }; module.exports = songDelete; <file_sep>const mongoose = require('mongoose'); const SongModel = mongoose.model('Song', { title: String, artist: String, youtubeLink: String, }); module.exports = SongModel; <file_sep># Middlewares ## Auth MWs * **auth-check**: Checking authentication information, redirect to login if no auth * **role-check**: Checking if the user's role is enough for the page * **login-with-google**: Redirect to authenticate with google, handle google's redirect response * **logout**: Clear authentication information about the user ## Session MWs * **session-create**: Create session * **session-delete**: Delete session * **session-get**: Get session * **session-list**: List sessions * **session-update**: Update session ## Song MWs * **song-create**: Create session * **song-delete**: Delete session * **song-get**: Get session * **song-list**: List sessions * **song-update**: Update session ## Render MWs * **render**: Render the given template # Routes ## Auth, Main page GET / * auth-check * role-check GET /login * render GET /login-with-google * login-with-google GET /logout * logout ## Sessions GET /sessions * auth-check * role-check * session-list * session-delete (admin) * render GET PATCH DELETE /sessions/:session-id * auth-check * role-check * session-get * session-update * render GET POST /sessions-create * auth-check * role-check * session-create * render ## Songs GET /songs * auth-check * role-check * song-list * song-delete (admin) * render GET PATCH DELETE /songs/:song-id * auth-check * role-check * song-get * song-update * render GET POST /song-create * auth-check * role-check * song-create * render<file_sep>const express = require('express'); const { songList, songDelete, songGet, songUpdate, songCreate, } = require('../middlewares/song/index'); const { renderMW } = require('../middlewares/render'); // const { authCheck, roleCheck } = require('../middlewares/auth'); const songRouter = new express.Router(); songRouter.use('/songs', authCheck, roleCheck); songRouter.get('/songs', songList, renderMW('song/songs')); songRouter.post('/songs/:songid', songUpdate, songGet, renderMW('song/song')); songRouter.get('/songs/:songid', songGet, renderMW('song/song')); songRouter.use('/song-delete', authCheck, roleCheck); songRouter.get('/song-delete/:songid', songDelete); songRouter.use('/song-create', authCheck, roleCheck); songRouter.get('/song-create', renderMW('song/song-create')); songRouter.post('/song-create', songCreate, renderMW('song/song-create')); module.exports = songRouter; <file_sep>// Checking Authentication // IF no_auth -> redirect to login // ELSE next() const { AuthService } = require('../../services'); // eslint-disable-next-line consistent-return const authCheck = (req, res, next) => { const currentUser = AuthService.getCurrentUser(req.session); if (!currentUser) { return res.redirect('/login'); } res.locals.currentUser = currentUser; res.locals.currentPath = req.originalUrl; next(); }; module.exports = authCheck; <file_sep>const UserModel = require('../models/user.model'); class UserService { static async getUser(userid) { try { const user = await UserModel.findById(userid); if (!user) { throw new Error(`User not found with id: "${user}"`); } return user; } catch (error) { console.log(error); return null; } } static async getUserByEmail(email) { try { const user = await UserModel.findOne({ email, }); if (!user) { return null; } return user; } catch (error) { console.log(error); return null; } } static async createUser({ name, email, role }) { const user = await UserModel.create({ name, email, role, }); return user; } } module.exports = UserService; <file_sep>const mongoose = require('mongoose'); const { ROLES } = require('../utils/const'); const UserModel = mongoose.model('User', { name: String, email: String, role: { type: String, enum: Object.keys(ROLES).map(roleKey => ROLES[roleKey]), }, }); module.exports = UserModel; <file_sep>const { SessionService } = require('../../services'); // Remove song for session const sessionRemoveSong = async (req, res) => { const { sessionid, songid } = req.query; await SessionService.removeSong(sessionid, songid); res.redirect(`/sessions/${sessionid}`); }; module.exports = sessionRemoveSong; <file_sep>const { SessionService } = require('../../services'); // Add song for session const sessionAddSong = async (req, res) => { const { sessionid, songid } = req.query; await SessionService.addSong(sessionid, songid); res.redirect(`/sessions/${sessionid}`); }; module.exports = sessionAddSong; <file_sep>const { SessionService } = require('../../services'); // Check request body, and create session const sessionCreate = async (req, res, next) => { const { name, location, date } = req.body; try { await SessionService.createSession({ name, location, date: new Date(date), }); res.redirect('/sessions'); } catch (error) { console.log(error); res.locals.error = error.message; res.locals.session = { name, location, date, }; next(); } }; module.exports = sessionCreate; <file_sep>const { SessionService } = require('../../services'); // List sessions const sessionList = async (req, res, next) => { const sessions = await SessionService.getSessions(); res.locals.sessions = sessions; next(); }; module.exports = sessionList; <file_sep>const SessionModel = require('../models/session.model'); const SongService = require('./song.service'); const UserService = require('./user.service'); class SessionService { static async getSessions() { try { const sessions = await SessionModel.find(); return sessions; } catch (error) { console.error(error); return []; } } static async getSession(sessionid) { try { const session = await SessionModel.findById(sessionid) .populate('songs') .populate('participants'); if (!session) { throw new Error(`Session not found with id: "${sessionid}"`); } return session; } catch (error) { console.log(error); return null; } } static async createSession({ name, date, location }) { await SessionModel.create({ name, date, location, songs: [], participants: [], }); } static async deleteSession(sessionid) { await SessionModel.remove({ _id: sessionid }); } static async addSong(sessionid, songid) { try { const session = await SessionService.getSession(sessionid); const song = await SongService.getSong(songid); session.songs.push(song); await session.save(); } catch (error) { console.log(error); } } static async removeSong(sessionid, songid) { try { const session = await SessionService.getSession(sessionid); const songToRemoveIndex = session.songs.findIndex(song => { // eslint-disable-next-line no-underscore-dangle return song._id.toString() === songid; }); if (songToRemoveIndex === -1) { throw new Error(`No song ${songid} in session ${sessionid}`); } session.songs.splice(songToRemoveIndex, 1); await session.save(); } catch (error) { console.log(error); } } static async addParticipant(sessionid, userid) { try { const session = await SessionService.getSession(sessionid); const user = await UserService.getUser(userid); session.participants.push(user); await session.save(); } catch (error) { console.log(error); } } static async removeParticipant(sessionid, userid) { try { const session = await SessionService.getSession(sessionid); const userToRemoveIndex = session.participants.findIndex(user => { // eslint-disable-next-line no-underscore-dangle return user._id.toString() === userid; }); if (userToRemoveIndex === -1) { throw new Error(`No user ${userid} in session ${sessionid}`); } session.participants.splice(userToRemoveIndex, 1); await session.save(); } catch (error) { console.log(error); } } } module.exports = SessionService; <file_sep>const express = require('express'); const { sessionList, sessionDelete, sessionGet, sessionUpdate, sessionCreate, sessionAddSong, sessionRemoveSong, sessionAddParticipant, sessionRemoveParticipant, } = require('../middlewares/session/index'); const { renderMW } = require('../middlewares/render'); // const { authCheck, roleCheck } = require('../middlewares/auth'); const sessionRouter = new express.Router(); sessionRouter.use('/sessions', authCheck, roleCheck); sessionRouter.get('/sessions', sessionList, renderMW('session/sessions')); sessionRouter.get('/sessions/:sessionid', sessionGet, renderMW('session/session')); sessionRouter.patch('/sessions/:sessionid', sessionUpdate, renderMW('session/session')); sessionRouter.use('/sessions', authCheck, roleCheck); sessionRouter.get('/session-delete/:sessionid', sessionDelete); sessionRouter.use('/session-create', authCheck, roleCheck); sessionRouter.get('/session-create', renderMW('session/session-create')); sessionRouter.post('/session-create', sessionCreate, renderMW('session/session-create')); sessionRouter.use('/session-add-song', authCheck, roleCheck); sessionRouter.get('/session-add-song', sessionAddSong); sessionRouter.use('/session-remove-song', authCheck, roleCheck); sessionRouter.get('/session-remove-song', sessionRemoveSong); sessionRouter.use('/session-add-participant', authCheck, roleCheck); sessionRouter.use('/session-add-participant', sessionAddParticipant); sessionRouter.use('/session-remove-participant', authCheck, roleCheck); sessionRouter.use('/session-remove-participant', sessionRemoveParticipant); module.exports = sessionRouter; <file_sep>const moment = require('moment'); // Render the given page const renderMW = viewName => (req, res) => { res.locals.moment = moment; res.render(viewName); }; module.exports = renderMW; <file_sep>const SongModel = require('../models/song.model'); class SongService { static async getSongs() { try { const songs = await SongModel.find(); return songs; } catch (error) { console.error(error); return []; } } static async getSong(songid) { try { const song = await SongModel.findById(songid); if (!song) { throw new Error(`Song not found with id: "${songid}"`); } return song; } catch (error) { console.log(error); return null; } } static async createSong({ title, artist, youtube }) { await SongModel.create({ title, artist, youtubeLink: youtube, }); } static async updateSong({ songid, title, artist, youtube }) { const song = await SongModel.findById(songid); if (!song) { throw new Error(`Song not found with id: "${songid}"`); } song.title = title; song.artist = artist; song.youtubeLink = youtube; await song.save(); } static async deleteSong(songid) { await SongModel.remove({ _id: songid, }); } } module.exports = SongService; <file_sep>module.exports = [ { id: 1, title: 'The Boxer', artist: '<NAME>', youtubeLink: 'https://www.youtube.com/watch?v=l3LFML_pxlY', }, { id: 2, title: '<NAME>', artist: 'Simon & Garfunkel', youtubeLink: 'https://www.youtube.com/watch?v=9C1BCAgu2I8', }, { id: 3, title: 'Feed Me', artist: 'Blue Tips', youtubeLink: 'https://www.youtube.com/watch?v=eG4pDOD9Plk', }, ]; <file_sep>// Checking User's role // IF requiredRoles is present next() // IF requiredRoles is not present redirect to LOGIN_PAGE // IF path = '/' && requiredRoles is present redirect to MAIN_PAGE const roleCheck = (req, res, next) => { next(); }; module.exports = roleCheck;
4c6e4d70f46172350a574024763b98a127027ea3
[ "JavaScript", "Markdown" ]
28
JavaScript
Kisfejes/bme-server-side-js
2a212f04c3a2abc3b9841acf93bf206a41497e08
32969af2b2aa701ac3c188603139e4581477bc03
refs/heads/master
<file_sep># phantergallery Gallery of images to python projects (Flask, Web2py, Django, etc) #requirements Python 3.6+ Pillow <file_sep># -*- coding: utf-8 -*- # Autor: PhanerJR from __future__ import print_function from .phantertagconstroi import MyTag import io import os from PIL import Image as PILImage class DIV(MyTag): def __init__(self, *content, **attributes): MyTag.__init__(self, 'div') self.singleton = False self.content = content self.attributes = attributes class I(MyTag): def __init__(self, *content, **attributes): MyTag.__init__(self, 'i') self.singleton = False self.content = content self.attributes = attributes class INPUT(MyTag): def __init__(self, *content, **attributes): MyTag.__init__(self, 'input') self.singleton = True self.content = content self.attributes = attributes class CANVAS(MyTag): def __init__(self, *content, **attributes): MyTag.__init__(self, 'canvas') self.singleton = False self.content = content self.attributes = attributes class PhanterGalleryInput(object): def __init__(self, src_img="", cut_size=(300, 300), global_id=None, zindex=None): """ @src_img: source_img @cut_size: Cut image size @global_id: Adds in all ids of the elements this id, in this way it is possible to add 2 distinct inputs without conflicts """ super(PhanterGalleryInput, self).__init__() self.cut_size = cut_size self.title_button = "Upload Image" self._image_button = I(_class="phantersvg upload-cloud") self.global_id = global_id self._src_img = src_img self.zindex = zindex @property def zindex(self): return self._zindex @zindex.setter def zindex(self, value): if isinstance(value, (int, type(None))): self._zindex=value else: raise TypeError("The zindex value must be integer") @property def global_id(self): return self._global_id @global_id.setter def global_id(self, _id): if isinstance(_id, (str, int, type(None))): if isinstance(_id, str): _id = _id.strip() if " " in _id: raise ValueError("The id can't have empty space") elif _id==None: self._global_id="" else: self._global_id = _id else: raise TypeError("The global_id must be string or integer or None") @property def title_button(self): """ Get or Set title button """ return self._title_button @title_button.setter def title_button(self, title): if isinstance(title, (str, MyTag)): if isinstance(title, MyTag): title = title.xml self._title_button = title else: raise TypeError("The title must be string") @property def image_button(self): """ Get or Set title button """ return self._image_button @image_button.setter def image_button(self, img_button): if isinstance(img_button, (str, MyTag)): if isinstance(img_button, MyTag): img_button = img_button.xml self._image_button = img_button else: raise TypeError("The image_button must be " + "string or MyTag instance") @property def xml(self): global_id = self._global_id self._xml = self._html_input(global_id) return self._xml def _html_input(self, _id=""): zindex = self._zindex style_zindex = None if zindex: style_zindex = "z-index:%s;" % zindex title_button = self._title_button image_button = self._image_button cut_size = self.cut_size ids_elements = { '_data-object': 'phantergallery_object', '_data-upload-form-container': 'phantergallery_upload-form-container', '_data-upload-input': 'phantergallery_upload-input-file', '_data-cutter-pad': 'phantergallery_cutter-pad', '_data-cutter-background': 'phantergallery_cutter-background', '_data-panel-cutter-container': 'phantergallery_panel-cutter-container', '_data-cutter-shadow': 'phantergallery_cutter-shadow', '_data-cutter-control-close': 'phantergallery_cutter-control-close', '_data-cutter-control-view': 'phantergallery_cutter-control-view', '_data-cutter-control-cut': 'phantergallery_cutter-control-cut', '_data-panel-cutter-size-container': 'phantergallery_panel-cutter-size-container', '_data-panel-cutter-image': 'phantergallery_panel-cutter-image', '_data-cutter-zoom-control': 'phantergallery_cutter-zoom-control', '_data-target-view': 'phantergallery_target-view', '_data-target-view-container': 'phantergallery_target-view-container', '_data-upload-messages': 'phantergallery_upload-messages', '_data-upload-area-progress': 'phantergallery_upload-area-progress', '_data-upload-image-button': 'phantergallery_upload-image-button', '_data-upload-title-button': 'phantergallery_upload-title-button', '_data-imagecuted-control-erase': 'phantergallery-imagecuted-control-erase', '_data-imagecuted-control-change': 'phantergallery-imagecuted-control-change', } if _id: for x in ids_elements: ids_elements[x] = "-".join([ids_elements[x], _id]) ids_elements['_data-cutter-size-x'] = str(cut_size[0]) ids_elements['_data-cutter-size-y'] = str(cut_size[1]) ids_elements['_data-upload-src-img'] = self._src_img html = DIV( DIV( DIV( DIV( DIV( I(_class="phantersvg recycle"), _id=ids_elements["_data-imagecuted-control-erase"], _class="phantergallery" + "_imagecuted-control" ), DIV( I(_class="phantersvg image-reload"), _id=ids_elements["_data-imagecuted" + "-control-change"], _class="phantergallery" + "_imagecuted-control" ), _class="phantergallery" + "_imagecuted-controls"), CANVAS(_id=ids_elements['_data-target-view']), _class='phantergallery-center-content', ), _id=ids_elements['_data-target-view-container'], _style="overflow: hidden; width: %spx; height: %spx;" % (cut_size[0], cut_size[1]), _class="phantergallery_target-view-container%s" % (" actived" if self._src_img else ""), ), DIV( DIV( DIV( DIV(image_button, _id=ids_elements["_data-upload-image-button"], _class="phantergallery_upload-image-button"), DIV(title_button, _id=ids_elements["_data-upload-title-button"], _class="phantergallery_upload-title-button"), _class="phantergallery_upload-button" ), _class="phantergallery_container-upload-button" ), _id=ids_elements['_data-object'], _class="phantergallery_object%s" % (" actived" if not self._src_img else ""), **ids_elements ), DIV( INPUT( _accept="image/png, image/jpeg, image/gif, image/bmp", _id=ids_elements["_data-upload-input"], _class="phantergallery_upload-input-file", _type="file", ), _id=ids_elements["_data-upload-form-container"], _class="phantergallery_upload-form-container", _style="display: none;" ), DIV( DIV(_id=ids_elements["_data-cutter-background"], _class="phantergallery_cutter-background"), DIV(_id=ids_elements["_data-cutter-shadow"], _class="phantergallery_cutter-shadow"), DIV( DIV( DIV( _class="phantergallery_panel-cutter-image", _id=ids_elements['_data-panel-cutter-image']), _style="overflow: hidden; width: %spx; height: %spx;" % (cut_size[0], cut_size[1]), _id=ids_elements['_data-panel-cutter-size-container'], _class="phantergallery_panel-cutter-size-container" ), _class="phantergallery_panel-cutter" ), DIV( _id=ids_elements['_data-cutter-pad'], _class="phantergallery_cutter-pad"), DIV( DIV( I(_class="phantersvg close-circle"), _id=ids_elements['_data-cutter-control-close'], _class="phantergallery_cutter-control"), DIV( I(_class="phantersvg image-view"), _id=ids_elements['_data-cutter-control-view'], _class="phantergallery_cutter-control"), DIV( I(_class="phantersvg image-cut"), _id=ids_elements['_data-cutter-control-cut'], _class="phantergallery_cutter-control"), _class='phantergallery_cutter-controls-container'), DIV( DIV( I(_class="phantersvg image-decrease"), DIV( DIV(_id=ids_elements['_data-cutter-zoom-control'], _class="phantergallery_cutter-zoom-control"), _class="phantergallery_cutter-zoom-control" + "-container" ), I(_class="phantersvg image-increase"), _class='phantergallery_cutter-zoom-controls'), _class='phantergallery_cutter-zoom-container'), _id=ids_elements['_data-panel-cutter-container'], _class="phantergallery_panel-cutter-container", _style=style_zindex ), DIV(_id=ids_elements['_data-upload-messages'], _class="phantergallery_upload-messages"), DIV( DIV( DIV( DIV(_class="phantergallery_progressbar-movement"), _class="phantergallery_progressbar"), _id=ids_elements['_data-upload-area-progress'], _class="phantergallery_upload-area-progress" ), _class="phantergallery_progressbar-container" ), _class="phantergallery_inert-container" ) return html.xml @property def cut_size(self): return self._cut_size @cut_size.setter def cut_size(self, cut_size): if isinstance(cut_size, (tuple, list)): if len(cut_size) == 2: if isinstance(cut_size[0], (int, float)) and \ isinstance(cut_size[1], (int, float)): self._cut_size = (cut_size[0], cut_size[1]) else: raise TypeError("Values of list or tuple must be " + "integers or float") else: raise SyntaxError("There must be at least 2 values") else: raise TypeError("The value has to be a tuple or a list") def __str__(self): return self.xml def __repr__(self): return self.xml class PhanterGalleryCutter(object): def __init__(self, imageName, imageType, imageBytes, cutterSizeX, cutterSizeY, positionX, positionY, newSizeX, newSizeY): self.imageName = imageName self.imageType = imageType self.imageBytes = imageBytes self.cutterSizeX = cutterSizeX self.cutterSizeY = cutterSizeY self.positionX = positionX self.positionY = positionY self.newSizeX = newSizeX self.newSizeY = newSizeY def getImage(self): imageBytes = self.imageBytes nome_da_imagem = self.imageName im = PILImage.open(imageBytes) newSizeX = int(float(self.newSizeX)) newSizeY = int(float(self.newSizeY)) cutterSizeX = float(self.cutterSizeX) cutterSizeY = float(self.cutterSizeY) positionX = float(self.positionX) * (-1) positionY = float(self.positionY) * (-1) extensao = os.path.splitext(nome_da_imagem)[1] im = im.resize((newSizeX, newSizeY), PILImage.ANTIALIAS) im = im.crop((positionX, positionY, positionX + cutterSizeX, positionY + cutterSizeY)) jpeg_image_buffer = io.BytesIO() if extensao.lower() == '.png': im.save(jpeg_image_buffer, 'png') else: im.save(jpeg_image_buffer, format='JPEG', quality=100) jpeg_image_buffer.seek(0) data = jpeg_image_buffer.read() return data class PhanterGalleryImageCutObj(object): def __init__(self, imageBytes): self.imageBytes = imageBytes def getImage(self, formatOut='png'): im = PILImage.open(self.imageBytes) jpeg_image_buffer = io.BytesIO() if formatOut == 'png': im.save(jpeg_image_buffer, 'png') else: im.save(jpeg_image_buffer, format='JPEG', quality=100) jpeg_image_buffer.seek(0) data = jpeg_image_buffer.read() return data <file_sep># -*- coding: utf-8 -*- # autor: PhanterJR class MyTag(object): """ Helper to constroi html tags. With this class you can create other predefined tags. Example: >>> class DIV(MyTag): def __init__(self, *content, **attributes): MyTag.__init__(self, 'div') self.singleton=False self.content=content self.attributes=attributes >>> print(DIV()) <div></div> >>> print(DIV("My content", _class="my_atribute_class")) <div class="my_atribute_class">My content</div> """ def __init__(self, tag, singleton=False, *content, **attributes): """ @tag = name of tag. Example: div, img, br @singleton = if True, the tag does not need to close. Example: MyTag("br", True) produce '<br>' MyTag("hr", True) produce '<hr>' MyTag("img", True, _href="#my_url") produce '<img href="#myurl">' if False, the tag will be close, MyTag("div") produce '<div></div>' MyTag("h1", False, "My title") produce '<h1>My title</h1>' MyTag("button", False, "my_content", _class="my_class") produce '<button class="my_class">"my_content"</button>' @content = Content of element. exemple: MyTag("this is", " my content") @attributes = Element attributes. Each key of the attribute must begin with underline (_) (because of the keyword class and id), keys without underline will create a Exeption. Example: MyTag(_class="my_class", _style="display:block") """ super(MyTag, self).__init__() self.tag = tag self.singleton = singleton self.content = content self.attributes = attributes @property def tag(self): """ Get or Set tag of element Set: >>> new_tag=MyTag('div', False) >>> print(new_tag) <div></div> new_tag.tag='button' >>> print(new_tag) <button></button> Get: >>> new_tag=MyTag('div', False) >>> print(new_tag.tag) div """ return self._tag @property def singleton(self): """ Get or Set if element is singleon or not Set True: >>> new_tag=MyTag("br", True) >>> print(new_tag) <br> >>> new_tag=MyTag("hr", True) >>> print(new_tag) <hr> >>> new_tag=MyTag("img", True, _href="#my_url") >>> print(new_tag) <img href="#myurl"> Set False: >>> new_tag=MyTag("div") >>> print(new_tag) <div></div> >>> new_tag=MyTag("h1", False, "My title") >>> print(new_tag) <h1>My title</h1> >>> new_tag=MyTag("button", False, "my_content", _class="my_class") >>> print(new_tag) <button class="my_class">"my_content"</button> Get: >>> new_tag=MyTag("button", False, "my_content", _class="my_class") >>> print(new_tag.singleton) False """ return self._singleton @property def content(self): """ Get or Set content of element. Set List: >>> new_tag=MyTag("div", False) >>> new_tag.content=['my', ' content'] >>> print(new_tag) <div>my content</div> Set String: >>> new_tag=MyTag("div", False) >>> new_tag.content="my other content" >>> print(new_tag) <div>my other content</div> Set MyTag instance: >>> new_tag=MyTag("div", False) >>> other_tag=MyTag("a", False, "click here", _href="#my_url") >>> new_tag.content=other_tag >>> print(new_tag) <div><a href="#my_url">click here</a></div> """ return self._content @property def attributes(self): """ Get or Set atributes of tag element. Can set a dict(recomended) or a string. Set a dict: Each key of the attribute must begin with underline (_) (because of the keyword class and id), keys without underline will create a Exeption. Example: >>> new_tag=MyTag('div', False) >>> new_tag.attributes={"_class":"my_class", "_id":"my_id"} >>> print(new_tag) <div class="my_class" id="my_id"></div> Set a string: Example: >>> new_tag.attributes='class="my_class_string"' >>> print(new_tag) <div class="my_class_string"></div> Get: Example: >>> new_tag=MyTag('div', False) >>> new_tag.attributes={"_class":"my_class", "_id":"my_id"} >>> new_tag.attributes class="my_class" id="my_id" """ return self._attributes @tag.setter def tag(self, tag): if isinstance(tag, str): self._tag = tag else: raise TypeError("The tag must be string") @singleton.setter def singleton(self, singleton): if isinstance(singleton, bool): self._singleton = singleton else: raise TypeError("The singleton must be boolean") @content.setter def content(self, content): if isinstance(content, str): self._content = content elif isinstance(content, MyTag): self._content = content.xml elif isinstance(content, (list, tuple)): temp_content = "" for x in content: if isinstance(x, (str, MyTag)): if isinstance(x, str): temp_content = "".join([temp_content, x]) else: temp_content = "".join([temp_content, x.xml]) else: raise TypeError("The elements of a content list or tuple \ must be strings or MyTag instances") self._content = temp_content else: raise TypeError( "The content must be a list, tuple, string or MyTag instance") @attributes.setter def attributes(self, attributes): print('veio aqui') if isinstance(attributes, str): self._attributes = " ".join(["", attributes.strip()]) elif isinstance(attributes, type(None)): pass elif isinstance(attributes, dict): temp_atributes = {} for x in attributes: if x.startswith("_"): if attributes[x] == None: pass else: temp_atributes[x] = attributes[x] else: raise TypeError( "Keys of attributes must starts with underline '_'") self._attributes = self._make_attr_element(temp_atributes) else: raise TypeError("The attributes must be a dict") @property def xml(self): """ Get xml(html) of element >>> new_tag=MyTag('div', False) >>> print(new_tag.xml) <div></div> """ html = self._update_xml() self._xml = html return self._xml def _make_attr_element(self, dict_attr): attr_element = "" for x in dict_attr: attr_temp = "=".join( [x.replace("_", ""), "".join(['"', dict_attr[x], '"'])]) attr_element = " ".join([attr_element, attr_temp]) return attr_element def _update_xml(self): attr_element = self._attributes tag = self.tag if self._singleton: template = "<%(tag)s%(attributes)s>" % dict( tag=tag, attributes=attr_element) else: content = self.content template = "<%(tag)s%(attributes)s>%(content)s</%(tag)s>" % dict( tag=tag, attributes=attr_element, content=content) html = template return html def __str__(self): return self.xml def __repr__(self): return self.xml if __name__ == '__main__': class DIV(MyTag): def __init__(self, *content, **attributes): MyTag.__init__(self, 'div') self.singleton = False self.content = content self.attributes = attributes print(DIV().xml) <file_sep> var phanterGalleryObj = function(elementPhanterGalleryObj, config, messages){ var MainObj = this MainObj.el = elementPhanterGalleryObj; MainObj.imageName = ""; MainObj.imageType = ""; MainObj.uploadArea = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-object")); MainObj.uploadFormContainer = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-upload-form-container")); MainObj.uploadInput = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-upload-input")); MainObj.panelCutterContainer = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-panel-cutter-container")); MainObj.cutterShadow = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-cutter-shadow")); MainObj.cutterControlClose = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-cutter-control-close")); MainObj.cutterControlView = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-cutter-control-view")); MainObj.cutterControlCut = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-cutter-control-cut")); MainObj.cutterPad = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-cutter-pad")); MainObj.cutterBackground = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-cutter-background")); MainObj.cutterZoomControl = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-cutter-zoom-control")); MainObj.panelCutterSizeContainer = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-panel-cutter-size-container")); MainObj.panelCutterImage = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-panel-cutter-image")); MainObj.targetView = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-target-view")); MainObj.targetViewContainer = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-target-view-container")); MainObj.imagecutedControlErase = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-imagecuted-control-erase")); MainObj.imagecutedControlChange = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-imagecuted-control-change")); MainObj.uploadMessages = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-upload-messages")); MainObj.uploadAreaProgress = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-upload-area-progress")); MainObj.uploadImageButton = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-upload-image-button")); MainObj.uploadTitleButton = phanterQuery("#"+elementPhanterGalleryObj.getAttribute("data-upload-title-button")); MainObj.cutterSizeX = elementPhanterGalleryObj.getAttribute("data-cutter-size-x"); MainObj.cutterSizeY = elementPhanterGalleryObj.getAttribute("data-cutter-size-y"); MainObj.uploadSrcImg = elementPhanterGalleryObj.getAttribute("data-upload-src-img"); MainObj.config = config; MainObj.messages = messages; MainObj.phanterGalleryCutterObj = undefined; MainObj.error = false; MainObj._callAfterCut = ""; MainObj.showProgress = function(){ MainObj.uploadAreaProgress.addClass("actived"); return MainObj }; MainObj.hideProgress = function(){ MainObj.uploadAreaProgress.removeClass("actived"); return MainObj }; MainObj.showMessage = function(message){ MainObj.uploadMessages.html(message); MainObj.uploadMessages.addClass("actived"); return MainObj }; MainObj.hideMessage = function(){ MainObj.uploadMessages.html(""); MainObj.uploadMessages.removeClass("actived"); return MainObj }; MainObj.click = function(){ MainObj.setTitleButton(MainObj.config.titleButtonWaiting) MainObj.uploadInput.trigger('click') return MainObj }; MainObj.setImgButton = function(img){ MainObj.uploadImageButton.html(img); return MainObj }; MainObj.setTitleButton = function(title){ MainObj.uploadTitleButton.html(title); return MainObj }; MainObj.inputChange = function(){ MainObj.showProgress(); var blob = MainObj.uploadInput[0][0].files; MainObj.imageBlob = blob[0] var fileslength = blob.length; for (var i = fileslength - 1; i >= 0; i--) { var img_type = blob[i]['type']; var img_name= blob[i]['name']; MainObj.imageName = img_name; MainObj.imageType = img_type; if (img_type=="image/png"||img_type=="image/bmp"||img_type=="image/gif"||img_type=="image/jpeg"){ if(img_name.length<50){ var reader = new FileReader(); reader.readAsDataURL(blob[0]) MainObj.targetView.html("") MainObj.hideProgress() reader.onloadend = function(){ var base64data = reader.result; MainObj.phanterGalleryCutterObj= new phanterGalleryCutterObj(base64data, MainObj) window.onresize = function(event){ } } } else { var message = MainObj.messages.nameOfFileLong MainObj.showMessage(message); }; } else{ var message = MainObj.messages.FileCouldNotBeUploaded.replace("%(name_file)s", img_name); throw message MainObj.showMessage(message); } } return MainObj }; MainObj.el=elementPhanterGalleryObj MainObj.uploadInput.on('change', function(){ MainObj.inputChange(); }); MainObj.el.onclick = function(){ MainObj.hideProgress(); MainObj.hideMessage(); MainObj.click(); }; return MainObj } var phanterGalleryCutterObj = function(base64data, PG){ var selfObj = this var PG=PG var base64data=base64data var img1=document.createElement("IMG"); var img2=document.createElement("IMG"); img1.onerror = function(){ PG.error=true; throw "invalid image!" } PG.panelCutterImage.html(""); PG.cutterBackground.html(""); PG.panelCutterImage[0][0].appendChild(img1) PG.cutterBackground[0][0].appendChild(img2) selfObj.base64data = base64data; selfObj.originalWidthImg = 0; selfObj.originalHeightImg = 0; selfObj.widthImg = 0; selfObj.heightImg = 0; selfObj.widthScreen = 0; selfObj.heightScreen = 0; selfObj.widthCutter = 0; selfObj.heightCutter = 0; selfObj.inicialPositionXBackground = 0; selfObj.inicialPositionYBackground = 0; selfObj.inicialPositionXImgToCut = 0; selfObj.inicialPositionYImgToCut = 0; selfObj.deslocationPositionXBackground = 0; selfObj.deslocationPositionYBackground = 0; selfObj.deslocationPositionXImgToCut = 0; selfObj.deslocationPositionYImgToCut = 0; selfObj.deslocationPositionZoom = 0; selfObj.positionDefaultZoom = 89.0; selfObj.widthImgAfterZoom = 0; selfObj.heightImgAfterZoom = 0; selfObj.positionXAfterZoom = 0; selfObj.positionYAfterZoom = 0; selfObj.activeViewImage = false; selfObj.calcMidPosition =function(sizeContainer, sizeContent, positionContent){ var midsize1=sizeContainer/2.0 var midsize2=sizeContent/2.0 var relativeposition=midsize1-midsize2 var finalPosition=relativeposition-positionContent return finalPosition }; selfObj.moveImage =function(x,y){ selfObj.deslocationPositionXBackground=x*(-1) selfObj.deslocationPositionYBackground=y*(-1) selfObj.deslocationPositionXImgToCut=x*(-1) selfObj.deslocationPositionYImgToCut=y*(-1) selfObj.calcPosition() }; selfObj.viewImage =function(){ if (selfObj.activeViewImage){ selfObj.activeViewImage=false PG.cutterControlView.removeClass("actived") PG.cutterShadow.removeClass("actived") } else{ selfObj.activeViewImage=true PG.cutterControlView.addClass("actived") PG.cutterShadow.addClass("actived") }; }; selfObj.closeImage = function(){ PG.panelCutterContainer.removeClass("actived") PG.setTitleButton(PG.config.titleButton) PG.panelCutterContainer.addClass("close") }; selfObj.cutImage = function(){ var canvas = PG.targetView[0][0] canvas.width = selfObj.widthCutter canvas.height = selfObj.heightCutter var ctx = canvas.getContext('2d'); var ratio = selfObj.originalWidthImg/parseFloat(selfObj.widthImgAfterZoom) var positionX = selfObj.positionXAfterZoom * (-1) * ratio var positionY = selfObj.positionYAfterZoom * (-1) * ratio var wX = PG.cutterSizeX * ratio var wY = PG.cutterSizeY * ratio PG.uploadArea.removeClass("actived") ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(img1, positionX, positionY, wX, wY, 0, 0, selfObj.widthCutter, selfObj.widthCutter) if (PG._callAfterCut){ var imageCutObj={ originalImage:{ imageName:PG.imageName, imageType:PG.imageType, imageBytes:PG.imageBlob, imagemBase64Data:selfObj.base64data, cutterSizeX:PG.cutterSizeX, cutterSizeY:PG.cutterSizeY, positionX:selfObj.positionXAfterZoom, positionY:selfObj.positionYAfterZoom, newSizeX:selfObj.widthImgAfterZoom, newSizeY:selfObj.heightImgAfterZoom, }, cuttedImage:{ imageName:PG.imageName, imageType:PG.imageType, imageBase64Data:canvas.toDataURL(), imageBytes:"", } } canvas.toBlob(function(blob){ var new_name = imageCutObj.originalImage.imageName var pos = new_name.lastIndexOf("."); new_name = new_name.substr(0, pos < 0 ? new_name.length : pos) + ".png"; imageCutObj.cuttedImage.imageName = new_name imageCutObj.cuttedImage.imageType = "image/png" var file = new File([blob], new_name) imageCutObj.cuttedImage.imageBytes=file PG._callAfterCut(imageCutObj) }) } PG.panelCutterContainer.removeClass("actived") PG.setTitleButton(PG.config.titleButton) PG.panelCutterContainer.addClass("close") PG.targetViewContainer.addClass("actived") PG.imagecutedControlErase.on('click', function(){ ctx.clearRect(0, 0, canvas.width, canvas.height); PG.targetViewContainer.removeClass("actived") PG.uploadArea.addClass("actived") }); PG.imagecutedControlChange.on('click', function(){ PG.uploadArea.trigger('click'); }); }; selfObj.movecutterZoom =function(x, zoominicial, width, height){ selfObj.deslocationPositionZoom=x*(-1) selfObj.calcZoomPosition(zoominicial, width, height) }; selfObj.changeSizeImage =function(ratio, width, height){ width = parseFloat(width)*ratio height = parseFloat(height)*ratio img1.style.width=width+"px" img1.style.height=height+"px" img2.style.width=width+"px" img2.style.height=height+"px" selfObj.widthImg=width selfObj.heightImg=height selfObj.widthImgAfterZoom=width selfObj.heightImgAfterZoom=height selfObj.calcPosition(); }; selfObj.calcZoomPosition =function(zoominicial, width, height){ var position = selfObj.positionDefaultZoom-selfObj.deslocationPositionZoom var ratio=position/zoominicial selfObj.changeSizeImage(ratio, width, height) PG.cutterZoomControl[0][0].style.left=position+"px" }; selfObj.calcPosition =function(){ var widthImg=selfObj.widthImg; var heightImg=selfObj.heightImg; var widthScreen=window.innerWidth; var heightScreen=window.innerHeight var widthCutter=selfObj.widthCutter; var heightCutter=selfObj.heightCutter; if((widthImg>0)&&(heightImg>0)&&(widthScreen>0)&&(heightScreen>0)){ var fCalc = selfObj.calcMidPosition; var iPXB = selfObj.inicialPositionXBackground+selfObj.deslocationPositionXBackground; var iPYB = selfObj.inicialPositionYBackground+selfObj.deslocationPositionYBackground; var iPXITC = selfObj.inicialPositionXImgToCut+selfObj.deslocationPositionXImgToCut; var iPYITC = selfObj.inicialPositionYImgToCut+selfObj.deslocationPositionYImgToCut; var relativePositionXBackground=fCalc(widthScreen, widthImg, iPXB); var relativePositionYBackground=fCalc(heightScreen, heightImg, iPYB); var relativePositionXImgToCut=fCalc(widthCutter, widthImg, iPXITC); var relativePositionYImgToCut=fCalc(heightCutter, heightImg, iPYITC); PG.panelCutterSizeContainer[0][0].style.left=fCalc(widthScreen, widthCutter, 0)+"px"; PG.panelCutterSizeContainer[0][0].style.top=fCalc(heightScreen, heightCutter, 0)+"px"; PG.cutterBackground[0][0].style.left=relativePositionXBackground+"px"; PG.cutterBackground[0][0].style.top=relativePositionYBackground+"px"; PG.panelCutterImage[0][0].style.left=relativePositionXImgToCut+"px"; PG.panelCutterImage[0][0].style.top=relativePositionYImgToCut+"px"; selfObj.positionXAfterZoom=relativePositionXImgToCut; selfObj.positionYAfterZoom=relativePositionYImgToCut; }; }; selfObj.saveinicialPosition =function(){ selfObj.inicialPositionXBackground+=selfObj.deslocationPositionXBackground selfObj.inicialPositionYBackground+=selfObj.deslocationPositionYBackground selfObj.inicialPositionXImgToCut+=selfObj.deslocationPositionXImgToCut selfObj.inicialPositionYImgToCut+=selfObj.deslocationPositionYImgToCut selfObj.deslocationPositionXBackground=0 selfObj.deslocationPositionYBackground=0 selfObj.deslocationPositionXImgToCut=0 selfObj.deslocationPositionYImgToCut=0 }; selfObj.savePositionZoom = function(){ selfObj.positionDefaultZoom-=selfObj.deslocationPositionZoom selfObj.deslocationPositionZoom=0; }; selfObj.setBase64 = function(value){ selfObj.setBase64=value }; selfObj.activeViewImage = false PG.cutterControlView.removeClass("actived") PG.cutterShadow.removeClass("actived") PG.cutterZoomControl[0][0].style.left=89+"px" PG.cutterControlView.on('click', function(){ selfObj.viewImage(); }); PG.cutterControlClose.on('click', function(){ selfObj.closeImage(); }); PG.cutterControlCut.on('click', function(){ selfObj.cutImage(); }); img1.onload = function(){ imgWidth = this.width imgHeight = this.height selfObj.widthImg = imgWidth selfObj.heightImg = imgHeight selfObj.originalWidthImg = imgWidth selfObj.originalHeightImg = imgHeight selfObj.widthImgAfterZoom = imgWidth selfObj.heightImgAfterZoom = imgHeight selfObj.widthCutter = parseFloat(PG.cutterSizeX) selfObj.heightCutter = parseFloat(PG.cutterSizeY) if (PG.error){ PG.showMessage(PG.messages.invalidImage) PG.setTitleButton(PG.config.titleButton) PG.error=false } else { selfObj.calcPosition() PG.panelCutterContainer.removeClass("close") PG.panelCutterContainer.addClass("actived") } } img1.src=base64data img2.src=base64data window.addEventListener("resize", function(){ selfObj.calcPosition() }); PG.cutterPad.on('mousedown', function(event){ var xInicial = event.clientX; var yInicial = event.clientY; PG.cutterPad.on('mousemove', function(event){ var xDeslocamento = event.clientX-xInicial; var yDeslocamento = event.clientY-yInicial; selfObj.moveImage(xDeslocamento, yDeslocamento) }); PG.cutterPad.on('mouseup', function(event){ selfObj.saveinicialPosition() PG.cutterPad.on('mousemove', ''); PG.cutterPad.on('mouseleave', ''); }); PG.cutterPad.on('mouseleave', function(event){ selfObj.saveinicialPosition() PG.cutterPad.on('mousemove', ''); PG.cutterPad.on('mouseleave', ''); }); }); PG.cutterZoomControl.on('mousedown', function(event){ var xInicial = event.clientX; var inicialPosition = selfObj.positionDefaultZoom; var width = selfObj.widthImg var height = selfObj.heightImg PG.cutterZoomControl.on('mousemove', function(event){ var xDeslocamento = event.clientX-xInicial; if (((inicialPosition+xDeslocamento)>0)&&(inicialPosition+xDeslocamento)<179){ selfObj.movecutterZoom(xDeslocamento, inicialPosition, width, height) } }); PG.cutterZoomControl.on('mouseup', function(event){ selfObj.savePositionZoom() PG.cutterZoomControl.on('mousemove', ''); PG.cutterZoomControl.on('mouseleave', ''); }); PG.cutterZoomControl.on('mouseleave', function(event){ selfObj.savePositionZoom() PG.cutterZoomControl.on('mousemove', ''); PG.cutterZoomControl.on('mouseleave', ''); }); }); return selfObj } var phanterGallery = new (function(){ this.phanterGalleryObjs=[] this._config = { titleButton:"Upload Image", titleButtonSend:"Send Image", titleButtonProcessing:"Process...", titleButtonWaiting:"Waiting...", imgButton:"<i class=\"phantersvg upload-cloud\"></i>", }; this._messages = { invalidImage:"The image is invalid!", nameOfFileLong:"The filename is too long! Please demote before upload", fileCouldNotBeUploaded:"File could not be uploaded: %(name_file)s", }; this._callAfterCut = "" this.setCallAfterCut = function(script){ this._callAfterCut = script this._update(); }; this.config = function(obj){ for (x in obj) { this._config[x]=obj[x] } this._update(); return this._config }; this.messages = function(obj){ for (y in obj) { this._messages[y]=obj[y] } this._update(); return this._messages }; this._update = function(init){ if (init===false){ var elements = phanterQuery(".phantergallery_object")[0]; for (var i = 0; i < elements.length; i++) { var PG = new phanterGalleryObj(elements[i], this._config, this._messages) if(PG.uploadSrcImg!=""){ var img = new Image; img.src = PG.uploadSrcImg img.onload = function(){ var canvas = PG.targetView[0][0] canvas.width = PG.cutterSizeX canvas.height = PG.cutterSizeY var ctx = canvas.getContext("2d") ctx.drawImage(img, 0, 0) PG.imagecutedControlErase.on('click', function(){ ctx.clearRect(0, 0, canvas.width, canvas.height); PG.targetViewContainer.removeClass("actived") PG.uploadArea.addClass("actived") }); PG.imagecutedControlChange.on('click', function(){ PG.uploadArea.trigger('click'); }); } } var objArray = this.phanterGalleryObjs objArray.push(PG); } } else { var elements = phanterQuery(".phantergallery_object")[0]; for (var i = 0; i < elements.length; i++) { var PG = new phanterGalleryObj(elements[i], this._config, this._messages) PG._callAfterCut = this._callAfterCut PG.setImgButton(this._config.imgButton) PG.setTitleButton(this._config.titleButton) phanterSvgs.update() var objArray = this.phanterGalleryObjs objArray.push(PG); } } } this._update(true) return this })(); var phanterGalleryAjaxObj = function(url, objectToSend, callback){ var xhttp; xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { callback(this); } else{ throw "error in ajax send" } }; var imageBlob = "" var fd = new FormData(); for (x in objectToSend){ if (objectToSend[x] instanceof Blob){ imageBlob=objectToSend[x] } else { fd.append(x, objectToSend[x]); } } xhttp.open("POST", url, true); xhttp.send(fd, imageBlob); }
0d399ec0b7b7ce8d685c696f609de2ed2f6935e1
[ "Markdown", "Python", "JavaScript" ]
4
Markdown
PhanterJR/phantergallery
8cfc034e0e798afccdc986f0b7861d16b67eebbf
ac9512f1398d31e54903dc10bac7ac033b06cf4c
refs/heads/master
<file_sep>class CallingPlan < ActiveHash::Base self.data = [ { id: 1, name: '---' }, { id: 2, name: '従量制(かけ放題等の契約なし)' }, { id: 3, name: '5分通話無料オプション' }, { id: 4, name: 'かけ放題' } ] end <file_sep>class CurrentPhone < ActiveHash::Base self.data = [ { id: 1, name: '---' }, { id: 2, name: 'docomo' }, { id: 3, name: 'au' }, { id: 4, name: 'softbank' }, { id: 5, name: 'その他' } ] end <file_sep>class Simulation < ApplicationRecord extend ActiveHash::Associations::ActiveRecordExtensions #belongs_to_active_hash :current_phone #belongs_to_active_hash :calling_plan belongs_to_active_hash :data_traffic belongs_to_active_hash :generation #belongs_to_active_hash :number belongs_to_active_hash :optical_line validates :duration_of_call, presence: true validates :generation_id, presence: true validates :data_traffic_id, presence: true validates :family_docomo, presence: true validates :family_au, presence: true validates :family_softbank, presence: true validates :optical_line_id, presence: true end <file_sep>class AddFamilyDocomoToSimulations < ActiveRecord::Migration[6.0] def change add_column :simulations, :family_docomo, :integer add_column :simulations, :family_softbank, :integer remove_column :simulations, :family_mobile, :integer rename_column :simulations, :unit, :family_au end end <file_sep>function price_simu(){ //通信キャリア名 const rank1_name = document.getElementById("1st-carrier-name"); const rank2_name = document.getElementById("2nd-carrier-name"); const rank3_name = document.getElementById("3rd-carrier-name"); const rank4_name = document.getElementById("4th-carrier-name"); //合計金額 const rank1_fee = document.getElementById("1st-carrier-fee"); const rank2_fee = document.getElementById("2nd-carrier-fee"); const rank3_fee = document.getElementById("3rd-carrier-fee"); const rank4_fee = document.getElementById("4th-carrier-fee"); //通話プラン金額 const rank1_calling_fee = document.getElementById("1st-calling-fee"); const rank2_calling_fee = document.getElementById("2nd-calling-fee"); const rank3_calling_fee = document.getElementById("3rd-calling-fee"); const rank4_calling_fee = document.getElementById("4th-calling-fee"); //通信プラン金額 const rank1_data_fee = document.getElementById("1st-data-fee"); const rank2_data_fee = document.getElementById("2nd-data-fee"); const rank3_data_fee = document.getElementById("3rd-data-fee"); const rank4_data_fee = document.getElementById("4th-data-fee"); //家族割金額 const rank1_family_discount = document.getElementById("1st-family-discount"); const rank2_family_discount = document.getElementById("2nd-family-discount"); const rank3_family_discount = document.getElementById("3rd-family-discount"); const rank4_family_discount = document.getElementById("4th-family-discount"); //光回線セット割金額 const rank1_optical_line_discount = document.getElementById("1st-optical-line-discount"); const rank2_optical_line_discount = document.getElementById("2nd-optical-line-discount"); const rank3_optical_line_discount = document.getElementById("3rd-optical-line-discount"); const rank4_optical_line_discount = document.getElementById("4th-optical-line-discount"); if ('addEventListener' in document) { document.addEventListener('DOMContentLoaded', function() { FastClick.attach(document.body); }, false); } //のりかえ割 //let docomo_trans_discount = 0; //let au_trans_discount = 0; //let softbank_trans_discount = 0; //let rakuten_trans_discount = 0; //const carrier_list = document.getElementsByName('current_phone'); //carrier_list.forEach(function(e) { //e.addEventListener("click", function() { //const current_carrier = document.querySelector("input:checked[name=current_phone]").value; //実装途中 //}); //}); //console.log(); //通話プラン選択 let docomo_calling_fee = 0; let au_calling_fee = 0; let softbank_calling_fee = 0; let rakuten_calling_fee = 0; const calling_plan_list = document.getElementsByName('simulation[duration_of_call]'); calling_plan_list.forEach(function(e) { e.addEventListener("click", function() { const calling_plan = document.querySelector("input:checked[name*=duration_of_call]").value; console.log(calling_plan); switch (calling_plan) { case "1": docomo_calling_fee = 0; au_calling_fee = 0; softbank_calling_fee = 0; rakuten_calling_fee = 0; break; case "2": docomo_calling_fee = 700; au_calling_fee = 800; softbank_calling_fee = 800; rakuten_calling_fee = 0; break; case "3": docomo_calling_fee = 1700; au_calling_fee = 1800; softbank_calling_fee = 1800; rakuten_calling_fee = 0; break; } fee_calc(); }); }); //通信データ量選択 let docomo_data_fee = 0; let au_data_fee = 0; let softbank_data_fee = 0; let rakuten_data_fee = 0; generation.addEventListener('input', () => { const generation = document.getElementById("generation").value; if (generation != 1) { document.getElementById("generation").classList.add("select-box-checked"); }else{ document.getElementById("generation").classList.remove("select-box-checked"); document.getElementById("generation").classList.add("select-box"); } datafee_calc(); fee_calc(); }); data_traffic.addEventListener('input', () => { const data_traffic = document.getElementById("data_traffic").value; if (data_traffic != 1) { document.getElementById("data_traffic").classList.add("select-box-checked"); }else{ document.getElementById("data_traffic").classList.remove("select-box-checked"); document.getElementById("data_traffic").classList.add("select-box"); } datafee_calc(); fee_calc(); }); function datafee_calc(){ const generation = document.getElementById("generation").value; const data_traffic = document.getElementById("data_traffic").value; switch (generation) { case "2": //4G switch (data_traffic) { case "2": //~1GB docomo_data_fee = 3150; au_data_fee = 3150; softbank_data_fee = 3980; rakuten_data_fee = 2980; break; case "3": //~2GB docomo_data_fee = 4150; au_data_fee = 4650; softbank_data_fee = 5980; rakuten_data_fee = 2980; break; case "4": //~3GB docomo_data_fee = 4150; au_data_fee = 4650; softbank_data_fee = 7480; rakuten_data_fee = 2980; break; case "5": //~4GB docomo_data_fee = 5150; au_data_fee = 4650; softbank_data_fee = 7480; rakuten_data_fee = 2980; break; case "6": //~5GB docomo_data_fee = 5150; au_data_fee = 6150; softbank_data_fee = 7480; rakuten_data_fee = 2980; break; case "7": //~7GB docomo_data_fee = 6150; au_data_fee = 6150; softbank_data_fee = 7480; rakuten_data_fee = 2980; break; case "8","9","10","11": //30GB~ docomo_data_fee = 7150; au_data_fee = 7650; softbank_data_fee = 7480; rakuten_data_fee = 2980; break; } case "3": //5G switch (data_traffic) { case "2": //~1GB docomo_data_fee = 3150; au_data_fee = 4150; softbank_data_fee = 4980; rakuten_data_fee = 2980; break; case "3": //~2GB docomo_data_fee = 4150; au_data_fee = 5650; softbank_data_fee = 6980; rakuten_data_fee = 2980; break; case "4": //~3GB docomo_data_fee = 4150; au_data_fee = 5650; softbank_data_fee = 8480; rakuten_data_fee = 2980; break; case "5": //~4GB docomo_data_fee = 5150; au_data_fee = 5650; softbank_data_fee = 8480; rakuten_data_fee = 2980; break; case "6": //~5GB docomo_data_fee = 5150; au_data_fee = 7150; softbank_data_fee = 8480; rakuten_data_fee = 2980; break; case "7": //~7GB docomo_data_fee = 6150; au_data_fee = 7150; softbank_data_fee = 8480; rakuten_data_fee = 2980; break; case "8","9","10","11": //30GB~ docomo_data_fee = 7650; au_data_fee = 8650; softbank_data_fee = 8480; rakuten_data_fee = 2980; break; } } } //家族割適用 let family_discount_docomo = 0; let family_discount_au = 0; let family_discount_softbank = 0; let family_discount_rakuten = 0; const family_docomo_list = document.getElementsByName('simulation[family_docomo]'); //console.log(family_docomo_list); family_docomo_list.forEach(function(e) { e.addEventListener("click", function() { //console.log(e); const family_docomo = document.querySelector("input:checked[name*=family_docomo]").value; //console.log(family_docomo); switch (family_docomo) { case "1": family_discount_docomo = 0; break; case "2": family_discount_docomo = -500; break; case "3": family_discount_docomo = -1000; break; } fee_calc(); }); }); const family_au_list = document.getElementsByName('simulation[family_au]'); family_au_list.forEach(function(e) { e.addEventListener("click", function() { const family_au = document.querySelector("input:checked[name*=family_au]").value; const data_traffic = document.getElementById("data_traffic").value; switch (family_au) { case "1": family_discount_au = 0; break; case "2": family_discount_au = -500; break; case "3": family_discount_au = -1000; break; case "4": console.log(data_traffic); switch (data_traffic) { case "2","3","4","5","6","7": family_discount_au = -1000; break; case "8","9","10","11": family_discount_au = -2020; break; } } fee_calc(); }); }); const family_softbank_list = document.getElementsByName('simulation[family_softbank]'); family_softbank_list.forEach(function(e) { e.addEventListener("click", function() { const family_softbank = document.querySelector("input:checked[name*=family_softbank]").value; switch (family_softbank) { case "1": family_discount_softbank = 0; break; case "2": family_discount_softbank = -500; break; case "3": family_discount_softbank = -1500; break; case "4": family_discount_softbank = -2000; break; } fee_calc(); }); }); //光回線セット割選択 let optical_line_discount_docomo = 0; let optical_line_discount_au = 0; let optical_line_discount_softbank = 0; let optical_line_discount_rakuten = 0; optical_line.addEventListener('input', () => { const optical_line = document.getElementById("optical_line").value; if (optical_line != 1) { document.getElementById("optical_line").classList.add("select-box-checked"); }else{ document.getElementById("optical_line").classList.remove("select-box-checked"); document.getElementById("optical_line").classList.add("select-box"); } switch (optical_line) { case "1": optical_line_discount_docomo = 0; optical_line_discount_au = 0; optical_line_discount_softbank = 0; break; case "2": optical_line_discount_docomo = -1000; optical_line_discount_au = 0; optical_line_discount_softbank = 0; break; case "3": optical_line_discount_docomo = 0; optical_line_discount_au = -1000; optical_line_discount_softbank = 0; break; case "4": optical_line_discount_docomo = 0; optical_line_discount_au = 0; optical_line_discount_softbank = -1000; break; } fee_calc(); }); //金額計算&金額出力 function fee_calc(){ let docomo_fee = docomo_calling_fee + docomo_data_fee + family_discount_docomo + optical_line_discount_docomo; let au_fee = au_calling_fee + au_data_fee + family_discount_au + optical_line_discount_au; let softbank_fee = softbank_calling_fee + softbank_data_fee + family_discount_softbank + optical_line_discount_softbank; let rakuten_fee = rakuten_calling_fee + rakuten_data_fee + family_discount_rakuten + optical_line_discount_rakuten; let ranking = [ {name: "docomo", fee: docomo_fee, calling_fee: docomo_calling_fee, data_fee: docomo_data_fee, family_discount: family_discount_docomo, optical_line_discount: optical_line_discount_docomo}, {name: "au", fee: au_fee, calling_fee: au_calling_fee, data_fee: au_data_fee, family_discount: family_discount_au, optical_line_discount: optical_line_discount_au}, {name: "softbank", fee: softbank_fee, calling_fee: softbank_calling_fee, data_fee: softbank_data_fee, family_discount: family_discount_softbank, optical_line_discount: optical_line_discount_softbank}, {name: "rakuten", fee: rakuten_fee, calling_fee: rakuten_calling_fee, data_fee: rakuten_data_fee, family_discount: family_discount_rakuten, optical_line_discount: optical_line_discount_rakuten} ]; ranking.sort(function( a, b ){ if( a.fee < b.fee ) return -1; if( a.fee > b.fee ) return 1; return 0; }); //通信キャリア名 rank1_name.textContent = ranking[0].name; rank2_name.textContent = ranking[1].name; rank3_name.textContent = ranking[2].name; rank4_name.textContent = ranking[3].name; //合計金額 rank1_fee.textContent = ranking[0].fee + "円"; rank2_fee.textContent = ranking[1].fee + "円"; rank3_fee.textContent = ranking[2].fee + "円"; rank4_fee.textContent = ranking[3].fee + "円"; //通話料金 rank1_calling_fee.textContent = ranking[0].calling_fee + "円"; rank2_calling_fee.textContent = ranking[1].calling_fee + "円"; rank3_calling_fee.textContent = ranking[2].calling_fee + "円"; rank4_calling_fee.textContent = ranking[3].calling_fee + "円"; //データ通信料金 rank1_data_fee.textContent = ranking[0].data_fee + "円"; rank2_data_fee.textContent = ranking[1].data_fee + "円"; rank3_data_fee.textContent = ranking[2].data_fee + "円"; rank4_data_fee.textContent = ranking[3].data_fee + "円"; //家族割料金 rank1_family_discount.textContent = ranking[0].family_discount + "円"; rank2_family_discount.textContent = ranking[1].family_discount + "円"; rank3_family_discount.textContent = ranking[2].family_discount + "円"; rank4_family_discount.textContent = ranking[3].family_discount + "円"; //光回線セット割料金 rank1_optical_line_discount.textContent = ranking[0].optical_line_discount + "円"; rank2_optical_line_discount.textContent = ranking[1].optical_line_discount + "円"; rank3_optical_line_discount.textContent = ranking[2].optical_line_discount + "円"; rank4_optical_line_discount.textContent = ranking[3].optical_line_discount + "円"; } } window.addEventListener('load', price_simu);<file_sep># アプリ名 #### Mobile Service Simulation ##### (通称:Myモシモシ) ※Mobile Service Simulation の「Mo」と「Si」から「モシ」が来て、携帯比較がテーマのアプリなので「モシモシ」としました。そして、利用者それぞれがシミュレーション結果を見れるということで、先頭に「My」をつけ、「Myモシモシ」という通称にしました。 <br> <br> # アプリケーション概要 携帯通信会社(docomoなど)各社の料金プランと利用サービスの料金を比較できるアプリケーションです。現在、実装中の段階です。 <br> <br> # URL https://mymosimosi.com/ <br> <br> # 利用方法 ### 【料金プランのシミュレーション実行】 ①トップページの「シミュレーションする」ボタンを押下します。 <br> ②料金プランのシミュレーション画面にはiPhoneとiPadがございますが、iPhoneの画面を模した箇所で料金プラン等入力いただき、iPadの画面を模した箇所にシミュレーション結果を表示します。 <br> ③シミュレーション結果詳細ボタンを押下することで、シミュレーション結果の詳細(料金の根拠など)が閲覧できます。なお、ボタンを押下することでシミュレーション結果のデータベースへの保存が完了します。※実装中 <br> ### 【シミュレーション結果を見返す】※実装中 ①トップページの「履歴を見る」ボタンを押下します。 <br> ②シミュレーション履歴が一覧で表示されます。シミュレーション結果へのリンクを押下することで、シミュレーション結果詳細が閲覧できます。 <br> # 目指した課題解決 昨今、携帯電話の料金プランは大変複雑です。それに加え、携帯各社が様々なサービスと連携して料金を割り引くキャンペーンが実施されています。そのため、自身の携帯の利用状況と様々なサービスの利用状況を考慮した場合、結局、どの会社が安いのかを導き出すことは困難を極める状況でした。そうした課題解決をするべく、このアプリケーションを作成しました。 <br> <br> # 要件定義(実装機能) ### 料金比較機能 ##### 《実装済み》 ・通話料金比較機能<br> ・データ通信料金比較機能<br> ・家族割料金比較機能<br> ・光回線セット割料金比較機能<br> ##### 《実装予定》 【優先度:高】<br> ・利用サービス(Netflix/DAZN等)を加味した料金比較機能<br> 【優先度:中】<br> ・料金の根拠(プラン名等)表示機能<br> 【優先度:低】<br> ・利用ECサイトを加味した料金比較機能<br> ・利用クレジットカードを加味した料金比較機能<br> ・利用電子マネー/QRコード決済を加味した料金比較機能<br> ・利用銀行を加味した料金比較機能<br> ・MVNOを含めた料金比較機能<br> ### データ保存機能 ##### 《実装予定》 【優先度:高】<br> ・料金比較データ保存機能<br> ### データ詳細表示機能 ##### 《実装予定》 【優先度:高】<br> ・料金比較データ詳細表示機能<br> ### アプリ効率化/見易さ向上のための実装 ##### 《実装予定》 【優先度:高】<br> ・サイトのhttps化<br> 【優先度:中】<br> ・最安値強調処理<br> ・レスポンシブデザイン<br> ・JSによる動的な表作成<br> 【優先度:低】<br> ・スクレイピングによる比較データ取得<br> ・金額の変化が動的に動く処理<br> ・選択肢の注釈ボタン<br> ・キャリアやサービスのロゴを本物にする<br> ・料金以外の要素についての記述(ex.データ通信費最安だが遅い懸念あり)実装<br> ・シミュレーション結果のSNS連携<br> ・各社の料金詳細ページ実装<br> ・比較結果をもとに契約を行うページへ遷移する<br> <file_sep>class Number < ActiveHash::Base self.data = [ { id: 1, name: '0台' }, { id: 2, name: '1台' }, { id: 3, name: '2台' }, { id: 4, name: '3台以上' } ] end <file_sep>class DataTraffic < ActiveHash::Base self.data = [ { id: 1, name: '想定データ通信量' }, { id: 2, name: '〜1GB' }, { id: 3, name: '〜2GB' }, { id: 4, name: '〜3GB' }, { id: 5, name: '〜4GB' }, { id: 6, name: '〜5GB' }, { id: 7, name: '〜7GB' }, { id: 8, name: '〜30GB' }, { id: 9, name: '〜50GB' }, { id: 10, name: '〜100GB' }, { id: 11, name: '100GB以上' } ] end <file_sep>class RenameGenerationColumnToSimulations < ActiveRecord::Migration[6.0] def change rename_column :simulations, :generation, :generation_id end end <file_sep>class AddUnitToSimulations < ActiveRecord::Migration[6.0] def change add_column :simulations, :unit, :integer end end <file_sep>class SimulationsController < ApplicationController def index end def new @simulation = Simulation.new end def create @simulation = Simulation.new(simulation_params) if @simulation.save redirect_to simulation_path(@simulation.id) else render :new end end def edit end def show end private def simulation_params params.require(:simulation).permit(:current_phone_id, :duration_of_call, :generation_id, :data_traffic_id, :family_docomo, :family_au, :family_softbank, :optical_line_id) end end <file_sep>class RenameDataTrafficColumnToSimulations < ActiveRecord::Migration[6.0] def change rename_column :simulations, :data_traffic, :data_traffic_id rename_column :simulations, :optical_line, :optical_line_id end end <file_sep>class OpticalLine < ActiveHash::Base self.data = [ { id: 1, name: '契約なし' }, { id: 2, name: 'ドコモ光' }, { id: 3, name: 'auひかり' }, { id: 4, name: 'softbank光' } ] end <file_sep>class CreateSituations < ActiveRecord::Migration[6.0] def change create_table :situations do |t| t.integer :duration_of_call t.integer :data_traffic t.integer :family_mobile t.integer :optical_line t.integer :service t.integer :ecsite t.integer :creditcard t.integer :electronic_money t.integer :qr_payment t.integer :bank t.references :user, foreign_key: true t.timestamps end end end
41155703571d1666f368016a77ceb6781dacbb22
[ "JavaScript", "Ruby", "Markdown" ]
14
Ruby
yutaro-nakaji/mobile_service_comparison
caaaada2ab620416c77ee40d47e94d6f859f4d81
f22d08fbd9c87944f489b0da4609904477a8cebb
refs/heads/master
<file_sep>sbtgen ====== Little script for generating an sbt directory structure. <file_sep>#!/usr/bin/env ruby require "fileutils" include FileUtils if project_name = ARGV[0] puts "Creating #{project_name} directory" mkdir project_name Dir.chdir project_name else project_name = Dir.pwd[/(\w+)$/,1] puts "Project name not given." puts "Generate sbt structure under current directory with project name: #{project_name}? (y/n)" res = gets.chomp exit if res == "n" end puts "Generating project structure" build_sbt_content = <<-EOS name := "#{project_name}" version := "1.0" scalaVersion := "2.10.2" EOS gitignore_content = <<-EOS *.class *.log # sbt specific dist/* target/ lib_managed/ src_managed/ project/boot/ project/plugins/project/ # Scala-IDE specific .scala_dependencies # Eclipse specific .project .classpath .cache .settings EOS File.open("build.sbt", "w") { |f| f.puts build_sbt_content } File.open(".gitignore", "w") { |f| f.puts gitignore_content } mkdir_p "lib" mkdir "project" touch "project/Build.scala" ["main", "test"].each do |mt| ["resources", "scala", "java"].each do |rsj| mkdir_p "src/#{mt}/#{rsj}" end end
529f7f9f5155628d059e2623000e5efecf321c17
[ "Markdown", "Ruby" ]
2
Markdown
moniyax/sbtgen
4ef79d6d997cd58abe5a0f5978b2c6c9c3e10112
b0a3dac1379cac9675336358b0832f3c035255c8
refs/heads/master
<repo_name>thigiacmaytinh/RawImageConverter<file_sep>/Cr2Converter/Form1.cs using Microsoft.VisualBasic.FileIO; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using TGMTcs; namespace Cr2Converter { public partial class Form1 : Form { string m_ext = ".jpg"; //////////////////////////////////////////////////////////////////////////////////////////////////// public Form1() { InitializeComponent(); lblMessage.Text = ""; progressBar.Visible = false; } //////////////////////////////////////////////////////////////////////////////////////////////////// private void Form1_Load(object sender, EventArgs e) { TGMTregistry.GetInstance().Init("TGMT cr2 to jpg"); chkOverwrite.Checked = TGMTregistry.GetInstance().ReadRegValueBool("chkOverwrite"); chkRotate.Checked = TGMTregistry.GetInstance().ReadRegValueBool("chkRotate"); chkDelete.Checked = TGMTregistry.GetInstance().ReadRegValueBool("chkDelete"); chkResize.Checked = TGMTregistry.GetInstance().ReadRegValueBool("chkResize"); chkKeepAspect.Checked = TGMTregistry.GetInstance().ReadRegValueBool("chkKeepAspect"); numWidth.Value = TGMTregistry.GetInstance().ReadRegValueInt("numWidth"); numHeight.Value = TGMTregistry.GetInstance().ReadRegValueInt("numHeight"); this.KeyPreview = true; } //////////////////////////////////////////////////////////////////////////////////////////////////// private void buttonCr2Folder_Click(object sender, EventArgs e) { FolderBrowserDialog d = new FolderBrowserDialog(); d.RootFolder = Environment.SpecialFolder.Desktop; d.ShowNewFolderButton = false; d.Description = "Choose a folder containing raw (.CR2) files:"; if (DialogResult.OK == d.ShowDialog()) { txtInputDir.Text = d.SelectedPath; } } //////////////////////////////////////////////////////////////////////////////////////////////////// private void buttonExtractJPG_Click(object sender, EventArgs e) { if(lstCr2.Items.Count == 0) { return; } progressBar.Visible = true; progressBar.Value = 0; lblMessage.Text = "Processing..."; int nbExtracted = 0; foreach (ListViewItem item in lstCr2.Items) { string filePath = item.Text; if (File.Exists(filePath)) { string baseName = Path.GetFileNameWithoutExtension(filePath); string outDir = Path.GetDirectoryName(filePath) + "\\"; baseName = outDir + baseName; string jpgName = baseName + m_ext; if (!chkOverwrite.Checked && File.Exists(jpgName)) { int version = 1; do { jpgName = String.Format("{0}_{1}" + m_ext, baseName, version); ++version; } while (File.Exists(jpgName)); } Size size = new Size(); if(chkResize.Checked ) { if(chkKeepAspect.Checked && numWidth.Value > 0 ) size = new Size((int)numWidth.Value, 0); else if(numWidth.Value > 0 && numHeight.Value > 0) size = new Size((int)numWidth.Value, (int)numHeight.Value); } if(TGMTimage.ConvertCr2(filePath, jpgName, chkRotate.Checked, size)) { progressBar.Value = ++nbExtracted; if (item.SubItems.Count == 1) { item.SubItems.Add("done"); } else { item.SubItems[1].Text = "done"; } item.ForeColor = Color.Green; if (chkDelete.Checked) { FileSystem.DeleteFile(filePath, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin); } } } else //file does not exist { if (item.SubItems.Count == 1) { item.SubItems.Add("File not exist"); } else { item.SubItems[1].Text = "File not exist"; } item.ForeColor = Color.Red; } } lblMessage.Text = "Complete"; progressBar.Visible = false; } //////////////////////////////////////////////////////////////////////////////////////////////////// private void txtInputDir_TextChanged(object sender, EventArgs e) { try { string[] cr2Files = Directory.GetFiles(txtInputDir.Text, "*.CR2"); if (cr2Files.Length > 0) { for (int i = 0; i != cr2Files.Length; ++i) { lstCr2.Items.Add(cr2Files[i]); } progressBar.Maximum = cr2Files.Length; } else { lblMessage.Text = "No raw (.CR2) files in folder."; } } catch (DirectoryNotFoundException) { lblMessage.Text = "Invalid folder name."; } progressBar.Value = 0; } //////////////////////////////////////////////////////////////////////////////////////////////////// private void Form1_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; } //////////////////////////////////////////////////////////////////////////////////////////////////// private void Form1_DragDrop(object sender, DragEventArgs e) { string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); for (int i = 0; i < files.Length; i++) { string f = files[i]; string ext = Path.GetExtension(f); if (ext.ToLower() == ".cr2") { lstCr2.Items.Add(f); } } btnExtractJPG.Enabled = lstCr2.Items.Count > 0; } //////////////////////////////////////////////////////////////////////////////////////////////////// private void chkDelete_CheckedChanged(object sender, EventArgs e) { TGMTregistry.GetInstance().SaveRegValue("chkDelete", chkDelete.Checked); } //////////////////////////////////////////////////////////////////////////////////////////////////// private void chkOverwrite_CheckedChanged(object sender, EventArgs e) { TGMTregistry.GetInstance().SaveRegValue("chkOverwrite", chkOverwrite.Checked); } //////////////////////////////////////////////////////////////////////////////////////////////////// private void chkRotate_CheckedChanged(object sender, EventArgs e) { TGMTregistry.GetInstance().SaveRegValue("chkRotate", chkRotate.Checked); } //////////////////////////////////////////////////////////////////////////////////////////////////// void ShortcutKey(KeyEventArgs e) { if (e.Control && e.KeyCode == Keys.A) { foreach (ListViewItem item in lstCr2.Items) { item.Selected = true; } } else if (e.KeyCode == Keys.Delete) { foreach (ListViewItem item in lstCr2.SelectedItems) { item.Remove(); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// private void Form1_KeyUp(object sender, KeyEventArgs e) { ShortcutKey(e); } //////////////////////////////////////////////////////////////////////////////////////////////////// private void lstCr2_KeyUp(object sender, KeyEventArgs e) { ShortcutKey(e); } //////////////////////////////////////////////////////////////////////////////////////////////////// private void chkResize_CheckedChanged(object sender, EventArgs e) { numWidth.Enabled = chkResize.Checked; numHeight.Enabled = chkResize.Checked; chkKeepAspect.Enabled = chkResize.Checked; TGMTregistry.GetInstance().SaveRegValue("chkResize", chkResize.Checked); } //////////////////////////////////////////////////////////////////////////////////////////////////// private void chkKeepAspect_CheckedChanged(object sender, EventArgs e) { numHeight.Enabled = !chkKeepAspect.Checked; numHeight.Value = 0; TGMTregistry.GetInstance().SaveRegValue("chkKeepAspect", chkKeepAspect.Checked); } //////////////////////////////////////////////////////////////////////////////////////////////////// private void numWidth_ValueChanged(object sender, EventArgs e) { TGMTregistry.GetInstance().SaveRegValue("numWidth", numWidth.Value); } //////////////////////////////////////////////////////////////////////////////////////////////////// private void numHeight_ValueChanged(object sender, EventArgs e) { TGMTregistry.GetInstance().SaveRegValue("numHeight", numHeight.Value); } //////////////////////////////////////////////////////////////////////////////////////////////////// private void rdJpg_CheckedChanged(object sender, EventArgs e) { m_ext = ".jpg"; } //////////////////////////////////////////////////////////////////////////////////////////////////// private void rdPng_CheckedChanged(object sender, EventArgs e) { m_ext = ".png"; } } } <file_sep>/README.md # RawImageConverter Convert raw image from digital camera (Canon, Nikon) to JPEG <file_sep>/Cr2Converter/TGMTregistry.cs using Microsoft.Win32; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace TGMTcs { public class TGMTregistry { static TGMTregistry m_instance; RegistryKey m_regKey; public bool Inited { get; set; } //////////////////////////////////////////////////////////////////////////////////////////////////////// public TGMTregistry() { } //////////////////////////////////////////////////////////////////////////////////////////////////////// public static TGMTregistry GetInstance() { if (m_instance == null) m_instance = new TGMTregistry(); return m_instance; } //////////////////////////////////////////////////////////////////////////////////////////////////////// public void Init(string key) { m_regKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\" + key, true); if (m_regKey == null) { Registry.CurrentUser.OpenSubKey("SOFTWARE", true).CreateSubKey(key); m_regKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\" + key, true); } Inited = true; } //////////////////////////////////////////////////////////////////////////////////////////////////////// public void DeleteKey(string value) { m_regKey.DeleteValue(value); } //////////////////////////////////////////////////////////////////////////////////////////////////////// public void SaveRegValue(string key, object value) { m_regKey.SetValue(key, value); } //////////////////////////////////////////////////////////////////////////////////////////////////////// public string ReadRegValueString(string key, string defaultData ="") { Object data = m_regKey.GetValue(key); if (data == null) return defaultData; else return (string)data; } //////////////////////////////////////////////////////////////////////////////////////////////////////// public int ReadRegValueInt(string key, int defaultData = 0) { Object data = m_regKey.GetValue(key); if (data == null) return defaultData; else return int.Parse(data.ToString()); } //////////////////////////////////////////////////////////////////////////////////////////////////////// public bool ReadRegValueBool(string key, bool defaultData = false) { return ReadRegValueString(key) == "True"; } //////////////////////////////////////////////////////////////////////////////////////////////////////// public float ReadRegValueFloat(string key, float defaultData = 0) { Object data = m_regKey.GetValue(key); if (data == null) return defaultData; else return float.Parse((string)data); } } } <file_sep>/Cr2Converter/TGMTimage.cs using Microsoft.VisualBasic; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TGMTcs { class TGMTimage { const int BUF_SIZE = 512 * 1024; static byte[] buffer = new byte[BUF_SIZE]; static ImageCodecInfo m_codecJpeg; public static Bitmap CorrectOrientation(Bitmap bmp) { if (Array.IndexOf(bmp.PropertyIdList, 274) > -1) { var orientation = (int)bmp.GetPropertyItem(274).Value[0]; switch (orientation) { case 1: // No rotation required. break; case 2: bmp.RotateFlip(RotateFlipType.RotateNoneFlipX); break; case 3: bmp.RotateFlip(RotateFlipType.Rotate180FlipNone); break; case 4: bmp.RotateFlip(RotateFlipType.Rotate180FlipX); break; case 5: bmp.RotateFlip(RotateFlipType.Rotate90FlipX); break; case 6: bmp.RotateFlip(RotateFlipType.Rotate90FlipNone); break; case 7: bmp.RotateFlip(RotateFlipType.Rotate270FlipX); break; case 8: bmp.RotateFlip(RotateFlipType.Rotate270FlipNone); break; } // This EXIF data is now invalid and should be removed. bmp.RemovePropertyItem(274); } return bmp; } //////////////////////////////////////////////////////////////////////////////////////////////////// public static string ImageToBase64(string filename) { FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read); byte[] filebytes = new byte[fs.Length]; fs.Read(filebytes, 0, Convert.ToInt32(fs.Length)); fs.Close(); return "data:image/png;base64," + Convert.ToBase64String(filebytes, Base64FormattingOptions.None); } //////////////////////////////////////////////////////////////////////////////////////////////////// public static bool ConvertCr2(string inputPath, string outputPath, bool rotateIfNeeded, Size size) { if (!File.Exists(inputPath)) return false; FileStream fi = new FileStream(inputPath, FileMode.Open, FileAccess.Read, FileShare.Read, BUF_SIZE, FileOptions.None); // Start address is at offset 0x62, file size at 0x7A, orientation at 0x6E fi.Seek(0x62, SeekOrigin.Begin); BinaryReader br = new BinaryReader(fi); uint jpgStartPosition = br.ReadUInt32(); // 62 br.ReadUInt32(); // 66 br.ReadUInt32(); // 6A uint orientation = br.ReadUInt32() & 0x000000FF; // 6E br.ReadUInt32(); // 72 br.ReadUInt32(); // 76 int fileSize = br.ReadInt32(); // 7A fi.Seek(jpgStartPosition, SeekOrigin.Begin); if (fi.ReadByte() != 0xFF || fi.ReadByte() != 0xD8) { fi.Close(); return false; } else { Bitmap bmp = new Bitmap(new PartialStream(fi, jpgStartPosition, fileSize)); //resize if (!size.IsEmpty) { int width = size.Width; int height = size.Height; if (height == 0) { double aspect = (double)bmp.Width / bmp.Height; height = (int)(width / aspect); } Bitmap result = new Bitmap(width, height); using (Graphics g = Graphics.FromImage(result)) { g.DrawImage(bmp, 0, 0, width, height); } bmp = result; } //rotate if (rotateIfNeeded) { if (orientation == 8) bmp.RotateFlip(RotateFlipType.Rotate270FlipNone); else if (orientation == 6) bmp.RotateFlip(RotateFlipType.Rotate90FlipNone); } string ext = outputPath.Substring(outputPath.Length - 3); if(ext == "jpg") { //save jpg bmp.Save(outputPath, ImageFormat.Jpeg); } else { //save png bmp.Save(outputPath, ImageFormat.Png); } } fi.Close(); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////// private static ImageCodecInfo GetJpegCodec() { foreach (ImageCodecInfo c in ImageCodecInfo.GetImageEncoders()) { if (c.CodecName.ToLower().Contains("jpeg") || c.FilenameExtension.ToLower().Contains("*.jpg") || c.FormatDescription.ToLower().Contains("jpeg") || c.MimeType.ToLower().Contains("image/jpeg")) return c; } return null; } //////////////////////////////////////////////////////////////////////////////////////////////////// class PartialStream : Stream // Fun solution and experiment... probably not the best idea here { internal PartialStream(FileStream p_f, uint p_start, int p_length) { m_f = p_f; m_start = p_start; m_length = p_length; m_f.Seek(p_start, SeekOrigin.Begin); } FileStream m_f; uint m_start; int m_length; public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return m_f.BeginRead(buffer, offset, count, callback, state); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return m_f.BeginWrite(buffer, offset, count, callback, state); } public override bool CanRead { get { return m_f.CanRead; } } public override bool CanSeek { get { return m_f.CanSeek; } } public override bool CanTimeout { get { return m_f.CanTimeout; } } public override bool CanWrite { get { return m_f.CanWrite; } } public override void Close() { m_f.Close(); } public override System.Runtime.Remoting.ObjRef CreateObjRef(Type requestedType) { return m_f.CreateObjRef(requestedType); } protected override void Dispose(bool disposing) { //m_f.Dispose(disposing); // Can't... base.Dispose(disposing); } public override int EndRead(IAsyncResult asyncResult) { return m_f.EndRead(asyncResult); } public override void EndWrite(IAsyncResult asyncResult) { m_f.EndWrite(asyncResult); } public override bool Equals(object obj) { return m_f.Equals(obj); } public override void Flush() { m_f.Flush(); } public override int GetHashCode() { return m_f.GetHashCode(); } public override object InitializeLifetimeService() { return m_f.InitializeLifetimeService(); } public override long Length { get { return m_length; } } public override long Position { get { return m_f.Position - m_start; } set { m_f.Position = value + m_start; } } public override int Read(byte[] buffer, int offset, int count) { long maxRead = Length - Position; return m_f.Read(buffer, offset, (count <= maxRead) ? count : (int)maxRead); } public override int ReadByte() { if (Position < Length) return m_f.ReadByte(); else return 0; } public override int ReadTimeout { get { return m_f.ReadTimeout; } set { m_f.ReadTimeout = value; } } public override void SetLength(long value) { m_f.SetLength(value); } public override string ToString() { return m_f.ToString(); } public override void Write(byte[] buffer, int offset, int count) { m_f.Write(buffer, offset, count); } public override void WriteByte(byte value) { m_f.WriteByte(value); } public override int WriteTimeout { get { return m_f.WriteTimeout; } set { m_f.WriteTimeout = value; } } public override long Seek(long offset, SeekOrigin origin) { return m_f.Seek(offset + m_start, origin); } } } }
a24aa40e8934c750bca11434355691cea1de4b11
[ "Markdown", "C#" ]
4
C#
thigiacmaytinh/RawImageConverter
cc8dc566ceebccf637a046d216ef4ce79c484c21
c8290b68a7ab30fbb1c0770150f935a2b9e87962
refs/heads/master
<file_sep>Statusnet on OpenShift ====================== This quickstart will help you get Statusnet up and running on Openshift. Running on OpenShift --------------------- 1) Create an account at http://openshift.redhat.com/ 2) Create a php-5.3 application (you can call your application whatever you want) rhc app create -a statusnet -t php-5.3 3) Add a MySQL cartridge to your gear rhc cartridge add -a statusnet -c mysql-5.1 4) Add this upstream git repository cd statusnet git remote add upstream -m master git://github.com/mmahut/statusnet-quickstart.git git pull -s recursive -X theirs upstream master 5) Then push the repo to your application git push 6) Login into your application URL with the login details below and change them. Login: Admin Password: <PASSWORD> Integrate with Twitter ---------------------- 1) Create yourself a new application at http://dev.twitter.com/apps/ and set the callback URL to http://statusnet-$username.rhcloud.com/index.php/twitter/authorization, also set the access read and write in the application settings. 2) Add the following to your config.php with your application consumer secrets addPlugin('TwitterBridge'); $config['twitter']['enabled'] = true; $config['twitterimport']['enabled'] = true; $config['admin']['panels'][] = 'twitter'; $config['twitter']['consumer_key'] = 'TLRBX1Ucf8UzYrjYqw'; $config['twitter']['consumer_secret'] = '<KEY>'; 3) Login into your statusnet and go to Settings -> Twitter. Connect your account and choose your Preferences. <file_sep>#!/bin/bash # This deploy hook gets executed after dependencies are resolved and the # build hook has been run but before the application has been started back # up again. This script gets executed directly, so it could be python, php, # ruby, etc. if [ -z $OPENSHIFT_MYSQL_DB_HOST ] then echo 1>&2 echo "Could not find mysql database. Please run:" 1>&2 echo "rhc cartridge add -a $OPENSHIFT_APP_NAME -c mysql-5.1" 1>&2 echo "then make a sample commit (add whitespace somewhere) and re-push" 1>&2 echo 1>&2 exit 5 fi # Confirm database exists, if not create it if ! /usr/bin/mysql -u "$OPENSHIFT_MYSQL_DB_USERNAME" --password="$<PASSWORD>" -h "$OPENSHIFT_MYSQL_DB_HOST" -e "show tables;" statusnet > /dev/null 2>&1 then echo echo "Database not found! Creating and importing" echo /usr/bin/mysqladmin -u "$OPENSHIFT_MYSQL_DB_USERNAME" --password="$<PASSWORD>" -h "$OPENSHIFT_MYSQL_DB_HOST" create "statusnet" /usr/bin/mysql -u "$OPENSHIFT_MYSQL_DB_USERNAME" --password="$<PASSWORD>" -h "$OPENSHIFT_MYSQL_DB_HOST" statusnet < "$OPENSHIFT_REPO_DIR/.openshift/action_hooks/openshift.sql" echo echo "done." echo "========================================================" echo " Login URL: http://$OPENSHIFT_APP_DNS/" echo " Statusnet login: Admin" echo " Statusnet password: <PASSWORD>" echo " Don't forget to change your admin password right away!" echo "========================================================" else echo "Database found, skipping build" fi if [[ ! -e $OPENSHIFT_DATA_DIR/attachments ]]; then mkdir -p $OPENSHIFT_DATA_DIR/attachments; fi if [[ ! -e $OPENSHIFT_DATA_DIR/avatars ]]; then mkdir -p $OPENSHIFT_DATA_DIR/avatars; fi if [[ ! -e $OPENSHIFT_DATA_DIR/backgrounds ]]; then mkdir -p $OPENSHIFT_DATA_DIR/backgrounds; fi
e089bd133aa974342e7115a951f69a0bdf16a9c9
[ "Markdown", "Shell" ]
2
Markdown
andypiper/statusnet-openshift-quickstart
b9584499f0826f738415edce97f840a64bcf7b10
d73e3eaee9c322feb458f65d686757d222c0b2fd
refs/heads/master
<file_sep>import { sortingByDate, ascendingSortingByVote, descendingSortingByVote, } from "../../utils/sorting"; describe("Sorting Test", () => { const mockItem = [ { linkName: "link1", id: 1, vote: 3, createdDate: "18/01/2021 13:55:27", }, { linkName: "link2", id: 2, vote: 4, createdDate: "16/01/2021 23:00:16", }, { linkName: "link3", id: 3, vote: 2, createdDate: "17/01/2021 13:55:01", }, ]; afterEach(() => { jest.clearAllMocks(); }); it("should output return sorting by date", () => { const sortingByDateReal = sortingByDate(mockItem); const sortedData = [ { linkName: "link1", id: 1, vote: 3, createdDate: "18/01/2021 13:55:27", }, { linkName: "link3", id: 3, vote: 2, createdDate: "17/01/2021 13:55:01", }, { linkName: "link2", id: 2, vote: 4, createdDate: "16/01/2021 23:00:16", }, ]; expect(sortingByDateReal).toStrictEqual(sortedData); }); it("should output return sorting by vote ascending", () => { const ascendingSortingByVoteReal = ascendingSortingByVote(mockItem); const sortedData = [ { linkName: "link2", id: 2, vote: 4, createdDate: "16/01/2021 23:00:16", }, { linkName: "link1", id: 1, vote: 3, createdDate: "18/01/2021 13:55:27", }, { linkName: "link3", id: 3, vote: 2, createdDate: "17/01/2021 13:55:01", }, ]; expect(ascendingSortingByVoteReal).toStrictEqual(sortedData); }); it("should output return sorting by vote descending", () => { const descendingSortingByVoteReal = descendingSortingByVote(mockItem); const sortedData = [ { linkName: "link3", id: 3, vote: 2, createdDate: "17/01/2021 13:55:01", }, { linkName: "link1", id: 1, vote: 3, createdDate: "18/01/2021 13:55:27", }, { linkName: "link2", id: 2, vote: 4, createdDate: "16/01/2021 23:00:16", }, ]; expect(descendingSortingByVoteReal).toStrictEqual(sortedData); }); }); <file_sep>import { FormValuesProps } from "./../Hooks/useForm/index"; const validate: ValidateType = (values: FormValuesProps): ValidateProps => { const errors: ValidateProps = {}; if (!values.linkName.trim()) { errors.linkName = "Link Name required"; } return errors; }; export interface ValidateProps { [key: string]: string; } export type ValidateType = (p: FormValuesProps) => ValidateProps; export default validate; <file_sep>const showToastrMessage = (setState: (e: boolean) => void, duration: number = 1000) => { setState(true); setTimeout(() => { setState(false); }, duration); }; export default showToastrMessage; <file_sep>import { dateFormatType } from "./helpers"; import moment from "moment"; const getCurrentDate = () => { const currentDate = new Date(); const formatedDate = moment(currentDate).format(dateFormatType); return formatedDate; }; export default getCurrentDate; <file_sep>import moment from "moment"; import getCurrentDate from "../../utils/date"; describe("Test Date", () => { it("should output format date", () => { const currentDate = new Date(); const formatedDate = moment(currentDate).format("DD/MM/YYYY HH:mm:ss"); const getCurrenDateReal = getCurrentDate(); expect(getCurrenDateReal).toBe(formatedDate); }); }); <file_sep>export const localStorageKey = "link"; export const dateFormatType = "DD/MM/YYYY HH:mm:ss"; <file_sep>import { ValuesProps } from "../Containers/AddLinkContainer/index"; const getLocalStorage = (key: string) => { const savedValue = JSON.parse(localStorage.getItem(key) || "[]"); return savedValue; }; const saveLocalStorage = (key: string, value: ValuesProps[]): void => { localStorage.setItem(key, JSON.stringify(value)); }; export { getLocalStorage, saveLocalStorage }; <file_sep>import { ValuesProps } from "../Containers/AddLinkContainer/index"; import { dateFormatType } from "./helpers"; import moment from "moment"; const sortingByDate = (data: ValuesProps[]): ValuesProps[] => { const sortedData = data.sort((a: ValuesProps, b: ValuesProps): number => { const aCreatedDate = moment(a.createdDate, dateFormatType).format(); const bCreatedDate = moment(b.createdDate, dateFormatType).format(); if (aCreatedDate > bCreatedDate) { return -1; } return 0; }); return sortedData; }; const ascendingSortingByVote = (data: ValuesProps[]): ValuesProps[] => { const sortedData = data.sort((a: ValuesProps, b: ValuesProps) => b.vote - a.vote); return sortedData; }; const descendingSortingByVote = (data: ValuesProps[]): ValuesProps[] => { const sortedData = data.sort((a: ValuesProps, b: ValuesProps) => a.vote - b.vote); return sortedData; }; export { sortingByDate, ascendingSortingByVote, descendingSortingByVote };
204ab2f4d92aaef62c1b1895ca421e1baba706c9
[ "TypeScript" ]
8
TypeScript
acerezci/Listing-App
6c31306bcb80994198759d5fd5cd2ab6c677a04e
bef56e3f5c7b37eb7b0d015f31b5325e2162fa3f
refs/heads/master
<file_sep><?php namespace Narration\Testing\Commands; use PHPStan\Command\AnalyseCommand; use Symfony\Component\Console\Command\Command as BaseCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; final class StaticAnalysisCommand extends AnalyseCommand { /** * {@inheritdoc} */ protected function configure(): void { parent::configure(); $this->setName('test:static-analysis'); } } <file_sep><?php namespace Tests\Unit; use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Command\Command; use Narration\Testing\Commands\StaticAnalysisCommand; final class StaticAnalysisCommandTest extends TestCase { public function testName(): void { $command = new StaticAnalysisCommand(); static::assertEquals($command->getName(), 'test:static-analysis'); } }
b73619fbd7020cb4bfb268c48b3c2c8fb8e80cb4
[ "PHP" ]
2
PHP
narration/testing
aa99867b348a6c603b79ad4d7e3adff327ded697
28026196cd6d17ebc2eb08398871985465327341
refs/heads/master
<repo_name>madmonkeyworks/jbmflickr<file_sep>/jbmflickr.dev.js /* Jbmflickr v1.2 by <NAME> - http://www.seven-m.com For more information, visit: http://www.seven-m.com/jbmflickr Licensed under the GPL v2 License - free for use in both personal and commercial projects - attribution requires leaving author name, author link, and the license info intact */ (function ($, window, document) { $(function () { var log = { debug : true, error : function(message) { var m = 'JBMFlickr error'; try { if (this.debug && window.console && window.console.error){ window.console.error([m, message].join(': ')); } } catch (e) { // no console available } }, info : function(message) { var m = 'JBMFlickr notice'; try { if (window.console && window.console.info){ window.console.info([m, message].join(': ')); } } catch (e) { // no console available } } } var flickr = { xhrPool : [], init : function( options ) { return this.each(function() { // get options from attributes var attrs = {}; $.each(this.attributes, function(i,v){ if (/jbmflickr/.test(v.nodeName)) { attrs[v.nodeName.replace('jbmflickr-','')] = v.nodeValue; } }); options = $.isPlainObject(options) ? options : {}; $.extend(options, attrs); var $this = $(this), params = { userid: "", link_images: true, lightbox: true, lightbox_theme: 'default', template: "", thumbnail_size: 'q', per_page: 10 }; // plugin not yet initialized? if (typeof $this.data('jbmflickr') == 'undefined') { $this.data('jbmflickr', $.extend(params, options)); flickr.$this = $this; var o = flickr.getSettings(); } else { log.info('jbmflickr already initialized'); return; } // get base path var basePath = flickr.set('basePath', $('script').filter(function(){ return /(jbmflickr\.js|jbmflickr\.dev\.js)/.test($(this).attr('src')) }).attr('src') .replace('jbmflickr.js','') .replace('jbmflickr.dev.js','')) // load main css $('<link />') .appendTo($('head')) .attr({type: 'text/css', rel: 'stylesheet'}) .attr('href', basePath + 'jbmflickr.css'); // load lightbox if (flickr.get('lightbox',true,'boolean')) { $.getScript(basePath + 'libs/lightbox/lightbox.js') .done(function(){ log.info('lightbox script loaded'); $('<link />') .appendTo($('head')) .attr({type: 'text/css', rel: 'stylesheet'}) .attr('href', basePath + 'libs/lightbox/css/' + flickr.get('lightbox_theme','default') + '/lightbox.css'); }) .fail(function(){ log.error('failed to load lightbox script') }) } // load jcycle2..save as deferred flickr.jcycleLoaded = $.getScript(basePath + 'libs/jcycle/jcycle.js') .done(function(){ log.info('jcycle2 script loaded') }) .fail(function(){ log.error('failed to load jcycle2 script') }) // insert container for slides flickr.$slides = $('<div class="slides" />').appendTo($this); // init pagination flickr.Display.init(); // prepare search input field if ($('.jbmflickr-search-field').length) { $('.jbmflickr-search-field').change(function(){ flickr.load({ text: $(this).val() }) }) } // load photos if (flickr.get('initial_load',false,'boolean')) { flickr.load(); } }); }, Display : { init : function(numPages) { this.pager = flickr.get('pager','<div class="pager" />'); var $this = flickr.$this, $pager = $(this.pager).appendTo($this), $this = flickr.$this, Display = this; this.params = { fx: 'scrollHorz', speed: parseInt(flickr.get('slideshow_speed',2000)), timeout: parseInt(flickr.get('slideshow_timeout',3000)), log : false, slides: '.page', pager: '.pager', events: { 'cycle-slide-added' : function(event, s, a, slide) { // turn on lightbox $(slide).find('a.lightbox-link').attr('rel','lightbox[gallery]'); // custom code if (typeof flickr.get('',null) == 'function') { flickr.get('').call($(slide)); } else { $(slide).find('.flickr-item').hover( function(){ $(this).find('.description').show(200); }, function(){ $(this).find('.description').hide(200); } ); } } } } // wait for jcycle2 is loaded $.when(flickr.jcycleLoaded) .done(function() { flickr.$slides .bind(Display.params.events) .cycle(Display.params) }) .fail(function() { log.error('JCycle2 was not loaded.') }) }, clear: function() { flickr.$slides.empty(); }, show : function(imgs) { var $this = flickr.$this, $slides = flickr.$slides, nextSlides = [], dImgs = [], Display = this, sizes = { s : 75, q : 150, t : 100, m : 240, n : 320, '-' : 500, z : 640 }, pages = [], template = flickr.get('template','<div class="flickr-item"><a class="lightbox-link" href="{url_z}" title="{title}"><div class="photo-wrapper"><div class="photo" style="background-image: url({url_'+flickr.get('thumbnail_size','q')+'});width: {width_q}px;height: {height_q}px"></div></div></a><div class="description"><div class="inner">{title}</div></div></div>'), items = []; Display.clear(); if (!imgs.length) { $slides.append($('<div class="placeholder" />').css({ width: sizes[flickr.get('thumbnail_size','q')]+'px', height: sizes[flickr.get('thumbnail_size','q')]+'px' })); $slides.cycle('destroy').off(); return; } $.each(imgs, function(i,img){ var item = template; $.each(img,function(j,v) { var r = new RegExp('{'+j+'}','g'); item = item.replace(r,img[j]); }); items.push(item); }) function wrapPage(p) { p = '<div class="page">'+p+'</div>'; return p; } // form pages while(items.length > flickr.get('per_page')){ pages.push(wrapPage(items.splice(0,flickr.get('per_page')).join(''))); } pages.push(wrapPage(items.join(''))); Display.params['progressive'] = pages.splice(1); // reinit slideshow $slides.find('.cycle-slide').remove(); $.when(flickr.jcycleLoaded).done(function() { $slides .cycle('destroy') .off() .on(Display.params.events) .cycle(Display.params) .cycle('add',pages[0]) }) } }, getPhotosUrl : function(params) { var settings = { page: 1, per_page: 500, media: 'all', method: 'flickr.photos.search' }, required = { api_key: "<KEY>", format: 'json', user_id: encodeURIComponent(flickr.get('userid')), nojsoncallback: '1', content_type: '7', extras: 'tags,description,url_sq,url_t,url_s,url_q,url_m,url_n,url_z,url_c, url_l,url_o' }, url = "https://api.flickr.com/services/rest/?"; // remove tags and text params..they cause flickr API error $.extend(settings, params, required); if (settings.tags) delete settings.tags; if (settings.text) delete settings.text; return url + decodeURIComponent($.param(settings)); }, _filterData : function(data, params) { if (!params.tags && !params.text) return data; var r = [], flag = false, isInString = function(needle, haystack) { needle .replace(/[\W]/g,"|") .replace(/\|{2,}/,"|") .replace(/(^\||\|$)/g,""); return new RegExp('(' + needle + ')','i').test(haystack); } $.each(data.photos.photo, function(index,v) { // filter tags if (params.tags) { flag = isInString(params.tags, v.tags); } // filter text in description and title if (params.text) { flag = isInString(params.text, v.title+' '+v.description); } if (flag) r.push(v); }) data.photos.photo = r; data.photos.total = r.length; return data; }, load: function(params){ var _this = flickr, $this = flickr.$this; if (arguments.length == 0) { params = {}; } url = flickr.getPhotosUrl(params); flickr.xhrPool.push($.ajax({ url: url, type: 'GET', cache: true, dataType: 'json' }) .fail(function(xhr, errMsg, err) { log.error(errMsg); }) .done(function(data) { if (data.stat !== 'ok') { log.error('Error retrieving data: ' + data.message); return; } // filter photos and show data = flickr._filterData(data, params); flickr.Display.show(data.photos.photo); }) ) }, get : function(param, def, type) { var $this = flickr.$this, o = flickr.getSettings(); type = type ? type : ''; switch (type) { case 'int' : return o[param] ? parseInt(o[param]) : (def ? def : false); break; case 'float' : return o[param] ? parseFloat(o[param]) : (def ? def : false); break; case 'boolean' : if (typeof o[param] === 'boolean') { return o[param]; } else if (typeof o[param] === 'string') { p = o[param].toLowerCase(); return (p == 'true' || p == '1') ? true : false; } else if (typeof o[param] === 'number') { return o[param] == 0 ? false : true; } else { return (def ? def : false); } break; default : return o[param] ? o[param] : (def ? def : ''); } }, set : function(param, value) { var $this = flickr.$this, o = flickr.getSettings(); if (!o) return false; o[param] = value; return value; }, getSettings : function() { var $this = flickr.$this; return $this.data('jbmflickr'); }, /* * public methods * this refers to div container */ search : function(params, xhr) { return this.each(function() { flickr.load(params); }); }, destroy : function() { return this.each(function() { var $this = $(this); $this.unbind().empty(); }) } } $.fn.jbmflickr = function( method ) { var public = 'destroy, search', isPublic = false; if (typeof method === 'string') { var r = new RegExp(method, 'i'); isPublic = r.test(public); } // Method calling logic if (typeof method ==='string' && !isPublic) { log.error( method + ' is a protected method on jQuery.JBMflickr' ); } else if ( flickr[method] ) { return flickr[ method ].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return flickr.init.apply( this, arguments ); } else { log.error( 'Method ' + method + ' does not exist on jQuery.JBMflickr' ); } }; /* FLICKR MAP CODE */ var flickrmap = { init: function(options) { return this.each(function() { // get options from attributes var attrs = {} $.each(this.attributes, function(i,v){ if (/^jbmflickrmap/.test(v.nodeName)) { attrs[v.nodeName.replace('jbmflickrmap-','')] = v.nodeValue; } }); options = $.isPlainObject(options) ? options : {}, $.extend(options, attrs); var $this = $(this), params = $.extend({ userid: null, zoom: 5, limit: 200, marker: 'google' }, options); // plugin not yet initialized? if (typeof $this.data('jbmflickrmap') == 'undefined') { $this.data('jbmflickrmap', $.extend(params, options)); flickrmap.$this = $this; var o = flickrmap.getSettings(); } else { log.info('jbmflickrmap already initialized'); return; } // get base path var basePath = $('script').filter(function(){ return /(jbmflickr|jbmflickr\.dev)\.js/.test($(this).attr('src')) }).attr('src') .replace('jbmflickr.js','') .replace('jbmflickr.dev.js','') // treat some values if (!params.userid) return; if (params.zoom) params.zoom = parseInt(params.zoom); function initialize() { var myLatlng = new google.maps.LatLng(44.699898, 34.189453); var mapOptions = { center: myLatlng, zoom: params.zoom, scrollwheel: false, keyboardShortcuts: false } var map = new google.maps.Map($this.get(0), mapOptions); var url = flickrmap.getFeedUrl(params); function showStandardKmlLayer() { var georssLayer = new google.maps.KmlLayer({ url:url, preserveViewport: true, map: map }); } var getFeed = $.ajax({ url: url, type: 'GET', cache: true, dataType: 'text' }); $.getScript('http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/1.0.2/src/markerclusterer.js') .done(function() { $.getScript(basePath + 'libs/geoxml3/geoxml3.js') .done(function() { markerclusterer = new MarkerClusterer(map, []); //Construct a geoXML3 parser var points=[]; var parser = new geoXML3.parser({ map: map, zoom: false, processStyles:true, failedParse : function() { showStandardKmlLayer() }, createMarker:function(placemark, parser){ var point = { lat: placemark.Point.coordinates[0].lat, lng: placemark.Point.coordinates[0].lng } function fixLocation(point) { if ($.inArray([point.lat,point.lng].join(':'), points) >= 0) { point.lng += 0.02; fixLocation(point); } else return; } fixLocation(point); var mapPoint = new google.maps.LatLng(point.lat, point.lng); points.push([point.lat,point.lng].join(':')); var href = placemark.styleUrl.replace('#styleMap/photo','//www.flickr.com/photos/'+flickrmap.get('userid')); var content = $('<div />') .append($('<div class="title" />').text(placemark.name)) .append($('<img />').attr({src: placemark.style.href.replace('_s.jpg','_m.jpg'), alt: placemark.name })) .append('<br />') .append($('<a />').text('view large').attr({ href: href, target: '_blank' })) .html() var infowindow = new google.maps.InfoWindow({ content: content, maxWidth: 400 }); var icon = null; switch (flickrmap.get('marker')) { case 'photo' : icon = placemark.style.icon; break; case 'google' : icon = null; break; default: icon = flickrmap.get('marker',null); } var marker = new google.maps.Marker({ position:point, icon: icon, flat: false, title: placemark.name }); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map, marker); }); markerclusterer.addMarker(marker); } }); getFeed .done(function(feed) { parser.parseKmlString(feed); }) .fail(function() { showStandardKmlLayer() }) }) }) .fail(function() { showStandardKmlLayer() }) // save map api into container data o.map = map; } // load googlemaps API // load the google api loader if( typeof(google) == 'undefined' || !google.load ) { $.getScript( '//www.google.com/jsapi', function() { loadMaps(); }); } else { loadMaps(); } // load the google maps api function loadMaps() { google.load("maps", "3", { callback: initialize, other_params: 'sensor=false' }); } }) }, getFeedUrl : function(params) { var settings = { page: 1, per_page: flickrmap.get('limit', 40), tags: '', text: '', format: 'feed-kml', media: 'photos', method: 'flickr.photos.search', has_geo:'1' }, required = { api_key: "<KEY>112e4263bfec74f3febf0d", user_id: flickrmap.get('userid'), jsoncallback: '?', content_type: '7' }, url = "https://api.flickr.com/services/rest/?"; $.extend(settings, params, required); return url + decodeURIComponent($.param(settings)); }, /* Public method */ locate : function(address) { return this.each(function() { var $this = $(this), map = flickrmap.getSettings().map, geocoder = new google.maps.Geocoder(); if (geocoder) { geocoder.geocode({ 'address': address }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { map.fitBounds(results[0].geometry.viewport); // show images from this area var b = map.getBounds(); var lat0 = b.getSouthWest().lat(); var lon0 = b.getSouthWest().lng(); var lat1 = b.getNorthEast().lat(); var lon1 = b.getNorthEast().lng(); var bbox = [lon0,lat0,lon1,lat1].join(','); $('.jbmflickr').jbmflickr('search', {bbox: bbox, accuracy:1}); } }); } }); }, get : function(param, def, type) { var $this = flickrmap.$this, o = flickrmap.getSettings(); type = type ? type : ''; switch (type) { case 'int' : return o[param] ? parseInt(o[param]) : (def ? def : false); break; case 'float' : return o[param] ? parseFloat(o[param]) : (def ? def : false); break; case 'boolean' : if (typeof o[param] === 'boolean') { return o[param]; } else if (typeof o[param] === 'string') { p = o[param].toLowerCase(); return (p == 'true' || p == '1') ? true : false; } else if (typeof o[param] === 'number') { return o[param] == 0 ? false : true; } else { return (def ? def : false); } break; default : return o[param] ? o[param] : (def ? def : ''); } }, set : function(param, value) { var $this = flickrmap.$this, o = flickrmap.getSettings(); if (!o) return false; o[param] = value; return value; }, getSettings : function() { var $this = flickrmap.$this; return $this.data('jbmflickrmap'); }, } $.fn.jbmflickrmap = function( method ) { var public = 'destroy, locate', isPublic = false; if (typeof method === 'string') { var r = new RegExp(method, 'i'); isPublic = r.test(public); } // Method calling logic if (typeof method ==='string' && !isPublic) { log.error( method + ' is a protected method on jQuery.JBMflickrmap' ); } else if ( flickrmap[method] ) { return flickrmap[ method ].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return flickrmap.init.apply( this, arguments ); } else { log.error( 'Method ' + method + ' does not exist on jQuery.JBMflickrmap' ); } }; /* * Initialization based on attributes */ // JBMFlickrmap if ($('.jbmflickrmap').length) { $('.jbmflickrmap').jbmflickrmap(); } // JBMFlickrmap location if ($('.jbmflickrmap-location')) { // bind event $('.jbmflickrmap-location').change(function() { // check which map if ($('#'+$('.jbmflickrmap-location').attr('rel')).length) { $('#'+$('.jbmflickrmap-location').attr('rel')).jbmflickrmap('locate', $(this).val()); } else { $('.jbmflickrmap').jbmflickrmap('locate', $(this).val()) } }) } // JBMFlickr if ($('.jbmflickr').length) { $('.jbmflickr').jbmflickr(); } // JBMFlickr tag cloud if ($('.jbmflickr-tag-cloud').length) { // check for jbmflickr if ($('.jbmflickr').length) { $('.jbmflickr-tag-cloud > a').click(function(e){ e.preventDefault(); $('.jbmflickr').jbmflickr('search',{tags:$(this).attr('href').replace('#','')}); }); } } }) } (this.jQuery, this, this.document));<file_sep>/readme.md # JBMFLICKR - JQUERY PLUGIN ## AUTHOR Name: <NAME> URL: https://madmonkey.works ## DEMO http://www.seven-m.com/demos/jbmflickr/ http://www.amicafoundation.com/en/collection.html ## DESCRIPTION Jbmflickr is a jQuery plugin that pulls images hosted on flickr and shows them in a lightbox-style gallery or in a google map. It allows you to: - search images by a text or tag entered in an input field - define your tag-cloud to retrieve tagged images - retrieve geo tagged images and display them in a googlemap - dynamically search googlemap and retrieve geo tagged images from a specific location ## INSTALLATION 1) Download the zip file, unzip it and insert the content into a folder (e.g. 'jbmflickr') anywhere on your website. 2) Link the script 'jbmflickr.js' in the head section of your html file. 3) Create div elements with class "jbmflickr" or "jbmflickrmap" ## INITIALIZATION In your html, insert a div element with class 'jbmflickr' and attributes. Attributes serve as plugin options, e.g. jbmflickr-userid="xxxxxx". See examples and all available options below... ### DISPLAY IMAGES ```html <div class="jbmflickr" jbmflickr-userid="xxxxxxxx" jbmflickr-initial_load="1" jbmflickr-thumbnail_size="q" jbmflickr-per_page="8" jbmflickr-per_row="8" ></div> ``` ### SEARCH BY KEYWORDS OR TAGS ```html <input type="text" class="jbmflickr-search-field" size="50" placeholder="Enter search text and hit enter"/> ``` ### USE TAG-CLOUD ```html <div class="jbmflickr-tag-cloud"> <span>tags: </span> <a href="#animal">animal</a> <a href="#nature">nature</a> <a href="#celebration">celebration</a> <a href="#playing">playing</a> </div> ``` ### DISPLAY GEO TAGGED IMAGES IN GOOGLE MAP ```html <div class="jbmflickrmap" style="height:400px; width: 100%;" jbmflickrmap-userid="xxxxxx" jbmflickrmap-zoom="2" ></div> ``` ### SEARCH BY GOOGLE LOCATION ```html <input type="text" class="jbmflickrmap-location" placeholder="Enter a location (country, city), e.g. 'Netherlands'" rel="myMap" /> ``` The map zooms to the location entered in the field. If 'rel' attribute is defined, only the map with such 'id' will get zoomed. ## PLUGIN OPTIONS The following table shows all attributes that you can use to specify plugin options. ### ATTRIBUTES Attribute: jbmflickr-userid Data type: string Default value: required Description: This is the flickr user ID. Attention: this is not the username but an ID. If you don't know what your ID is, check it via www.idgettr.com. Attribute: jbmflickr-initial_load Data type: boolean Default value: "1" Descriptio: If "1" then plugin loads images upon the page loads. if "0" then plugin will not load anything. Attribute: jbmflickr-thumbnail_size Data type: string Default value: "m" Description: Defines size of the images. Possible values are based on flickr specifications: * s small square 75x75 * q large square 150x150 * t thumbnail, 100 on longest side * m small, 240 on longest side * n small, 320 on longest side * medium, 500 on longest side * z medium 640, 640 on longest side * ...see http://www.flickr.com/services/api/misc.urls.html #### Attribute: jbmflickr-per_page Data type: integer Default value: "8" Description: Defines number of images per page. #### Attribute: jbmflickr-per_row Data type: integer Default value: "8" Description: Defines number of images per row. #### Attribute: jbmflickr-link_images Data type: boolean Default Value: "1" Description: If "1" then image thumbnails will act as links to large images. #### Attribute: jbmflickr-lightbox Data type: boolean Default value: "1" Description: If "1" then lightbox will be used to enlarge image when a thumbnail is clicked. #### Attribute: jbmflickr-lightbox_theme Data type: string Default Value: "default" Description: Name of the custom theme. You can create your own 'default.css' file and insert it into the folder "libs/lightbox/css/your_theme" ##### For Google map container ...div with class 'jbmflickrmap' #### Attribute: jbmflickrmap-userid Data type: string Default Value: required Description: This is the flickr user ID. Attention: this is not the username but an ID. If you don't know what your ID is, check it via www.idgettr.com. #### Attribute: jbmflickrmap-zoom Data type: integer Default Value: "5" Description: Initial zoom. Values between 0 - 15. #### Attribute: jbmflickrmap-limit Data type: integer Default Value: "200" Description: Max. number of retrieved images. ## NOT TO DO Do NOT rename the 'jbmflickr.js' file, or change its location within its parent directory. This would break proper determination of the base path necessary for the inclusion of other scripts. ##CREDITS The jbmflickr plugin wouldn't be possible without: - lightbox2 made by <NAME>... http://lokeshdhakar.com/projects/lightbox2/ - jcycle2 made by <NAME>... http://jquery.malsup.com/cycle2/ - geoxml3 by <NAME>, <NAME>ss... https://code.google.com/p/geoxml3/ - Marker Clusterer by <NAME>... https://code.google.com/p/google-maps-utility-library-v3/source/browse/trunk/markerclusterer/
045ffe6d0a8d2984809260eb4fe8fa417299e473
[ "JavaScript", "Markdown" ]
2
JavaScript
madmonkeyworks/jbmflickr
7b42e667e74d8facb7fdd970e9e98c18e17ff303
3c295b33fb883c5f9f85355078ba122a71eb4074
refs/heads/master
<file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Subject, Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { Router } from '@angular/router'; import { environment } from 'src/environments/environment'; @Injectable({ providedIn: 'root' }) export class AuthService { isLoggedIn: boolean; userType: string; private authStatusListener = new Subject<boolean>(); token: any; tokenTimer: any; constructor(private http: HttpClient, private route: Router) { } getAuthStatusListener() { return this.authStatusListener.asObservable(); } logout() { this.token = null; localStorage.removeItem('token'); this.authStatusListener.next(false); this.route.navigate(['/']); } getToken() { return (localStorage.getItem('token')); } createUser(reqBody): Observable<any> { const url: any = `${environment.url}/register`; return this.http.post(url, reqBody).pipe( map(response => { return response; }) ); } loginUser(reqBody): Observable<any> { return this.http .post<{ token }>( `${environment.url}/authenticate`, reqBody ) .pipe( map(response => { const token = response.token; this.token = token; if (token) { localStorage.setItem('token', JSON.parse(JSON.stringify(response.token))); // const expiresInDuration = response.data.expiresIn; // this.setAuthTimer(expiresInDuration); this.authStatusListener.next(true); // const now = new Date(); // const expirationDate = new Date( // now.getTime() + expiresInDuration * 1000 // ); // console.log(expirationDate); // this.saveAuthData(token, expirationDate); } return response; }) ); } private setAuthTimer(duration: number) { // console.log('Setting timer: ' + duration); this.tokenTimer = setTimeout(() => { this.logout(); }, duration * 1000); } private saveAuthData(token: string, expirationDate: Date) { localStorage.setItem('token', token); localStorage.setItem('expiration', expirationDate.toISOString()); } getIsAuth() { let loggedIn: boolean; if (localStorage.getItem('token')) { loggedIn = true; } else { loggedIn = false; } return loggedIn; } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-manage-users', templateUrl: './manage-users.component.html', styleUrls: ['./manage-users.component.css'] }) export class ManageUsersComponent implements OnInit { users :any = []; selectedUsers:any loading : boolean; displayModal:boolean; selectedStatus :boolean; userStatus : any = [{'label' : 'Active' , value : true},{'label' : 'Inactive' , value : false}]; constructor() { } ngOnInit(): void { this.users.push({'id':1,'name':'DJ','email':'<EMAIL>','mobile':'8600256227','status': true}, {'id':2,'name':'Swapnil','email':'<EMAIL>','mobile':'9220772661','status':true}, {'id':3,'name':'<NAME>','email':'<EMAIL>','mobile':'9657265481','status':false}, {'id':4,'name':'<NAME>','email':'<EMAIL>','mobile':'9220772668','status':true}, {'id':5,'name':'<NAME>','email':'<EMAIL>','mobile':'9657276489','status':true}, {'id':6,'name':'<NAME>','email':'<EMAIL>','mobile':'7977961694','status':true}, {'id':1,'name':'DJ','email':'<EMAIL>','mobile':'8600256227','status': false}, {'id':2,'name':'Swapnil','email':'<EMAIL>','mobile':'9220772661','status':true}, {'id':3,'name':'<NAME>','email':'<EMAIL>','mobile':'9657265481','status':false}, {'id':4,'name':'<NAME>','email':'<EMAIL>','mobile':'9220772668','status':true}, {'id':5,'name':'<NAME>','email':'<EMAIL>','mobile':'9657276489','status':true}, {'id':6,'name':'<NAME>','email':'<EMAIL>','mobile':'7977961694','status':true}, {'id':1,'name':'DJ','email':'<EMAIL>','mobile':'8600256227','status': true}, {'id':2,'name':'Swapnil','email':'<EMAIL>','mobile':'9220772661','status':true}, {'id':3,'name':'<NAME>','email':'<EMAIL>','mobile':'9657265481','status':true}, {'id':4,'name':'<NAME>','email':'<EMAIL>','mobile':'9220772668','status':true}, {'id':5,'name':'<NAME>','email':'<EMAIL>','mobile':'9657276489','status':true}, {'id':6,'name':'<NAME>','email':'<EMAIL>','mobile':'7977961694','status':true}, {'id':1,'name':'DJ','email':'<EMAIL>','mobile':'8600256227','status': false}, {'id':2,'name':'Swapnil','email':'<EMAIL>','mobile':'9220772661','status':true}, {'id':3,'name':'<NAME>','email':'<EMAIL>','mobile':'9657265481','status':true}, {'id':4,'name':'<NAME>','email':'<EMAIL>','mobile':'9220772668','status':true}, {'id':5,'name':'<NAME>','email':'<EMAIL>','mobile':'9657276489','status':false}, {'id':6,'name':'<NAME>','email':'<EMAIL>','mobile':'7977961694','status':false}); } onClick(row:any){ this.displayModal =true; } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import {FormsModule } from '@angular/forms' import { AdminRoutingModule } from './admin-routing.module'; import { AdminComponent } from './admin.component'; import { ManageUsersComponent } from './manage-users/manage-users.component'; import { ManageTrainersComponent } from './manage-trainers/manage-trainers.component'; import { ManageDomainsComponent } from './manage-domains/manage-domains.component'; import { TechnologyComponent } from './technology/technology.component'; import { ManagePaymentsComponent } from './manage-payments/manage-payments.component'; import { AppSettingsComponent } from './app-settings/app-settings.component'; import { AdminMenuComponent } from './admin-menu/admin-menu.component'; import {TableModule} from 'primeng/table'; import {DialogModule} from 'primeng/dialog'; import {DropdownModule} from 'primeng/dropdown'; import { AdminDashboardComponent } from './admin-dashboard/admin-dashboard.component'; @NgModule({ declarations: [AdminComponent, ManageUsersComponent, ManageTrainersComponent, ManageDomainsComponent, TechnologyComponent, ManagePaymentsComponent, AppSettingsComponent, AdminMenuComponent, AdminDashboardComponent], imports: [ CommonModule, AdminRoutingModule, TableModule, DialogModule, DropdownModule, FormsModule ] }) export class AdminModule { } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { Router } from '@angular/router'; import { environment } from 'src/environments/environment'; @Injectable({ providedIn: 'root' }) export class AdminService { constructor(private http: HttpClient, private route: Router) { } welcome(): Observable<any> { const url: any = `${environment.url}/greeting`; return this.http.get(url, { responseType: 'text' }).pipe( map(response => { console.log('response', response); return response; }) ); } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-technology', templateUrl: './technology.component.html', styleUrls: ['./technology.component.css'] }) export class TechnologyComponent implements OnInit { technologies :any = []; selectedUsers:any loading : boolean; displayModal:boolean; selectedStatus :boolean; userStatus : any = [{'label' : 'Active' , value : true},{'label' : 'Inactive' , value : false}]; constructor() { } ngOnInit(): void { this.technologies.push( {'id':1,'technology':'AI','description':'this is test description', 'domain':'Development','status': true}, {'id':2,'technology':'Web Development','domain':'Business','description':'this is test description','status': true}, {'id':3,'technology':'Robotics','domain':'Data Science','description':'this is test description','status': true}, {'id':4,'technology':'Space Research','domain':'Mobile App','description':'this is test description','status': true}, {'id':5,'technology':'Health Secience','domain':'Programming Languages','description':'this is test description','status': true}, ); } onClick(row:any){ this.displayModal =true; } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Subscription } from 'rxjs'; import { AuthService } from '../auth/auth.service'; @Component({ selector: 'app-navbar', templateUrl: './navbar.component.html', styleUrls: ['./navbar.component.css'] }) export class NavbarComponent implements OnInit { display: boolean; authStatSubs: Subscription; isLoggedIn: boolean; constructor(private authService: AuthService) { } ngOnInit(): void { this.isLoggedIn = this.authService.getIsAuth(); this.authStatSubs = this.authService .getAuthStatusListener() .subscribe(isAuthenticated => { this.isLoggedIn = isAuthenticated; }); console.log(this.isLoggedIn); // this.isLoggedIn = true; // this.authService.userType = 'mentor'; } doLogout() { this.authService.logout(); } }
d5c0350fd08524e1f336f398ea222b14d0f3d221
[ "TypeScript" ]
6
TypeScript
amuameya/modwebapp
42c050456f7798427893c934db39c42628bab290
51d32b3d701bf7f00e6415bc8743f48384eec2b0
refs/heads/master
<file_sep>require 'json' require 'open-uri' class GamesController < ApplicationController def new @letters = (0...10).map { ('A'..'Z').to_a[rand(26)] } end def score @word = params[:word].upcase @letters = params[:letters].split(' ') response = open("https://wagon-dictionary.herokuapp.com/#{@word}").read message = JSON.parse(response) if (@word.chars - @letters).empty? == false @result = "Sorry but #{@word} can't be built out of #{@letters}." elsif @word == message['word'] @result = "Congratulations! #{@word} is a valid English word!" else @result = "Sorry but #{@word} does not seem to be a valid English word..." end end end
c653f58deeed61fb729394afd35d887c83158ce6
[ "Ruby" ]
1
Ruby
jeancharlesvial/rails-longest-word-game
59d1f01a6c10ee156c5cc858d1a2f488cb882414
55432a53a94a90ac037c48ac107d1330211188b5
refs/heads/master
<file_sep># react-artist-search Building a simple react application to search for an band/musician and finding related artists using the Spotify API <file_sep>import React from 'react' class Search extends React.Component { constructor(props) { super(props) this.state = { term: '' } } onTermChange(term) { this.setState({term}) } onTermSubmission(event) { event.preventDefault(); let term = this.state.term this.props.onSearchSubmit(term) } render() { return( <div className="search col-lg-6 col-lg-push-3" > <form onSubmit={event => this.onTermSubmission(event)}> <span>Search: </span> <input onChange={event => this.onTermChange(event.target.value)} style={{ width: 400 }} /> </form> </div> ); } } export default Search<file_sep>import webpack from 'webpack'; // importing the module bundler import path from 'path'; // path comes from NodeJS // for more info on the webpack configuration, go to https://webpack.github.io/docs/configuration.html export default { // developer tool for debugging devtool: 'inline-source-map', // A SourceMap is added as DataUrl to the JavaScript file // entry point for our application entry: [ 'webpack-hot-middleware/client', // the Hot Module Replacement for express path.resolve(__dirname, 'src/index.js') // index.js is the entry point to our application ], // what compile method should webpack aim for target: 'web', // this is the default // options for the output file output: { path: path.resolve(__dirname, 'src'), publicPath: '/', filename: 'bundle.js' }, // This is not needed. this would be used for webpack-dev-server. // devServer: { // contentBase: path.resolve(__dirname, 'src') // }, // adding addtional plugins to the compiler plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin() ], // options affecting the nomal modules module: { // loaders allow for preprocessing of files loaders: [ { test: /\.js$/, exclude: /node_modules/, loaders: ['babel-loader'] }, // preprocessing the .js files with babel-loader // Used for Bootstrap Less Source Files { test: /\.less/, loader: 'style-loader!css!less-loader' }, // Used for Bootstrap Less Source Files { test: /\.css/, loader: 'style-loader!css-loader' }, // Used for Bootstrap Glyphicon Fonts { test: /\.(woff2|woff|ttf|svg|eot)$/, loader: 'file-loader' } ] } };<file_sep>import React from 'react' import ReactDOM from 'react-dom' import axios from 'axios' import Bootstrap from 'bootstrap/dist/css/bootstrap.css' import Search from './components/Search' import RelatedArtists from './components/RelatedArtists' import Artist from './components/Artist' class App extends React.Component { constructor(props) { super(props) this.state = { ready: false, searchedArtist: '', relatedArtists: [] } } handleSearchSubmit(term){ axios.get(`https://api.spotify.com/v1/search?q=${term}&type=artist`) .then((result) => { const searchedArtist = result.data.artists.items[0] this.setState({'searchedArtist': searchedArtist}) }) .then((result) => { axios.get(`https://api.spotify.com/v1/artists/${ this.state.searchedArtist.id }/related-artists`) .then((results) => { const relatedArtists = results.data.artists this.setState({'relatedArtists': relatedArtists}) }) .then(() => { this.setState({'ready': true}) }) }) } render() { return( <div className="react-artist-search container"> <div className="row"> <Search onSearchSubmit={ this.handleSearchSubmit.bind(this) }/> </div> {!this.state.ready ? <div className="row"><span className="col-lg-6 col-lg-push-3">Search for something</span></div> : <div> <div className="row"> <div className="col-lg-6 col-lg-push-3"> <h3>Searched Artist</h3> <Artist artist={this.state.searchedArtist} /> </div> </div> <div className="row"> <h4>Related Artist</h4> <RelatedArtists relatedArtists={this.state.relatedArtists} /> </div> </div> } </div> ); } } ReactDOM.render(<App />, document.getElementById('root'));
e8a838a3ad1915873ace48988f986901d150a89a
[ "Markdown", "JavaScript" ]
4
Markdown
tkearney18/react-artist-search
9c96f4acbb8a95080bd126e9220e0c0f260e777e
ea7f5844ed541beb8da874d922c253c2a60eaad2
refs/heads/master
<file_sep>#ifndef _POSTPROCESS_H #define _POSTPROCESS_H #include <iostream> #include <fstream> #include <cstdlib> #include <string.h> using namespace std; //Character classes const char CONSONANT[30][4] = {"ཀ", "ཁ", "ག", "ང", "ཅ", "ཆ", "ཇ", "ཉ", "ཏ", "ཐ", \ "ད", "ན", "པ", "ཕ", "བ", "མ", "ཙ", "ཚ", "ཛ", "ཝ", \ "ཞ", "ཟ", "འ", "ཡ", "ར", "ལ", "ཤ", "ས", "ཧ", "ཨ"}; const char LOWER_CONSONANT[30][4] = {"ྐ", "ྑ", "ྒ", "ྔ", "ྕ", "ྖ", "ྗ", "ྙ", "ྟ", "ྠ", \ "ྡ", "ྣ", "ྤ", "ྥ", "ྦ", "ྨ", "ྩ", "ྪ", "ྫ", "ྭ", \ "ྮ", "ྯ", "ཱ", "ྱ", "ྲ", "ླ", "ྴ", "ྶ", "ྷ", "ྸ"}; const char CACC1[10][4] = {"ག", "ང", "ད", "ན", "བ", "མ", "འ", "ར", "ལ", "ཤ"}; const char CACC2[2][4] = {"ད", "ས"}; const char UPPER_VOWEL[3][4] = {"ི", "ེ", "ོ"}; const char LOWER_VOWEL[4] = "ུ"; const char TSA_TSHA_ZA[3][4] = {"ཙ", "ཚ", "ཛ"}; const char RA_LA_SA[3][4] = {"ར", "ལ", "ས"}; const char NYA_TA_DA_HA[4][4] = {"ཉ", "ཏ", "ད", "ཧ"}; const char NYA_TA_DA_HA_LOWER[4][4] = {"ྙ", "ྟ", "ྡ", "ྷ"}; const char PUNCTUATION[2][4] = {"་", "།"}; //---End Character Classes --- //Function prototypes void get_characters(char *, char **&, int); void process_text(char **&, int, ofstream &); void clear(char **&, int length); #endif <file_sep>#include "postprocess.h" int main(int argc, char **argv) { ifstream infile(argv[1]); ofstream outfile("dzo.out"); char text_line[1024], **char_list = NULL; int length; if(!infile) { cout << "Error opening input File" << endl; exit(1); } if(!outfile) { cout << "Error opening output file" << endl; exit(1); } while (infile.getline(text_line, 1024)) { length = strlen(text_line) / 3; get_characters(text_line, char_list, length); for (int i = 0; i < length; i++) cout << char_list[i] << " "; cout << endl << "length = " << length << endl; process_text(char_list, length, outfile); clear(char_list, length); } return 0; } <file_sep>#include <iostream> #include <sstream> #include <fstream> #include "segment.h" using namespace cimg_library; using namespace std; int main (int argc, char **argv) { //check for correct command line arguments if (argc < 3) { cout << "Usage Error" << endl << "Usage: "<< argv[0] << " <input_image_name> <output_text_name>" << endl; exit (1); } //Load input image CImg <unsigned char> image; //try //{ image.load(argv[1]); //} //catch (CImgIOException ex) //{ //cout << "CImg Library Error : " << ex.message << endl; //exit (1); //} ofstream final_text(argv[2]); ifstream line_file; CImgList <unsigned char> image_list, image_block_list, image_component_list, line_cut, image_cut; int no_of_lines = 0, no_of_blocks = 0; char *img_filename = NULL; char *args = NULL; char *line_name; char buffer[1024]; //Process the image line_slice (image, image_list, 10); //Line segmentation no_of_lines = image_list.size(); line_cut.clear(); image_cut.clear(); cout << "No of lines: " << no_of_lines << endl; for (int i = 0; i < no_of_lines; i++) { //Create output file names for the images //string filename = "out/", temp_name; //std::ostringstream fileNum; //fileNum << (i + 1); //filename += fileNum.str(); //filename += ".tif"; //img_filename = &filename[0]; //Get vertical slices for all the lines vertical_slice(image_list[i], image_block_list, 3); //Vertical segmentation no_of_blocks = image_block_list.size(); for (int j = 0; j < no_of_blocks; j++) { //Get connected components and return new image with the segmented components arranged in a single image get_connected_components(image_block_list[j], image_component_list); line_cut.insert(get_composite_image(image_component_list)); image_component_list.clear(); } image_block_list.clear(); //get_composite_image(line_cut).save(img_filename); //Save the final segmented and arranged image for a line image_cut.insert(get_composite_image(line_cut)); line_cut.clear(); //Run tesseract on the saved image //string string_args = "/usr/local/bin/tesseract " + filename + " " + filename + " -l dzo"; //args = &string_args[0]; //system (args); //temp_name = filename + ".txt"; //line_name = &temp_name[0]; //line_file.open(line_name); //if(!line_file) //{ //cout << "Error opening text line File" << endl; //exit(1); //} //while (line_file.getline(buffer, 1024)) //{ // final_text << buffer; //} //final_text << endl; //line_file.close(); } image_list.clear(); //final_text.close(); cout << "calling " << endl; //Get composite image as well as individual lines get_composite_image_final(image_cut).save("out/out.png"); for (int i = 0; i < image_cut.size(); i++) { string filename = "out/"; std::ostringstream fileNum; fileNum << (i + 1); filename += fileNum.str(); filename += ".tif"; img_filename = &filename[0]; image_cut[i].save(img_filename); } return 0; } <file_sep>//Post Processing Functions #include "postprocess.h" //Function to get a dzongkha text line and store individual unicode strings in 2-d array for later processing void get_characters(char *text_line, char **&char_list, int length) { char text[4]; //Allocate space for char_list char_list = new char*[length]; for (int i = 0; i < length; i++) char_list[i] = new char[4]; //Copy each character in the character array int tracker = 0; for (int i = 0; i < length; i++) { for (int j = 0; j < 3; j++) { if (text_line[tracker + j] == ' ') //unwanted space in the text - ignore it and go to next char. { j = j - 1; tracker = tracker + 1; } else text[j] = text_line[tracker + j]; } text[3] = '\0'; strcpy(char_list[i], text); tracker = tracker + 3; } } //------End---- //function to clear the char_list structure after its use void clear(char **&char_list, int length) { for (int i = 0; i < length; i++) delete [] char_list[i]; delete [] char_list; } //--End chear--- //Functions to check the group in which unicode char falls bool is_consonant(char *text) { for (int i = 0; i < 30; i++) { if (strcmp(text, CONSONANT[i]) == 0) //is consonant return true; } return false; } bool is_lower_consonant(char *text) { for (int i = 0; i < 30; i++) { if(strcmp(text, LOWER_CONSONANT[i]) == 0) //is lower consonant return true; } return false; } bool is_cacc1(char *text) { for (int i = 0; i < 10; i++) { if(strcmp(text, CACC1[i]) == 0) //is CACC1 return true; } return false; } bool is_cacc2(char *text) { for (int i = 0; i < 2; i++) { if(strcmp(text, CACC2[i]) == 0) //is CACC2 return true; } return false; } bool is_upper_vowel(char *text) { for (int i = 0; i < 3; i++) { if(strcmp(text, UPPER_VOWEL[i]) == 0) //is upper vowel return true; } return false; } bool is_lower_vowel(char *text) { if(strcmp(text, LOWER_VOWEL) == 0) //is lower vowel return true; else return false; } bool is_punctuation(char *text) { for (int i = 0; i < 2; i++) { if(strcmp(text, PUNCTUATION[i]) == 0) //is upper vowel return true; } return false; } bool is_tsa_tsha_za(char *text) { for (int i = 0; i < 3; i++) { if (strcmp(text, TSA_TSHA_ZA[i]) == 0) //is Tsa or Tsha or Za return true; } return false; } bool is_ra_la_sa(char *text) { for (int i = 0; i < 3; i++) { if(strcmp(text, RA_LA_SA[i]) == 0) //is ra || la || sa return true; } return false; } int is_nya_ta_da_ha(char *text) { for (int i = 0; i < 4; i++) { if(strcmp(text, NYA_TA_DA_HA[i]) == 0) //is ra || la || sa return i; //return index here. not boolean } return -1; } //---End check --------- //Main processing function void process_text(char **&char_list, int length, ofstream &outfile) { for (int i = 0; i < length; i++) { if (is_consonant(char_list[i])) //start consonant check { if (is_tsa_tsha_za(char_list[i]) && is_upper_vowel(char_list[i + 1])) // checking for tsa, tsha, za + upper vowel ordering { outfile << char_list[i]; outfile << char_list[i + 1]; i = i +1; } else if(is_ra_la_sa(char_list[i]) && (is_nya_ta_da_ha(char_list[i + 1]) != -1)) //Checking ra, la sa + nya, ta, ha without upper vowel { int index = is_nya_ta_da_ha(char_list[i + 1]); outfile << char_list[i] << NYA_TA_DA_HA_LOWER[index]; i = i + 1; } else outfile << char_list[i]; } //-- End consonant ordering else if (is_lower_consonant(char_list[i])) { outfile << char_list[i]; } else if (is_upper_vowel(char_list[i])) // start upper vowel - things need to correct here - according to our segmentation output { if (is_punctuation(char_list[i + 1])) //if tsheg or shed follow upper vowel, we need no ordering . { outfile << char_list[i] << char_list[i + 1]; i = i + 1; } else if (is_ra_la_sa(char_list[i + 1]) && (is_nya_ta_da_ha(char_list[i + 2]) != -1)) //checking for nya, ta and ha with superscrib ra, la and sa { int index1 = is_nya_ta_da_ha(char_list[i + 2]); outfile << char_list[i + 1] << NYA_TA_DA_HA_LOWER[index1] << char_list[i]; i = i + 2; } else //generic upper vowel ordering { char temp[4]; strcpy(temp, char_list[i]); for (int count = 1; ; count ++) { if (is_consonant(char_list[i + count])) { outfile << char_list[i + count]; if (!is_lower_consonant(char_list[i + count +1])) { i = i + count; break; } } if (is_lower_consonant(char_list[i + count])) { outfile << char_list[i + count]; if (!is_lower_consonant(char_list[i + count +1])) { i = i + count; break; } } } outfile << temp; } } //--End upper vowel ordering else if (is_lower_vowel(char_list[i])) { outfile << char_list[i]; } else { outfile << char_list[i]; } } outfile << endl; } //---End---- <file_sep>// Preprocessing Functions for Dzongkha OCR #include "preprocess.h" // Function to Binarize the input image using Otsu Method // Function takes CImg object of grayimage and returns CImg object of the corresponding binary image CImg <unsigned char> binarize_by_otsu(CImg <unsigned char> gray_image) { int hist[GRAYLEVEL]; double prob[GRAYLEVEL], omega[GRAYLEVEL]; //Probabilities of graylevels double myu[GRAYLEVEL]; //mean value for separation double max_sigma, sigma[GRAYLEVEL]; // inter-class variance int threshold; //Threshold for binarization int width = gray_image.width(); int height = gray_image.height(); CImg <unsigned char> binary_image(width, height); //Initialize histogram for (int i = 0; i < GRAYLEVEL; i++) hist[i] = 0; cimg_forY(gray_image, y) { cimg_forX(gray_image, x) hist[int(gray_image(x, y))]++; } // calculation of probability density for (int i = 0; i < GRAYLEVEL; i ++ ) { prob[i] = (double)hist[i] / (width * height); } //omega & myu generation omega[0] = prob[0]; myu[0] = 0.0; //0.0 times prob[0] equals zero for (int i = 1; i < GRAYLEVEL; i++) { omega[i] = omega[i-1] + prob[i]; myu[i] = myu[i-1] + i*prob[i]; } // sigma maximization // sigma stands for inter-class variance // and determines optimal threshold value threshold = 0; max_sigma = 0.0; for (int i = 0; i < GRAYLEVEL-1; i++) { if (omega[i] != 0.0 && omega[i] != 1.0) sigma[i] = pow(myu[GRAYLEVEL-1]*omega[i] - myu[i], 2) / (omega[i]*(1.0 - omega[i])); else sigma[i] = 0.0; if (sigma[i] > max_sigma) { max_sigma = sigma[i]; threshold = i; } } //cout << "Threshold is = " << threshold << endl; //Create the binary image using threslhold cimg_forY(gray_image, y) { cimg_forX(gray_image, x) { if (int(gray_image(x, y)) > threshold) binary_image(x, y) = 255; else binary_image(x, y) = 0; } } return binary_image; } // End binarize_by_otsu <file_sep>#ifndef _PREPROCESS_H #define _PREPROCESS_H #include <iostream> #include "CImg.h" using namespace std; using namespace cimg_library; #define GRAYLEVEL 256 //No of Gray level CImg <unsigned char> binarize_by_otsu(CImg <unsigned char>); #endif <file_sep># dzocr A jumble of stuffs I wrote long time ago to implement a simple Dzonkgha OCR system using tesseract as the recognition engine.. 21 August 2017 - Created the repo as a backup for my old USB drive which is on the verge of giving up its ghost - More Readme materials will be added later <file_sep>#include <iostream> #include <sstream> #include "segment.h" using namespace std; int main(int argc, char *argv[]) { CImg <unsigned char> image(argv[1]); CImgList <unsigned char> image_list; vertical_slice(image, image_list, 3); string filename; char *img_filename = NULL; for (int i = 0; i < image_list.size(); i++) { std::ostringstream fileNum; fileNum << (i + 1); filename = fileNum.str(); filename += ".jpg"; img_filename = &filename[0]; image_list[i].save(img_filename); } return 0; } <file_sep> segmenter: segment.o segmenter.o g++ -o segmenter segmenter.o segment.o -ffast-math -lm -lpthread -I/usr/X11R6/include -L/usr/X11R6/lib -lX11 -Dcimg_strict -Dcimg_use_xshm -lXext -Dcimg_use_xrandr -lXrandr test_connected: segment.o test_connected.o g++ -o test_connected test_connected.o segment.o -ffast-math -lm -lpthread -I/usr/X11R6/include -L/usr/X11R6/lib -lX11 -Dcimg_strict -Dcimg_use_xshm -lXext -Dcimg_use_xrandr -lXrandr test_line_segment: segment.o test_line_segment.o g++ -o test_line_segment test_line_segment.o segment.o -ffast-math -lm -lpthread -I/usr/X11R6/include -L/usr/X11R6/lib -lX11 -Dcimg_strict -Dcimg_use_xshm -lXext -Dcimg_use_xrandr -lXrandr test_image_write: segment.o test_image_write.o g++ -o test_image_write test_image_write.o segment.o -ffast-math -lm -lpthread -I/usr/X11R6/include -L/usr/X11R6/lib -lX11 -Dcimg_strict -Dcimg_use_xshm -lXext -Dcimg_use_xrandr -lXrandr test_preprocess: preprocess.o test_preprocess.o g++ -o test_preprocess test_preprocess.o preprocess.o -ffast-math -lm -lpthread -I/usr/X11R6/include -L/usr/X11R6/lib -lX11 -Dcimg_strict -Dcimg_use_xshm -lXext -Dcimg_use_xrandr -lXrandr preprocess.o: preprocess.cpp g++ -c preprocess.cpp test_preprocess.o: test_preprocess.cpp g++ -c test_preprocess.cpp postprocessor: postprocessor.o postprocess.o g++ -o postprocessor postprocess.o postprocessor.o -ffast-math -lm -lpthread -I/usr/X11R6/include -L/usr/X11R6/lib -lX11 -Dcimg_strict -Dcimg_use_xshm -lXext -Dcimg_use_xrandr -lXrandr postprocessor.o: postprocessor.cpp g++ -c postprocessor.cpp postprocess.o: postprocess.cpp g++ -c postprocess.cpp dzocr: segment.o dzocr.o g++ -o dzocr dzocr.o segment.o -ffast-math -lm -lpthread -I/usr/X11R6/include -L/usr/X11R6/lib -lX11 -Dcimg_strict -Dcimg_use_xshm -lXext -Dcimg_use_xrandr -lXrandr test_connected.o: test_connected.cpp g++ -c test_connected.cpp test_line_segment.o: test_line_segment.cpp g++ -c test_line_segment.cpp test_image_write.o: test_image_write.cpp g++ -c test_image_write.cpp dzocr.o: dzocr.cpp g++ -c dzocr.cpp segmenter.o: segmenter.cpp g++ -c segmenter.cpp segment.o: segment.cpp g++ -c segment.cpp clean: rm -rf *.o segmenter test_connected cleanobject: rm *.o <file_sep>#include <iostream> #include "preprocess.h" using namespace std; int main(int argc, char *argv[]) { CImg <unsigned char> image(argv[1]), image1; image1 = binarize_by_otsu(image); image1.save(argv[2]); return 0; } <file_sep>// Segmentation functions for Dzongkha OCR #include "segment.h" // Connected component using the intrinsic stack based recursive implementation void connected_component(int **&image_map, int width, int height, int posx, int posy, int original_color, int replacement_color, bool &increase_color) { if(image_map[posx][posy] != original_color) return; if(image_map[posx][posy] == replacement_color) return; image_map[posx][posy] = replacement_color; increase_color = true; if(posx != 0) //Going West - Check posx is not a pixel in first col { connected_component(image_map, width, height, (posx - 1), posy, original_color, replacement_color, increase_color); //check North-West if(posy != 0) connected_component(image_map, width, height, (posx - 1), (posy - 1), original_color, replacement_color, increase_color); //check South-West if(posy != (height - 1)) connected_component(image_map, width, height, (posx - 1), (posy + 1), original_color, replacement_color, increase_color); } if(posy != 0) //Going North - Check posy is not a pixel in the first row connected_component(image_map, width, height, posx, (posy - 1), original_color, replacement_color, increase_color); if(posx != (width - 1)) //Going East - Check posx is not a pixel in last col { connected_component(image_map, width, height, (posx + 1), posy, original_color, replacement_color, increase_color); //check North-East if(posy != 0) connected_component(image_map, width, height, (posx + 1), (posy - 1), original_color, replacement_color, increase_color); //check South-East if(posy != (height - 1)) connected_component(image_map, width, height, (posx + 1), (posy + 1), original_color, replacement_color, increase_color); } if(posy != (height - 1)) //Going South - Check posy is not pixel in last row connected_component(image_map, width, height, posx, (posy + 1), original_color, replacement_color, increase_color); } // ************************* End of connected_components() ******************************** // Function to clear borde of image by 1 pixel CImg<unsigned char> clear_border(CImg<unsigned char> image) { int width = image.width(); int height = image.height(); for(int i = 0; i < width; i++) { image(i, 0) = 255; image(i, (height - 1)) = 255; } for(int j = 0; j < height; j++) { image(0, j) = 255; image((width - 1), j) = 255; } return image; } // ************************** Endo of clear_border() ********************* // Functions to get the position of the first pixel from top, bottom, left, right , of the given image int get_starty(CImg<unsigned char> image) { cimg_forY(image, y) { cimg_forX(image, x) { if (int(image(x, y)) == 0) return y; } } return 0; } // ********** End of get_starty() **************** int get_endy(CImg<unsigned char> image) { int height = image.height(); cimg_forY(image, y) { cimg_forX(image, x) { if (int(image(x, (height -1) - y)) == 0) return ((height -1) - y); } } return 0; } // ******************** End of get_endy() *********** int get_startx(CImg<unsigned char> image) { cimg_forX(image, x) { cimg_forY(image, y) { if (int(image(x, y)) == 0) return x; } } return 0; } // ******************** End of get_startx() *********** int get_endx(CImg<unsigned char> image) { int width = image.width(); cimg_forX(image, x) { cimg_forY(image, y) { if (int(image((width -1 ) - x, y)) == 0) return ((width -1 ) - x); } } return 0; } // **************************** End of get_endx() *********** // Function to return an image list consisting of all the images extracted by flood fill. The returned image list is in // "Left to Right, Top to Bottom" sorted. CImgList<unsigned char> get_images_sorted(int **&image_map, int width, int height, int no_of_components, int color) { CImg<unsigned char> image(width, height); CImgList<unsigned char> unordered_image_list, ordered_image_list, image_list; int startx[no_of_components], endx[no_of_components], starty[no_of_components], endy[no_of_components]; for(int i = 0; i < no_of_components; i++) { cimg_forY(image, y) { cimg_forX(image, x) { if(image_map[x][y] == color) image(x, y) = 0; else image(x, y) = 255; } } unordered_image_list.insert(image); color = color + 1; } // Order the unordered_image_list while(unordered_image_list.size() > 0) { if(unordered_image_list.size() >= 2) //more than or equal to two imagess yet to process { if(get_endx(unordered_image_list[0]) - get_startx(unordered_image_list[1]) > 4) // they are overlapping vertically { //cout << "2 images overlapping" << endl; //if(get_endy(unordered_image_list[0]) <= get_starty(unordered_image_list[1])) // 0 is probably upper vovel if(get_starty(unordered_image_list[0]) <= get_starty(unordered_image_list[1])) { //cout << "first image is vovel" << endl; ordered_image_list.insert(unordered_image_list[0]); ordered_image_list.insert(unordered_image_list[1]); unordered_image_list.pop_front(); unordered_image_list.pop_front(); } else //(get_endy(unordered_image_list[1]) <= get_starty(unordered_image_list[0])) 1 is probably upper vovel or something else { ordered_image_list.insert(unordered_image_list[1]); ordered_image_list.insert(unordered_image_list[0]); unordered_image_list.pop_front(); unordered_image_list.pop_front(); } } else //Not overlapping vertically - just insert the first image { ordered_image_list.insert(unordered_image_list[0]); unordered_image_list.pop_front(); } } else //only one image left { ordered_image_list.insert(unordered_image_list[0]); unordered_image_list.pop_front(); } } // Now clean the images, get border and send them back for(int i = 0; i < ordered_image_list.size(); i++) { //-1 and +1 to have one pixel border around the output image. and clear_border function ensures the one pixel border to be white/255 int startx = get_startx(ordered_image_list[i]); int starty = get_starty(ordered_image_list[i]); int endx = get_endx(ordered_image_list[i]); int endy = get_endy(ordered_image_list[i]); //check if the image is noise or not if((endx - startx) > 2 && (endy - starty) > 2) //Not noise image_list.insert(clear_border(ordered_image_list[i].crop(startx - 1 , starty - 1, endx + 1, endy +1))); } return image_list; } // **************************** End of get_image_sorted() *************************************** //Function to cut the image passed as the first argument horizontally (line segmentation/slicing) and place the segments in a CImgList object void line_slice(CImg<unsigned char> &image, CImgList<unsigned char> &image_list, int threshold) { CImg<unsigned char> temp; int width, height, no_of_lines, start_line[150], end_line[150], *horizontal_pixel_count; bool inside_pix = false; width = image.width(); height = image.height(); no_of_lines = 0; horizontal_pixel_count = new int[height]; //Initialize arrays that keep track of the line beginning and line end. Need to implement these trackers better for(int i = 0; i < 150; i++) { start_line[i] = 0; end_line[i] = height - 1; //So that if a line extends to the end of image height, it wont get a segfault. } //Initialize array containing line wise pixel counts to zeros for(int i = 0; i < height; i++) horizontal_pixel_count[i] = 0; //Horizontal Scanning to get the no of pixels in each row of the image cimg_forY(image, y) { cimg_forX(image, x) { if (int(image(x,y)) == 0) horizontal_pixel_count[y] = horizontal_pixel_count[y] + 1; } } //compute start and end of line for(int i = 0; i < height; i++) { if(horizontal_pixel_count[i] != 0 && !inside_pix) { //start of a new text line inside_pix = true; start_line[no_of_lines] = i; } else { if(horizontal_pixel_count[i] == 0 && inside_pix) { //end of text line inside_pix = false; end_line[no_of_lines] = i; //Check if the text line found is really a text line or noise by comparing height to a threshold if((end_line[no_of_lines] - start_line[no_of_lines]) >= threshold) { //It is indeed a line \0/, Now we go on to check for the next line no_of_lines = no_of_lines + 1; } } } } //Check to see if some lines are cut into 2 because of the upper vowels not touching the consonants //Checks whether the width b/t start of one line and end of next line is greater than a threshold or not for(int i = 0; i < no_of_lines; i++) { if((i + 1) < no_of_lines) //check to see if we have reached the last line or not. If its the last line, then theres nothing to check { //check for threshold if((start_line[i+1] - end_line[i]) <= 2 && (end_line[i] - start_line[i] < 20)) //gap is too small + previous line is too thin to be a line in itself.. probably part of line - we may need to get threshold dynamically { //join lines i and i+1 and shift the whole arrays one step forward and decrease the no_of_lines end_line[i] = end_line[i + 1]; for(int j = i + 1; j < (no_of_lines - 1); j++) { start_line[j] = start_line[j+1]; end_line[j] = end_line[j+1]; } no_of_lines = no_of_lines - 1; } } } //save all the horizontal line segments into the image_list CImgList object for(int i = 0; i < no_of_lines; i++) { temp = image.get_crop(0, start_line[i], (width - 1), (end_line[i] - 1)); image_list.insert(temp); } //Cleanup delete horizontal_pixel_count; } //************************ End Line Slice****************************** //Function to cut the image passed as the first argument vertically (vertical slicing) and place the segments in a CImgList object void vertical_slice(CImg<unsigned char> &image, CImgList<unsigned char> &image_list, int threshold) { CImg<unsigned char> temp; int width, height, no_of_blocks, start_block[150], end_block[150], *vertical_pixel_count; bool inside_pix = false; width = image.width(); height = image.height(); no_of_blocks = 0; vertical_pixel_count = new int[width]; //Initialize arrays that keep track of beginning and end of vertical blocks for(int i = 0; i < 150; i++) { start_block[i] = 0; end_block[i] = width - 1; //so that we dont segfault on some images } //Initialize the vertical pixel count array to zeros for(int i = 0; i < width; i++) vertical_pixel_count[i] = 0; //Vertical scanning to get no. of pixels in each column of the present line image cimg_forX(image, x) { cimg_forY(image, y) { if (int(image(x,y)) == 0) vertical_pixel_count[x] = vertical_pixel_count[x] + 1; } } //compute start and end of vertical block for(int i = 0; i < width; i++) { if(vertical_pixel_count[i] != 0 && !inside_pix) { //start of a new vertical block inside_pix = true; start_block[no_of_blocks] = i; } else { if(vertical_pixel_count[i] == 0 && inside_pix) { //end of text line inside_pix = false; end_block[no_of_blocks] = i; //Check if the text line found is really a text line or noise by comparing height to a threshold if((end_block[no_of_blocks] - start_block[no_of_blocks]) >= threshold) { //It is indeed a line \0/, Now we go on to check for the next line no_of_blocks = no_of_blocks + 1; } } } } //save all the horizontal line segments into the image_list CImgList object for(int i = 0; i < no_of_blocks; i++) { temp = image.get_crop(start_block[i], 0, (end_block[i] - 1), (height - 1)); //slice the temp image horizontally , i.e. the block height is not same as the parent line //image_list.insert(temp.get_crop(0, get_firstpix_top(temp), (temp.dimx() - 1), (temp.dimy() - 1))); image_list.insert(temp); } //Cleanup delete vertical_pixel_count; } //*********************End Vertical Slice*********************************************** //Function to get all the connected components from the input image, determine their order of writing and store in image list void get_connected_components(CImg<unsigned char> image, CImgList<unsigned char> &image_list) { CImg<unsigned char> temp_image; int **image_map, width, height; //Image map will have 0 for black pixels and 1 for background/white pixels int replacement_color = 2, no_of_components = 0; //replacement color begins from 2 and will increase for every conn. component width = image.width(); height = image.height(); image_map = new int* [width]; bool increase_color = false; //To keep track of the replacement color increment //Get image data into image_map cimg_forX(image, x) { image_map[x] = new int[height]; cimg_forY(image, y) { if (int(image(x,y)) == 0) image_map[x][y] = 0; //Black else image_map[x][y] = 1; //White } } //Call Flood Fill :-) for(int i = 0; i < width; i++) { for(int j = 0; j < height; j++) { if(image_map[i][j] == 0) connected_component(image_map, width, height, i, j, 0, replacement_color, increase_color); if(increase_color) { replacement_color = replacement_color + 1; no_of_components = no_of_components + 1; increase_color = false; } } } //Get the connected components marked with different colors as individual images keeping the writing order intact :-( int begin_color = 2; //the start color of the components image_list = get_images_sorted(image_map, width, height, no_of_components, begin_color); //Cleanup for (int i = 0; i < width; i++) delete [] image_map[i]; delete [] image_map; } //************************** End Get Connected Components ********************************* //************************ Get Composite Image - Horizontal (Line) *************************** CImg <unsigned char> get_composite_image(CImgList <unsigned char> image_list) { int no_of_images = image_list.size(); int width = 0, height = 0, temp = 0; int width_tracker = 5; //Get the greatest height and addition of all widths; for (int i =0; i < no_of_images; i++) { width = width + image_list[i].width(); if (image_list[i].height() > height) height = image_list[i].height(); } width = width + (5 * no_of_images) + 5; height = height + 1; CImg <unsigned char> image(width, height); image.fill(255); //Fill with white/background color for (int i =0; i < no_of_images; i++) { int w = image_list[i].width(); int h = image_list[i].height(); for (int x = 0; x < w; x++) { for (int y = 0; y < h; y++) { image(x + width_tracker, y + (height - h)) = image_list[i](x,y); } } width_tracker = width_tracker + w + 5; } return image; } //******************** End Composite Image - Line ************************ //******************** Get composite image - Final ************************* CImg <unsigned char> get_composite_image_final(CImgList <unsigned char> image_list) { int no_of_images = image_list.size(); cout << "no of images " << no_of_images << endl; int width = 0, height = 0, height_tracker = 5; // Find the greatest width among all the images in list. Get the addition of all heights for (int i = 0; i < no_of_images; i++) { height = height + image_list[i].height(); if (image_list[i].width() > width) width = image_list[i].width(); } height = height + (5 * no_of_images) + 5; width = width + 10; cout << "width and height found" << endl; // Create new image, draw all the images in image_list on this new image. CImg <unsigned char> image(width, height); image.fill(255); //Fill with white/background color for (int i = 0; i < no_of_images; i ++) { int w = image_list[i].width(); int h = image_list[i].height(); for (int x = 0; x < w; x++) { for (int y = 0; y < h; y++) image(x + 5, y + height_tracker) = image_list[i](x, y); } height_tracker = height_tracker + h + 5; cout << "done with image " << i + 1 << endl; } return image; } //******************** End Composite Image - Final ************************ <file_sep>/** Program to Segment an input image of Dzongkha text into respective lines and then lines into vertical blocks. (Basically Looks for whitespace between the lines and vertical blocks - Horizontal and Vertical Histograms) **/ #include <iostream> #include<fstream> #include <sys/stat.h> #include <sys/types.h> #include "segment.h" using namespace std; int main() { CImgList<unsigned char> image_line_list, image_block_list, image_component_list; int no_of_images; ifstream info_file("Info.txt"); info_file >> no_of_images; while(no_of_images > 0) { char inp = ' '; char output_file_name[64], system_args[256]; info_file >> inp; char main_dir_name[2] = {inp, '\0'}; char sub_dir_name[64]; char image_file_name[6] = {inp, '.', 'p', 'n', 'g', '\0'}; CImg<unsigned char> image(image_file_name); int no_of_lines = 0, no_of_blocks = 0, no_of_components = 0; line_slice(image, image_line_list, 10); //Call the line slicing function mkdir(main_dir_name, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); //Create main directory of the particular test image no_of_lines = image_line_list.size(); for(int i = 0; i < no_of_lines; i++) { char temp1[10]; //create sub directories strcpy(sub_dir_name, main_dir_name); strcat(sub_dir_name, "/"); sprintf(temp1, "%d", (i+1)); strcat(sub_dir_name, temp1); vertical_slice(image_line_list[i], image_block_list, 3); mkdir(sub_dir_name, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); //Create sub directory for ith line no_of_blocks = image_block_list.size(); for(int j = 0; j < no_of_blocks; j++) { get_connected_components(image_block_list[j], image_component_list); no_of_components = image_component_list.size(); for(int k = 0; k < no_of_components; k++) { char temp[10], component_name[2] = {char(97+k), '\0'}; strcpy(output_file_name, sub_dir_name); strcat(output_file_name, "/"); sprintf(temp, "%d", (j+1)); strcat(output_file_name, temp); strcat(output_file_name, component_name); strcat(output_file_name, ".tif"); image_component_list[k].save(output_file_name); //Calling Tesseract /**strcpy(system_args, "/usr/local/bin/tesseract "); strcat(system_args, output_file_name); strcat(system_args, " "); strcat(system_args, output_file_name); strcat(system_args, " -l dzo"); system(system_args);**/ //End of calling tesseract } image_component_list.clear(); } image_block_list.clear(); } image_line_list.clear(); no_of_images = no_of_images - 1; } return 0; } <file_sep>#ifndef _SEGMENT_H #define _SEGMENT_H #define cimg_debug 0 #include "CImg.h" #include <iostream> using namespace cimg_library; using namespace std; void connected_component(int **&, int, int, int, int, int, int, bool &); CImg<unsigned char> clear_border(CImg<unsigned char>); int get_starty(CImg<unsigned char>); int get_endy(CImg<unsigned char>); int get_startx(CImg<unsigned char>); int get_endx(CImg<unsigned char>); CImgList<unsigned char> get_images_sorted(int **&, int , int , int , int ); void line_slice(CImg<unsigned char> &, CImgList<unsigned char> &, int); void vertical_slice(CImg<unsigned char> &, CImgList<unsigned char> &, int ); void get_connected_components(CImg<unsigned char> , CImgList<unsigned char> &); CImg <unsigned char> get_composite_image(CImgList <unsigned char>); CImg <unsigned char> get_composite_image_final(CImgList <unsigned char>); #endif
6d988109a65ab6721921777ccb3046534ae09585
[ "Markdown", "Makefile", "C++" ]
13
C++
tenzin/dzocr
3ceec0ad88301b4beaf2ca5744b45208b5572563
8537cba6c0c950fc42bb2eb5c1af8a78e1f885a9
refs/heads/master
<repo_name>andrewmcdonough/dailyexercise<file_sep>/exercise.rb require 'sinatra' # Specify the list of developers and the start date for the rotation # -- EXERCISES = ["Plank","Wall Squat"] START_DATE = Time.mktime(2011,02,04) # -- SATURDAY_OFFSET = 6 - START_DATE.wday SUNDAY_OFFSET = 7 - START_DATE.wday get '/' do @who = what_exercise(Time.now) erb :index end def what_exercise(date) what_exercise_on_day(days_since_start(date)) end def what_exercise_on_day(day) developers = EXERCISES.clone (1..day).each do |i| next if [SATURDAY_OFFSET,SUNDAY_OFFSET].include? i % 7 # Don't rotate at weekends developers.rotate! end return developers[0] end def days_since_start(date) ((date - START_DATE) / (60*60*24)).floor end <file_sep>/config.ru require './exercise' run Sinatra::Application
3cdc1b3dc2e4c53c6b532c1e0c2cbc678855d28b
[ "Ruby" ]
2
Ruby
andrewmcdonough/dailyexercise
3a16090859c7906cbaee78747b5436e6cf1cbb0e
a3ffed587b7a677dc4980e1b94ffee0b41346784
refs/heads/master
<file_sep>'use strict'; module.exports = function(app) { var parser = require('../controllers/parserController'); app.route('/') .get(parser.parse_home); app.route('/parser/:landingUrl') .get(parser.parse_landingurl); };<file_sep># rest-api-meta-data-parser<file_sep>var og = require('open-graph'); var url = "http://google.com"; og(url, function(err, meta){ if (meta) { console.log(meta); } if (err) { console.log(err); } })<file_sep>var request = require('request'), bodyParser = require('body-parser'); var og = require('open-graph'); var express = require('express'), app = express(), port = process.env.PORT || 3000; app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); var routes = require('./api/routes/parserRoute'); routes(app); app.listen(port); console.log('Server started on: ' + port);
266e9c55528daf4cdd7f51a79366840691b5af83
[ "JavaScript", "Markdown" ]
4
JavaScript
npham20489/rest-api-meta-data-parser
b7b1e91018e17bd79c9f6b25e43609f1a96c37ed
0344fdbbde94126b91f6acc3447f57dd4bca4602
refs/heads/master
<file_sep>import React, { useContext } from "react"; import { Link } from "react-router-dom"; import styled from "styled-components"; import { heoresContext } from "../../context/heroesContext"; const HeroesStyles = styled.div` .heroes { margin: 0 0 2em 0; list-style-type: none; padding: 0; width: 15em; } .heroes li { cursor: pointer; position: relative; left: 0; background-color: #eee; margin: 0.5em; padding: 0.3em 0; height: 1.6em; border-radius: 4px; } .heroes a { text-decoration: none; } .heroes li:hover { color: #607d8b; background-color: #ddd; left: 0.1em; } .heroes li.selected { background-color: #cfd8dc; color: white; } .heroes li.selected:hover { background-color: #bbd8dc; color: white; } .heroes .badge { display: inline-block; font-size: small; color: white; padding: 0.8em 0.7em 0 0.7em; background-color: #405061; line-height: 1em; position: relative; left: -1px; top: -4px; height: 1.8em; margin-right: 0.8em; border-radius: 4px 0 0 4px; } `; const Heores = () => { const { heroes } = useContext(heoresContext); return ( <HeroesStyles> <h2>My Heroes</h2> <ul className="heroes"> {heroes.map((h) => ( <Link key={h.id} to={`/detail/${h.id}`}> <li> <span className="badge">{h.id}</span> {h.name} </li> </Link> ))} </ul> </HeroesStyles> ); }; export default Heores; <file_sep>import React, { useContext } from "react"; import { Link } from "react-router-dom"; import styled from "styled-components"; import { heoresContext } from "../../context/heroesContext"; const DashboardStyled = styled.div` [class*="col-"] { float: left; padding-right: 20px; padding-bottom: 20px; } [class*="col-"]:last-of-type { padding-right: 0; } a { text-decoration: none; } h3 { text-align: center; margin-bottom: 0; } h4 { position: relative; } .grid { margin: 0; } .col-1-4 { width: 15%; } .module { padding: 20px; text-align: center; color: #eee; max-height: 120px; min-width: 120px; background-color: #3f525c; border-radius: 2px; } .module:hover { background-color: #eee; cursor: pointer; color: #607d8b; } .grid-pad { padding: 10px 0; } .grid-pad > [class*="col-"]:last-of-type { padding-right: 20px; } @media (max-width: 600px) { .module { font-size: 10px; max-height: 75px; } } @media (max-width: 1024px) { .grid { margin: 0; } .module { min-width: 60px; } } `; const Dashboard = () => { const { heroes } = useContext(heoresContext); return ( <DashboardStyled> <h3>Top Heroes</h3> <div className="grid grid-pad"> {heroes.slice(1, 5).map((hero) => ( <Link key={hero.id} to={`/detail/${hero.id}`} className="col-1-4"> <div className="module hero"> <h4>{hero.name}</h4> </div> </Link> ))} </div> </DashboardStyled> ); }; export default Dashboard; <file_sep>import "./App.css"; import Heores from "./components/Heores"; import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; import HeroesProvider from "./context/heroesContext"; import Dashboard from "./components/Dashboard"; import HeroDetails from "./components/HeroDetails"; function App() { const title = "Tour of Heroes"; return ( <HeroesProvider> <Router> <div> <h1>{title}</h1> <nav> <Link to="/dashboard">Dashboard</Link> <Link to="/heroes">Heroes</Link> </nav> </div> <Switch> <Route path="/dashboard"> <Dashboard /> </Route> <Route path="/heroes"> <Heores /> </Route> <Route path="/detail/:id"> <HeroDetails /> </Route> <Route exact path="/detail"> <h3>Please select a hero.</h3> </Route> </Switch> </Router> </HeroesProvider> ); } export default App;
95275684660d9918501401d2566caacef6f521b7
[ "JavaScript" ]
3
JavaScript
miloszmos/ptsi-zal
ce7c41c116b269fd00963a34f5a9e11dd4236f8f
0e66644760edf203e65847f45e75902bd2aea7fc
refs/heads/master
<repo_name>ballaneypranav/.dotfiles<file_sep>/volume.sh #!/usr/bin/env bash # Allows controlling speaker volume and mic mute/unmute through media keys MAXVOLUME=100 device=$1 action=$2 if [[ $device = speaker ]]; then if [[ $action = toggle ]]; then pactl set-sink-mute @DEFAULT_SINK@ toggle elif [[ $action = inc ]]; then # get current volume SINK=$(pactl list short sinks | grep RUNNING | awk '{print $1}') NOW=$( pactl list sinks | grep '^[[:space:]]Volume:' | head -n $(( $SINK + 1 )) | tail -n 1 | sed -e 's,.* \([0-9][0-9]*\)%.*,\1,' ) # increase if possible if [[ $NOW -lt $MAXVOLUME ]]; then pactl set-sink-volume @DEFAULT_SINK@ +10% fi elif [[ $action = dec ]]; then pactl set-sink-volume @DEFAULT_SINK@ -10% fi elif [[ $device = mic ]]; then if [[ $action = toggle ]]; then pactl set-source-mute @DEFAULT_SOURCE@ toggle fi fi
c354e042945e070e3169b5747aa980ca9f2ba4b3
[ "Shell" ]
1
Shell
ballaneypranav/.dotfiles
d29379b47437296336e044fd2ce908463513aea2
3db09ed41f5ce123f616930d28305dbfff60a603
refs/heads/master
<file_sep>#!/bin/sh rm -rf ./default ./types if dir=$(nix-build release.nix -A dhall-kubernetes --no-out-link); then cp -r "$dir"/default . chmod u+w ./default cp -r "$dir"/types . chmod u+w ./types cp "$dir/README.md" README.md chmod u+w ./README.md fi <file_sep># `dhall-kubernetes` <img src="logo/dhall-kubernetes-logo.svg" alt="dhall-kubernetes logo" height="300px"/> `dhall-kubernetes` contains [Dhall][dhall-lang] bindings to [Kubernetes][kubernetes], so you can generate Kubernetes objects definitions from Dhall expressions. This will let you easily typecheck, template and modularize your Kubernetes definitions. ## Why do I need this Once you build a slightly non-trivial Kubernetes setup, with many objects floating around, you'll encounter several issues: 1. Writing the definitions in YAML is really verbose, and the actually important things don't stand out that much 2. Ok I have a bunch of objects that'll need to be configured together, how do I share data? 3. I'd like to reuse an object for different environments, but I cannot make it parametric.. 4. In general, I'd really love to reuse parts of some definitions in other definitions 5. Oh no, I typoed a key and I had to wait until I pushed to the cluster to get an error back :( The natural tendency is to reach for a templating language + a programming language to orchestrate that + some more configuration for it... But this is just really messy (been there), and we can do better. Dhall solves all of this, being a programming language with builtin templating, all while being non-Turing complete, strongly typed and [strongly normalizing][normalization] (i.e.: reduces everything to a normal form, no matter how much abstraction you build), so saving you from the *"oh-noes-I-made-my-config-in-code-and-now-its-too-abstract"* nightmare. For a Dhall Tutorial, see the [readme of the project][dhall-lang], or the [full tutorial][dhall-tutorial]. ## Prerequisites **NOTE**: `dhall-kubernetes` requires at least version `1.20.1` of [the interpreter](https://github.com/dhall-lang/dhall-haskell) (version `5.0.0` of the language). You can install the latest version with the following: ```bash stack install dhall-1.20.1 dhall-json-1.2.6 --resolver=nightly-2019-01-17 ``` ## Quickstart - main API We provide a simple API for the most common cases (For a list, see the [api](./api) folder). Let's say we'd like to configure a Deployment exposing an `nginx` webserver. In the following example, we: 1. Define a `config` for our service, by merging a [default config][default-deployment] (with the Dhall record-merge operator `//`) with a record with our parameters. 2. In there we define the details of the Deployment we care about (note that we do the same "merging with defaults" operation for our container as well, so we don't have to specify all the parameters) 3. We call the [`mkDeployment`][mkDeployment] function on our `config` ```haskell -- examples/deployment.dhall let config = ../api/Deployment/default // { name = "nginx" , replicas = 2 , containers = [ ../api/Deployment/defaultContainer // { name = "nginx" , imageName = "nginx" , imageTag = "1.15.3" , port = [ 80 ] : Optional Natural } ] } in ../api/Deployment/mkDeployment config ``` We then run this through `dhall-to-yaml` to generate our Kubernetes definition: ```bash dhall-to-yaml --omitNull < deployment.dhall ``` And we get: ```yaml ## examples/out/deployment.yaml apiVersion: apps/v1 kind: Deployment spec: revisionHistoryLimit: 20 selector: matchLabels: app: nginx strategy: rollingUpdate: maxSurge: 5 maxUnavailable: 0 type: RollingUpdate template: spec: containers: - image: nginx:1.15.3 imagePullPolicy: Always env: [] volumeMounts: [] resources: limits: cpu: 500m requests: cpu: 10m name: nginx ports: - containerPort: 80 volumes: [] metadata: name: nginx labels: app: nginx replicas: 2 metadata: name: nginx ``` ## Advanced usage - raw API If the main API is not enough (e.g. the object you'd like to generate is not in the list), you can just fall back on using the raw Types and defaults the library provides (and Pull Request here your program afterwards!). Let's say we want to generate an Ingress definition (for an [Nginx Ingress][nginx-ingress]) that contains TLS certs and routes for every service. For more examples of using this API see the [`./examples` folder](./examples). In the [`types`](./types) folder you'll find the types for the Kubernetes definitions. E.g. [here's][Ingress] the type for the Ingress. Since _most_ of the fields in all definitions are optional, for better ergonomics while coding Dhall we also generate default values for all types, in the [`default`](./default) folder. When some fields are required, the default value is a function whose input is a record of required fields, that returns the object with these fields set. E.g. the default for the Ingress is [this function][Ingress-default]. Let's say we have a Service with the following configuration: ```haskell -- examples/myConfig.dhall { name = "foo" , host = "foo.example.com" , version = "1.0.1" } ``` That has the following type: ```haskell -- examples/Config.dhall { name : Text , host : Text , version : Text } ``` We can now expose this service out to the world with the Ingress: ```haskell -- examples/ingressRaw.dhall -- Prelude imports let map = (../Prelude.dhall).`List`.map -- dhall-kubernetes types and defaults in let TLS = ../types/io.k8s.api.extensions.v1beta1.IngressTLS.dhall in let Rule = ../types/io.k8s.api.extensions.v1beta1.IngressRule.dhall in let RuleVal = ../types/io.k8s.api.extensions.v1beta1.HTTPIngressRuleValue.dhall in let Spec = ../types/io.k8s.api.extensions.v1beta1.IngressSpec.dhall in let Ingress = ../types/io.k8s.api.extensions.v1beta1.Ingress.dhall in let defaultIngress = ../default/io.k8s.api.extensions.v1beta1.Ingress.dhall in let defaultMeta = ../default/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta.dhall in let defaultSpec = ../default/io.k8s.api.extensions.v1beta1.IngressSpec.dhall in let IntOrString = ../types/io.k8s.apimachinery.pkg.util.intstr.IntOrString.dhall -- Our Service type in let Service = ./Config.dhall in let Config = { services : List Service } -- A function to generate an ingress given a configuration in let mkIngress : Config -> Ingress = \(config : Config) -> -- Given a service, make a TLS definition with their host and certificate let makeTLS = \(service : Service) -> { hosts = Some [ service.host ] , secretName = Some "${service.name}-certificate" } -- Given a service, make an Ingress Rule in let makeRule = \(service : Service) -> { host = Some service.host , http = Some { paths = [ { backend = { serviceName = service.name , servicePort = IntOrString.Int 80 } , path = None Text } ] } } -- Nginx ingress requires a default service as a catchall in let defaultService = { name = "default" , host = "default.example.com" , version = " 1.0" } -- List of services in let services = config.services # [ defaultService ] -- Some metadata annotations -- NOTE: `dhall-to-yaml` will generate a record with arbitrary keys from a list -- of records where mapKey is the key and mapValue is the value of that key in let genericRecord = List { mapKey : Text, mapValue : Text } in let kv = \(k : Text) -> \(v : Text) -> { mapKey = k, mapValue = v } in let annotations = Some [ kv "kubernetes.io/ingress.class" "nginx" , kv "kubernetes.io/ingress.allow-http" "false" ] -- Generate spec from services in let spec = defaultSpec // { tls = Some (map Service TLS makeTLS services) , rules = Some (map Service Rule makeRule services) } in defaultIngress { metadata = defaultMeta { name = "nginx" } // { annotations = annotations } } // { spec = Some spec } -- Here we import our example service, and generate the ingress with it in mkIngress { services = [ ./myConfig.dhall ] } ``` As before we get the yaml out by running: ```bash dhall-to-yaml --omitNull < ingress.yaml.dhall ``` Result: ```yaml ## examples/out/ingressRaw.yaml apiVersion: extensions/v1beta1 kind: Ingress spec: rules: - http: paths: - backend: servicePort: 80 serviceName: foo host: foo.example.com - http: paths: - backend: servicePort: 80 serviceName: default host: default.example.com tls: - hosts: - foo.example.com secretName: foo-certificate - hosts: - default.example.com secretName: default-certificate metadata: annotations: kubernetes.io/ingress.class: nginx kubernetes.io/ingress.allow-http: 'false' name: nginx ``` ## Development ### Updating the nixpkgs snapshot (and kubernetes version) Run ```bash ./scripts/update-nixpkgs.sh ./generate.sh ``` If the tests fail, rollback. If they don't then you have sucessfully upgraded! ### Tests All tests are defined in `release.nix`. We run these tests in CI in a [Hydra project][hydra-project]. You can run the tests locally with the following command: ```bash nix build --file ./release.nix ``` ### Generating `types` `default` and `README.md` Running `scripts/generate.sh` will generate all dhall files from the kubernetes swagger specification, and copy them to `types` and `default`. It will also generate `README.md` from `docs/README.md.dhall`. If you make changes to `scripts/convert.py` or `docs/README.md.dhall`, you need to run this command afterwards. ## Projects Using `dhall-kubernetes` * [dhall-prometheus-operator][dhall-prometheus-operator]: Provides types and default records for [Prometheus Operators][prometheus-operator]. [hydra-project]: http://hydra.dhall-lang.org/project/dhall-kubernetes [dhall-lang]: https://github.com/dhall-lang/dhall-lang [kubernetes]: https://kubernetes.io/ [normalization]: https://en.wikipedia.org/wiki/Normalization_property_(abstract_rewriting) [nginx-ingress]: https://github.com/kubernetes/ingress-nginx [dhall-tutorial]: http://hackage.haskell.org/package/dhall-1.17.0/docs/Dhall-Tutorial.html [default-deployment]: ./api/Deployment/default [mkDeployment]: ./api/Deployment/mkDeployment [Ingress]: ./types/io.k8s.api.extensions.v1beta1.Ingress.dhall [Ingress-default]: ./default/io.k8s.api.extensions.v1beta1.Ingress.dhall [prometheus-operator]: https://github.com/coreos/prometheus-operator [dhall-prometheus-operator]: https://github.com/coralogix/dhall-prometheus-operator <file_sep>#! /usr/bin/env python3 import json import re import sys # See https://kubernetes.io/docs/concepts/overview/working-with-objects/kubernetes-objects/#required-fields # because k8s API allows PUTS etc with partial data, it's not clear from the data types OR the API which # fields are required for A POST... so we resort to .. RTFM always_required = {'apiVersion', 'kind', 'metadata'} required_for = { 'io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta': {'name'}, } not_required_for = { 'io.k8s.api.core.v1.ObjectFieldSelector': {'apiVersion'}, } def schema_path_from_ref(prefix, ref): return '{}/{}.dhall'.format(prefix, ref.split('/')[2]) def required_properties (schema_name, schema): required = set(schema.get('required', [])) | always_required if schema_name in required_for.keys(): required |= required_for[schema_name] if schema_name in not_required_for.keys(): required -= not_required_for[schema_name] return required def build_type(schema, path_prefix, schema_name=None): """ Take an OpenAPI Schema Object and return a corresponding Dhall type. If the schema is a reference we translate the reference path to a Dhall path and return that path. The ``path_prefix`` argument is prepended to the returned path. """ if '$ref' in schema: return schema_path_from_ref(path_prefix, schema['$ref']) elif 'type' in schema: typ = schema['type'] if typ == 'object': return '(List {mapKey : Text, mapValue : Text})' elif typ == 'array': return 'List {}'.format(build_type(schema['items'], path_prefix)) # Fix for the funny format parameters they use in Kube elif typ == 'string' and 'format' in schema and schema['format'] == 'int-or-string': return '< Int : Natural | String : Text >' else: return { 'string' : 'Text', 'boolean': 'Bool', 'integer': 'Natural', 'number': 'Double', }[typ] elif 'properties' in schema: required = required_properties(schema_name, schema) fields = [] for propName, propSpec in schema['properties'].items(): propType = build_type(propSpec, path_prefix) if propName not in required: propType = 'Optional ({})'.format(propType) fields.append(' {} : ({})\n'.format(labelize(propName), propType)) return '{' + ','.join(fields) + '}' else: # There are empty schemas that only have a description. return '{}' def get_default(prop, required, value): typ = build_type(prop, '../types') if not required: return '([] : Optional ({}))'.format(typ) elif value: return '("{}" : {})'.format(value, typ) else: raise ValueError('Missing value for required property') def get_static_data(modelSpec): """ Return a dictionary of static values that all objects of this model have. This applies only to kubernetes resources where ``kind`` and ``apiVersion`` are statically determined by the resource. See the `Kubernetes OpenAPI Spec Readme`__. For example for a v1 Deployment we return :: { 'kind': 'Deployment', 'apiVersion': 'apps/v1' } .. __: https://github.com/kubernetes/kubernetes/blob/master/api/openapi-spec/README.md#x-kubernetes-group-version-kind """ if 'x-kubernetes-group-version-kind' in modelSpec: values = modelSpec['x-kubernetes-group-version-kind'] if len(values) == 1: group = values[0].get('group', '') if group: group = group + '/' return { 'kind': values[0]['kind'], 'apiVersion': group + values[0]['version'] } else: return {} else: return {} def labelize(propName): """ If a propName doesn't match the 'simple-label' grammar, we return a quoted label See: https://github.com/dhall-lang/dhall-lang/blob/1d2912067658fdbbc17696fc86f057d6f91712b9/standard/dhall.abnf#L125 """ if not re.match("^[a-zA-Z_][a-zA-Z0-9_\-/]*$", propName): return "`" + propName + "`" else: return propName def main(): with open(sys.argv[1]) as specf: spec = json.load(specf) for modelName, modelSpec in spec['definitions'].items(): with open('types/' + modelName + '.dhall', 'w') as f: f.write('{}\n'.format(build_type(modelSpec, '.', modelName))) with open('default/' + modelName + '.dhall', 'w') as f: if 'type' in modelSpec: typ = build_type(modelSpec, '../types') # In case we have a union, we make the constructors for it if typ[0] == '<': f.write('{}\n'.format(typ)) # Otherwise we just output the identity else: f.write('\(a : {}) -> a\n'.format(typ)) elif '$ref' in modelSpec: path = schema_path_from_ref('.', modelSpec['$ref']) f.write('{}\n'.format(path)) else: required = required_properties(modelName, modelSpec) if modelName in required_for.keys(): required |= required_for[modelName] properties = modelSpec.get('properties', {}) resource_data = get_static_data(modelSpec) param_names = required - set(resource_data.keys()) # If there's multiple required props, we make it a lambda requiredProps = [k for k in properties if k in required] if len(requiredProps) > 0: params = ['{} : ({})'.format(labelize(propName), build_type(propVal, '../types')) for propName, propVal in properties.items() if propName in param_names] f.write('\(_params : {' + ', '.join(params) + '}) ->\n') # If it's required we're passing it in as a parameter KVs = [(propName, "_params." + propName) if propName in param_names else (propName, get_default(propDef, propName in required, resource_data.get(propName, None))) for propName, propDef in properties.items()] # If there's no fields, should be an empty record if len(KVs) > 0: formatted = [" {} = {}\n".format(labelize(k), v) for k, v in KVs] else: formatted = '=' f.write('{' + ','.join(formatted) + '} : ../types/' + modelName + '.dhall\n') if __name__ == '__main__': main() <file_sep>.PHONY: install build check default default: build README.md: docs/README.md.dhall ./scripts/build-readme.sh build: README.md mkdir -p types default ./scripts/convert.py "${OPENAPI_SPEC}" check: build LC_ALL=en_US.UTF-8 ./scripts/check-source.py mkdir -p tmp LC_ALL=en_US.UTF-8 ./scripts/build-examples.py tmp install: build cp -r types default "${out}" cp README.md "${out}"
45c1a4edc4ca4c23e65ba9b2757122198d54ffe7
[ "Markdown", "Python", "Makefile", "Shell" ]
4
Shell
Atidot/dhall-kubernetes
69c85131d17816889311905aaacfcb621dcaf59c
ed07f9d45aeb6f22ec3c960efd07fca205a84c38
refs/heads/master
<file_sep># codenarc-example <file_sep> #!/usr/bin/env sh export GROOVY_VERSION=2.5.0 export GROOVY_HOME=${HOME}/.sdkman/candidates/groovy/${GROOVY_VERSION} export GROOVY_JAR="" # export GROOVY_JAR=${GROOVY_JAR}:${GROOVY_HOME}/embeddable/groovy-all-${GROOVY_VERSION}.jar # Invalid since Groovy 2.5. export GROOVY_JAR=${GROOVY_JAR}:${GROOVY_HOME}/lib/groovy-${GROOVY_VERSION}.jar export GROOVY_JAR=${GROOVY_JAR}:${GROOVY_HOME}/lib/groovy-templates-${GROOVY_VERSION}.jar export GROOVY_JAR=${GROOVY_JAR}:${GROOVY_HOME}/lib/groovy-xml-${GROOVY_VERSION}.jar export REQUIRED_JAR="" export REQUIRED_JAR=${REQUIRED_JAR}:${PWD}/lib/CodeNarc-1.0.jar export REQUIRED_JAR=${REQUIRED_JAR}:${PWD}/lib/slf4j-api-1.7.25.jar export REQUIRED_JAR=${REQUIRED_JAR}:${PWD}/lib/slf4j-simple-1.7.25.jar export REQUIRED_JAR=${REQUIRED_JAR}:${PWD}/lib/GMetrics-1.0.jar export CLASSPATH=${GROOVY_JAR}:${REQUIRED_JAR} java -classpath ${CLASSPATH} org.codenarc.CodeNarc # In order to cater to the module system of Java 9+, only the individual jar files of the core and all modules will be provided since Groovy 2.5.0, i.e. the fat jar file groovy-all-x.y.z.jar will not be available. # http://groovy-lang.org/download.html # CodeNarc # https://search.maven.org/remotecontent?filepath=org/codenarc/CodeNarc/1.0/CodeNarc-1.0.jar # Command Options: # http://codenarc.sourceforge.net/codenarc-command-line.html # -includes="**/*.groovy,**/Jenkinsfile,**/*.gr" # -rulesetfiles=rulesets/basic.xml,rulesets/braces.xml,rulesets/concurrency.xml,rulesets/convention.xml,rulesets/design.xml,rulesets/dry.xml,rulesets/enhanced.xml,rulesets/exceptions.xml,rulesets/formatting.xml,rulesets/generic.xml,rulesets/grails.xml,rulesets/groovyism.xml,rulesets/imports.xml,rulesets/jdbc.xml,rulesets/junit.xml,rulesets/logging.xml,rulesets/naming.xml,rulesets/security.xml,rulesets/serialization.xml,rulesets/size.xml,rulesets/unnecessary.xml,rulesets/unused.xml # ./codeNarcing.sh -includes="**/*.groovy,**/Jenkinsfile,**/*.gr" -rulesetfiles=rulesets/basic.xml,rulesets/braces.xml,rulesets/concurrency.xml,rulesets/convention.xml,rulesets/design.xml,rulesets/dry.xml,rulesets/enhanced.xml,rulesets/exceptions.xml,rulesets/formatting.xml,rulesets/generic.xml,rulesets/grails.xml,rulesets/groovyism.xml,rulesets/imports.xml,rulesets/jdbc.xml,rulesets/junit.xml,rulesets/logging.xml,rulesets/naming.xml,rulesets/security.xml,rulesets/serialization.xml,rulesets/size.xml,rulesets/unnecessary.xml,rulesets/unused.xml # SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder" # https://www.slf4j.org/codes.html#StaticLoggerBinder # This warning message is reported when the org.slf4j.impl.StaticLoggerBinder class could not be loaded into memory. # This happens when no appropriate SLF4J binding could be found on the class path. # Placing one (and only one) of slf4j-nop.jar slf4j-simple.jar, slf4j-log4j12.jar, slf4j-jdk14.jar or logback-classic.jar on the class path should solve the problem. # https://search.maven.org/remotecontent?filepath=org/slf4j/slf4j-api/1.7.25/slf4j-api-1.7.25.jar # https://search.maven.org/remotecontent?filepath=org/slf4j/slf4j-simple/1.7.25/slf4j-simple-1.7.25.jar # java.lang.NoClassDefFoundError: org/gmetrics/metric/Metric # https://search.maven.org/remotecontent?filepath=org/gmetrics/gmetrics/1.0/gmetrics-1.0.jar # java.lang.NoClassDefFoundError: org/junit/Assert # https://search.maven.org/remotecontent?filepath=junit/junit/4.12/junit-4.12.jar
5a9d0ce34c49f5a11cb45308fbd166539793d7d2
[ "Markdown", "Shell" ]
2
Markdown
sheeeng/codenarc-example
1fb96697b6807e32c49044825e5da8dadced67e2
d250153fcd3d70fd45a5cfeb54fbf53b8a4d6d7c
refs/heads/master
<repo_name>vazhakolil/angularWork<file_sep>/app/services/loginService.js /** * Created by rajeevan.vazhakolil on 4/18/2016. */ var app=angular.module('myApp', [ 'ngRoute' ])<file_sep>/app/services/deals.js /** * Created by rajeevan.vazhakolil on 4/23/2016. */ var deals=angular.module('dealsModule', [ ]) deals.service('dealsToday',[function(){ var dealService=this; this.getDealsToday=function(input){ var data=[{ 'imgSrc':'tempImages/shirt.jpg', 'name':'Logo Shirt (Gray)', 'price':'20.5' },{ 'imgSrc':'tempImages/shirt1.jpg', 'name':'white Shirt (Gray)', 'price':'20.5' },{ 'imgSrc':'tempImages/shirt.jpg', 'name':'Logo Shirt (Gray)', 'price':'20.5' } ,{ 'imgSrc':'tempImages/shirt.jpg', 'name':'Logo Shirt (Gray)', 'price':'20.5' },{ 'imgSrc':'tempImages/shirt.jpg', 'name':'Logo Shirt (Gray)', 'price':'20.5' },{ 'imgSrc':'tempImages/shirt.jpg', 'name':'Logo Shirt (Gray)', 'price':'20.5' },{ 'imgSrc':'tempImages/shirt.jpg', 'name':'Logo Shirt (Gray)', 'price':'20.5' } ] return data; } }])<file_sep>/app/services/carouselDataService.js var carouselServiceModule=angular.module('carouselDataServiceModule',[]) carouselServiceModule.service('carouselDataService',function(){ var carouselDataService=this; carouselDataService.getTodaysFruitDeals= function() { var fruits=[{ 'imgSrc':'tempImages/currant.jpg', 'name':'currant', 'price':'20.5' },{ 'imgSrc':'tempImages/mango.jpg', 'name':'mango', 'price':'20.5' },{ 'imgSrc':'tempImages/banana.jpg', 'name':'banana', 'price':'20.5' } ,{ 'imgSrc':'tempImages/strawberries.jpg', 'name':'strawberries', 'price':'20.5' }] return fruits; } }); <file_sep>/app/directives/carousleDirective.js /** * Created by rajeevan.vazhakolil on 4/24/2016. * This is a test for directives */ var carouselApp= angular.module('carosuelDirectiveModule',['carouselDataServiceModule']) carouselApp.directive('carouselTag',['carouselDataService','$timeout',function(carouselDataService,$timeout){ return{ restrict:'E', templateUrl:'views/carousleTemplate.html', link:function($scope,element,attr){ // $scope.data=carouselDataService.getTodaysFruitDeals(); // element.carousel({interval: false}); /* element.bind('click', function() { // var src = elem.find('img').attr('src'); alert("dfsd"); // call your SmoothZoom here // angular.element(attrs.options).css({'background-image':'url('+ scope.item.src +')'}); }); */ /* $timeout(function() { angular.element('.carousel[data-type="multi"] .item').each(function(){ var next = $(this).next(); if (!next.length) { next = $(this).siblings(':first'); } next.children(':first-child').clone().appendTo($(this)); for (var i=0;i<2;i++) { next=next.next(); if (!next.length) { next = $(this).siblings(':first'); } next.children(':first-child').clone().appendTo($(this)); } }); }); */ $timeout(setCarousleMulti()); }, controller: function($scope, $element){ $element.carousel({interval: false}); $scope.prev=function() { $element.carousel("prev"); } $scope.next=function() { $element.carousel("next"); } } } }]) function setCarousleMulti() { angular.element('.carousel[data-type="multi"] .item').each(function(){ var next = $(this).next(); if (!next.length) { next = $(this).siblings(':first'); } next.children(':first-child').clone().appendTo($(this)); for (var i=0;i<2;i++) { next=next.next(); if (!next.length) { next = $(this).siblings(':first'); } next.children(':first-child').clone().appendTo($(this)); } }); }
3f789d3e483c5784cd41de63264ce8527ace1dfc
[ "JavaScript" ]
4
JavaScript
vazhakolil/angularWork
f5e7b76835927e553a947dbc520046dbabc2d53e
1196d78e2d78854ce469494a1b48507a12053c1f
refs/heads/master
<repo_name>Akhilchennu/Weather<file_sep>/src/Components/weather.js import React from 'react'; import Card from '@material-ui/core/Card'; import CardContent from '@material-ui/core/CardContent'; import WeatherIcon from 'react-icons-weather'; import '../App.css'; function Weather(props) { const { responseData: { name, weather, main, sys,coord,wind,clouds,visibility }, degress } = props return ( <div className="blockStyle"> <div className="cardBlock"> <Card className="flex"> <CardContent> <div className="centerAlign"> <WeatherIcon name="owm" iconId={weather[0].id.toString()} flip="horizontal" rotate="90" /> <span className="boldFont subHeading">{`${name},${sys["country"]} Temparature`}</span> </div> <div className="boldFont marginAlign">{weather[0].description}</div> <div className="weatherRightBlock"> <table> <tbody> <tr> <td>Temparature in Kelvin</td> <td>{`${main['temp']}k`}</td> </tr> <tr> <td >Temparature in Degres</td> <td>{`${Math.ceil(main['temp'] - degress)}℃`}</td> </tr> <tr> <td >Temparature in Fahrenheit</td> <td>{`${(parseInt(main['temp'] - degress) * 1.8) + 32}℉`}</td> </tr> <tr> <td > Max Temparature</td> <td>{`${main['temp_max']}k`}</td> </tr> <tr> <td > Max Temparature</td> <td>{`${main['temp_min']}k`}</td> </tr> <tr> <td > Max Temparature</td> <td>{`${main['temp_min']}k`}</td> </tr> </tbody> </table> </div> </CardContent> </Card> <Card className="cardColor flex"> <CardContent className="contentColor"> <div className="centerAlign"> <span className="boldFont subHeading">{`${name},${sys["country"]} Additional Info`}</span> </div> <div className="boldFont marginAlign">{`RealFeel®${main['feels_like']}`}</div> <div className="weatherRightBlock"> <table> <tbody> <tr> <td>Latitude</td> <td>{`${coord["lat"]}°`}</td> </tr> <tr> <td >Longitude</td> <td>{`${coord["lon"]}°`}</td> </tr> <tr> <td >Wind Speed</td> <td>{`${wind["speed"]}meter/sec`}</td> </tr> <tr> <td >Humidity</td> <td>{`${main["humidity"]}%`}</td> </tr> <tr> <td >Pressure</td> <td>{`${main['pressure']}hpa`}</td> </tr> <tr> <td >Cloudiness</td> <td>{`${clouds['all']}%`}</td> </tr> <tr> <td >Visibility</td> <td>{`${visibility}`}</td> </tr> </tbody> </table> </div> </CardContent> </Card> </div> </div> ); } export default Weather;<file_sep>/src/App.js import React, { useState } from 'react'; import Selectcity from './Components/select'; import Weather from './Components/weather'; import Button from '@material-ui/core/Button'; import { useSelector } from 'react-redux'; import { service } from './Services/service'; import './App.css'; function App() { const weatherData = useSelector(state => state.weatherData); const [result,getResult]=useState([]) const [buttonDisable,getButtonDisable]=useState(false) const getUpdates=()=>{ if(weatherData.length>0){ getButtonDisable(true); const responseData = service.getWeatherData(weatherData); responseData.then((data)=>{ if(data.success){ getResult(data.weather); getButtonDisable(false); }else{ } }).catch((error)=>{ console.log("error"); }) } } return ( <> <div className="boldFont marginAlign">Select city to get weather updates</div> <Selectcity /> <div className="marginAlign"> <Button disabled={weatherData.length === 0 || buttonDisable} className="buttonStyle" variant="contained" color="primary" onClick={getUpdates}>Get Updates</Button> </div> {result.length>0 && weatherData.length>0?<><div className="boldFont marginAlign">CURRENT WEATHER</div> <div className="maindiv"> {result.map((value)=>{ return <Weather responseData={value} key={value.id} degress={273.15}/> })} </div> </>:null} </> ); } export default App; <file_sep>/src/Services/service.js export const service={ getWeatherData } function getWeatherData(weatherData){ return fetch('http://localhost:3002/getWeatherUpdates',{ method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ weatherData: weatherData }) }).then(response => response.json()) }
75fd2ce0036da1aa34c41d9a78a93deeabe98c32
[ "JavaScript" ]
3
JavaScript
Akhilchennu/Weather
1bf39b74b480a29f05c4da01f09acf98ad14c491
67f1c494cc2e71a5319c04b1451867b52ebbecc2
refs/heads/master
<file_sep>from flask import Flask, render_template import sqlite3 app = Flask(__name__) # establish a connection with the database file conn = sqlite3.connect('flowers2019.db') # create a cursor to query the database; does NOT change cursorObj = conn.cursor() # All items retrieval from FLOWERS table in DB cursorObj.execute("SELECT * FROM FLOWERS") # save fetch all to itemsFlowers list; to be referenced in templates itemsFlowers = cursorObj.fetchall() # close the connection to the database conn.close() @app.route('/flowers') def flowers(): return render_template('flowers.html',itemsFlowers=itemsFlowers) @app.route('/') def index(): return render_template('index.html') if __name__ == '__main__': app.run()
750d37addd8ee831bbaf9bdd26e641082988e3a2
[ "Python" ]
1
Python
Jhavaa/assign5_2
090e0551a43679b96f7841a5ab3614a0ee650a31
f1055b24bc7b2ef6d61e849dab813c2752f5e3d1
refs/heads/master
<file_sep># RESTful Web API with Node.js Framework (ExpressJS) This project exposes a [levelDB](https://github.com/Level/level) blockchain database to a publicly accessible API. I have built the API on top of the popular NodeJS minimal framework [ExpressJS](https://expressjs.com/). ## How to use this API: #### Install the code 1. Download OR clone this GitHub repository 2. Open a terminal or command-prompt and navigate to the directory where this repository was saved and type: `npm install` 3. From terminal or command-prompt (remaining in the same directory as above) type: `node app.js` #### Get a block from the database * Make a `GET` request from a web browser or via a utility of your choice such as [Curl](https://curl.haxx.se/) or [PostMan](https://www.getpostman.com/). The request endpoint follows the structure: `localhost:8000/block/[block-index]` * Example `GET` request that will return the block at index 0 using curl: `curl localhost:8000/block/0` #### Insert a new Block to the database * Make a `POST` request with a single key value pair (the key must be named "body") * Example `POST` request using curl: `curl -d "body=mock%20data" -X POST http://localhost:8000/block` <br/> #### Errors * If you send a `POST` request without the correct body data (key = body), then you will receive an error message and your new block will NOT be created. <br/> Enjoy! <file_sep>//Importing Express.js module const express = require("express"); //Importing BodyParser.js module const bodyParser = require("body-parser"); /** * Class Definition for the REST API */ class BlockAPI { /** * Constructor that allows initialize the class */ constructor() { // create the express application instance. this.app = express(); // setup the port. this.initExpress(); // setup the middleware - body-parser in our case for incoming req bodies. this.initExpressMiddleWare(); //setup the Controllers - i.e. the route endpoints (found in BlockControllers.js). this.initControllers(); // start the REST API by calling the express app.listen() method on port 8000. this.start(); } /** * Initilization of the Express framework */ initExpress() { // set the server port using the express .set() method this.app.set("port", process.env.PORT || 8000); } /** * Initialization of the middleware modules */ initExpressMiddleWare() { // these middleware allow us to "automatically" parser request bodies // and have easy access to these from the req.body property. // urlencoded see -> ( https://www.npmjs.com/package/body-parser#bodyparserurlencodedoptions ) // json see -> ( https://www.npmjs.com/package/body-parser#bodyparserjsonoptions ) this.app.use(bodyParser.urlencoded({extended:true})); this.app.use(bodyParser.json()); } /** * Initilization of all the controllers */ initControllers() { // require the Controller function that accepts the express app as a parameter. // this will give us access to the route endpoints. /** We will have to configure the BlockController.js file to be able to interact with our instance of levelDB. In a previous tutorial we created a file called LevelSandbox.js and we used this file to configure and connect to a levelDB database: const level = require('level'); <- requiring the level module (npm install level --save) const chainDB = './chaindata'; <- the path and name of our levelDB In this tutorial / review I will be using the same method by copying over the LevelSandbox.js file into this projects code base - I will then use the predefined methods to interact to the database via the RESTful API (app.js, BlockController.js) */ require("./BlockController.js")(this.app); } /** * Starting the REST Api application */ start() { // self = this to access the instance of BlockAPI inside the .listen callback let self = this; // set the port using express method .get() // we set the port in the initExpress method above with this.app.set("port", 8000) this.app.listen(this.app.get("port"), () => { console.log(`Server Listening for port: ${self.app.get("port")}`); }); } } // init a new instance of the RESTFul API - so we can access the api. new BlockAPI();
5f9553ee4abb39c7bb17106e544fd86da029cb36
[ "Markdown", "JavaScript" ]
2
Markdown
block8-tech/udacity_blockchain_project3
ac8726edd6c2b8b68e74ec1bdd41faef81b40e98
df84d16ad86b0924a14b5ca11ff11cdbc5823de4
refs/heads/master
<repo_name>Columbus19/team-8<file_sep>/main.py from flask import Flask, render_template from model import User, db, app import pdb from flask import request @app.route("/") def login(): return render_template("login.html") @app.route("/charts") def home(): joe = User(fullname='<NAME>', email='<EMAIL>', ssn='123-45-6789',phone_number='8106236861', monthly_income='1,000,000', value_of_assets='1,000,000', total_debt=20,debt_dist1=10,debt_dist2=20,debt_dist3=70) average = User(fullname='AVERAGE', email='<EMAIL>', ssn='987-54-321',phone_number='12345678', monthly_income='2,000,000', value_of_assets='2,000,000',total_debt=300000,debt_dist1=50,debt_dist2=30,debt_dist3=20) joe_data = User.query.filter_by(fullname='<NAME>').first() avg_data = User.query.filter_by(fullname='AVERAGE').first() if not joe_data: db.session.add(joe) if not avg_data: db.session.add(average) joe_data = User.query.filter_by(fullname='<NAME>').first() avg_data = User.query.filter_by(fullname='AVERAGE').first() db.session.commit() bar = joe_data.total_debt val1 = joe_data.debt_dist1 val2 = joe_data.debt_dist2 val3 = joe_data.debt_dist3 avg1 = avg_data.debt_dist1 avg2 = avg_data.debt_dist2 avg3 = avg_data.debt_dist3 return render_template("chart.html", joe_data=joe_data, val1=val1, val2=val2, val3=val3, bar=bar, avg1=avg1, avg2=avg2, avg3=avg3) @app.route("/profile") def profile(): return render_template("profile.html") @app.route("/tools") def tools(): return render_template("tools.html") @app.route('/charts', methods=['GET', 'POST']) def template(): if request.method == 'POST': joe = User(fullname='<NAME>', email='<EMAIL>', ssn='123-45-6789',phone_number='8106236861', monthly_income='1,000,000', value_of_assets='1,000,000', total_debt=20,debt_dist1=10,debt_dist2=20,debt_dist3=70) average = User(fullname='AVERAGE', email='<EMAIL>', ssn='987-54-321',phone_number='12345678', monthly_income='2,000,000', value_of_assets='2,000,000',total_debt=300000,debt_dist1=50,debt_dist2=30,debt_dist3=20) joe_data = User.query.filter_by(fullname='<NAME>').first() avg_data = User.query.filter_by(fullname='AVERAGE').first() if not joe_data: db.session.add(joe) if not avg_data: db.session.add(average) joe_data = User.query.filter_by(fullname='<NAME>').first() avg_data = User.query.filter_by(fullname='AVERAGE').first() db.session.commit() bar = joe_data.total_debt val1 = joe_data.debt_dist1 val2 = joe_data.debt_dist2 val3 = joe_data.debt_dist3 avg1 = avg_data.debt_dist1 avg2 = avg_data.debt_dist2 avg3 = avg_data.debt_dist3 return render_template("chart.html", joe_data=joe_data, val1=val1, val2=val2, val3=val3, bar=bar, avg1=avg1, avg2=avg2, avg3=avg3) if __name__ == "__main__": app.run(debug=True) <file_sep>/model.py from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) fullname = db.Column(db.String(120), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) ssn = db.Column(db.String(120), unique=True, nullable=False) phone_number = db.Column(db.String(120), unique=True, nullable=False) monthly_income = db.Column(db.String(120), unique=True, nullable=False) value_of_assets = db.Column(db.String(120), unique=True, nullable=False) total_debt = db.Column(db.Integer, unique=True, nullable=False) debt_dist1 = db.Column(db.Integer, unique=True, nullable=False) debt_dist2 = db.Column(db.Integer, unique=True, nullable=False) debt_dist3 = db.Column(db.Integer, unique=True, nullable=False) def __repr__(self): return '%r' % self.fullname db.create_all() db.session.commit()<file_sep>/README.md # team-8 https://docs.google.com/document/d/1r6F3TgEVS4D3wOD42w7Cx33OrBEVwDlP509qihu7sa0/edit?usp=sharing https://docs.google.com/presentation/d/110Z8WfqufklKsdPe6W4vNmZQJQZf6dHH-yTIS54jGi4/edit?usp=sharing
a315f6175db90c3c4e79b884dccf7686849d1211
[ "Markdown", "Python" ]
3
Python
Columbus19/team-8
c1bf76b738e15d777db792ba343a6e5fc73cd85d
7943e071ca1d3cbc41baa2b880ff2c431a3e4f0a
refs/heads/master
<file_sep>using System; using System.Threading; using Prometheus.Client; using Prometheus.Client.Collectors; using Prometheus.Client.MetricPusher; namespace CoreConsoleMetricPusher { internal class Program { internal static void Main(string[] args) { var defaultPusher = new MetricPusher("http://localhost:9091", "pushgateway-testworker", "default"); var registry = new CollectorRegistry(); var customPusher = new MetricPusher(registry, "http://localhost:9091", "pushgateway-testworker", "custom", null, null); var counter = Metrics.CreateCounter("example_counter1", "help"); var counterInCustom = Metrics.WithCustomRegistry(registry).CreateCounter("example_counter2", "help1"); IMetricPushServer server = new MetricPushServer(new IMetricPusher[] { defaultPusher, customPusher }); server.Start(); for (int i = 0; i < 10; i++) { counter.Inc(); counterInCustom.Inc(2); Console.WriteLine("count: " + i); Thread.Sleep(2000); } server.Stop(); } } } <file_sep>using System.Web.Http; using Microsoft.Owin; using Owin; using Prometheus.Client.Owin; using WebOwin; [assembly: OwinStartup(typeof(Startup))] namespace WebOwin { public class Startup { public void Configuration(IAppBuilder app) { var config = new HttpConfiguration(); config.MapHttpAttributeRoutes(); app.UsePrometheusServer(q => { q.MapPath = "/test-metrics"; }); app.UseWebApi(config); } } } <file_sep>namespace WebOwin { public class WebOwin : System.Web.HttpApplication { protected void Application_Start() { } } } <file_sep>using Microsoft.AspNetCore.Mvc; using Prometheus.Client; using Prometheus.Client.Collectors; namespace CoreWebWithoutExtensions.Controllers { [Route("[controller]")] public class MetricsController : Controller { [HttpGet] public void Get() { Response.StatusCode = 200; using (var outputStream = Response.Body) { ScrapeHandler.Process(CollectorRegistry.Instance, outputStream); } } } }<file_sep>using Microsoft.AspNetCore.Mvc; using Prometheus.Client; namespace CoreWebWithoutExtensions.Controllers { [Route("[controller]")] public class HistogramController : Controller { private readonly Histogram _histogram = Metrics.CreateHistogram("test_hist", "help_text", "params1"); [HttpGet] public IActionResult Get() { _histogram.Labels("test1").Observe(1); _histogram.Labels("test2").Observe(2); return Ok(); } } } <file_sep>using System.Web.Http; using Prometheus.Client; namespace WebOwin.Controllers { [Route("api/counter")] public class CounterController : ApiController { readonly Counter _counter = Metrics.CreateCounter("myCounter", "some help about this"); [HttpGet] public IHttpActionResult Get() { _counter.Inc(); return Ok(); } } } <file_sep>using System; using Prometheus.Client; using Prometheus.Client.MetricServer; namespace CoreConsoleMetricServer { class Program { static void Main(string[] args) { IMetricServer metricServer = new MetricServer("localhost", 9091); metricServer.Start(); var counter = Metrics.CreateCounter("test_count", "helptext"); counter.Inc(); Console.WriteLine("Press any key.."); Console.ReadKey(); metricServer.Stop(); } } }<file_sep>using Microsoft.AspNetCore.Mvc; using Prometheus.Client; namespace CoreWebWithoutExtensions.Controllers { [Route("[controller]")] public class CounterController : Controller { private readonly Counter _counter = Metrics.CreateCounter("my_counter", "some help about this"); private readonly Counter _counterTs = Metrics.CreateCounter("my_counter_ts", "some help about this", true); [HttpGet] public IActionResult Get() { _counter.Inc(); _counterTs.Inc(3); return Ok(); } } } <file_sep># Prometheus.Client.Examples Code Examples for [Prometheus.Client.*](https://github.com/PrometheusClientNet) ## Support If you are having problems, send a mail to [<EMAIL>](mailto://<EMAIL>). I will try to help you. I would also very much appreciate your support by buying me a coffee. <a href="https://www.buymeacoffee.com/phnx47" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/yellow_img.png" alt="Buy Me A Coffee" style="height: auto !important;width: auto !important;" ></a> <file_sep>using Microsoft.AspNetCore.Mvc; using Prometheus.Client; namespace WebAspNetCore.Controllers { [Route("[controller]")] public class HistogramController : Controller { // Write HELP and Type only /* * # HELP test_hist help_text * # TYPE test_hist histogram */ private readonly Histogram _histogram = Metrics.CreateHistogram("test_hist", "help_text", "params1"); [HttpGet("1")] public IActionResult Get1() { return Ok(); } [HttpGet("2")] public IActionResult Get2() { _histogram.Observe(1); // No Crash _histogram.Labels("test1").Observe(1); _histogram.Labels("test2").Observe(2); return Ok(); } } }
88c923d907fbbfac8d4068a8f8d05e3540d3090e
[ "Markdown", "C#" ]
10
C#
randomchance/Prometheus.Client.Examples
206e912104747e676b4d4036591292aaf22200a7
13a5ce846410fae2065a4e8a2593b725a3c827f1
refs/heads/master
<repo_name>maximdanilchenko/atol-api<file_sep>/Helpers.py # -*- coding: utf-8 -*- # Вспомогательные скрипты для функций REST-API import re from flask import request import datetime red_border, yellow_border, day_border = 3600 * 36, 3600 * 24, 60 # константы default_color = 'dark-grey' def validate_get(names, types, defaults): if not len(names) == len(types) == len(defaults): raise AppException("different length of tuples") try: return ( types[i](request.args.get(names[i])) if request.args.get(names[i]) else defaults[i] for i in range(len(names))) except: return False def validate_post(names, types, defaults): if not len(names) == len(types) == len(defaults): raise AppException("different length of tuples") try: return ( types[i](request.form[names[i]]) if names[i] in request.form else defaults[i] for i in range(len(names))) except: return False class AppException(Exception): pass def to_int(text): """ Проверяет число в текстовом формате и возвращает корректное значение типа int @param text: число в текстовом формате @return: корректное значение типа int """ if not text: return None if isinstance(text, basestring): return None if re.findall('[^0-9\.]', text) else int( re.search('[0-9]+', text).group()) elif isinstance(text, (int, long, float)): return int(text) else: return text def user_info(req=request): return req.user_agent.browser + req.user_agent.platform + req.remote_addr def make_code_for_id(hub_id): return "code" def get_tree(node, user_type): if user_type not in ('partner', 'client'): return None groups_list = [get_tree(child, user_type) for child in node.childes] hubs_list = [{"id": hub.id, "type": "hub", "name": hub.name, "order_id": hub.order_id} for hub in node.hubs] return {"id": node.id, "type": "group", "name": node.name, "order_id": node.order_id, "hub_num": len(hubs_list), "group_num": len(groups_list), "children": groups_list + hubs_list} def statistics(meta, stats): info = {} limit = datetime.date.today() + datetime.timedelta(days=60) info['utm_version'] = [meta.utm_version, default_color] if meta.utm_version is not None else ['-', default_color] if meta.certificate_rsa_date is not None: d = (meta.certificate_rsa_date - datetime.date.today()).days rsa_color = 'red' if meta.certificate_rsa_date < limit else 'green' info['certificate_rsa_date'] = [d, rsa_color] else: info['certificate_rsa_date'] = ['-', default_color] if meta.certificate_gost_date is not None: d = (meta.certificate_gost_date - datetime.date.today()).days gost_color = 'red' if meta.certificate_gost_date < limit else 'green' info['certificate_gost_date'] = [d, gost_color] else: info['certificate_gost_date'] = ['-', default_color] if stats.utm_status is not None: t = u'Включен' if stats.utm_status else u'Выключен' z = 1 if stats.utm_status else 0 utm_color = 'green' if stats.utm_status else default_color info['utm_status'] = [t, utm_color, z] else: info['utm_status'] = ['-', default_color, None] info['unset_tickets_count'] = [stats.unset_tickets_count, default_color] if stats.unset_tickets_count is not None else ['-', default_color] info['total_tickets_count'] = [stats.total_tickets_count, default_color] if stats.total_tickets_count is not None else ['-', default_color] info['retail_buffer_size'] = [stats.retail_buffer_size, default_color] if stats.retail_buffer_size is not None else ['-', default_color] if stats.buffer_age is not None: buffer_color = 'green' if stats.buffer_age < yellow_border else \ 'yellow' if stats.buffer_age < red_border else 'red' t = stats.buffer_age info['buffer_age'] = [u"%s д, %s ч, %s м" % ( t // 86400, t % 86400 // 3600, t % 3600 // 60), buffer_color] else: info['buffer_age'] = ['-', default_color] info['time'] = stats.create_time.strftime("%Y-%m-%d %H:%M:%S+00:00") print info return info def chart_statistics(stats): total_tickets_count_chart = {'times': [], 'values': []} unset_tickets_checks_count_chart = {'times': [], 'tickets': [], 'checks': []} utm_status_chart = {'times': [], 'values': []} for n in range(len(stats)): total_tickets_count_chart['values'].append(stats[n].total_tickets_count) total_tickets_count_chart['times'].append(stats[n].create_time.strftime("%Y-%m-%d %H:%M:%S+00:00")) unset_tickets_checks_count_chart['checks'].append(stats[n].retail_buffer_size) unset_tickets_checks_count_chart['tickets'].append(stats[n].unset_tickets_count) unset_tickets_checks_count_chart['times'].append(stats[n].create_time.strftime("%Y-%m-%d %H:%M:%S+00:00")) utm_status_chart['values'].append(stats[n].utm_status) utm_status_chart['times'].append(stats[n].create_time.strftime("%Y-%m-%d %H:%M:%S+00:00")) # for n, stat in enumerate(stats[1:-1]): # if not (stats[n - 1].total_tickets_count == stats[n].total_tickets_count == stats[n + 1].total_tickets_count): # total_tickets_count_chart['values'].append(stats[n].total_tickets_count) # total_tickets_count_chart['times'].append(stats[n].create_time.strftime("%Y-%m-%d %H:%M:%S+00:00")) # if not (stats[n - 1].unset_tickets_count == stats[n].unset_tickets_count == stats[n + 1].unset_tickets_count) or \ # not (stats[n - 1].retail_buffer_size == stats[n].retail_buffer_size == stats[n + 1].retail_buffer_size): # unset_tickets_checks_count_chart['checks'].append(stats[n].retail_buffer_size) # unset_tickets_checks_count_chart['tickets'].append(stats[n].unset_tickets_count) # unset_tickets_checks_count_chart['times'].append(stats[n].create_time.strftime("%Y-%m-%d %H:%M:%S+00:00")) # if not (stats[n - 1].utm_status == stats[n].utm_status == stats[n + 1].utm_status): # utm_status_chart['values'].append(stats[n].utm_status) # utm_status_chart['times'].append(stats[n].create_time.strftime("%Y-%m-%d %H:%M:%S+00:00")) # # total_tickets_count_chart['values'].append(stats[-1].total_tickets_count) # total_tickets_count_chart['times'].append(stats[-1].create_time.strftime("%Y-%m-%d %H:%M:%S+00:00")) # unset_tickets_checks_count_chart['checks'].append(stats[-1].retail_buffer_size) # unset_tickets_checks_count_chart['tickets'].append(stats[-1].unset_tickets_count) # unset_tickets_checks_count_chart['times'].append(stats[-1].create_time.strftime("%Y-%m-%d %H:%M:%S+00:00")) # utm_status_chart['values'].append(stats[-1].utm_status) # utm_status_chart['times'].append(stats[-1].create_time.strftime("%Y-%m-%d %H:%M:%S+00:00")) return { "total_tickets_count": total_tickets_count_chart, "unset_tickets_checks_count": unset_tickets_checks_count_chart, "utm_status": utm_status_chart, } # --проверка на пренадлежность группы пользователю def valid_group_user(group, user): if user.user_type == 'client': gr = group user_gr = gr.client while not user_gr: gr = gr.parent user_gr = gr.client if user_gr.user != user: return False elif user.user_type == 'partner': gr = group user_gr = gr.partner while not user_gr: gr = gr.parent user_gr = gr.partner if user_gr.user != user: return False return True def parseList(name): result = {} p = re.compile('%s\[(?P<i>\d+)\]\[(?P<type>\w+)\]' % name) for key in request.form.iterkeys(): m = re.match(p, key) if m: d = m.groupdict() if not result.has_key(d['i']): result[d['i']] = {} result[d['i']][d['type']] = request.form[key] return result def get_settings(settings): st = settings return { "supervisor": { "max_timer_transport_restart": st.supervisor.max_timer_transport_restart, "restart_if_no_cert": st.supervisor.restart_if_no_cert, "logging": st.supervisor.logging, "max_force_restart_count": st.supervisor.max_force_restart_count, "max_timer_transport_reboot": st.supervisor.max_timer_transport_reboot, "restart_allow_reboot": st.supervisor.restart_allow_reboot, "scan_period": st.supervisor.scan_period, "max_timer_transport_force_restart": st.supervisor.max_timer_transport_force_restart, "supervisor_enabled": st.supervisor.supervisor_enabled }, "scanner": { "sens": st.scanner.sens, "port": st.scanner.port, "suffix": st.scanner.suffix }, "proxy": { "proxy_port": st.proxy.proxy_port, "proxy_type": st.proxy.proxy_type }, "mail": { "mail": st.mail.mail }, "vpn": { "tls": st.vpn.tls, "zip": st.vpn.zip, "vpn_type": st.vpn.vpn_type, "proto": st.vpn.proto, "cipher": st.vpn.cipher, "hosts": st.vpn.hosts, "interface": st.vpn.interface }, "transport": { "access_control_allow_origin": st.transport.access_control_allow_origin, "key_pincode": st.transport.key_pincode, "user_pincode": st.transport.user_pincode, "rolling_log": st.transport.rolling_log }, "hostapd": { "ap_name": st.hostapd.ap_name, "ap_channel": st.hostapd.ap_channel, "ap_pass": st.hostapd.ap_pass }, "wifi": { "network": st.wifi.network, "ap_pass": st.wifi.ap_pass, "ip": st.wifi.ip, "mask": st.wifi.mask, "ap_channel": st.wifi.ap_channel, "ap_list": st.wifi.ap_list, "broadcast": st.wifi.broadcast, "ap_name": st.wifi.ap_name, "mode": st.wifi.mode, "dns": st.wifi.dns, "address_type": st.wifi.address_type, "gateway": st.wifi.gateway }, "internet": { "gateway": st.internet.gateway }, "ethernet": { "network": st.ethernet.network, "ip": st.ethernet.ip, "mask": st.ethernet.mask, "broadcast": st.ethernet.broadcast, "dns": st.ethernet.dns, "address_type": st.ethernet.address_type, "gateway": st.ethernet.gateway }, "modem": { "modem_phone": st.modem.modem_phone, "modem_password": <PASSWORD>, "modem_user": st.modem.modem_user, "modem_apn": st.modem.modem_apn }, "ttn": { "logging": st.ttn.logging, "auth": st.ttn.auth } } def set_settings(settings, json): st = settings st.supervisor.max_timer_transport_restart, = json["supervisor"]["max_timer_transport_restart"] st.supervisor.restart_if_no_cert, = json["supervisor"]["restart_if_no_cert"] st.supervisor.logging, = json["supervisor"]["logging"] st.supervisor.max_force_restart_count, = json["supervisor"]["max_force_restart_count"] st.supervisor.max_timer_transport_reboot, = json["supervisor"]["max_timer_transport_reboot"] st.supervisor.restart_allow_reboot, = json["supervisor"]["restart_allow_reboot"] st.supervisor.scan_period, = json["supervisor"]["scan_period"] st.supervisor.max_timer_transport_force_restart, = json["supervisor"]["max_timer_transport_force_restart"] st.supervisor.supervisor_enabled = json["supervisor"]["supervisor_enabled"] st.scanner.sens, = json["scanner"]["sens"] st.scanner.port, = json["scanner"]["port"] st.scanner.suffix = json["scanner"]["suffix"] st.proxy.proxy_port, = json["proxy"]["proxy_port"] st.proxy.proxy_type = json["proxy"]["proxy_type"] st.mail.mail = json["mail"]["mail"] st.vpn.tls, = json["vpn"]["tls"] st.vpn.zip, = json["vpn"]["zip"] st.vpn.vpn_type, = json["vpn"]["vpn_type"] st.vpn.proto, = json["vpn"]["proto"] st.vpn.cipher, = json["vpn"]["cipher"] st.vpn.hosts, = json["vpn"]["hosts"] st.vpn.interface = json["vpn"]["interface"] st.transport.access_control_allow_origin, = json["transport"]["access_control_allow_origin"] st.transport.key_pincode, = json["transport"]["key_pincode"] st.transport.user_pincode, = json["transport"]["user_pincode"] st.transport.rolling_log = json["transport"]["rolling_log"] st.hostapd.ap_name, = json["hostapd"]["ap_name"] st.hostapd.ap_channel, = json["hostapd"]["ap_channel"] st.hostapd.ap_pass = json["hostapd"]["ap_pass"] st.wifi.network, = json["wifi"]["network"] st.wifi.ap_pass, = json["wifi"]["ap_pass"] st.wifi.ip, = json["wifi"]["ip"] st.wifi.mask, = json["wifi"]["mask"] st.wifi.ap_channel, = json["wifi"]["ap_channel"] st.wifi.ap_list, = json["wifi"]["ap_list"] st.wifi.broadcast, = json["wifi"]["broadcast"] st.wifi.ap_name, = json["wifi"]["ap_name"] st.wifi.mode, = json["wifi"]["mode"] st.wifi.dns, = json["wifi"]["dns"] st.wifi.address_type, = json["wifi"]["address_type"] st.wifi.gateway = json["wifi"]["gateway"] st.internet.gateway = json["internet"]["gateway"] st.ethernet.network, = json["ethernet"]["network"] st.ethernet.ip, = json["ethernet"]["ip"] st.ethernet.mask, = json["ethernet"]["mask"] st.ethernet.broadcast, = json["ethernet"]["broadcast"] st.ethernet.dns, = json["ethernet"]["dns"] st.ethernet.address_type, = json["ethernet"]["address_type"] st.ethernet.gateway = json["ethernet"]["gateway"] st.modem.modem_phone, = json["modem"]["modem_phone"] st.modem.modem_password, = json["modem"]["modem_password"] st.modem.modem_user, = json["modem"]["modem_user"] st.modem.modem_apn = json["modem"]["modem_apn"] st.ttn.logging, = json["ttn"]["logging"] st.ttn.auth = json["ttn"]["auth"] <file_sep>/main.py # -*- coding: utf-8 -*- # API сервер, сайт личного кабинета, старт flask-приложения import uuid import os import sys import datetime import time from flask import send_file, url_for, jsonify, abort, \ make_response, redirect, request, current_app from jinja2 import Environment, FileSystemLoader from functools import wraps from Helpers import * import Token from Models import User, Partner, Client, Hub, \ Client_group, Partner_group, Hub_meta, Hub_statistics, Hub_settings, \ Hub_partner, Hub_client from App import app, db from sqlalchemy import desc, asc from sqlalchemy.sql.expression import func on_gae = True try: from google.appengine.api import mail except ImportError: on_gae = False # from flask_mail import Mail # mail = Mail(app) # рабочая директория work_dir = os.path.dirname(sys.executable) if getattr(sys, 'frozen', False) \ else os.path.dirname(os.path.realpath(__file__)) work_dir = "%s/%s" % (work_dir.replace("\\", "/"), 'html') # Коды команд для выполнения на хабе DO_NOTHING, RESET_SETTINGS, GET_SETTINGS, EXEC_CODE, RESET_PARAMS = range(5) CLIENT, PARTNER = 'client', 'partner' # html тело писем для отправки MAIL_HTML_REG = """<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css"> <link rel="stylesheet" href="http://www.w3schools.com/lib/w3-theme-red.css"> <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"> </head> <body> <header> </header> <div class="w3-row-padding w3-center w3-margin-top"> <div> <img src="https://atol-test.appspot.com/static/img/logo.png" alt="АТОЛ" width="130" height="35"> <h1>Поздравляем!</h1> <p>Регистрация в личном кабинете ATOL почти завершена</p> <a href={}>Пройдите по этой ссылке для завершения регистрации</a> </div> </div> </body> </html>""" MAIL_HTML_REC = """<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css"> <link rel="stylesheet" href="http://www.w3schools.com/lib/w3-theme-red.css"> <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"> </head> <body> <header> </header> <div class="w3-row-padding w3-center w3-margin-top"> <div> <img src="https://atol-test.appspot.com/static/img/logo.png" alt="АТОЛ" width="130" height="35"> <h1>Изменение пароля</h1> <p>Изменение пароля личного кабинета ATOL почти завершено</p> <a href={}>Пройдите по этой ссылке для изменения пароля</a> </div> </div> </body> </html>""" """ -----Настройка приложения----- Объекты: db, cache """ # раскомментить, чтобы удалить все таблицы из БД при старте приложения # db.drop_all() db.create_all() # задаем кэширование в зависимости от платформы запуска from werkzeug.contrib.cache import GAEMemcachedCache, SimpleCache if 'win' in sys.platform: cache = SimpleCache() else: cache = GAEMemcachedCache() """ -----API сервера----- """ # обработчики ошибок @app.errorhandler(400) def bad_request(error): return make_response(jsonify({'success': False, 'error': 'Bad request'}), 400) @app.errorhandler(401) def not_auth(error): return make_response(jsonify({'success': False, 'error': 'Unauthorized'}), 401) @app.errorhandler(404) def not_found(error): return make_response(jsonify({'success': False, 'error': 'Not found'}), 404) def is_auth(fn): """Декоратор для проверки аутентификации методов API""" @wraps(fn) def wrapped(*args, **kwargs): access_token = 0 if request.method == "POST": access_token, = validate_post(('access_token',), (str,), (0,)) elif request.method == "GET": access_token, = validate_get(('access_token',), (str,), (0,)) if not access_token: abort(401) addr = cache.get(access_token) if addr and addr == user_info(request): cache.set(access_token, user_info(request), app.config['MAX_CACHE_TIME']) return fn(*args, **kwargs) else: abort(401) return wrapped def jsonp(func): """Декоратор. Преобразует JSON в JSONP (если передан параметр callback)""" @wraps(func) def decorated_function(*args, **kwargs): callback = request.args.get('callback', False) if callback: data = str(func(*args, **kwargs).data) content = str(callback) + '(' + data + ')' mimetype = 'application/javascript' return current_app.response_class(content, mimetype=mimetype) else: return func(*args, **kwargs) return decorated_function def validate_user(access_token): if not access_token: abort(401) user_id = Token.confirm_token(access_token, app.config['SECRET_KEY'], None) user = User.query.get_or_404(user_id) if not user.user_type: abort(400) return user @app.route("/hub/new_device_id", methods=['GET']) def new_device_id(): serial_id, = validate_get(('serial_id',), (unicode,), (0,)) if not serial_id: abort(400) hub = Hub.query.filter_by(serial_id=serial_id).first() if not hub: if len(serial_id) == 32: hub = Hub(serial_id) db.session.add(hub) else: abort(400) new_device_id = str(uuid.uuid4())[-12:] hub.device_id = new_device_id db.session.commit() return jsonify({'success': True, 'device_id': hub.device_id}) @app.route("/hub/device_id", methods=['GET']) def get_device_id(): serial_id, = validate_get(('serial_id',), (unicode,), (0,)) if not serial_id: abort(400) hub = Hub.query.filter_by(serial_id=serial_id).first() if not hub or not hub.device_id: return jsonify({'success': False, 'device_id': None}) return jsonify({'success': True, 'device_id': hub.device_id}) @app.route("/hub/connect", methods=['POST']) def try_update_post(): """ Метод для подключения к хабу. Если идентификатор соответсвтует хабу, который нужно обновить, то на хаб отправляется скрипт для запуска :return: """ print request.form.items() serial_id, = validate_post(('serial_id',), (unicode,), (0,)) if not serial_id: abort(400) hub = Hub.query.filter_by(serial_id=serial_id).first() if not hub: if len(serial_id) == 32: hub = Hub(serial_id) db.session.add(hub) else: abort(400) utmOn, unsentTicketsCount, totalTicketsCount, retailBufferSize, \ bufferAge, version, certificateRSA, certificateGOST, utime \ = validate_post(("utmOn", "unsentTicketsCount", "totalTicketsCount", "retailBufferSize", "bufferAge", "version", "certificateRSABestBefore", "certificateGOSTBestBefore", "utc_time"), (str,) + (int,)*4 + (str,) + (int,)*2 + (str,), (None,) * 9) if utmOn.lower().startswith('t'): utmOn = True else: utmOn = False hub_st = Hub_statistics.query.filter_by(create_time=utime).first() if hub_st: hub_st.utm_status = utmOn hub_st.unset_tickets_count = unsentTicketsCount hub_st.total_tickets_count = totalTicketsCount hub_st.retail_buffer_size = retailBufferSize hub_st.buffer_age = bufferAge else: hub.stats.append(Hub_statistics(utmOn, unsentTicketsCount, totalTicketsCount, retailBufferSize, bufferAge, utime)) if certificateRSA: hub.meta.certificate_rsa_date = datetime.date.today() + datetime.timedelta(days=certificateRSA) if certificateGOST: hub.meta.certificate_gost_date = datetime.date.today()+ datetime.timedelta(days=certificateGOST) if version: hub.meta.utm_version = version # if (utmOn or unsentTicketsCount or totalTicketsCount # or retailBufferSize or bufferAge): # new_stat = Hub_statistics(utmOn, unsentTicketsCount, totalTicketsCount, # retailBufferSize, bufferAge) # hub.stats.append(new_stat) # if certificateRSA: # hub.hub_meta.certificate_rsa_date = date.fromtimestamp(time.time() # + certificateRSA) # if certificateGOST: # hub.hub_meta.certificate_gost_date = date.fromtimestamp(time.time() # + certificateGOST) db.session.commit() command = DO_NOTHING if not hub.sended_settings: command = GET_SETTINGS if not hub.uploaded_settings: command = RESET_SETTINGS return jsonify({'success': True, 'command_code': command}) @app.route("/tasks/cleanbd", methods=['GET']) def cleanbd(): for hub in Hub.query.yield_per(100): last_time = datetime.datetime.utcnow() for stata in Hub_statistics.query.filter_by(hub_id=hub.id).order_by(desc(Hub_statistics.create_time)).yield_per(100): if last_time - stata.create_time < datetime.timedelta(hours=1): db.session.delete(stata) else: last_time = stata.create_time db.session.commit() return jsonify({'success': True}) # @app.route("/test/cleaning", methods=['GET']) # def cleaning(): # for hub in Hub.query.yield_per(100): # max_utc = db.session.query(func.max(Hub_statistics.unset_tickets_count)).filter_by(hub_id=hub.id).first()[0] # max_utc = float(max_utc) if max_utc else None # max_ttc = db.session.query(func.max(Hub_statistics.total_tickets_count)).filter_by(hub_id=hub.id).first()[0] # max_ttc = float(max_ttc) if max_ttc else None # max_rbs = db.session.query(func.max(Hub_statistics.retail_buffer_size)).filter_by(hub_id=hub.id).first()[0] # max_rbs = float(max_rbs) if max_rbs else None # for stata in Hub_statistics.query.filter_by(hub_id=hub.id).order_by(desc(Hub_statistics.create_time)).yield_per(100): # if max_utc and stata.unset_tickets_count > 150: # stata.unset_tickets_count = int(stata.unset_tickets_count / max_utc * 100) # if max_ttc and stata.total_tickets_count > 150: # stata.total_tickets_count = int(stata.total_tickets_count / max_ttc * 100) # if max_rbs and stata.retail_buffer_size > 150: # stata.retail_buffer_size = int(stata.retail_buffer_size / max_rbs * 100) # db.session.commit() # return jsonify({'success': True}) @app.route("/api/recovery", methods=['POST']) @jsonp def api_recovery(): """ Вызывается для того, чтобы на почту отправить ссылку на страницу для замены пароля. В базе сохраняется токен для валидации пользователся по ссылке , который в дальнейшем удаляется после смены пароля пользователем. :return: """ email, = validate_post(('email',),(str,), ('',)) if not email: abort(400) token = Token.generate_token(email, app.config['SECRET_KEY']) try: user = User.query.filter_by(email=email).first_or_404() user.recovery_token = token db.session.commit() except: abort(401) a = url_for('recovery', token=token, _external=True) print a mail_subject = 'Замена пароля' mail_body = """Пройдите по ссылке для замены пароля: %s""" % a mail_html_body = MAIL_HTML_REC.format(a) mail_to = email mail_from = '<EMAIL>' if on_gae: mail.send_mail(sender=mail_from, to=mail_to, subject=mail_subject, body=mail_body, html=mail_html_body) return jsonify({'success': True}) @app.route("/api/signup", methods=['POST']) @jsonp def api_signup(): """ Регистрация пользователя. Требуются почта и два поля пароля. Пользователь сохраняется в базе и на его почту высылается ссылка для подтверждения адреса почты. Если пользователь не подтвердил почту, то он может ещй раз зарегестрироваться. :return: """ email, password, conf_password, user_type = validate_post( ('email', 'password', 'conf_password', 'type'), (str,) * 4, ('',) * 4) if not (email and user_type and password and conf_password == password): abort(400) token = Token.generate_token(email, app.config['SECRET_KEY']) user = User.query.filter_by(email=email, confirmed=False, user_type=user_type).first() if not user: user = User('', email, Token.generate_token(password, app.config['SECRET_KEY']), user_type) if user_type == CLIENT: client = Client(user) db.session.add(client) elif user_type == PARTNER: partner = Partner(user) db.session.add(partner) else: abort(400) db.session.add(user) db.session.commit() try: db.session.commit() except: abort(400) # if app.config['DEBUG'] and user.email == '<EMAIL>': # testdata() a = url_for('api_confirm', token=token, _external=True) print a mail_subject = 'Регистрация' mail_body = """Поздравляем! Пройдите по ссылке для завершения регистрации: %s""" % a mail_html_body = MAIL_HTML_REG.format(a) mail_to = email mail_from = '<EMAIL>' if on_gae: mail.send_mail(sender=mail_from, to=mail_to, subject=mail_subject, body=mail_body, html=mail_html_body) return jsonify({'success': True}) @app.route("/api/signin", methods=['POST']) @jsonp def api_signin(): """ Вход. ищется пользователь с данной почтой и проверяется его пароль. Если все хорошо, то возвращается access_token, который генерируется на основе id пользователя, а в кэше запоминается информация об устройстве/браузере/ip пользователя. :return: """ email, password = validate_post(('email', 'password',), (str,) * 2, ('',) * 2) if not (email and password): abort(400) user = User.query.filter_by(email=email).first_or_404() if Token.confirm_token(user.password, app.config['SECRET_KEY'], None) != password or not user.confirmed: abort(401) token = Token.generate_token(user.id, app.config['SECRET_KEY']) # Получить обратно: user_id = Token.confirm_token(access_token, app.config['SECRET_KEY'], None) cache.set(token, user_info(request), app.config['MAX_CACHE_TIME']) user.recovery_token = '' db.session.commit() return jsonify({'success': True, 'access_token': token}) @app.route("/api/newpas", methods=['POST']) @jsonp def api_newpas(): """ Меняет пароль пользователя, а потом регистрирует его и возвращает access_token :return: """ token, password, conf_password = validate_post(('token', 'password', 'conf_password',), (str,) * 3, ('',) * 3) if not (token and password and conf_password == password): abort(400) # email = Token.confirm_token(token, app.config['SECRET_KEY'], None) user = User.query.filter_by(recovery_token=token).first_or_404() user.password = Token.generate_token(password, app.config['SECRET_KEY']) user.recovery_token = '' user.confirmed = True db.session.commit() # Получить обратно: user_id = Token.confirm_token(access_token, app.config['SECRET_KEY'], None) in_token = Token.generate_token(user.id, app.config['SECRET_KEY']) cache.set(in_token, user_info(request), app.config['MAX_CACHE_TIME']) return jsonify({'success': True, 'access_token': token}) @app.route("/confirm/<string:token>", methods=['GET']) def api_confirm(token): """ поддверждения адреса почты, происходит пометка в БД, что пользователь подтвержден, после чего он может войти Происходит редирект на страницу успеха :param token: :return: """ if token: email = Token.confirm_token(token, app.config['SECRET_KEY'], app.config['CONFIRM_TIME']) # проверить пользователя по почте в базе и пометить, что он подтвердил email if not email: abort(400) user = User.query.filter_by(email=email).first_or_404() user.confirmed = True db.session.commit() return redirect(url_for('success')) @app.route("/recovery/<string:token>", methods=['GET']) def recovery(token): """ """ if token: user = User.query.filter_by(recovery_token=token).first_or_404() return redirect(url_for('newpassword', email=user.email, token=token)) @app.route("/api/get_user_info", methods=['GET']) @is_auth @jsonp def get_info(): access_token, = validate_get(('access_token',), (str,), (0,)) if not access_token: abort(400) user = validate_user(access_token) name = user.name or user.email if len(name) > 30: name = '%s..' % name[:28] return jsonify({'success': True, 'name': name, 'type': user.user_type}) @app.route("/api/get_tree", methods=['GET']) @is_auth @jsonp def api_get_tree(): access_token, = validate_get(('access_token',), (str,), (0,)) user = validate_user(access_token) if user.user_type == CLIENT: tree = get_tree(user.client.group, CLIENT) return jsonify({'success': True, 'tree': tree}) elif user.user_type == PARTNER: tree = get_tree(user.partner.group, PARTNER) return jsonify({'success': True, 'tree': tree}) abort(400) @app.route("/api/connect_hub", methods=['POST']) @is_auth @jsonp def connect_hub(): access_token, device_id, group_id, name, order_id = validate_post( ('access_token', 'device_id', 'group_id', 'name', 'order_id'), (str, str, int, unicode, int), (0,)*5) if not (access_token and device_id and name and group_id): abort(400) user = validate_user(access_token) device = Hub.query.filter_by(device_id=device_id).first_or_404() if user.user_type == CLIENT and device.hub_client \ or user.user_type == PARTNER and device.hub_partner: abort(404) group = Client_group.query.get_or_404(group_id) if user.user_type == CLIENT \ else Partner_group.query.get_or_404(group_id) if not valid_group_user(group, user): abort(404) hub = Hub_client(name, device, order_id, group) if user.user_type == CLIENT \ else Hub_partner(name, device, order_id, group) db.session.add(hub) db.session.commit() return jsonify({'success': True, 'id': hub.id, 'name': name}) @app.route("/api/disconnect_hub", methods=['POST']) @is_auth @jsonp def disconnect_hub(): access_token, hub_id, group_id = validate_post( ('access_token', 'hub_id', 'group_id'), (str, int, int), (0,)*3) if not (access_token and hub_id and group_id): abort(400) user = validate_user(access_token) hub = Hub_client.query.get_or_404(hub_id) if user.user_type == CLIENT \ else Hub_partner.query.get_or_404(hub_id) group = Client_group.query.get_or_404(group_id) if user.user_type == CLIENT \ else Partner_group.query.get_or_404(group_id) if not valid_group_user(group, user): abort(404) if hub not in group.hubs: abort(404) db.session.delete(hub) db.session.commit() return jsonify({'success': True}) @app.route("/api/rename_hub", methods=['POST']) @is_auth @jsonp def rename_hub(): access_token, hub_id, name = validate_post( ('access_token', 'hub_id', 'name'), (str, str, unicode), (0,)*4) if not (access_token and hub_id and name): abort(400) user = validate_user(access_token) hub = Hub_client.query.get_or_404(hub_id) if user.user_type == CLIENT \ else Hub_partner.query.get_or_404(hub_id) group = hub.group if not valid_group_user(group, user): abort(404) hub.name = name db.session.commit() return jsonify({'success': True, 'name': name}) @app.route("/api/hub_statistics", methods=['GET']) @is_auth @jsonp def hub_statistics(): access_token, hub_id = validate_get( ('access_token', 'hub_id'), (str, str), (0,)*2) if not (access_token and hub_id): abort(400) user = validate_user(access_token) hub = Hub_client.query.get_or_404(hub_id) if user.user_type == CLIENT \ else Hub_partner.query.get_or_404(hub_id) group = hub.group if not valid_group_user(group, user): abort(401) if hub.hub is None: abort(404) stats = Hub_statistics.query.filter_by(hub_id=hub.hub.id).order_by(desc(Hub_statistics.create_time)).first() try: data = statistics(hub.hub.meta, stats) except Exception as e: abort(500) return jsonify({'success': True, 'data': data}) @app.route("/api/charts_statistics", methods=['GET']) @is_auth @jsonp def charts_statistics(): access_token, hub_id, period = validate_get( ('access_token', 'hub_id', 'period'), (str, str, str), (0,)*3) if not (access_token and hub_id): abort(400) user = validate_user(access_token) hub = Hub_client.query.get_or_404(hub_id) if user.user_type == CLIENT \ else Hub_partner.query.get_or_404(hub_id) group = hub.group if not valid_group_user(group, user): abort(404) if hub.hub is None: abort(404) # try: if period == 'week': q = Hub_statistics.query.filter_by(hub_id=hub.hub.id)\ .filter(Hub_statistics.create_time > datetime.datetime.utcnow() - datetime.timedelta(days=7))\ .order_by(asc(Hub_statistics.create_time))\ .distinct(Hub_statistics.create_time).group_by(func.date(Hub_statistics.create_time))\ .group_by(func.hour(Hub_statistics.create_time).op('div')(8)*8) elif period == 'month': q = Hub_statistics.query.filter_by(hub_id=hub.hub.id) \ .filter(Hub_statistics.create_time > datetime.datetime.utcnow() - datetime.timedelta(days=30)) \ .order_by(asc(Hub_statistics.create_time)) \ .distinct(Hub_statistics.create_time).group_by(func.date(Hub_statistics.create_time)) else: q = Hub_statistics.query.filter_by(hub_id=hub.hub.id) \ .filter(Hub_statistics.create_time > datetime.datetime.utcnow() - datetime.timedelta(days=1)) \ .order_by(asc(Hub_statistics.create_time)) \ .distinct(Hub_statistics.create_time).group_by(func.hour(Hub_statistics.create_time)) # except Exception as e: # abort(500) return jsonify({'success': True, 'data': chart_statistics(q.all())}) @app.route("/api/create_group", methods=['POST']) @is_auth @jsonp def create_group(): access_token, parent_id, name, order_id = validate_post(('access_token', 'parent_id', 'name', 'order_id'), (str, int, unicode, int), (0,)*4) if not (access_token and name and parent_id): abort(400) user = validate_user(access_token) if user.user_type == 'client': parent = Client_group.query.get_or_404(parent_id) if not valid_group_user(parent, user): abort(404) new_group = Client_group(name, parent=parent) new_group.order_id = order_id db.session.add(new_group) elif user.user_type == 'partner': parent = Partner_group.query.get_or_404(parent_id) if not valid_group_user(parent, user): abort(404) new_group = Partner_group(name, parent=parent) new_group.order_id = order_id db.session.add(new_group) else: abort(400) db.session.commit() return jsonify({'success': True, 'id': new_group.id, 'name': name}) @app.route("/api/remove_group", methods=['POST']) @is_auth @jsonp def remove_group(): access_token, group_id = validate_post(('access_token', 'group_id'), (str, int), (0,)*2) if not (access_token and group_id): abort(400) user = validate_user(access_token) if user.user_type == 'client': group = Client_group.query.get_or_404(group_id) if not valid_group_user(group, user): abort(404) db.session.delete(group) elif user.user_type == 'partner': group = Partner_group.query.get_or_404(group_id) if not valid_group_user(group, user): abort(404) db.session.delete(group) else: abort(400) db.session.commit() return jsonify({'success': True}) @app.route("/api/rename_group", methods=['POST']) @is_auth @jsonp def rename_group(): access_token, group_id, name = validate_post(('access_token', 'group_id', 'name'), (str, int, unicode), (0,)*3) if not (access_token and name and group_id): abort(400) user = validate_user(access_token) if user.user_type == 'client': group = Client_group.query.get_or_404(group_id) if not valid_group_user(group, user): abort(404) group.name = name elif user.user_type == 'partner': group = Partner_group.query.get_or_404(group_id) if not valid_group_user(group, user): abort(404) group.name = name else: abort(400) db.session.commit() return jsonify({'success': True, 'name': name}) @app.route("/api/reorder", methods=['POST']) @is_auth @jsonp def reorder(): access_token, parent_id = validate_post(('access_token', 'parent_id'), (str, int), (0,)*2) if not (access_token and parent_id): abort(400) children = parseList('children') if not children: abort(400) user = validate_user(access_token) if user.user_type == CLIENT: if not valid_group_user(Client_group.query.get_or_404(parent_id), user): abort(401) for key in children: if children[key]['type'] == 'hub': hub = Hub_client.query.get_or_404(int(children[key]['id'])) if not valid_group_user(hub.group, user): abort(401) hub.order_id = int(children[key]['order_id']) hub.group_id = parent_id db.session.commit() if children[key]['type'] == 'tab': group = Client_group.query.get_or_404(int(children[key]['id'])) if not valid_group_user(group, user): abort(401) group.order_id = int(children[key]['order_id']) group.parent_id = parent_id db.session.commit() elif user.user_type == PARTNER: if not valid_group_user(Partner_group.query.get_or_404(parent_id), user): abort(401) for key in children: if children[key]['type'] == 'hub': hub = Hub_partner.query.get_or_404(int(children[key]['id'])) if not valid_group_user(hub.group, user): abort(401) hub.order_id = int(children[key]['order_id']) hub.group_id = parent_id db.session.commit() if children[key]['type'] == 'tab': group = Partner_group.query.get_or_404(int(children[key]['id'])) if not valid_group_user(group, user): abort(401) group.order_id = int(children[key]['order_id']) group.parent_id = parent_id db.session.commit() return jsonify({'success': True}) """ -----Страницы личного кабинета----- """ siteBasePath = "html" # путь к шаблонам относительно запущенного приложения env = Environment(loader=FileSystemLoader(siteBasePath)) # Страницы сайта @app.route("/success.html") def success(): return env.get_template("Success.html").render() @app.route("/index.html") @app.route("/index") @app.route("/Home.html") @app.route("/Home") @app.route("/home.html") @app.route("/home") @app.route("/") def home(): return env.get_template("Home.html").render() @app.route("/signin.html") @app.route("/signin") def signin(): return env.get_template("signin.html").render() @app.route("/signup.html") @app.route("/signup") def signup(): return env.get_template("signup.html").render() @app.route("/recover.html") @app.route("/recover") def recover(): return env.get_template("recover.html").render() @app.route("/newpassword.html") @app.route("/newpassword") def newpassword(): email, token = validate_get(('email', 'token',), (str,) * 2, ('',) * 2) return env.get_template("newpassword.html").render(email=email, token=token) def testdata(): if Hub.query.filter_by(device_id='hub1').first(): return user = User.query.filter_by(email='<EMAIL>', user_type='partner').first() new_group = user.partner.group hub1 = Hub('hub1') hub2 = Hub('hub2') hub3 = Hub('hub3') hub4 = Hub('hub4') hub5 = Hub('hub5') new_sub_group = Partner_group('group2', parent=new_group) new_sub_sub_group = Partner_group('group3', parent=new_sub_group) db.session.add_all([hub1, hub2, hub3, hub4, hub5, new_group, new_sub_group, new_sub_sub_group]) db.session.commit() new_group.hubs.extend([hub1, hub2]) hub1.order_partner_id = 2 hub2.order_partner_id = 1 new_sub_group.hubs.extend([hub3, hub4]) hub3.order_partner_id = 0 hub4.order_partner_id = 1 new_sub_sub_group.hubs.extend([hub5]) db.session.commit() tree = get_tree(new_group, 'partner') print tree env_serv = os.getenv('SERVER_SOFTWARE') if app.config['DEBUG']: base = ''.join(str(0) for i in range(32)) if not Hub.query.filter_by(serial_id=base).first(): db.session.add_all( [Hub(base[:32-len(str(i))]+str(i), device_id='device-id-%d' % i) for i in range(app.config['TEST_HUB_NUM'])]) db.session.commit() if not (env_serv and env_serv.startswith('Google App Engine/')): if 'win' in sys.platform and __name__ == "__main__": app.run(host='0.0.0.0', port=81) <file_sep>/hub_code/Code.py import time print time.strftime('%X %x %Z') <file_sep>/Token.py # -*- coding: utf-8 -*- # Генерация/подтверждение токена from itsdangerous import URLSafeTimedSerializer as urlsave def generate_token(target, secret_key): serializer = urlsave(secret_key) return serializer.dumps(target) def confirm_token(token, secret_key, expiration): serializer = urlsave(secret_key) try: target = serializer.loads( token, max_age=expiration ) except: return False return target <file_sep>/Config.py # -*- coding: utf-8 -*- # Конфигурация приложения import os import sys # приложение DEBUG = True TEST_HUB_NUM = 100 # база данных env = os.getenv('SERVER_SOFTWARE') if env and env.startswith('Google App Engine/'): # Connecting from App Engine SQLALCHEMY_DATABASE_URI = 'mysql+mysqldb://root@/atol_hab?unix_socket=/cloudsql/atol-test:us-central1:cloudbd1' else: # Connecting from an external network. # Make sure your network is whitelisted if 'win' in sys.platform: SQLALCHEMY_DATABASE_URI = 'mysql://root:root@localhost/cloudbd' else: SQLALCHEMY_DATABASE_URI = 'mysql://root@172.16.17.32:3306/cloudbd1' SQLALCHEMY_TRACK_MODIFICATIONS = False with open('key.secret') as key: SECRET_KEY = key.readline() # время, через которое удаляется кэш запись, если она не обновляется (в секундах) MAX_CACHE_TIME = 24 * 60 * 60 # # почта (если сервер - не Google App Engine) # MAIL_SERVER = 'smtp.gmail.com' # MAIL_PORT = 587 # MAIL_USE_SSL = True # MAIL_USE_TLS = False # MAIL_USERNAME = '<EMAIL>' # MAIL_PASSWORD = '<PASSWORD>' # время, в течение которого ссылка для подтверждения почты # является действующей (confirmation token is valid) CONFIRM_TIME = 24 * 60 * 60 PROJECT_ID = 'atol-test' <file_sep>/Models.py # -*- coding: utf-8 -*- # Определение архитектуры базы данных from datetime import datetime from App import db from Helpers import AppException from sqlalchemy.ext.hybrid import hybrid_property class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(128)) email = db.Column(db.String(128), unique=True, nullable=False) password = db.Column(db.String(128), unique=True, nullable=False) confirmed = db.Column(db.Boolean, default=False) recovery_token = db.Column(db.String(128)) user_type = db.Column(db.Enum('partner', 'client'), nullable=False) client = db.relationship("Client", uselist=False, backref="user") partner = db.relationship("Partner", uselist=False, backref="user") def __init__(self, name, email, password, user_type): self.name = name self.email = email self.password = <PASSWORD> self.user_type = user_type def __repr__(self): return self.email class Client(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False, unique=True) group = db.relationship('Client_group', backref='client', uselist=False) def __init__(self, user): self.user = user self.group = Client_group(user.name if user.name else user.email) class Partner(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False, unique=True) group = db.relationship('Partner_group', backref='partner', uselist=False) def __init__(self, user): self.user = user self.group = Partner_group(user.name if user.name else user.email) class Client_group(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(128)) parent_id = db.Column(db.Integer, db.ForeignKey(id)) client_id = db.Column(db.Integer, db.ForeignKey('client.id'), unique=True) order_id = db.Column(db.Integer) childes = db.relationship('Client_group', cascade="all, delete", backref=db.backref('parent', remote_side=id), lazy='dynamic') hubs = db.relationship('Hub_client', cascade="all, delete", backref='group', lazy='dynamic') def __init__(self, name, parent=None): self.name = name self.parent = parent class Partner_group(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(128)) parent_id = db.Column(db.Integer, db.ForeignKey(id)) partner_id = db.Column(db.Integer, db.ForeignKey('partner.id'), unique=True) order_id = db.Column(db.Integer) childes = db.relationship('Partner_group', cascade="all, delete", backref=db.backref('parent', remote_side=id), lazy='dynamic') hubs = db.relationship('Hub_partner', cascade="all, delete", backref='group', lazy='dynamic') def __init__(self, name, parent=None): self.name = name self.parent = parent class Hub_partner(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(128)) group_id = db.Column(db.Integer, db.ForeignKey('partner_group.id'), nullable=False) order_id = db.Column(db.Integer) device_id = db.Column(db.String(128), db.ForeignKey('hub.device_id', onupdate="set null")) def __init__(self, name, hub, order_id=0, group=None): self.name = name self.hub = hub self.order_id = order_id self.group = group class Hub_client(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(128)) group_id = db.Column(db.Integer, db.ForeignKey('client_group.id'), nullable=False) order_id = db.Column(db.Integer) device_id = db.Column(db.String(128), db.ForeignKey('hub.device_id', onupdate="cascade")) def __init__(self, name, hub, order_id=0, group=None): self.name = name self.hub = hub self.order_id = order_id self.group = group class Hub(db.Model): id = db.Column(db.Integer, primary_key=True) serial_id = db.Column(db.String(32), unique=True, nullable=False) device_id = db.Column(db.String(128), unique=True) uploaded_settings = db.Column(db.Boolean, default=True) sended_settings = db.Column(db.Boolean, default=True) hub_client = db.relationship('Hub_client', backref='hub', uselist=False) hub_partner = db.relationship('Hub_partner', backref='hub', uselist=False) meta = db.relationship('Hub_meta', backref='hub', uselist=False) settings = db.relationship('Hub_settings', backref='hub', uselist=False) stats = db.relationship('Hub_statistics', backref='hub', lazy='dynamic') def __init__(self, serial_id, device_id=None): self.meta = Hub_meta() self.settings = Hub_settings() self.serial_id = serial_id if device_id: self.device_id = device_id class Hub_meta(db.Model): id = db.Column(db.Integer, primary_key=True) hub_id = db.Column(db.Integer, db.ForeignKey('hub.id'), unique=True) utm_version = db.Column(db.String(96)) certificate_rsa_date = db.Column(db.Date) certificate_gost_date = db.Column(db.Date) class Hub_statistics(db.Model): id = db.Column(db.Integer, primary_key=True) utm_status = db.Column(db.Boolean, default=False) unset_tickets_count = db.Column(db.Integer) total_tickets_count = db.Column(db.Integer) retail_buffer_size = db.Column(db.Integer) buffer_age = db.Column(db.BigInteger) create_time = db.Column(db.DateTime, unique=True) hub_id = db.Column(db.Integer, db.ForeignKey('hub.id')) def __init__(self, utm_status, unset_tickets_count, total_tickets_count, retail_buffer_size, buffer_age, create_time=datetime.utcnow()): self.utm_status = utm_status self.unset_tickets_count = unset_tickets_count self.total_tickets_count = total_tickets_count self.retail_buffer_size = retail_buffer_size self.buffer_age = buffer_age self.create_time = create_time # Здоровеееенная (но простая) часть БД, отвечающая за хранение настроек - - - - class Hub_settings(db.Model): id = db.Column(db.Integer, primary_key=True) supervisor = db.relationship('Supervisor', backref='hub_settings', uselist=False) scanner = db.relationship('Scanner', backref='hub_settings', uselist=False) proxy = db.relationship('Proxy', backref='hub_settings', uselist=False) mail = db.relationship('Mail', backref='hub_settings', uselist=False) vpn = db.relationship('Vpn', backref='hub_settings', uselist=False) transport = db.relationship('Transport', backref='hub_settings', uselist=False) hostapd = db.relationship('Hostapd', backref='hub_settings', uselist=False) wifi = db.relationship('Wifi', backref='hub_settings', uselist=False) internet = db.relationship('Internet', backref='hub_settings', uselist=False) ethernet = db.relationship('Ethernet', backref='hub_settings',uselist=False) modem = db.relationship('Modem', backref='hub_settings', uselist=False) ttn = db.relationship('Ttn', backref='hub_settings', uselist=False) hub_id = db.Column(db.Integer, db.ForeignKey('hub.id'), unique=True) class Supervisor(db.Model): id = db.Column(db.Integer, primary_key=True) max_timer_transport_restart = db.Column(db.Integer) restart_if_no_cert = db.Column(db.Boolean) logging = db.Column(db.Enum('release', 'debug')) max_force_restart_count = db.Column(db.Integer) max_timer_transport_reboot = db.Column(db.Integer) restart_allow_reboot = db.Column(db.Boolean) scan_period = db.Column(db.Integer) max_timer_transport_force_restart = db.Column(db.Integer) supervisor_enabled = db.Column(db.Boolean) settings_id = db.Column(db.Integer, db.ForeignKey('hub_settings.id'), unique=True) class Scanner(db.Model): id = db.Column(db.Integer, primary_key=True) sens = db.Column(db.Integer) port = db.Column(db.String(128)) suffix = db.Column(db.String(64)) settings_id = db.Column(db.Integer, db.ForeignKey('hub_settings.id'), unique=True) class Proxy(db.Model): id = db.Column(db.Integer, primary_key=True) proxy_port = db.Column(db.Integer) proxy_type = db.Column(db.String(128)) settings_id = db.Column(db.Integer, db.ForeignKey('hub_settings.id'), unique=True) class Mail(db.Model): id = db.Column(db.Integer, primary_key=True) mail = db.Column(db.String(128)) settings_id = db.Column(db.Integer, db.ForeignKey('hub_settings.id'), unique=True) class Vpn(db.Model): id = db.Column(db.Integer, primary_key=True) tls = db.Column(db.Enum('enable', 'disable')) zip = db.Column(db.Enum('enable', 'disable')) vpn_type = db.Column(db.Enum('client', 'off')) proto = db.Column(db.String(32)) cipher = db.Column(db.String(32)) hosts = db.Column(db.String(128)) interface = db.Column(db.String(128)) settings_id = db.Column(db.Integer, db.ForeignKey('hub_settings.id'), unique=True) class Transport(db.Model): id = db.Column(db.Integer, primary_key=True) access_control_allow_origin = db.Column(db.String(128)) key_pincode = db.Column(db.String(128)) user_pincode = db.Column(db.String(128)) rolling_log = db.Column(db.Enum('off', 'on')) settings_id = db.Column(db.Integer, db.ForeignKey('hub_settings.id'), unique=True) class Hostapd(db.Model): id = db.Column(db.Integer, primary_key=True) ap_name = db.Column(db.String(128)) ap_channel = db.Column(db.String(32)) ap_pass = db.Column(db.String(128)) settings_id = db.Column(db.Integer, db.ForeignKey('hub_settings.id'), unique=True) class Wifi(db.Model): id = db.Column(db.Integer, primary_key=True) network = db.Column(db.String(64)) ap_pass = db.Column(db.String(64)) ip = db.Column(db.String(64)) mask = db.Column(db.String(64)) ap_channel = db.Column(db.String(64)) ap_list = db.Column(db.String(64)) broadcast = db.Column(db.String(64)) ap_name = db.Column(db.String(128)) mode = db.Column(db.String(64)) dns = db.Column(db.String(64)) address_type = db.Column(db.String(64)) gateway = db.Column(db.String(64)) settings_id = db.Column(db.Integer, db.ForeignKey('hub_settings.id'), unique=True) class Internet(db.Model): id = db.Column(db.Integer, primary_key=True) gateway = db.Column(db.String(64)) settings_id = db.Column(db.Integer, db.ForeignKey('hub_settings.id'), unique=True) class Ethernet(db.Model): id = db.Column(db.Integer, primary_key=True) network = db.Column(db.String(64)) ip = db.Column(db.String(64)) mask = db.Column(db.String(64)) broadcast = db.Column(db.String(64)) dns = db.Column(db.String(64)) address_type = db.Column(db.String(64)) gateway = db.Column(db.String(64)) settings_id = db.Column(db.Integer, db.ForeignKey('hub_settings.id'), unique=True) class Modem(db.Model): id = db.Column(db.Integer, primary_key=True) modem_phone = db.Column(db.String(32)) modem_password = db.Column(db.String(64)) modem_user = db.Column(db.String(64)) modem_apn = db.Column(db.String(64)) settings_id = db.Column(db.Integer, db.ForeignKey('hub_settings.id'), unique=True) class Ttn(db.Model): id = db.Column(db.Integer, primary_key=True) logging = db.Column(db.Enum('release', 'debug')) auth = db.Column(db.Boolean) settings_id = db.Column(db.Integer, db.ForeignKey('hub_settings.id'), unique=True) <file_sep>/static/js/atol-api.js function reloadTree() { $('.sortable').nestedSortable({ handle: 'div', items: 'li', toleranceElement: '> div', listType: 'ul', disableNesting: 'hub', rootID: 'rootHub', protectRoot: true, delay: 150, placeholder: "ui-state-highlight", revert: 250, opacity: 0.7, helper: "clone", handle: "a", distance: 4, // containment: '.sortable', update: function (event, ui) { group_id = ui.item.parent().parent().children('div').attr('id'); children_arr = []; ui.item.parent().children().each(function (i) { $(this).children('div').attr("data-order_id", i); children_arr[i] = {id: $(this).children('div').attr("id"), order_id: i, type: $(this).attr('class') }; }); $("#modal-wait").show(); $.post( "/api/reorder", {access_token: localStorage.getItem("atol_access_token"), parent_id: group_id, children: children_arr, }, function(response,textStatus,xhr){ if (xhr.status == 401){ signOut(); } if (response.success == true){ console.log("success"); } else { $('.sortable').nestedSortable("cancel"); }; $("#modal-wait").hide(); }, 'json' ).fail(function() { $("#modal-wait").hide(); $('.sortable').nestedSortable("cancel"); }); }, }); } function openMenu() { $('#open-menu').toggle('fast'); } function getUserInfo() { $("#modal-wait").show(); // getUserInfo $.get( "/api/get_user_info", {access_token: localStorage.getItem("atol_access_token")}, function(response,textStatus,xhr){ if (xhr.status == 401){ signOut(); } if (response.success == true){ $('.body-title').append(response.name); //response.type } else { window.open("signin.html","_self"); }; $("#modal-wait").hide(); }, 'json' ).fail(function() { $("#modal-wait").hide(); // $("#main").css("display","none"); window.open("signin.html","_self"); }); } function getTree() { $("#modal-wait").show(); $.get( "/api/get_tree", {access_token: localStorage.getItem("atol_access_token")}, function(response,textStatus,xhr){ if (xhr.status == 401){ signOut(); } if (response.success == true){ data = response.tree; $("#rootHub > div > a").html(data.name); $("#rootHub > div").attr("id",data.id); $("#rootHub > div").attr("data-hub_num",data.hub_num); $("#rootHub > div").attr("data-group_num",data.group_num); $('#dashboard-group').html(data.name); localStorage.setItem("rootId", data.id); var children = data.children.sort(function(a, b) { return a.order_id - b.order_id || a.name.localeCompare(b.name); }); for (var i = 0; i < children.length; i++) { if (children[i].type == "hub") $("#rootHub > ul").append( "<li class='hub'><div id='"+children[i].id+"' data-order_id='"+children[i].order_id+"'><i class='fa fa-laptop fa-fw'></i>&nbsp;<a>"+children[i].name+"</a></div></li>" ); else if (children[i].type == "group") $("#rootHub > ul").append( parseTree(children[i]) ); } } else { }; function parseTree(elem){ var children = elem.children.sort(function(a, b) { return a.order_id - b.order_id || a.name.localeCompare(b.name); }); var s = "<li class='tab'><div id = '"+elem.id+"' data-hub_num='"+elem.hub_num+"' data-group_num='"+elem.group_num+"' data-order_id='"+elem.order_id+"'><i class='fa fa-fw fa-folder' style='display:none;'></i><i class='fa fa-fw fa-folder-open'></i>&nbsp;<a>"; s = s + elem.name + "</a></div><ul>"; for (var i = 0; i < children.length; i++) { if (children[i].type == "hub") s = s + "<li class='hub'><div id='"+children[i].id+"' data-order_id='"+children[i].order_id+"'><i class='fa fa-laptop fa-fw'></i>&nbsp;<a>"+children[i].name+"</a></div></li>"; else if (children[i].type == "group") s = s + parseTree(children[i]); } return (s + "</ul></li>"); } $("#modal-wait").hide(); }, dataType='JSON' ).fail(function() { $("#modal-wait").hide(); }).done(function(){ $('#group_stats1 > b').text($('.active-elem').attr("data-group_num")); $('#group_stats2 > b').text($('.active-elem').attr("data-hub_num")); }); } function addGroup(){ $("#modal-wait").show(); order = $('.active-elem').closest('li').children('ul').children('li').last().children('div').attr("data-order_id")+1; if (isNaN(order)) order = 0; console.log(order); $.post( "/api/create_group", {access_token: localStorage.getItem("atol_access_token"), name: $("#group-form input[name='name']").val(), parent_id: $('.active-elem').attr('id'), order_id: order }, function(response,textStatus,xhr){ if (xhr.status == 401){ signOut(); } if (response.success == true){ $('.active-elem').parent().children("ul").append( "<li class='tab'><div id = '"+response.id+"' data-order_id='"+order+"'><i class='fa fa-fw fa-folder' style='display:none;'></i><i class='fa fa-fw fa-folder-open'></i>&nbsp;<a>"+response.name+"</a></div><ul></ul></li>" ); $("#group-form input[name='device_id']").val(''); $("#group-form input[name='name']").val(''); $("#modal-group").hide(); reloadTree(); //response.type } else { }; $("#modal-wait").hide(); }, 'json' ).fail(function() { $("#modal-wait").hide(); }); } function addHub(){ //access_token, device_id, name, group_id $("#modal-wait").show(); order = $('.active-elem').closest('li').children('ul').children('li').last().children('div').attr("data-order_id")+1; if (isNaN(order)) order = 0; $.post( "/api/connect_hub", {access_token: localStorage.getItem("atol_access_token"), device_id: $("#hub-form input[name='device_id']").val(), name: $("#hub-form input[name='name']").val(), group_id: $('.active-elem').attr('id'), order_id: order }, function(response,textStatus,xhr){ if (xhr.status == 401){ signOut(); } if (response.success == true){ $('.active-elem').parent().children("ul").append( "<li class='hub'><div id='"+response.id+"' data-order_id='"+order+"'><i class='fa fa-laptop fa-fw'></i>&nbsp;<a>"+response.name+"</a></div></li>" ); $("#hub-form input[name='device_id']").val(''); $("#hub-form input[name='name']").val(''); $("#hub-label").html("Введите идентификатор Хаба"); $("#modal-hub").hide(); reloadTree(); //response.type } else { $("#hub-form input[name='device_id']").val(''); $("#hub-label").html("Неправильный идентификатор. Введите другой идентификатор Хаба"); }; $("#modal-wait").hide(); }, 'json' ).fail(function() { $("#modal-wait").hide(); $("#hub-form input[name='device_id']").val(''); $("#hub-label").html("Ошибка. Введите другой идентификатор Хаба"); }); } function deleteGroup(){ $("#modal-wait").show(); $.post( "/api/remove_group", {access_token: <EMAIL>.getItem("atol_access_token"), group_id: $('.active-elem').attr('id') }, function(response,textStatus,xhr){ if (xhr.status == 401){ signOut(); } if (response.success == true){ el = $('.active-elem').closest('ul').parent().children('div'); $('.active-elem').closest('li').remove(); el.addClass("active-elem"); $("#modal-delete-group").hide(); if (el.hasClass('tab-root')) { $('#panel-group').show("fast"); $('#panel-hub').show("fast"); $('#panel-rename-group').show("fast"); $('#panel-rename-hub').hide("fast"); $('#panel-delete-hub').hide("fast"); $('#panel-delete-group').hide("fast"); } else{ $('#panel-group').show(); $('#panel-hub').show(); $('#panel-rename-group').show(); $('#panel-rename-hub').hide(); $('#panel-delete-hub').hide(); $('#panel-delete-group').show(); } $('#dashboard-hub').hide(); $('#dashboard-group').show(); $('#dashboard-group').html(el.children("a").html()); //response.type } else { }; $("#modal-wait").hide(); }, 'json' ).fail(function() { $("#modal-wait").hide(); }); } function deleteHub(){ $("#modal-wait").show(); $.post( "/api/disconnect_hub", {access_token: localStorage.getItem("atol_access_token"), hub_id: $('.active-elem').attr('id'), group_id: $('.active-elem').closest('ul').parent().children('div').attr('id') }, function(response,textStatus,xhr){ if (xhr.status == 401){ signOut(); } if (response.success == true){ el = $('.active-elem').closest('ul').parent().children('div'); $('.active-elem').closest('li').remove(); el.addClass("active-elem"); $("#modal-delete-hub").hide(); $('#panel-group').show(); $('#panel-hub').show(); $('#panel-rename-group').show(); $('#panel-rename-hub').hide(); $('#panel-delete-hub').hide(); $('#panel-delete-group').show(); $('#dashboard-group').show(); $('#dashboard-group').html(el.children("a").html()); $('#dashboard-hub').hide(); //response.type $("#modal-wait").hide(); } else { }; }, 'json' ).fail(function() { $("#modal-wait").hide(); }); } function renameGroup(){ $("#modal-wait").show(); $.post( "/api/rename_group", {access_token: localStorage.getItem("atol_access_token"), group_id: $('.active-elem').attr('id'), name: $("#rename-form-group input[name='name']").val(), }, function(response,textStatus,xhr){ if (xhr.status == 401){ signOut(); } if (response.success == true){ $('.active-elem > a').html(response.name); $("#rename-form-group input[name='name']").val(''); $("#modal-rename-group").hide(); reloadTree(); } else { }; $("#modal-wait").hide(); }, 'json' ).fail(function() { $("#modal-wait").hide(); }); } function renameHub(){ $("#modal-wait").show(); $.post( "/api/rename_hub", {access_token: localStorage.getItem("atol_access_token"), hub_id: $('.active-elem').attr('id'), name: $("#rename-form-hub input[name='name']").val() }, function(response,textStatus,xhr){ if (xhr.status == 401){ signOut(); } if (response.success == true){ $('.active-elem > a').html(response.name); $("#rename-form-hub input[name='name']").val(''); $("#modal-rename-hub").hide(); reloadTree(); //response.type } else { }; $("#modal-wait").hide(); }, 'json' ).fail(function() { $("#modal-wait").hide(); }); } var TimeoutId = 1; if (!Array.prototype.last){ Array.prototype.last = function(){ return this[this.length - 1]; }; }; function getSmallHubStatistics(){ clearTimeout(TimeoutId); if ($('.active-elem').parent().hasClass("hub")){ $.get( "/api/hub_statistics", {access_token: localStorage.getItem("atol_access_token"), hub_id: $('.active-elem').attr('id') }, function(response,textStatus,xhr){ if (xhr.status == 401){ signOut(); } if (response.success == true){ $('span[id^=hub_stats]').removeClass('w3-text-green w3-text-red w3-text-dark-grey'); $('#hub_stats1 > b').text(response.data.utm_version[0]); $('#hub_stats1').addClass('w3-text-'+response.data.utm_version[1]); $('#hub_stats2 > b').text(response.data.utm_status[0]); $('#hub_stats2').addClass('w3-text-'+response.data.utm_status[1]); $('#hub_stats3 > b').text(response.data.certificate_gost_date[0]); $('#hub_stats3').addClass('w3-text-'+response.data.certificate_gost_date[1]); $('#hub_stats4 > b').text(response.data.certificate_rsa_date[0]); $('#hub_stats4').addClass('w3-text-'+response.data.certificate_rsa_date[1]); $('#hub_stats5 > b').text(response.data.total_tickets_count[0]); $('#hub_stats5').addClass('w3-text-'+response.data.total_tickets_count[1]); $('#hub_stats6 > b').text(response.data.unset_tickets_count[0]); $('#hub_stats6').addClass('w3-text-'+response.data.unset_tickets_count[1]); $('#hub_stats7 > b').text(response.data.buffer_age[0]); $('#hub_stats7').addClass('w3-text-'+response.data.buffer_age[1]); $('#hub_stats8 > b').text(response.data.retail_buffer_size[0]); $('#hub_stats8').addClass('w3-text-'+response.data.retail_buffer_size[1]); $('#status').text(moment(response.data.time).format('DD.MM.YY kk:mm:ss')); // if (myChart !== undefined && myChart.data.labels.last() !== moment(response.data.time)){ // myChart.data.labels.push(moment(response.data.time)); // myChart.data.datasets[0].data.push(response.data.utm_status[2]); // } // // if (myChart1 !== undefined && myChart1.data.labels.last() !== moment(response.data.time)){ // myChart1.data.labels.push(moment(response.data.time)); // myChart1.data.datasets[0].data.push(response.data.total_tickets_count[0]); // myChart1.update(); // } // // if (myChart2 !== undefined && myChart2.data.labels.last() !== moment(response.data.time)){ // myChart2.data.labels.push(moment(response.data.time)); // myChart2.data.datasets[1].data.push(response.data.unset_tickets_count[0]);//документы // myChart2.data.datasets[0].data.push(response.data.retail_buffer_size[0]);//чеки // myChart2.update(); // } // ChartsColors(); } else { $("#hub_stats").hide(); $("#no_stats").show(); }; }, 'json' ).fail(function(response,textStatus,xhr){ if (xhr.status == 401){ signOut(); } $("#hub_stats").hide(); $("#no_stats").show(); }).done(function(){ $("#current_state").animate({ opacity: 1 }, 50); }); } TimeoutId = setTimeout(function(){getSmallHubStatistics();}, 150000); } function ChartsColors() { if (myChart !== undefined){ if (myChart.data.datasets[0].data.last() == 1){ myChart.data.datasets[0].backgroundColor = 'rgba(50, 100, 0, 0.2)'; myChart.data.datasets[0].borderColor = 'rgba(50, 100, 0, 1)'; } else if (myChart.data.datasets[0].data.last() == 0){ myChart.data.datasets[0].backgroundColor = 'rgba(255, 0, 0, 0.2)'; myChart.data.datasets[0].borderColor = 'rgba(255, 0, 0, 1)'; } else { myChart.data.datasets[0].backgroundColor = 'rgba(99, 99, 99, 0.2)'; myChart.data.datasets[0].borderColor = 'rgba(99, 99, 99, 1)'; } myChart.update(); if (isNaN(myChart1.data.datasets[0].data.last())){ myChart1.data.datasets[0].backgroundColor = 'rgba(99, 99, 99, 0.2)'; myChart1.data.datasets[0].borderColor = 'rgba(99, 99, 99, 1)'; } else { myChart1.data.datasets[0].backgroundColor = 'rgba(50, 100, 0, 0.2)'; myChart1.data.datasets[0].borderColor = 'rgba(50, 100, 0, 1)'; } myChart1.update(); if ($('#hub_stats7').hasClass('w3-text-green')){ myChart2.data.datasets[0].backgroundColor = 'rgba(50, 100, 0, 0.2)'; myChart2.data.datasets[0].borderColor = 'rgba(50, 100, 0, 1)'; } else if ($('#hub_stats7').hasClass('w3-text-red')){ myChart2.data.datasets[0].backgroundColor = 'rgba(255, 0, 0, 0.2)'; myChart2.data.datasets[0].borderColor = 'rgba(255, 0, 0, 1)'; } else { myChart2.data.datasets[0].backgroundColor = 'rgba(99, 99, 99, 0.2)'; myChart2.data.datasets[0].borderColor = 'rgba(99, 99, 99, 1)'; } myChart2.update(); } } var myChart; //Статус УТМ var myChart1; //Количество отправленных документов var myChart2; //Размер буффера чеков/неотправленных документов var TimeoutIdCh = 1; function reloadCharts(period){ clearTimeout(TimeoutIdCh); if ($('.active-elem').parent().hasClass("hub")){ $.get( "/api/charts_statistics", {access_token: localStorage.getItem("atol_access_token"), hub_id: $('.active-elem').attr('id'), period: period }, function(response,textStatus,xhr){ if (xhr.status == 401){ signOut(); } if (response.success == true && response.data){ if (myChart !== undefined){ myChart.destroy(); myChart1.destroy(); myChart2.destroy(); } var lbls = Array.from(response.data.total_tickets_count.times, x => moment(x)); var vls = response.data.total_tickets_count.values; var ctx = document.getElementById("myChart1"); myChart1 = new Chart(ctx, { type: 'line', data: { labels: lbls, datasets: [{ lineTension: 0.1, label: 'Количество отправленных документов', pointHitRadius: 10, data: vls, backgroundColor: 'rgba(0, 0, 0, 0.2)' , borderColor: 'rgba(0, 0, 0, 1)' , borderWidth: 1 }] }, options: { scales: { yAxes: [{ }], xAxes: [{ type: 'time', time: { displayFormats: { second: 'DD.MM.YY kk:mm:ss', minute: 'DD.MM.YY kk:mm', hour: 'DD.MM.YY kk:mm', day: 'DD.MM.YY', month: 'DD.MM.YY', year: 'YYYY' } }, ticks: { // maxRotation: 0 } }] } } }); var lbls = Array.from(response.data.utm_status.times, x => moment(x)); var vls = response.data.utm_status.values; var ctx = document.getElementById("myChart"); myChart = new Chart(ctx, { type: 'line', data: { labels: lbls, datasets: [{ steppedLine: true, label: 'Статус УТМ', pointHitRadius: 10, data: vls, backgroundColor: 'rgba(0, 255, 0, 0.2)' , borderColor: 'rgba(0, 255, 0, 1)' , borderWidth: 1 }, ] }, options: { scales: { yAxes: [{ stacked: true }], xAxes: [{ type: 'time', time: { displayFormats: { second: 'DD.MM.YY kk:mm:ss', minute: 'DD.MM.YY kk:mm', hour: 'DD.MM.YY kk:mm', day: 'DD.MM.YY', month: 'DD.MM.YY', year: 'YYYY' } }, ticks: { // maxRotation: 0 } }] } } }); var lbls = Array.from(response.data.unset_tickets_checks_count.times, x => moment(x)); var vls1 = response.data.unset_tickets_checks_count.tickets; var vls2 = response.data.unset_tickets_checks_count.checks; var ctx = document.getElementById("myChart2"); myChart2 = new Chart(ctx, { type: 'line', data: { labels: lbls, datasets: [ { lineTension: 0.1, label: 'Размер буффера чеков', pointHitRadius: 10, data: vls2, backgroundColor: 'rgba(255, 0, 0, 0.2)' , borderColor: 'rgba(255, 0, 0, 1)' , borderWidth: 1 }, { lineTension: 0.1, label: 'Количество неотправленных документов', pointHitRadius: 10, data: vls1, backgroundColor: 'rgba(50, 100, 0, 0.2)' , borderColor: 'rgba(50, 200, 0, 1)' , borderWidth: 1 }] }, options: { scales: { yAxes: [{ }], xAxes: [{ type: 'time', time: { displayFormats: { second: 'DD.MM.YY kk:mm:ss', minute: 'DD.MM.YY kk:mm', hour: 'DD.MM.YY kk:mm', day: 'DD.MM.YY', month: 'DD.MM.YY', year: 'YYYY' } }, ticks: { // maxRotation: 0 } }] } } }); ChartsColors(); } else { }; }, 'json' ).fail(function() { }).done(function(){ $("#history").animate({ opacity: 1 }, 50); $("#history_full").animate({ opacity: 1 }, 50); }); } TimeoutIdCh = setTimeout(function(){reloadCharts(period);}, 1000000); }
06414f3a0655b4c6275572d7fd6ddea36ad9b386
[ "JavaScript", "Python" ]
7
Python
maximdanilchenko/atol-api
c1bf648964566757a78bf959bca62182cd016365
76919516c09f86f98952daba40e9b2f487d5375a
refs/heads/main
<repo_name>nicholasbishop/writedisk<file_sep>/xtask/src/main.rs mod vmtest; use anyhow::Result; use argh::FromArgs; #[derive(FromArgs)] /// Tasks for writedisk. struct Opt { #[argh(subcommand)] action: Action, } #[derive(FromArgs)] #[argh(subcommand)] enum Action { VmTest(ActionVmTest), } /// Test writedisk in a VM. #[derive(FromArgs)] #[argh(subcommand, name = "vmtest")] pub struct ActionVmTest { /// don't enable KVM #[argh(switch)] disable_kvm: bool, } fn main() -> Result<()> { let opt: Opt = argh::from_env(); match &opt.action { Action::VmTest(action) => vmtest::run(action), } } <file_sep>/Cargo.toml [package] name = "writedisk" version = "1.3.0" authors = ["<NAME> <<EMAIL>>"] edition = "2021" repository = "https://github.com/nicholasbishop/writedisk" license = "Apache-2.0" description = "Utility for writing a disk image to a USB drive" readme = "README.md" categories = ["command-line-utilities"] keywords = ["disk", "usb", "image", "burn"] default-run = "writedisk" [dependencies] clap = { version = "4.3.22", features = ["derive"] } procfs = { version = "0.15.1", default-features = false } progress = { version = "0.2.0", default-features = false } [workspace] members = ["xtask"] <file_sep>/xtask/Cargo.toml [package] name = "xtask" version = "0.0.0" edition = "2018" publish = false [dependencies] anyhow = "1.0.75" argh = "0.1.12" camino = "1.1.6" command-run = "1.1.1" fs-err = "2.9.0" rexpect = "0.5.0" tempfile = "3.8.0" <file_sep>/src/bin/wd_copier.rs #![warn(clippy::pedantic)] use clap::Parser; use std::convert::TryInto; use std::io::{Read, Write}; use std::path::PathBuf; use std::sync::mpsc; use std::time::Duration; use std::{fs, thread}; #[derive(Debug, Parser)] struct Opt { src: PathBuf, dst: PathBuf, } /// Get OS dirty byte count using [`procfs::Meminfo`]. fn get_dirty_bytes() -> u64 { match procfs::Meminfo::new() { Ok(o) => o.dirty, Err(_e) => 0, } } struct DirtyInfo { /// Dirty bytes before the copy. This is the "goal". before_copy: u64, /// Dirty bytes after the copy. after_copy: u64, /// Current number of dirty bytes. current: u64, } impl DirtyInfo { /// Estimate the percent completion (between 0 and 100) of the sync /// operation. /// /// The estimate is based on the idea that the number of dirty bytes /// will be close to the value it was before the copy operation once /// sync has completed. After the copy completes, the `current` /// value will be the same as `after_copy`, and it should decrease /// as the sync is underway until it reaches `before_copy`. fn calc_sync_percent(&self) -> i32 { let current = self.current.saturating_sub(self.before_copy); let max = self.after_copy.saturating_sub(self.before_copy); // Flip the value because a lower number of dirty pages is // closer to completion. 100 - calc_percent(current, max) } } #[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)] fn calc_percent(current: u64, max: u64) -> i32 { // Prevent division by zero. if max == 0 { return 0; } let percent = (current as f64) / (max as f64) * 100_f64; let percent = percent as i32; if percent > 100 { 100 } else { percent } } /// Draws a progress bar for a disk sync. /// /// Uses the dirty value before our copy as our 'goal' by reading from /// `/proc/meminfo`. This isn't an exact science and is just a rough estimate /// of our completion. /// /// Meant to be run on a thread parallel to the actual sync process and exits /// after receiving a signal from main that the sync is complete. fn sync_progress_bar( rx: &mpsc::Receiver<()>, mut progress_bar: progress::Bar, mut dirty: DirtyInfo, ) { progress_bar.set_job_title("syncing... (2/2)"); loop { dirty.current = get_dirty_bytes(); progress_bar.reach_percent(dirty.calc_sync_percent()); thread::sleep(Duration::from_millis(500)); if matches!( rx.try_recv(), Ok(_) | Err(mpsc::TryRecvError::Disconnected) ) { return; } } } #[allow(clippy::read_zero_byte_vec)] fn main() { let opt = Opt::parse(); let mut dirty = DirtyInfo { before_copy: get_dirty_bytes(), after_copy: 0, current: 0, }; let mut progress_bar = progress::Bar::new(); progress_bar.set_job_title("copying... (1/2)"); let mut src = fs::File::open(opt.src).unwrap(); let src_size = src.metadata().unwrap().len(); let mut dst = fs::OpenOptions::new().write(true).open(&opt.dst).unwrap(); let mut remaining = src_size; let mut bytes_written: u64 = 0; let chunk_size: u64 = 1024 * 1024; // TODO let mut buf = Vec::new(); while remaining > 0 { let percent = calc_percent(bytes_written, src_size); progress_bar.reach_percent(percent); let read_size = if chunk_size > remaining { remaining } else { chunk_size }; buf.resize(read_size.try_into().unwrap(), 0); src.read_exact(&mut buf).unwrap(); dst.write_all(&buf).unwrap(); remaining -= read_size; bytes_written += read_size; } let (tx, rx) = mpsc::channel(); dirty.after_copy = get_dirty_bytes() - dirty.before_copy; // If we can't get dirty bytes info we can just print 'syncing...' to the screen if dirty.after_copy == 0 { println!("syncing... (2/2)"); } else { thread::spawn(move || { sync_progress_bar(&rx, progress_bar, dirty); }); } dst.sync_data().unwrap(); tx.send(()).unwrap(); println!("finished"); } #[cfg(test)] mod tests { use super::*; #[test] fn test_calc_percent() { assert_eq!(calc_percent(0, 20), 0); assert_eq!(calc_percent(1, 20), 5); assert_eq!(calc_percent(20, 20), 100); // Check clamping. assert_eq!(calc_percent(100, 20), 100); // Check for division by zero. assert_eq!(calc_percent(100, 0), 0); } #[test] fn test_dirty_calc_percent() { let mut dirty = DirtyInfo { before_copy: 100, after_copy: 120, current: 120, }; assert_eq!(dirty.calc_sync_percent(), 0); dirty.current = 105; assert_eq!(dirty.calc_sync_percent(), 75); dirty.current = 100; assert_eq!(dirty.calc_sync_percent(), 100); // Check clamping. dirty.current = 0; assert_eq!(dirty.calc_sync_percent(), 100); dirty.current = 200; assert_eq!(dirty.calc_sync_percent(), 0); } } <file_sep>/README.md # writedisk Small utility for writing a disk image to a USB drive. Usage: `writedisk <input>` This will scan for connected USB disks and prompt for you to select one. Then the input file will be copied to the drive. The copying operation is done with a small `wd_copier` binary that is automatically invoked with `sudo`. Linux only for now. ## Installation ### Cargo ```shell cargo install writedisk ``` ### Nix/NixOS Per user: ```shell nix-env --install writedisk ``` System-wide: ```shell environment.systemPackages = with pkgs; [ writedisk ]; ``` ## License Apache 2.0 <file_sep>/xtask/src/vmtest.rs use crate::ActionVmTest; use anyhow::{anyhow, Result}; use camino::Utf8PathBuf; use command_run::Command; use fs_err as fs; use rexpect::session::PtySession; use std::env; struct AlpineVersion { major: u32, minor: u32, patch: u32, } impl AlpineVersion { fn new(major: u32, minor: u32, patch: u32) -> AlpineVersion { AlpineVersion { major, minor, patch, } } fn iso_file_name(&self) -> String { format!( "alpine-virt-{}.{}.{}-x86_64.iso", self.major, self.minor, self.patch ) } fn iso_url(&self) -> String { format!( "https://dl-cdn.alpinelinux.org/alpine/v{}.{}/releases/x86_64/{}", self.major, self.minor, self.iso_file_name() ) } } struct Vm { qemu: String, iso_path: Utf8PathBuf, usb_backing_file: Utf8PathBuf, data_path: Utf8PathBuf, } fn session_run_cmd(p: &mut PtySession, cmd: &str) -> Result<()> { let prompt = "localhost:~# "; println!("{cmd}"); p.exp_string(prompt)?; p.send_line(cmd)?; Ok(()) } fn session_verify_success(p: &mut PtySession) -> Result<()> { session_run_cmd(p, "echo $?")?; // Skip the echo of the command. p.read_line()?; let exit_code = p.read_line()?; let exit_code = exit_code.trim(); if exit_code != "0" { panic!("command exited non-zero: {}", exit_code); } Ok(()) } impl Vm { fn run(&self, action: &ActionVmTest) -> Result<()> { let qemu_cmd = [ self.qemu.as_str(), if action.disable_kvm { "" } else { "-enable-kvm" }, "-display none", &format!("-drive format=raw,file={}", self.iso_path.as_str()), "-m 512", "-serial stdio", // Add a disk backed by the data subdirectory, will appear as sdb1. &format!("-drive format=raw,file=fat:rw:{}", self.data_path), // Add a USB disk device backed by a file. &format!( "-drive if=none,id=stick,format=raw,file={}", self.usb_backing_file ), "-device nec-usb-xhci,id=xhci", "-device usb-storage,bus=xhci.0,drive=stick", ] .join(" "); println!("{qemu_cmd}"); // Use a fairly long timeout to avoid failing in the CI. let p = &mut rexpect::spawn(&qemu_cmd, Some(100_000))?; // Log in. println!("waiting to log in..."); p.exp_string("localhost login: ")?; println!("logging in"); p.send_line("root")?; // Mount the data dir. session_run_cmd(p, "mkdir /mnt/data")?; session_verify_success(p)?; session_run_cmd(p, "mount /dev/sdb1 /mnt/data")?; session_verify_success(p)?; // Run writedisk. Set the path to the data dir. This is necessary so // that the pseudo sudo executable will be found. session_run_cmd(p, "PATH=/mnt/data writedisk /mnt/data/test_file")?; // Skip the echo of the command. p.read_line()?; // Expect one USB device to be found. let choice_0 = p.read_line()?; if !choice_0.starts_with("0: [/dev/sdc] QEMU QEMU USB HARDDRIVE") { panic!("unexpected output: {}", choice_0); } // Choose the first disk and start the copy. println!("starting copy..."); p.send_line("0")?; // Check the exit code. session_verify_success(p)?; // Shut down. session_run_cmd(p, "poweroff")?; p.exp_eof()?; Ok(()) } } /// Get the absolute path of the repo. Assumes that this executable is /// located at <repo>/target/<buildmode>/<exename>. fn get_repo_path() -> Result<Utf8PathBuf> { let exe = Utf8PathBuf::from_path_buf(env::current_exe()?) .map_err(|_| anyhow!("exe path is not utf-8"))?; Ok(exe .parent() .and_then(|path| path.parent()) .and_then(|path| path.parent()) .ok_or_else(|| anyhow!("not enough parents: {}", exe))? .into()) } pub fn run(action: &ActionVmTest) -> Result<()> { let repo_path = get_repo_path()?; let tmp_dir = tempfile::tempdir()?; let tmp_path = Utf8PathBuf::from_path_buf(tmp_dir.path().into()).unwrap(); let alpine_version = AlpineVersion::new(3, 14, 2); // Download the Alpine ISO. let iso_path = tmp_path.join(alpine_version.iso_file_name()); Command::with_args( "curl", ["--output", iso_path.as_str(), &alpine_version.iso_url()], ) .run()?; // Create a file to back the virtual USB device. let usb_backing_file = tmp_path.join("usb_data"); Command::with_args( "truncate", ["--size", "10MiB", usb_backing_file.as_str()], ) .run()?; // Create the data dir. let data_path = tmp_path.join("data"); fs::create_dir(&data_path)?; // Copy the pseudo sudo executable to the data dir. fs::copy( repo_path.join("xtask/src/pseudo_sudo"), data_path.join("sudo"), )?; // Build a statically-linked writedisk and copy to the data dir. Command::with_args( "cargo", [ "build", "--release", "--target", "x86_64-unknown-linux-musl", ], ) .run()?; let build_path = repo_path.join("target/x86_64-unknown-linux-musl/release"); fs::copy(build_path.join("writedisk"), data_path.join("writedisk"))?; fs::copy(build_path.join("wd_copier"), data_path.join("wd_copier"))?; // Write out a test file that writedisk will use as input. let test_disk_data = b"This is the content of the test file"; let test_data_path = data_path.join("test_file"); fs::write(test_data_path, test_disk_data)?; // Run the VM. let vm = Vm { qemu: "qemu-system-x86_64".into(), iso_path, usb_backing_file: usb_backing_file.clone(), data_path, }; vm.run(action).unwrap(); // Verify the correct data was written. It should start with the // string in `test_disk_data` and the rest should be zeroes. let actual = fs::read(&usb_backing_file)?; assert_eq!(actual.len(), 10 * 1024 * 1024); assert_eq!(&actual[..test_disk_data.len()], test_disk_data); for byte in &actual[test_disk_data.len()..] { assert_eq!(*byte, 0); } println!("test passed"); Ok(()) } <file_sep>/src/bin/writedisk.rs #![warn(clippy::pedantic)] use clap::Parser; use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::{env, fs, process}; #[derive(Clone, Debug)] struct UsbBlockDevice { /// The device path, e.g. "/dev/sdc" device: PathBuf, manufacturer: String, product: String, serial: String, } /// Try to determine whether this is a USB device or not by searching /// upwards for a directory name starting with "usb". fn is_usb_in_path(path: &Path) -> bool { for path in path.ancestors() { if let Some(name) = path.file_name() { if let Some(name) = name.to_str() { if name.starts_with("usb") { return true; } } } } false } /// Search upwards for a directory containing device info /// (manufacturer, product, and serial). fn find_usb_info(path: &Path) -> Option<PathBuf> { for path in path.ancestors() { if path.join("manufacturer").exists() && path.join("product").exists() && path.join("serial").exists() { return Some(path.into()); } } None } impl UsbBlockDevice { fn get_all() -> io::Result<Vec<UsbBlockDevice>> { let mut result = Vec::new(); for entry in fs::read_dir("/sys/block")? { let entry = entry?; let path = entry.path(); let device_path = path.join("device"); if !device_path.exists() { continue; } // This will give a very long path such as: // /sys/devices/pci0000:00/0000:00:01.2/0000:02:00.0/ // 0000:03:08.0/0000:08:00.3/usb4/4-3/4-3.2/4-3.2:1.0/ // host7/target7:0:0/7:0:0:0 let device_path = device_path.canonicalize()?; // Skip non-USB devices if !is_usb_in_path(&device_path) { continue; } if let Some(info_path) = find_usb_info(&device_path) { let read = |name| -> io::Result<String> { let path = info_path.join(name); let contents = fs::read_to_string(path)?; Ok(contents.trim().into()) }; result.push(UsbBlockDevice { device: Path::new("/dev").join(entry.file_name()), manufacturer: read("manufacturer")?, product: read("product")?, serial: read("serial")?, }); } } Ok(result) } fn summary(&self) -> String { format!( "[{}] {} {} {}", self.device.display(), &self.manufacturer, &self.product, &self.serial, ) } } fn choose_device() -> UsbBlockDevice { let devices = UsbBlockDevice::get_all().unwrap(); if devices.is_empty() { println!("no devices found"); process::exit(1); } for (index, device) in devices.iter().enumerate() { println!("{index}: {}", device.summary()); } print!("select device: "); io::stdout().flush().unwrap(); let mut input = String::new(); io::stdin().read_line(&mut input).unwrap(); let index = match input.trim().parse::<usize>() { Ok(i) => i, Err(_e) => { println!("invalid input"); process::exit(1); } }; if index >= devices.len() { println!("invalid index"); process::exit(1); } devices[index].clone() } #[derive(Debug, Parser)] #[command(about = "Write a disk image to a USB disk.", version)] struct Opt { /// Disk image input: PathBuf, } fn main() { let opt = Opt::parse(); // Check if the input file exists before doing anything else. if !opt.input.exists() { eprintln!("file not found: {}", opt.input.display()); process::exit(1); } let device = choose_device(); let copier_path = env::current_exe() .expect("failed to get current exe path") .parent() .expect("failed to get current exe directory") .join("wd_copier"); println!( "sudo {} {} {}", copier_path.display(), opt.input.display(), device.device.display() ); let status = process::Command::new("sudo") .args([&copier_path, &opt.input, &device.device]) .status() .expect("failed to run command"); if !status.success() { println!("copy failed"); process::exit(1); } }
7476f7dd942a301f65d12cd10267dd68c4baadb3
[ "TOML", "Rust", "Markdown" ]
7
Rust
nicholasbishop/writedisk
e21306bb765fdeb0c103a15bec9be69d1875bedc
b6f3b22bf4170040f13feae31f7777c606112fef
refs/heads/master
<file_sep>import numpy as np import matplotlib.pyplot as plt from PIL import Image class EdgeDetector(object): # Sobel filters as numpy array sobel_filter_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) sobel_filter_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]) # Gaussian Filter for smoothening # Discrete approximation to Gaussian function(sigma = 1.0) gaussian_filter = np.array([[1, 4, 7, 4, 1], [4, 16, 26, 16, 4], [7, 26, 41, 26, 7], [4, 16, 26, 16, 4], [1, 4, 7, 4, 1]], dtype=np.float) gaussian_filter = (1.0 / 273) * gaussian_filter def __init__(self): pass def _read_image(self, path): """ Read an image from given path and return coressponded numpy array :param path: image path to be read :return: a numpy array representing the image """ img = np.asarray(Image.open(path)) # If RGB image, convert to gray scale if len(img.shape) == 3: return self._rgb2gray(img) elif len(img.shape) == 2: return img else: raise IOError("Check the image in {}".format(path)) def _rgb2gray(self, rgb): """ convert given rgb image to grayscale image :param rgb: rgb image as numpy array :return: gray scale image as numpy array """ return np.dot(rgb[..., :3], [0.299, 0.587, 0.114]) def _add_padding(self, x, p): """ Add padding to given matrix :param x: matrix (numpy array) :param p: padding size :return: padded matrix as numpy array """ out = np.zeros((x.shape[0] + 2 * p, x.shape[1] + 2 * p)) for i in range(x.shape[0]): for j in range(x.shape[1]): out[i + p][j + p] = x[i][j] return out def _convolution(self, x, w, padding=0): """ Apply convolution to given matrix :param x: matrix as numpy array :param w: kernel matrix as numpy array :param padding: padding size :return: output matrix as nupy array """ img_height, img_width = x.shape filter_height, filter_width = w.shape # Apply Padding x_pad = self._add_padding(x, padding) # Calculate output matrix shape output_height = 1 + (img_height + 2 * padding - filter_height) output_width = 1 + (img_width + 2 * padding - filter_width) out = np.zeros((output_height, output_width)) # Apply convolution for k in range(output_height): if k + filter_height > img_height: break for l in range(output_width): if l + filter_width > img_width: break out[k, l] = np.sum( x_pad[k:k + filter_height, l:l + filter_width] * w) return out def _non_maximum_suppression(self, gradient_magnitude, theta): """ Apply non-maximum supression for given gradient magnitude and theta matrixes :param gradient_magnitude: :param theta: :return: """ assert gradient_magnitude.shape == theta.shape for i in range(gradient_magnitude.shape[0]): for j in range(gradient_magnitude.shape[1]): if i == 0 or i == gradient_magnitude.shape[0] - 1 or j == 0 or j == gradient_magnitude.shape[1] - 1: gradient_magnitude[i, j] = 0 continue direction = theta[i, j] % 4 if direction == 0: # horizontal + if gradient_magnitude[i, j] <= gradient_magnitude[i, j - 1] or gradient_magnitude[i, j] <= \ gradient_magnitude[i, j + 1]: gradient_magnitude[i, j] = 0 if direction == 1: # horizontal - if gradient_magnitude[i, j] <= gradient_magnitude[i - 1, j + 1] or gradient_magnitude[i, j] <= \ gradient_magnitude[i + 1, j - 1]: gradient_magnitude[i, j] = 0 if direction == 2: # vertical + if gradient_magnitude[i, j] <= gradient_magnitude[i - 1, j] or gradient_magnitude[i, j] <= \ gradient_magnitude[i + 1, j]: gradient_magnitude[i, j] = 0 if direction == 3: # vertical - if gradient_magnitude[i, j] <= gradient_magnitude[i - 1, j - 1] or gradient_magnitude[i, j] <= \ gradient_magnitude[i + 1, j + 1]: gradient_magnitude[i, j] = 0 return gradient_magnitude def _check_strong_in_neighbors(self, i, j, img, strong_value): # Check whether given pixel i,j has a strong neighbor or not neighbors = img[max([0, i-1]):min([img.shape[0],i+2]), max([0, j-1]):min([img.shape[1], j+2])] if strong_value in neighbors: return True def _hysteresis_threshold(self, x, low_threshold=60, high_threshold=120): """ Apply Hysteresis Threshold to given matrix :param x: input matrix as numpy array :param low_threshold: :param high_threshold: :return: """ strong_i, strong_j = np.where(x > high_threshold) candidate_i, candidate_j = np.where((x >= low_threshold) & (x <= high_threshold)) zero_i, zero_j = np.where(x < low_threshold) strong = np.int32(255) candidate = np.int32(50) x[strong_i, strong_j] = strong x[candidate_i, candidate_j] = candidate x[zero_i, zero_j] = np.int32(0) M, N = x.shape for i in range(M): for j in range(N): if x[i, j] == candidate: # check if one of the neighbours is strong if self._check_strong_in_neighbors(i, j, x, strong): x[i, j] = strong else: x[i, j] = 0 return x def _show_img(self, img): """ Plot given image :param img: Image to be plotted :return: """ plt.imshow(img, cmap=plt.get_cmap('gray')) plt.show() def _save_img(self, img_arr, path): """ Save given image to file :param img_arr: Imput image :param path: Path to save image :return: """ img = Image.fromarray(np.uint8(img_arr)) img.save(path) def detect_edges(self, img_path, output_path, show_outputs_of_steps=False): """ This method detects edges in input image using Canny Edge Detection Algortihm :param img_path: Path for input image :param output_path: Path for output image :param show_outputs_of_steps: if true, the program will plot the images that are generated in each step :return: Image with edges """ img_data = self._read_image(img_path) if show_outputs_of_steps: self._show_img(img_data) # Gaussion filter for smoothining img_data_smoothened = self._convolution(img_data, EdgeDetector.gaussian_filter) # Find magnitude and angle of gradient gradient_magnitude_x = self._convolution(img_data_smoothened, EdgeDetector.sobel_filter_x, padding=0) if show_outputs_of_steps: self._show_img(gradient_magnitude_x) gradient_magnitude_y = self._convolution(img_data_smoothened, EdgeDetector.sobel_filter_y, padding=0) if show_outputs_of_steps: self._show_img(gradient_magnitude_y) gradient_magnitude = np.sqrt(np.square(gradient_magnitude_x) + np.square(gradient_magnitude_y)) if show_outputs_of_steps: self._show_img(gradient_magnitude) theta = np.arctan2(gradient_magnitude_x, gradient_magnitude_x) # Non Maximum Suppression res = self._non_maximum_suppression(gradient_magnitude, theta) if show_outputs_of_steps: self._show_img(res) # Hysteresis Threshold res = self._hysteresis_threshold(res) if show_outputs_of_steps: self._show_img(res) self._save_img(res, output_path) <file_sep># canny Edge Detector Canny edge detector for ITU Image Processing Course Assignment (2017 Fall). To run the program from command line just run main.py file without any argument. The system will read images in test\_images directory and write the outputs to output\_images directory. Or you can give the input and output paths as command line arguments respectively.<file_sep>import sys import canny_edge_detector from os import listdir from os.path import isfile, join def main(argv): # Create EdgeDetector instance edge_detector = canny_edge_detector.EdgeDetector() # Check command line arguments if len(argv) == 2: # If command line arguments is equal to 2, # the first argument is the directory with input images # and the second argument is the directory for output images image_paths = [argv[0]+"/"+f for f in listdir(argv[0]) if isfile(join(argv[0], f))] output_path = argv[1] elif len(argv) == 0: # If no argument is provided, the program will use default directories for input and output images image_paths = ["test_images/" + f for f in listdir("test_images") if isfile(join("test_images", f))] output_path = "output_images/" else: raise NotImplementedError("Arguments length must be 2! " "First argument is path for input images and second argument is path for output " "images.") # Find images in input directory, find edges and writes edge images to the output directory for img in image_paths: img_file_name = img[img.rfind('/'):] edge_detector.detect_edges(img, output_path + img_file_name) if __name__ == "__main__": main(sys.argv[1:]) <file_sep>numpy=1.13.1 matplotlib=2.0.2 Pillow=4.2.1
275a3cc671abfec12218844dfea62d109c5d3511
[ "Markdown", "Python", "Text" ]
4
Python
erayyildiz/canny_edge_detector
5320abf2110b95f87fdcef47e7694fd002af58a2
5cf83f5b25f4029dee5b489f59cb0c9ad0bb41eb
refs/heads/master
<repo_name>fishgege/gocertsigner<file_sep>/gocertsigner.go // Package gocertsigner is a cgo layer that uses libcrypto to produce pkcs7 signatures for golang. package gocertsigner /* #cgo !windows LDFLAGS: -lcrypto #cgo windows LDFLAGS: /DEV/openssl-1.0.1e/libcrypto.a -lgdi32 #cgo windows CFLAGS: -I /DEV/openssl-1.0.1e/include #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/pkcs12.h> #include <openssl/pkcs7.h> #include <openssl/pem.h> #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/safestack.h> #include <stdio.h> typedef STACK_OF(X509) STACK; static STACK_OF(X509)* X509NewNull() { return sk_X509_new_null(); } static void X509Push(STACK_OF(X509) *ca,X509 *cert) { sk_X509_push(ca, cert); } static void X509PopFree(STACK_OF(X509) *ca) { sk_X509_pop_free(ca, X509_free); } */ import "C" import ( "fmt" "unsafe" ) //KeysAndCerts is a struct to store all openssl types and passwords used for signing. type KeysAndCerts struct { password []byte //password for the p12 cert scert *C.X509 //cert from the p12 cert skey *C.EVP_PKEY //key from the p12 cert ca *C.STACK //stack of certificate authorities. CA from 2 sources } //init is used to setup openssl by adding all ciphers and digests. func init() { C.OpenSSL_add_all_ciphers() C.OpenSSL_add_all_digests() } //free cleans up all openssl certificate and key allocated memory func (kc *KeysAndCerts) free() { kc.clearPassword() C.X509PopFree(kc.ca) C.X509_free(kc.scert) C.EVP_PKEY_free(kc.skey) } //clearPassword writes over the memory where the password was stored. func (kc *KeysAndCerts) clearPassword() { for i := 0; i < len(kc.password); i++ { kc.password[i] = 0 } } //parse12 reads the Pkcs12 certificate byte slice and parses it into a //openssl *C.X509 certificate type and an openssl *C.EVP_PKEY type. func (kc *KeysAndCerts) parseP12(p12Bytes []byte) error { var p12 *C.PKCS12 kc.scert = nil kc.skey = nil p12 = nil defer C.PKCS12_free(p12) p12BufLen := C.long(len(p12Bytes)) p12Buf := ((*C.uchar)(unsafe.Pointer(&p12Bytes[0]))) //go []bytes to C * unsigned char if C.d2i_PKCS12(&p12, &p12Buf, p12BufLen) == nil { return fmt.Errorf("p12 convert error") } pass := C.CString(string(kc.password)) defer C.free(unsafe.Pointer(pass)) if C.PKCS12_parse(p12, pass, &kc.skey, &kc.scert, nil) == 0 { //parse pkcs12 into 3 files var cstr [256]C.char C.ERR_error_string(C.ERR_peek_error(), &cstr[0]) errorStr := C.GoString(&cstr[0]) return fmt.Errorf("%s", errorStr) } if kc.skey == nil { return fmt.Errorf("p12 key is nil") } if kc.scert == nil { return fmt.Errorf("p12 cert is nil") } return nil } //parseX509Cert reads the X509 der formatted certificate byte slice and parses it into a //openssl *C.X509 type. func (kc *KeysAndCerts) parseX509Cert(certX509 []byte) error { kc.scert = nil certBufLen := C.long(len(certX509)) certBuf := ((*C.uchar)(unsafe.Pointer(&certX509[0]))) //bytes[] to * unsigned char //parse X509 for certificate if C.d2i_X509(&kc.scert, &certBuf, certBufLen) == nil { var cstr [256]C.char C.ERR_error_string(C.ERR_peek_error(), &cstr[0]) //get openssl error code errorStr := C.GoString(&cstr[0]) errorStr = "parse Cert Fail:" + errorStr return fmt.Errorf("%s", errorStr) } if kc.scert == nil { return fmt.Errorf("X509 cert is nil") } return nil } //parsePrivateKeyPem reads the private key pem byte slice and parses it into a //openssl *C.EVP_PKEY type. func (kc *KeysAndCerts) parsePrivateKeyPem(privKeyPem []byte) error { kc.skey = nil pemBufLen := C.int(len(privKeyPem)) pemBuf := (unsafe.Pointer(&privKeyPem[0])) //bytes[] to * unsigned char //load the data into a BIO buffer privKeyBio := C.BIO_new_mem_buf(pemBuf, pemBufLen) defer C.BIO_free(privKeyBio) if privKeyBio == nil { return fmt.Errorf("error making key pem buffer") } pass := C.CString(string(kc.password)) defer C.free(unsafe.Pointer(pass)) if C.PEM_read_bio_PrivateKey(privKeyBio, &kc.skey, nil, unsafe.Pointer(pass)) == nil { var cstr [256]C.char C.ERR_error_string(C.ERR_peek_error(), &cstr[0]) //get openssl error code errorStr := C.GoString(&cstr[0]) return fmt.Errorf("%s", errorStr) } return nil } //addCA reads the intermediate & CA root certificates and //adds them to a X509 cert stack. func (kc *KeysAndCerts) addCA(ca []byte) error { /* Read intermediate & CA root certificates */ var caCert *C.X509 caCert = nil defer C.X509_free(caCert) caBufLen := C.long(len(ca)) caBuf := ((*C.uchar)(unsafe.Pointer(&ca[0]))) //bytes[] to * unsigned char if C.d2i_X509(&caCert, &caBuf, caBufLen) == nil { return fmt.Errorf("error adding CA to X509 cert stack") } if caCert == nil { return fmt.Errorf("CA Cert is nil") } //Add the intermediate CA certificate to the signing stack if kc.ca == nil { kc.ca = C.X509NewNull() } C.X509Push(kc.ca, caCert) return nil } //signDoc uses the KeysAndCerts struct to create a pkcs7 signature. func (kc *KeysAndCerts) signDoc(document []byte) ([]byte, error) { flags := C.int(C.PKCS7_DETACHED | C.PKCS7_BINARY) documentBufLen := C.int(len(document)) documentBuf := (unsafe.Pointer(&document[0])) //bytes[] to * unsigned char //load the data into a BIO buffer doc := C.BIO_new_mem_buf(documentBuf, documentBufLen) defer C.BIO_free(doc) if doc == nil { return nil, fmt.Errorf("error making document buffer") } //sign the data and create a pkcs7 p7 := C.PKCS7_sign(kc.scert, kc.skey, kc.ca, doc, flags) defer C.PKCS7_free(p7) if p7 == nil { return nil, fmt.Errorf("p7 signing error") } //output pkcs7 to []byte var buf (*C.uchar) defer C.free(unsafe.Pointer(buf)) len := C.i2d_PKCS7(p7, &buf) if len == 0 { return nil, fmt.Errorf("error converting pkcs7 to byte buffer") } return C.GoBytes(unsafe.Pointer(buf), len), nil } //SignWithP12 signs a document using a p12 cert producing a pkcs7 signature. func SignWithP12(doc []byte, pkcs12 []byte, pkcsPass string, caCert []byte) ([]byte, error) { var kc KeysAndCerts defer kc.free() //free the C allocated memory kc.password = []byte(pkcsPass) //set the password to open the encrypted pkcs12 cert //add the intermediate CA certificate err := kc.addCA(caCert) if err != nil { return nil, err } //parse the p12 into various keys and certificates err = kc.parseP12(pkcs12) if err != nil { return nil, err } //sign the document return kc.signDoc(doc) } //SignWithX509PEM signs a document using a x509 der formatted certificate with a pem formatted key producing a pkcs7 signature. func SignWithX509PEM(doc []byte, x509Cert []byte, pemKey []byte, keyPass string, caCert []byte) ([]byte, error) { var kc KeysAndCerts defer kc.free() //free the C allocated memory kc.password = []byte(keyPass) //set the password to open the encrypted pem private key //add the intermediate CA certificate err := kc.addCA(caCert) if err != nil { return nil, err } //parse the x509 Der to get the certificate err = kc.parseX509Cert(x509Cert) if err != nil { return nil, err } //parse the pem private key err = kc.parsePrivateKeyPem(pemKey) if err != nil { return nil, err } //sign the document return kc.signDoc(doc) } <file_sep>/README.md [![Go Report Card](https://goreportcard.com/badge/github.com/nullboundary/gocertsigner)](https://goreportcard.com/report/github.com/nullboundary/gocertsigner) Name : GoCertSigner Library Author : <NAME>, http://socialhardware.net Date : July 8th 2014 Version : 0.1 Notes : A cgo layer that uses openssl to produce pkcs7 signatures for golang Dependencies: openssl or libressl: libcrypto *** # Function List: ```go //signs a document using a p12 cert producing a pkcs7 signature SignWithP12(doc []byte, pkcs12 []byte, pkcsPass string, caCert []byte) (signature []byte, err error) //signs a document using a x509 der cert with a pem Key producing a pkcs7 signature SignWithX509PEM(doc []byte, x509Cert []byte, pemKey []byte, keyPass string, caCert []byte) (signature []byte, err error) ``` *** # Example: ```go package main import ( s "github.com/nullboundary/gocertsigner" "io/ioutil" "log" ) func main() { //get doc to sign doc, err := ioutil.ReadFile("myfile.txt") if err != nil { log.Printf("error: %s", err) } //your pkcs12 certificate p12, err := ioutil.ReadFile("testCert.p12") if err != nil { log.Printf("error: %s", err) } //your certificate authority cert caCert, err := ioutil.ReadFile("ca.cer") if err != nil { log.Printf("error: %s", err) } //your cert password. Store somewhere safe, not in code. p12pass := "<PASSWORD>" //create the signature signature, err := s.SignWithP12(doc, p12, p12pass, caCert) if err != nil { log.Printf("error: %s", err) } //write out to disk ioutil.WriteFile("Signature", signature, 0644) if err != nil { log.Printf("error: %s", err) } } ```
f1449a43e12b332c1f7db716a224ed72017f0e6a
[ "Markdown", "Go" ]
2
Go
fishgege/gocertsigner
b776af8ada2601bb5ac35b94e56877fd308ec964
32be7e42c3def84861b6328cb9792d24220d55f4
refs/heads/master
<file_sep>package starCompanion; import java.io.File; public class FileCleaner implements Runnable { private File descriptionDirectory = null; private File datasetDirectory = null; private File[] descriptions = null; private File[] statements = null; private String descriptionsPath = null; private String datasetPath = null; private String mysqlPath = null; private String oraclePath = null; public FileCleaner(String descriptionsLocation, String statementsLocation, String mysql, String oracle) { this.descriptionsPath = descriptionsLocation; this.datasetPath = statementsLocation; this.mysqlPath = mysql; this.oraclePath = oracle; } public void cleanDirectories() { datasetDirectory = new File(mysqlPath); statements = datasetDirectory.listFiles(); for (File statement : statements) { if (statement.isFile()) { statement.delete(); } } datasetDirectory = new File(oraclePath); statements = datasetDirectory.listFiles(); for (File statement : statements) { if (statement.isFile()) { statement.delete(); } } datasetDirectory = new File(datasetPath); statements = datasetDirectory.listFiles(); for (File statement : statements) { if (statement.isFile()) { statement.delete(); } } descriptionDirectory = new File(descriptionsPath); descriptions = descriptionDirectory.listFiles(); for (File starDescription : descriptions) { if (starDescription.isFile()) { starDescription.delete(); } } } @Override public void run() { cleanDirectories(); } }
7a390f8f3ba804752fb6acfdb3abbaddc6215b0c
[ "Java" ]
1
Java
fabioelialocatelli/stellarcalculator
3e022d0f6ce19f0292274634fe45ebe73c4c7e70
2d6b5c504b1329419111f604b2a622e13aa537c9
refs/heads/master
<repo_name>vairavan6/spring-mongo<file_sep>/src/main/java/devactivist/service/StartupVersionControlService.java package devactivist.service; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import devactivist.dto.UtilityConstants; import devactivist.entity.VersionControlStatus; import devactivist.repository.interfaces.VersionControlStatusRepo; import lombok.extern.slf4j.Slf4j; @Service @Slf4j public class StartupVersionControlService { @Autowired private VersionControlStatusRepo versionControlStatusRepo; @PostConstruct public void callSVN() { List<String> versionList = new ArrayList<>(); versionList.add(UtilityConstants.AC_GIT); versionList.add(UtilityConstants.AC_SVN40); versionList.add(UtilityConstants.AC_SVN41); VersionControlStatus versionControlStatus = VersionControlStatus.builder() .syncInProgress(true) .lastSyncStartTime(new Date()) .build(); versionList.forEach(vType -> { versionControlStatus.setVersionType(vType); versionControlStatus.setModuleName("CAC"); versionControlStatusRepo.save(versionControlStatus); versionControlStatus.setModuleName("CAM"); versionControlStatusRepo.save(versionControlStatus); versionControlStatus.setModuleName("CBM"); versionControlStatusRepo.save(versionControlStatus); versionControlStatus.setModuleName("CCM"); versionControlStatusRepo.save(versionControlStatus); versionControlStatus.setModuleName("CFM"); versionControlStatusRepo.save(versionControlStatus); }); } } <file_sep>/readme.md 1. Create a token in Jenkins user profile. 2. Generate another token and add in job remote script 3. use the sample url format and send a post request. http://vairavan:114d6a4cf64610ca8a44a5dbe3e371a470@localhost:8080/job/Hello/build?token=11e6ddc79064e9523c5659fe155417f460 username:userapitoken@jenkinspath/xccc/vvvv/?token=job-addedtoken<file_sep>/src/main/java/devactivist/service/GitSyncService.java package devactivist.service; import java.io.File; import java.io.IOException; import java.util.Date; import org.eclipse.jgit.api.FetchCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.MergeResult.MergeStatus; import org.eclipse.jgit.api.PullResult; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.InvalidRemoteException; import org.eclipse.jgit.api.errors.TransportException; import org.eclipse.jgit.transport.FetchResult; import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider; import org.springframework.stereotype.Service; import lombok.extern.slf4j.Slf4j; @Service @Slf4j public class GitSyncService { static String remoteRepo = "https://github.com/vairavan6/devtools.git"; static String localRepo = "H:\\GitProjectTest\\"; static String gitUser = "****"; static String gitPass = "****"; public static void main(String[] args) { try { callGit(); } catch (GitAPIException | IOException e) { e.printStackTrace(); } } public static void callGit() throws InvalidRemoteException, TransportException, GitAPIException, IOException { File gitFilePath = new File(localRepo+".git"); boolean isGitExists = gitFilePath.exists(); UsernamePasswordCredentialsProvider credsProvider = new UsernamePasswordCredentialsProvider(gitUser, gitPass); if(isGitExists) { log.info("------------------------>Git Open "+new Date().toLocaleString()); Git localGit = Git.open(gitFilePath); FetchResult fResult = localGit.fetch().call(); String fetchMessage = fResult.getMessages(); log.info("------------------------>Git Fetch "+new Date().toLocaleString()); PullResult pResult = localGit.pull().setCredentialsProvider(credsProvider).setTimeout(10).call(); String pullMessage = pResult.getFetchResult().getMessages(); log.info("------------------------>Git Pull "+new Date().toLocaleString()); } else { log.info(new Date().toLocaleString()); Git.cloneRepository() .setURI(remoteRepo) .setDirectory(new File(localRepo)) .call(); log.info(new Date().toLocaleString()); } } } <file_sep>/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.foryou.devtools</groupId> <artifactId>spring-mongo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>mongo_java</name> <description>mongo</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>org.springframework.plugin</groupId> <artifactId>spring-plugin-core</artifactId> <version>1.1.0.RELEASE</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>com.taskadapter</groupId> <artifactId>redmine-java-api</artifactId> <version>3.1.2</version> </dependency> <!-- https://github.com/centic9/jgit-cookbook --> <dependency> <groupId>org.eclipse.jgit</groupId> <artifactId>org.eclipse.jgit</artifactId> <version>4.6.0.201612231935-r</version> </dependency> <dependency> <groupId>org.tmatesoft.svnkit</groupId> <artifactId>svnkit</artifactId> <version>1.9.3</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <artifactId>maven-failsafe-plugin</artifactId> <executions> <execution> <goals> <goal>integration-test</goal> <goal>verify</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>/src/main/java/devactivist/repository/interfaces/VersionControlStatusRepo.java package devactivist.repository.interfaces; import org.springframework.data.mongodb.repository.MongoRepository; import devactivist.entity.VersionControlStatus; public interface VersionControlStatusRepo extends MongoRepository<VersionControlStatus, String>{ } <file_sep>/src/main/java/devactivist/development/DevEntity.java package devactivist.development; import lombok.Builder; import lombok.Data; @Data @Builder public class DevEntity { private String fileName; private String framework; private String layoutType; private String layoutPattern; } <file_sep>/src/main/java/devactivist/controller/WorksheetDetailController.java package devactivist.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import devactivist.entity.PasFileHierarchy; import devactivist.service.HierarchyClassifierService; @RestController @CrossOrigin @RequestMapping("worksheet/") public class WorksheetDetailController { @Autowired private HierarchyClassifierService hierarchyService; @GetMapping("save/pas/hiearchy") public void savePasFileHierarchy() { hierarchyService.main(); } @GetMapping("pas/hiearchy") public List<PasFileHierarchy> retrievePasFileHierarchy() { return hierarchyService.getHierarchyData(); } @PostMapping("save/pas/details") public void persistPasInfo() { } @PostMapping("save/suggest/plugin/details") public void persistSuggestPluginData() { } @PostMapping("save/social/plugin/details") public void persistSocialPluginData() { } } <file_sep>/src/main/java/devactivist/Application.java package devactivist; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import devactivist.repository.interfaces.WorksheetPasDetailsRepo; @SpringBootApplication public class Application implements CommandLineRunner{ @Autowired private WorksheetPasDetailsRepo pasDetailsRepo; public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override public void run(String... args) throws Exception { /*List<WorksheetPasDetails> cxv = pasDetailsRepo.findAll(); System.out.println(cxv); List<String> pasFileList = new ArrayList<String>(); pasFileList.add("file1.pas"); pasFileList.add("file2.pas"); pasFileList.add("file3.pas"); List<String> dupFileList = new ArrayList<String>(); dupFileList.add("file1.pas"); dupFileList.add("file2.pas"); dupFileList.add("file3.pas"); WorksheetPasDetails pasDetails = WorksheetPasDetails.builder() .dprName("aciil.dpr") .assignee("developer") .lableader("lead") .commonCount(5) .targetCount(5) .totalCount(15) .duplicateCount(5) .targetPasFiles(pasFileList) .duplicatePasFiles(dupFileList) .build(); // pasDetailsRepo.save(pasDetails); cxv = pasDetailsRepo.findAll(); System.out.println(cxv);*/ } } <file_sep>/src/main/java/devactivist/entity/PasFileHierarchy.java package devactivist.entity; import java.util.List; import org.springframework.data.mongodb.core.mapping.Document; import lombok.Builder; import lombok.Data; @Data @Builder @Document(collection="pas_file_hierarchy") public class PasFileHierarchy { private boolean isChild = false; private boolean isParent; private String parentFile; private String fileName; private List<PasFileHierarchy> childEntry; }
838a8c2c0a692c877b41e84b6dba4c78bb844f1f
[ "Markdown", "Java", "Maven POM" ]
9
Java
vairavan6/spring-mongo
dcbdb34460c776d466161a70637ad9093c2e2cf1
941b95c0f9f536c8384fa54e236290bb51b8563e
refs/heads/master
<repo_name>Arpi15/Exploratory-Data-Analysis-Week-1-Project<file_sep>/Desktop/coursera/Explo_data_assignment1/plot2.R install.packages("dplyr") #installing required packages library(dplyr) epc <- read.table("./household_power_consumption.txt", stringsAsFactors = FALSE, header = TRUE, sep = ";") # reading data FullTimeDate <- strptime(paste(epc$Date, epc$Time, sep=" "), "%d/%m/%Y %H:%M:%S") # combining data and time together epc <- cbind(epc, FullTimeDate) epc$Date <- as.Date(epc$Date, format = "%d/%m/%Y") #converting each class to proper class epc$Time <- format(epc$Time, format = "%H:%M:%S") epc$Global_active_power <- as.numeric(epc$Global_active_power) epc$Global_reactive_power <- as.numeric(epc$Global_reactive_power) epc$Voltage <- as.numeric(epc$Voltage) epc$Global_intensity <- as.numeric(epc$Global_intensity) epc$Sub_metering_1 <- as.numeric(epc$Sub_metering_1) epc$Sub_metering_2 <- as.numeric(epc$Sub_metering_2) epc$Sub_metering_3 <- as.numeric(epc$Sub_metering_3) subsetdata <- subset(epc, Date == "2007-02-01" | Date == "2007-02-02" ) # subsetting data for 2 required days png('plot2.png', width = 480, height = 480) with(subsetdata, plot(FullTimeDate, Global_active_power, type = "l", ylab = "Global Active Power")) dev.off()<file_sep>/Desktop/coursera/Explo_data_assignment1/plot3.R install.packages("dplyr") #installing required packages library(dplyr) epc <- read.table("./household_power_consumption.txt", stringsAsFactors = FALSE, header = TRUE, sep = ";") # reading data FullTimeDate <- strptime(paste(epc$Date, epc$Time, sep=" "), "%d/%m/%Y %H:%M:%S") # combining data and time together epc <- cbind(epc, FullTimeDate) epc$Date <- as.Date(epc$Date, format = "%d/%m/%Y") #converting each class to proper class epc$Time <- format(epc$Time, format = "%H:%M:%S") epc$Global_active_power <- as.numeric(epc$Global_active_power) epc$Global_reactive_power <- as.numeric(epc$Global_reactive_power) epc$Voltage <- as.numeric(epc$Voltage) epc$Global_intensity <- as.numeric(epc$Global_intensity) epc$Sub_metering_1 <- as.numeric(epc$Sub_metering_1) epc$Sub_metering_2 <- as.numeric(epc$Sub_metering_2) epc$Sub_metering_3 <- as.numeric(epc$Sub_metering_3) subsetdata <- subset(epc, Date == "2007-02-01" | Date == "2007-02-02" ) # subsetting data for 2 required days png('plot3.png', width = 480, height = 480) # plotting data with(subsetdata, plot(FullTimeDate, Sub_metering_1, type = "l",xlab = "Day", ylab = "Energy sub metering")) lines(subsetdata$FullTimeDate, subsetdata$Sub_metering_2, type = "l", col = "red") lines(subsetdata$FullTimeDate, subsetdata$Sub_metering_3, type = "l", col = "blue") legend(c("topright"), c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), lty = 1, lwd = 2, col = c("black", "red", "blue")) dev.off()<file_sep>/Desktop/coursera/Explo_data_assignment1/plot1.R install.packages("dplyr") #installing required packages library(dplyr) epc <- read.table("./household_power_consumption.txt", stringsAsFactors = FALSE, header = TRUE, sep = ";") # reading data epc$Date <- as.Date(epc$Date, format = "%d/%m/%Y") #converting to proper class epc$Time <- format(epc$Time, format = "%H:%M:%S") epc$Global_active_power <- as.numeric(epc$Global_active_power) epc$Global_reactive_power <- as.numeric(epc$Global_reactive_power) epc$Voltage <- as.numeric(epc$Voltage) epc$Global_intensity <- as.numeric(epc$Global_intensity) epc$Sub_metering_1 <- as.numeric(epc$Sub_metering_1) epc$Sub_metering_2 <- as.numeric(epc$Sub_metering_2) epc$Sub_metering_3 <- as.numeric(epc$Sub_metering_3) subsetdata <- subset(epc, Date == "2007-02-01" | Date == "2007-02-02" ) # subsetting data for 2 required days png('plot1.png', width = 480, height = 480) # plotting data hist(subsetdata$Global_active_power, col="red", border="black", main ="Global Active Power", xlab="Global Active Power (kilowatts)", ylab="Frequency") #plotting the histogram dev.off()
c4aa51a7d3d55c2c1769c4ea885822a3bdecfb35
[ "R" ]
3
R
Arpi15/Exploratory-Data-Analysis-Week-1-Project
50f252363e40b659d3b3e08f6f5a9c9196ecce70
b1f175872e40be3dd9e7824cbf749c1698fa8f9a
refs/heads/master
<repo_name>place222/test<file_sep>/App/js/services.js /** * Created by Administrator on 2016/4/22. */ var testServices = angular.module('testServices',[]); testServices.service('menuService',function($http){ this.getMenus = function(url){ $http.get(url).success(function(response){ return response.data; }); } }); <file_sep>/test.js /* * 模仿一个JQuery * */ var lQuery = lQuery||{}; /* * 第一个模块 * */ (function(lQuery){ lQuery.dropDown = function(){ function init(){ var li = document.querySelectorAll('[data-toggle="dropdown"]'); console.log(li); for(var i=0;i<li.length;i++){ (function(i){ li[i].addEventListener('mouseover',function(){ this.className += ' open'; this.className += ' site-nav-dropdown'; }); li[i].addEventListener('mouseout',function(){ this.className = this.className.replace(' open',''); this.className = this.className.replace(' site-nav-dropdown',''); }); })(i); } } return { Init: init } }; })(lQuery); /* * 第二个菜单的hover * */ (function(lQuery){ lQuery.cateHover = function(){ function init(){ var cateList = document.querySelectorAll('.cate ul li'); var siderBar = document.querySelector('.sidebar'); for(var i=0; i <cateList.length;i++){ (function(i){ cateList[i].addEventListener('mouseover',function(){ this.style.backgroundColor = '#fff'; siderBar.querySelector('.panel-'+i).style.display = 'block'; }); //cateList[i].addEventListener('mouseout',function(event){ // this.style.backgroundColor = '#aaa'; // //siderBar.querySelector('.panel-'+i).style.display = 'none'; //}); })(i); } var panel = document.querySelector('.panel-0'); panel.addEventListener('mouseout',function(event){ if(event.target == this){ console.log(event.target); this.style.display = 'none'; }else{ console.log("不是自己"); } }); } return { Init:init } } })(lQuery); window.onload = function(){ lQuery.dropDown().Init(); //lQuery.cateHover().Init(); };
30682228eba2c0ea91c4cba72e8edb81274f72b3
[ "JavaScript" ]
2
JavaScript
place222/test
71845ae4f8873447e9796f130d14571f6c5f0020
a3dfe381d4a5e2ecf227a9a0c0efe382838c543a
refs/heads/master
<repo_name>pavelsust/Android-Architecture-Components-Example<file_sep>/app/src/main/java/com/madina/androidarchitecturalexample/viewmodel/color/ColorChangeViewModel.kt package com.madina.androidarchitecturalexample.viewmodel.color import android.graphics.Color import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import java.util.* class ColorChangeViewModel : ViewModel(){ val colorResource = MutableLiveData<Int>() init { colorResource.value = 0xfff } fun addColor(){ val rnd = Random() colorResource.value= Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)) } }<file_sep>/app/src/main/java/com/madina/androidarchitecturalexample/viewmodel/ViewModelActivity.kt package com.madina.androidarchitecturalexample.viewmodel import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProviders import com.madina.androidarchitecturalexample.R import com.madina.androidarchitecturalexample.viewmodel.model.ClickViewModel import com.madina.androidarchitecturalexample.viewmodel.model.CustomViewModelFactory import kotlinx.android.synthetic.main.activity_view_model.* import kotlinx.android.synthetic.main.content_view_model.* class ViewModelActivity : AppCompatActivity() { var number: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_view_model) setSupportActionBar(toolbar) var viewModel = ViewModelProviders.of(this@ViewModelActivity, CustomViewModelFactory(1)).get(ClickViewModel::class.java) click_count_text.text = "" + viewModel?.number increment_button.setOnClickListener { number = viewModel?.number + 1 viewModel?.number = number click_count_text.text = "" + number } } } <file_sep>/settings.gradle include ':app' rootProject.name='AndroidArchitecturalExample' <file_sep>/app/src/main/java/com/madina/androidarchitecturalexample/viewmodel/addremove/data/DataAddExampleActivity.kt package com.madina.androidarchitecturalexample.viewmodel.addremove.data import android.app.ProgressDialog import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import com.madina.androidarchitecturalexample.R import com.madina.androidarchitecturalexample.viewmodel.addremove.data.adapter.MyAdapter import com.madina.androidarchitecturalexample.viewmodel.addremove.data.model.NicePlace import com.madina.androidarchitecturalexample.viewmodel.addremove.data.viewmodel.MainViewModel import kotlinx.android.synthetic.main.activity_data_add_example.* import kotlinx.android.synthetic.main.activity_my_data.* class DataAddExampleActivity : AppCompatActivity() , MyAdapter.onClickCallBack { var mainViewModel: MainViewModel? = null var linearLayoutManager: LinearLayoutManager? = null var myAdapter: MyAdapter? = null var progressDialog: ProgressDialog? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_data_add_example) linearLayoutManager = LinearLayoutManager(applicationContext) recycleview.layoutManager = linearLayoutManager progressDialog = ProgressDialog(this@DataAddExampleActivity) progressDialog?.setTitle("Loading....") mainViewModel = ViewModelProviders.of(this@DataAddExampleActivity).get(MainViewModel::class.java) mainViewModel?.init() mainViewModel?.getNicePlaces()?.observe(this@DataAddExampleActivity, object : Observer<List<NicePlace>> { override fun onChanged(item: List<NicePlace>?) { myAdapter?.notifyDataSetChanged() } }) mainViewModel?.getIsLoading()?.observe(this@DataAddExampleActivity, object : Observer<Boolean> { override fun onChanged(t: Boolean?) { if (t!!) { progressDialog?.show() } else { progressDialog?.dismiss() } } }) fab_add.setOnClickListener { mainViewModel?.addNewValue(NicePlace("test title ", "test address")) } initAdapter() } fun initAdapter() { myAdapter = MyAdapter(this, mainViewModel?.getNicePlaces()?.value!!) recycleview.adapter = myAdapter } override fun onClickItem(position: Int) { mainViewModel?.removeItem(position) } } <file_sep>/app/src/main/java/com/madina/androidarchitecturalexample/viewmodel/database/MyDataActivity.kt package com.madina.androidarchitecturalexample.viewmodel.database import android.content.DialogInterface import android.os.Bundle import android.widget.EditText import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import com.madina.androidarchitecturalexample.R import kotlinx.android.synthetic.main.activity_my_data.* import kotlinx.android.synthetic.main.content_my_data.* import java.util.* class MyDataActivity : AppCompatActivity() { var favouriteAdapter: FavouriteAdapter?=null var favouritesViewModel:FavouritesViewModel?=null val mFav: List<Favourites>? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_my_data) setSupportActionBar(toolbar) recyclerView.layoutManager = LinearLayoutManager(applicationContext) favouritesViewModel = ViewModelProviders.of(this@MyDataActivity).get(FavouritesViewModel::class.java) favouritesViewModel?.mFavs?.observe(this@MyDataActivity, object : Observer<List<Favourites>>{ override fun onChanged(it: List<Favourites>?) { favouriteAdapter = FavouriteAdapter(applicationContext , it!! , favouritesViewModel!!) recyclerView.adapter = favouriteAdapter } }) fab.setOnClickListener { var mUrl = EditText(this@MyDataActivity) var dialog = AlertDialog.Builder(this@MyDataActivity).setTitle("New Favourite") .setMessage("Add a url link below") .setView(mUrl) .setPositiveButton("Add" , object : DialogInterface.OnClickListener{ override fun onClick(dialog: DialogInterface?, which: Int) { var url = ""+mUrl.text.toString() val date = Date().time favouritesViewModel?.addFav(url, date) dialog?.dismiss() } }).setNegativeButton("Cancel" , null) .create() dialog.show() } } } <file_sep>/app/src/main/java/com/madina/androidarchitecturalexample/viewmodel/database/FavouritesViewModel.kt package com.madina.androidarchitecturalexample.viewmodel.database import android.app.Application import android.content.ContentValues import android.database.sqlite.SQLiteDatabase import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData class FavouritesViewModel(application: Application) : AndroidViewModel(application) { var mFavHelper: FavouritesDBHelper? = null var mFavs: MutableLiveData<List<Favourites>>? = null init { mFavHelper = FavouritesDBHelper(application) } fun getFavs(): MutableLiveData<List<Favourites>> { if (mFavs == null) { mFavs = MutableLiveData() loadLivedata() } return mFavs!! } private fun loadLivedata() { var newFavs = ArrayList<Favourites>() val db = mFavHelper?.readableDatabase val cursor = db?.query(DbSettings.DBEntry.TABLE, arrayOf(DBEntry._ID, DbSettings.DBEntry.COL_FAV_URL, DbSettings.DBEntry.COL_FAV_DATE), null, null, null, null, null) while (cursor?.moveToNext()!!) { val idxId = cursor.getColumnIndex(DBEntry._ID) val idxUrl = cursor.getColumnIndex(DBEntry.COL_FAV_URL) val idxDate = cursor.getColumnIndex(DBEntry.COL_FAV_DATE) newFavs.add(Favourites(cursor.getLong(idxId), cursor.getString(idxUrl), cursor.getLong(idxDate))) } cursor.close() db.close() mFavs?.value = newFavs } fun addFav(url:String , date: Long){ var db = mFavHelper?.writableDatabase var values = ContentValues() values.put(DBEntry.COL_FAV_URL , url) values.put(DBEntry.COL_FAV_DATE , date) var id = db?.insertWithOnConflict(DBEntry.TABLE , null , values , SQLiteDatabase.CONFLICT_REPLACE) db?.close() var favourites: List<Favourites> = mFavs?.value!! var clonedFavs : ArrayList<Favourites> if (favourites==null){ clonedFavs = ArrayList() }else{ clonedFavs = ArrayList(favourites.size) for (i in favourites.indices){ clonedFavs.add(Favourites(favourites[i])) } } var fav = Favourites(id!! , url , date) clonedFavs.add(fav) mFavs?.value = clonedFavs } fun removeFav(id : Long){ var db = mFavHelper?.writableDatabase db?.delete(DBEntry.TABLE , DBEntry._ID + " = ?" , arrayOf(id.toString())) db?.close() val favourite = mFavs?.value val clonedFavourite : ArrayList<Favourites> = ArrayList(favourite!!.size) for (i in favourite.indices){ clonedFavourite.add(Favourites(favourite[i])) } var index: Int = -1 for (i in favourite.indices){ var favourite = clonedFavourite.get(i) if (favourite.mID == id){ index = i } } if (index!=-1){ clonedFavourite.removeAt(index) } mFavs?.value = clonedFavourite } }<file_sep>/app/src/main/java/com/madina/androidarchitecturalexample/viewmodel/model/ClickViewModel.kt package com.madina.androidarchitecturalexample.viewmodel.model import androidx.lifecycle.ViewModel data class ClickViewModel(var number: Int) : ViewModel()<file_sep>/app/src/main/java/com/madina/androidarchitecturalexample/viewmodel/addremove/data/adapter/MyAdapter.kt package com.madina.androidarchitecturalexample.viewmodel.addremove.data.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.madina.androidarchitecturalexample.R import com.madina.androidarchitecturalexample.viewmodel.addremove.data.model.NicePlace import kotlinx.android.synthetic.main.item_data_layout.view.* class MyAdapter(var onClick: onClickCallBack ,var dataList: List<NicePlace>) : RecyclerView.Adapter<MyAdapter.CustomViewModel>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewModel { var view = LayoutInflater.from(parent.context).inflate(R.layout.item_data_layout , parent , false) return CustomViewModel(view) } override fun getItemCount(): Int { return dataList.size } override fun onBindViewHolder(holder: CustomViewModel, position: Int) { var myData = dataList.get(position) holder.name.text = myData.title holder.address.text = myData.imageUrl holder.view.setOnClickListener { onClick.onClickItem(holder.adapterPosition) } } inner class CustomViewModel(view :View): RecyclerView.ViewHolder(view) { var name = view.text_name var address = view.text_address var view = view } interface onClickCallBack{ fun onClickItem(position: Int) } }<file_sep>/app/src/main/java/com/madina/androidarchitecturalexample/viewmodel/addremove/data/repositry/NicePlaceRepositry.kt package com.madina.androidarchitecturalexample.viewmodel.addremove.data.repositry import android.util.Log import androidx.lifecycle.MutableLiveData import com.madina.androidarchitecturalexample.viewmodel.addremove.data.model.NicePlace object NicePlaceRepositry { var dataset: MutableList<NicePlace> = ArrayList() fun getNicePlaces(): MutableLiveData<List<NicePlace>>{ setNicePlaces() var data: MutableLiveData<List<NicePlace>> = MutableLiveData() data.value = dataset return data } private fun setNicePlaces(){ dataset.add(NicePlace("pavel" , "demra")) dataset.add(NicePlace("Robin" , "demra")) dataset.add(NicePlace("Lia" , "demra")) } fun addNewValue(nicePlace: NicePlace){ dataset.add(nicePlace) Log.d("DATA_CHANGE" , ""+ dataset.toString()) } fun removeItem(position: Int){ if (dataset.size>0){ dataset.removeAt(position) } } }<file_sep>/app/src/main/java/com/madina/androidarchitecturalexample/viewmodel/database/FavouriteAdapter.kt package com.madina.androidarchitecturalexample.viewmodel.database import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.madina.androidarchitecturalexample.R import kotlinx.android.synthetic.main.list_item_row.view.* import java.util.* class FavouriteAdapter(context: Context , val favouriteList: List<Favourites> ,val favouritesViewModel: FavouritesViewModel) : RecyclerView.Adapter<FavouriteAdapter.FavouriteHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FavouriteHolder { var view = LayoutInflater.from(parent.context).inflate(R.layout.list_item_row , parent, false) return FavouriteHolder(view) } override fun getItemCount(): Int { return favouriteList.size } override fun onBindViewHolder(holder: FavouriteHolder, position: Int) { var favourite = favouriteList.get(position) holder.textUrl.text = favourite.mUrl holder.textDate.setText(( Date(favourite.mDate).toString())); } inner class FavouriteHolder(view: View) : RecyclerView.ViewHolder(view) { val textUrl = view.tvUrl val textDate = view.tvDate val imageButton = view.btnDelete init { imageButton.setOnClickListener { var favourite = favouriteList.get(adapterPosition) favouritesViewModel.removeFav(favourite.mID) } } } } <file_sep>/app/src/main/java/com/madina/androidarchitecturalexample/viewmodel/model/CustomViewModelFactory.kt package com.madina.androidarchitecturalexample.viewmodel.model import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider class CustomViewModelFactory(var number: Int) : ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return ClickViewModel(number) as T } }<file_sep>/app/src/main/java/com/madina/androidarchitecturalexample/viewmodel/addremove/data/model/NicePlace.kt package com.madina.androidarchitecturalexample.viewmodel.addremove.data.model class NicePlace(var title:String , var imageUrl:String){ override fun toString(): String { return "title: $title , address: $imageUrl" } }<file_sep>/app/src/main/java/com/madina/androidarchitecturalexample/viewmodel/database/Favourites.kt package com.madina.androidarchitecturalexample.viewmodel.database class Favourites { var mID: Long = 0 var mUrl: String var mDate: Long = 0 constructor(id: Long, mUrl: String, mDate: Long) { this.mID = id this.mUrl = mUrl this.mDate = mDate } constructor(favourites: Favourites) { mID = favourites.mID mUrl = favourites.mUrl mDate = favourites.mDate } }<file_sep>/app/src/main/java/com/madina/androidarchitecturalexample/viewmodel/addremove/data/viewmodel/MainViewModel.kt package com.madina.androidarchitecturalexample.viewmodel.addremove.data.viewmodel import android.os.Handler import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.madina.androidarchitecturalexample.viewmodel.addremove.data.model.NicePlace import com.madina.androidarchitecturalexample.viewmodel.addremove.data.repositry.NicePlaceRepositry class MainViewModel : ViewModel() { private var nicePlace : MutableLiveData<List<NicePlace>>?=null private var isUpdeting: MutableLiveData<Boolean>?=null fun init(){ isUpdeting = MutableLiveData() nicePlace = NicePlaceRepositry.getNicePlaces() } fun getNicePlaces(): LiveData<List<NicePlace>>{ return nicePlace!! } fun getIsLoading(): MutableLiveData<Boolean>{ return isUpdeting!! } fun addNewValue(nice: NicePlace){ isUpdeting?.value = true var handeler = Handler() handeler.postDelayed({ NicePlaceRepositry.addNewValue(nice) nicePlace?.postValue(NicePlaceRepositry.dataset) isUpdeting?.postValue(false) }, 1000) } fun removeItem( position : Int){ isUpdeting?.value = true NicePlaceRepositry.removeItem(position) nicePlace?.postValue(NicePlaceRepositry.dataset) isUpdeting?.postValue(false) } }<file_sep>/app/src/main/java/com/madina/androidarchitecturalexample/viewmodel/database/DbSettings.kt package com.madina.androidarchitecturalexample.viewmodel.database import android.provider.BaseColumns class DbSettings { class DBEntry : BaseColumns { companion object { val TABLE = "fav" val COL_FAV_URL = "url" val COL_FAV_DATE = "date" } } companion object { val DB_NAME = "favourites.db" val DB_VERSION = 1 } }<file_sep>/app/src/main/java/com/madina/androidarchitecturalexample/viewmodel/color/ColorViewModelActivity.kt package com.madina.androidarchitecturalexample.viewmodel.color import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.madina.androidarchitecturalexample.R import kotlinx.android.synthetic.main.activity_color_view_model.* import java.util.* class ColorViewModelActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_color_view_model) val colorChangeViewModel = ViewModelProviders.of(this@ColorViewModelActivity).get(ColorChangeViewModel::class.java) colorChangeViewModel.colorResource.observe(this, object: Observer<Int> { override fun onChanged(t: Int?) { background_layout.setBackgroundColor(t!!) } }) change_color.setOnClickListener { colorChangeViewModel.addColor() } } } <file_sep>/app/src/main/java/com/madina/androidarchitecturalexample/viewmodel/database/FavouritesDBHelper.kt package com.madina.androidarchitecturalexample.viewmodel.database import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper class FavouritesDBHelper(context: Context) : SQLiteOpenHelper(context , DbSettings.DB_NAME , null , DbSettings.DB_VERSION) { override fun onCreate(db: SQLiteDatabase?) { val createTable = "CREATE TABLE " + DbSettings.DBEntry.TABLE + " ( " + DBEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + DBEntry.COL_FAV_URL + " TEXT NOT NULL, " + DBEntry.COL_FAV_DATE + " INTEGER NOT NULL);" db?.execSQL(createTable) } override fun onUpgrade(p0: SQLiteDatabase?, p1: Int, p2: Int) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }<file_sep>/app/src/main/java/com/madina/androidarchitecturalexample/HomeActivity.kt package com.madina.androidarchitecturalexample import android.content.Intent import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import com.madina.androidarchitecturalexample.viewmodel.ViewModelActivity import com.madina.androidarchitecturalexample.viewmodel.addremove.data.DataAddExampleActivity import com.madina.androidarchitecturalexample.viewmodel.color.ColorViewModelActivity import com.madina.androidarchitecturalexample.viewmodel.database.MyDataActivity import kotlinx.android.synthetic.main.activity_home.* class HomeActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) setSupportActionBar(toolbar) } fun openViewModel(view: View){ openNewActivity(ViewModelActivity::class.java) } fun openColorViewModel(view: View){ openNewActivity(ColorViewModelActivity::class.java) } fun openDbActivity(view: View){ openNewActivity(MyDataActivity::class.java) } fun openAddRemoveData(view:View){ openNewActivity(DataAddExampleActivity::class.java) } fun <T> openNewActivity(it : Class<T>) = Intent().apply { startActivity(Intent(this@HomeActivity , it)) } } <file_sep>/app/src/main/java/com/madina/androidarchitecturalexample/viewmodel/database/DBEntry.kt package com.madina.androidarchitecturalexample.viewmodel.database import android.provider.BaseColumns class DBEntry : BaseColumns { companion object { val TABLE = "fav" val COL_FAV_URL = "url" val COL_FAV_DATE = "date" val _ID = "_id" } }
56a879aa737c2479df639cfe0e467c8cf397c7a8
[ "Kotlin", "Gradle" ]
19
Kotlin
pavelsust/Android-Architecture-Components-Example
e397383c3fd1dad90d316b5b6030f782de6e3d81
63ad9a7033bff8580ad1ab36e755c495c62ffeba