branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>var PeerServer = require('peer').PeerServer; var port = process.env.PORT || 5000 var server = new PeerServer({port: port}); console.log("----- Server port:" + port);
794476ebf038579a3d15542c10ebce5c92ae7d46
[ "JavaScript" ]
1
JavaScript
DadaMonad/peerjs_heroku
1b5b6945e504ed6efb1231f86b2da499278122d8
f352630640a17141548b166a780a2ea8c8cd7574
refs/heads/master
<repo_name>BojianHou/pytorch-demos<file_sep>/visor/README.md # visor `python visor.py categories.txt -i 0`<file_sep>/visor/visor.py #! /usr/local/bin/python3 import sys import os import time import cv2 # install cv3, python3: http://seeb0h.github.io/howto/howto-install-homebrew-python-opencv-osx-el-capitan/ # add to profile: export PYTHONPATH=$PYTHONPATH:/usr/local/Cellar/opencv3/3.2.0/lib/python3.6/site-packages/ import numpy as np import argparse import torch import torch.nn as nn import torchvision.models as models import torchvision.transforms as transforms def define_and_parse_args(): # argument Checking parser = argparse.ArgumentParser(description="Visor Demo") # parser.add_argument('network', help='CNN model file') parser.add_argument('categories', help='text file with categories') parser.add_argument('-i', '--input', type=int, default='0', help='camera device index or file name, default 0') parser.add_argument('-s', '--size', type=int, default=224, help='network input size') # parser.add_argument('-S', '--stat', help='stat.txt file') return parser.parse_args() def cat_file(): # load classes file categories = [] if hasattr(args, 'categories') and args.categories: try: f = open(args.categories, 'r') for line in f: cat = line.split(',')[0].split('\n')[0] if cat != 'classes': categories.append(cat) f.close() print('Number of categories:', len(categories)) except: print('Error opening file ' + args.categories) quit() return categories print("Visor demo e-Lab") xres = 640 yres = 480 args = define_and_parse_args() categories = cat_file() # load category file font = cv2.FONT_HERSHEY_SIMPLEX # setup camera input: cam = cv2.VideoCapture(args.input) cam.set(3, xres) cam.set(4, yres) # load CNN model: # model = torch.load(args.network) model = models.resnet18(pretrained=True) model.eval() # print model softMax = nn.Softmax() # to get probabilities out of CNN # image pre-processing functions: transformsImage = transforms.Compose([ # transforms.ToPILImage(), # transforms.Scale(256), # transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) # needed for pythorch ZOO models on ImageNet (stats) ]) while True: startt = time.time() ret, frame = cam.read() if not ret: break if xres > yres: frame = frame[:,int((xres - yres)/2):int((xres+yres)/2),:] else: frame = frame[int((yres - xres)/2):int((yres+xres)/2),:,:] pframe = cv2.resize(frame, dsize=(args.size, args.size)) # prepare and normalize frame for processing: pframe = np.swapaxes(pframe, 0, 2) pframe = np.expand_dims(pframe, axis=0) pframe = transformsImage(pframe) pframe = torch.autograd.Variable(pframe) # turn Tensor to variable required for pytorch processing # process via CNN model: output = model(pframe) if output is None: print('no output from CNN model file') break output = softMax(output) # convert CNN output to probabilities output = output.data.numpy()[0] # get data from pytorch Variable, [0] = get vector from array # process output and print results: order = output.argsort() last = len(categories)-1 text = '' for i in range(min(5, last+1)): text += categories[order[last-i]] + ' (' + '{0:.2f}'.format(output[order[last-i]]*100) + '%) ' # overlay on GUI frame cv2.putText(frame, text, (10, yres-20), font, 0.5, (255, 255, 255), 1) cv2.imshow('win', frame) endt = time.time() # sys.stdout.write("\r"+text+"fps: "+'{0:.2f}'.format(1/(endt-startt))) # text output sys.stdout.write("\rfps: "+'{0:.2f}'.format(1/(endt-startt))) sys.stdout.flush() if cv2.waitKey(1) == 27: # ESC to stop break # end program: cam.release() cv2.destroyAllWindows()
d97dbf751bf6c3e8484f6bb269044753d941dfbf
[ "Markdown", "Python" ]
2
Markdown
BojianHou/pytorch-demos
512a03708d88e66a51aa7e76581799b2c7b2bd62
8886c29556ee3e265daafc215b3251c9647f87d8
refs/heads/master
<repo_name>KarimM7mad/ML_EEG<file_sep>/NEW different Time Windows DIFFERENT PCAs/toRun2.sh #!/bin/bash for (( COUNTER=180; COUNTER>0; COUNTER-=12 )); do echo $COUNTER python NEWallElectrodesDiffmsTraining.py $COUNTER > "NEWresultsOF_${COUNTER}_ColperElectrodeAllPCAs.txt" done <file_sep>/tgrobaFile.py import numpy as np import pandas as pd np.set_printoptions(threshold=np.inf, linewidth=30000) #File to try different pieces of codes and techniques # # subjectsNames = ["VPae", "VPbad", "VPbax", "VPbba", "VPdx", "VPgaa", "VPgab", "VPgac", "VPgae", "VPgag", "VPgah", "VPgal", "VPgam", "VPih", "VPii", "VPja", "VPsaj", "VPsal"] subjectsNames = ["Fatema.csv"] # # # # # # df = pd.read_csv("dataset/" + subjectsNames[0]) # for i in range(len(df.columns)): print(df.columns[i]) print(df.shape) # # df = df.drop(columns=['y']) # # print("=========================================================") # # numberOfElectrodes = 60 # # finissh = 280 # # nColToKeep = 200 # # # for nColToKeep in range(280, finissh-20, -20): # for i in range(1, numberOfElectrodes): # df = df.drop(df.columns[(i * nColToKeep):( (i * nColToKeep) + (300 - nColToKeep) )], axis=1) # print("=========================================================") # print(df.shape) # # for x in range(len(df.columns)): # print(df.columns[x]) # x = int(sys.argv[1]) # # print(type(x)) # # print("sys.argv[1] enetered is |"+str(x)+"|") # nColToKeep = 60 # for i in range(1, numberOfElectrodes): # df = df.drop(df.columns[(i * nColToKeep):(280 + (i - 1) * nColToKeep)], axis=1) # print("=========================================================") # for i in range(len(df.columns)): # print(df.columns[i]) # print(df.shape) #x = np.loadtxt("arraykda.txt") #print(x) #print("=============") #print(x[:, 2]) # for fileIndex in range(len(subjectsNames)): # print("file " + subjectsNames[fileIndex] + " shape is " + str(pd.read_csv("dataset/" + subjectsNames[fileIndex]+".csv").shape)) # LRwithPCA = np.zeros(shape=(4, 3, 3), dtype=int) # # LRwithPCA[0, 0] = [100, 2, 3] # LRwithPCA[0, 1] = [200, 8, 9] # LRwithPCA[0, 2] = [300, 5, 6] # # LRwithPCA[1, 0] = [100, 12, 13] # LRwithPCA[1, 1] = [200, 15, 16] # LRwithPCA[1, 2] = [300, 18, 19] # # LRwithPCA[2, 0] = [100, 22, 23] # LRwithPCA[2, 1] = [200, 25, 26] # LRwithPCA[2, 2] = [300, 28, 29] # # LRwithPCA[3, 0] = [100, 32, 33] # LRwithPCA[3, 1] = [200, 35, 36] # LRwithPCA[3, 2] = [300, 38, 39] # # print("================") # print("Original Matrix") # print(LRwithPCA) # # print("================") # print("matrix Transpose") # x = LRwithPCA # print(x) # print("================") # print("OPS") # xx = np.max(x, axis=1) # print(xx) # # # # # print("================") # print("mean of all row") # x = x.mean(axis=0, keepdims=True) # print(x) # print("================") # print("mean of all col") # x = LRwithPCA.mean(axis=1, keepdims=True) # print(x) # print("================") # print("mean of all elements In a col") # x = LRwithPCA.mean(axis=2, keepdims=True) # print(x) # print("================") # print("mean of all elements in the first row , first col") # x = LRwithPCA.mean(axis=(2,1,0), keepdims=True) # print(x) # # x = -10 # # # for x in range(x, 10): # print(x) # print("-----------------------") # print(x) # # # for x in range(x,0,-1): # print(x) # # print("-----------------------") # print(x) <file_sep>/toRun.sh #!/usr/bin/env bash python negANDposConcat.py Fatemaneg.csv Fatemapos.csv Fatema.csv python negANDposConcat.py Hesham2neg.csv Hesham2pos.csv Hesham2.csv python negANDposConcat.py Heshamneg.csv Heshampos.csv Hesham.csv python negANDposConcat.py MohamedelTairneg.csv MohamedelTairpos.csv MohamedelTair.csv python negANDposConcat.py Mohamed\ Wagihneg.csv Mohamed\ Wagihpos.csv Mohamed\ Wagih.csv python negANDposConcat.py Tair2neg.csv Tair2pos.csv Tair2.csv python negANDposConcat.py Wagih2neg.csv Wagih2pos.csv Wagih2.csv python negANDposConcat.py Yousefneg.csv Yousefpos.csv Yousef.csv
feae3a6f3153b5a434aeb3b10c12e82a2f606308
[ "Python", "Shell" ]
3
Shell
KarimM7mad/ML_EEG
073acc93943cb65b9257413fbe0a28f71d35f816
38df08d1cc7fea34b724534711188d689575b2ea
refs/heads/master
<repo_name>CarlKarlQarl/ruby-objects-has-many-lab-denver-web-111819<file_sep>/lib/environment.rb require_relative "./song" require_relative "./artist" require "pry" adele = Artist.new "Adele" hello = Song.new "Hello" hello.artist = adele binding.pry 0
eec671a28ea47c90b344fc0c655e87858903bb4a
[ "Ruby" ]
1
Ruby
CarlKarlQarl/ruby-objects-has-many-lab-denver-web-111819
7ea2f8bf3d5392dad380aba04eaa4b9c0001a4a8
0bcf13d81d8b2e8858d3b7281f191b955ea5c36c
refs/heads/master
<repo_name>JainamJhaveri/Bottle-Compiler<file_sep>/run.sh lex lex.l yacc -d parse.y gcc lex.yy.c y.tab.c -lfl cat test.txt | ./a.out <file_sep>/symtab.h typedef struct { char NAME[80]; int value; } table;
712af39f34a2787381b8341a253c60b13d5c07e1
[ "C", "Shell" ]
2
Shell
JainamJhaveri/Bottle-Compiler
951b4560a7550bebf4d66cdc221e51905fe9caa6
e2982586973cb4e7d72e1c9697ed7d88fd2f9096
refs/heads/master
<repo_name>ajinzrathod/googleLogin<file_sep>/login.php <?php require_once('head.php'); require_once('google-signin.php'); require_once 'vendor/autoload.php'; require_once('verifyGoogleUser.php'); # ----- Get Sub Functios Starts ----- function getSub($payload, $CLIENT_ID){ $sub = $payload['sub']; return $sub; } # ----- Get Sub Function Ends ----- # Get ID Token from post getIdToken(); // $CLIENT_ID is specified in `google-signin.php` $client = new Google_Client(['client_id' => $CLIENT_ID]); // Specify the CLIENT_ID of the app that accesses the backend $payload = $client->verifyIdToken($id_token); // Verifying ID Token verifyIdToken($payload); // Verifing the integrity of the ID token verifyingIntegrityOfIdToken($payload, $CLIENT_ID); // Getting SUB $sub = getSub($payload, $CLIENT_ID); echo $sub; ?> <file_sep>/signout.php <?php require_once('head.php'); require_once('google-signin.php'); ?> <!-- This button is just for loading auth2, thats why it is hidden --> <div class="g-signin2" data-onsuccess="onSignIn" style="display: none;"></div> <a href="#" id="signOut" onclick="signOut();">Sign out</a> <script> function signOut() { var auth2 = gapi.auth2.getAuthInstance(); auth2.signOut().then(function () { console.log('User signed out.'); }); } </script>
e8076ad7644ed9e77fbbbb8cf98fed17e2b11e5b
[ "PHP" ]
2
PHP
ajinzrathod/googleLogin
c48affee936ffe36b732e9304c7142264514e8ec
7b8b4812675edaa3b0a94d6bce3fbebb4ac2761c
refs/heads/master
<file_sep>#!/bin/bash echo "/nDelete Existing Tables.." aws dynamodb delete-table --table-name Users --endpoint-url http://localhost:8000 --profile local echo "\n\n Creating new tables now" aws dynamodb create-table --endpoint-url http://localhost:8000 --profile local --cli-input-json file://user_table_creation.json echo "Inserting Dummy Records.." aws dynamodb put-item --table-name Users --item file://user_table_data.json --endpoint-url http://localhost:8000 --profile local echo "Writing Item in Batch" aws dynamodb batch-write-item --request-items file://user_data.json --endpoint-url http://localhost:8000 --profile local echo "/n/n Done .!!"
d0fbfb77463cb8616198093b1be981347e0ce68e
[ "Shell" ]
1
Shell
shred22/dynamodb_ops
e182509e3c04cf6fc57e2386e26ab24a6ffd331e
cfe39978a3d9d1c7a2ad254137ee770d1c38883b
refs/heads/master
<repo_name>RohKumar/VicRoadCodingTest<file_sep>/Nasa.MarsRover/LandingSurface/Coordinate.cs namespace Nasa.MarsRover.LandingSurface { public struct Coordinate { public int X; public int Y; public Coordinate(int anX, int aY) { X = anX; Y = aY; } } } <file_sep>/Nasa.MarsRover/Command/LandingSurfaceSizeCommand.cs using Nasa.MarsRover.LandingSurface; namespace Nasa.MarsRover.Command { public class LandingSurfaceSizeCommand : ISurfaceSizeCommand { public Dimension Dimension { get; private set; } private ISurface landingSurface; public LandingSurfaceSizeCommand(Dimension aSize) { Dimension = aSize; } public CommandType GetCommandType() { return CommandType.LandingSurfaceSizeCommand; } public void Execute() { landingSurface.SetSize(Dimension); } public void SetReceiver(ISurface aLandingSurface) { landingSurface = aLandingSurface; } } } <file_sep>/Nasa.MarsRover/ICommandCenter.cs using Nasa.MarsRover.LandingSurface; namespace Nasa.MarsRover { public interface ICommandMain { void Execute(string commandString); ISurface GetLandingSurface(); string GetCombinedRoverReport(); } } <file_sep>/Nasa.MarsRover/Rovers/IRover.cs using System.Collections.Generic; using Nasa.MarsRover.LandingSurface; namespace Nasa.MarsRover.Rovers { public interface IRover { Coordinate Position { get; set; } CardinalDirection CardinalDirection { get; set; } void Deploy(ISurface aLandingSurface, Coordinate aCoordinate, CardinalDirection aDirection); void Move(IEnumerable<Direction> Directions); bool IsDeployed(); } }<file_sep>/Nasa.MarsRover/Command/IRoverExploreCommand.cs using System.Collections.Generic; using Nasa.MarsRover.Rovers; namespace Nasa.MarsRover.Command { public interface IRoverExploreCommand : ICommand { IList<Direction> Directions { get; } void SetReceiver(IRover aRover); } }<file_sep>/Nasa.MarsRover/Program.cs using System; using System.Reflection; using System.Text; using Autofac; namespace Nasa.MarsRover { public class Program { static void Main(string[] args) { var commandString = buildCommand(); var containerBuilder = createContainerBuilder(); using (var container = containerBuilder.Build()) { var commandMain = container.Resolve<ICommandMain>(); commandMain.Execute(commandString); var Reports = commandMain.GetCombinedRoverReport(); Display(commandString, Reports); } } private static ContainerBuilder createContainerBuilder() { var programAssembly = Assembly.GetExecutingAssembly(); var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(programAssembly) .AsImplementedInterfaces(); return builder; } private static void Display(string commandString, string Reports) { Console.WriteLine("Input:"); Console.WriteLine(commandString); Console.WriteLine(Environment.NewLine); Console.WriteLine("Output:"); Console.WriteLine(Reports); Console.Write(Environment.NewLine); Console.Write("Press <enter> to exit..."); Console.ReadLine(); } private static string buildCommand() { var commandStringBuilder = new StringBuilder(); commandStringBuilder.AppendLine("5 5"); commandStringBuilder.AppendLine("1 2 N"); commandStringBuilder.AppendLine("LMLMLMLMM"); commandStringBuilder.AppendLine("3 3 E"); commandStringBuilder.Append("MMRMMRMRRM"); return commandStringBuilder.ToString(); } } } <file_sep>/Nasa.MarsRover/Rovers/Rover.cs using System; using System.Collections.Generic; using System.Linq.Expressions; using Nasa.MarsRover.LandingSurface; namespace Nasa.MarsRover.Rovers { public class Rover : IRover { public Coordinate Position { get; set; } public CardinalDirection CardinalDirection { get; set; } private bool isDeployed; private readonly IDictionary<Direction, Action> DirectionMethodDictionary; private readonly IDictionary<CardinalDirection, Action> leftMoveDictionary; private readonly IDictionary<CardinalDirection, Action> rightMoveDictionary; private readonly IDictionary<CardinalDirection, Action> forwardMoveDictionary; public Rover() { DirectionMethodDictionary = new Dictionary<Direction, Action> { {Direction.Left, () => leftMoveDictionary[CardinalDirection].Invoke()}, {Direction.Right, () => rightMoveDictionary[CardinalDirection].Invoke()}, {Direction.Forward, () => forwardMoveDictionary[CardinalDirection].Invoke()} }; leftMoveDictionary = new Dictionary<CardinalDirection, Action> { {CardinalDirection.North, () => CardinalDirection = CardinalDirection.West}, {CardinalDirection.East, () => CardinalDirection = CardinalDirection.North}, {CardinalDirection.South, () => CardinalDirection = CardinalDirection.East}, {CardinalDirection.West, () => CardinalDirection = CardinalDirection.South} }; rightMoveDictionary = new Dictionary<CardinalDirection, Action> { {CardinalDirection.North, () => CardinalDirection = CardinalDirection.East}, {CardinalDirection.East, () => CardinalDirection = CardinalDirection.South}, {CardinalDirection.South, () => CardinalDirection = CardinalDirection.West}, {CardinalDirection.West, () => CardinalDirection = CardinalDirection.North} }; forwardMoveDictionary = new Dictionary<CardinalDirection, Action> { {CardinalDirection.North, () => {Position = new Coordinate(Position.X, Position.Y + 1);}}, {CardinalDirection.East, () => {Position = new Coordinate(Position.X + 1, Position.Y);}}, {CardinalDirection.South, () => {Position = new Coordinate(Position.X, Position.Y - 1);}}, {CardinalDirection.West, () => {Position = new Coordinate(Position.X - 1, Position.Y);}} }; } public void Deploy(ISurface aLandingSurface, Coordinate aCoordinate, CardinalDirection aDirection) { if (aLandingSurface.IsValid(aCoordinate)) { Position = aCoordinate; CardinalDirection = aDirection; isDeployed = true; return; } throwDeployException(aLandingSurface, aCoordinate); } public void Move(IEnumerable<Direction> Directions) { foreach (var Direction in Directions) { DirectionMethodDictionary[Direction].Invoke(); } } public bool IsDeployed() { return isDeployed; } private static void throwDeployException(ISurface aLandingSurface, Coordinate aCoordinate) { var size = aLandingSurface.GetSize(); var exceptionMessage = String.Format("Deploy failed for Coordinate ({0},{1}). Landing surface size is {2} x {3}.", aCoordinate.X, aCoordinate.Y, size.Width, size.Height); throw new RoverDeployException(exceptionMessage); } } } <file_sep>/Nasa.MarsRover/Command/Interpret/CommandParser.cs using System; using System.Collections.Generic; using System.Linq; using Nasa.MarsRover.LandingSurface; using Nasa.MarsRover.Rovers; namespace Nasa.MarsRover.Command.Interpret { public class CommandParser : ICommandParser { private readonly Func<Dimension, ISurfaceSizeCommand> landingSurfaceSizeCommandFactory; private readonly Func<Coordinate, CardinalDirection, IRoverDeployCommand> roverDeployCommandFactory; private readonly Func<IList<Direction>, IRoverExploreCommand> roverExploreCommandFactory; private readonly ICommandMatcher commandMatcher; private readonly IDictionary<CommandType, Func<string, ICommand>> commandParserDictionary; private readonly IDictionary<char, CardinalDirection> cardinalDirectionDictionary; private readonly IDictionary<char, Direction> DirectionDictionary; public CommandParser(ICommandMatcher aCommandMatcher, Func<Dimension, ISurfaceSizeCommand> aLandingSurfaceSizeCommandFactory, Func<Coordinate, CardinalDirection, IRoverDeployCommand> aRoverDeployCommandFactory, Func<IList<Direction>, IRoverExploreCommand> aRoverExploreCommandFactory) { commandMatcher = aCommandMatcher; landingSurfaceSizeCommandFactory = aLandingSurfaceSizeCommandFactory; roverDeployCommandFactory = aRoverDeployCommandFactory; roverExploreCommandFactory = aRoverExploreCommandFactory; commandParserDictionary = new Dictionary<CommandType, Func<string, ICommand>> { {CommandType.LandingSurfaceSizeCommand, ParseLandingSurfaceSizeCommand}, {CommandType.RoverDeployCommand, ParseRoverDeployCommand}, {CommandType.RoverExploreCommand, ParseRoverExploreCommand} }; cardinalDirectionDictionary = new Dictionary<char, CardinalDirection> { {'N', CardinalDirection.North}, {'S', CardinalDirection.South}, {'E', CardinalDirection.East}, {'W', CardinalDirection.West} }; DirectionDictionary = new Dictionary<char, Direction> { {'L', Direction.Left}, {'R', Direction.Right}, {'M', Direction.Forward} }; } public IEnumerable<ICommand> Parse(string commandString) { var commands = commandString.Split(new[] { Environment.NewLine }, StringSplitOptions.None); return commands.Select( command => commandParserDictionary[commandMatcher.GetCommandType(command)] .Invoke(command)).ToList(); } private ICommand ParseLandingSurfaceSizeCommand(string toParse) { var arguments = toParse.Split(' '); var width = int.Parse(arguments[0]); var height = int.Parse(arguments[1]); var size = new Dimension(width, height); var populatedCommand = landingSurfaceSizeCommandFactory(size); return populatedCommand; } private ICommand ParseRoverDeployCommand(string toParse) { var arguments = toParse.Split(' '); var deployX = int.Parse(arguments[0]); var deployY = int.Parse(arguments[1]); var directionSignifier = arguments[2][0]; var deployDirection = cardinalDirectionDictionary[directionSignifier]; var deployCoordinate = new Coordinate(deployX, deployY); var populatedCommand = roverDeployCommandFactory(deployCoordinate, deployDirection); return populatedCommand; } private ICommand ParseRoverExploreCommand(string toParse) { var arguments = toParse.ToCharArray(); var Directions = arguments.Select(argument => DirectionDictionary[argument]).ToList(); var populatedCommand = roverExploreCommandFactory(Directions); return populatedCommand; } } }<file_sep>/Nasa.MarsRover/Command/RoverExploreCommand.cs using System.Collections.Generic; using Nasa.MarsRover.Rovers; namespace Nasa.MarsRover.Command { public class RoverExploreCommand : IRoverExploreCommand { public IList<Direction> Directions { get; private set; } private IRover rover; public RoverExploreCommand(IList<Direction> someDirections) { Directions = someDirections; } public CommandType GetCommandType() { return CommandType.RoverExploreCommand; } public void Execute() { rover.Move(Directions); } public void SetReceiver(IRover aRover) { rover = aRover; } } } <file_sep>/Nasa.MarsRover/LandingSurface/Dimension.cs namespace Nasa.MarsRover.LandingSurface { public struct Dimension { public int Width; public int Height; public Dimension(int aWidth, int aHeight) { Width = aWidth; Height = aHeight; } } } <file_sep>/Nasa.MarsRover/LandingSurface/Plateau.cs namespace Nasa.MarsRover.LandingSurface { public class Plateau : ISurface { private Dimension size { get; set; } public void SetSize(Dimension aSize) { size = aSize; } public Dimension GetSize() { return size; } public bool IsValid(Coordinate aCoordinate) { var isValidX = aCoordinate.X >= 0 && aCoordinate.X <= size.Width; var isValidY = aCoordinate.Y >= 0 && aCoordinate.Y <= size.Height; return isValidX && isValidY; } } } <file_sep>/Nasa.MarsRover/Command/RoverDeployCommand.cs using Nasa.MarsRover.LandingSurface; using Nasa.MarsRover.Rovers; namespace Nasa.MarsRover.Command { public class RoverDeployCommand : IRoverDeployCommand { public Coordinate DeployCoordinate { get; set; } public CardinalDirection DeployDirection { get; set; } private IRover rover; private ISurface landingSurface; public RoverDeployCommand(Coordinate aCoordinate, CardinalDirection aDirection) { DeployCoordinate = aCoordinate; DeployDirection = aDirection; } public CommandType GetCommandType() { return CommandType.RoverDeployCommand; } public void Execute() { rover.Deploy(landingSurface, DeployCoordinate, DeployDirection); } public void SetReceivers(IRover aRover, ISurface aLandingSurface) { rover = aRover; landingSurface = aLandingSurface; } } } <file_sep>/Nasa.MarsRover/Command/ILandingSurfaceSizeCommand.cs using Nasa.MarsRover.LandingSurface; namespace Nasa.MarsRover.Command { public interface ISurfaceSizeCommand : ICommand { Dimension Dimension { get; } void SetReceiver(ISurface aLandingSurface); } }<file_sep>/Nasa.MarsRover/Command/IRoverDeployCommand.cs using Nasa.MarsRover.LandingSurface; using Nasa.MarsRover.Rovers; namespace Nasa.MarsRover.Command { public interface IRoverDeployCommand : ICommand { Coordinate DeployCoordinate { get; set; } CardinalDirection DeployDirection { get; set; } void SetReceivers(IRover aRover, ISurface aLandingSurface); } }<file_sep>/Nasa.MarsRover/LandingSurface/ISurface.cs namespace Nasa.MarsRover.LandingSurface { public interface ISurface { void SetSize(Dimension aSize); Dimension GetSize(); bool IsValid(Coordinate aCoordinate); } }
db11cb3f5fb95a2d6b7fe0fbffcabc4296a836be
[ "C#" ]
15
C#
RohKumar/VicRoadCodingTest
e1cca44253fe82e99331df6312953e99ef006c9c
0344fecffe39f26c3dd4a058581a9c53e3002cae
refs/heads/master
<repo_name>davelab6/responsiveLettering<file_sep>/LTRMathShape.roboFontExt/lib/mathShape/makePage.py import os import json """ Because we need a way to preview a mathshape in a single page without having to load a json file locally. """ class PageMaker(object): # XXXX does not need to be a class. htmlPath = "template.html" cssPath = "styles.css" mathShapePath = "mathShape.js" outputPath = "test.html" def __init__(self, resourcesRoot, shapePath, outputPath, fillColor=None, saveFile=True): if fillColor is None: fillColor = '#ff3300' self.shapePath = shapePath self.root = resourcesRoot # acquire the code f = open(os.path.join(self.root, self.htmlPath), 'rb') self.html = f.read() f.close() f = open(os.path.join(self.root, self.cssPath), 'rb') css = f.read() f.close() f = open(os.path.join(self.root, self.mathShapePath), 'rb') js = f.read() f.close() # mathshape data jsonPath = os.path.join(shapePath, 'files.json'); # print "jsonPath", jsonPath f = open(jsonPath, 'rb') data = f.read() f.close() jsonData = json.loads(data) svgLoaderContainer = [] for name in jsonData['files']: svgPath = os.path.join(shapePath, os.path.basename(name)) # print svgPath, os.path.exists(svgPath) f = open(svgPath, 'rb') svgData = f.read() svgLoaderContainer.append(svgData) # paste self.html = self.html.replace("//mathshape", js) self.html = self.html.replace("/*styles*/", css) self.html = self.html.replace("//__jsondata", data) self.html = self.html.replace("<!--svgobjects-->", "\n".join(svgLoaderContainer)) self.html = self.html.replace('/*testShapeFillColor*/', "\""+fillColor+"\"") # release # print self.html] if saveFile: f = open(os.path.join(self.root, outputPath), 'w') f.write(self.html) f.close() if __name__ == "__main__": root = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "Resources") outputPath = os.path.join(root, "test.html") # print os.listdir(root) pm = PageMaker(root, os.path.join(root,'placeholder_ms'), outputPath) print pm.html <file_sep>/LTRMathShape.roboFontExt/lib/mathShape/cmd_exportCurrentFont.py import os import json import vanilla from mojo.UI import * from AppKit import NSColor from exportTools import makeSVGShape, makeMaster import makePage reload(makePage) from makePage import PageMaker import tempfile class ExportUI(object): masterNames = ['narrow-thin', 'wide-thin', 'narrow-bold', 'wide-bold'] def __init__(self): self.color = "#FF0000" self.w = vanilla.Window((500, 600), "MathShape Exporter", minSize=(300,200)) self.w.preview = HTMLView((0,0,-0, -200)) self.w.exportButton = vanilla.Button((-150, -30, -10, 20), "Export", callback=self.cbExport) self.w.previewButton = vanilla.Button((10, -30, -160, 20), "Preview", callback=self.cbMakePreview) valueWidth = 50 columnDescriptions = [ dict(title="Glyphname", key="name", width=100), dict(title="Width", key="width"), dict(title="Bounds", key="bounds", width=100), ] self.w.l = vanilla.List((0,-200,-0,-60), self.wrapGlyphs(), columnDescriptions=columnDescriptions) self.w.t = vanilla.TextBox((40,-53,-5,20), "FontName", sizeStyle="small") self.w.clr = vanilla.ColorWell((10,-55, 20, 20), callback=self.cbColor, color=NSColor.redColor()) self.update() self.w.open() def update(self): # when starting, or when there is an update? f = CurrentFont() glyphs = self.wrapGlyphs() self.w.l.set(glyphs) folderName = self.proposeFilename(f) self.w.t.set(folderName) #self.cbMakePreview(None) def validate(self, font): # can we generate this one? # test. # do we have all the right names: print 'validating' for name in self.masterNames: if name not in font: print 'msiing glyph', name self.w.t.set("Glyph %s missing."%name) return False return True def wrapGlyphs(self): f = CurrentFont() glyphs = [] names = f.keys() names.sort() layers = f.layerOrder if 'bounds' in layers: hasBounds = True else: hasBounds = False for n in names: if n in self.masterNames: status = True else: continue g = f[n] g.getLayer d = dict(name=g.name,width=g.width,bounds=hasBounds,status=status) glyphs.append(d) return glyphs def cbColor(self, sender): clr = sender.get() red = clr.redComponent()*0xff grn = clr.greenComponent()*0xff blu = clr.blueComponent()*0xff self.color = "#%x%x%x"%(red,grn,blu) self.cbMakePreview(self) def cbMakePreview(self, sender): # generate a preview f = CurrentFont() proposedName = self.proposeFilename(f) # export the mathshape root, tags, metaData = exportCurrentFont(f, self.masterNames, proposedName) resourcesPath = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "Resources") #print "resourcesPath", resourcesPath, os.path.exists(resourcesPath) outputPath = os.path.join(root, "preview_%s.html"%proposedName) pm = PageMaker(resourcesPath, os.path.join(root, proposedName), outputPath, fillColor=self.color) self.w.preview.setHTMLPath(outputPath) def cbExport(self, sender): if not self.validate: # show error message print 'error' return f = CurrentFont() proposedName = self.proposeFilename(f) # export the mathshape root, tags, metaData = exportCurrentFont(f, self.masterNames, proposedName) #/Users/erik/Library/Application Support/RoboFont/plugins/LTRMathShape.roboFontExt/lib/cmd_exportCurrentFont.py resourcesPath = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "Resources") #print "resourcesPath", resourcesPath, os.path.exists(resourcesPath) outputPath = os.path.join(root, "test_%s.html"%proposedName) pm = PageMaker(resourcesPath, os.path.join(root, proposedName), outputPath, fillColor=self.color) self.w.close() def proposeFilename(self, exportFont): name = "%s%s_ms"%(exportFont.info.familyName, exportFont.info.styleName) name = name.lower() return name def exportCurrentFont(exportFont, masterNames, folderName, saveFiles=True): tags = [] # the svg tags as they are produced exportFont.save() path = exportFont.path #exportFont.close() #exportFont = OpenFont(path) checkBoundsLayer = False if 'bounds' in exportFont.layerOrder: checkBoundsLayer = True root = os.path.dirname(exportFont.path) if saveFiles: # if we want to export to a real folder imagesFolder = os.path.join(root, folderName) jsonPath = os.path.join(imagesFolder, "files.json") if not os.path.exists(imagesFolder): os.makedirs(imagesFolder) allBounds = [] for name in masterNames: g = exportFont[name] undo = False if len(g.components)>0: exportFont.prepareUndo(undoTitle="decompose_for_svg_export") g.decompose() undo = True # check the bounds layer for the bounds first bounds, tag = makeSVGShape(g, name=name) tags.append(tag) k = [bounds[2],bounds[3]] if k not in allBounds: allBounds.append(k) if saveFiles: filePath = os.path.join(imagesFolder, "%s.svg"%name) makeMaster(filePath, tag) if undo: exportFont.performUndo() metaData = dict(sizebounds=allBounds, files=[folderName+"/%s.svg"%n for n in masterNames]) metaData['extrapolatemin']=0 metaData['extrapolatemax']=1.25 metaData['designspace']='twobytwo' if saveFiles: jsonFile = open(jsonPath, 'w') jsonFile.write(json.dumps(metaData)) jsonFile.close() return root, tags, metaData ExportUI()<file_sep>/LTRMathShape.roboFontExt/lib/mathShape/cmd_prepareNewShape.py """ Make a new UFO and give it the appropriate glyphs and layers. """ import os, time def prepareMathShapeUFO(narrow=500, wide=2500): styleName = time.strftime("%Y%m%d", time.localtime()) f = NewFont(familyName="MathShape", styleName=styleName) f.info.note = "This is a template font for a MathShape. The font names and glyph widths can all tbe changed." glyphs = [ ('narrow-thin', narrow), ('wide-thin', wide), ('narrow-bold',narrow), ('wide-bold', wide), ] # draw bounds layer asc = f.info.ascender dsc = f.info.descender for name, width in glyphs: f.newGlyph(name) g = f[name] g.width = width boundsGlyph = g.getLayer('bounds', clear=True) pen = boundsGlyph.getPen() pen.moveTo((0,dsc)) pen.lineTo((g.width,dsc)) pen.lineTo((g.width,asc)) pen.lineTo((0,asc)) pen.closePath() # draw some sort of intro / test shape? thin = 5 thick = 100 for g in f: w = g.width if g.name.find("thin")!=-1: thin = 5 else: thin = 100 pen = g.getPen() pen.moveTo((0,dsc)) pen.lineTo((thin, dsc)) pen.lineTo((w, asc-thin)) pen.lineTo((w, asc)) pen.lineTo((w-thin,asc)) pen.lineTo((0,dsc+thin)) pen.closePath() pen.moveTo((0,asc)) pen.lineTo((0,asc-thin)) pen.lineTo((w-thin,dsc)) pen.lineTo((w,dsc)) pen.lineTo((w,dsc+thin)) pen.lineTo((thin,asc)) pen.closePath() prepareMathShapeUFO()
6f3ee020dda244a0e93f0381123e73b8cc1528b1
[ "Python" ]
3
Python
davelab6/responsiveLettering
8b8cecbcf77b0cd4c54ef21cc3a393a17e2d035c
dae6f49adf20cc6f81c5527a450e01ffa1e69e73
refs/heads/master
<file_sep>package com.xiaoweng.project.entity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * 角色表 */ @ApiModel(value = "com-xiaoweng-project-entity-Role") @Data public class Role { /** * 角色id */ @ApiModelProperty(value = "角色id") private Integer roleId; /** * 角色名 */ @ApiModelProperty(value = "角色名") private String roleName; }<file_sep>package com.xiaoweng.project.service; import com.xiaoweng.project.dto.LoginDTO; import com.xiaoweng.project.entity.User; /** * @ClassName UserService * @Description TODO 业务逻辑层--UserService * @Date 2020/12/2 * @Author XiaoWeng * @Version v1.0.0 */ public interface UserService { User getUser(LoginDTO loginDTO); } <file_sep>package com.xiaoweng.project.common.result; /** * @ClassName ResultBuilder * @Description TODO 返回构建类 * @Date 2020/12/3 * @Author XiaoWeng * @Version v1.0.0 */ public class ResultBuilder { //成功,不返回具体数据 public static <T> Result<T> successNoData(ResultCode code){ return new Result<>(code.getCode(),code.getMsg()); } //成功,返回数据 public static <T> Result<T> success(ResultCode code,T t){ return new Result<>(code.getCode(),code.getMsg(),t); } //失败,返回失败信息 public static <T> Result<T> fail(ResultCode code){ return new Result<>(code.getCode(),code.getMsg()); } } <file_sep>package com.xiaoweng.project.dto; import lombok.Data; import javax.validation.constraints.NotBlank; /** * @ClassName LoginDTO * @Description TODO 登录传输类 * @Date 2020/12/2 * @Author XiaoWeng * @Version v1.0.0 */ @Data public class LoginDTO { @NotBlank(message = "用户名不能为空") private String username; @NotBlank(message = "密码不能为空") private String password; }<file_sep>package com.xiaoweng.project.mapper; import com.xiaoweng.project.entity.RolePermission; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @Mapper public interface RolePermissionMapper { int deleteByPrimaryKey(@Param("roleId") Integer roleId, @Param("permissionId") Integer permissionId); int insertSelective(RolePermission record); }<file_sep>package com.xiaoweng.project.mapper; import com.xiaoweng.project.entity.Role; import org.apache.ibatis.annotations.Mapper; @Mapper public interface RoleMapper { int deleteByPrimaryKey(Integer roleId); int insertSelective(Role record); Role selectByPrimaryKey(Integer roleId); int updateByPrimaryKeySelective(Role record); }<file_sep>package com.xiaoweng.project.mapper; import com.xiaoweng.project.entity.UserRole; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @Mapper public interface UserRoleMapper { int deleteByPrimaryKey(@Param("userId") Integer userId, @Param("roleId") Integer roleId); int insertSelective(UserRole record); }<file_sep>package com.xiaoweng.project.entity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * 用户角色关联表 */ @ApiModel(value = "com-xiaoweng-project-entity-UserRole") @Data public class UserRole { /** * 用户id */ @ApiModelProperty(value = "用户id") private Integer userId; /** * 角色id */ @ApiModelProperty(value = "角色id") private Integer roleId; }<file_sep>package com.xiaoweng.project.entity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.Date; import lombok.Data; @ApiModel(value = "com-xiaoweng-project-entity-User") @Data public class User { /** * 用户id */ @ApiModelProperty(value = "用户id") private Integer userId; /** * 用户名 */ @ApiModelProperty(value = "用户名") private String username; /** * 密码 */ @ApiModelProperty(value = "密码") private String password; /** * 用户令牌 */ @ApiModelProperty(value = "用户令牌") private String token; /** * 令牌失效时间 */ @ApiModelProperty(value = "令牌失效时间") private Date expireTime; /** * 更新时间 */ @ApiModelProperty(value = "更新时间") private Date updateTime; /** * 创建时间 */ @ApiModelProperty(value = "创建时间") private Date createTime; }<file_sep>package com.xiaoweng.project.entity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * 角色权限关联表 */ @ApiModel(value = "com-xiaoweng-project-entity-RolePermission") @Data public class RolePermission { /** * 角色id */ @ApiModelProperty(value = "角色id") private Integer roleId; /** * 权限id */ @ApiModelProperty(value = "权限id") private Integer permissionId; }
f303661b01d4570b1a15c3a7c980a7a90ba57af6
[ "Java" ]
10
Java
moxiaoweng/TechnicalProject
24a7fc37a445cdc025cb430258c69b9e08653204
996be38f8ac1c65b0253a7c0e93d64d72012809b
refs/heads/master
<file_sep>package api.com.bairos; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author <NAME> */ public class Datas { Date Data2; String DataConvertida; SimpleDateFormat DataFormatada = new SimpleDateFormat("yyyy/MM/dd"); SimpleDateFormat DataFormatada2 = new SimpleDateFormat("dd/MM/yyyy"); public String ConverterData(String Data, String Linguagem, String Local) { try { Data2 = DataFormatada.parse(Data); } catch (ParseException ex) { System.err.println("Error to parse the typed date: " + ex); } /* * if ((Data == null) || (Linguagem == null) || (Local == null)) { throw * new IllegalArgumentException("parameter cannot be null"); }// */ if (LocaleISOData.isoLanguageTable.contains(Linguagem)) { DateFormat DF = SimpleDateFormat.getDateInstance(SimpleDateFormat.MEDIUM, new Locale(Linguagem, Local)); DataConvertida = DF.format(Data2); } else { throw new IllegalArgumentException("The \"" + Linguagem + "\" encoding ISO not available!"); } if (LocaleISOData.isoCountryTable.contains(Local)) { DateFormat DF = SimpleDateFormat.getDateInstance(SimpleDateFormat.MEDIUM, new Locale(Linguagem, Local)); DataConvertida = DF.format(Data2); } else { throw new IllegalArgumentException("The \"" + Local + "\" encoding ISO not available!"); } return DataConvertida; } public String ConverterDataPorExtenso(String Data, String Linguagem, String Local) { try { Data2 = DataFormatada2.parse(Data); } catch (ParseException ex) { System.err.println("Error to parse the typed date: " + ex); } if ((Data == null) || (Local == null)) { throw new IllegalArgumentException("parameter cannot be null"); } if ((Linguagem == null) || (Linguagem.equals(""))) { DateFormat DF = SimpleDateFormat.getDateInstance(SimpleDateFormat.LONG, Locale.getDefault()); DataConvertida = DF.format(Data2); } else if (LocaleISOData.isoCountryTable.contains(Local)) { DateFormat DF = SimpleDateFormat.getDateInstance(SimpleDateFormat.LONG, new Locale(Linguagem, Local)); DataConvertida = DF.format(Data2); } else { throw new IllegalArgumentException("The \"" + Local + "\" encoding ISO not available!"); } return DataConvertida; } public static void main(String[] args) { System.out.println(new Datas().ConverterData("2012/06/10", "pt", "BR")); System.out.println(new Datas().ConverterDataPorExtenso("10/06/2012", "en", "US")); } }
b5f4772a236e7f37ae83354299542e324cce8bda
[ "Java" ]
1
Java
guigo82/DataAPI
a4c8b67206fd76250ca52e975a1a51a339982d92
4a66c05d27426851de67db3c04b4e8e312ba5072
refs/heads/master
<repo_name>Cecil0o0/miniprogram1<file_sep>/src/components/loadmore/index.js import Taro, { Component } from '@tarojs/taro' import { View, Text } from '@tarojs/components' import './index.styl' export default class Loadmore extends Component { render() { return ( <View className="loadmore"> <Text>加载更多...</Text> </View> ) } } <file_sep>/src/components/modal/index.js import Taro, { Component } from '@tarojs/taro' import { View } from '@tarojs/components' import './index.styl' export default class Modal extends Component { InnerClick(e) { e.stopPropagation() } render() { return ( <View className="qf-modal"> <View onClick={this.InnerClick}>{this.props.children}</View> </View> ) } } <file_sep>/src/pages/view-avatar/index.js import Taro, { Component } from '@tarojs/taro' import { View } from '@tarojs/components' import './index.styl' import { promisifyUpload, delayToExec, showToast } from '../../lib/utils' import { USER_MODEL_INFO } from '../../lib/constants' import { api_info_edit } from '../../api' export default class ViewAvatar extends Component { config = { navigationBarTitleText: '更换头像' } state = { info: { avatar: 'http://t2.hddhhn.com/uploads/tu/20150402/220ZQ614-0.jpg' } } componentDidMount() { this.setState({ info: Taro.getStorageSync(USER_MODEL_INFO) }) } selectImg = () => { return new Promise(resolve => { Taro.chooseImage({ count: 1, sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], success: res => { this.setState({ info: Object.assign({}, this.state.info, { avatar: res.tempFilePaths[0] }) }, resolve) } }) }) } upload = () => { return promisifyUpload(this.state.info.avatar).then(res => { const { id } = this.state.info api_info_edit({ id, avatar: res.data }).then(res => { if (res.success) { Taro.setStorageSync(USER_MODEL_INFO, this.state.info) showToast('保存成功') delayToExec(() => Taro.navigateBack()) } }) }) } selectAndUpload () { this.selectImg().then(this.upload) } cancel() { Taro.navigateBack({ delta: 1 }) } render() { return ( <View className="view-avatar"> <View style={{backgroundImage: `url("${this.state.info.avatar}")`}} className="img" /> <View className="upload-btn" onClick={this.selectAndUpload}> 更换头像 </View> <View className="confirm-btn" onClick={this.cancel}> 取消 </View> </View> ) } } <file_sep>/src/lib/constants.js export const USER_MODEL_INFO = 'USER_MODEL_INFO' export const USER_INFO = 'USER_INFO' export const LOGIN_STATUS = 'LOGIN_STATUS' export const SEARCH_TAGS = 'SEARCH_TAGS' export const IMAGE_URL = `${URL_PREFIX}/upload/` export const SIZE = 6<file_sep>/src/api/index.js import fetch from '../lib/fetch' import { SIZE, LOGIN_STATUS } from '../lib/constants' import Taro from '@tarojs/taro' /* eslint-disable-next-line */ const prefix = URL_PREFIX + '/v1' export const api_banners = () => { return fetch({ url: `${prefix}/banners` }) } export const api_info = (id) => { return fetch({ url: `${prefix}/model/${id}` }) } export const api_info_edit = (data) => { return fetch({ url: `${prefix}/model`, method: 'PUT', data }) } export const api_advice_add = data => { return fetch({ url: `${prefix}/advice`, method: 'POST', data }) } // 以逗号分割的字符串 export const api_get_uploads = ids => { return fetch({ url: `${prefix}/upload/${ids}`, method: 'GET' }) } export const api_login = code => { return fetch({ url: `${prefix}/login`, method: 'POST', data: { code } }) } export const api_home_models = ({ type = 'hot', page = 1, size = SIZE}) => { return fetch({ url: `${prefix}/model/${type}`, data: { page, size } }) } export const api_model_hot = (modelId) => { return fetch({ url: `${prefix}/hf/hot`, data: { modelId } }) } // 关注 export const api_user_attention = ({ modelId }) => { const userId = Taro.getStorageSync(LOGIN_STATUS).id return fetch({ url: `${prefix}/hf/addAttention`, method: 'POST', data: { modelId, userId } }) } // 取消关注 export const api_user_remove_attention = (modelId) => { const userId = Taro.getStorageSync(LOGIN_STATUS).id return fetch({ url: `${prefix}/hf/removeAttention`, method: 'POST', data: { modelId, userId } }) } export const api_user_if_follow = (modelId) => { const userId = Taro.getStorageSync(LOGIN_STATUS).id return fetch({ url: `${prefix}/hf/getIfAttention?userId=${userId}&modelId=${modelId}`, }) } export const api_get_partical_models = (ids) => { return fetch({ url: `${prefix}/models`, method: 'POST', data: { ids } }) } export const api_models_search = (text, page, size = SIZE) => { return fetch({ url: `${prefix}/search/models?text=${text}&page=${page}&size=${size}` }) }<file_sep>/src/lib/fetch.js import Taro from '@tarojs/taro' import { LOGIN_STATUS } from '../lib/constants' export default function({ url, data, method = 'GET', dataType = 'json' } = {}) { return Taro.request({ url, data, method, dataType, header: { 'Content-Type': 'application/json', 'token': Taro.getStorageSync(LOGIN_STATUS).token } }).then(res => res.data).then(res => { if (!res.success) { Taro.showToast({ title: res.reason || '服务器错误', duration: 1500, mask: true, icon: 'none' }) } return res }) } <file_sep>/src/pages/info-photo-edit/index.js import Taro, { Component } from '@tarojs/taro' import { View } from '@tarojs/components' import update from 'immutability-helper' import './index.styl' import { USER_MODEL_INFO } from '../../lib/constants' import { uploadFiles, getUploadResAbsAddress, delayToExec, showToast } from '../../lib/utils' import { api_info_edit, api_info } from '../../api' export default class InfoPhotoEdit extends Component { state = { isEdit: false, selected: [], imgs: [], type: 1 } componentWillMount() { // 1为poster // 2为photo this.state.type = this.$router.params.type || 1 Taro.setNavigationBarTitle({ title: this.state.type === '1' ? '海报编辑' : '相册编辑' }) } getAttr() { return this.state.type === '1' ? 'posters' : 'photos' } componentDidMount(params) { let info = Taro.getStorageSync(USER_MODEL_INFO) this.setState({ imgs: info[this.getAttr()] }) } delete() { let deleteIndexes = this.state.selected.map(item => ([this.state.imgs.findIndex(img => img.id === item), 1])) this.setState({ imgs: update(this.state.imgs, { $splice: deleteIndexes }), selected: [], isEdit: false }) } complete() { // 非常复杂的上传操作 let info = Taro.getStorageSync(USER_MODEL_INFO) let uploadedFiles = this.state.imgs.filter(item => item.type === 'new') Taro.showLoading('正在上传') uploadFiles(uploadedFiles.map(item => item.src)).then(res => { const indexes = res.map((resItem, index) => { return this.state.imgs.findIndex(item => item.src === uploadedFiles[index].src) }) let obj = {} indexes.forEach((item, index) => { obj[item] = { $set: { src: res[index].data } } }) this.setState({ imgs: update(this.state.imgs, obj) }, () => { Taro.showLoading('正在保存') // 保存信息 api_info_edit({ id: info.id, [this.getAttr()]: this.state.imgs }).then(res => { const info = Taro.getStorageSync(USER_MODEL_INFO) Taro.setStorageSync(USER_MODEL_INFO, Object.assign(info, {[this.getAttr()]: this.state.imgs})) showToast('保存成功') delayToExec(Taro.navigateBack) }) }) }) } add() { wx.chooseImage({ count: 9 - this.state.imgs.length, sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], success: (res) => { // tempFilePath可以作为img标签的src属性显示图片 const tempFilePaths = res.tempFilePaths this.setState({ imgs: update(this.state.imgs, { $push: tempFilePaths.map(item => ({ type: 'new', src: item })) }) }) } }) } itemClick(src, isSelected) { if (!this.state.isEdit) return if (isSelected) { const index = this.state.selected.findIndex(item => item === src) this.setState( update(this.state, { selected: { $splice: [[index, 1]] } }) ) } else { this.setState( update(this.state, { selected: { $push: [src] } }) ) } } editPhoto(src) { this.setState( update(this.state, { isEdit: { $set: true }, selected: { $push: [src] } }) ) } render() { const { imgs, isEdit, selected } = this.state return ( <View className="photo-edit"> <View className="header">长按图片编辑</View> <View className="img-wrapper"> {imgs.map((item, key) => { const isSelected = selected.indexOf(item.src) !== -1 return ( <View key={key} className="item" style={{ backgroundImage: `url("${item.src}")` }} onLongPress={this.editPhoto.bind(this, item.src)} onClick={this.itemClick.bind(this, item.src, isSelected)} > {isEdit && (isSelected ? <View className="checked" /> : <View className="uncheck" />)} </View> ) })} {imgs.length < 9 && ( <View className="uploader" onClick={this.add}> + </View> )} </View> {isEdit && ( <View className="cancelBtn" onClick={this.delete}> 删除选中照片 </View> )} <View className="confirmBtn" onClick={this.complete}> 完成 </View> </View> ) } } <file_sep>/src/pages/card-edit-2/index.js import Taro, { Component } from '@tarojs/taro' import { View, Image, Picker, Input, Canvas } from '@tarojs/components' import './index.styl' import CaretRightPng from '../../images/caret_right.png' const heights = [] for (let i = 60; i <= 220; i++) { heights.push(i) } const weights = [] for (let i = 20; i <= 150; i++) { weights.push(i) } const bwhs = [] const col = [] for (let j = 0; j < 3; j++) { for (let i = 30; i <= 130; i++) { col.push(i) } bwhs.push(col) } const shoess = [] for (let i = 30; i <= 50; i++) { shoess.push(i) } const bgcolors = [ { name: '红', value: 'red' }, { name: '黄', value: 'yellow' }, { name: '蓝', value: 'blue' }, { name: '白', value: 'white' }, { name: '浅灰', value: '#d1d3db'} ] export default class CardEdit2 extends Component { constructor() { super(...arguments) this.type = +this.$router.params.type || 3 this.state = { info: { name: '某某某', age: 20, height: 165, weight: 50, bwh: [88, 88, 88], shoeSize: 35, city: ['北京市', '无', '无'], bgcolor: { name: '白', value: 'white' } } } switch(this.type) { case 1: this.state.canvasSize = { width: 4050 / 2, height: 2447 / 2 } break case 2: this.state.canvasSize = { width: 4056 / 2, height: 1717 / 2 } break case 3: this.state.canvasSize = { width: 2502, height: 1079 } break } } config = { navigationBarTitleText: '模卡制作' } dataTrans(key, value) { let i = value if (key === 'specialities') { i = value.join(' ') } else if (key === 'bwh') { i = value.join('/') } else if (key === 'city') { i = value.join('-') } else if (key === 'bgcolor') { i = value.name } return i } componentWillMount() {} componentDidMount() {} generateModelCard = (type) => { const { name, height, weight, bwh, shoeSize, bgcolor } = this.state.info const { canvasSize } = this.state const ctx = Taro.createCanvasContext('canvas') const imgs = Taro.getStorageSync(`${type}$card-edit-photos`) // Taro.showLoading({ // title: '正在生成模卡', // mask: true // }) let fnName = '' switch(type) { case 1: fnName = 'drawTypeone' break case 2: fnName = 'drawTypetwo' break case 3: fnName = 'drawTypethree' break } this[fnName](ctx, name, height, weight, bwh, shoeSize, bgcolor, imgs) ctx.draw(false, () => { Taro.canvasToTempFilePath({ x: 0, y: 0, width: canvasSize.width, height: canvasSize.height, destWidth: canvasSize.width * 2, destHeight: canvasSize.height * 2, canvasId: 'canvas', success: (res) => { Taro.showLoading({ title: '正在保存模卡', mask: true }) Taro.saveImageToPhotosAlbum({ filePath: res.tempFilePath, complete: () => { Taro.hideLoading() Taro.showToast({ title: '已保存至相册', duration: 1000 }) var timer = setTimeout(() => { Taro.navigateBack({ delta: 3 }) Taro.switchTab({ url: '/pages/index/index' }) clearTimeout(timer) }, 1000) } }) }, fail: (e) => { console.log(e) } }) }) } drawTypeone(ctx, name, height, weight, bwh, shoeSize, bgcolor, imgs) { const { canvasSize } = this.state // 背景 ctx.setFillStyle(bgcolor.value) ctx.fillRect(0, 0, canvasSize.width, canvasSize.height) const scale = 0.5 ctx.setTransform(scale, 0, 0, scale, 0, 0) ctx.setFontSize(213) ctx.setFillStyle('#000') ctx.setTextAlign('left') ctx.setTextBaseline('top') ctx.fillText(name, 249, 185) ctx.setFontSize(80) ctx.fillText(`HEIGHT:${height}CM WEIGHT:${weight}KG`, 249, 563) ctx.fillText(`BUST:${bwh[0]} WAIST:${bwh[1]} HIPS:${bwh[2]} SHOES:${shoeSize}`, 249, 700) // 二维码 ctx.fillRect(1660, 112, 546, 546) // 图片1 imgs[0] && ctx.drawImage(imgs[0], 230, 900, 475, 710) imgs[1] && ctx.drawImage(imgs[1], 741, 900, 475, 710) imgs[2] && ctx.drawImage(imgs[2], 1252, 900, 475, 710) imgs[3] && ctx.drawImage(imgs[3], 1765, 900, 475, 710) imgs[4] && ctx.drawImage(imgs[4], 230, 1646, 475, 710) imgs[5] && ctx.drawImage(imgs[5], 741, 1646, 475, 710) imgs[6] && ctx.drawImage(imgs[6], 1252, 1646, 475, 710) imgs[7] && ctx.drawImage(imgs[7], 1765, 1646, 475, 710) imgs[8] && ctx.drawImage(imgs[8], 2418, 0, 1632, 2442) } drawTypetwo(ctx, name, height, weight, bwh, shoeSize, bgcolor, imgs) { const { canvasSize } = this.state // 背景 ctx.setFillStyle(bgcolor.value) ctx.fillRect(0, 0, canvasSize.width, canvasSize.height) const scale = 0.5 ctx.setTransform(scale, 0, 0, scale, 0, 0) ctx.setFontSize(86) ctx.setFillStyle('#000') ctx.fillRect(102, 76, 16, 85) ctx.fillText(name, 137, 150) ctx.setFontSize(57) ctx.fillText('身高|HEIGHT', 90, 267) ctx.fillText(`${height}cm`, 93, 355) ctx.fillText('体重|WEIGHT', 89, 426) ctx.fillText(`${weight}cm`, 89, 507) ctx.fillText('胸围|BUST', 89, 580) ctx.fillText(`${bwh[0]}`, 91, 669) ctx.fillText('腰围|WAIST', 89, 741) ctx.fillText(`${bwh[1]}`, 91, 826) ctx.fillText('臀围|HIPS', 89, 899) ctx.fillText(`${bwh[2]}`, 91, 982) ctx.fillText('鞋码|SHOES', 89, 1053) ctx.fillText(shoeSize, 92, 1139) // 二维码 ctx.fillRect(59, 1272, 434, 434) // 图片1 imgs[0] && ctx.drawImage(imgs[0], 558, 11, 1158, 1695) imgs[1] && ctx.drawImage(imgs[1], 1721, 11, 579, 846) imgs[2] && ctx.drawImage(imgs[2], 2304, 11, 579, 846) imgs[3] && ctx.drawImage(imgs[3], 1721, 860, 579, 846) imgs[4] && ctx.drawImage(imgs[4], 2304, 860, 579, 846) imgs[5] && ctx.drawImage(imgs[5], 2888, 11, 1158, 1695) } drawTypethree(ctx, name, height, weight, bwh, shoeSize, bgcolor, imgs) { const { canvasSize } = this.state // 背景 ctx.setFillStyle(bgcolor.value) ctx.fillRect(0, 0, canvasSize.width, canvasSize.height) ctx.setFontSize(60) ctx.setFillStyle('#000') ctx.setTextAlign('left') ctx.setTextBaseline('top') ctx.fillRect(807, 110, 225, 6) ctx.fillText(name, 831, 24) ctx.setFontSize(40) ctx.setTextAlign('center') ctx.fillText('身高|HEIGHT', 925, 115) ctx.fillText(`${height}cm`, 925, 176) ctx.fillText('体重|WEIGHT', 925, 226) ctx.fillText(`${weight}cm`, 925, 283) ctx.fillText('胸围|BUST', 925, 334) ctx.fillText(`${bwh[0]}`, 925, 396) ctx.fillText('腰围|WAIST', 925, 447) ctx.fillText(`${bwh[1]}`, 925, 506) ctx.fillText('臀围|HIPS', 925, 557) ctx.fillText(`${bwh[2]}`, 925, 615) ctx.fillText('鞋码|SHOES', 925, 665) ctx.fillText(shoeSize, 925, 725) // 二维码 ctx.fillRect(760, 771, 301, 301) // 图片1 imgs[0] && ctx.drawImage(imgs[0], 1075, 6, 348, 349) imgs[1] && ctx.drawImage(imgs[1], 1433, 6, 348, 349) imgs[2] && ctx.drawImage(imgs[2], 1791, 6, 348, 349) imgs[3] && ctx.drawImage(imgs[3], 2149, 6, 348, 349) imgs[0] && ctx.drawImage(imgs[0], 1075, 365, 348, 349) imgs[1] && ctx.drawImage(imgs[1], 1433, 365, 348, 349) imgs[2] && ctx.drawImage(imgs[2], 1791, 365, 348, 349) imgs[3] && ctx.drawImage(imgs[3], 2149, 365, 348, 349) imgs[0] && ctx.drawImage(imgs[0], 1075, 724, 348, 349) imgs[1] && ctx.drawImage(imgs[1], 1433, 724, 348, 349) imgs[2] && ctx.drawImage(imgs[2], 1791, 724, 348, 349) imgs[3] && ctx.drawImage(imgs[3], 2149, 724, 348, 349) imgs[5] && ctx.drawImage(imgs[5], 6, 6, 740, 1067) } componentWillUnmount() {} componentDidShow() {} componentDidHide() {} confirm() { this.generateModelCard(this.type) } cancel() { Taro.navigateBack() } setInfo(key, value) { return Object.assign({}, this.state.info, { [key]: value }) } onNameChange(e) { const value = e.detail.value this.setState({ info: this.setInfo('name', value) }) } onHeightChange(e) { const index = e.detail.value this.setState({ info: this.setInfo('height', heights[index]) }) } onWeightChange(e) { const index = e.detail.value this.setState({ info: this.setInfo('weight', weights[index]) }) } onBWHChange(e) { const indexArr = e.detail.value const val = indexArr.map((item, index) => { return bwhs[index][item] }) this.setState({ info: this.setInfo('bwh', val) }) } onColorChange(e) { const index = e.detail.value this.setState({ info: this.setInfo('bgcolor', Object.assign({}, bgcolors[index])) }) } onCityChange(e) { this.setState({ info: this.setInfo('city', e.detail.value) }) } render() { const { info, canvasSize } = this.state // 身高 const currHeight = this.dataTrans('height', info['height']) const height_value = heights.findIndex(item => item === currHeight) // 体重 const currWeight = this.dataTrans('weight', info['weight']) const weight_value = weights.findIndex(item => item === currWeight) // 三围 const bwh_value = this.state.info.bwh.map((item, index) => { return bwhs[index].findIndex(i => i === item) }) // 鞋码 const currShoeSize = this.dataTrans('shoeSize', info['shoeSize']) const shoeSize_value = shoess.findIndex(item => item === currShoeSize) // 背景颜色 const currBgcolor = info['bgcolor'].value const bgcolor_value = bgcolors.findIndex(item => item.value === currBgcolor) return ( <View className="page-edit-2"> <View className="form-item" onClick={this.onClickFormItem.bind(this, 'name')}> <View className="form-item-label">姓名</View> <View className="form-item-info"> <Input value={this.dataTrans('name', info['name'])} onChange={this.onNameChange} /> </View> <View className="form-item-suffix" /> </View> <Picker range={heights} onChange={this.onHeightChange} value={height_value}> <View className="form-item"> <View className="form-item-label">身高</View> <View className="form-item-info">{this.dataTrans('height', info['height'])}</View> <View className="form-item-suffix"> <Image src={CaretRightPng} /> </View> </View> </Picker> <Picker range={weights} onChange={this.onWeightChange} value={weight_value}> <View className="form-item"> <View className="form-item-label">体重</View> <View className="form-item-info">{this.dataTrans('weight', info['weight'])}</View> <View className="form-item-suffix"> <Image src={CaretRightPng} /> </View> </View> </Picker> <Picker mode="multiSelector" range={bwhs} onChange={this.onBWHChange} value={bwh_value}> <View className="form-item"> <View className="form-item-label">三围</View> <View className="form-item-info">{this.dataTrans('bwh', info['bwh'])}</View> <View className="form-item-suffix"> <Image src={CaretRightPng} /> </View> </View> </Picker> <View style={{ height: 22, backgroundColor: '#F8F8F8' }} /> <Picker range={shoess} onChange={this.onShoeSizeChange} value={shoeSize_value}> <View className="form-item"> <View className="form-item-label">鞋码</View> <View className="form-item-info">{this.dataTrans('shoeSize', info['shoeSize'])}</View> <View className="form-item-suffix"> <Image src={CaretRightPng} /> </View> </View> </Picker> <Picker mode="region" onChange={this.onCityChange} value={0} custom-item="无"> <View className="form-item"> <View className="form-item-label">所在地</View> <View className="form-item-info">{this.dataTrans('city', info['city'])}</View> <View className="form-item-suffix"> <Image src={CaretRightPng} /> </View> </View> </Picker> {/* <View className="form-item" onClick={this.onClickFormItem.bind(this, 'qrcode')}> <View className="form-item-label">二维码展示</View> <View className="form-item-info"></View> <View className="form-item-suffix"> <Image src={CaretRightPng} /> </View> </View> */} <Picker range={bgcolors} range-key="name" onChange={this.onColorChange} value={bgcolor_value}> <View className="form-item"> <View className="form-item-label">背景颜色</View> <View className="form-item-info">{this.dataTrans('bgcolor', info['bgcolor'])}</View> <View className="form-item-suffix"> <Image src={CaretRightPng} /> </View> </View> </Picker> <View className="btn-group"> <View onClick={this.confirm} className="confirm button"> 完成 </View> <View onClick={this.cancel} className="cancel button"> 取消 </View> </View> <Canvas canvasId="canvas" style={`width:${canvasSize.width}px; height: ${canvasSize.height}px;position:fixed;left:3000rpx;`} /> </View> ) } } <file_sep>/src/pages/card-edit-1/index.js import Taro, { Component } from '@tarojs/taro' import { View, Image } from '@tarojs/components' import './index.styl' import CaretRightPng from '../../images/caret_right.png' import modelcard1Png from '../../images/modelcard1.png' import modelcard2Png from '../../images/modelcard2.png' export default class CardEdit1 extends Component { config = { navigationBarTitleText: '模卡信息填写' } componentWillMount () { } componentDidMount () { } componentWillUnmount () { } componentDidShow () { } componentDidHide () { } onClickFormItem(type) { let count = type === 1 ? 9 : type === 2 ? 6 : type === 3 ? 9 : 1 Taro.chooseImage({ count, sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], success (res) { // tempFilePath可以作为img标签的src属性显示图片 const tempFilePaths = res.tempFilePaths if (tempFilePaths.length === count) { Taro.setStorageSync(type + '$card-edit-photos', tempFilePaths) Taro.navigateTo({ url: `/pages/card-edit-3/index?type=${type}` }) } else { Taro.showModal({ title: '温馨提示', content: '请提供模特卡需求的图片数量,在进行下一步。', showCancel: false, confirmText: '知道啦' }) } }, fail (e) { console.log(e) } }) } render () { return ( <View className='page-card-edit-1'> <View className="demo-wrapper" onClick={this.onClickFormItem.bind(this, 1)}> <View className="label">模卡一</View> <Image src={modelcard1Png} className="demo1" /> </View> {/* <View className="demo-wrapper" onClick={this.onClickFormItem.bind(this, 2)}> <View className="label">模卡二</View> <View className="demo2"> <View className="basic-info"> <View className="name">某某某</View> <View className="content"> <View className="label">身高|HEIGHT</View> <View className="value">167cm</View> <View className="label">体重|WEIGHT</View> <View className="value">45kg</View> <View className="label">胸围|BUST</View> <View className="value">88</View> <View className="label">腰围|WAIST</View> <View className="value">88</View> <View className="label">臀围|HIPS</View> <View className="value">88</View> <View className="label">鞋码|SHOES</View> <View className="value">34</View> </View> <View className="qrcode">二维码</View> </View> <View className="imgs-wrapper"> <View className="img1"> <Image src="" /> </View> <View className="img2"> <Image src="" /> </View> <View className="img3"> <Image src="" /> </View> <View className="img4"> <Image src="" /> </View> <View className="img5"> <Image src="" /> </View> <View className="img6"> <Image src="" /> </View> </View> </View> </View> */} <View className="demo-wrapper" onClick={this.onClickFormItem.bind(this, 2)}> <View className="label">模卡二</View> <Image src={modelcard2Png} className="demo2" /> </View> </View> ) } } <file_sep>/src/pages/attention/index.js import Taro, { Component } from '@tarojs/taro' import { View, Image } from '@tarojs/components' import './index.styl' import HeartPng from '../../images/heart.png' import MoneyBagPng from '../../images/money_bag.png' import { USER_MODEL_INFO } from '../../lib/constants' import { api_get_partical_models, api_user_remove_attention } from '../../api' export default class Attention extends Component { constructor() { super(...arguments) this.state = { list: [ { id: 0, avatar: 'https://wx4.sinaimg.cn/orj360/96a79eebgy1fpo3ig1w9qj20c80c83zr.jpg', name: '某某某', popularity: 1258, subscribe: 225874, intro: '坚持不一定会胜利,放弃不一定是认输,人生有很多时候需要的不仅仅是执着,更是回眸一笑的洒脱,加油!' } ] } } config = { navigationBarTitleText: '关注的人' } componentWillMount() { const info = Taro.getStorageSync(USER_MODEL_INFO) this.info = info api_get_partical_models(info.attentions || []).then(res => { if (res.success) { if (res.data.length) { this.setState({ list: res.data }) } else { showToast('无数据', 'none') } } }) } removeAttention(id) { wx.showModal({ title: '提示', content: '是否取消关注', success: res => { if (res.confirm) { api_user_remove_attention(id).then(res => { if(res.success) { Taro.showToast({ title: '已取消关注', icon: 'none', mask: true, duration: 1000 }) let index = this.state.list.findIndex(item => item.id === id) this.state.list.splice(index, 1) this.setState({ list: this.state.list }) Taro.setStorageSync(USER_MODEL_INFO, Object.assign({}, this.info, { attentions: this.state.list.map(item => item.id) })) } }) } } }) } render() { return ( <View className="page-attention"> {this.state.list.map((item, key) => { return ( <View key={key} className="item-wrapper"> <View className="cancel-btn" onClick={this.removeAttention.bind(this, item.id)}>取消关注</View> <View className="avatar-wrapper"> <Image src={item.avatar} /> </View> <View className="info-wrapper"> <View className="name">{item.name}</View> <View className="middle"> <Image src={HeartPng} className="heart" /> <View> 人气值: {item.popularity} </View> <Image src={MoneyBagPng} className="moneybag" /> <View> 赞助值: {item.subscribe} </View> </View> <View className="intro ellipsis">{item.intro}</View> </View> </View> ) })} </View> ) } } <file_sep>/src/pages/info-video-edit/index.js import Taro, { Component } from '@tarojs/taro' import { View, Video } from '@tarojs/components' import './index.styl' import { USER_MODEL_INFO } from '../../lib/constants' import { api_info_edit } from '../../api' import { delayToExec, promisifyUpload, showToast } from '../../lib/utils' export default class InfoVideoEdit extends Component { config = { navigationBarTitleText: '视频编辑' } state = { src: '', info: {}, changed: false } videoCtx = null componentDidShow () { const info = Taro.getStorageSync(USER_MODEL_INFO) this.state.info = info if (info.video) { this.setState({ src: info.video }) this.videoCtx = Taro.createVideoContext('video') this.videoCtx.play() } } select () { wx.chooseVideo({ sourceType: ['album','camera'], maxDuration: 60, camera: 'back', compressed: true, success: res => { console.log(res) this.setState({ src: null }, () => { this.setState({ src: res.data, changed: true }, () => { this.videoCtx.play() }) }) } }) } confirm () { const fn = () => { promisifyUpload(this.state.src).then(res => { api_info_edit({ id: this.state.info.id, video: res.data }).then(res => { if (res.success) { Taro.showToast({ title: '上传成功', duration: 1000, mask: true }) delayToExec(() => { const info = Taro.getStorageSync(USER_MODEL_INFO) Taro.setStorageSync(USER_MODEL_INFO, Object.assign(info, { video: this.state.src})) Taro.navigateBack() }, 1000) } }) }) } if (this.state.changed) { fn() } else { showToast('请先选择视频', 'none') } } render () { const { src } = this.state return ( <View className='video-edit'> {src ? <Video id="video" src={src}></Video> : <Video src={null}></Video>} <View className="upload-btn" onClick={this.select}>重新选择视频</View> <View className="confirm-btn" onClick={this.confirm}>确定</View> </View> ) } } <file_sep>/src/app.js import Taro, { Component } from '@tarojs/taro' import Index from './pages/index' import './app.styl' class App extends Component { config = { pages: [ 'pages/index/index', 'pages/card-edit-2/index', 'pages/card-edit-1/index', 'pages/card-edit-3/index', 'pages/wx-cropper/index', 'pages/advice/index', 'pages/attention/index', 'pages/id-verify/index', 'pages/info-exp-edit/index', 'pages/resume/index', 'pages/bind-mobile/index', 'pages/info-basic-edit/index', 'pages/view-cover/index', 'pages/cash/index', 'pages/view-avatar/index', 'pages/info-video-edit/index', 'pages/info-photo-edit/index', 'pages/subscribe/index', 'pages/self-center/index', 'pages/search/index' ], window: { backgroundTextStyle: 'light', navigationBarBackgroundColor: '#fff', navigationBarTitleText: '芃叔小简历', navigationBarTextStyle: 'black' }, tabBar: { list: [ { pagePath: 'pages/index/index', text: '首页', iconPath: './images/home_home.png', selectedIconPath: './images/home_home_active.png' }, { pagePath: 'pages/self-center/index', text: '个人中心', iconPath: './images/home_person.png', selectedIconPath: './images/home_person_active.png' } ], color: '#BDC0C5', selectedColor: '#000', backgroundColor: '#fff', borderStyle: 'black', position: 'bottom' } } componentDidMount () {} componentDidShow () {} componentDidHide () {} componentCatchError () {} render () { return ( <Index /> ) } } Taro.render(<App />, document.getElementById('app')) <file_sep>/src/pages/resume/index.js import Taro, { Component } from '@tarojs/taro' import { View, Swiper, SwiperItem, Image, Text, Button } from '@tarojs/components' import cn from 'classnames' import SelfInfo from '../../components/self-info' import './index.styl' import HeartPng from '../../images/heart.png' import MoneyBagPng from '../../images/money_bag.png' import FemalePng from '../../images/female.png' import MalePng from '../../images/male.png' import IdVerify2Png from '../../images/verify_icon.png' import NotDonatePng from '../../images/resume_not_donate.png' import DonatePng from '../../images/resume_donate.png' import NotPopuPng from '../../images/resume_not_popu.png' import PopuPng from '../../images/resume_popu.png' import SharePng from '../../images/resume_share.png' import MobileWhitePng from '../../images/self_center_mobile_white.png' import * as api from '../../api' import { debounce } from '../../lib/utils' import { LOGIN_STATUS, USER_MODEL_INFO } from '../../lib/constants'; export default class Resume extends Component { constructor(props) { super(props) this.state = { swipers: [], currTab: 1, info: { posters: [] }, isAttention: true } } handleTabClick(index) { this.setState({ currTab: index }) } config = { navigationBarTitleText: '个人简历' } getIfAttention() { api.api_user_if_follow(this.state.info.id).then(res => { if (res.success) { this.setState({ isAttention: res.data }) } }) } makePhoneCall (phoneNumber) { if (phoneNumber) { Taro.makePhoneCall({ phoneNumber }) } else { Taro.showToast({ title: '未绑定手机号', mask: true, duration: 1000 }) } } onShareAppMessage() { return { title: '某某某|芃叔小简历', imageUrl: 'http://t2.hddhhn.com/uploads/tu/201610/198/hkgip2b102z.jpg', path: '/pages/index/index?redirect=/pages/resume/index' } } previewPhotos(current) { wx.previewImage({ urls: this.state.info.photos.map(item => item.src), current }) } componentDidMount() { const id = this.$router.params.id api.api_info(id).then(res => { if (res.success) { this.setState({ info: res.data }, this.getIfAttention) } }) } debouncer = debounce((type) => { api[`api_model_${type}`](this.state.info.id).then(res => { if(res.success) { Taro.showToast({ title: type === 'hot' ? '点赞成功' : '打气成功' }) } }) }, 200) touchStart(type) { this.setState({ [`${type}ing`]: true }) } touchEnd(type) { this.setState({ [`${type}ing`]: false }) this.debouncer(type) } addAttention() { const userId = Taro.getStorageSync(LOGIN_STATUS).id const modelId = this.state.info.id api.api_user_attention({ userId, modelId }).then(res => { if (res.success) { Taro.showToast({ title: '关注成功' }) this.setState({ isAttention: true }) // 更新本地缓存 let modelInfo = Taro.getStorageSync(USER_MODEL_INFO) modelInfo.attentions.push(modelId) Taro.setStorageSync(USER_MODEL_INFO, modelInfo) } }) } render() { const { info, currTab } = this.state let mobile = info.bindMobile && info.bindMobile.number ? info.bindMobile.number : '未绑定' return ( <View className="resume"> <Swiper className="swiper" indicatorColor="#999" indicatorActiveColor="#333" circular indicatorDots={false} autoplay > {info.posters.map((item, key) => { return ( <SwiperItem key={key}> <View style={{ backgroundImage: `url("${item.src}")` }} /> </SwiperItem> ) })} </Swiper> <View className="parallax-card"> <View className="avatar" style={{ backgroundImage: `url("${info.avatar}")` }} /> <View className="info1"> <View className="first"> <View className="name">{info.name}</View> <Image className="sex" src={info.sex === 1 ? MalePng : FemalePng} /> <View className="id-wrapper" style={{visibility: info.idVerify && info.idVerify.isPass ? 'visible' : 'hidden'}}> <Image src={IdVerify2Png} className="id-verify-icon" /> <Text className="verify-text">实名认证</Text> </View> </View> <View className="second"> <View className="btn-group" onClick={this.makePhoneCall.bind(this, info.bindMobile.number)}> <Image src={MobileWhitePng} className="btn" /> <View className="divider-vertical" /> <Text className="mobile"> {mobile} </Text> </View> </View> </View> <View className="divider-horizontal" /> <View className="info2"> <View className="popularity"> <Image src={HeartPng} className="heart icon" /> <View> 人气值: {info.popularity} </View> </View> <View className="divider-vertical" /> <View className="subscribe"> <Image src={MoneyBagPng} className="money-bag icon" /> <View> 赞助值: {info.subscribe} </View> </View> </View> <View className="info3">{info.intro}</View> <View className="tabs"> <View className={cn({ active: currTab === 1 })} onClick={this.handleTabClick.bind(this, 1)} > <Text>个人简介</Text> </View> <View className={cn({ active: currTab === 2 })} onClick={this.handleTabClick.bind(this, 2)} > <Text>相册</Text> </View> </View> </View> {currTab === 1 ? ( <SelfInfo info={info} /> ) : ( <View className="container"> <View className="photos-wrapper"> {this.state.info.photos.map((item, key) => { return ( <View key={key} className="photo" onClick={this.previewPhotos.bind(this, item.src)} ><Image className="img" mode="aspectFit" src={item.src} /></View> ) })} </View> {/* <Loadmore /> */} </View> )} <View className="menu"> <Image className={cn({ active: this.state.hoting })} src={this.state.hoting ? DonatePng : NotDonatePng} onTouchStart={this.touchStart.bind(this, 'hot')} onTouchEnd={this.touchEnd.bind(this,'hot')} /> <Image src={this.state.isAttention ? PopuPng : NotPopuPng} onClick={this.addAttention} /> <Button className="transparent" open-type="share"><Image src={SharePng} /></Button> </View> </View> ) } } <file_sep>/src/pages/card-edit-3/index.js import Taro, { Component } from '@tarojs/taro' import { View, Image } from '@tarojs/components' import update from 'immutability-helper' import './index.styl' export default class CardEdit22 extends Component { constructor() { super(...arguments) this.type = +this.$router.params.type || 1 this.state = { imgs: Taro.getStorageSync(this.type + '$card-edit-photos') || [], currDragIndex: -1, startpos: { x: 0, y: 0 }, endpos: { x: 0, y: 0 } } this.selectedToEditId = -1 } config = { navigationBarTitleText: '图片编辑' } componentWillMount() {} componentDidMount() {} componentWillUnmount() {} componentDidShow() {} componentDidHide() {} handleTouchStart = (idx, e) => { this.setState({ currDragIndex: idx, startpos: { x: e.changedTouches[0].clientX, y: e.changedTouches[0].clientY } }) } handleTouchMove = e => { this.setState({ endpos: { x: e.changedTouches[0].clientX, y: e.changedTouches[0].clientY } }) } handleTouchEnd = e => { const idx = this.state.currDragIndex const x = e.changedTouches[0].clientX const y = e.changedTouches[0].clientY const img = this.state.imgs[idx] this.setState({ currDragIndex: -1, startpos: { x: 0, y: 0 }, endpos: { x: 0, y: 0 } }) for (let i = 0; i < this.state.imgs.length; i++) { if (i === idx) continue Taro.createSelectorQuery() .select('#node' + i) .boundingClientRect(res => { if (x <= res.right && x >= res.left && y >= res.top && y <= res.bottom) { this.setState( update(this.state, { imgs: { $splice: [[idx, 1], [i, 0, img]] } }) ) } }) .exec() } } handleClick = (idx) => { Taro.setStorageSync('cropper__img', this.state.imgs[idx]) Taro.navigateTo({ url: '/pages/wx-cropper/index' }) this.selectedToEditIdx = idx } componentDidShow = () => { let img = Taro.getStorageSync('cropper_complete_url') if (img && this.selectedToEditIdx !== -1) { let imgsCopy = this.state.imgs imgsCopy.splice(this.selectedToEditIdx, 1, img) this.setState({ imgs: imgsCopy }) this.selectedToEditIdx = -1 Taro.removeStorageSync('cropper_complete_url') } } cancel() { Taro.navigateBack() } confirm() { Taro.setStorageSync(this.type + '$card-edit-photos', this.state.imgs) Taro.navigateTo({ url: `/pages/card-edit-2/index?type=${this.type}` }) } render() { const { currDragIndex, imgs, startpos, endpos } = this.state return ( <View className="page-edit-3" onTouchMove={this.handleTouchMove} onTouchEnd={this.handleTouchEnd}> <View className="wrapper"> {imgs.map((item, idx) => { let translateX = endpos.x > 0 && startpos.x > 0 ? endpos.x - startpos.x : 0 let translateY = endpos.y > 0 && startpos.y > 0 ? endpos.y - startpos.y : 0 return ( <View className="item" key={idx} id={`node${idx}`} dataIdx={idx} onClick={this.handleClick.bind(this, idx)} onTouchStart={this.handleTouchStart.bind(this, idx)} style={{ transform: currDragIndex === idx ? `translate(${translateX}px,${translateY}px)` : undefined }} > <Image src={item} mode="aspectFit" /> </View> ) })} </View> <View className="btn-group"> <View onClick={this.confirm} className="confirm button"> 下一步 </View> <View onClick={this.cancel} className="cancel button"> 返回 </View> </View> <View className="help-text">温馨提示:所有图片需进行编辑</View> </View> ) } } <file_sep>/src/components/model-card/index.js import Taro, { Component } from '@tarojs/taro' import { View, Image, Text } from '@tarojs/components' import './index.styl' export default class ModelCard extends Component { handleClick(e) { this.props.onClick(e) } render() { const { num, imgSrc, name, weight, height, text, icon } = this.props.model || {} return ( <View className="model-card" onClick={this.handleClick}> <View className="popularity"> <Image src={icon} /> <Text>{text}:</Text> <Text>{num}</Text> </View> <View className="img"> <Image src={imgSrc || ''} mode="aspectFit" /> </View> <View className="info"> <Text>{name}</Text> <Text> {height} cm </Text> <Text> {weight} kg </Text> </View> </View> ) } } <file_sep>/src/components/form-item/index.js import Taro, { Component } from '@tarojs/taro' import { View } from '@tarojs/components' import cn from 'classnames' import CaretRightPng from '../../images/caret_right.png' export default class FormItem extends Component { render() { const { name, label, value, className } = this.props const caretStyle = { backgroundImage: `url("${CaretRightPng}")` } return ( <View className={cn('form-item', className)} onClick={this.props.onClick.bind(this, name)}> <View className="form-item-label">{label}</View> <View className="form-item-info">{value}</View> <View className="form-item-suffix" style={caretStyle} /> </View> ) } } <file_sep>/src/components/self-info/experiences.js import Taro, { Component } from '@tarojs/taro' import { View, Image } from '@tarojs/components' import ListPng from '../../images/list.png' import ActionPng from '../../images/action.png' import PersonOPng from '../../images/person_o.png' import PeoplePng from '../../images/people.png' import './experiences.styl' export default class Experiences extends Component { defaultProps = { info: [ { year: 2013, name: '非诚勿扰', type: '电影', director: '冯小刚', character: '王嘉涵', coActor: '葛优 舒淇 郑恺' } ] } render() { const exps = this.props.info || this.defaultProps.info return ( <View className="experiences-wrapper"> {exps.map((exp, idx) => { return ( <View key={idx} className="item"> <View className="name">{exp.name}</View> <View className="content"> <View> <Image src={ListPng} /> 类型 </View> <View>{exp.type}</View> </View> <View className="content"> <View> <Image src={ActionPng} /> 导演 </View> <View>{exp.director}</View> </View> <View className="content"> <View> <Image src={PersonOPng} /> 饰演角色 </View> <View>{exp.character}</View> </View> <View className="content"> <View> <Image src={PeoplePng} /> 合作演员 </View> <View>{exp.coActor}</View> </View> </View> ) })} </View> ) } } <file_sep>/src/components/self-info/index.js import Taro, { Component } from '@tarojs/taro' import { View, Image, Video } from '@tarojs/components' import cn from 'classnames' import './index.styl' import PersonPng from '../../images/person.png' import CakePng from '../../images/cake.png' import HeightPng from '../../images/height.png' import WeightPng from '../../images/weight.png' import BWHPng from '../../images/bwh.png' import LocationPng from '../../images/location.png' import DegreePng from '../../images/degree.png' import JobPng from '../../images/job.png' import CrownPng from '../../images/crown.png' import VideoPng from '../../images/black_video.png' import ExpPng from '../../images/yanyijingli.png' import CaretRightPng from '../../images/caret_right.png' import PointPng from '../../images/point.png' import Experiences from './experiences' export default class SelfInfo extends Component { defaultProps = { info: { id: 0, poster: 'https://www.10wallpaper.com/wallpaper/1366x768/1609/kenza_mel_beach_photography-Beauty_poster_wallpaper_1366x768.jpg', avatar: 'https://wx4.sinaimg.cn/orj360/96a79eebgy1fpo3ig1w9qj20c80c83zr.jpg', name: '某某某', age: 20, height: 168, weight: 45, idVerify: true, sex: 0, popularity: 1258, subscribe: 225874, intro: '坚持不一定会胜利,放弃不一定是认输,人生有很多时候需要的不仅仅是执着,更是回眸一笑的洒脱,加油!', bwh: [45, 48, 52], city: '北京市', school: '北京电影学院', exp: '三年平面模特', specialities: ['唱歌', '跳舞', '书法'], actingExperience: { id: [ { year: 2013, name: '非诚勿扰', type: '电影', director: '冯小刚', character: '王嘉涵', coActor: '葛优 舒淇 郑恺' }, { year: 2013, name: '非诚勿扰', type: '电影', director: '冯小刚', character: '王嘉涵', coActor: '葛优 舒淇 郑恺' }, { year: 2014, name: '非诚勿扰', type: '电影', director: '冯小刚', character: '王嘉涵', coActor: '葛优 舒淇 郑恺' } ], other: `2013年,范冰冰蝉联2014福布斯中国名人榜第一位,5月23日,布莱恩·辛格导演,休·杰克曼;詹姆斯·麦卡沃伊;迈克尔·法斯宾德主演的电影《X战警:逆转未来》全球同步上映,范冰冰在其中饰演“闪烁女Blink”一角。` } } } state = { selectedExp: 0 } handleClick(idx) { this.setState({ selectedExp: idx === this.state.selectedExp ? -1 : idx }) } render() { const info = this.props.info || this.defaultProps.info const years = {} info.actingExperience && info.actingExperience.list && info.actingExperience.list.forEach(item => { if (!years[item.year]) years[item.year] = [] years[item.year].push(item) }) return ( <View className="self-info"> <View className="basic wrapper"> <View className="header"> <Image src={PersonPng} className="person" /> 基本信息 </View> <View className="first"> <View> <Image src={CakePng} className="icon age" /> <View>{info.age}岁</View> </View> <View> <Image src={HeightPng} className="icon height" /> <View> {info.height} cm </View> </View> <View> <Image src={WeightPng} className="icon weight" /> <View> {info.weight} kg </View> </View> <View> <Image src={BWHPng} className="icon bwh" /> <View>{info.bwh ? info.bwh.join('/') : ''}</View> </View> </View> <View className="middle-line" /> <View className="second"> <View className="item"> <Image className="location" src={LocationPng} /> {info.city} </View> <View className="divider-line" /> <View className="item"> <Image className="degree" src={DegreePng} /> {info.school} </View> <View className="divider-line" /> <View className="item"> <Image className="job" src={JobPng} /> {info.exp} </View> </View> </View> <View className="specialities wrapper"> <View className="header"> <Image src={CrownPng} className="crown" /> 特长 </View> <View className="inner-wrapper"> {info.specialities.map((item, key) => { return ( <View className="speciality" key={key}> {item} </View> ) })} </View> </View> <View className="video wrapper"> <View className="header"> <Image src={VideoPng} className="video-image" /> 个人视频 </View> <View className="inner-wrapper"> <Video src={info.video} /> </View> </View> <View className="exp wrapper"> <View className="header"> <Image src={ExpPng} className="crown" /> 演艺经历 </View> <View className="inner-wrapper accordion-wrapper"> {Object.keys(years).map((year, idx) => { let everyYears = years[year] return ( <View className={cn('accordion-item', { active: this.state.selectedExp === idx })} key={idx} > <View className="icon"> <Image src={PointPng} /> </View> <View className="content"> <View className="header" onClick={this.handleClick.bind(this, idx)}> {year}年 <Image src={CaretRightPng} className="caret" /> </View> <View className="body"> <Experiences info={everyYears || []} /> <View className="other-title">其他</View> <View className="other">{info.actingExperience.other}</View> </View> </View> </View> ) })} </View> </View> </View> ) } } <file_sep>/src/pages/subscribe/index.js import Taro, { Component } from '@tarojs/taro' import { View, Text } from '@tarojs/components' import './index.styl' import SubscribePng from '../../images/subscribe_ticket.png' export default class Index extends Component { config = { navigationBarTitleText: '赞助我们' } state = { tickets: [ { type: 1, price: 1, months: 1, intros: ['日升1点赞助值', '可使用模特卡,打气加5次'] }, { type: 2, price: 30, months: 1, intros: ['日升1点赞助值', '可使用模特卡,打气加5次'] }, { type: 3, price: 150, months: 6, intros: ['日升1点赞助值', '可互相聊天使用模特卡打气五次并送一条10图形象照和自我介绍拍摄'] } ] } componentWillMount() {} componentDidMount() {} componentWillUnmount() {} componentDidShow() {} componentDidHide() {} render() { return ( <View className="subscribe"> {this.state.tickets.map((item, key) => { return ( <View key={key} className="ticket" style={{backgroundImage: `url("${SubscribePng}")`}}> <View className="left"> <Text>{item.price}</Text> {item.months > 1 ? ( <Text> 元/ {item.months} 个月 </Text> ) : ( <Text>元/月</Text> )} </View> <View className="divider" /> <View className="intros"> {item.intros.map((intro, index) => { return <View key={index}>{intro}</View> })} </View> <View className="right">立即开通</View> </View> ) })} </View> ) } } <file_sep>/src/pages/info-exp-edit/index.js import Taro, { Component } from '@tarojs/taro' import { View, Input, Picker, Textarea, Image } from '@tarojs/components' import update from 'immutability-helper' import './index.styl' import CaretRightPng from '../../images/caret_right.png' import { experiences_types as types } from '../../helper/types' import RabbishPng from '../../images/rabbish.png' import { api_info_edit } from '../../api' import { showToast, delayToExec } from '../../lib/utils' import { USER_MODEL_INFO } from '../../lib/constants' export default class ExpEdit extends Component { state = { experiences: [], other: '' } componentDidMount() { const info = Taro.getStorageSync(USER_MODEL_INFO) this.info = info this.setState({ experiences: info.actingExperience.list, other: info.actingExperience.other }) } onDateChange(index, e) { const val = e.detail.value this.setState(update(this.state, { experiences: { [index]: { year: { $set: val } } } })) } deleteExp(idx) { this.setState(update(this.state, { experiences: { $splice: [[idx, 1]] } })) } onTypeChange(index, e) { const idx = e.detail.value const type = types[idx] this.setState(update(this.state, { experiences: { [index]: { type: { $set: type } } } })) } handleChange = (key, idx, e) => { const val = e.target.value this.setState({ experiences: update(this.state.experiences, { [idx]: { [key]: { $set: val } } }) }) } handleOtherChange = (e) => { this.setState({ other: e.target.value }) } handleAdd = () => { this.setState(update(this.state, { experiences: { $push: [{ year: 2018, name: '', type: '', director: '', character: '', coActor: '' }] } })) } dataTrans(key, value) { let i = value if (key === 'coActor') { i = value.join(' ') } else if (key === 'year') { i = value + '年' } return i } complete() { const { experiences, other } = this.state let actingExperience = { list: experiences, other } api_info_edit({ id: this.info.id, actingExperience }).then(res => { if (res.success) { showToast('保存成功') delayToExec(() => Taro.navigateBack()) Taro.setStorageSync(USER_MODEL_INFO, Object.assign(this.info, { actingExperience })) } }) } config = { navigationBarTitleText: '演艺经历编辑' } render() { const { experiences } = this.state return ( <View className="page-exp-edit"> {experiences.map((item, idx) => { const { year, name, type, director, character, coActor } = item return ( <View className="exp-wrapper" key={idx}> <View className="close-wrapper"> <View className="close-btn" onClick={this.deleteExp.bind(this, idx)}> <Image src={RabbishPng} /> </View> <Picker mode="date" fields="year" start="1970-01-01" end="2019-01-01" value={year} onChange={this.onDateChange.bind(this, idx)}> <View className="form-item year"> <View className="form-item-label">{year}年</View> <View className="form-item-info">选择年份</View> <View className="form-item-suffix"><Image src={CaretRightPng}></Image></View> </View> </Picker> </View> <View className="form-item"> <View className="form-item-label">影片名称</View> <Input value={name} className="form-item-info" onInput={this.handleChange.bind(this, 'name', idx)} /> <View className="form-item-suffix"></View> </View> <Picker range={types} value={name} onChange={this.onTypeChange.bind(this, idx)}> <View className="form-item"> <View className="form-item-label">类型</View> <View className="form-item-info">{type}</View> <View className="form-item-suffix"><Image src={CaretRightPng}></Image></View> </View> </Picker> <View className="form-item"> <View className="form-item-label">导演</View> <Input value={director} className="form-item-info" onInput={this.handleChange.bind(this, 'director', idx)} /> <View className="form-item-suffix"></View> </View> <View className="form-item"> <View className="form-item-label">饰演角色</View> <Input value={character} className="form-item-info" onInput={this.handleChange.bind(this, 'character', idx)} /> <View className="form-item-suffix"></View> </View> <View className="form-item"> <View className="form-item-label">合作演员</View> <Input value={coActor} className="form-item-info" onInput={this.handleChange.bind(this, 'coActor', idx)} /> <View className="form-item-suffix"></View> </View> </View> ) })} <View className="add-wrapper"> <View className="button add-exp" onClick={this.handleAdd}><View>+</View>增加经历</View> </View> <View className="other-exp"> <View className="form-item"> <View className="form-item-label">其他介绍</View> <View className="form-item-info"></View> <View className="form-item-suffix" /> </View> <Textarea value={this.state.other} onInput={this.handleOtherChange} /> <View className="divider-horizontal" /> </View> <View className="bottom-btn button" onClick={this.complete}>完成</View> </View> ) } } <file_sep>/src/pages/cash/index.js import Taro, { Component } from '@tarojs/taro' import { View, Image } from '@tarojs/components' import './index.styl' import BgPng from '../../images/cash_bg.png' import KefuPng from '../../images/cash_kefu.png' import { formatCurrency, showToast } from '../../lib/utils' import { USER_MODEL_INFO } from '../../lib/constants'; export default class Cash extends Component { config = { navigationBarTitleText: '提现' } state = { info: { cash: '999999' }, wechat: "5598356" } componentDidMount() { const info = Taro.getStorageSync(USER_MODEL_INFO) this.setState({ info }) } copyWechat() { Taro.setClipboardData({ data: this.state.wechat, success (res) { showToast('复制成功') } }) } render() { return ( <View className="page-cash"> <View className="cash-wrapper"> <Image src={BgPng} className="bg" /> <View className="money">{formatCurrency(this.state.info.cash)}</View> <View className="helper-text">可提现额度(元)</View> </View> <View className="helper-text-wrapper"> <Image src={KefuPng} /> <View>提现需要联系客服人员,微信:</View> <View>{this.state.wechat}</View> </View> <View className="button" onClick={this.copyWechat}>复制客服微信</View> </View> ) } } <file_sep>/src/pages/bind-mobile/index.js import Taro, { Component } from '@tarojs/taro' import { View, Image, Input } from '@tarojs/components' import update from 'immutability-helper' import './index.styl' import BgPng from '../../images/bind_mobile_bg.png' import ClockPng from '../../images/bind_mobile_clock.png' import MobilePng from '../../images/bind_mobile_mobile.png' import { USER_MODEL_INFO } from '../../lib/constants' import { showToast, delayToExec } from '../../lib/utils' import { api_info_edit } from '../../api' export default class BindMobile extends Component { config = { navigationBarTitleText: '绑定手机' } state = { info: { bindMobile: { number: '' } }, disabled: false } componentDidMount() { const info = Taro.getStorageSync(USER_MODEL_INFO) this.setState({ info }) if (info.bindMobile.isPass === undefined && info.bindMobile.number) { this.setState({ disabled: true }) } } handleChange(e) { this.setState({ info: update(this.state.info, { bindMobile: { number: { $set: e.target.value } } }) }) } submit() { if (this.state.disabled) { showToast('请耐心等待审核结果', 'none') delayToExec(() => Taro.navigateBack()) return } const { id, bindMobile } = this.state.info api_info_edit({ id, bindMobile }).then(res => { if (res.success) { showToast('保存成功') delayToExec(() => Taro.navigateBack()) Taro.setStorageSync(USER_MODEL_INFO, this.state.info) } }) } cancel() { Taro.navigateBack() } render() { return ( <View className="page-bind-mobile"> <View className="banner-back"> <Image className="bg" src={BgPng} /> <View className="inner"> <Image src={ClockPng} /> <View>待客服核实后,将为您绑定。</View> </View> </View> <View className="suspension"> <Image src={MobilePng} /> <Input placeholder="请输入手机号" placeholderStyle={{color: '#575757', lineHeight: '44px'}} onInput={this.handleChange} value={this.state.info.bindMobile.number} disabled={this.state.disabled} /> </View> <View className="btns-wrapper"> <View className="button submit" onClick={this.submit}>提交</View> <View className="button cancel" onClick={this.cancel}>取消</View> </View> </View> ) } } <file_sep>/src/lib/utils.js import Taro from '@tarojs/taro' export const delayToExec = function(fn, delay = 1500) { let timer = setTimeout(() => { fn.apply(this, Array.from(arguments)) clearTimeout(timer) }, delay) } export const getUploadResAbsAddress = function(name) { return `${URL_PREFIX}/upload/${name}` } // 相当于oss的上传接口 export const promisifyUpload = function(filePath) { return new Promise((resolve, reject) => { wx.uploadFile({ url: URL_PREFIX + '/v1/upload/', filePath, name: 'file', success: resolve, fail: reject }) }) } export const uploadFiles = function(files = []) { return Promise.all(files.map(file => promisifyUpload(file))) } export const showToast = function(title, icon = 'success') { Taro.showToast({ title, mask: true, duration: 1500, icon }) } export const formatCurrency = function formatCurrency(str) { return `${str.slice(0, -2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}.${str.slice(-2)}` } export const pick = function pick(obj, arr) { let o = {} arr.forEach(key => o[key] = obj[key]) return o } export const debounce = function debounce(fn, delay = 50) { let timer = null let context = this return function() { let args = Array.from(arguments) if (timer) { clearTimeout(timer) } timer = setTimeout(() => { fn.apply(context, args) clearTimeout(timer) }, delay) } }<file_sep>/src/pages/advice/index.js import Taro, { Component } from '@tarojs/taro' import { View, Textarea, Input } from '@tarojs/components' import './index.styl' import { USER_MODEL_INFO, LOGIN_STATUS } from '../../lib/constants' import { showToast, delayToExec } from '../../lib/utils' import { api_advice_add } from '../../api' export default class Advice extends Component { config = { navigationBarTitleText: '投诉建议' } state = { contact: '', content: '' } submit() { const loginStatus = Taro.getStorageSync(LOGIN_STATUS) const { content, contact } = this.state api_advice_add({ userId: loginStatus.id, content, contact }).then(res => { if (res.success) { showToast('提交成功') delayToExec(Taro.navigateBack) } }) } handleChange(key, e) { this.setState({ [key]: e.target.value }) } cancel() { Taro.navigateBack() } render() { return ( <View className="page-advice"> <View className="textarea-wrapper"> <Textarea placeholder="请输入您的意见或建议" placeholder-style="color: #BABABA" onInput={this.handleChange.bind(this, 'content')} /> </View> <View className="divider-horizontal" /> <View className="input-wrapper"> <Input placeholder="请输入您的qq、微信、邮箱等联系方式,方便我们与您联系" placeholder-style="color: #CBCBCB" onInput={this.handleChange.bind(this, 'contact')}/> </View> <View className="btns-wrapper"> <View className="button submit" onClick={this.submit}>提交</View> <View className="button cancel" onClick={this.cancel}>取消</View> </View> </View> ) } } <file_sep>/src/pages/view-cover/index.js import Taro, { Component } from '@tarojs/taro' import { View } from '@tarojs/components' import './index.styl' import { promisifyUpload, delayToExec, showToast } from '../../lib/utils' import { USER_MODEL_INFO } from '../../lib/constants' import { api_info_edit } from '../../api' export default class ViewPoster extends Component { config = { navigationBarTitleText: '更换封面图片' } state = { info: { cover: 'http://t2.hddhhn.com/uploads/tu/20150402/220ZQ614-0.jpg' } } componentDidMount() { this.setState({ info: Taro.getStorageSync(USER_MODEL_INFO) }) } selectImg = () => { return new Promise(resolve => { Taro.chooseImage({ count: 1, sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], success: res => { this.setState({ info: Object.assign({}, this.state.info, { cover: res.tempFilePaths[0] }) }, resolve) } }) }) } upload = () => { promisifyUpload(this.state.info.cover).then(res => { const { id } = this.state.info api_info_edit({ id, cover: res.data }).then(res => { if (res.success) { Taro.setStorageSync(USER_MODEL_INFO, this.state.info) showToast('保存成功') delayToExec(() => Taro.navigateBack()) } }) }) } selectImgAndUpload() { this.selectImg().then(this.upload) } cancel() { Taro.navigateBack({ delta: 1 }) } render() { return ( <View className="view-poster"> <View style={{ backgroundImage: `url("${this.state.info.cover}")` }} className="img" /> <View className="btn-wrapper"> <View className="upload-btn" onClick={this.selectImgAndUpload}> 更换封面图片 </View> <View className="confirm-btn" onClick={this.cancel}> 取消 </View> </View> </View> ) } }
a5756be22f97e40006a38d2f4d6573cb14c6bea1
[ "JavaScript" ]
25
JavaScript
Cecil0o0/miniprogram1
f3695a0e7b5cf754938e0d449436279735541627
2e78a90611eaf418f6179b276a1224b61c79a86a
refs/heads/master
<repo_name>TahasinHafizAveins/FinancR<file_sep>/financrr/src/main/java/com/forbitbd/financrr/ui/finance/accountAdd/AddAccountFragment.java package com.forbitbd.financrr.ui.finance.accountAdd; import android.app.Dialog; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.AppCompatSpinner; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.Fragment; import com.forbitbd.androidutils.models.Project; import com.forbitbd.androidutils.utils.Constant; import com.forbitbd.financrr.R; import com.forbitbd.financrr.models.Account; import com.forbitbd.financrr.ui.finance.FinanceActivity; import com.forbitbd.financrr.ui.finance.account.AccountFragment; import com.google.android.material.button.MaterialButton; import com.google.android.material.textfield.TextInputLayout; /** * A simple {@link Fragment} subclass. */ public class AddAccountFragment extends DialogFragment implements AddAccountContract.View, View.OnClickListener { private EditText etName; private TextInputLayout tiName; private AppCompatSpinner spType; private AddAccountPresenter mPresenter; TextView tvTitle; MaterialButton btnSave,btnCancel; private Account account; private Project project; public AddAccountFragment() { // Required empty public constructor } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPresenter = new AddAccountPresenter(this); this.account = (Account) getArguments().getSerializable(Constant.ACCOUNT); this.project = (Project) getArguments().getSerializable(Constant.PROJECT); } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { LayoutInflater inflater = LayoutInflater.from(getContext()); View view = inflater.inflate(R.layout.fragment_add_account, null); initView(view); AlertDialog alertDialog = new AlertDialog.Builder(getActivity(), R.style.MyDialog).create(); //AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), R.style.ThemeOverlay_AppCompat_Dialog); alertDialog.setView(view); return alertDialog; } private void initView(View view) { btnCancel = view.findViewById(R.id.cancel); btnSave = view.findViewById(R.id.save); tvTitle = view.findViewById(R.id.title); etName = view.findViewById(R.id.account_name); tiName = view.findViewById(R.id.ti_account_name); spType = view.findViewById(R.id.sp_types); spType.setAdapter(new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.account_type))); btnSave.setOnClickListener(this); btnCancel.setOnClickListener(this); if(account!=null){ mPresenter.bind(account); } } @Override public void onClick(View view) { if(view==btnSave){ String name = etName.getText().toString().trim(); if(account==null){ account = new Account(); } account.setProject(project.get_id()); account.setName(name); account.setType(spType.getSelectedItemPosition()); boolean valid = mPresenter.validate(account); if(!valid){ return; } if(account.get_id()!=null){ mPresenter.updateAccount(account); }else{ mPresenter.saveAccount(account); } }else if(view==btnCancel){ dismiss(); } } @Override public void bind(Account account) { etName.setText(account.getName()); spType.setSelection(account.getType()); tvTitle.setText("Account Update Form"); btnSave.setText("Update"); } @Override public void showToast(String message) { //Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show(); etName.requestFocus(); tiName.setError(message); } @Override public void clearPreError() { tiName.setErrorEnabled(false); } @Override public void showDialog() { if(getParentFragment() instanceof AccountFragment){ AccountFragment af = (AccountFragment) getParentFragment(); af.showDialog(); } } @Override public void hideDialog() { if(getParentFragment() instanceof AccountFragment){ AccountFragment af = (AccountFragment) getParentFragment(); af.hideDialog(); } } @Override public void complete(Account account) { dismiss(); if(getActivity() instanceof FinanceActivity){ FinanceActivity fa = (FinanceActivity) getActivity(); fa.addAccount(account); } } @Override public void updateAccountInAdapter(Account account) { dismiss(); if(getParentFragment() instanceof AccountFragment){ AccountFragment af = (AccountFragment) getParentFragment(); af.updateAccountInAdapter(account); } } } <file_sep>/financrr/src/main/java/com/forbitbd/financrr/ui/finance/FinancePresenter.java package com.forbitbd.financrr.ui.finance; public class FinancePresenter implements FinanceContract.Presenter { private FinanceContract.View mView; public FinancePresenter(FinanceContract.View mView) { this.mView = mView; } @Override public void filter(String query) { mView.filter(query); } @Override public void showAccountAddDialog() { mView.showAccountAddDialog(); } @Override public void startAddTransactionActivity() { mView.startAddTransactionActivity(); } @Override public void startFinanceReportActivity() { mView.startFinanceReportActivity(); } }
9f09608732d28b46918f31551ac7cd1e1871adaf
[ "Java" ]
2
Java
TahasinHafizAveins/FinancR
d2b5cffb18d19eec2a279d7922b5438ef06c24a1
6039c7fb588ef0f2258fe12e7ad7456ad89ea644
refs/heads/master
<repo_name>y-2-j/DreamTeam<file_sep>/public_static/account.js var topper; var content; var un; var tn; var balance=100; var purse; var players=[]; var auctiontable; var teamdisplay; var myplayers; var myplay=[]; var nextpg; var modalhead; var modaltext; var fillun; $(function () { teamdisplay=$('#team'); purse=$('#balance'); auctiontable=$('#auctiontable'); myplayers=$('#myplayers'); nextpg=$('#nextpg'); modalhead=$('#modaltitle'); modaltext=$('#modalfiller'); fillun=$('#username'); DisplayLists(); retrieveNames(); balanceColor(); teamshow(); getPlayers(DisplayLists); pursedisplay(); DisplayLists(); nextpg.click(function () { }); }); function DisplayLists() { DisplayPlayers(); displayMyPlayers(); } function retrieveNames() { let u =localStorage.getItem('username'); let t =localStorage.getItem('teamname'); un=JSON.parse(u); tn=JSON.parse(t); } function balanceColor() { if(balance>70){ purse.attr('class','badge badge-success'); } else if(balance>30){ purse.attr('class','badge badge-warning') } else{ purse.attr('class','badge badge-danger'); } } function teamshow() { fillun.append($(` <span> ${un}!</span> `)); teamdisplay.append($(` <span class="badge badge-info"><h3 class="regheading">${tn}</h3></span> `)); } function pursedisplay() { purse.empty(); purse.append($(` <span><h4 class="regheading2">Remaining Balance: ${balance}<i class="fa fa-money"></i> </h4></span> `)) } function getPlayers(myFun) { $.getJSON("data.json",function (data) { players=data; myFun(); }); } function DisplayPlayers() { retrieveMyPlayers(); auctiontable.empty(); for(var i in players){ var roler=roleDefiner(players[i]); var foreigner=removePlane(players[i]); auctiontable.append( $(` <tr> <th scope="row">${+i+1}</th> <td><button type="button" id="addtolist" class="adder" onclick="addToMyPlayers(${i})" data-toggle="modal" data-whatever="@mdo"><i class="fa fa-plus-square"></i> </button></td> <td>${players[i].name}</td> <td>${roler}</td> <td>${players[i].price}<i class="fa fa-money"></i> </td> <td>${foreigner}</td> </tr> `) ); } } function displayMyPlayers() { retrieveMyPlayers(); myplayers.empty(); for(var i in myplay){ var roler=roleDefiner(myplay[i]);k var foreigner=removePlane(myplay[i]); myplayers.append( $(` <tr> <th scope="row">${+i+1}</th> <td><button id="removefromlist" onclick="deleteFromMyPlayers(${i})"><i class="fa fa-minus-square"></i> </button></td> <td>${myplay[i].name}</td> <td>${roler}</td> <td>${myplay[i].price}<i class="fa fa-money"></i> </td> <td>${foreigner}</td> </tr> `) ); } } function removePlane(p) { if(p.role %2 ==0){ return '<i class="fa fa-plane" id="plane"></i>'; } else return ''; } function roleDefiner(p) { if((p.role) ==1 || (p.role)==2){ return "Batsman"; } else if((p.role)==3 || (p.role)==4){ return "Bowler"; } else if((p.role)==5 || (p.role)==6){ return "All rounder"; } else if((p.role)==8 || (p.role)==7){ return "Wicketkeeper"; } } function addToMyPlayers(index) { var icon=$('.adder'); var obj=players[index]; modaltext.empty(); modalhead.empty(); balance=balance-obj.price; if(balance>=0) { myplay.push(obj); players.splice(index, 1); // console.log(obj); } else { // console.log(players[index]); modalhead.append("Oops something went wrong!"); modaltext.append("You don't have enough amount to buy this player"); icon.attr('data-target','#exampleModal'); balance=balance+obj.price; } pursedisplay(); saveMyPlayers(); DisplayPlayers(); displayMyPlayers(); balanceColor(); } function deleteFromMyPlayers(index) { var obj=myplay[index]; balance=balance+obj.price; players.push(obj); myplay.splice(index,1); pursedisplay(); saveMyPlayers(); DisplayPlayers(); displayMyPlayers(); balanceColor(); } function saveMyPlayers() { let change1=JSON.stringify(myplay); let change2=JSON.stringify(players); let change3=JSON.stringify(balance); localStorage.setItem('myxi',change1); localStorage.setItem('others',change2); localStorage.setItem('purse',change3); } function retrieveMyPlayers() { let change1=localStorage.getItem('myxi'); let change2=localStorage.getItem('others'); let change3=localStorage.getItem('purse'); if(change1){ myplay=JSON.parse(change1); } if(change2){ players=JSON.parse(change2); } if(change3){ balance=JSON.parse(change3); } }<file_sep>/public_static/register.js var submit; var showTnC; $(function () { var username=$('#username'); var teamname=$('#teamname'); var email=$('#email'); var password=$('<PASSWORD>'); submit=$('#sub'); showTnC=$('#showtc'); submit.click(function () { savenames(username.val(),teamname.val()); }); }); function savenames(a,b) { localStorage.setItem('username',JSON.stringify(a)); localStorage.setItem('teamname',JSON.stringify(b)); } function showModal() { showTnC.attr('data-target','#exampleModal'); } <file_sep>/public_static/myteam.js var teamname; var myplayers=[]; var playingXI; var restSquad; var myXI=[]; var Rest=[]; var XI; var bench; var modaltext; var modalhead; var save; $(function () { playingXI=$('#eleven'); restSquad=$('#others'); modaltext=$('#modalfiller'); modalhead=$('#modaltitle'); save=$('#final'); retrieveNames(); benchInit(); // retrieveXI(); displayTop(); displayXI(); displayRest(); save.click(function () { onSave(); }); }); function benchInit() { Rest=myplayers; } function saveTeam() { XI=JSON.stringify(myXI); bench=JSON.stringify(Rest); if(XI){ localStorage.setItem('playingXI',XI); } if(bench){ localStorage.setItem('rest',bench); } } function retrieveNames() { let u =localStorage.getItem('username'); let t =localStorage.getItem('teamname'); let chnge =localStorage.getItem('myxi'); un=JSON.parse(u); tn=JSON.parse(t); myplayers=JSON.parse(chnge); } function displayTop() { teamname=$('#team'); teamname.append( $(` <span class="badge badge-info"><h3 class="regheading">${tn}</h3></span> `) ) } function displayXI() { retrieveNames(); playingXI.empty(); for(var i in myXI){ var roler=roleDefiner(myXI[i]); var foreigner=removePlane(myXI[i]); playingXI.append( $(` <tr> <th scope="row">${+i+1}</th> <td><button id="removefromlist" onclick="removeFromXI(${i})"><i class="fa fa-thumbs-o-down"></i> </button></td> <td colspan="2">${myXI[i].name}</td> <td colspan="2">${roler}</td> <td>${foreigner}</td> </tr> `) ); } } function displayRest() { retrieveNames(); restSquad.empty(); for(var i in Rest){ var roler=roleDefiner(Rest[i]); var foreigner=removePlane(Rest[i]); restSquad.append( $(` <tr> <th scope="row">${+i+1}</th> <td><button id="addtolist" onclick="addtoXI(${i})"><i class="adder fa fa-thumbs-o-up"></i> </button></td> <td colspan="2">${Rest[i].name}</td> <td colspan="2">${roler}</td> <td>${foreigner}</td> </tr> `) ); } } function addtoXI(index) { // retrieveXI(); if(myXI.length < 11){ var obj=Rest[index]; myXI.push(obj); Rest.splice(index,1); // saveTeam(); } else{ modalhead.empty(); modaltext.empty(); modalhead.append("Oops something went wrong!"); modaltext.append("All eleven positions are filled"); var adder=$('.adder'); adder.attr('data-target','#exampleModal'); } displayRest(); displayXI(); } function removeFromXI(index) { // retrieveXI(); var obj=myXI[index]; Rest.push(obj); myXI.splice(index,1); displayRest(); displayXI(); // saveTeam(); } function removePlane(p) { if(p.role %2 ==0){ return '<i class="fa fa-plane" id="plane"></i>'; } else return ''; } function roleDefiner(p) { if((p.role) ==1 || (p.role)==2){ return "Batsman"; } else if((p.role)==3 || (p.role)==4){ return "Bowler"; } else if((p.role)==5 || (p.role)==6){ return "All rounder"; } else if((p.role)==8 || (p.role)==7){ return "Wicketkeeper"; } } function onSave() { modaltext.empty(); modalhead.empty(); if(myXI.length != 11){ modalhead.append("Oops something went wrong!"); modaltext.append("You must have 11 players in your final squad"); // data-target="#exampleModal" } else if(noWK()== true){ modalhead.append("Oops something went wrong!"); modaltext.append("You must have atleast one wicketkeeper in your final squad"); } else if(onlyFourForeigners()==true){ modalhead.append("Oops something went wrong!"); modaltext.append("You must have only four foreign players in your final squad"); } else if(fiveBowlers()==true){ modalhead.append("Oops something went wrong!"); modaltext.append("You must have atleast five bowlers/all rounders in your final squad"); } else{ modalhead.append("Success!"); modaltext.append("You are ready to take part in the league now!"); saveTeam(); } save.attr('data-target','#exampleModal'); } function noWK() { for(var a of myXI){ if(a.role==7 || a.role == 8){ return false; } } return true; } function onlyFourForeigners() { var counter=0; for(var a of myXI){ if(a.role==2 || a.role==4 || a.role==6 || a.role==8 ){ counter++; } } if(counter>4){ return true; } else return false; } function fiveBowlers() { var counter=0; for(var a of myXI){ if(a.role==3 || a.role==4 || a.role==5 || a.role==6){ counter++; } } if(counter<5){ return true; } return false; }
d346f1296bd45366a66e08bd643b4c16b136bf20
[ "JavaScript" ]
3
JavaScript
y-2-j/DreamTeam
1384d36c4b0baa82a6e88015e746fd954efa77f7
d77e747c474e34520891614e43dab17087f4e3e4
refs/heads/master
<file_sep>A drone config extension to force drone use configuration from your primary branch. This can protect your drone from running unwanted ci pipeline edit by unauthorized people from pull request. You may find more infomation [here](https://discourse.drone.io/t/drone-protected-build-workaround/3585) _Please note this project requires Drone server version 1.4 or higher._ ## Note For I'm living in China where it's hard to connect to github directly, this project use [fastgithub](https://github.com/dotnetcore/FastGithub) to speed up connection in China. ## Installation Create a shared secret: ```console $ openssl rand -hex 16 bea26a2221fd8090ea38720fc445eca6 ``` Download and run the extension: ```console $ docker run -d \ --publish=3000:3000 \ --env=DRONE_DEBUG=true \ --env=DRONE_SECRET=bea26a2221fd8090ea38720fc445eca6 \ --env=GITHUB_TOKEN=<KEY> \ --restart=always \ --name=config registry.cn-hangzhou.aliyuncs.com/pivotstudio/drone-master-config ``` Update your Drone server configuration to include the extension address and the shared secret. ```text DRONE_YAML_ENDPOINT=http://1.2.3.4:3000 DRONE_YAML_SECRET=bea26a2221fd8090ea38720fc445eca6 ``` For k8s usage: Change the template value in [deploy files](./deploy) then apply them. ## Testing Use the command line tools to test your extension. _This extension uses http-signatures to authorize client access and will reject unverified requests. You will be unable to test this extension using a simple curl command._ ```text export DRONE_YAML_ENDPOINT=http://1.2.3.4:3000 export DRONE_YAML_SECRET=bea26a2221fd8090ea38720fc445eca6 drone plugins config get <repo> ``` <file_sep>FROM ubuntu:18.04 RUN sed -i s@/archive.ubuntu.com/@/mirrors.aliyun.com/@g /etc/apt/sources.list RUN apt-get clean RUN apt-get update RUN apt-get install -y libssl-dev RUN apt-get install -y libgssapi-krb5-2 RUN apt-get install -y ca-certificates COPY app /bin/app COPY . / RUN chmod +x /entry.sh RUN chmod -R +x /fastgithub_linux-x64 ENTRYPOINT ["/entry.sh"]<file_sep>// Copyright 2019 the Drone Authors. All rights reserved. // Use of this source code is governed by the Blue Oak Model License // that can be found in the LICENSE file. package plugin import ( "context" "io" "net/http" "sync" "github.com/drone/drone-go/drone" "github.com/drone/drone-go/plugin/config" "github.com/google/go-github/github" "github.com/sirupsen/logrus" "golang.org/x/oauth2" ) var ( once = sync.Once{} oauthClient *http.Client ) // New returns a new config plugin. func New(token string) config.Plugin { return &plugin{ // TODO replace or remove these configuration // parameters. They are for demo purposes only. token: token, } } type plugin struct { // TODO replace or remove these configuration // parameters. They are for demo purposes only. token string } func (p *plugin) Find(ctx context.Context, req *config.Request) (*drone.Config, error) { // creates a github client used to fetch the yaml. logrus.Infoln("got request", req) trans := http.DefaultClient if len(p.token) > 0 { once.Do(func() { oauthClient = oauth2.NewClient(ctx, oauth2.StaticTokenSource( &oauth2.Token{AccessToken: p.token}, )) }) trans = oauthClient } c := github.NewClient(trans) repo, _, err := c.Repositories.Get(ctx, req.Repo.Namespace, req.Repo.Name) if err != nil { logrus.Error(err) return nil, err } reader, err := c.Repositories.DownloadContents(ctx, req.Repo.Namespace, req.Repo.Name, req.Repo.Config, &github.RepositoryContentGetOptions{ Ref: *repo.DefaultBranch, }) if err != nil { logrus.Error(err) return nil, err } bs, err := io.ReadAll(reader) if err != nil { logrus.Error(err) return nil, err } logrus.Infoln("request master config success") return &drone.Config{ Data: string(bs), }, nil } <file_sep>module github.com/Pivot-Studio/masterext go 1.12 require ( github.com/drone/drone-go v1.0.6 github.com/google/go-github v17.0.0+incompatible // indirect github.com/google/go-querystring v1.1.0 // indirect github.com/joho/godotenv v1.3.0 github.com/kelseyhightower/envconfig v1.4.0 github.com/sirupsen/logrus v1.4.2 golang.org/x/oauth2 v0.0.0-20210819190943-2bc19b11175f // indirect ) <file_sep>// Copyright 2019 the Drone Authors. All rights reserved. // Use of this source code is governed by the Blue Oak Model License // that can be found in the LICENSE file. package plugin import ( "context" "os" "testing" "github.com/drone/drone-go/drone" "github.com/drone/drone-go/plugin/config" ) func TestPlugin(t *testing.T) { if len(os.Getenv("CI")) > 0 { t.Skip("this test may fail in ci env due to github connection issue, we'll skip it") } p := plugin{ token: "", // your secret here } conf, err := p.Find(context.Background(), &config.Request{ Repo: drone.Repo{ Namespace: "Pivot-Studio", Name: "masterext", Config: ".drone.yml", }, }) if err != nil { t.Error(err) return } if conf == nil { t.Errorf("conf should not be nil") } } <file_sep>#!/bin/bash cd /fastgithub_linux-x64 export DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 ./fastgithub>/dev/null & sleep 3s cp cacert/fastgithub.cer /usr/local/share/ca-certificates/my-cert.crt cat cacert/fastgithub.cer >> /etc/ssl/certs/ca-certificates.crt update-ca-certificates export HTTP_PROXY="http://127.0.0.1:38457" export HTTPS_PROXY="http://127.0.0.1:38457" /bin/app
91542baf239723784c0b42c776e3beba244a0add
[ "Markdown", "Go", "Go Module", "Dockerfile", "Shell" ]
6
Markdown
Pivot-Studio/masterext
0ba32a419fe7cbbf403f3abe75334f172e164083
b8a612b50839033a6b6c4a06f04d057e89dacfc1
refs/heads/main
<file_sep><?php namespace App\Http\Controllers; use App\Http\Requests\InvoiceStoreRequest; use App\Mail\InvoiceMail; use App\Models\Buyer; use App\Models\Invoice; use App\Models\InvoiceDetail; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; class InvoiceController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $invoices = Invoice::with('buyer')->paginate(3); return view('invoices.index', compact('invoices')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $invoice = new Invoice(); $buyers = Buyer::all(); return view('invoices.create', compact('invoice', 'buyers')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(InvoiceStoreRequest $request) { $invoice = Invoice::create($request->validated()); return redirect()->route('invoices.add_products', ["invoice" => $invoice->id])->with(['status' => 'Success', 'color' => 'green', 'message' => 'Item added successfully']); } /** * Display the specified resource. * * @param \App\Models\Invoice $invoice * @return \Illuminate\Http\Response */ public function show(Invoice $invoice) { // } /** * Show the form for editing the specified resource. * * @param \App\Models\Invoice $invoice * @return \Illuminate\Http\Response */ public function edit(Invoice $invoice) { return view('inovices.create', compact('invoice')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\Invoice $invoice * @return \Illuminate\Http\Response */ public function update(Request $request, Invoice $invoice) { $invoice->fill($request->validated()); $invoice->save(); return redirect()->route('invoices.index')->with(['status' => 'Success', 'color' => 'blue', 'message' => 'Product updated successfully']); } /** * Remove the specified resource from storage. * * @param \App\Models\Invoice $invoice * @return \Illuminate\Http\Response */ public function destroy(Invoice $invoice) { try { $invoice->delete(); $result = ['status' => 'success', 'color' => 'green', 'message' => 'Deleted successfully']; } catch (\Exception $e) { $result = ['status' => 'error', 'color' => 'red', 'message' => 'Invoice cannot be delete']; } return redirect()->route('invoices.index')->with($result); } public function completeSend(Request $request, Invoice $invoice) { $details = InvoiceDetail::with('product') ->where('invoice_id', $invoice->id) ->get(); try { Mail::to($invoice->buyer->email) ->queue(new InvoiceMail($invoice, $details)); $result = ['status' => 'success', 'color' => 'green', 'message' => 'Mail sent successfully']; } catch (\Exception $e) { $result = ['status' => 'success', 'color' => 'green', 'message' => $e->getMessage()]; } $invoice->status = 'complete'; $invoice->save(); return redirect()->route('invoices.index')->with($result); } }
d776325b0213203fd1f0d3fd165bc69151b49cf8
[ "PHP" ]
1
PHP
GiancarlosJ/curso-laravel-invoices
1005df8c0bb4c1ab2453c8440edcc80aa740d600
e9447ef067cce4eab9971e63899bdc0a06ed0d3d
refs/heads/master
<file_sep># Konputaziorako-Sarrera Matematikako Gradua 2019-2020 * Edukia ikusteko: [nbviewer](https://nbviewer.jupyter.org/github/mpenagar/Konputaziorako-Sarrera-2019-2020) * Modu interaktiboa: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/mpenagar/Konputaziorako-Sarrera-2019-2020/master) <file_sep>def kaixo(): print("kaixo")
802bd90ecd70d3d565670f4b0ceddb6298a227bf
[ "Markdown", "Python" ]
2
Markdown
mpenagar/Konputaziorako-Sarrera-2019-2020
b7afefc89cc2aa333f6b6fbb4d5b7865e1e0c539
ee56b14b06c34b70afbe2c9fc9e7825ffeb47afe
refs/heads/main
<repo_name>TeodorVecerdi/saxion_procedural_art<file_sep>/Assets/Procedural Art/Scripts/Data/Arr3d.cs using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; public class Arr3d<T> : IEnumerable<T> { private T[][][] arr; private int length1; private int length2; private int length3; public Arr3d(Vector3Int length, T initialValue = default) : this(length.x, length.y, length.z, initialValue) { } public Arr3d(int length1, int length2, int length3, T initialValue = default) { this.length1 = length1; this.length2 = length2; this.length3 = length3; arr = new T[length1][][]; for (int i = 0; i < length1; i++) { arr[i] = new T[length2][]; for (int j = 0; j < length2; j++) arr[i][j] = new T[length3]; } if (!EqualityComparer<T>.Default.Equals(initialValue, default)) { FillAll(initialValue); } } public Arr2d<T> CrossSection(int y) { var arr2d = new Arr2d<T>(length1, length3); for(var i = 0; i < length1; i++) for (var j = 0; j < length3; j++) arr2d[i, j] = arr[i][y][j]; return arr2d; } public void Expand(int dimension, int size, bool reverseSide = false, T value = default) { if (size == 0) return; var newLength1 = length1; var newLength2 = length2; var newLength3 = length3; var dimensionVec = new Vector3Int(0, 0, 0); switch (dimension) { case 1: newLength1 += size; dimensionVec.x = size; break; case 2: newLength2 += size; dimensionVec.y = size; break; case 3: newLength3 += size; dimensionVec.z = size; break; default: throw new InvalidOperationException($"Invalid dimension {dimension}. Should be one of: [1, 2, 3]."); } var arrTemp = new T[newLength1][][]; for (int i = 0; i < newLength1; i++) { arrTemp[i] = new T[newLength2][]; for (int j = 0; j < newLength2; j++) { arrTemp[i][j] = new T[newLength3]; if (!EqualityComparer<T>.Default.Equals(value, default)) for (int k = 0; k < newLength3; k++) arrTemp[i][j][k] = value; } } for (int i = 0; i < length1; i++) for (int j = 0; j < length2; j++) for (int k = 0; k < length3; k++) { if (!reverseSide) { arrTemp[i][j][k] = arr[i][j][k]; } else arrTemp[i + dimensionVec.x][j + dimensionVec.y][k + dimensionVec.z] = arr[i][j][k]; } arr = arrTemp; length1 = newLength1; length2 = newLength2; length3 = newLength3; } public void FillAll(T value) { for (int i = 0; i < length1; i++) for (int j = 0; j < length2; j++) for (int k = 0; k < length3; k++) arr[i][j][k] = value; } public void Fill(Vector3Int from, Vector3Int to, T value) { for (int i = from.x; i < to.x; i++) for (int j = from.y; j < to.y; j++) for (int k = from.z; k < to.z; k++) arr[i][j][k] = value; } public int Length1 => length1; public int Length2 => length2; public int Length3 => length3; public Vector3Int Length => new Vector3Int(length1, length2, length3); public T this[int x, int y, int z] { get { if (x < 0 || x >= length1 || y < 0 || y >= length2 || z < 0 || z >= length3) return default; return arr[x][y][z]; } set { if (x < 0 || x >= length1 || y < 0 || y >= length2 || z < 0 || z >= length3) return; arr[x][y][z] = value; } } public T this[Vector3Int index] { get => this[index.x, index.y, index.z]; set => this[index.x, index.y, index.z] = value; } public IEnumerator<T> GetEnumerator() { for (int i = 0; i < length1; i++) for (int j = 0; j < length2; j++) for (int k = 0; k < length3; k++) { if (arr[i][j][k] == null) continue; yield return arr[i][j][k]; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }<file_sep>/README.md # Procedural Art Repository for the Procedural Art course at Saxion where the task was to procedurally generate a city in the style of a chosen theme (in my case The Witcher 3's city center of Novigrad). [**Research document**](Github/docs/novigrad_visual_research.pdf) ## Top view ![Top view of a procedurally generated city on top of an island](Github/img/top.png) ## Side view ![Side view of a procedurally generated city on top of an island](Github/img/side.png) ## City markets ![City center containing market stalls, a fountain, and trees](Github/img/center.png) ## Tooling ![Top-down image of a city showcasing the tool used to generate a city](Github/img/tooling.png) ![Top-down image with selected green rectangles](Github/img/tooling_2.png) ## Building blocks ![Image containing different 3D objects](Github/img/building_blocks.png)<file_sep>/Assets/Procedural Art/Scripts/Settings/MaterialSettings.cs using UnityEngine; [CreateAssetMenu(fileName = "Material Settings", menuName = "Material Settings", order = 0)] public class MaterialSettings : ScriptableObject { public Material WallMaterial; public Material RoofMaterial; public Material WindowMaterial; public Material FeatureMaterial1; public Material FeatureMaterial2; public Material FeatureMaterial3; }<file_sep>/Assets/Procedural Art/Scripts/Mesh Generation/PlaneGenerator.cs using System; using System.Collections.Generic; using UnityEngine; public class PlaneGenerator : MeshGenerator { private PlaneOrientation orientation; private UVSettings extraUvSettings; private float sizeA; private float sizeB; private int submeshIndex; private bool flip; protected override void SetDefaultSettings() { defaultParameters = new Dictionary<string, dynamic> { {"orientation", PlaneOrientation.XZ}, {"extraUvSettings", UVSettings.None}, {"sizeA", 1}, {"sizeB", 1}, {"submeshIndex", 0}, {"flip", false} }; } protected override void DeconstructSettings(Dictionary<string, dynamic> parameters) { orientation = parameters.ContainsKey("orientation") ? parameters["orientation"] : defaultParameters["orientation"]; extraUvSettings = parameters.ContainsKey("extraUvSettings") ? parameters["extraUvSettings"] : defaultParameters["extraUvSettings"]; sizeA = (parameters.ContainsKey("sizeA") ? parameters["sizeA"] : defaultParameters["sizeA"]) * GlobalSettings.Instance.GridSize; sizeB = (parameters.ContainsKey("sizeB") ? parameters["sizeB"] : defaultParameters["sizeB"]) * GlobalSettings.Instance.GridSize; submeshIndex = parameters.ContainsKey("submeshIndex") ? parameters["submeshIndex"] : defaultParameters["submeshIndex"]; flip = parameters.ContainsKey("flip") ? parameters["flip"] : defaultParameters["flip"]; } protected override void Generate() { var p1 = Vector3.zero; var p2 = p1 + Vector3.right * sizeA; var p3 = p2 + Vector3.forward * sizeB; var p4 = p1 + Vector3.forward * sizeB; if (orientation == PlaneOrientation.XY) { p3 = p2 + Vector3.up * sizeB; p4 = p1 + Vector3.up * sizeB; } else if (orientation == PlaneOrientation.YZ) { p2 = p1 + Vector3.up * sizeA; p3 = p2 + Vector3.forward * sizeB; } AddQuad(p1, p4, p3, p2, submeshIndex, flip, extraUvSettings); } public enum PlaneOrientation { XY, XZ, YZ } }<file_sep>/Assets/Procedural Art/Scripts/Plots/PlotScriptableObject.cs using System; using System.Collections.Generic; using UnityEngine; [Serializable] public struct PlotData { public Rect Bounds; public float Rotation; } [Serializable] public struct PlotGridData { public List<PlotData> Plots; public Color Color; public string Name; } public class PlotScriptableObject : ScriptableObject { public List<PlotGridData> PlotGrids; }<file_sep>/Assets/Procedural Art/Scripts/Generators/WallBuildingGenerator.cs using System; using System.Collections.Generic; using UnityEngine; public class WallBuildingGenerator : BuildingGenerator { private WallSettings wallSettings; public static new bool DoneOnceField; private static float roofHeight; private static float wallHeight; public override MeshData Generate(PlotData plot, BuildingTypeSettings settings, float heightAdjustment, Vector3 offset, int LOD) { wallSettings = settings.GeneratorSettings as WallSettings; DoOnce(ref DoneOnceField); var size = new Vector2Int(Mathf.RoundToInt(plot.Bounds.size.x), Mathf.RoundToInt(plot.Bounds.size.y)); DimensionsA = new Vector2Int(size.x, size.y); DimensionsB = Vector2Int.zero; var boolArr = new Arr2d<bool>(DimensionsA.x, DimensionsA.y, true); var roof = GenRoof(); var path = MarchingSquares.March(boolArr); CleanupOutline(boolArr); var walls = GenWalls(path); var features = GenFeatures(path); return MeshUtils.Combine(roof, walls, features); } public override void DoOnce(ref bool doneOnceField) { if (doneOnceField) return; doneOnceField = true; roofHeight = Rand.Range(wallSettings.RoofHeightVariation.x, wallSettings.RoofHeightVariation.y); wallHeight = wallSettings.Height + Rand.Range(wallSettings.HeightVariation.x, wallSettings.HeightVariation.y); } public override void Setup(BuildingTypeSettings settings) { } private MeshData GenWalls(List<Vector2Int> path) { var walls = new MeshData(); var current = Vector2Int.zero; foreach (var point in path) { var next = current + point; var from = new Vector3(current.x - 0.5f, 0, current.y - 0.5f); var to = new Vector3(next.x - 0.5f, 0, next.y - 0.5f); var diff = to - from; var angle = Vector3.SignedAngle(Vector3.right, diff, Vector3.up); var wallWidth = diff.magnitude; var wall = MeshGenerator.GetMesh<PlaneGenerator>(to, Quaternion.Euler(0, angle - 180, 0), new Dictionary<string, dynamic> { {"sizeA", wallWidth}, {"sizeB", wallHeight}, {"orientation", PlaneGenerator.PlaneOrientation.XY}, {"submeshIndex", 0} }); walls.MergeMeshData(wall); current = next; } return walls; } private MeshData GenRoof() { var roofA = MeshGenerator.GetMesh<StraightRoofGenerator>(new Vector3(-0.5f, wallHeight, -0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"width", DimensionsA.x}, {"height", roofHeight}, {"thickness", wallSettings.RoofThickness}, {"length", DimensionsA.y / 2f}, {"extrusion", wallSettings.RoofExtrusion}, {"addCap", true}, {"closeRoof", true} }); var roofA1 = MeshGenerator.GetMesh<StraightRoofGenerator>(new Vector3(DimensionsA.x - 0.5f, wallHeight, DimensionsA.y - 0.5f), Quaternion.Euler(0, 180, 0), new Dictionary<string, dynamic> { {"width", DimensionsA.x}, {"height", roofHeight}, {"thickness", wallSettings.RoofThickness}, {"length", DimensionsA.y / 2f}, {"extrusion", wallSettings.RoofExtrusion}, {"addCap", true}, {"closeRoof", true} }); return MeshUtils.Combine(roofA, roofA1); } private MeshData GenFeatures(List<Vector2Int> path) { return new MeshData(); } }<file_sep>/Assets/Procedural Art/Scripts/Misc/GizmoUtils.cs using UnityEngine; public static class GizmoUtils { public static void DrawLine(Vector3 p1, Vector3 p2, float width) { var count = Mathf.CeilToInt(width); if (count == 1) { Gizmos.DrawLine(p1, p2); } else { var c = Camera.current; if (c == null) { Debug.LogError("Camera.current is null"); return; } var scp1 = c.WorldToScreenPoint(p1); var scp2 = c.WorldToScreenPoint(p2); var v1 = (scp2 - scp1).normalized; // line direction var n = Vector3.Cross(v1, Vector3.forward); // normal vector for (var i = 0; i < count; i++) { var o = 0.99f * n * width * ((float) i / (count - 1) - 0.5f); var origin = c.ScreenToWorldPoint(scp1 + o); var destiny = c.ScreenToWorldPoint(scp2 + o); Gizmos.DrawLine(origin, destiny); } } } }<file_sep>/Assets/Procedural Art/Scripts/Generators/NormalLBuildingGenerator.cs using System; using System.Collections.Generic; using UnityEditor; using UnityEngine; public class NormalLBuildingGenerator : BuildingGenerator { public static new bool DoneOnceField = false; public override void DoOnce(ref bool doneOnceField) { if (doneOnceField) return; doneOnceField = true; } public override MeshData Generate(PlotData plot, BuildingTypeSettings settings, float heightAdjustment, Vector3 offset, int LOD) { DoOnce(ref DoneOnceField); var size = new Vector2Int(Mathf.RoundToInt(plot.Bounds.size.x), Mathf.RoundToInt(plot.Bounds.size.y)); var boolArr = GenL(size, heightAdjustment); var overhang = GenLOverhang(LOD); var roofs = GenLRoof(); var path = MarchingSquares.March(boolArr); CleanupOutline(boolArr); var walls = GenWalls(path, LOD); return MeshUtils.Combine(roofs, walls, overhang); } protected Arr2d<bool> GenL(Vector2Int size, float heightAdjustment) { var widthA = RandUtils.RandomBetween(GeneratorSettings.LSettings.MinMaxWidthA); var lengthA = RandUtils.RandomBetween(GeneratorSettings.LSettings.MinMaxLengthA); var widthB = RandUtils.RandomBetween(GeneratorSettings.LSettings.MinMaxWidthB); // widthB = MathUtils.Clamp(widthB, 2, widthA - 1); var lengthB = RandUtils.RandomBetween(GeneratorSettings.LSettings.MinMaxLengthB); // lengthB = MathUtils.Clamp(lengthB, 1, Mathf.CeilToInt(lengthA / 2f)); BuildingHeight = heightAdjustment+ RandUtils.RandomBetween(GeneratorSettings.LSettings.MinMaxHeight); // normalize size so it's in range of <size> var proportionWA = widthA / (float) (widthA + widthB); var proportionWB = widthB / (float) (widthA + widthB); var proportionLA = lengthA / (float) (lengthA + lengthB); var proportionLB = lengthB / (float) (lengthA + lengthB); var actualWidthA = Mathf.CeilToInt(proportionWA * size.x); var actualWidthB = Mathf.FloorToInt(proportionWB * size.x); var actualLengthA = Mathf.CeilToInt(proportionLA * size.y); var actualLengthB = Mathf.FloorToInt(proportionLB * size.y); actualWidthA += (size.x - actualWidthA - actualWidthB); actualLengthA += (size.y - actualLengthA - actualLengthB); DimensionsA = new Vector2Int(actualWidthA + actualWidthB, actualLengthA + actualLengthB); DimensionsB = new Vector2Int(actualWidthB, actualLengthB); var boolArr = new Arr2d<bool>(DimensionsA, true); CarveLShape(boolArr); return boolArr; } protected MeshData GenLRoof() { var height = RandUtils.RandomBetween(GeneratorSettings.LSettings.MinMaxRoofHeight); var thickness = GeneratorSettings.GeneralSettings.RoofThickness; var extrusion = GeneratorSettings.GeneralSettings.RoofExtrusion; var cornerRoofEndingChance = GeneratorSettings.LSettings.CornerEndingChance; var roofs = new List<MeshData>(); if (RandUtils.BoolWeighted(cornerRoofEndingChance)) { var roofInset = DimensionsB.x * RandUtils.RandomBetween(GeneratorSettings.LSettings.CornerInsetRatio); var roofSize = (DimensionsA.x - roofInset) - (DimensionsA.x - DimensionsB.x) / 2f; var cornerA = MeshGenerator.GetMesh<CornerRoofGenerator>(new Vector3(DimensionsA.x - 0.5f, BuildingHeight, DimensionsA.y - DimensionsB.y - 0.5f), Quaternion.Euler(0, 180, 0), new Dictionary<string, dynamic> { {"width", roofInset}, {"height", height}, {"length", (DimensionsA.y - DimensionsB.y) / 2f}, {"thickness", thickness}, {"addCap", true}, {"joinCaps", true}, }); var cornerA1 = MeshGenerator.GetMesh<CornerRoofGenerator>(new Vector3(DimensionsA.x - 0.5f, BuildingHeight, -0.5f), Quaternion.Euler(0, 270, 0), new Dictionary<string, dynamic> { {"width", (DimensionsA.y - DimensionsB.y) / 2f}, {"height", height}, {"length", roofInset}, {"thickness", thickness}, {"addCap", true}, {"joinCaps", true}, }); var roofA = MeshGenerator.GetMesh<StraightRoofGenerator>(new Vector3(DimensionsA.x - roofSize - roofInset - 0.5f, BuildingHeight, -0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"width", roofSize}, {"height", height}, {"thickness", thickness}, {"length", (DimensionsA.y - DimensionsB.y) / 2f}, {"extrusion", 0}, {"addCap", true}, {"closeRoof", true} }); var roofA1 = MeshGenerator.GetMesh<StraightRoofGenerator>(new Vector3(DimensionsA.x - roofInset - 0.5f, BuildingHeight, DimensionsA.y - DimensionsB.y - 0.5f), Quaternion.Euler(0, 180, 0), new Dictionary<string, dynamic> { {"width", roofSize}, {"height", height}, {"length", (DimensionsA.y - DimensionsB.y) / 2f}, {"thickness", thickness}, {"extrusion", 0}, {"addCap", true}, {"closeRoof", true} }); roofs.Add(cornerA); roofs.Add(cornerA1); roofs.Add(roofA); roofs.Add(roofA1); } else { var roofSize = (DimensionsA.x) - (DimensionsA.x - DimensionsB.x) / 2f; var roofA = MeshGenerator.GetMesh<StraightRoofGenerator>(new Vector3(DimensionsA.x - roofSize - 0.5f, BuildingHeight, -0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"width", roofSize}, {"height", height}, {"thickness", thickness}, {"length", (DimensionsA.y - DimensionsB.y) / 2f}, {"extrusion", extrusion}, {"extrusionLeft", false}, {"addCap", true}, {"closeRoof", true} }); var roofA1 = MeshGenerator.GetMesh<StraightRoofGenerator>(new Vector3(DimensionsA.x - 0.5f, BuildingHeight, DimensionsA.y - DimensionsB.y - 0.5f), Quaternion.Euler(0, 180, 0), new Dictionary<string, dynamic> { {"width", roofSize}, {"height", height}, {"length", (DimensionsA.y - DimensionsB.y) / 2f}, {"thickness", thickness}, {"extrusion", extrusion}, {"extrusionRight", false}, {"addCap", true}, {"closeRoof", true} }); roofs.Add(roofA); roofs.Add(roofA1); } var cornerB = MeshGenerator.GetMesh<CornerRoofGenerator>(new Vector3(-0.5f, BuildingHeight, -0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"width", (DimensionsA.x - DimensionsB.x) / 2f}, {"height", height}, {"length", (DimensionsA.y - DimensionsB.y) / 2f}, {"thickness", thickness}, {"addCap", true}, {"joinCaps", true} }); roofs.Add(cornerB); var roofB = MeshGenerator.GetMesh<StraightRoofGenerator>(new Vector3(-0.5f, BuildingHeight, DimensionsA.y - 0.5f), Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"width", DimensionsB.y + (DimensionsA.y - DimensionsB.y) / 2f}, {"height", height}, {"length", (DimensionsA.x - DimensionsB.x) / 2f}, {"thickness", thickness}, {"extrusion", extrusion}, {"extrusionRight", false}, {"addCap", true}, {"closeRoof", true} }); var roofB1 = MeshGenerator.GetMesh<StraightRoofGenerator>(new Vector3(DimensionsA.x - DimensionsB.x - 0.5f, BuildingHeight, (DimensionsA.y - DimensionsB.y) / 2f - 0.5f), Quaternion.Euler(0, -90, 0), new Dictionary<string, dynamic> { {"width", DimensionsB.y + (DimensionsA.y - DimensionsB.y) / 2f}, {"height", height}, {"length", (DimensionsA.x - DimensionsB.x) / 2f}, {"thickness", thickness}, {"extrusion", extrusion}, {"extrusionLeft", false}, {"addCap", true}, {"closeRoof", true}, }); roofs.Add(roofB); roofs.Add(roofB1); return MeshUtils.Combine(roofs); } protected MeshData GenLOverhang(int LOD) { if (!RandUtils.BoolWeighted(GeneratorSettings.LSettings.OverhangChance)) return new MeshData(); var featureThickness = 0.1f; var meshes = new List<MeshData>(); var thickness = 0.25f; var start = 2; var end = Rand.Range(start + 1, BuildingHeight - 1); var height = end - start; // WALLS var wallA = MeshGenerator.GetMesh<PlaneGenerator>(new Vector3(DimensionsA.x - DimensionsB.x - 0.5f, start, DimensionsA.y - 0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"sizeA", DimensionsB.x}, {"sizeB", height}, {"orientation", PlaneGenerator.PlaneOrientation.XY}, {"flip", true} }); var wallB = MeshGenerator.GetMesh<PlaneGenerator>(new Vector3(DimensionsA.x - 0.5f, start, DimensionsA.y - 0.5f), Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"sizeA", DimensionsB.y}, {"sizeB", height}, {"orientation", PlaneGenerator.PlaneOrientation.XY}, {"flip", true} }); var plane = MeshGenerator.GetMesh<PlaneGenerator>(new Vector3(DimensionsA.x - DimensionsB.x - 0.5f, start + height, DimensionsA.y - DimensionsB.y - 0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"sizeA", DimensionsB.x}, {"sizeB", DimensionsB.y} }); meshes.Add(wallA); meshes.Add(wallB); meshes.Add(plane); var fromA = new Vector3(DimensionsA.x - DimensionsB.x - 0.5f, start, DimensionsA.y - 0.5f); var toA = fromA + Vector3.right * DimensionsB.x; var wallAPerpendicular = Vector3.Cross((toA - fromA).normalized, Vector3.up); meshes.Add(AddWallFeatures(fromA, toA, height, DimensionsB.x, 0, LOD, false)); meshes.Add(MeshGenerator.GetMesh<LineGenerator>(fromA + Vector3.up * featureThickness - wallAPerpendicular * featureThickness / 2f, Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero + Vector3.right * featureThickness / 2f}, {"end", Vector3.right * (DimensionsB.x - featureThickness / 2f)}, {"thickness", featureThickness}, {"extrusion", featureThickness}, {"submeshIndex", 2}, {"rotateUV", true} })); var fromB = new Vector3(DimensionsA.x - 0.5f, start, DimensionsA.y - 0.5f); var toB = fromB - Vector3.forward * DimensionsB.y; var wallBPerpendicular = Vector3.Cross((toB - fromB).normalized, Vector3.up); meshes.Add(AddWallFeatures(fromB, toB, height, DimensionsB.y, 90, LOD, false)); meshes.Add(MeshGenerator.GetMesh<LineGenerator>(fromB + Vector3.up * featureThickness - wallBPerpendicular * featureThickness / 2f, Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero + Vector3.right * featureThickness / 2f}, {"end", Vector3.right * (DimensionsB.y - featureThickness / 2f)}, {"thickness", featureThickness}, {"extrusion", featureThickness}, {"submeshIndex", 2}, {"rotateUV", true} })); meshes.Add(MeshGenerator.GetMesh<LineGenerator>(new Vector3(DimensionsA.x - 0.5f, 0, DimensionsA.y - 0.5f) - wallAPerpendicular * featureThickness / 2f, Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * (end + featureThickness / 2f)}, {"thickness", featureThickness}, {"extrusion", featureThickness}, {"submeshIndex", 2}, {"rotateUV", true} })); // ARCHES var archChance = 0.5f; var archLOD = LOD == 0 ? 45 : LOD == 1 ? 21 : 7; var shouldAddWallsA = false; var shouldAddWallsB = false; if (RandUtils.BoolWeighted(archChance)) { // ARCHES/ARCH X if (RandUtils.BoolWeighted(archChance)) { var diffA = DimensionsB.x - start; var archWidthA = DimensionsB.x - 2 * thickness; var archOffsetA = thickness; if (diffA > 0) { archWidthA = start; archOffsetA = diffA / 2f; shouldAddWallsA = true; } var archA = MeshGenerator.GetMesh<ArchGenerator>(new Vector3(DimensionsA.x - DimensionsB.x - 0.5f + archOffsetA, start - 1, DimensionsA.y - thickness - 0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"width", archWidthA}, {"height", 1}, {"length", thickness}, {"points", archLOD} }); meshes.Add(archA); if (shouldAddWallsA) { var wallC = MeshGenerator.GetMesh<WallGenerator>(new Vector3(DimensionsA.x - 0.5f, 0, DimensionsA.y - 0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"width", diffA / 2f}, {"height", start}, {"thickness", 0.01f}, {"thicknessInwards", true}, {"flip", true} }); var wallC1 = MeshGenerator.GetMesh<WallGenerator>(new Vector3(DimensionsA.x - DimensionsB.x - 0.5f, 0, DimensionsA.y - 0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"width", diffA / 2f}, {"height", start}, {"thickness", 0.01f}, {"thicknessInwards", true} }); meshes.Add(wallC); meshes.Add(wallC1); } else { var pillarX = MeshGenerator.GetMesh<PillarGenerator>(new Vector3(DimensionsA.x - DimensionsB.x + thickness / 2f - 0.5f, 0, DimensionsA.y - 0.5f), Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"width", thickness}, {"height", start}, {"thicknessInwards", true} }); meshes.Add(pillarX); } } else { shouldAddWallsA = true; var wallX = MeshGenerator.GetMesh<WallGenerator>(new Vector3(DimensionsA.x - 0.5f, 0, DimensionsA.y - 0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"width", DimensionsB.x}, {"height", start}, {"thickness", 0.01f}, {"thicknessInwards", true}, {"flip", true} }); meshes.Add(wallX); } // ARCHES/ARCH Z if (RandUtils.BoolWeighted(archChance)) { var diffB = DimensionsB.y - start; var archWidthB = DimensionsB.y - 2 * thickness; var archOffsetB = thickness; if (diffB > 0) { archWidthB = start; archOffsetB = diffB / 2f; shouldAddWallsB = true; } var archB = MeshGenerator.GetMesh<ArchGenerator>(new Vector3(DimensionsA.x - 0.5f, start - 1, DimensionsA.y - DimensionsB.y + archOffsetB - 0.5f), Quaternion.Euler(0, -90, 0), new Dictionary<string, dynamic> { {"width", archWidthB}, {"height", 1}, {"length", thickness}, {"points", archLOD} }); meshes.Add(archB); if (shouldAddWallsB) { var wallD = MeshGenerator.GetMesh<WallGenerator>(new Vector3(DimensionsA.x - 0.5f, 0, DimensionsA.y - 0.5f), Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"width", diffB / 2f}, {"height", start}, {"thickness", 0.01f}, {"thicknessInwards", true} }); var wallD1 = MeshGenerator.GetMesh<WallGenerator>(new Vector3(DimensionsA.x - 0.5f, 0, DimensionsA.y - DimensionsB.y - 0.5f), Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"width", diffB / 2f}, {"height", start}, {"thickness", 0.01f}, {"thicknessInwards", true}, {"flip", true} }); meshes.Add(wallD); meshes.Add(wallD1); } else { var pillarZ = MeshGenerator.GetMesh<PillarGenerator>(new Vector3(DimensionsA.x - thickness / 2f - 0.5f, 0, DimensionsA.y - DimensionsB.y + thickness - 0.5f), Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"width", thickness}, {"height", start}, {"thicknessInwards", true} }); meshes.Add(pillarZ); } } else { shouldAddWallsB = true; var wallZ = MeshGenerator.GetMesh<WallGenerator>(new Vector3(DimensionsA.x - 0.5f, 0, DimensionsA.y - 0.5f), Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"width", DimensionsB.y}, {"height", start}, {"thickness", 0.01f}, {"thicknessInwards", true} }); meshes.Add(wallZ); } } // MIDDLE PILLAR if (!shouldAddWallsA || !shouldAddWallsB) { var pillarMid = MeshGenerator.GetMesh<PillarGenerator>(new Vector3(DimensionsA.x - thickness / 2f - 0.5f, 0, DimensionsA.y - 0.5f), Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"width", thickness}, {"height", start}, {"thicknessInwards", true} }); meshes.Add(pillarMid); } return MeshUtils.Combine(meshes); } protected override MeshData AddWallFeatures(Vector3 wallStart, Vector3 wallEnd, float buildingHeight, float wallWidth, float wallAngle, int LOD, bool addPillar = true) { var thickness = GeneratorSettings.GeneralSettings.FeatureThickness; var pillarThickness = GeneratorSettings.GeneralSettings.PillarThickness; var windowChance = GeneratorSettings.GeneralSettings.WindowChance; var wallDirection = (wallEnd - wallStart).normalized; var wallPerpendicular = Vector3.Cross(wallDirection, Vector3.up); var wallSize = Mathf.RoundToInt((wallEnd - wallStart).magnitude); var features = new MeshData(); if (addPillar) { var pillar = MeshGenerator.GetMesh<LineGenerator>(wallEnd - Vector3.forward * pillarThickness / 2f, Quaternion.identity, new Dictionary<string, dynamic> { {"end", Vector3.up * buildingHeight}, {"thickness", pillarThickness}, {"extrusion", pillarThickness}, {"submeshIndex", 2}, {"extrusionOutwards", false} }); features.MergeMeshData(pillar); } var splitSectionsVertical = new List<float> {0, 1}; var lastSplitPoint = splitSectionsVertical[1]; while (lastSplitPoint < buildingHeight) { var nextSize = RandUtils.RandomBetween(GeneratorSettings.GeneralSettings.VerticalSplitMinMax); if (lastSplitPoint + nextSize < buildingHeight && lastSplitPoint + nextSize > buildingHeight - 1) nextSize = buildingHeight - lastSplitPoint - 1; lastSplitPoint += nextSize; if (lastSplitPoint >= buildingHeight) lastSplitPoint = buildingHeight; splitSectionsVertical.Add(lastSplitPoint); } var splitSectionsHorizontal = new List<float> {0}; var lastSplitPointH = splitSectionsHorizontal[0]; while (lastSplitPointH < wallSize) { var nextSize = RandUtils.RandomBetween(GeneratorSettings.GeneralSettings.HorizontalSplitMinMax); if (lastSplitPointH + nextSize < wallSize && lastSplitPointH + nextSize > wallSize - 1) nextSize = wallSize - lastSplitPointH - 1; lastSplitPointH += nextSize; if (lastSplitPointH > wallSize) lastSplitPointH = wallSize; splitSectionsHorizontal.Add(lastSplitPointH); } for (var i = 1; i < splitSectionsVertical.Count; i++) { var sectionHeight = splitSectionsVertical[i] - splitSectionsVertical[i - 1]; var addWindow = wallSize > 2 && RandUtils.BoolWeighted(windowChance) && LOD <= 1; var windowWidth = 0.0f; var windowHeight = 0.0f; if (addWindow) { windowHeight = Rand.Range(1f, Mathf.Max(1f, sectionHeight * 0.75f)); } for (var i2 = 1; i2 < splitSectionsHorizontal.Count; i2++) { var sectionWidth = splitSectionsHorizontal[i2] - splitSectionsHorizontal[i2 - 1]; var addWindowHorizontal = addWindow; if (RandUtils.BoolWeighted(windowChance/2.0f)) addWindowHorizontal = false; if (addWindowHorizontal) { windowWidth = Mathf.Min(sectionWidth - pillarThickness, Rand.Range(1f, Mathf.Max(1f, sectionWidth * 0.75f))); } if (i2 != splitSectionsHorizontal.Count - 1) { var verticalLine = MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * splitSectionsHorizontal[i2], Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * buildingHeight}, {"thickness", pillarThickness}, {"extrusion", pillarThickness}, {"submeshIndex", 2}, {"extrusionCenter", true} }); features.MergeMeshData(verticalLine); } if (i == 1) continue; if (LOD <= 1 && addWindowHorizontal) { var windowPosition = splitSectionsHorizontal[i2] - 0.5f * (sectionWidth); var window = MeshGenerator.GetMesh<PlaneGenerator>(wallStart + wallDirection * (windowPosition + 0.5f * windowWidth) + Vector3.up * (splitSectionsVertical[i - 1] + thickness / 2f) + wallPerpendicular * thickness / 4f, Quaternion.Euler(0, wallAngle - 180, 0), new Dictionary<string, dynamic> { {"sizeA", windowWidth}, {"sizeB", windowHeight}, {"orientation", PlaneGenerator.PlaneOrientation.XY}, {"submeshIndex", 3}, {"extraUvSettings", MeshGenerator.UVSettings.NoOffset} }); features.MergeMeshData(window); /* BEGIN Frame */ features.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition - 0.5f * windowWidth) + Vector3.up * (splitSectionsVertical[i - 1] + 0.33334f * windowHeight), Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.right * windowWidth}, {"thickness", 0.035f}, {"extrusion", 0.035f}, {"submeshIndex", 2}, {"rotateUV", true} })); features.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition - 0.5f * windowWidth) + Vector3.up * (splitSectionsVertical[i - 1] + windowHeight - 0.33334f * windowHeight), Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.right * windowWidth}, {"thickness", 0.035f}, {"extrusion", 0.035f}, {"submeshIndex", 2}, {"rotateUV", true} })); features.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition + 0.5f * windowWidth - 0.33334f * windowWidth) + Vector3.up * (splitSectionsVertical[i - 1] + thickness / 2f) - wallPerpendicular * 0.005f, Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * (windowHeight - thickness / 2f)}, {"thickness", 0.035f}, {"extrusion", 0.035f}, {"submeshIndex", 2}, {"rotateUV", true} })); features.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition - 0.5f * windowWidth + 0.33334f * windowWidth) + Vector3.up * (splitSectionsVertical[i - 1] + thickness / 2f) - wallPerpendicular * 0.005f, Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * (windowHeight - thickness / 2f)}, {"thickness", 0.035f}, {"extrusion", 0.035f}, {"submeshIndex", 2}, {"rotateUV", true} })); /* END Frame */ if (sectionHeight > 1) { var line = MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition - 0.5f * windowWidth) + Vector3.up * (splitSectionsVertical[i - 1] + windowHeight) - wallPerpendicular * thickness / 2f, Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.right * windowWidth}, {"thickness", thickness}, {"extrusion", thickness}, {"submeshIndex", 2}, {"rotateUV", true} }); features.MergeMeshData(line); } if (sectionWidth > 1) { var lineLeft = MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition + 0.5f * windowWidth + 0.5f * thickness) + Vector3.up * (splitSectionsVertical[i - 1] + thickness / 2f) - wallPerpendicular * thickness / 2f, Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * windowHeight}, {"thickness", thickness}, {"extrusion", thickness}, {"submeshIndex", 2}, {"rotateUV", true} }); features.MergeMeshData(lineLeft); var lineRight = MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition - 0.5f * windowWidth - 0.5f * thickness) + Vector3.up * (splitSectionsVertical[i - 1] + thickness / 2f) - wallPerpendicular * thickness / 2f, Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * windowHeight}, {"thickness", thickness}, {"extrusion", thickness}, {"submeshIndex", 2}, {"rotateUV", true} }); features.MergeMeshData(lineRight); } } } } return features; } private void CarveLShape(Arr2d<bool> arr) { var from = new Vector2Int(DimensionsA.x - DimensionsB.x, DimensionsA.y - DimensionsB.y); var to = new Vector2Int(DimensionsA.x, DimensionsA.y); arr.Fill(from, to, false); } }<file_sep>/Assets/Procedural Art/Scripts/Mesh Generation/LineGenerator.cs using System.Collections.Generic; using UnityEngine; public class LineGenerator : MeshGenerator { private Vector3 start; private Vector3 end; private float thickness; private float extrusion; private int submeshIndex; private bool extrusionOutwards; private bool extrusionCenter; private bool rotateUV; protected override void SetDefaultSettings() { defaultParameters = new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up}, {"thickness", 0.1f}, {"extrusion", 0.1f}, {"submeshIndex", 0}, {"extrusionOutwards", false}, {"extrusionCenter", false}, {"rotateUV", false} }; } protected override void DeconstructSettings(Dictionary<string, dynamic> parameters) { start = parameters.ContainsKey("start") ? parameters["start"] : defaultParameters["start"]; end = parameters.ContainsKey("end") ? parameters["end"] : defaultParameters["end"]; thickness = parameters.ContainsKey("thickness") ? parameters["thickness"] : defaultParameters["thickness"]; extrusion = parameters.ContainsKey("extrusion") ? parameters["extrusion"] : defaultParameters["extrusion"]; submeshIndex = parameters.ContainsKey("submeshIndex") ? parameters["submeshIndex"] : defaultParameters["submeshIndex"]; extrusionOutwards = parameters.ContainsKey("extrusionOutwards") ? parameters["extrusionOutwards"] : defaultParameters["extrusionOutwards"]; extrusionCenter = parameters.ContainsKey("extrusionCenter") ? parameters["extrusionCenter"] : defaultParameters["extrusionCenter"]; rotateUV = parameters.ContainsKey("rotateUV") ? parameters["rotateUV"] : defaultParameters["rotateUV"]; } /*protected override void ApplyCustomSettings() { // Translate so it starts from (0,0,0) and add original offset to mesh position var startPos = start; end -= start; start = Vector3.zero; position += startPos; }*/ protected override void Generate() { var absEnd = end - start; var cross = Vector3.Cross((absEnd).normalized, Vector3.forward).normalized; var lowerLeft = start - cross * thickness / 2f; var lowerRight = start + cross * thickness / 2f; var upperLeft = lowerLeft + absEnd; var upperRight = lowerRight + absEnd; var secondCross = Vector3.Cross(lowerRight - lowerLeft, upperLeft - lowerLeft).normalized; var lowerLeftBack = lowerLeft + secondCross * extrusion; var lowerRightBack = lowerRight + secondCross * extrusion; var upperLeftBack = upperLeft + secondCross * extrusion; var upperRightBack = upperRight + secondCross * extrusion; if (extrusionCenter) { lowerLeft -= secondCross * extrusion / 2f; lowerRight -= secondCross * extrusion / 2f; upperLeft -= secondCross * extrusion / 2f; upperRight -= secondCross * extrusion / 2f; lowerLeftBack -= secondCross * extrusion / 2f; lowerRightBack -= secondCross * extrusion / 2f; upperLeftBack -= secondCross * extrusion / 2f; upperRightBack -= secondCross * extrusion / 2f; } else if (extrusionOutwards) { lowerLeftBack -= secondCross * (2 * extrusion); lowerRightBack -= secondCross * (2 * extrusion); upperLeftBack -= secondCross * (2 * extrusion); upperRightBack -= secondCross * (2 * extrusion); } AddQuad(lowerLeft, upperLeft, upperRight, lowerRight, submeshIndex, extrusionOutwards, rotateUV ? UVSettings.Rotate : UVSettings.None); AddQuad(lowerRightBack, upperRightBack, upperLeftBack, lowerLeftBack, submeshIndex, extrusionOutwards, rotateUV ? UVSettings.Rotate : UVSettings.None); AddQuad(lowerLeftBack, upperLeftBack, upperLeft, lowerLeft, submeshIndex, extrusionOutwards, rotateUV ? UVSettings.Rotate : UVSettings.None); AddQuad(lowerRight, upperRight, upperRightBack, lowerRightBack, submeshIndex, extrusionOutwards, rotateUV ? UVSettings.Rotate : UVSettings.None); AddQuad(upperLeft, upperLeftBack, upperRightBack, upperRight, submeshIndex, extrusionOutwards, rotateUV ? UVSettings.Rotate : UVSettings.None); AddQuad(lowerRight, lowerRightBack, lowerLeftBack, lowerLeft, submeshIndex, extrusionOutwards, rotateUV ? UVSettings.Rotate : UVSettings.None); } }<file_sep>/Assets/Procedural Art/Scripts/Misc/MarchingSquares/MarchingSquares.cs using System.Collections.Generic; using UnityEngine; using static Direction; public class MarchingSquares { public static List<Vector2Int> March(Arr2d<bool> data) { var directions = new List<Vector2Int>(); var x = 0; var y = 0; while (!data[x, y]) { x++; if (x >= data.Length1) { x = 0; y++; } if (y >= data.Length2) { Debug.LogError("MarchingSquares could not find valid path."); return new List<Vector2Int>(); } } var previous = Vector2Int.zero; var startX = x; var startY = y; do { Vector2Int current; switch (Value(x, y, data)) { case 1: current = N; break; case 2: current = E; break; case 3: current = E; break; case 4: current = W; break; case 5: current = N; break; case 6: current = previous == N ? W : E; break; case 7: current = E; break; case 8: current = S; break; case 9: current = previous == E ? N : S; break; case 10: current = S; break; case 11: current = S; break; case 12: current = W; break; case 13: current = N; break; default: current = W; break; } directions.Add(current); x += current.x; y += current.y; previous = current; } while (x != startX || y != startY); return Path.SimplifyPath(directions); } private static int Value(int x, int y, Arr2d<bool> data) { var sum = 0; if (data[x-1, y-1]) sum |= 1; if (data[x, y-1]) sum |= 2; if (data[x-1, y]) sum |= 4; if (data[x, y]) sum |= 8; return sum; } }<file_sep>/Assets/Procedural Art/Scripts/Settings/OverhangSettings.cs using UnityEngine; [CreateAssetMenu(fileName = "Overhang Settings", menuName = "Overhang Settings", order = 0)] public class OverhangSettings : WallSettings { public float GroundOffset; public Vector2 GroundOffsetVariation; }<file_sep>/Assets/Procedural Art/Scripts/PerlinMapGenerator.cs using System.Collections; using System.Collections.Generic; using System.IO; using System.Net.Mime; using UnityEditor; using UnityEngine; using UnityEngine.Experimental.Rendering; [ExecuteInEditMode] public class PerlinMapGenerator : MonoBehaviour { public int TextureSize = 1024; public float Frequency = 4f; public float Seed = 0; public bool SeparateRGB; public bool Alpha; [HideInInspector] public Texture2D texture; public void Generate() { var texture = new Texture2D(TextureSize, TextureSize, TextureFormat.RGBA32, true); texture.alphaIsTransparency = true; var colors = new Color[TextureSize * TextureSize]; for (int x = 0; x < TextureSize; x++) { for (int y = 0; y < TextureSize; y++) { float r, g, b; var a = 1f; r = g = b = Mathf.PerlinNoise(Seed + (x + 0.01f) / Frequency, Seed + (y + 0.01f) / Frequency); if (SeparateRGB) g = Mathf.PerlinNoise(Seed + Seed + (x + 0.01f) / Frequency, Seed + (y + 0.01f) / Frequency); if (SeparateRGB) b = Mathf.PerlinNoise(Seed + (x + 0.01f) / Frequency, Seed + Seed + (y + 0.01f) / Frequency); if (Alpha) a = Mathf.PerlinNoise(Seed + Seed + (x + 0.01f) / Frequency, Seed + Seed + (y + 0.01f) / Frequency); // Debug.Log($"rgba = {r} {g} {b} {a}"); var vec3 = new Vector4(r, g, b, a); // vec3.Normalize(); colors[x * TextureSize + y] = new Color(r, g, b, a); } } texture.SetPixels(colors); texture.Apply(true, false); this.texture = texture; } } [CustomEditor(typeof(PerlinMapGenerator))] public class PerlinMapGeneratorEditor : Editor { public override void OnInspectorGUI() { base.OnInspectorGUI(); var generator = target as PerlinMapGenerator; if (GUILayout.Button("Generate Seed")) { generator.Seed = Random.Range(0f, (float) (1 << 10)); } if (GUILayout.Button("Generate Image")) { generator.Generate(); } if (generator.texture != null) { GUILayout.Space(6); var rect = GUILayoutUtility.GetAspectRect(1f, GUIStyle.none); // rect.height = rect.width; GUI.DrawTexture(rect, generator.texture); if (GUILayout.Button("Save As...")) { var savePath = EditorUtility.SaveFilePanelInProject("Save As...", "NoiseTexture", "png", "", Application.dataPath); savePath = savePath.Replace(Application.dataPath, "Assets"); if (!string.IsNullOrEmpty(savePath)) { var bytes = generator.texture.EncodeToPNG(); File.WriteAllBytes(savePath, bytes); AssetDatabase.ImportAsset(savePath); } } } } }<file_sep>/Assets/Procedural Art/Scripts/Plots/Editor/PlotCreatorTool.cs using System; using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEditor.EditorTools; using UnityEngine; [EditorTool("Plot Creator", typeof(PlotCreator))] public class PlotCreatorTool : EditorTool { private Vector3 startPoint = Vector3.zero; private Vector3 currentPoint = Vector3.zero; private PlotCreator plotCreator; private bool isDragging; private bool isDraggingSelection; private bool isRemovingFromSelection; private HashSet<int> selectedPlots = new HashSet<int>(); private HashSet<int> plotsUnderSelection = new HashSet<int>(); private int hoveredPlot = -1; private GUIContent iconContent; private Tool currentTool; private int previousSelectedGridIndex; private void OnEnable() { var icon = EditorGUIUtility.isProSkin ? Resources.Load<Texture2D>("PlotCreator/plotCreator_pro") : Resources.Load<Texture2D>("PlotCreator/plotCreator"); iconContent = new GUIContent { image = icon, text = "Plot Creator Tool", tooltip = "Drag with your mouse to create rectangular plots" }; currentTool = Tool.Move; } public override GUIContent toolbarIcon => iconContent; public void Clear() { hoveredPlot = -1; selectedPlots.Clear(); plotsUnderSelection.Clear(); } public override void OnToolGUI(EditorWindow window) { plotCreator = target as PlotCreator; if (plotCreator.SelectedPlotGrid == null) return; if(previousSelectedGridIndex != plotCreator.SelectedPlotGridIndex) Clear(); previousSelectedGridIndex = plotCreator.SelectedPlotGridIndex; if (plotCreator.ShowPlots) { for (int plotI = 0; plotI < plotCreator.PlotGrids.Count; plotI++) { for (var i = 0; i < plotCreator.PlotGrids[plotI].Plots.Count; i++) { Color color; if (plotI == plotCreator.SelectedPlotGridIndex) { color = plotCreator.NormalColor; if (selectedPlots.Contains(i) || (plotsUnderSelection.Contains(i) && !isRemovingFromSelection && isDraggingSelection) || (hoveredPlot == i && !isDragging)) color = plotCreator.SelectedColor; if (plotsUnderSelection.Contains(i) && isRemovingFromSelection && selectedPlots.Contains(i)) color = plotCreator.UnselectColor; if (!plotCreator.IsEnabled) color = Color.gray; } else color = plotCreator.DisabledColor(plotI); var rotated = MathUtils.RotatedRectangle(plotCreator.PlotGrids[plotI].Plots[i]); Handles.DrawSolidRectangleWithOutline(new[] {rotated.leftDown, rotated.leftUp, rotated.rightUp, rotated.rightDown}, color, Color.black); } } } if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.W) { currentTool = Tool.Move; Event.current.Use(); } else if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.E) { currentTool = Tool.Rotate; Event.current.Use(); } else if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.R) { currentTool = Tool.Scale; Event.current.Use(); } if (selectedPlots.Count > 0) { switch (currentTool) { case Tool.Move: { var selectionCenter = Vector3.zero; foreach (var selected in selectedPlots) { var bounds = plotCreator.SelectedPlotGrid.Plots[selected].Bounds; selectionCenter += new Vector3(bounds.center.x, 0, bounds.center.y); var labelStyle = new GUIStyle(EditorStyles.largeLabel) {fontSize = 24, fontStyle = FontStyle.Bold}; Handles.Label(new Vector3(bounds.x, 0, bounds.y), $"{bounds.width} x {bounds.height}", labelStyle); } selectionCenter /= selectedPlots.Count; EditorGUI.BeginChangeCheck(); var offsetToGrid = selectionCenter - selectionCenter.ClosestGridPoint(true); var newPosition = Handles.PositionHandle(selectionCenter, Quaternion.identity).ClosestGridPoint(true); var delta = newPosition - selectionCenter + offsetToGrid; var deltaV2 = new Vector2(delta.x, delta.z); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(plotCreator, "Moved plot(s)"); foreach (var selected in selectedPlots) { plotCreator.SelectedPlotGrid.Plots[selected].Bounds.center += deltaV2; } Event.current.Use(); } break; } case Tool.Rotate: { var labelStyle = new GUIStyle(EditorStyles.largeLabel) {fontSize = 24, fontStyle = FontStyle.Bold}; foreach (var selected in selectedPlots) { var currentPlot = plotCreator.SelectedPlotGrid.Plots[selected]; Handles.Label(new Vector3(currentPlot.Bounds.x, 0, currentPlot.Bounds.y), $"{currentPlot.Rotation}°", labelStyle); EditorGUI.BeginChangeCheck(); var newRotation = Handles.RotationHandle(Quaternion.Euler(0, currentPlot.Rotation, 0), currentPlot.Bounds.center.ToVec3()).eulerAngles.y; if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(plotCreator, "Rotated plot(s)"); currentPlot.Rotation = newRotation; if (currentPlot.Rotation >= 360) currentPlot.Rotation -= 360; Event.current.Use(); } } break; } case Tool.Scale: { foreach (var selected in selectedPlots) { var currentPlot = plotCreator.SelectedPlotGrid.Plots[selected]; EditorGUI.BeginChangeCheck(); var scale = currentPlot.Bounds.size.ToVec3(1); var newScale = Handles.ScaleHandle(scale, currentPlot.Bounds.center.ToVec3(), Quaternion.Euler(0, currentPlot.Rotation, 0), HandleUtility.GetHandleSize(currentPlot.Bounds.center.ToVec3())).ClosestGridPoint(false); if (EditorGUI.EndChangeCheck()) { newScale.y = 0; if (newScale.x <= 0) newScale.x = GlobalSettings.Instance.GridSize; if (newScale.y <= 0) newScale.y = GlobalSettings.Instance.GridSize; Undo.RecordObject(plotCreator, "Scaled plot"); currentPlot.Bounds.size = newScale.ToVec2(); } } break; } } } if (selectedPlots.Count > 0 && Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Delete || Event.current.keyCode == KeyCode.Backspace) { Event.current.Use(); Undo.RecordObject(plotCreator, "Deleted plots"); var plotsToRemove = new List<int>(selectedPlots); plotsToRemove.Sort(); selectedPlots.Clear(); int offset = 0; foreach (var plot in plotsToRemove) { plotCreator.SelectedPlotGrid.Plots.RemoveAt(plot - offset); offset++; } } if (!plotCreator.IsEnabled) return; var rayMouse = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); // rayMouse.origin = rotationRev * rayMouse.origin; if (Physics.Raycast(rayMouse, out var mouseInfo)) { var mousePoint = mouseInfo.point.ClosestGridPoint(true); Handles.color = new Color(1, 1, 1, 0.1f); Handles.DrawSolidDisc(mousePoint, mouseInfo.normal, 0.15f); hoveredPlot = FindIntersectingPlot(new Vector2(mousePoint.x, mousePoint.z)); } plotsUnderSelection.Clear(); if (Event.current.type == EventType.MouseDown && !isDragging && (Event.current.modifiers == EventModifiers.None || Event.current.modifiers.OnlyTheseFlags(EventModifiers.Control) || Event.current.modifiers.OnlyTheseFlags(EventModifiers.Control | EventModifiers.Shift)) && Event.current.button != 2) { var ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); if (Physics.Raycast(ray, out var info)) { if (Event.current.control) { isDraggingSelection = true; } isDragging = true; startPoint = currentPoint = info.point.ClosestGridPoint(true); GUIUtility.hotControl = GUIUtility.GetControlID(FocusType.Passive); Event.current.Use(); /*if (Tools.current != Tool.None) { currentTool = Tools.current; Tools.current = Tool.None; }*/ } } if (isDragging) { var ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); var point = Vector3.zero; if (Physics.Raycast(ray, out var info)) { currentPoint = info.point.ClosestGridPoint(true); var size = currentPoint - startPoint; var alignedSize = size.ClosestGridPoint(false); currentPoint = startPoint + alignedSize; point = info.point; } var labelStyle = new GUIStyle(EditorStyles.largeLabel) {fontSize = 24, fontStyle = FontStyle.Bold}; var currentSize = (currentPoint - startPoint).Abs(); Handles.Label((currentPoint - Vector3.right * currentSize.x), $"{currentSize.x} x {currentSize.z}", labelStyle); Handles.color = Color.white; Handles.DrawSolidDisc(startPoint, info.normal, 0.2f); Handles.DrawSolidDisc(currentPoint, info.normal, 0.2f); isDraggingSelection = Event.current.control; isRemovingFromSelection = isDraggingSelection && Event.current.shift; var minX = Mathf.Min(startPoint.x, currentPoint.x); var maxX = Mathf.Max(startPoint.x, currentPoint.x); var minZ = Mathf.Min(startPoint.z, currentPoint.z); var maxZ = Mathf.Max(startPoint.z, currentPoint.z); var leftBack = new Vector3(minX, 0, minZ); var rightBack = new Vector3(maxX, 0, minZ); var leftFront = new Vector3(minX, 0, maxZ); var rightFront = new Vector3(maxX, 0, maxZ); if (isDraggingSelection) { Handles.color = Color.blue; if (Event.current.shift) Handles.color = Color.red; } Handles.DrawAAConvexPolygon(leftBack, rightBack); Handles.DrawAAConvexPolygon(rightBack, rightFront); Handles.DrawAAConvexPolygon(rightFront, leftFront); Handles.DrawAAConvexPolygon(leftFront, leftBack); var start = new Vector2(leftBack.x, leftBack.z); var end = new Vector2(rightFront.x, rightFront.z); var rect = new Rect {min = start, max = end}; var selection = FindIntersectingPlots(rect); selection.ForEach(i => plotsUnderSelection.Add(i)); if (Event.current.type == EventType.MouseUp) { if (Event.current.button == 0) { var diff = startPoint - currentPoint; if (Math.Abs(diff.x) > 0.0001f && Math.Abs(diff.z) > 0.0001f) { if (isDraggingSelection) { if (selection.Count > 0) { if (Event.current.shift) { selectedPlots.RemoveWhere(i => selection.Contains(i)); } else { selection.ForEach(i => selectedPlots.Add(i)); } } } else { Undo.RecordObject(plotCreator, "Created plot"); plotCreator.SelectedPlotGrid.Plots.Add(Plot.FromStartEnd(start, end)); } } else { var selectedPlot = FindIntersectingPlot(new Vector2(point.x, point.z)); if (selectedPlot != -1) { if (Event.current.control) { if (selectedPlots.Contains(selectedPlot)) selectedPlots.Remove(selectedPlot); else selectedPlots.Add(selectedPlot); } else { selectedPlots.Clear(); selectedPlots.Add(selectedPlot); } } else { if (!Event.current.control) selectedPlots.Clear(); } } // if (selectedPlots.Count == 0) Tools.current = currentTool; } Handles.color = plotCreator.NormalColor; isDragging = false; isDraggingSelection = false; GUIUtility.hotControl = 0; Event.current.Use(); // Tools.current = currentTool; } } } private int FindIntersectingPlot(Vector2 position) { for (var i = 0; i < plotCreator.SelectedPlotGrid.Plots.Count; i++) { if (MathUtils.PointInRotatedRectangle(position, plotCreator.SelectedPlotGrid.Plots[i])) return i; } return -1; } private List<int> FindIntersectingPlots(Rect rect) { var plots = new List<int>(); for (var i = 0; i < plotCreator.SelectedPlotGrid.Plots.Count; i++) { var current = plotCreator.SelectedPlotGrid.Plots[i]; if (MathUtils.RectangleContains(rect, current)) plots.Add(i); } return plots; } }<file_sep>/Assets/Procedural Art/Scripts/Generators/TowerBuildingGenerator.cs using System; using System.Collections.Generic; using UnityEngine; public class TowerBuildingGenerator : BuildingGenerator { private WallSettings towerSettings; public static new bool DoneOnceField; private static float roofHeight; private static float towerHeight; public override MeshData Generate(PlotData plot, BuildingTypeSettings settings, float heightAdjustment, Vector3 offset, int LOD) { towerSettings = settings.GeneratorSettings as WallSettings; DoOnce(ref DoneOnceField); var size = new Vector2Int(Mathf.RoundToInt(plot.Bounds.size.x), Mathf.RoundToInt(plot.Bounds.size.y)); DimensionsA = new Vector2Int(size.x, size.y); DimensionsB = Vector2Int.zero; var boolArr = new Arr2d<bool>(DimensionsA.x, DimensionsA.y, true); var roof = GenRoof(); var path = MarchingSquares.March(boolArr); CleanupOutline(boolArr); var walls = GenWalls(path); var features = GenFeatures(path); return MeshUtils.Combine(roof, walls, features); } public override void DoOnce(ref bool doneOnceField) { if (doneOnceField) return; doneOnceField = true; roofHeight = Rand.Range(towerSettings.RoofHeightVariation.x, towerSettings.RoofHeightVariation.y); towerHeight = towerSettings.Height + Rand.Range(towerSettings.HeightVariation.x, towerSettings.HeightVariation.y); } public override void Setup(BuildingTypeSettings settings) { } private MeshData GenWalls(List<Vector2Int> path) { var walls = new MeshData(); var current = Vector2Int.zero; foreach (var point in path) { var next = current + point; var from = new Vector3(current.x - 0.5f, 0, current.y - 0.5f); var to = new Vector3(next.x - 0.5f, 0, next.y - 0.5f); var diff = to - from; var angle = Vector3.SignedAngle(Vector3.right, diff, Vector3.up); var wallWidth = diff.magnitude; var wall = MeshGenerator.GetMesh<PlaneGenerator>(to, Quaternion.Euler(0, angle - 180, 0), new Dictionary<string, dynamic> { {"sizeA", wallWidth}, {"sizeB", towerHeight}, {"orientation", PlaneGenerator.PlaneOrientation.XY}, {"submeshIndex", 0} }); walls.MergeMeshData(wall); current = next; } return walls; } private MeshData GenRoof() { var cornerA = MeshGenerator.GetMesh<CornerRoofGenerator>(new Vector3(DimensionsA.x - 0.5f, towerHeight, -0.5f), Quaternion.Euler(0, -90, 0), new Dictionary<string, dynamic> { {"width", DimensionsA.y / 2f}, {"height", roofHeight}, {"length", DimensionsA.x / 2.0f}, {"thickness", towerSettings.RoofThickness}, {"addCap", true}, {"joinCaps", true} }); var cornerA1 = MeshGenerator.GetMesh<CornerRoofGenerator>(new Vector3(DimensionsA.x - 0.5f, towerHeight, DimensionsA.y - 0.5f), Quaternion.Euler(0, 180, 0), new Dictionary<string, dynamic> { {"width", DimensionsA.x / 2.0f}, {"height", roofHeight}, {"length", DimensionsA.y / 2f}, {"thickness", towerSettings.RoofThickness}, {"addCap", true}, {"joinCaps", true} }); var cornerB = MeshGenerator.GetMesh<CornerRoofGenerator>(new Vector3(-0.5f, towerHeight, -0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"width", DimensionsA.x / 2.0f}, {"height", roofHeight}, {"length", DimensionsA.y / 2f}, {"thickness", towerSettings.RoofThickness}, {"addCap", true}, {"joinCaps", true} }); var cornerB1 = MeshGenerator.GetMesh<CornerRoofGenerator>(new Vector3(-0.5f, towerHeight, DimensionsA.y - 0.5f), Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"width", DimensionsA.y / 2f}, {"height", roofHeight}, {"length", DimensionsA.x / 2.0f}, {"thickness", towerSettings.RoofThickness}, {"addCap", true}, {"joinCaps", true} }); return MeshUtils.Combine(cornerA, cornerA1, cornerB, cornerB1); } private MeshData GenFeatures(List<Vector2Int> path) { return new MeshData(); } }<file_sep>/Assets/Procedural Art/Scripts/Misc/ListUtils.cs using System; using System.Collections.Generic; using UnityEngine; public static class ListUtils { public static List<T> Combine<T>(params List<T>[] lists) { var combined = new List<T>(); foreach (var list in lists) { combined.AddRange(list); } return combined; } public static int CountAllowNull<T>(this IList<T> list) { if (list != null) return list.Count; return 0; } public static bool NullOrEmpty<T>(this IList<T> list) { if (list != null) return list.Count == 0; return true; } public static List<T> ListFullCopy<T>(this List<T> source) { List<T> objList = new List<T>(source.Count); for (int index = 0; index < source.Count; ++index) objList.Add(source[index]); return objList; } public static List<T> ListFullCopyOrNull<T>(this List<T> source) { if (source == null) return null; return source.ListFullCopy(); } public static void RemoveDuplicates<T>(this List<T> list) where T : class { if (list.Count <= 1) return; for (int index1 = list.Count - 1; index1 >= 0; --index1) { for (int index2 = 0; index2 < index1; ++index2) { if (list[index1] == list[index2]) { list.RemoveAt(index1); break; } } } } public static void Shuffle<T>(this IList<T> list) { int count = list.Count; while (count > 1) { --count; int index = Rand.RangeInclusive(0, count); T obj = list[index]; list[index] = list[count]; list[count] = obj; } } public static void InsertionSort<T>(this IList<T> list, Comparison<T> comparison) { int count = list.Count; for (int index1 = 1; index1 < count; ++index1) { T y = list[index1]; int index2; for (index2 = index1 - 1; index2 >= 0 && comparison(list[index2], y) > 0; --index2) list[index2 + 1] = list[index2]; list[index2 + 1] = y; } } }<file_sep>/Assets/Procedural Art/Scripts/Plots/Editor/PlotCreatorInspector.cs using System; using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEditor.EditorTools; using UnityEditor.Rendering; using UnityEngine; [CustomEditor(typeof(PlotCreator))] public class PlotCreatorInspector : Editor { private bool alreadySetTool; private void OnEnable() { alreadySetTool = false; } private void OnSceneGUI() { if (EditorTools.activeToolType != typeof(PlotCreatorTool) && !alreadySetTool && (target as PlotCreator).IsEnabled) { EditorTools.SetActiveTool<PlotCreatorTool>(); alreadySetTool = true; } } public override void OnInspectorGUI() { var plotCreator = target as PlotCreator; if (plotCreator.PlotGrids.Count == 0) { plotCreator.PlotGrids.Add(new PlotGrid {Name = "Default", Color = Color.green, Plots = new List<Plot>()}); plotCreator.SelectedPlotGridIndex = 0; } if (GUILayout.Button(plotCreator.IsEnabled ? "Disable tool" : "Enable tool")) { plotCreator.IsEnabled = !plotCreator.IsEnabled; } if (GUILayout.Button("Fix plot alignment")) { foreach (var plotGrid in plotCreator.PlotGrids) foreach (var plot in plotGrid.Plots) { plot.Bounds.position = plot.Bounds.position.ClosestGridPoint(true); } } if (GUILayout.Button("Save plots to file")) { var scriptableObject = CreateInstance<PlotScriptableObject>(); scriptableObject.PlotGrids = new List<PlotGridData>(); foreach (var plotGrid in plotCreator.PlotGrids) { var plotGridData = new PlotGridData {Color = plotGrid.Color, Name = plotGrid.Name, Plots = new List<PlotData>()}; plotGridData.Plots.AddRange(plotGrid.Plots.Select(plot => new PlotData {Bounds = plot.Bounds, Rotation = plot.Rotation})); scriptableObject.PlotGrids.Add(plotGridData); } var path = EditorUtility.SaveFilePanelInProject("Save plot file", "New plot file", "asset", ""); if (path.Length != 0) { AssetDatabase.CreateAsset(scriptableObject, path); } } if (GUILayout.Button("Load plots from file")) { if (plotCreator.PlotGrids.Count > 0 && EditorUtility.DisplayDialog("Override Existing Plots", "Are you sure you want to override existing plots by loading a plot file?", "Yes", "No") || plotCreator.PlotGrids.Count == 0) { var path = EditorUtility.OpenFilePanel("Load plot file", "Assets/", "asset"); if (path.Length != 0) { if (path.StartsWith(Application.dataPath)) { path = "Assets" + path.Substring(Application.dataPath.Length); } var asset = AssetDatabase.LoadAssetAtPath<PlotScriptableObject>(path); if (asset != null) { plotCreator.PlotGrids = new List<PlotGrid>(); asset.PlotGrids.ForEach(data => { var plotGrid = new PlotGrid {Color = data.Color, Name = data.Name, Plots = new List<Plot>()}; plotGrid.Plots.AddRange(data.Plots.Select(plotData => Plot.FromStartEnd(plotData.Bounds.min, plotData.Bounds.max, plotData.Rotation))); plotCreator.PlotGrids.Add(plotGrid); }); plotCreator.SelectedPlotGridIndex = 0; } else { EditorUtility.DisplayDialog("Invalid File", "The file you are trying to open is not a valid plot file!", "OK"); } } } } GUILayout.BeginVertical("Plot Grids", GUIStyle.none); if (GUILayout.Button("New layer")) { plotCreator.PlotGrids.Add(new PlotGrid {Name ="New Grid", Color = Color.magenta, Plots = new List<Plot>()}); } var copy = new List<PlotGrid>(plotCreator.PlotGrids); for (var i = 0; i < copy.Count; i++) { GUILayout.BeginHorizontal(); GUI.enabled = i != plotCreator.SelectedPlotGridIndex; if (GUILayout.Button($"Select")) { plotCreator.SelectedPlotGridIndex = i; } GUI.enabled = true; plotCreator.PlotGrids[i].Color = EditorGUILayout.ColorField(plotCreator.PlotGrids[i].Color); plotCreator.PlotGrids[i].Name = EditorGUILayout.TextField(plotCreator.PlotGrids[i].Name); if (GUILayout.Button("x") && copy.Count > 1) { plotCreator.PlotGrids.RemoveAt(i); plotCreator.SelectedPlotGridIndex = 0; } GUILayout.EndHorizontal(); } GUILayout.EndVertical(); base.OnInspectorGUI(); } }<file_sep>/Assets/Procedural Art/Scripts/Mesh Generation/StraightRoofGenerator.cs using System.Collections.Generic; using UnityEngine; public class StraightRoofGenerator : MeshGenerator { private float width; private float length; private float height; private float thickness; private float extrusion; private bool extrusionLeft; private bool extrusionRight; private bool thicknessBasedOnRoofAngle; private bool closeRoof; private bool addCap; private Vector3 capOffset; private bool flip; protected override void SetDefaultSettings() { defaultParameters = new Dictionary<string, dynamic> { {"width", 1f}, {"length", 1f}, {"height", 1f}, {"thickness", 0.1f}, {"extrusion", 0.25f}, {"extrusionLeft", true}, {"extrusionRight", true}, {"thicknessBasedOnRoofAngle", false}, {"addCap", false}, {"capOffset", Vector3.zero}, {"flip", false}, {"closeRoof", false} }; } protected override void DeconstructSettings(Dictionary<string, dynamic> parameters) { width = (parameters.ContainsKey("width") ? parameters["width"] : defaultParameters["width"]) * GlobalSettings.Instance.GridSize; length = (parameters.ContainsKey("length") ? parameters["length"] : defaultParameters["length"]) * GlobalSettings.Instance.GridSize; height = (parameters.ContainsKey("height") ? parameters["height"] : defaultParameters["height"]) * GlobalSettings.Instance.GridSize; thickness = (parameters.ContainsKey("thickness") ? parameters["thickness"] : defaultParameters["thickness"]) * GlobalSettings.Instance.GridSize; extrusion = (parameters.ContainsKey("extrusion") ? parameters["extrusion"] : defaultParameters["extrusion"]) * GlobalSettings.Instance.GridSize; extrusionLeft = parameters.ContainsKey("extrusionLeft") ? parameters["extrusionLeft"] : defaultParameters["extrusionLeft"]; extrusionRight = parameters.ContainsKey("extrusionRight") ? parameters["extrusionRight"] : defaultParameters["extrusionRight"]; thicknessBasedOnRoofAngle = parameters.ContainsKey("thicknessBasedOnRoofAngle") ? parameters["thicknessBasedOnRoofAngle"] : defaultParameters["thicknessBasedOnRoofAngle"]; addCap = parameters.ContainsKey("addCap") ? parameters["addCap"] : defaultParameters["addCap"]; capOffset = (parameters.ContainsKey("capOffset") ? parameters["capOffset"] : defaultParameters["capOffset"]) * GlobalSettings.Instance.GridSize; flip = parameters.ContainsKey("flip") ? parameters["flip"] : defaultParameters["flip"]; closeRoof = parameters.ContainsKey("closeRoof") ? parameters["closeRoof"] : defaultParameters["closeRoof"]; } protected override void Generate() { var cap10 = new Vector3(extrusionLeft ? (flip ? extrusion : -extrusion) : 0, thickness, 0); var cap11 = new Vector3(flip ? -width - (extrusionRight ? extrusion : 0) : width + (extrusionRight ? extrusion : 0), thickness, 0); var cap12 = new Vector3(flip ? -width - (extrusionRight ? extrusion : 0) : width + (extrusionRight ? extrusion : 0), 0, 0); var cap13 = new Vector3(extrusionLeft ? (flip ? extrusion : -extrusion) : 0, 0, 0); var cap20 = new Vector3(extrusionLeft ? (flip ? extrusion : -extrusion) : 0, height - thickness, length); var cap21 = new Vector3(flip ? -width - (extrusionRight ? extrusion : 0) : width + (extrusionRight ? extrusion : 0), height - thickness, length); var cap22 = new Vector3(flip ? -width - (extrusionRight ? extrusion : 0) : width + (extrusionRight ? extrusion : 0), height, length); var cap23 = new Vector3(extrusionLeft ? (flip ? extrusion : -extrusion) : 0, height, length); var cap30 = new Vector3(extrusionLeft ? (flip ? extrusion : -extrusion) : 0 + capOffset.z, capOffset.y, -thickness + capOffset.x); var cap31 = new Vector3((flip ? -width - (extrusionRight ? extrusion : 0) : width + (extrusionRight ? extrusion : 0)) + capOffset.z, capOffset.y, -thickness + capOffset.x); var cap40 = new Vector3(flip ? -width : width, 0, 0); var cap41 = new Vector3(flip ? -width : width, height - thickness, length); var cap42 = new Vector3(flip ? -width : width, 0, length); var cap50 = new Vector3(0, 0, 0); var cap51 = new Vector3(0, height - thickness, length); var cap52 = new Vector3(0, 0, length); if (thicknessBasedOnRoofAngle) { var v1 = cap11 - cap12; var v2 = cap21 - cap12; var angle = Mathf.Deg2Rad * Vector3.Angle(v1, v2); var multiplier = 1f / Mathf.Sin(angle); var actualRoofThickness = thickness * multiplier; cap10.y = actualRoofThickness; cap11.y = actualRoofThickness; cap20.y = height - actualRoofThickness; cap21.y = height - actualRoofThickness; cap30.z = -actualRoofThickness + capOffset.x; cap31.z = -actualRoofThickness + capOffset.x; cap41.y = height - actualRoofThickness; cap51.y = height - actualRoofThickness; } AddQuad(cap10, cap11, cap12, cap13, 1, flip); AddQuad(cap20, cap21, cap22, cap23, 1, flip); AddQuad(cap13, cap12, cap21, cap20, 1, flip); AddQuad(cap12, cap11, cap22, cap21, 1, flip); AddQuad(cap10, cap13, cap20, cap23, 1, flip); AddQuad(cap10, cap23, cap22, cap11, 1, flip); if (addCap) { AddTriangle(cap12, cap31, cap11, 1, flip); AddTriangle(cap13, cap10, cap30, 1, flip); AddQuad(cap12, cap13, cap30, cap31, 1, flip, UVSettings.FlipHorizontal); AddQuad(cap10, cap11, cap31, cap30, 1, flip, UVSettings.FlipHorizontal); } if (closeRoof) { AddTriangle(cap42, cap41, cap40, 0, !flip, UVSettings.FlipBottomPart); AddTriangle(cap52, cap51, cap50, 0, flip, UVSettings.FlipHorizontal); } } }<file_sep>/Assets/Procedural Art/Scripts/Settings/MarketSettings.cs using UnityEngine; [CreateAssetMenu(fileName = "Market Settings", menuName = "Market Settings", order = 0)] public class MarketSettings : ScriptableObject { public float MinDistanceFromCenter = 2f; public Vector2Int MinMaxStalls = (Vector2Int.one + Vector2Int.up) * 4; public Vector2Int MinMaxDetails = (Vector2Int.one + Vector2Int.up) * 4; public Vector2Int MinMaxTreeClumps = (Vector2Int.one + Vector2Int.up) * 4; public Vector2Int MinMaxTreesPerClump = Vector2Int.one * 2 + Vector2Int.up * 2; public float MaxTreeDistance = 1f; public float MinTreeDistance = 0.25f; public float BorderDistance = 3f; }<file_sep>/Assets/Procedural Art/Scripts/CameraRotator.cs using UnityEditor; using UnityEngine; [ExecuteInEditMode] public class CameraRotator : MonoBehaviour { public Transform Upper; public Transform Lower; public Transform Camera; public float RotationSpeedUpper = 2f; public float RotationSpeedLower = 0.05f; [Space] public bool ShowUpper = true; public float TransitionTime = 2f; private bool lastShowUpper; private bool isTransitioning; private Vector3 sourceTransitionPosition; private Vector3 targetTransitionPosition; private Quaternion sourceTransitionRotation; private Quaternion targetTransitionRotation; private float sourceRotationSpeed; private float targetRotationSpeed; private float currentRotationSpeed; private float transitionTimer; private void OnEnable() { EditorApplication.update += Update; } private void OnDisable() { EditorApplication.update -= Update; } private void Update() { if (ShowUpper != lastShowUpper) { // start transition isTransitioning = true; sourceTransitionPosition = (ShowUpper ? Lower : Upper).localPosition; targetTransitionPosition = (ShowUpper ? Upper : Lower).localPosition; sourceTransitionRotation = (ShowUpper ? Lower : Upper).localRotation; targetTransitionRotation = (ShowUpper ? Upper : Lower).localRotation; sourceRotationSpeed = ShowUpper ? RotationSpeedLower : RotationSpeedUpper; targetRotationSpeed = ShowUpper ? RotationSpeedUpper : RotationSpeedLower; transitionTimer = TransitionTime - transitionTimer; } lastShowUpper = ShowUpper; if (isTransitioning) { transitionTimer += Time.smoothDeltaTime; Camera.localPosition = Vector3.Lerp(sourceTransitionPosition, targetTransitionPosition, MathUtils.EaseInOut(transitionTimer/TransitionTime)); Camera.localRotation = Quaternion.Slerp(sourceTransitionRotation, targetTransitionRotation, MathUtils.EaseInOut(transitionTimer/TransitionTime)); currentRotationSpeed = Mathf.Lerp(sourceRotationSpeed, targetRotationSpeed, MathUtils.EaseInOut(transitionTimer/TransitionTime)); if (transitionTimer >= TransitionTime) { isTransitioning = false; } } if(!isTransitioning) { Camera.localPosition = (ShowUpper ? Upper : Lower).localPosition; Camera.localRotation = (ShowUpper ? Upper : Lower).localRotation; currentRotationSpeed = ShowUpper ? RotationSpeedUpper : RotationSpeedLower; } var currentRotation = transform.eulerAngles; currentRotation.y += currentRotationSpeed * Time.smoothDeltaTime; if (currentRotation.y >= 360) currentRotation.y -= 360; transform.eulerAngles = currentRotation; } }<file_sep>/Assets/Procedural Art/Scripts/Data/MeshData.cs using System.Collections.Generic; using UnityEngine; public class MeshData { public readonly List<Vector3> Vertices; public readonly List<Vector2> UVs; public readonly Dictionary<int, List<int>> Triangles; public MeshData() { Vertices = new List<Vector3>(); UVs = new List<Vector2>(); Triangles = new Dictionary<int, List<int>>(); } public void AppendMeshData(List<Vector3> vertices, List<Vector2> uvs, List<int> triangles, int submeshIndex) { FixTriangles(triangles); Vertices.AddRange(vertices); UVs.AddRange(uvs); if (!Triangles.ContainsKey(submeshIndex)) { Triangles[submeshIndex] = new List<int>(); } Triangles[submeshIndex].AddRange(triangles); } public void AppendMeshData((List<Vector3> vertices, List<int> triangles) meshData, int submeshIndex) { AppendMeshData(meshData.vertices, new List<Vector2>(), meshData.triangles, submeshIndex); } public void AppendMeshData((List<Vector3> vertices, List<Vector2> uvs, List<int> triangles) meshData, int submeshIndex) { AppendMeshData(meshData.vertices, meshData.uvs, meshData.triangles, submeshIndex); } public void MergeMeshData(MeshData meshData) { foreach (var key in meshData.Triangles.Keys) { FixTriangles(meshData.Triangles[key]); if (!Triangles.ContainsKey(key)) Triangles[key] = new List<int>(); Triangles[key].AddRange(meshData.Triangles[key]); } Vertices.AddRange(meshData.Vertices); UVs.AddRange(meshData.UVs); } private void FixTriangles(List<int> triangles) { var offset = Vertices.Count; for (var i = 0; i < triangles.Count; i++) { triangles[i] += offset; } } public void Translate(Vector3 position) { for (var i = 0; i < Vertices.Count; i++) { Vertices[i] += position; } } public void Rotate(Quaternion rotation) { for (var i = 0; i < Vertices.Count; i++) { Vertices[i] = rotation * Vertices[i]; } } public void Rotate(Quaternion rotation, Vector3 around) { for (var i = 0; i < Vertices.Count; i++) { Vertices[i] = rotation * (Vertices[i]-around) + around; } } }<file_sep>/Assets/Procedural Art/Scripts/Generators/NormalSBuildingGenerator.cs using System.Collections.Generic; using UnityEngine; public class NormalSBuildingGenerator : BuildingGenerator { public static new bool DoneOnceField = false; public override void DoOnce(ref bool doneOnceField) { if (doneOnceField) return; doneOnceField = true; } public override void Setup(BuildingTypeSettings settings) { } public override MeshData Generate(PlotData plot, BuildingTypeSettings settings, float heightAdjustment, Vector3 offset, int LOD) { DoOnce(ref DoneOnceField); var size = new Vector2Int(Mathf.RoundToInt(plot.Bounds.size.x), Mathf.RoundToInt(plot.Bounds.size.y)); var boolArr = GenSquare(size, heightAdjustment); var roofs = GenSquareRoof(); var path = MarchingSquares.March(boolArr); CleanupOutline(boolArr); var walls = GenWalls(path, LOD); var mesh = MeshUtils.Combine(roofs, walls); return mesh; } protected override MeshData AddWallFeatures(Vector3 wallStart, Vector3 wallEnd, float buildingHeight, float wallWidth, float wallAngle, int LOD, bool addPillar = true) { var thickness = GeneratorSettings.GeneralSettings.FeatureThickness; var pillarThickness = GeneratorSettings.GeneralSettings.PillarThickness; var windowChance = GeneratorSettings.GeneralSettings.WindowChance; var wallDirection = (wallEnd - wallStart).normalized; var wallPerpendicular = Vector3.Cross(wallDirection, Vector3.up); var wallSize = Mathf.RoundToInt((wallEnd - wallStart).magnitude); var features = new MeshData(); if (addPillar) { var pillar = MeshGenerator.GetMesh<LineGenerator>(wallEnd - Vector3.forward * pillarThickness / 2f, Quaternion.identity, new Dictionary<string, dynamic> { {"end", Vector3.up * buildingHeight}, {"thickness", pillarThickness}, {"extrusion", pillarThickness}, {"submeshIndex", 2}, {"extrusionOutwards", false} }); features.MergeMeshData(pillar); features.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(wallPerpendicular * 0.035f + wallEnd + Vector3.up * buildingHeight, Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector2.left * (0.4f * pillarThickness)}, {"end", Vector2.left * (wallSize + 0.7f * pillarThickness)}, {"thickness", pillarThickness}, {"extrusion", pillarThickness}, {"submeshIndex", 2}, {"extrusionCenter", true}, {"rotateUV", true} })); } var splitSectionsVertical = new List<float> {0, 1}; var lastSplitPoint = splitSectionsVertical[1]; while (lastSplitPoint < buildingHeight) { var nextSize = RandUtils.RandomBetween(GeneratorSettings.GeneralSettings.VerticalSplitMinMax); if (lastSplitPoint + nextSize < buildingHeight && lastSplitPoint + nextSize > buildingHeight - 1) nextSize = buildingHeight - lastSplitPoint - 1; lastSplitPoint += nextSize; if (lastSplitPoint >= buildingHeight) lastSplitPoint = buildingHeight; splitSectionsVertical.Add(lastSplitPoint); } var splitSectionsHorizontal = new List<float> {0}; var lastSplitPointH = splitSectionsHorizontal[0]; while (lastSplitPointH < wallSize) { var nextSize = RandUtils.RandomBetween(GeneratorSettings.GeneralSettings.HorizontalSplitMinMax); if (lastSplitPointH + nextSize < wallSize && lastSplitPointH + nextSize > wallSize - 1) nextSize = wallSize - lastSplitPointH - 1; lastSplitPointH += nextSize; if (lastSplitPointH > wallSize) lastSplitPointH = wallSize; splitSectionsHorizontal.Add(lastSplitPointH); } for (var i = 1; i < splitSectionsVertical.Count; i++) { var sectionHeight = splitSectionsVertical[i] - splitSectionsVertical[i - 1]; var addWindow = wallSize > 2 && RandUtils.BoolWeighted(windowChance) && LOD <= 1; var windowWidth = 0.0f; var windowHeight = 0.0f; if (addWindow) { windowHeight = Rand.Range(1f, Mathf.Max(1f, sectionHeight * 0.75f)); } for (var i2 = 1; i2 < splitSectionsHorizontal.Count; i2++) { var sectionWidth = splitSectionsHorizontal[i2] - splitSectionsHorizontal[i2 - 1]; var addWindowHorizontal = addWindow; if (RandUtils.BoolWeighted(windowChance / 2.0f)) addWindowHorizontal = false; if (addWindowHorizontal) { windowWidth = Mathf.Min(sectionWidth - pillarThickness, Rand.Range(1f, Mathf.Max(1f, sectionWidth * 0.75f))); } if (i2 != splitSectionsHorizontal.Count - 1) { var verticalLine = MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * splitSectionsHorizontal[i2], Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * buildingHeight}, {"thickness", pillarThickness}, {"extrusion", pillarThickness}, {"submeshIndex", 2}, {"extrusionCenter", true} }); features.MergeMeshData(verticalLine); } if (i == 1) continue; if (LOD <= 1 && addWindowHorizontal) { var windowPosition = splitSectionsHorizontal[i2] - 0.5f * (sectionWidth); var window = MeshGenerator.GetMesh<PlaneGenerator>(wallStart + wallDirection * (windowPosition + 0.5f * windowWidth) + Vector3.up * (splitSectionsVertical[i - 1] + thickness / 2f) + wallPerpendicular * thickness / 4f, Quaternion.Euler(0, wallAngle - 180, 0), new Dictionary<string, dynamic> { {"sizeA", windowWidth}, {"sizeB", windowHeight}, {"orientation", PlaneGenerator.PlaneOrientation.XY}, {"submeshIndex", 3}, {"extraUvSettings", MeshGenerator.UVSettings.NoOffset} }); features.MergeMeshData(window); /* BEGIN Frame */ features.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition - 0.5f * windowWidth) + Vector3.up * (splitSectionsVertical[i - 1] + 0.33334f * windowHeight), Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.right * windowWidth}, {"thickness", 0.035f}, {"extrusion", 0.035f}, {"submeshIndex", 2}, {"rotateUV", true} })); features.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition - 0.5f * windowWidth) + Vector3.up * (splitSectionsVertical[i - 1] + windowHeight - 0.33334f * windowHeight), Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.right * windowWidth}, {"thickness", 0.035f}, {"extrusion", 0.035f}, {"submeshIndex", 2}, {"rotateUV", true} })); features.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition + 0.5f * windowWidth - 0.33334f * windowWidth) + Vector3.up * (splitSectionsVertical[i - 1] + thickness / 2f) - wallPerpendicular * 0.005f, Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * (windowHeight - thickness / 2f)}, {"thickness", 0.035f}, {"extrusion", 0.035f}, {"submeshIndex", 2}, {"rotateUV", true} })); features.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition - 0.5f * windowWidth + 0.33334f * windowWidth) + Vector3.up * (splitSectionsVertical[i - 1] + thickness / 2f) - wallPerpendicular * 0.005f, Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * (windowHeight - thickness / 2f)}, {"thickness", 0.035f}, {"extrusion", 0.035f}, {"submeshIndex", 2}, {"rotateUV", true} })); /* END Frame */ if (sectionHeight > 1) { var line = MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition - 0.5f * windowWidth) + Vector3.up * (splitSectionsVertical[i - 1] + windowHeight) - wallPerpendicular * thickness / 2f, Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.right * windowWidth}, {"thickness", thickness}, {"extrusion", thickness}, {"submeshIndex", 2}, {"rotateUV", true} }); features.MergeMeshData(line); } if (sectionWidth > 1) { var lineLeft = MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition + 0.5f * windowWidth + 0.5f * thickness) + Vector3.up * (splitSectionsVertical[i - 1] + thickness / 2f) - wallPerpendicular * thickness / 2f, Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * windowHeight}, {"thickness", thickness}, {"extrusion", thickness}, {"submeshIndex", 2}, {"rotateUV", true} }); features.MergeMeshData(lineLeft); var lineRight = MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition - 0.5f * windowWidth - 0.5f * thickness) + Vector3.up * (splitSectionsVertical[i - 1] + thickness / 2f) - wallPerpendicular * thickness / 2f, Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * windowHeight}, {"thickness", thickness}, {"extrusion", thickness}, {"submeshIndex", 2}, {"rotateUV", true} }); features.MergeMeshData(lineRight); } } } } return features; } protected override MeshData GenSquareRoof() { var baseRoof = base.GenSquareRoof(); var pillarThickness = GeneratorSettings.GeneralSettings.PillarThickness; var halfWidth = DimensionsA.y / 2; if (DimensionsA.y % 2 == 0) { var stepHeight = (RoofHeight - 1f) / (halfWidth - 1); for (var i = 0; i < halfWidth; i++) { baseRoof.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(Vector3.up * (BuildingHeight + pillarThickness / 2.0f) + Vector3.forward * (i - 0.5f * pillarThickness) + Vector3.right * (-0.5f - 0.2f * pillarThickness), Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * (1f + i * stepHeight)}, {"thickness", pillarThickness}, {"extrusion", 1f}, {"submeshIndex", 2}, {"extrusionCenter", true}, {"rotateUV", false} })); baseRoof.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(Vector3.up * (BuildingHeight + pillarThickness / 2.0f) + Vector3.forward * (i - 0.5f * pillarThickness) + Vector3.right * (DimensionsA.x - 0.5f + 0.2f * pillarThickness), Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * (1f + i * stepHeight)}, {"thickness", pillarThickness}, {"extrusion", 1f}, {"submeshIndex", 2}, {"extrusionCenter", true}, {"rotateUV", false} })); baseRoof.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(Vector3.up * (BuildingHeight + pillarThickness / 2.0f) + Vector3.forward * (DimensionsA.y / 2.0f + i + 0.5f * pillarThickness) + Vector3.right * (-0.5f - 0.2f * pillarThickness), Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * (1f + (halfWidth - i - 1) * stepHeight)}, {"thickness", pillarThickness}, {"extrusion", 1f}, {"submeshIndex", 2}, {"extrusionCenter", true}, {"rotateUV", false} })); baseRoof.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(Vector3.up * (BuildingHeight + pillarThickness / 2.0f) + Vector3.forward * (DimensionsA.y / 2.0f + i + 0.5f * pillarThickness) + Vector3.right * (DimensionsA.x - 0.5f + 0.2f * pillarThickness), Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * (1f + (halfWidth - i - 1) * stepHeight)}, {"thickness", pillarThickness}, {"extrusion", 1f}, {"submeshIndex", 2}, {"extrusionCenter", true}, {"rotateUV", false} })); } baseRoof.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(Vector3.up * (BuildingHeight + pillarThickness / 2.0f) + Vector3.forward * (DimensionsA.y / 2.0f - 0.5f) + Vector3.right * (-0.5f - 0.2f * pillarThickness), Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * (1f + (halfWidth - 0.5f) * stepHeight)}, {"thickness", pillarThickness}, {"extrusion", 1f}, {"submeshIndex", 2}, {"extrusionCenter", true}, {"rotateUV", false} })); baseRoof.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(Vector3.up * (BuildingHeight + pillarThickness / 2.0f) + Vector3.forward * (DimensionsA.y / 2.0f - 0.5f) + Vector3.right * (DimensionsA.x - 0.5f + 0.2f * pillarThickness), Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * (1f + (halfWidth - 0.5f) * stepHeight)}, {"thickness", pillarThickness}, {"extrusion", 1f}, {"submeshIndex", 2}, {"extrusionCenter", true}, {"rotateUV", false} })); } else if(DimensionsA.y % 2 == 1) { var stepHeight = (RoofHeight - 1f) / (halfWidth - 1); for (var i = 0; i < halfWidth; i++) { baseRoof.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(Vector3.up * (BuildingHeight + pillarThickness / 2.0f) + Vector3.forward * (i - 0.5f * pillarThickness) + Vector3.right * (-0.5f - 0.2f * pillarThickness), Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * (1f + i * stepHeight)}, {"thickness", pillarThickness}, {"extrusion", 1f}, {"submeshIndex", 2}, {"extrusionCenter", true}, {"rotateUV", false} })); baseRoof.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(Vector3.up * (BuildingHeight + pillarThickness / 2.0f) + Vector3.forward * (i - 0.5f * pillarThickness) + Vector3.right * (DimensionsA.x - 0.5f + 0.2f * pillarThickness), Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * (1f + i * stepHeight)}, {"thickness", pillarThickness}, {"extrusion", 1f}, {"submeshIndex", 2}, {"extrusionCenter", true}, {"rotateUV", false} })); baseRoof.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(Vector3.up * (BuildingHeight + pillarThickness / 2.0f) + Vector3.forward * (DimensionsA.y / 2.0f + i + 0.5f * pillarThickness + 0.5f) + Vector3.right * (-0.5f - 0.2f * pillarThickness), Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * (1f + (halfWidth - i - 1) * stepHeight)}, {"thickness", pillarThickness}, {"extrusion", 1f}, {"submeshIndex", 2}, {"extrusionCenter", true}, {"rotateUV", false} })); baseRoof.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(Vector3.up * (BuildingHeight + pillarThickness / 2.0f) + Vector3.forward * (DimensionsA.y / 2.0f + i + 0.5f * pillarThickness + 0.5f) + Vector3.right * (DimensionsA.x - 0.5f + 0.2f * pillarThickness), Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * (1f + (halfWidth - i - 1) * stepHeight)}, {"thickness", pillarThickness}, {"extrusion", 1f}, {"submeshIndex", 2}, {"extrusionCenter", true}, {"rotateUV", false} })); } baseRoof.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(Vector3.up * (BuildingHeight + pillarThickness / 2.0f) + Vector3.forward * (DimensionsA.y / 2.0f - 0.5f) + Vector3.right * (-0.5f - 0.2f * pillarThickness), Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * (1f + halfWidth * stepHeight)}, {"thickness", pillarThickness}, {"extrusion", 1f + pillarThickness}, {"submeshIndex", 2}, {"extrusionCenter", true}, {"rotateUV", false} })); baseRoof.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(Vector3.up * (BuildingHeight + pillarThickness / 2.0f) + Vector3.forward * (DimensionsA.y / 2.0f - 0.5f) + Vector3.right * (DimensionsA.x - 0.5f + 0.2f * pillarThickness), Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * (1f + halfWidth * stepHeight)}, {"thickness", pillarThickness}, {"extrusion", 1f + pillarThickness}, {"submeshIndex", 2}, {"extrusionCenter", true}, {"rotateUV", false} })); } return baseRoof; } }<file_sep>/Assets/Procedural Art/Scripts/Generators/BuildingGenerator.cs using System.Collections.Generic; using UnityEngine; public class LODData { public readonly Mesh Mesh; public readonly MeshFilter MeshFilter; public readonly MeshRenderer MeshRenderer; public LODData(GameObject parent, string LODName) { Mesh = new Mesh {name = $"Building_{LODName}"}; MeshFilter = parent.GetComponent<MeshFilter>(); MeshRenderer = parent.GetComponent<MeshRenderer>(); } } [ExecuteInEditMode] public class BuildingGenerator : MonoBehaviour { public static bool DoneOnceField = false; public GameObject LOD0; public GameObject LOD1; public GameObject LOD2; [Space] public GameObject SmokePrefab; public LODData LOD0Data; public LODData LOD1Data; public LODData LOD2Data; protected float BuildingHeight; protected float RoofHeight; protected Vector2Int DimensionsA; protected Vector2Int DimensionsB; protected SLSettings GeneratorSettings; private bool addedSmoke; private bool triedToAddSmoke; public virtual void DoOnce(ref bool doneOnceField) { if (doneOnceField) return; doneOnceField = true; } public void GenerateFromPlot(PlotData plot, BuildingTypeSettings settings, float heightAdjustment, Vector3 offset) { GeneratorSettings = settings.GeneratorSettings as SLSettings; SetupLOD(); Setup(settings); SetupMaterials(settings); addedSmoke = false; // This keeps the buildings mainly the same over the different LOD levels var buildingSeed = Rand.Int; Rand.PushState(buildingSeed); var lod0 = Generate(plot, settings, heightAdjustment, offset, 0); Rand.PopState(); Rand.PushState(buildingSeed); var lod1 = Generate(plot, settings, heightAdjustment, offset, 1); Rand.PopState(); Rand.PushState(buildingSeed); var lod2 = Generate(plot, settings, heightAdjustment, offset, 2); Rand.PopState(); var finalMesh0 = MeshUtils.Translate(lod0, -0.5f * plot.Bounds.size.ToVec3() + new Vector3(0.5f, 0, 0.5f) /* + offset*/); var finalMesh1 = MeshUtils.Translate(lod1, -0.5f * plot.Bounds.size.ToVec3() + new Vector3(0.5f, 0, 0.5f) /* + offset*/); var finalMesh2 = MeshUtils.Translate(lod2, -0.5f * plot.Bounds.size.ToVec3() + new Vector3(0.5f, 0, 0.5f) /* + offset*/); SetMesh(LOD0Data, finalMesh0); SetMesh(LOD1Data, finalMesh1); SetMesh(LOD2Data, finalMesh2); } private void SetupLOD() { LOD0Data = new LODData(LOD0, "LOD0"); LOD1Data = new LODData(LOD1, "LOD1"); LOD2Data = new LODData(LOD2, "LOD2"); } public virtual void Setup(BuildingTypeSettings settings) { } private void SetupMaterials(BuildingTypeSettings settings) { var sharedMaterials = new Material[6]; LOD0Data.MeshRenderer.sharedMaterial = settings.MaterialSetting.WallMaterial; LOD1Data.MeshRenderer.sharedMaterial = settings.MaterialSetting.WallMaterial; LOD2Data.MeshRenderer.sharedMaterial = settings.MaterialSetting.WallMaterial; sharedMaterials[0] = settings.MaterialSetting.WallMaterial; sharedMaterials[1] = settings.MaterialSetting.RoofMaterial; sharedMaterials[2] = settings.MaterialSetting.FeatureMaterial1 != null ? settings.MaterialSetting.FeatureMaterial1 : settings.MaterialSetting.WallMaterial; sharedMaterials[3] = settings.MaterialSetting.WindowMaterial; sharedMaterials[4] = settings.MaterialSetting.FeatureMaterial2 != null ? settings.MaterialSetting.FeatureMaterial2 : settings.MaterialSetting.WallMaterial; sharedMaterials[5] = settings.MaterialSetting.FeatureMaterial3 != null ? settings.MaterialSetting.FeatureMaterial3 : settings.MaterialSetting.WallMaterial; LOD0Data.MeshRenderer.sharedMaterials = sharedMaterials; LOD1Data.MeshRenderer.sharedMaterials = sharedMaterials; LOD2Data.MeshRenderer.sharedMaterials = sharedMaterials; } private void SetMesh(LODData lodData, MeshData mesh) { if (lodData.MeshFilter.sharedMesh != null) DestroyImmediate(lodData.MeshFilter.sharedMesh); lodData.MeshFilter.sharedMesh = lodData.Mesh; lodData.Mesh.SetVertices(mesh.Vertices); lodData.Mesh.SetUVs(0, mesh.UVs); lodData.Mesh.subMeshCount = lodData.MeshRenderer.sharedMaterials.Length; foreach (var submesh in mesh.Triangles.Keys) { lodData.Mesh.SetTriangles(mesh.Triangles[submesh], submesh); } lodData.Mesh.RecalculateNormals(); } public virtual MeshData Generate(PlotData plot, BuildingTypeSettings settings, float heightAdjustment, Vector3 offset, int LOD) { DoOnce(ref DoneOnceField); var size = new Vector2Int(Mathf.RoundToInt(plot.Bounds.size.x), Mathf.RoundToInt(plot.Bounds.size.y)); var boolArr = GenSquare(size, heightAdjustment); var roofs = GenSquareRoof(); var path = MarchingSquares.March(boolArr); CleanupOutline(boolArr); var walls = GenWalls(path, LOD); var mesh = MeshUtils.Combine(roofs, walls); return mesh; } protected Arr2d<bool> GenSquare(Vector2Int size, float heightAdjustment) { BuildingHeight = heightAdjustment + RandUtils.RandomBetween(GeneratorSettings.SquareSettings.MinMaxHeight); DimensionsA = new Vector2Int(size.x, size.y); DimensionsB = Vector2Int.zero; var boolArr = new Arr2d<bool>(DimensionsA.x, DimensionsA.y, true); return boolArr; } protected virtual MeshData GenSquareRoof() { RoofHeight = RandUtils.RandomBetween(GeneratorSettings.SquareSettings.MinMaxRoofHeight); var thickness = GeneratorSettings.GeneralSettings.RoofThickness; var extrusion = GeneratorSettings.GeneralSettings.RoofExtrusion; var roofTypeRandomizer = new WeightedRandom(GeneratorSettings.SquareSettings.StraightRoofChance, GeneratorSettings.SquareSettings.DoubleCornerRoofChance, GeneratorSettings.SquareSettings.CornerRoofChance); roofTypeRandomizer.NormalizeWeights(); roofTypeRandomizer.CalculateAdditiveWeights(); var roofValue = roofTypeRandomizer.Value(); var straightRoof = roofValue == 0; var doubleCornerRoof = roofValue == 1; var chimneyChance = GeneratorSettings.GeneralSettings.ChimneyChance; var chimneySmokeChance = GeneratorSettings.GeneralSettings.ChimneySmokeChance; var chimneyThickness = RandUtils.RandomBetween(GeneratorSettings.GeneralSettings.ChimneyThicknessMinMax); var chimney = new MeshData(); if (RandUtils.BoolWeighted(chimneyChance)) { var chimneyHeight = RoofHeight / 2.0f + Rand.Range(0f, RoofHeight / 2.0f); var chimneyX = Rand.Range(chimneyThickness, DimensionsA.x - chimneyThickness); var chimneyZ = Rand.Range(chimneyThickness, 0.2f * DimensionsA.y); chimney.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(new Vector3(chimneyX, BuildingHeight, chimneyZ), Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * chimneyHeight}, {"thickness", chimneyThickness}, {"extrusion", chimneyThickness}, {"extrusionCenter", true}, {"submeshIndex", 4} })); if (RandUtils.BoolWeighted(chimneySmokeChance) && !addedSmoke && !triedToAddSmoke) { var smoke = Instantiate(SmokePrefab, Vector3.zero, Quaternion.identity); smoke.transform.parent = transform; smoke.transform.localPosition = new Vector3(chimneyX - DimensionsA.x / 2.0f + 0.5f, BuildingHeight + chimneyHeight - 0.5f, chimneyZ - DimensionsA.y / 2.0f + 0.5f); addedSmoke = true; } triedToAddSmoke = true; } if (straightRoof) { var roofA = MeshGenerator.GetMesh<StraightRoofGenerator>(new Vector3(-0.5f, BuildingHeight, -0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"width", DimensionsA.x}, {"height", RoofHeight}, {"thickness", thickness}, {"length", DimensionsA.y / 2f}, {"extrusion", extrusion}, {"addCap", true}, {"closeRoof", true} }); var roofA1 = MeshGenerator.GetMesh<StraightRoofGenerator>(new Vector3(DimensionsA.x - 0.5f, BuildingHeight, DimensionsA.y - 0.5f), Quaternion.Euler(0, 180, 0), new Dictionary<string, dynamic> { {"width", DimensionsA.x}, {"height", RoofHeight}, {"thickness", thickness}, {"length", DimensionsA.y / 2f}, {"extrusion", extrusion}, {"addCap", true}, {"closeRoof", true} }); return MeshUtils.Combine(chimney, roofA, roofA1); } var cornerWidth = DimensionsA.y * RandUtils.RandomBetween(GeneratorSettings.SquareSettings.RoofWidthToBuildingWidthRatio); if (doubleCornerRoof) { var cornerA = MeshGenerator.GetMesh<CornerRoofGenerator>(new Vector3(DimensionsA.x - 0.5f, BuildingHeight, -0.5f), Quaternion.Euler(0, -90, 0), new Dictionary<string, dynamic> { {"width", cornerWidth}, {"height", RoofHeight}, {"length", DimensionsA.x / 2.0f}, {"thickness", thickness}, {"addCap", true}, {"joinCaps", true} }); var cornerA1 = MeshGenerator.GetMesh<CornerRoofGenerator>(new Vector3(DimensionsA.x - 0.5f, BuildingHeight, DimensionsA.y - 0.5f), Quaternion.Euler(0, 180, 0), new Dictionary<string, dynamic> { {"width", DimensionsA.x / 2.0f}, {"height", RoofHeight}, {"length", cornerWidth}, {"thickness", thickness}, {"addCap", true}, {"joinCaps", true} }); var cornerB = MeshGenerator.GetMesh<CornerRoofGenerator>(new Vector3(-0.5f, BuildingHeight, -0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"width", DimensionsA.x / 2.0f}, {"height", RoofHeight}, {"length", cornerWidth}, {"thickness", thickness}, {"addCap", true}, {"joinCaps", true} }); var cornerB1 = MeshGenerator.GetMesh<CornerRoofGenerator>(new Vector3(-0.5f, BuildingHeight, DimensionsA.y - 0.5f), Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"width", cornerWidth}, {"height", RoofHeight}, {"length", DimensionsA.x / 2.0f}, {"thickness", thickness}, {"addCap", true}, {"joinCaps", true} }); var roofA = MeshGenerator.GetMesh<StraightRoofGenerator>(new Vector3(DimensionsA.x - 0.5f, BuildingHeight, cornerWidth - 0.5f), Quaternion.Euler(0, -90, 0), new Dictionary<string, dynamic> { {"width", DimensionsA.y - 2 * cornerWidth}, {"height", RoofHeight}, {"thickness", thickness}, {"length", DimensionsA.x / 2f}, {"extrusion", 0}, {"addCap", true}, {"closeRoof", true} }); var roofA1 = MeshGenerator.GetMesh<StraightRoofGenerator>(new Vector3(-0.5f, BuildingHeight, DimensionsA.y - cornerWidth - 0.5f), Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"width", DimensionsA.y - 2 * cornerWidth}, {"height", RoofHeight}, {"thickness", thickness}, {"length", DimensionsA.x / 2f}, {"extrusion", 0}, {"addCap", true}, {"closeRoof", true} }); return MeshUtils.Combine(chimney, cornerA, cornerA1, cornerB, cornerB1, roofA, roofA1); } else { var cornerA = MeshGenerator.GetMesh<CornerRoofGenerator>(new Vector3(DimensionsA.x - 0.5f, BuildingHeight, -0.5f), Quaternion.Euler(0, -90, 0), new Dictionary<string, dynamic> { {"width", DimensionsA.y / 2f}, {"height", RoofHeight}, {"length", cornerWidth}, {"thickness", thickness}, {"addCap", true}, {"joinCaps", true} }); var cornerB = MeshGenerator.GetMesh<CornerRoofGenerator>(new Vector3(DimensionsA.x - 0.5f, BuildingHeight, DimensionsA.y - 0.5f), Quaternion.Euler(0, 180, 0), new Dictionary<string, dynamic> { {"width", cornerWidth}, {"height", RoofHeight}, {"length", DimensionsA.y / 2f}, {"thickness", thickness}, {"addCap", true}, {"joinCaps", true} }); var roofA = MeshGenerator.GetMesh<StraightRoofGenerator>(new Vector3(-0.5f, BuildingHeight, -0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"width", DimensionsA.x - cornerWidth}, {"height", RoofHeight}, {"thickness", thickness}, {"length", DimensionsA.y / 2f}, {"extrusion", extrusion}, {"addCap", true}, {"extrusionRight", false}, {"closeRoof", true} }); var roofA1 = MeshGenerator.GetMesh<StraightRoofGenerator>(new Vector3(-0.5f, BuildingHeight, DimensionsA.y - 0.5f), Quaternion.Euler(0, 180, 0), new Dictionary<string, dynamic> { {"width", DimensionsA.x - cornerWidth}, {"height", RoofHeight}, {"thickness", thickness}, {"length", DimensionsA.y / 2f}, {"extrusion", extrusion}, {"extrusionRight", false}, {"addCap", true}, {"flip", true}, {"closeRoof", true} }); return MeshUtils.Combine(chimney, cornerA, cornerB, roofA, roofA1); } } protected MeshData GenWalls(List<Vector2Int> path, int LOD) { var walls = new MeshData(); var current = Vector2Int.zero; foreach (var point in path) { var next = current + point; var from = new Vector3(current.x - 0.5f, 0, current.y - 0.5f); var to = new Vector3(next.x - 0.5f, 0, next.y - 0.5f); var diff = to - from; var angle = Vector3.SignedAngle(Vector3.right, diff, Vector3.up); var wallWidth = diff.magnitude; var wall = MeshGenerator.GetMesh<PlaneGenerator>(to, Quaternion.Euler(0, angle - 180, 0), new Dictionary<string, dynamic> { {"sizeA", wallWidth}, {"sizeB", BuildingHeight}, {"orientation", PlaneGenerator.PlaneOrientation.XY}, }); walls.MergeMeshData(wall); walls.MergeMeshData(AddWallFeatures(from, to, BuildingHeight, wallWidth, angle, LOD)); current = next; } return walls; } protected virtual MeshData AddWallFeatures(Vector3 wallStart, Vector3 wallEnd, float buildingHeight, float wallWidth, float wallAngle, int LOD, bool addPillar = true) { var thickness = GeneratorSettings.GeneralSettings.FeatureThickness; var diagonalAChance = GeneratorSettings.GeneralSettings.DiagonalAChance; var diagonalBChance = GeneratorSettings.GeneralSettings.DiagonalBChance; var windowChance = GeneratorSettings.GeneralSettings.WindowChance; var wallDirection = (wallEnd - wallStart).normalized; var wallPerpendicular = Vector3.Cross(wallDirection, Vector3.up); var wallSize = Mathf.RoundToInt((wallEnd - wallStart).magnitude); var features = new MeshData(); if (addPillar) { var pillar = MeshGenerator.GetMesh<LineGenerator>(wallEnd - Vector3.forward * thickness / 2f, Quaternion.identity, new Dictionary<string, dynamic> { {"end", Vector3.up * buildingHeight}, {"thickness", thickness}, {"extrusion", thickness}, {"submeshIndex", 2}, {"extrusionOutwards", false} }); features.MergeMeshData(pillar); } var splitSectionsVertical = new List<float> {0, 1}; var lastSplitPoint = splitSectionsVertical[1]; while (lastSplitPoint < buildingHeight) { var nextSize = RandUtils.RandomBetween(GeneratorSettings.GeneralSettings.VerticalSplitMinMax); if (lastSplitPoint + nextSize < buildingHeight && lastSplitPoint + nextSize > buildingHeight - 1) nextSize = buildingHeight - lastSplitPoint - 1; lastSplitPoint += nextSize; if (lastSplitPoint >= buildingHeight) lastSplitPoint = buildingHeight; splitSectionsVertical.Add(lastSplitPoint); } var splitSectionsHorizontal = new List<float> {0}; var lastSplitPointH = splitSectionsHorizontal[0]; while (lastSplitPointH < wallSize) { var nextSize = RandUtils.RandomBetween(GeneratorSettings.GeneralSettings.HorizontalSplitMinMax); if (lastSplitPointH + nextSize < wallSize && lastSplitPointH + nextSize > wallSize - 1) nextSize = wallSize - lastSplitPointH - 1; lastSplitPointH += nextSize; if (lastSplitPointH > wallSize) lastSplitPointH = wallSize; splitSectionsHorizontal.Add(lastSplitPointH); } for (var i = 1; i < splitSectionsVertical.Count; i++) { var sectionHeight = splitSectionsVertical[i] - splitSectionsVertical[i - 1]; var addWindow = wallSize > 2 && RandUtils.BoolWeighted(windowChance) && LOD <= 1; var windowWidth = 0.0f; var windowHeight = 0.0f; if (addWindow) { windowHeight = Rand.Range(1f, Mathf.Max(1f, sectionHeight * 0.75f)); } for (var i2 = 1; i2 < splitSectionsHorizontal.Count; i2++) { var sectionWidth = splitSectionsHorizontal[i2] - splitSectionsHorizontal[i2 - 1]; var addWindowHorizontal = addWindow; if (RandUtils.BoolWeighted(windowChance / 2.0f)) addWindowHorizontal = false; if (addWindowHorizontal) { windowWidth = Rand.Range(1f, Mathf.Max(1f, sectionWidth * 0.75f)); } if (LOD <= 1 && i2 != splitSectionsHorizontal.Count - 1) { var verticalLine = MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * splitSectionsHorizontal[i2] + Vector3.up * (thickness / 2f), Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * buildingHeight}, {"thickness", thickness}, {"extrusion", thickness}, {"submeshIndex", 2}, {"extrusionCenter", true} }); features.MergeMeshData(verticalLine); } var horizontalLine = MeshGenerator.GetMesh<LineGenerator>(wallStart + Vector3.up * splitSectionsVertical[i] - wallPerpendicular * thickness / 2f, Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero + Vector3.right * thickness / 2f}, {"end", Vector3.right * (wallWidth - thickness / 2f)}, {"thickness", thickness}, {"extrusion", thickness}, {"submeshIndex", 2}, {"rotateUV", true} }); if (LOD <= 1) features.MergeMeshData(horizontalLine); if (i == 1) continue; if (LOD <= 1 && addWindowHorizontal) { var windowPosition = splitSectionsHorizontal[i2] - 0.5f * (sectionWidth); var window = MeshGenerator.GetMesh<PlaneGenerator>(wallStart + wallDirection * (windowPosition + 0.5f * windowWidth) + Vector3.up * (splitSectionsVertical[i - 1] + thickness / 2f) + wallPerpendicular * thickness / 4f, Quaternion.Euler(0, wallAngle - 180, 0), new Dictionary<string, dynamic> { {"sizeA", windowWidth}, {"sizeB", windowHeight}, {"orientation", PlaneGenerator.PlaneOrientation.XY}, {"submeshIndex", 3}, {"extraUvSettings", MeshGenerator.UVSettings.NoOffset} }); features.MergeMeshData(window); /* BEGIN Frame */ features.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition - 0.5f * windowWidth) + Vector3.up * (splitSectionsVertical[i - 1] + 0.33334f * windowHeight), Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.right * windowWidth}, {"thickness", 0.035f}, {"extrusion", 0.035f}, {"submeshIndex", 2}, {"rotateUV", true} })); features.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition - 0.5f * windowWidth) + Vector3.up * (splitSectionsVertical[i - 1] + windowHeight - 0.33334f * windowHeight), Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.right * windowWidth}, {"thickness", 0.035f}, {"extrusion", 0.035f}, {"submeshIndex", 2}, {"rotateUV", true} })); features.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition + 0.5f * windowWidth - 0.33334f * windowWidth) + Vector3.up * (splitSectionsVertical[i - 1] + thickness / 2f) - wallPerpendicular * 0.005f, Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * (windowHeight - thickness / 2f)}, {"thickness", 0.035f}, {"extrusion", 0.035f}, {"submeshIndex", 2}, {"rotateUV", true} })); features.MergeMeshData(MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition - 0.5f * windowWidth + 0.33334f * windowWidth) + Vector3.up * (splitSectionsVertical[i - 1] + thickness / 2f) - wallPerpendicular * 0.005f, Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * (windowHeight - thickness / 2f)}, {"thickness", 0.035f}, {"extrusion", 0.035f}, {"submeshIndex", 2}, {"rotateUV", true} })); /* END Frame */ if (sectionHeight > 1) { var line = MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition - 0.5f * windowWidth) + Vector3.up * (splitSectionsVertical[i - 1] + windowHeight) - wallPerpendicular * thickness / 2f, Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.right * windowWidth}, {"thickness", thickness}, {"extrusion", thickness}, {"submeshIndex", 2}, {"rotateUV", true} }); features.MergeMeshData(line); } if (RandUtils.BoolWeighted(GeneratorSettings.GeneralSettings.FillWallSegmentChance) && LOD <= 0) { var fillWallSpacing = RandUtils.RandomBetween(GeneratorSettings.GeneralSettings.FillWallSegmentSpacing); var fillWallThickness = thickness - fillWallSpacing; var totalWidth = splitSectionsHorizontal[i2] - splitSectionsHorizontal[i2 - 1] - fillWallSpacing; var totalSteps = (int) (totalWidth / thickness); for (var fillIndex = 0; fillIndex < totalSteps; fillIndex++) { var verticalLine = MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (splitSectionsHorizontal[i2 - 1] + fillIndex * (fillWallThickness + fillWallSpacing) + thickness) + Vector3.up * (splitSectionsVertical[i - 1] + thickness / 2f) - wallPerpendicular * thickness / 4f, Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero - Vector3.zero}, {"end", Vector3.up * (splitSectionsVertical[i] - splitSectionsVertical[i - 1] - thickness + (i == 1 ? 1.5f * thickness : 0))}, {"thickness", fillWallThickness}, {"extrusion", fillWallThickness}, {"submeshIndex", 2}, {"extrusionCenter", true} }); features.MergeMeshData(verticalLine); } } if (sectionWidth > 1) { var lineLeft = MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition + 0.5f * windowWidth + 0.5f * thickness) + Vector3.up * (splitSectionsVertical[i - 1] + thickness / 2f) - wallPerpendicular * thickness / 2f, Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * windowHeight}, {"thickness", thickness}, {"extrusion", thickness}, {"submeshIndex", 2}, {"rotateUV", true} }); features.MergeMeshData(lineLeft); var lineRight = MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * (windowPosition - 0.5f * windowWidth - 0.5f * thickness) + Vector3.up * (splitSectionsVertical[i - 1] + thickness / 2f) - wallPerpendicular * thickness / 2f, Quaternion.Euler(0, wallAngle, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * windowHeight}, {"thickness", thickness}, {"extrusion", thickness}, {"submeshIndex", 2}, {"rotateUV", true} }); features.MergeMeshData(lineRight); } } if (RandUtils.BoolWeighted(diagonalAChance) && LOD <= 0) { var diff = splitSectionsHorizontal[i2] - splitSectionsHorizontal[i2 - 1]; var diagonalLine = MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * splitSectionsHorizontal[i2 - 1] + Vector3.up * (splitSectionsVertical[i - 1] + thickness / 2f) - wallPerpendicular * thickness / 2.5f, Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", wallDirection * diff + Vector3.up * (splitSectionsVertical[i] - splitSectionsVertical[i - 1] - thickness)}, {"thickness", thickness}, {"extrusion", thickness}, {"submeshIndex", 2}, {"extrusionCenter", true} }); features.MergeMeshData(diagonalLine); } if (RandUtils.BoolWeighted(diagonalBChance) && LOD <= 0) { var diff = splitSectionsHorizontal[i2] - splitSectionsHorizontal[i2 - 1]; var diagonalLine = MeshGenerator.GetMesh<LineGenerator>(wallStart + wallDirection * splitSectionsHorizontal[i2 - 1] + Vector3.up * (splitSectionsVertical[i - 1] + thickness / 2f) - wallPerpendicular * thickness / 2.5f, Quaternion.identity, new Dictionary<string, dynamic> { {"start", wallDirection * diff}, {"end", Vector3.up * (splitSectionsVertical[i] - splitSectionsVertical[i - 1] - thickness)}, {"thickness", thickness}, {"extrusion", thickness}, {"submeshIndex", 2}, {"extrusionCenter", true} }); features.MergeMeshData(diagonalLine); } } } return features; } protected void CleanupOutline(Arr2d<bool> boolArr) { var queuedToRemove = new List<Vector2Int>(); for (int x = 1; x < boolArr.Length1 - 1; x++) { for (int y = 1; y < boolArr.Length2 - 1; y++) { var north = boolArr[x, y - 1]; var south = boolArr[x, y + 1]; var east = boolArr[x + 1, y]; var west = boolArr[x - 1, y]; if (!boolArr[x, y]) continue; // Remove if surrounded if (north && south && east && west) { queuedToRemove.Add(new Vector2Int(x, y)); } } } queuedToRemove.ForEach(coord => boolArr[coord] = false); } }<file_sep>/Assets/Procedural Art/Scripts/Misc/UVUtils.cs using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using UnityEngine; public static class UVUtils { [SuppressMessage("ReSharper", "InconsistentNaming")] public static List<Vector2> QuadUVS(Vector3 v0, Vector3 v1, Vector3 v2, Vector3 v3, Vector3 worldPosition, MeshGenerator.UVSettings uvSettings) { var compVec = new List<Vector2>(); var v0_1 = v0 - v0; var v1_1 = v1 - v0; var v2_1 = v2 - v0; var v3_1 = v3 - v0; var triangleNormal = Vector3.Cross(v1_1 - v0_1, v3_1 - v0_1).Abs(); if (triangleNormal.x >= triangleNormal.y && triangleNormal.x >= triangleNormal.z) { v0_1.x = 0; v1_1.x = 0; v2_1.x = 0; v3_1.x = 0; compVec.AddRange(new[] {new Vector2(v0_1.y, v0_1.z), new Vector2(v1_1.y, v1_1.z), new Vector2(v2_1.y, v2_1.z), new Vector2(v3_1.y, v3_1.z)}); } else if (triangleNormal.y >= triangleNormal.x && triangleNormal.y >= triangleNormal.z) { v0_1.y = 0; v1_1.y = 0; v2_1.y = 0; v3_1.y = 0; compVec.AddRange(new[] {new Vector2(v0_1.x, v0_1.z), new Vector2(v1_1.x, v1_1.z), new Vector2(v2_1.x, v2_1.z), new Vector2(v3_1.x, v3_1.z)}); } else if (triangleNormal.z >= triangleNormal.x && triangleNormal.z >= triangleNormal.y) { v0_1.z = 0; v1_1.z = 0; v2_1.z = 0; v3_1.z = 0; compVec.AddRange(new[] {new Vector2(v0_1.x, v0_1.y), new Vector2(v1_1.x, v1_1.y), new Vector2(v2_1.x, v2_1.y), new Vector2(v3_1.x, v3_1.y)}); } if (compVec.Count == 0) Debug.Log($"CompVec ended up empty. Triangle normal: {triangleNormal}"); /* STEP 2: Do calculations to sort vertices properly: * This orientation 1 -- 2 * | | * 0 -- 3 */ var uvs = new List<Vector2>(); if (IsAboveBelow(compVec[0], compVec[1])) { var verticalSize = (v1 - v0).magnitude; var horizontalSize = (v3 - v0).magnitude; if (IsRight(compVec[2], compVec[1])) { uvs.AddRange(new[] {Vector2.zero, Vector2.up * verticalSize, Vector2.up * verticalSize + Vector2.right * horizontalSize, Vector2.right * horizontalSize}); } else { uvs.AddRange(new[] {Vector2.up * verticalSize + Vector2.right * horizontalSize, Vector2.right * horizontalSize, Vector2.zero, Vector2.up * verticalSize}); } } else { var verticalSize = (v3 - v0).magnitude; var horizontalSize = (v1 - v0).magnitude; if (IsAbove(compVec[1], compVec[2])) { uvs.AddRange(new[] {Vector2.right * horizontalSize, Vector2.zero, Vector2.up * verticalSize, Vector2.up * verticalSize + Vector2.right * horizontalSize}); } else { uvs.AddRange(new[] {Vector2.up * verticalSize, Vector2.up * verticalSize + Vector2.right * horizontalSize, Vector2.right * horizontalSize, Vector2.zero}); } } if (uvSettings.HasFlag(MeshGenerator.UVSettings.FlipHorizontal)) { Swap(1, 2, uvs); Swap(0, 3, uvs); } if (uvSettings.HasFlag(MeshGenerator.UVSettings.FlipVertical)) { Swap(0, 1, uvs); Swap(2, 3, uvs); } if (uvSettings.HasFlag(MeshGenerator.UVSettings.Rotate)) { var t0 = uvs[0]; for (int i = 0; i < 3; i++) uvs[i] = uvs[i + 1]; uvs[3] = t0; } var uvOffset = new Vector2(0, worldPosition.y); var diffX = Mathf.Abs(v0.x) + Mathf.Abs(v1.x) + Mathf.Abs(v2.x) + Mathf.Abs(v3.x); var diffZ = Mathf.Abs(v0.z) + Mathf.Abs(v1.z) + Mathf.Abs(v2.z) + Mathf.Abs(v3.z); uvOffset.x = diffX > diffZ ? worldPosition.x : worldPosition.z; uvs[0] += uvOffset; uvs[1] += uvOffset; uvs[2] += uvOffset; uvs[3] += uvOffset; return uvs; } public static List<Vector2> QuadUVS2(Vector3 v0, Vector3 v1, Vector3 v2, Vector3 v3, Vector3 worldPosition, MeshGenerator.UVSettings uvSettings) { var sizeHorizontal = (v3 - v0).magnitude; var sizeVertical = (v1 - v0).magnitude; if (uvSettings.HasFlag(MeshGenerator.UVSettings.Rotate)) { var tmp = sizeHorizontal; sizeHorizontal = sizeVertical; sizeVertical = tmp; } var uvs = new List<Vector2>(); uvs.AddRange(new[] {Vector2.zero, Vector2.up * sizeVertical, Vector2.up * sizeVertical + Vector2.right * sizeHorizontal, Vector2.right * sizeHorizontal}); if (uvSettings.HasFlag(MeshGenerator.UVSettings.FlipHorizontal)) { Swap(1, 2, uvs); Swap(0, 3, uvs); } if (uvSettings.HasFlag(MeshGenerator.UVSettings.FlipVertical)) { Swap(0, 1, uvs); Swap(2, 3, uvs); } if (uvSettings.HasFlag(MeshGenerator.UVSettings.Rotate)) { var t0 = uvs[0]; for (int i = 0; i < 3; i++) uvs[i] = uvs[i + 1]; uvs[3] = t0; } if (!uvSettings.HasFlag(MeshGenerator.UVSettings.NoOffset)) { var uvOffset = new Vector2(0, worldPosition.y); var diffX = Mathf.Max(Mathf.Abs(v1.x - v0.x), Mathf.Abs(v2.x - v0.x), Mathf.Abs(v3.x - v0.x)); var diffZ = Mathf.Max(Mathf.Abs(v1.z - v0.z), Mathf.Abs(v2.z - v0.z), Mathf.Abs(v3.z - v0.z)); uvOffset.x = diffX > diffZ ? (v3.x - v0.x < 0 ? -1 : 1) * worldPosition.x : (v3.z - v0.z < 0 ? -1 : 1) * worldPosition.z; uvs[0] += uvOffset; uvs[1] += uvOffset; uvs[2] += uvOffset; uvs[3] += uvOffset; } return uvs; } public static List<Vector2> TriangleUVS(Vector3 v0, Vector3 v1, Vector3 v2, MeshGenerator.UVSettings uvSettings, bool flip) { var compVec = new List<Vector2>(); var v0_1 = v0 - v0; var v1_1 = v1 - v0; var v2_1 = v2 - v0; var triangleNormal = Vector3.Cross(v1_1 - v0_1, v2_1 - v0_1).Abs(); if (triangleNormal.x >= triangleNormal.y && triangleNormal.x >= triangleNormal.z) { v0_1.x = 0; v1_1.x = 0; v2_1.x = 0; compVec.AddRange(new[] {new Vector2(v0_1.y, v0_1.z), new Vector2(v1_1.y, v1_1.z), new Vector2(v2_1.y, v2_1.z)}); } else if (triangleNormal.y >= triangleNormal.x && triangleNormal.y >= triangleNormal.z) { v0_1.y = 0; v1_1.y = 0; v2_1.y = 0; compVec.AddRange(new[] {new Vector2(v0_1.x, v0_1.z), new Vector2(v1_1.x, v1_1.z), new Vector2(v2_1.x, v2_1.z)}); } else if (triangleNormal.z >= triangleNormal.x && triangleNormal.z >= triangleNormal.y) { v0_1.z = 0; v1_1.z = 0; v2_1.z = 0; compVec.AddRange(new[] {new Vector2(v0_1.x, v0_1.y), new Vector2(v1_1.x, v1_1.y), new Vector2(v2_1.x, v2_1.y)}); } var v20 = (v2 - v0).sqrMagnitude; var v10 = (v1 - v0).sqrMagnitude; var v21 = (v2 - v1).sqrMagnitude; var sortedVertices = new List<Vector3>(); if (Math.Abs(v21 - (v10 + v20)) < 0.01f) { sortedVertices.AddRange(new[] {v0, v1, v2}); } else if (Math.Abs(v10 - (v21 + v20)) < 0.01f) { sortedVertices.AddRange(new[] {v0, v1, v2}); // sortedVertices.AddRange(new[] {v2, v0, v1}); } else { sortedVertices.AddRange(new[] {v0, v1, v2}); // sortedVertices.AddRange(new[] {v1, v2, v0}); } if (flip) { sortedVertices.Reverse(); } var uvs = new List<Vector2>(); float horizontalSize; float verticalSize; if (IsAboveBelow(sortedVertices[0], sortedVertices[1])) { verticalSize = (v1 - v0).magnitude; horizontalSize = (v2 - v0).magnitude; if (IsRight(sortedVertices[2], sortedVertices[0])) { uvs.AddRange(new[] {Vector2.zero, Vector2.up * verticalSize, Vector2.right * horizontalSize}); } else { uvs.AddRange(new[] {Vector2.up * verticalSize + Vector2.right * horizontalSize, Vector2.right * horizontalSize, Vector2.up * verticalSize}); if (flip) uvs[1] = Vector2.zero; } } else { verticalSize = (v2 - v0).magnitude; horizontalSize = (v1 - v0).magnitude; if (IsAbove(sortedVertices[2], sortedVertices[0])) { uvs.AddRange(new[] {Vector2.right * horizontalSize, Vector2.zero, Vector2.up * verticalSize}); } else { uvs.AddRange(new[] {Vector2.up * verticalSize, Vector2.up * verticalSize + Vector2.right * horizontalSize, Vector2.zero}); } } if (uvSettings.HasFlag(MeshGenerator.UVSettings.Rotate)) RotateTriangle(uvs, verticalSize, horizontalSize); if (uvSettings.HasFlag(MeshGenerator.UVSettings.FlipHorizontal)) FlipTriangleHorizontal(uvs, horizontalSize); if (uvSettings.HasFlag(MeshGenerator.UVSettings.FlipVertical)) FlipTriangleVertical(uvs, verticalSize); if (uvSettings.HasFlag(MeshGenerator.UVSettings.TriangleMiddle)) TriangleMiddle(uvs); return uvs; } public static List<Vector2> TriangleUVS2(Vector3 v0, Vector3 v1, Vector3 v2, MeshGenerator.UVSettings uvSettings, Vector3 position) { var sizeHorizontal = (v2 - v0).magnitude; var sizeVertical = (v1 - v0).magnitude; var uvs = new List<Vector2>(); uvs.AddRange(new[] {Vector2.zero, Vector2.up * sizeVertical, Vector2.right * sizeHorizontal}); if (uvSettings.HasFlag(MeshGenerator.UVSettings.FlipHorizontal)) FlipTriangleHorizontal(uvs, sizeHorizontal); if (uvSettings.HasFlag(MeshGenerator.UVSettings.FlipVertical)) FlipTriangleVertical(uvs, sizeVertical); if (uvSettings.HasFlag(MeshGenerator.UVSettings.FlipTopPart)) { uvs[1] += Vector2.right * sizeHorizontal; } if (uvSettings.HasFlag(MeshGenerator.UVSettings.FlipBottomPart)) { uvs[0] += Vector2.right * sizeHorizontal; uvs[2] -= Vector2.right * sizeHorizontal; } return uvs; } private static bool IsAboveBelow(Vector2 a, Vector2 b) { return Mathf.Abs(a.x - b.x) < Mathf.Abs(a.y - b.y); } private static bool IsRightLeft(Vector2 a, Vector2 b) { return !IsAboveBelow(a, b); } private static bool IsAbove(Vector2 a, Vector2 b) { return IsAboveBelow(a, b) && a.y > b.y; } private static bool IsRight(Vector2 a, Vector2 b) { return IsRightLeft(a, b) && a.x > b.x; } private static void Swap<T>(int a, int b, List<T> list) { var tA = list[a]; list[a] = list[b]; list[b] = tA; } private static void FlipTriangleHorizontal(List<Vector2> uvs, float horizontalSize) { for (int i = 0; i < 3; i++) { var uv = uvs[i]; if (Math.Abs(uv.x - 0) < 0.01f) uv.x = horizontalSize; else uv.x = 0; uvs[i] = uv; } } private static void FlipTriangleVertical(List<Vector2> uvs, float verticalSize) { for (int i = 0; i < 3; i++) { var uv = uvs[i]; if (Math.Abs(uv.y - 0) < 0.01f) uv.y = verticalSize; else uv.y = 0; uvs[i] = uv; } } private static void RotateTriangle(List<Vector2> uvs, float verticalSize, float horizontalSize) { var offsets = new List<Vector2>(); if (uvs[0] == Vector2.zero) offsets.AddRange(new[] {Vector2.up * verticalSize, Vector2.right * horizontalSize, Vector2.left * horizontalSize}); else if (uvs[0] == Vector2.up * verticalSize) offsets.AddRange(new[] {Vector2.right * horizontalSize, Vector2.down * verticalSize, Vector2.up * verticalSize}); else if (uvs[0] == Vector2.right * horizontalSize) offsets.AddRange(new[] {Vector2.left * horizontalSize, Vector2.up * verticalSize, Vector2.down * verticalSize}); else offsets.AddRange(new[] {Vector2.down * verticalSize, Vector2.left * horizontalSize, Vector2.right * horizontalSize}); uvs[0] += offsets[0]; uvs[1] += offsets[1]; uvs[2] += offsets[2]; } private static void TriangleMiddle(List<Vector2> uvs) { if (IsAboveBelow(uvs[0], uvs[1])) uvs[1] = new Vector2((uvs[0].x + uvs[2].x) / 2f, uvs[1].y); else uvs[1] = new Vector2(uvs[1].x, (uvs[0].y + uvs[2].y) / 2f); } }<file_sep>/Assets/Procedural Art/Scripts/Misc/MathUtils.cs using System; using System.Runtime.CompilerServices; using UnityEngine; using UnityEngine.Rendering; using V2i = UnityEngine.Vector2Int; using V3i = UnityEngine.Vector3Int; using V3 = UnityEngine.Vector3; using V2 = UnityEngine.Vector2; public static class MathUtils { public static float EaseIn(float t) => t * t; public static float EaseOut(float t) => 1 - EaseIn(1 - t); public static float EaseInOut(float t) => Mathf.Lerp(EaseIn(t), EaseOut(t), t); public static float InverseLerp(Vector3 a, Vector3 b, Vector3 value) { var ab = b - a; var av = value - a; return Mathf.Clamp01(Vector3.Dot(av, ab) / Vector3.Dot(ab, ab)); } public static float Map(this float value, float a1, float a2, float b1, float b2) => b1 + (value - a1) * (b2 - b1) / (a2 - a1); public static V2 Map(this V2 value, float a1, float a2, float b1, float b2) => new V2(Map(value.x, a1, a2, b1, b2), Map(value.y, a1, a2, b1, b2)); public static int Clamp(int value, int min, int max) => value < min ? min : value > max ? max : value; public static V2 Scaled(this V2 vector, V2 scale) { return new V2(vector.x * scale.x, vector.y * scale.y); } public static V2 WithMagnitude(this V2 vector, float magnitude) { return vector.normalized * magnitude; } public static V2i ToV2I(this V2 value, bool round = false, bool floor = false) => new V2i(round ? Mathf.RoundToInt(value.x) : floor ? Mathf.FloorToInt(value.x) : Mathf.CeilToInt(value.x), round ? Mathf.RoundToInt(value.y) : floor ? Mathf.FloorToInt(value.y) : Mathf.CeilToInt(value.y)); public static V2i Clamp(this V2i value, V2i min, V2i max) { return new V2i(Clamp(value.x, min.x, max.x), Clamp(value.y, min.y, max.y)); } public static V3i Clamp(this V3i value, V3i min, V3i max) { return new V3i(Clamp(value.x, min.x, max.x), Clamp(value.y, min.y, max.y), Clamp(value.z, min.z, max.z)); } public static V3 Abs(this V3 value) { return new V3(Mathf.Abs(value.x), Mathf.Abs(value.y), Mathf.Abs(value.z)); } public static float ClosestGridPoint(this float f, bool useSubGrid) { var size = useSubGrid ? GlobalSettings.Instance.GridSizeMinor : GlobalSettings.Instance.GridSize; var min = Mathf.Floor(f / size) * size; var max = Mathf.Ceil(f / size) * size; return Mathf.Abs(f - min) < Mathf.Abs(f - max) ? min : max; } public static V3 ClosestGridPoint(this V3 vector, bool useSubGrid) { var size = useSubGrid ? GlobalSettings.Instance.GridSizeMinor : GlobalSettings.Instance.GridSize; var minX = Mathf.Floor(vector.x / size) * size; var maxX = Mathf.Ceil(vector.x / size) * size; var minZ = Mathf.Floor(vector.z / size) * size; var maxZ = Mathf.Ceil(vector.z / size) * size; vector.x = Mathf.Abs(vector.x - minX) < Mathf.Abs(vector.x - maxX) ? minX : maxX; vector.z = Mathf.Abs(vector.z - minZ) < Mathf.Abs(vector.z - maxZ) ? minZ : maxZ; return vector; } public static V2 ClosestGridPoint(this V2 vector, bool useSubGrid) { var v3 = new V3(vector.x, 0, vector.y); var closest = v3.ClosestGridPoint(useSubGrid); var v2 = new V2(closest.x, closest.z); return v2; } public static V3 ToVec3(this V2 vector, float extraValue = 0) { return new V3(vector.x, extraValue, vector.y); } public static V2 ToVec2(this V3 vector) { return new V2(vector.x, vector.z); } public static bool OnlyTheseFlags(this Enum bitset, Enum bitmask) { var bitsetInt = Convert.ToInt32(bitset); var bitmaskInt = Convert.ToInt32(bitmask); var hasBits = (bitsetInt & bitmaskInt) != 0; var noOtherBits = (bitsetInt & ~bitmaskInt) == 0; return hasBits && noOtherBits; } public static (Vector3 leftDown, Vector3 rightDown, Vector3 rightUp, Vector3 leftUp) RotatedRectangle(Plot plot) { var rotation = Quaternion.Euler(0, plot.Rotation, 0); var leftDown = new Vector3(plot.Bounds.min.x, 0, plot.Bounds.min.y); var rightDown = new Vector3(plot.Bounds.min.x + plot.Bounds.width, 0, plot.Bounds.min.y); var rightUp = new Vector3(plot.Bounds.min.x + plot.Bounds.width, 0, plot.Bounds.min.y + plot.Bounds.height); var leftUp = new Vector3(plot.Bounds.min.x, 0, plot.Bounds.min.y + plot.Bounds.height); leftDown = leftDown - plot.Bounds.min.ToVec3() - plot.Bounds.size.ToVec3() / 2f; rightDown = rightDown - plot.Bounds.min.ToVec3() - plot.Bounds.size.ToVec3() / 2f; rightUp = rightUp - plot.Bounds.min.ToVec3() - plot.Bounds.size.ToVec3() / 2f; leftUp = leftUp - plot.Bounds.min.ToVec3() - plot.Bounds.size.ToVec3() / 2f; leftDown = rotation * leftDown; rightDown = rotation * rightDown; rightUp = rotation * rightUp; leftUp = rotation * leftUp; leftDown = leftDown + plot.Bounds.min.ToVec3() + plot.Bounds.size.ToVec3() / 2f; rightDown = rightDown + plot.Bounds.min.ToVec3() + plot.Bounds.size.ToVec3() / 2f; rightUp = rightUp + plot.Bounds.min.ToVec3() + plot.Bounds.size.ToVec3() / 2f; leftUp = leftUp + plot.Bounds.min.ToVec3() + plot.Bounds.size.ToVec3() / 2f; return (leftDown, rightDown, rightUp, leftUp); } public static (Vector3 leftDown, Vector3 rightDown, Vector3 rightUp, Vector3 leftUp) RotatedRectangle(PlotData plot) { var rotation = Quaternion.Euler(0, plot.Rotation, 0); var leftDown = new Vector3(plot.Bounds.min.x, 0, plot.Bounds.min.y); var rightDown = new Vector3(plot.Bounds.min.x + plot.Bounds.width, 0, plot.Bounds.min.y); var rightUp = new Vector3(plot.Bounds.min.x + plot.Bounds.width, 0, plot.Bounds.min.y + plot.Bounds.height); var leftUp = new Vector3(plot.Bounds.min.x, 0, plot.Bounds.min.y + plot.Bounds.height); leftDown = leftDown - plot.Bounds.min.ToVec3() - plot.Bounds.size.ToVec3() / 2f; rightDown = rightDown - plot.Bounds.min.ToVec3() - plot.Bounds.size.ToVec3() / 2f; rightUp = rightUp - plot.Bounds.min.ToVec3() - plot.Bounds.size.ToVec3() / 2f; leftUp = leftUp - plot.Bounds.min.ToVec3() - plot.Bounds.size.ToVec3() / 2f; leftDown = rotation * leftDown; rightDown = rotation * rightDown; rightUp = rotation * rightUp; leftUp = rotation * leftUp; leftDown = leftDown + plot.Bounds.min.ToVec3() + plot.Bounds.size.ToVec3() / 2f; rightDown = rightDown + plot.Bounds.min.ToVec3() + plot.Bounds.size.ToVec3() / 2f; rightUp = rightUp + plot.Bounds.min.ToVec3() + plot.Bounds.size.ToVec3() / 2f; leftUp = leftUp + plot.Bounds.min.ToVec3() + plot.Bounds.size.ToVec3() / 2f; return (leftDown, rightDown, rightUp, leftUp); } public static bool RectangleOverlap(Rect a, Plot b) { var pointsB = RotatedRectangle(b); return a.Contains(pointsB.leftDown) || a.Contains(pointsB.leftUp) || a.Contains(pointsB.rightDown) || a.Contains(pointsB.rightUp); } public static bool RectangleContains(Rect a, Plot b) { var pointsB = RotatedRectangle(b); return a.Contains(pointsB.leftDown.ToVec2()) && a.Contains(pointsB.leftUp.ToVec2()) && a.Contains(pointsB.rightDown.ToVec2()) && a.Contains(pointsB.rightUp.ToVec2()); } public static bool PointInRotatedRectangle(Vector2 point, Plot plot, float? rotationAngle = null) { var rot = -plot.Rotation; if (rotationAngle != null) rot = -rotationAngle.Value; var rotation = Quaternion.Euler(0, rot, 0); var localPoint = (point - plot.Bounds.center).ToVec3(); var rotatedPoint = (rotation * localPoint).ToVec2() + plot.Bounds.center; return plot.Bounds.Contains(rotatedPoint); } }<file_sep>/Assets/Procedural Art/Scripts/Misc/MarchingSquares/Path.cs using System.Collections.Generic; using UnityEngine; public static class Path { public static List<Vector2Int> SimplifyPath(List<Vector2Int> directions) { var simplified = new List<Vector2Int> {directions[0]}; var counts = new List<int> {1}; for (var i = 1; i < directions.Count; i++) { if (directions[i] != simplified[simplified.Count - 1]) { simplified.Add(directions[i]); counts.Add(1); } else counts[simplified.Count - 1]++; } for (var i = 0; i < simplified.Count; i++) { simplified[i] *= counts[i]; } return simplified; } }<file_sep>/Assets/Procedural Art/Scripts/Misc/Rand.cs using System; using System.Collections.Generic; using System.Linq; using UnityEngine; /// <summary> /// Took this from the source code of an amazing game called RimWorld. /// I am not proud of this but for the scope of this project I didn't have time to implement something like this. /// The Unity Random is really bad. /// </summary> public static class Rand { private static Stack<ulong> stateStack = new Stack<ulong>(); private static RandomNumberGenerator random = new RandomNumberGenerator(); private static uint iterations = 0; private static List<int> tmpRange = new List<int>(); static Rand() { random.seed = (uint) DateTime.Now.GetHashCode(); } public static int Seed { set { if (stateStack.Count == 0) Debug.LogError("Modifying the initial rand seed. Call PushState() first. The initial rand seed should always be based on the startup time and set only once."); random.seed = (uint) value; iterations = 0U; } } public static float Value => random.GetFloat(iterations++); public static bool Bool => Value < 0.5; public static int Sign => Bool ? 1 : -1; public static int Int => random.GetInt(iterations++); public static Vector3 UnitVector3 => new Vector3(Gaussian(), Gaussian(), Gaussian()).normalized; public static Vector2 UnitVector2 => new Vector2(Gaussian(), Gaussian()).normalized; public static Vector2 InsideUnitCircle { get { Vector2 vector2; do { vector2 = new Vector2(Value - 0.5f, Value - 0.5f) * 2f; } while (vector2.sqrMagnitude > 1.0); return vector2; } } public static Vector3 InsideUnitCircleVec3 { get { Vector2 insideUnitCircle = InsideUnitCircle; return new Vector3(insideUnitCircle.x, 0.0f, insideUnitCircle.y); } } private static ulong StateCompressed { get => random.seed | (ulong) iterations << 32; set { random.seed = (uint) (value & uint.MaxValue); iterations = (uint) (value >> 32 & uint.MaxValue); } } public static void EnsureStateStackEmpty() { if (stateStack.Count <= 0) return; Debug.LogWarning("Random state stack is not empty. There were more calls to PushState than PopState. Fixing."); while (stateStack.Any()) PopState(); } public static float Gaussian(float centerX = 0.0f, float widthFactor = 1f) { return Mathf.Sqrt(-2f * Mathf.Log(Value)) * Mathf.Sin(6.283185f * Value) * widthFactor + centerX; } public static float GaussianAsymmetric(float centerX = 0.0f, float lowerWidthFactor = 1f, float upperWidthFactor = 1f) { float num = Mathf.Sqrt(-2f * Mathf.Log(Value)) * Mathf.Sin(6.283185f * Value); if (num <= 0.0) return num * lowerWidthFactor + centerX; return num * upperWidthFactor + centerX; } public static int Range(int min, int max) { if (max <= min) return min; return min + Mathf.Abs(Int % (max - min)); } public static int Range(int max) { return Range(0, max); } public static int RangeInclusive(int min, int max) { if (max <= min) return min; return Range(min, max + 1); } public static float Range(float min, float max) { if (max <= (double) min) return min; return Value * (max - min) + min; } public static float Range(float max) { return Range(0f, max); } public static bool Chance(float chance) { if (chance <= 0.0) return false; if (chance >= 1.0) return true; return Value < (double) chance; } public static bool ChanceSeeded(float chance, int specialSeed) { PushState(specialSeed); bool flag = Chance(chance); PopState(); return flag; } public static float ValueSeeded(int specialSeed) { PushState(specialSeed); float num = Value; PopState(); return num; } public static float RangeSeeded(float min, float max, int specialSeed) { PushState(specialSeed); float num = Range(min, max); PopState(); return num; } public static int RangeSeeded(int min, int max, int specialSeed) { PushState(specialSeed); int num = Range(min, max); PopState(); return num; } public static int RangeInclusiveSeeded(int min, int max, int specialSeed) { PushState(specialSeed); int num = RangeInclusive(min, max); PopState(); return num; } public static T Element<T>(T a, T b) { if (Bool) return a; return b; } public static T Element<T>(T a, T b, T c) { float num = Value; if (num < 0.333330005407333) return a; if (num < 0.666660010814667) return b; return c; } public static T Element<T>(T a, T b, T c, T d) { float num = Value; if (num < 0.25) return a; if (num < 0.5) return b; if (num < 0.75) return c; return d; } public static T Element<T>(T a, T b, T c, T d, T e) { float num = Value; if (num < 0.200000002980232) return a; if (num < 0.400000005960464) return b; if (num < 0.600000023841858) return c; if (num < 0.800000011920929) return d; return e; } public static T Element<T>(T a, T b, T c, T d, T e, T f) { float num = Value; if (num < 0.166659995913506) return a; if (num < 0.333330005407333) return b; if (num < 0.5) return c; if (num < 0.666660010814667) return d; if (num < 0.833329975605011) return e; return f; } public static void PushState() { stateStack.Push(StateCompressed); } public static void PushState(int replacementSeed) { PushState(); Seed = replacementSeed; } public static void PopState() { StateCompressed = stateStack.Pop(); } }<file_sep>/Assets/Procedural Art/Scripts/Settings/GeneralSettings.cs using UnityEngine; [CreateAssetMenu(fileName = "General Settings", menuName = "General Settings", order = 0)] public class GeneralSettings : ScriptableObject { public long Seed = 0; public bool AutoSeed = true; }<file_sep>/Assets/Procedural Art/Scripts/Mesh Generation/ArchGenerator.cs using System.Collections.Generic; using UnityEngine; public class ArchGenerator : MeshGenerator { private float width; private float height; private float length; private int points; protected override void SetDefaultSettings() { defaultParameters = new Dictionary<string, dynamic> { {"width", 1}, {"height", 1}, {"length", 1}, {"points", 90} }; } protected override void DeconstructSettings(Dictionary<string, dynamic> parameters) { width = (parameters.ContainsKey("width") ? parameters["width"] : defaultParameters["width"]) * GlobalSettings.Instance.GridSize; height = (parameters.ContainsKey("height") ? parameters["height"] : defaultParameters["height"]) * GlobalSettings.Instance.GridSize; length = (parameters.ContainsKey("length") ? parameters["length"] : defaultParameters["length"]) * GlobalSettings.Instance.GridSize; points = parameters.ContainsKey("points") ? parameters["points"] : defaultParameters["points"]; } protected override void Generate() { var b0 = new Vector3(0, 0, 0); var b1 = new Vector3(width, 0, 0); var b2 = new Vector3(width, 0, length); var b3 = new Vector3(0, 0, length); var c0 = new Vector3(0, height, 0); var c1 = new Vector3(width, height, 0); var c2 = new Vector3(width, height, length); var c3 = new Vector3(0, height, length); var step = 180f / (points - 1) * Mathf.Deg2Rad; for (var val = 0f; val <= Mathf.PI - (step / 4f); val += step) { var x = ((Mathf.Cos(val) + 1) / 2f) * width; var y = Mathf.Sin(val) * height; var x2 = ((Mathf.Cos(val + step) + 1) / 2f) * width; var y2 = Mathf.Sin(val + step) * height; var p0 = new Vector3(x, y, 0); var p1 = new Vector3(x2, y2, 0); var p2 = new Vector3(x2, y2, length); var p3 = new Vector3(x, y, length); AddQuad(p3, p2, p1, p0, 0); if (points % 2 == 0 && Mathf.Abs(y - y2) < 0.00001f) { var t0 = new Vector3(x, height, 0); var t1 = new Vector3(x2, height, 0); var t2 = new Vector3(x2, height, length); var t3 = new Vector3(x, height, length); AddQuad(p1, t1, t0, p0, 0); AddQuad(p3, t3, t2, p2, 0); AddTriangle(p1, c0, t1, 0); AddTriangle(p0, t0, c1, 0); AddTriangle(p3, c2, t3, 0); AddTriangle(p2, t2, c3, 0); } else { if ((x2 + x) / 2f >= width / 2f) { AddTriangle(p0, p1, c1, 0); AddTriangle(c2, p2, p3, 0); } else { AddTriangle(p0, p1, c0, 0); AddTriangle(p3, c3,p2, 0); } } } AddQuad(c0, c3, c2, c1, 0); AddQuad(b0, b3, c3, c0, 0); AddQuad(b1, c1, c2, b2, 0); } }<file_sep>/Assets/Procedural Art/Scripts/Settings/GlobalSettings.cs using System; using UnityEngine; [ExecuteInEditMode] public class GlobalSettings : MonoBehaviour { private static GlobalSettings instance; public static GlobalSettings Instance { get { if (instance != null) return instance; var resources = Resources.FindObjectsOfTypeAll<GlobalSettings>(); Debug.Assert(resources.Length == 1); resources[0].OnEnable(); return instance; } } public float GridSize = 1f; public int GridSubdivisionsMinor = 4; public float GridSizeMinor => GridSize / GridSubdivisionsMinor; private void OnEnable() { instance = this; } }<file_sep>/Assets/Procedural Art/Scripts/Plots/PlotCreator.cs using System.Collections.Generic; using UnityEngine; public class PlotCreator : MonoBehaviour { public float NormalAlpha = 0.5f; public float SelectedAlpha = 0.75f; public float DisabledAlpha = 0.1f; public Color NormalColor { get { var col = SelectedPlotGrid.Color; col.a = NormalAlpha; return col; } } public Color SelectedColor { get { var col = NormalColor; col.a = SelectedAlpha; return col; } } public Color DisabledColor(int gridIndex) { var col = PlotGrids[gridIndex].Color; col.a = DisabledAlpha; return col; } public Color UnselectColor = Color.red; public Color DisabledColorAbs = Color.gray; public bool ShowPlots; [HideInInspector] public bool IsEnabled; [HideInInspector] public int SelectedPlotGridIndex = -1; [HideInInspector] public List<PlotGrid> PlotGrids = new List<PlotGrid>(); public PlotGrid SelectedPlotGrid => SelectedPlotGridIndex == -1 ? null : PlotGrids[SelectedPlotGridIndex]; }<file_sep>/Assets/Procedural Art/Scripts/Plots/Plot.cs using System; using UnityEngine; [Serializable] public class Plot { public Rect Bounds; public float Rotation; private Plot() {} public static Plot FromStartEnd(Vector2 start, Vector2 end, float rotation = 0) { var plot = new Plot {Bounds = new Rect()}; plot.Bounds.min = start; plot.Bounds.max = end; plot.Rotation = rotation; return plot; } }<file_sep>/Assets/Procedural Art/Scripts/Generators/MarketGenerator.cs using System; using System.Collections.Generic; using UnityEngine; public class MarketGenerator : BuildingGenerator { [HideInInspector] public MarketSettings MarketSettings; public List<GameObject> FountainPrefabs; public List<GameObject> StallPrefabs; public List<GameObject> DetailPrefabs; public List<GameObject> TreePrefabs; public static new bool DoneOnceField; public override MeshData Generate(PlotData plot, BuildingTypeSettings settings, float heightAdjustment, Vector3 offset, int LOD) { DoOnce(ref DoneOnceField); // Don't do LOD if (LOD >= 1) return new MeshData(); var container = new GameObject(); var (leftDown, rightDown, rightUp, leftUp) = MathUtils.RotatedRectangle(plot); var center = (leftDown + rightDown + rightUp + leftUp) / 4; SetLocalPosition(container, transform, -new Vector3(plot.Bounds.width / 2.0f, transform.localPosition.y, plot.Bounds.height / 2.0f)); container.transform.localRotation = Quaternion.identity; var fountainPrefab = RandUtils.ListItem(FountainPrefabs); var fountain = Instantiate(fountainPrefab, Vector3.zero, Quaternion.identity); var fountainPosition = PlaceObject(plot.Bounds, new Vector3(plot.Bounds.width / 2.0f, 0, plot.Bounds.height / 2.0f)); SetLocalPosition(fountain, container.transform, fountainPosition); var stalls = RandUtils.RandomBetween(MarketSettings.MinMaxStalls); var details = RandUtils.RandomBetween(MarketSettings.MinMaxDetails); var treeClumps = RandUtils.RandomBetween(MarketSettings.MinMaxTreeClumps); for (var i = 0; i < stalls; i++) { var stall = Instantiate(RandUtils.ListItem(StallPrefabs), Vector3.zero, Quaternion.Euler(0, Rand.Range(360f), 0)); var stallPosition = PlaceObject(plot.Bounds, GetPositionAwayFromBorder(plot.Bounds, MarketSettings.BorderDistance).ToVec3()); SetLocalPosition(stall, container.transform, stallPosition); } for (var i = 0; i < details; i++) { var detail = Instantiate(RandUtils.ListItem(DetailPrefabs), Vector3.zero, Quaternion.Euler(0, Rand.Range(360f), 0)); var detailPosition = PlaceObject(plot.Bounds, GetPositionAwayFromBorder(plot.Bounds, MarketSettings.BorderDistance).ToVec3()); SetLocalPosition(detail, container.transform, detailPosition); } for (var i = 0; i < treeClumps; i++) { var treeCount = RandUtils.RandomBetween(MarketSettings.MinMaxTreesPerClump); var clumpPosition = GetPositionNearBorder(plot.Bounds, MarketSettings.BorderDistance); for (var j = 0; j < treeCount; j++) { var tree = Instantiate(RandUtils.ListItem(TreePrefabs), Vector3.zero, Quaternion.Euler(0, Rand.Range(360f), 0)); var treePosition = PlaceObject(plot.Bounds, GetOffset(clumpPosition, MarketSettings.MaxTreeDistance, MarketSettings.MinTreeDistance).ToVec3()); SetLocalPosition(tree, container.transform, treePosition); } } return new MeshData(); } public override void DoOnce(ref bool doneOnceField) { if (doneOnceField) return; doneOnceField = true; } public override void Setup(BuildingTypeSettings settings) { MarketSettings = settings.GeneratorSettings as MarketSettings; } private Vector3 PlaceObject(Rect plotBounds, Vector3 position) { if (Physics.Raycast(position + plotBounds.position.ToVec3() + Vector3.up * 200, Vector3.down, out var hitInfo, LayerMask.GetMask("Terrain"))) { position.y = hitInfo.point.y; return position; } return position; } private Vector2 GetPosition(Rect plotBounds) { var randomizer = new WeightedRandom(0.25f, 0.25f, 0.25f, 0.25f); randomizer.NormalizeWeights(); randomizer.CalculateAdditiveWeights(); var choice = randomizer.Value(); var left = new Vector2(Rand.Range(0f, plotBounds.width / 2.0f - MarketSettings.MinDistanceFromCenter), Rand.Range(0f, plotBounds.height)); var right = new Vector2(Rand.Range(plotBounds.width / 2.0f + MarketSettings.MinDistanceFromCenter, plotBounds.width), Rand.Range(0f, plotBounds.height)); var top = new Vector2(Rand.Range(0, plotBounds.width), Rand.Range(plotBounds.height / 2.0f + MarketSettings.MinDistanceFromCenter, plotBounds.height)); var bottom = new Vector2(Rand.Range(0, plotBounds.width), Rand.Range(0f, plotBounds.height / 2.0f - MarketSettings.MinDistanceFromCenter)); switch (choice) { case 0: return left; case 1: return right; case 2: return top; default: return bottom; } } private Vector2 GetPositionAwayFromBorder(Rect plotBounds, float borderDistance) { var randomizer = new WeightedRandom(0.25f, 0.25f, 0.25f, 0.25f); randomizer.NormalizeWeights(); randomizer.CalculateAdditiveWeights(); var choice = randomizer.Value(); var left = new Vector2(Rand.Range(borderDistance, plotBounds.width / 2.0f - MarketSettings.MinDistanceFromCenter), Rand.Range(borderDistance, plotBounds.height - borderDistance)); var right = new Vector2(Rand.Range(plotBounds.width / 2.0f + MarketSettings.MinDistanceFromCenter, plotBounds.width - borderDistance), Rand.Range(borderDistance, plotBounds.height - borderDistance)); var top = new Vector2(Rand.Range(borderDistance, plotBounds.width - borderDistance), Rand.Range(plotBounds.height / 2.0f + MarketSettings.MinDistanceFromCenter, plotBounds.height - borderDistance)); var bottom = new Vector2(Rand.Range(borderDistance, plotBounds.width - borderDistance), Rand.Range(borderDistance, plotBounds.height / 2.0f - MarketSettings.MinDistanceFromCenter)); switch (choice) { case 0: return left; case 1: return right; case 2: return top; default: return bottom; } } private Vector2 GetPositionNearBorder(Rect plotBounds, float borderDistance) { var randomizer = new WeightedRandom(0.25f, 0.25f, 0.25f, 0.25f); randomizer.NormalizeWeights(); randomizer.CalculateAdditiveWeights(); var choice = randomizer.Value(); var left = new Vector2(Rand.Range(0f, borderDistance), Rand.Range(0f, plotBounds.height)); var right = new Vector2(Rand.Range(plotBounds.width - borderDistance, plotBounds.width), Rand.Range(0f, plotBounds.height)); var top = new Vector2(Rand.Range(0, plotBounds.width), Rand.Range(plotBounds.height - borderDistance, plotBounds.height)); var bottom = new Vector2(Rand.Range(0, plotBounds.width), Rand.Range(0f, borderDistance)); switch (choice) { case 0: return left; case 1: return right; case 2: return top; default: return bottom; } } private Vector2 GetOffset(Vector2 point, float maxDistance, float minDistance) { var unit = Rand.UnitVector2; var minDist = unit.Map(0f, 1f, minDistance, 1f + minDistance); var maxDist = minDist.WithMagnitude(maxDistance - minDistance); return point + maxDist; } private void SetLocalPosition(GameObject @object, Transform parent, Vector3 position) { @object.transform.parent = parent; @object.transform.localPosition = position; } }<file_sep>/Assets/Procedural Art/Scripts/Generators/LBuildingGenerator.cs using System; using System.Collections.Generic; using UnityEditor; using UnityEngine; public class LBuildingGenerator : BuildingGenerator { public static new bool DoneOnceField = false; public override void DoOnce(ref bool doneOnceField) { if (doneOnceField) return; doneOnceField = true; } public override MeshData Generate(PlotData plot, BuildingTypeSettings settings, float heightAdjustment, Vector3 offset, int LOD) { DoOnce(ref DoneOnceField); var size = new Vector2Int(Mathf.RoundToInt(plot.Bounds.size.x), Mathf.RoundToInt(plot.Bounds.size.y)); var boolArr = GenL(size, heightAdjustment); var overhang = GenLOverhang(LOD); var roofs = GenLRoof(); var path = MarchingSquares.March(boolArr); CleanupOutline(boolArr); var walls = GenWalls(path, LOD); return MeshUtils.Combine(roofs, walls, overhang); } protected Arr2d<bool> GenL(Vector2Int size, float heightAdjustment) { var widthA = RandUtils.RandomBetween(GeneratorSettings.LSettings.MinMaxWidthA); var lengthA = RandUtils.RandomBetween(GeneratorSettings.LSettings.MinMaxLengthA); var widthB = RandUtils.RandomBetween(GeneratorSettings.LSettings.MinMaxWidthB); // widthB = MathUtils.Clamp(widthB, 2, widthA - 1); var lengthB = RandUtils.RandomBetween(GeneratorSettings.LSettings.MinMaxLengthB); // lengthB = MathUtils.Clamp(lengthB, 1, Mathf.CeilToInt(lengthA / 2f)); BuildingHeight = heightAdjustment+ RandUtils.RandomBetween(GeneratorSettings.LSettings.MinMaxHeight); // normalize size so it's in range of <size> var proportionWA = widthA / (float) (widthA + widthB); var proportionWB = widthB / (float) (widthA + widthB); var proportionLA = lengthA / (float) (lengthA + lengthB); var proportionLB = lengthB / (float) (lengthA + lengthB); var actualWidthA = Mathf.CeilToInt(proportionWA * size.x); var actualWidthB = Mathf.FloorToInt(proportionWB * size.x); var actualLengthA = Mathf.CeilToInt(proportionLA * size.y); var actualLengthB = Mathf.FloorToInt(proportionLB * size.y); actualWidthA += (size.x - actualWidthA - actualWidthB); actualLengthA += (size.y - actualLengthA - actualLengthB); DimensionsA = new Vector2Int(actualWidthA + actualWidthB, actualLengthA + actualLengthB); DimensionsB = new Vector2Int(actualWidthB, actualLengthB); var boolArr = new Arr2d<bool>(DimensionsA, true); CarveLShape(boolArr); return boolArr; } protected MeshData GenLRoof() { var height = RandUtils.RandomBetween(GeneratorSettings.LSettings.MinMaxRoofHeight); var thickness = GeneratorSettings.GeneralSettings.RoofThickness; var extrusion = GeneratorSettings.GeneralSettings.RoofExtrusion; var cornerRoofEndingChance = GeneratorSettings.LSettings.CornerEndingChance; var roofs = new List<MeshData>(); if (RandUtils.BoolWeighted(cornerRoofEndingChance)) { var roofInset = DimensionsB.x * RandUtils.RandomBetween(GeneratorSettings.LSettings.CornerInsetRatio); var roofSize = (DimensionsA.x - roofInset) - (DimensionsA.x - DimensionsB.x) / 2f; var cornerA = MeshGenerator.GetMesh<CornerRoofGenerator>(new Vector3(DimensionsA.x - 0.5f, BuildingHeight, DimensionsA.y - DimensionsB.y - 0.5f), Quaternion.Euler(0, 180, 0), new Dictionary<string, dynamic> { {"width", roofInset}, {"height", height}, {"length", (DimensionsA.y - DimensionsB.y) / 2f}, {"thickness", thickness}, {"addCap", true}, {"joinCaps", true}, }); var cornerA1 = MeshGenerator.GetMesh<CornerRoofGenerator>(new Vector3(DimensionsA.x - 0.5f, BuildingHeight, -0.5f), Quaternion.Euler(0, 270, 0), new Dictionary<string, dynamic> { {"width", (DimensionsA.y - DimensionsB.y) / 2f}, {"height", height}, {"length", roofInset}, {"thickness", thickness}, {"addCap", true}, {"joinCaps", true}, }); var roofA = MeshGenerator.GetMesh<StraightRoofGenerator>(new Vector3(DimensionsA.x - roofSize - roofInset - 0.5f, BuildingHeight, -0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"width", roofSize}, {"height", height}, {"thickness", thickness}, {"length", (DimensionsA.y - DimensionsB.y) / 2f}, {"extrusion", 0}, {"addCap", true}, {"closeRoof", true} }); var roofA1 = MeshGenerator.GetMesh<StraightRoofGenerator>(new Vector3(DimensionsA.x - roofInset - 0.5f, BuildingHeight, DimensionsA.y - DimensionsB.y - 0.5f), Quaternion.Euler(0, 180, 0), new Dictionary<string, dynamic> { {"width", roofSize}, {"height", height}, {"length", (DimensionsA.y - DimensionsB.y) / 2f}, {"thickness", thickness}, {"extrusion", 0}, {"addCap", true}, {"closeRoof", true} }); roofs.Add(cornerA); roofs.Add(cornerA1); roofs.Add(roofA); roofs.Add(roofA1); } else { var roofSize = (DimensionsA.x) - (DimensionsA.x - DimensionsB.x) / 2f; var roofA = MeshGenerator.GetMesh<StraightRoofGenerator>(new Vector3(DimensionsA.x - roofSize - 0.5f, BuildingHeight, -0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"width", roofSize}, {"height", height}, {"thickness", thickness}, {"length", (DimensionsA.y - DimensionsB.y) / 2f}, {"extrusion", extrusion}, {"extrusionLeft", false}, {"addCap", true}, {"closeRoof", true} }); var roofA1 = MeshGenerator.GetMesh<StraightRoofGenerator>(new Vector3(DimensionsA.x - 0.5f, BuildingHeight, DimensionsA.y - DimensionsB.y - 0.5f), Quaternion.Euler(0, 180, 0), new Dictionary<string, dynamic> { {"width", roofSize}, {"height", height}, {"length", (DimensionsA.y - DimensionsB.y) / 2f}, {"thickness", thickness}, {"extrusion", extrusion}, {"extrusionRight", false}, {"addCap", true}, {"closeRoof", true} }); roofs.Add(roofA); roofs.Add(roofA1); } var cornerB = MeshGenerator.GetMesh<CornerRoofGenerator>(new Vector3(-0.5f, BuildingHeight, -0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"width", (DimensionsA.x - DimensionsB.x) / 2f}, {"height", height}, {"length", (DimensionsA.y - DimensionsB.y) / 2f}, {"thickness", thickness}, {"addCap", true}, {"joinCaps", true} }); roofs.Add(cornerB); var roofB = MeshGenerator.GetMesh<StraightRoofGenerator>(new Vector3(-0.5f, BuildingHeight, DimensionsA.y - 0.5f), Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"width", DimensionsB.y + (DimensionsA.y - DimensionsB.y) / 2f}, {"height", height}, {"length", (DimensionsA.x - DimensionsB.x) / 2f}, {"thickness", thickness}, {"extrusion", extrusion}, {"extrusionRight", false}, {"addCap", true}, {"closeRoof", true} }); var roofB1 = MeshGenerator.GetMesh<StraightRoofGenerator>(new Vector3(DimensionsA.x - DimensionsB.x - 0.5f, BuildingHeight, (DimensionsA.y - DimensionsB.y) / 2f - 0.5f), Quaternion.Euler(0, -90, 0), new Dictionary<string, dynamic> { {"width", DimensionsB.y + (DimensionsA.y - DimensionsB.y) / 2f}, {"height", height}, {"length", (DimensionsA.x - DimensionsB.x) / 2f}, {"thickness", thickness}, {"extrusion", extrusion}, {"extrusionLeft", false}, {"addCap", true}, {"closeRoof", true}, }); roofs.Add(roofB); roofs.Add(roofB1); return MeshUtils.Combine(roofs); } protected MeshData GenLOverhang(int LOD) { if (!RandUtils.BoolWeighted(GeneratorSettings.LSettings.OverhangChance)) return new MeshData(); var featureThickness = 0.1f; var meshes = new List<MeshData>(); var thickness = 0.25f; var start = 2; var end = Rand.Range(start + 1, BuildingHeight - 1); var height = end - start; // WALLS var wallA = MeshGenerator.GetMesh<PlaneGenerator>(new Vector3(DimensionsA.x - DimensionsB.x - 0.5f, start, DimensionsA.y - 0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"sizeA", DimensionsB.x}, {"sizeB", height}, {"orientation", PlaneGenerator.PlaneOrientation.XY}, {"flip", true} }); var wallB = MeshGenerator.GetMesh<PlaneGenerator>(new Vector3(DimensionsA.x - 0.5f, start, DimensionsA.y - 0.5f), Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"sizeA", DimensionsB.y}, {"sizeB", height}, {"orientation", PlaneGenerator.PlaneOrientation.XY}, {"flip", true} }); var plane = MeshGenerator.GetMesh<PlaneGenerator>(new Vector3(DimensionsA.x - DimensionsB.x - 0.5f, start + height, DimensionsA.y - DimensionsB.y - 0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"sizeA", DimensionsB.x}, {"sizeB", DimensionsB.y} }); meshes.Add(wallA); meshes.Add(wallB); meshes.Add(plane); var fromA = new Vector3(DimensionsA.x - DimensionsB.x - 0.5f, start, DimensionsA.y - 0.5f); var toA = fromA + Vector3.right * DimensionsB.x; var wallAPerpendicular = Vector3.Cross((toA - fromA).normalized, Vector3.up); meshes.Add(AddWallFeatures(fromA, toA, height, DimensionsB.x, 0, LOD, false)); meshes.Add(MeshGenerator.GetMesh<LineGenerator>(fromA + Vector3.up * featureThickness - wallAPerpendicular * featureThickness / 2f, Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero + Vector3.right * featureThickness / 2f}, {"end", Vector3.right * (DimensionsB.x - featureThickness / 2f)}, {"thickness", featureThickness}, {"extrusion", featureThickness}, {"submeshIndex", 2}, {"rotateUV", true} })); var fromB = new Vector3(DimensionsA.x - 0.5f, start, DimensionsA.y - 0.5f); var toB = fromB - Vector3.forward * DimensionsB.y; var wallBPerpendicular = Vector3.Cross((toB - fromB).normalized, Vector3.up); meshes.Add(AddWallFeatures(fromB, toB, height, DimensionsB.y, 90, LOD, false)); meshes.Add(MeshGenerator.GetMesh<LineGenerator>(fromB + Vector3.up * featureThickness - wallBPerpendicular * featureThickness / 2f, Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"start", Vector3.zero + Vector3.right * featureThickness / 2f}, {"end", Vector3.right * (DimensionsB.y - featureThickness / 2f)}, {"thickness", featureThickness}, {"extrusion", featureThickness}, {"submeshIndex", 2}, {"rotateUV", true} })); meshes.Add(MeshGenerator.GetMesh<LineGenerator>(new Vector3(DimensionsA.x - 0.5f, 0, DimensionsA.y - 0.5f) - wallAPerpendicular * featureThickness / 2f, Quaternion.identity, new Dictionary<string, dynamic> { {"start", Vector3.zero}, {"end", Vector3.up * (end + featureThickness / 2f)}, {"thickness", featureThickness}, {"extrusion", featureThickness}, {"submeshIndex", 2}, {"rotateUV", true} })); // ARCHES var archChance = 0.5f; var archLOD = LOD == 0 ? 45 : LOD == 1 ? 21 : 7; var shouldAddWallsA = false; var shouldAddWallsB = false; if (RandUtils.BoolWeighted(archChance)) { // ARCHES/ARCH X if (RandUtils.BoolWeighted(archChance)) { var diffA = DimensionsB.x - start; var archWidthA = DimensionsB.x - 2 * thickness; var archOffsetA = thickness; if (diffA > 0) { archWidthA = start; archOffsetA = diffA / 2f; shouldAddWallsA = true; } var archA = MeshGenerator.GetMesh<ArchGenerator>(new Vector3(DimensionsA.x - DimensionsB.x - 0.5f + archOffsetA, start - 1, DimensionsA.y - thickness - 0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"width", archWidthA}, {"height", 1}, {"length", thickness}, {"points", archLOD} }); meshes.Add(archA); if (shouldAddWallsA) { var wallC = MeshGenerator.GetMesh<WallGenerator>(new Vector3(DimensionsA.x - 0.5f, 0, DimensionsA.y - 0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"width", diffA / 2f}, {"height", start}, {"thickness", 0.01f}, {"thicknessInwards", true}, {"flip", true} }); var wallC1 = MeshGenerator.GetMesh<WallGenerator>(new Vector3(DimensionsA.x - DimensionsB.x - 0.5f, 0, DimensionsA.y - 0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"width", diffA / 2f}, {"height", start}, {"thickness", 0.01f}, {"thicknessInwards", true} }); meshes.Add(wallC); meshes.Add(wallC1); } else { var pillarX = MeshGenerator.GetMesh<PillarGenerator>(new Vector3(DimensionsA.x - DimensionsB.x + thickness / 2f - 0.5f, 0, DimensionsA.y - 0.5f), Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"width", thickness}, {"height", start}, {"thicknessInwards", true} }); meshes.Add(pillarX); } } else { shouldAddWallsA = true; var wallX = MeshGenerator.GetMesh<WallGenerator>(new Vector3(DimensionsA.x - 0.5f, 0, DimensionsA.y - 0.5f), Quaternion.identity, new Dictionary<string, dynamic> { {"width", DimensionsB.x}, {"height", start}, {"thickness", 0.01f}, {"thicknessInwards", true}, {"flip", true} }); meshes.Add(wallX); } // ARCHES/ARCH Z if (RandUtils.BoolWeighted(archChance)) { var diffB = DimensionsB.y - start; var archWidthB = DimensionsB.y - 2 * thickness; var archOffsetB = thickness; if (diffB > 0) { archWidthB = start; archOffsetB = diffB / 2f; shouldAddWallsB = true; } var archB = MeshGenerator.GetMesh<ArchGenerator>(new Vector3(DimensionsA.x - 0.5f, start - 1, DimensionsA.y - DimensionsB.y + archOffsetB - 0.5f), Quaternion.Euler(0, -90, 0), new Dictionary<string, dynamic> { {"width", archWidthB}, {"height", 1}, {"length", thickness}, {"points", archLOD} }); meshes.Add(archB); if (shouldAddWallsB) { var wallD = MeshGenerator.GetMesh<WallGenerator>(new Vector3(DimensionsA.x - 0.5f, 0, DimensionsA.y - 0.5f), Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"width", diffB / 2f}, {"height", start}, {"thickness", 0.01f}, {"thicknessInwards", true} }); var wallD1 = MeshGenerator.GetMesh<WallGenerator>(new Vector3(DimensionsA.x - 0.5f, 0, DimensionsA.y - DimensionsB.y - 0.5f), Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"width", diffB / 2f}, {"height", start}, {"thickness", 0.01f}, {"thicknessInwards", true}, {"flip", true} }); meshes.Add(wallD); meshes.Add(wallD1); } else { var pillarZ = MeshGenerator.GetMesh<PillarGenerator>(new Vector3(DimensionsA.x - thickness / 2f - 0.5f, 0, DimensionsA.y - DimensionsB.y + thickness - 0.5f), Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"width", thickness}, {"height", start}, {"thicknessInwards", true} }); meshes.Add(pillarZ); } } else { shouldAddWallsB = true; var wallZ = MeshGenerator.GetMesh<WallGenerator>(new Vector3(DimensionsA.x - 0.5f, 0, DimensionsA.y - 0.5f), Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"width", DimensionsB.y}, {"height", start}, {"thickness", 0.01f}, {"thicknessInwards", true} }); meshes.Add(wallZ); } } // MIDDLE PILLAR if (!shouldAddWallsA || !shouldAddWallsB) { var pillarMid = MeshGenerator.GetMesh<PillarGenerator>(new Vector3(DimensionsA.x - thickness / 2f - 0.5f, 0, DimensionsA.y - 0.5f), Quaternion.Euler(0, 90, 0), new Dictionary<string, dynamic> { {"width", thickness}, {"height", start}, {"thicknessInwards", true} }); meshes.Add(pillarMid); } return MeshUtils.Combine(meshes); } private void CarveLShape(Arr2d<bool> arr) { var from = new Vector2Int(DimensionsA.x - DimensionsB.x, DimensionsA.y - DimensionsB.y); var to = new Vector2Int(DimensionsA.x, DimensionsA.y); arr.Fill(from, to, false); } }<file_sep>/Assets/Procedural Art/Scripts/Mesh Generation/WallGenerator.cs using System.Collections.Generic; using JetBrains.Annotations; using UnityEngine; public class WallGenerator : MeshGenerator { private float width; private float height; private float thickness; private bool thicknessInwards; private bool thicknessOutwards; // if neither of these two are set, it will be in the middle private bool flip; protected override void SetDefaultSettings() { defaultParameters = new Dictionary<string, dynamic> { {"width", 1f}, {"height", 1f}, {"thickness", 0.1f}, {"thicknessInwards", false}, {"thicknessOutwards", false}, {"flip", false} }; } protected override void DeconstructSettings(Dictionary<string, dynamic> parameters) { width = (parameters.ContainsKey("width") ? parameters["width"] : defaultParameters["width"]) * GlobalSettings.Instance.GridSize; height = (parameters.ContainsKey("height") ? parameters["height"] : defaultParameters["height"]) * GlobalSettings.Instance.GridSize; thickness = (parameters.ContainsKey("thickness") ? parameters["thickness"] : defaultParameters["thickness"]) * GlobalSettings.Instance.GridSize; thicknessInwards = parameters.ContainsKey("thicknessInwards") ? parameters["thicknessInwards"] : defaultParameters["thicknessInwards"]; thicknessOutwards = parameters.ContainsKey("thicknessOutwards") ? parameters["thicknessOutwards"] : defaultParameters["thicknessOutwards"]; flip = parameters.ContainsKey("flip") ? parameters["flip"] : defaultParameters["flip"]; } protected override void Generate() { // Outwards thickness var bottomLeft1 = Vector3.zero; var bottomRight1 = bottomLeft1 + (flip ? Vector3.left : Vector3.right) * width; var topLeft1 = bottomLeft1 + Vector3.up * height; var topRight1 = bottomRight1 + Vector3.up * height; var bottomLeft2 = bottomLeft1 + Vector3.forward * thickness; var bottomRight2 = bottomRight1 + Vector3.forward * thickness; var topLeft2 = topLeft1 + Vector3.forward * thickness; var topRight2 = topRight1 + Vector3.forward * thickness; // Middle thickness if (!(thicknessInwards ^ thicknessOutwards)) { bottomLeft1 -= Vector3.forward * (thickness / 2f); bottomRight1 -= Vector3.forward * (thickness / 2f); topLeft1 -= Vector3.forward * (thickness / 2f); topRight1 -= Vector3.forward * (thickness / 2f); bottomLeft2 -= Vector3.forward * (thickness / 2f); bottomRight2 -= Vector3.forward * (thickness / 2f); topLeft2 -= Vector3.forward * (thickness / 2f); topRight2 -= Vector3.forward * (thickness / 2f); } else if (thicknessInwards) { bottomLeft1 -= Vector3.forward * thickness; bottomRight1 -= Vector3.forward * thickness; topLeft1 -= Vector3.forward * thickness; topRight1 -= Vector3.forward * thickness; bottomLeft2 -= Vector3.forward * thickness; bottomRight2 -= Vector3.forward * thickness; topLeft2 -= Vector3.forward * thickness; topRight2 -= Vector3.forward * thickness; } // Front & Back AddQuad(bottomLeft1, topLeft1, topRight1, bottomRight1, 0, flip); // meshData.UVs.AddRange(new List<Vector2> {Vector2.zero, Vector2.up * height, Vector2.up * height + Vector2.right * width, Vector2.right * width}); AddQuad(bottomRight2, topRight2, topLeft2, bottomLeft2, 0, flip); // meshData.UVs.AddRange(new List<Vector2> {Vector2.zero, Vector2.up * height, Vector2.up * height + Vector2.right * width, Vector2.right * width}); // East & West AddQuad(bottomRight1, topRight1, topRight2, bottomRight2, 0, flip); // meshData.UVs.AddRange(new List<Vector2> {Vector2.zero, Vector2.up * height, Vector2.up * height + Vector2.right * thickness, Vector2.right * thickness}); AddQuad(bottomLeft2, topLeft2, topLeft1, bottomLeft1, 0, flip); // meshData.UVs.AddRange(new List<Vector2> {Vector2.zero, Vector2.up * height, Vector2.up * height + Vector2.right * thickness, Vector2.right * thickness}); // North & South AddQuad(topLeft1, topLeft2, topRight2, topRight1, 0, flip); // meshData.UVs.AddRange(new List<Vector2> {Vector2.zero, Vector2.up * thickness, Vector2.up * thickness + Vector2.right * width, Vector2.right * width}); AddQuad(bottomLeft2, bottomLeft1, bottomRight1, bottomRight2, 0, flip); // meshData.UVs.AddRange(new List<Vector2> {Vector2.zero, Vector2.up * thickness, Vector2.up * thickness + Vector2.right * width, Vector2.right * width}); } }<file_sep>/Assets/Procedural Art/Scripts/Settings/WallSettings.cs using UnityEngine; [CreateAssetMenu(fileName = "Wall Settings", menuName = "Wall Settings", order = 0)] public class WallSettings : ScriptableObject { public int Height; public Vector2 HeightVariation; public Vector2 RoofHeightVariation; public float RoofThickness = 0.15f; public float RoofExtrusion = 0.25f; }<file_sep>/Assets/Procedural Art/Scripts/Mesh Generation/CornerRoofGenerator.cs using System.Collections.Generic; using UnityEngine; public class CornerRoofGenerator : MeshGenerator { private float width; private float length; private float height; private float thickness; private bool thicknessBasedOnRoofAngle; private bool addCap; private Vector3 capOffset; private bool flipX; private bool flipZ; private bool joinCaps; protected override void SetDefaultSettings() { defaultParameters = new Dictionary<string, dynamic> { {"width", 1f}, {"length", 1f}, {"height", 1f}, {"thickness", 0.1f}, {"thicknessBasedOnRoofAngle", false}, {"addCap", false}, {"capOffset", Vector3.zero}, {"flipX", false}, {"flipZ", false}, {"joinCaps", false} }; } protected override void DeconstructSettings(Dictionary<string, dynamic> parameters) { width = (parameters.ContainsKey("width") ? parameters["width"] : defaultParameters["width"]) * GlobalSettings.Instance.GridSize; length = (parameters.ContainsKey("length") ? parameters["length"] : defaultParameters["length"]) * GlobalSettings.Instance.GridSize; height = (parameters.ContainsKey("height") ? parameters["height"] : defaultParameters["height"]) * GlobalSettings.Instance.GridSize; thickness = (parameters.ContainsKey("thickness") ? parameters["thickness"] : defaultParameters["thickness"]) * GlobalSettings.Instance.GridSize; thicknessBasedOnRoofAngle = parameters.ContainsKey("thicknessBasedOnRoofAngle") ? parameters["thicknessBasedOnRoofAngle"] : defaultParameters["thicknessBasedOnRoofAngle"]; addCap = parameters.ContainsKey("addCap") ? parameters["addCap"] : defaultParameters["addCap"]; capOffset = (parameters.ContainsKey("capOffset") ? parameters["capOffset"] : defaultParameters["capOffset"]) * GlobalSettings.Instance.GridSize; flipX = parameters.ContainsKey("flipX") ? parameters["flipX"] : defaultParameters["flipX"]; flipZ = parameters.ContainsKey("flipZ") ? parameters["flipZ"] : defaultParameters["flipZ"]; joinCaps = parameters.ContainsKey("joinCaps") ? parameters["joinCaps"] : defaultParameters["joinCaps"]; } protected override void Generate() { var cap10 = new Vector3(0, thickness, 0); var cap13 = new Vector3(0, 0, 0); var cap11 = new Vector3(flipX ? -width : width, thickness, 0); var cap12 = new Vector3(flipX ? -width : width, 0, 0); var cap20 = new Vector3(0, thickness, flipZ ? -length : length); var cap23 = new Vector3(0, 0, flipZ ? -length : length); var cap21 = new Vector3(0, thickness, 0); var cap22 = new Vector3(0, 0, 0); var capMovement30 = joinCaps ? flipX ? thickness : -thickness : 0; var capMovement41 = joinCaps ? flipZ ? thickness : -thickness : 0; var cap30 = new Vector3(capOffset.z + capMovement30, capOffset.y, flipZ ? thickness : -thickness + capOffset.x); var cap31 = new Vector3(flipX ? -width : width + capOffset.z, capOffset.y, flipZ ? thickness : -thickness + capOffset.x); var cap40 = new Vector3(flipX ? thickness : -thickness + capOffset.x, capOffset.y, flipZ ? -length : length + capOffset.z); var cap41 = new Vector3(flipX ? thickness : -thickness + capOffset.x, capOffset.y, capOffset.z + capMovement41); var cap50 = new Vector3(flipX ? -width : width, height, flipZ ? -length : length); var cap51 = new Vector3(flipX ? -width : width, height - thickness, flipZ ? -length : length); if (thicknessBasedOnRoofAngle) { var v1 = cap11 - cap12; var v2 = cap51 - cap12; var angle = Mathf.Deg2Rad * Vector3.Angle(v1, v2); var multiplier = 1f / Mathf.Sin(angle); var actualRoofThickness = thickness * multiplier; cap10.y = actualRoofThickness; cap11.y = actualRoofThickness; cap20.y = actualRoofThickness; cap21.y = actualRoofThickness; cap30.z = flipZ ? actualRoofThickness : -actualRoofThickness + capOffset.x; cap31.z = flipZ ? actualRoofThickness : -actualRoofThickness + capOffset.x; cap40.x = flipX ? actualRoofThickness : -actualRoofThickness + capOffset.x; cap41.x = flipX ? actualRoofThickness : -actualRoofThickness + capOffset.x; cap51.y = height - actualRoofThickness; } AddQuad(cap10, cap11, cap12, cap13, 1, flipX ^ flipZ); AddQuad(cap20, cap21, cap22, cap23, 1, flipX ^ flipZ); AddTriangle(cap11, cap50, cap21, 1, !(flipX ^ flipZ), UVSettings.FlipBottomPart); AddTriangle(cap20, cap50, cap21, 1, flipX ^ flipZ); AddQuad(cap11, cap50, cap51, cap12, 1, flipX ^ flipZ); AddQuad(cap50, cap20, cap23, cap51, 1, flipX ^ flipZ); AddTriangle(cap22, cap12, cap51, 1, flipX ^ flipZ); AddTriangle(cap22, cap51, cap23, 1, flipX ^ flipZ); if (addCap) { AddTriangle(cap12, cap31, cap11, 1, flipX ^ flipZ); AddQuad(cap12, cap13, cap30, cap31, 1, flipX ^ flipZ); AddQuad(cap10, cap11, cap31, cap30, 1, flipX ^ flipZ); AddTriangle(cap23, cap20, cap40, 1, flipX ^ flipZ); AddQuad(cap22, cap23, cap40, cap41, 1, flipX ^ flipZ); AddQuad(cap20, cap21, cap41, cap40, 1, flipX ^ flipZ); AddTriangle(cap21, cap30, cap41, 1, flipX ^ flipZ); AddTriangle(cap41, cap30, cap22, 1, flipX ^ flipZ); } } }<file_sep>/Assets/Procedural Art/Scripts/Misc/PerlinGenerator.cs using UnityEngine; public static class PerlinGenerator { public static Color[] Generate(int textureSize, float frequency, float seed, bool separateRGB = false, bool alpha = false) { var colors = new Color[textureSize * textureSize]; for (int x = 0; x < textureSize; x++) { for (int y = 0; y < textureSize; y++) { float r, g, b; var a = 1f; r = Mathf.PerlinNoise(seed + (x + 0.01f) / frequency, seed + (y + 0.01f) / frequency); g = b = r; if (separateRGB) g = Mathf.PerlinNoise(seed + seed + (x + 0.01f) / frequency, seed + (y + 0.01f) / frequency); if (separateRGB) b = Mathf.PerlinNoise(seed + (x + 0.01f) / frequency, seed + seed + (y + 0.01f) / frequency); if (alpha) a = Mathf.PerlinNoise(seed + seed + (x + 0.01f) / frequency, seed + seed + (y + 0.01f) / frequency); colors[x * textureSize + y] = new Color(r, g, b, a); } } return colors; } }<file_sep>/Assets/Procedural Art/Scripts/Misc/MarchingSquares/Direction.cs using UnityEngine; // ReSharper disable InconsistentNaming public static class Direction { public static readonly Vector2Int E = Vector2Int.right; public static readonly Vector2Int W = Vector2Int.left; public static readonly Vector2Int N = Vector2Int.down; public static readonly Vector2Int S = Vector2Int.up; public static readonly Vector2Int NE = N + E; public static readonly Vector2Int NW = N + W; public static readonly Vector2Int SE = S + E; public static readonly Vector2Int SW = S + W; }<file_sep>/Assets/Procedural Art/Scripts/Settings/BuildingTypeSettings.cs using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "Building Settings", menuName = "Building Settings", order = 0)] public class BuildingTypeSettings : ScriptableObject { public MaterialSettings MaterialSetting; public ScriptableObject GeneratorSettings; public BuildingGenerator GeneratorPrefab; }<file_sep>/Assets/Procedural Art/Scripts/Misc/RandUtils.cs using System.Collections.Generic; using UnityEngine; public static class RandUtils { public static bool BoolWeighted(float weight) { return Rand.Value < weight; } public static float RandomBetween(Vector2 range) { return Rand.Range(range.x, range.y); } public static int RandomBetween(Vector2Int range) { return Rand.RangeInclusive(range.x, range.y); } public static Vector2Int RandomBetween(Vector2Int a, Vector2Int b) { return new Vector2Int(Rand.RangeInclusive(a.x, b.x), Rand.RangeInclusive(a.y, b.y)); } public static Vector3Int RandomBetween(Vector3Int a, Vector3Int b) { return new Vector3Int(Rand.RangeInclusive(a.x, b.x), Rand.RangeInclusive(a.y, b.y), Rand.RangeInclusive(a.z, b.z)); } public static T ListItem<T>(List<T> list) { return list[Rand.Range(0, list.Count)]; } }<file_sep>/Assets/Allegorithmic/Plugins/Substance.EditorHelper/Scripter.cs  using System; using UnityEditor; using UnityEngine; using System.Runtime.InteropServices; using System.IO; using System.Reflection; using System.Collections.Generic; namespace Substance.EditorHelper { public class Scripter { public static void Hello() { Debug.Log("Scripter's Hello"); #if UNITY_2019_3_OR_NEWER Debug.Log("UNITY_2019_3_OR_NEWER"); #endif } public static class UnityPipeline { // The active project context is in the 'Edit->Project Settings->Graphics->Scriptable Render Pipeline Settings' field. public static bool IsHDRP() { #if UNITY_2019_3_OR_NEWER bool bActive = false; UnityEngine.Rendering.RenderPipelineAsset asset; asset = UnityEngine.Rendering.GraphicsSettings.renderPipelineAsset; if ((asset != null) && (asset.GetType().ToString().EndsWith(".HDRenderPipelineAsset"))) { bActive = true; } return bActive; #else return false; #endif } public static bool IsURP() { #if UNITY_2019_3_OR_NEWER bool bActive = false; UnityEngine.Rendering.RenderPipelineAsset asset; asset = UnityEngine.Rendering.GraphicsSettings.renderPipelineAsset; if ((asset != null) && (asset.GetType().ToString().EndsWith(".UniversalRenderPipelineAsset"))) { bActive = true; } return bActive; #else return false; #endif } } } }<file_sep>/Assets/Procedural Art/Scripts/Data/Arr2d.cs using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Arr2d<T> : IEnumerable<T> { private T[][] arr; private int length1; private int length2; public Arr2d(Vector2Int length, T initialValue = default) : this(length.x, length.y, initialValue) { } public Arr2d(int length1, int length2, T initialValue = default) { this.length1 = length1; this.length2 = length2; arr = new T[length1][]; for (int i = 0; i < length1; i++) { arr[i] = new T[length2]; } if (!EqualityComparer<T>.Default.Equals(initialValue, default)) { FillAll(initialValue); } } public void Shrink(int dimension, int size, bool reverseSide = false) { if (size == 0) return; var newLength1 = length1; var newLength2 = length2; var dimensionVec = new Vector2Int(0, 0); switch (dimension) { case 1: newLength1 += size; dimensionVec.x = size; break; case 2: newLength2 += size; dimensionVec.y = size; break; default: throw new InvalidOperationException($"Invalid dimension {dimension}. Should be one of: [1, 2]."); } var arrTemp = new T[newLength1][]; for (int i = 0; i < newLength1; i++) { arrTemp[i] = new T[newLength2]; for (int j = 0; j < newLength2; j++) { if (!reverseSide) arrTemp[i][j] = arr[i][j]; else arrTemp[i][j] = arr[i + dimensionVec.x][j + dimensionVec.y]; } } arr = arrTemp; length1 = newLength1; length2 = newLength2; } public void FlipX() { var arrTemp = new T[length1][]; for (int i = 0; i < length1; i++) { arrTemp[i] = new T[length2]; for (int j = 0; j < length2; j++) { arrTemp[i][j] = arr[length1-i-1][j]; } } arr = arrTemp; } public void FlipY() { var arrTemp = new T[length1][]; for (int i = 0; i < length1; i++) { arrTemp[i] = new T[length2]; for (int j = 0; j < length2; j++) { arrTemp[i][j] = arr[i][length2-j-1]; } } arr = arrTemp; } public void Expand(int dimension, int size, bool reverseSide = false, T value = default) { if (size == 0) return; var newLength1 = length1; var newLength2 = length2; var dimensionVec = new Vector2Int(0, 0); switch (dimension) { case 1: newLength1 += size; dimensionVec.x = size; break; case 2: newLength2 += size; dimensionVec.y = size; break; default: throw new InvalidOperationException($"Invalid dimension {dimension}. Should be one of: [1, 2]."); } var arrTemp = new T[newLength1][]; for (int i = 0; i < newLength1; i++) { arrTemp[i] = new T[newLength2]; if (!EqualityComparer<T>.Default.Equals(value, default)) for (int j = 0; j < newLength2; j++) arrTemp[i][j] = value; } for (int i = 0; i < length1; i++) for (int j = 0; j < length2; j++) { if (!reverseSide) { arrTemp[i][j] = arr[i][j]; } else arrTemp[i + dimensionVec.x][j + dimensionVec.y] = arr[i][j]; } arr = arrTemp; length1 = newLength1; length2 = newLength2; } public void FillAll(T value) { for (int i = 0; i < length1; i++) for (int j = 0; j < length2; j++) arr[i][j] = value; } public void Fill(Vector2Int from, Vector2Int to, T value) { for (int i = from.x; i < to.x; i++) for (int j = from.y; j < to.y; j++) arr[i][j] = value; } public int Length1 => length1; public int Length2 => length2; public Vector2Int Length => new Vector2Int(length1, length2); public T this[int x, int y] { get { if (x < 0 || x >= length1 || y < 0 || y >= length2) return default; return arr[x][y]; } set { if (x < 0 || x >= length1 || y < 0 || y >= length2) return; arr[x][y] = value; } } public T this[Vector2Int index] { get => this[index.x, index.y]; set => this[index.x, index.y] = value; } public IEnumerator<T> GetEnumerator() { for (int i = 0; i < length1; i++) for (int j = 0; j < length2; j++) { if (arr[i][j] == null) continue; yield return arr[i][j]; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }<file_sep>/Assets/Procedural Art/Scripts/Misc/WeightedRandom.cs using System.Collections.Generic; using UnityEngine; public class WeightedRandom { private float[] weights; private float[] additiveWeights; private readonly int count; private bool calculatedAdditiveWeights; public WeightedRandom(params float[] weights) { count = weights.Length; this.weights = new float[count]; for (var i = 0; i < count; i++) { this.weights[i] = weights[i]; } calculatedAdditiveWeights = false; } public void NormalizeWeights() { var weightSum = 0f; for (var i = 0; i < count; i++) { weightSum += weights[i]; } var multiplier = 1f / weightSum; for (var i = 0; i < count; i++) { weights[i] *= multiplier; } if(calculatedAdditiveWeights) CalculateAdditiveWeights(); } public void CalculateAdditiveWeights() { additiveWeights = new float[count]; additiveWeights[0] = weights[0]; for (var i = 1; i < count; i++) { additiveWeights[i] = additiveWeights[i - 1] + weights[i]; } calculatedAdditiveWeights = true; } public int Value() { float[] array = weights; if (calculatedAdditiveWeights) array = additiveWeights; var randomValue = Rand.Value; for (var i = 0; i < count-1; i++) { if (randomValue < array[i]) return i; } return count - 1; } }<file_sep>/Assets/Procedural Art/Scripts/Settings/SLSettings.cs using System; using UnityEngine; using UnityEngine.Serialization; [CreateAssetMenu(menuName = "SL Settings", order = 0)] public class SLSettings : ScriptableObject { public GeneralBuildingSettingsData GeneralSettings; [FormerlySerializedAs("SquareBuildingSettings")] public SquareBuildingSettingsData SquareSettings; [FormerlySerializedAs("LBuildingSettings")] public LBuildingSettingsData LSettings; [Serializable] public class GeneralBuildingSettingsData { public float RoofThickness = 0.15f; public float RoofExtrusion = 0.25f; public float ChimneyChance = 0.9f; public float ChimneySmokeChance = 0.3f; public Vector2 ChimneyThicknessMinMax = 0.25f*(Vector2.up + Vector2.one); [Header("Very Poor wall features")] public float FillWallSegmentChance = 0.1f; public Vector2 FillWallSegmentSpacing = 0.01f*(Vector2.one + Vector2.up); [Header("<= Poor wall features")] public float FeatureThickness = 0.1f; public float DiagonalAChance = 0.5f; public float DiagonalBChance = 0.5f; public float WindowChance = 0.2f; public Vector2 HorizontalSplitMinMax = 2*Vector2.one + Vector2.up; public Vector2 VerticalSplitMinMax = 2*Vector2.one + 2*Vector2.up; [Header(">= Normal wall features")] public float PillarThickness = 0.25f; } [Serializable] public class SquareBuildingSettingsData { public Vector2Int MinMaxHeight; public Vector2 MinMaxRoofHeight; [Space] public float StraightRoofChance = 0.33334F; public float DoubleCornerRoofChance = 0.33333F; public float CornerRoofChance = 0.33333F; [Space] public Vector2 RoofWidthToBuildingWidthRatio = Vector2.up; } [Serializable] public class LBuildingSettingsData { public Vector2Int MinMaxHeight; public Vector2 MinMaxRoofHeight; [Space] public float CornerEndingChance = 0.3333F; public Vector2 CornerInsetRatio = Vector2.one - 0.5f * Vector2.right; [Space] public Vector2Int MinMaxWidthA; public Vector2Int MinMaxLengthA; public Vector2Int MinMaxWidthB; public Vector2Int MinMaxLengthB; [Space] public float OverhangChance; } }<file_sep>/Assets/Procedural Art/Scripts/Plots/PlotGrid.cs using System; using System.Collections.Generic; using UnityEngine; [Serializable] public class PlotGrid { public List<Plot> Plots; public string Name; public Color Color; }<file_sep>/Assets/Procedural Art/Scripts/Readme/Readme.cs using System; using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; using Object = UnityEngine.Object; public class Readme : MonoBehaviour { } [CustomEditor(typeof(Readme))] public class ReadmeEditor : Editor { public override void OnInspectorGUI() { var heading = new GUIStyle(GUI.skin.label); heading.fontStyle = FontStyle.Bold; heading.fontSize = 24; var sectionTitle = new GUIStyle(GUI.skin.label); sectionTitle.fontStyle = FontStyle.Bold; sectionTitle.fontSize = 16; var label = new GUIStyle(GUI.skin.label); label.wordWrap = true; label.fontSize = 14; var buttonStyle = new GUIStyle(GUI.skin.button); buttonStyle.fontSize = 14; GUILayout.Label("Scene structure", heading); GUILayout.BeginVertical(); GUILayout.Label("Camera Controller", sectionTitle); GUILayout.Label("The GameObject \"CameraContainer\" contains a script which rotates the game view camera and offers two different view modes which I thought were appropriate for a city scape. The overall high above view (the one that is visible now) and a low, sea level, view which I think shows the city scape and makes evident the verticality aspect.", label); if (GUILayout.Button("Show CameraContainer object", buttonStyle)) { EditorGUIUtility.PingObject(20208); } GUILayout.EndVertical(); GUILayout.BeginVertical(); GUILayout.Label("Generator", sectionTitle); GUILayout.Label("The \"Builder\" GameObject is responsible for generating the procedural buildings. It has different settings, such as the Plot file (layout of city), general settings (seed/auto seeding) and richness/height maps among many others. Sometimes the internal structures that the script uses get nullified (mostly after assembly reloading) so if you're getting null ref exceptions press the \"Fix Refs\" button.\nFinally, the \"Generate\" button initiates the generation. Warning: you should wait for generation to finish before clicking the generate button again because otherwise weird things might happen.", label); if (GUILayout.Button("Show Builder object", buttonStyle)) { EditorGUIUtility.PingObject(20298); } GUILayout.EndVertical(); GUILayout.BeginVertical(); GUILayout.Label("Folder structure", heading); if (GUILayout.Button("Show Prefabs folder")) EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath<Object>("Assets/Procedural Art/Prefabs")); if (GUILayout.Button("Show Resources folder")) EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath<Object>("Assets/Procedural Art/Resources")); if(GUILayout.Button("Show General settings")) EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath<Object>("Assets/Procedural Art/Resources/General Settings.asset")); if(GUILayout.Button("Show Building settings")) EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath<Object>("Assets/Procedural Art/Resources/Settings")); if(GUILayout.Button("Show Material settings")) EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath<Object>("Assets/Procedural Art/Resources/Materials")); GUILayout.EndVertical(); } }<file_sep>/Assets/Procedural Art/Scripts/Misc/MeshUtils.cs using System.Collections.Generic; using UnityEngine; public static class MeshUtils { public static MeshData Combine(params MeshData[] lists) { var combined = new MeshData(); foreach (var meshData in lists) { combined.MergeMeshData(meshData); } return combined; } public static MeshData Combine(List<MeshData> lists) { var combined = new MeshData(); foreach (var meshData in lists) { combined.MergeMeshData(meshData); } return combined; } public static MeshData Translate(MeshData data, Vector3 translation) { var clone = Combine(data); for (int i = 0; i < data.Vertices.Count; i++) { clone.Vertices[i] += translation; } return clone; } }<file_sep>/Assets/Procedural Art/Scripts/Settings/BuildingVersions.cs using System; using System.Runtime.CompilerServices; using JetBrains.Annotations; using UnityEngine; [CreateAssetMenu(fileName = "Building Versions", menuName = "Building Versions", order = 0)] public class BuildingVersions : ScriptableObject { [Header("Richness (0 - very poor, 3 - rich)")] public BuildingTypeSettings[] Versions = new BuildingTypeSettings[4]; public string PlotLayerName; private void OnValidate() { if (Versions.Length != 4) { Array.Resize(ref Versions, 4); } } public BuildingTypeSettings Select(int richness) { for (int i = richness; i > 0; i--) { if (Versions[i] != null) return Versions[i]; } return Versions[0]; } }<file_sep>/Assets/Procedural Art/Scripts/Misc/RandomNumberGenerator.cs using System; /// <summary> /// Took this from the source code of an amazing game called RimWorld. /// I am not proud of this but for the scope of this project I didn't have time to implement something like this. /// The Unity Random is really bad. /// </summary> public class RandomNumberGenerator { public uint seed = (uint) DateTime.Now.GetHashCode(); public int GetInt(uint iterations) { return (int) GetHash((int) iterations); } public float GetFloat(uint iterations) { return (float) ((GetInt(iterations) - (double) int.MinValue) / uint.MaxValue); } private uint GetHash(int buffer) { uint num1 = Rotate(seed + 374761393U + 4U + (uint) (buffer * -1028477379), 17) * 668265263U; uint num2 = (num1 ^ num1 >> 15) * 2246822519U; uint num3 = (num2 ^ num2 >> 13) * 3266489917U; return num3 ^ num3 >> 16; } private static uint Rotate(uint value, int count) { return value << count | value >> 32 - count; } }<file_sep>/Assets/Procedural Art/Scripts/Mesh Generation/MeshGenerator.cs using System; using System.Collections.Generic; using UnityEngine; public abstract class MeshGenerator { protected MeshData meshData; protected Vector3 position; protected Vector3 scale; protected Quaternion rotation; protected Dictionary<string, dynamic> defaultParameters; protected abstract void SetDefaultSettings(); protected abstract void DeconstructSettings(Dictionary<string, dynamic> parameters); protected virtual void ApplyCustomSettings() { } protected abstract void Generate(); public static MeshData GetMesh<T>(Vector3 position, Quaternion rotation, Dictionary<string, dynamic> parameters) where T : MeshGenerator, new() { var generator = new T(); return generator.GetMesh(position, rotation, parameters); } private MeshData GetMesh(Vector3 position, Quaternion rotation, Dictionary<string, dynamic> parameters) { this.position = position; this.rotation = rotation; meshData = new MeshData(); SetDefaultSettings(); DeconstructSettings(parameters); ApplyCustomSettings(); Generate(); ApplyTransformation(); return meshData; } private void ApplyTransformation() { for (var i = 0; i < meshData.Vertices.Count; i++) { meshData.Vertices[i] = rotation * (meshData.Vertices[i] * GlobalSettings.Instance.GridSize) + position * GlobalSettings.Instance.GridSize; } } protected void AddQuad(Vector3 v0, Vector3 v1, Vector3 v2, Vector3 v3, int submesh, bool flip = false, UVSettings uvSettings = Default) { var quadIndex = meshData.Vertices.Count; if (flip) { meshData.Vertices.Add(v3); meshData.Vertices.Add(v2); meshData.Vertices.Add(v1); meshData.Vertices.Add(v0); } else { meshData.Vertices.Add(v0); meshData.Vertices.Add(v1); meshData.Vertices.Add(v2); meshData.Vertices.Add(v3); } var uvs = UVUtils.QuadUVS2(v0, v1, v2, v3, position, uvSettings); meshData.UVs.AddRange(uvs); if (!meshData.Triangles.ContainsKey(submesh)) meshData.Triangles[submesh] = new List<int>(); meshData.Triangles[submesh].Add(quadIndex); meshData.Triangles[submesh].Add(quadIndex + 1); meshData.Triangles[submesh].Add(quadIndex + 2); meshData.Triangles[submesh].Add(quadIndex); meshData.Triangles[submesh].Add(quadIndex + 2); meshData.Triangles[submesh].Add(quadIndex + 3); } protected void AddTriangle(Vector3 v0, Vector3 v1, Vector3 v2, int submesh, bool flip = false, UVSettings uvSettings = Default) { var triangleIndex = meshData.Vertices.Count; if (flip) { meshData.Vertices.Add(v2); meshData.Vertices.Add(v1); meshData.Vertices.Add(v0); // var uvs = UVUtils.TriangleUVS2(v2, v1, v0, uvSettings, flip); // meshData.UVs.AddRange(uvs); } else { meshData.Vertices.Add(v0); meshData.Vertices.Add(v1); meshData.Vertices.Add(v2); } var uvs = UVUtils.TriangleUVS2(v0, v1, v2, uvSettings, position); meshData.UVs.AddRange(uvs); if (!meshData.Triangles.ContainsKey(submesh)) meshData.Triangles[submesh] = new List<int>(); meshData.Triangles[submesh].Add(triangleIndex); meshData.Triangles[submesh].Add(triangleIndex + 1); meshData.Triangles[submesh].Add(triangleIndex + 2); } [Flags] public enum UVSettings { None = 0, FlipHorizontal = 1, FlipVertical = 2, Rotate = 4, TriangleMiddle = 8, FlipTopPart = 16, FlipBottomPart = 32, NoOffset = 64 } public const UVSettings Default = UVSettings.None; }<file_sep>/Assets/Procedural Art/Scripts/PlotBuildingGenerator.cs using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEngine; public class PlotBuildingGenerator : MonoBehaviour { public PlotScriptableObject PlotFile; public GeneralSettings GeneralSettings; public List<BuildingVersions> BuildingVersions; [Space] public Texture2D RichnessMap; [Tooltip("Generate a random richness map using perlin noise instead of the recommended map")] public bool GenerateRichnessMap; [Range(0f, 1f)] public float RandomRichnessChance = 0.25f; public List<string> IgnoreRandomRichness; [Space] public Texture2D HeightMap; [Tooltip("Generate a random height map using perlin noise instead of the recommended map")] public bool GenerateHeightMap; public float HeightMapMagnitude = 2f; [Space] public bool PlaceOnMinY; private List<Transform> children; private Color[] richnessColors; private int richnessMapSize; private Color[] heightColors; private int heightMapSize; // Update is called once per frame public void Fix() { while (transform.childCount > 0) DestroyImmediate(transform.GetChild(0).gameObject); children = new List<Transform>(); } public void Generate() { if (GenerateRichnessMap) { Rand.PushState(); richnessColors = PerlinGenerator.Generate(1024, 300, Rand.Range(0, (float)(1<<12))); Rand.PopState(); richnessMapSize = 1024; } else { richnessColors = RichnessMap.GetPixels(); richnessMapSize = RichnessMap.width; } if (GenerateHeightMap) { Rand.PushState(); heightColors = PerlinGenerator.Generate(1024, 300, Rand.Range(0, (float)(1<<12))); Rand.PopState(); heightMapSize = 1024; } else { heightColors = HeightMap.GetPixels(); heightMapSize = HeightMap.width; } var seed = GeneralSettings.Seed; if (GeneralSettings.AutoSeed) { seed = DateTime.Now.Ticks; GeneralSettings.Seed = seed; } Rand.PushState((int) seed); try { children.ForEach(child => DestroyImmediate(child.gameObject)); children.Clear(); } catch (Exception e) { Debug.LogError("Internal data ended up as null (probably from an assembly reload). Press the <<Fix Refs>> button on the Generator"); throw; } // Reset static fields BuildingGenerator.DoneOnceField = false; PoorSBuildingGenerator.DoneOnceField = false; NormalSBuildingGenerator.DoneOnceField = false; LBuildingGenerator.DoneOnceField = false; PoorLBuildingGenerator.DoneOnceField = false; NormalLBuildingGenerator.DoneOnceField = false; WallBuildingGenerator.DoneOnceField = false; TowerBuildingGenerator.DoneOnceField = false; OverhangBuildingGenerator.DoneOnceField = false; for (var i = 0; i < PlotFile.PlotGrids.Count; i++) { var buildingVersions = BuildingVersions.Find(settings => settings.PlotLayerName == PlotFile.PlotGrids[i].Name); if (buildingVersions == null) continue; StartCoroutine(GenerateBuildings(buildingVersions, i)); } } public IEnumerator GenerateBuilding(PlotData plot, BuildingTypeSettings settings, float heightAdjustment, Action<Transform> callback) { yield return new WaitForSecondsRealtime(0); var building = Instantiate(settings.GeneratorPrefab, new Vector3(plot.Bounds.center.x, transform.position.y, plot.Bounds.center.y), Quaternion.Euler(0, plot.Rotation, 0)); PlaceBuilding(plot, building); building.GenerateFromPlot(plot, settings, heightAdjustment, transform.position); callback(building.transform); } private void PlaceBuilding(PlotData plot, BuildingGenerator building) { var (leftDown, rightDown, rightUp, leftUp) = MathUtils.RotatedRectangle(plot); var averageY = 0f; var count = 0; var minY = 1000f; if (Physics.Raycast(leftDown + Vector3.up * 200, Vector3.down, out var hitInfo1, LayerMask.GetMask("Terrain"))) { averageY += hitInfo1.point.y; minY = Math.Min(minY, hitInfo1.point.y); count++; } if (Physics.Raycast(leftUp + Vector3.up * 200, Vector3.down, out var hitInfo2, LayerMask.GetMask("Terrain"))) { averageY += hitInfo2.point.y; minY = Math.Min(minY, hitInfo2.point.y); count++; } if (Physics.Raycast(rightDown + Vector3.up * 200, Vector3.down, out var hitInfo3, LayerMask.GetMask("Terrain"))) { averageY += hitInfo3.point.y; minY = Math.Min(minY, hitInfo3.point.y); count++; } if (Physics.Raycast(rightUp + Vector3.up * 200, Vector3.down, out var hitInfo4, LayerMask.GetMask("Terrain"))) { averageY += hitInfo4.point.y; minY = Math.Min(minY, hitInfo4.point.y); count++; } averageY /= count; var currentPosition =building.transform.position; currentPosition.y = PlaceOnMinY ? minY : averageY; building.transform.position = currentPosition; } public IEnumerator GenerateBuildings(BuildingVersions settings, int plotGridIndex) { var plotGrid = PlotFile.PlotGrids[plotGridIndex]; foreach (var plot in plotGrid.Plots) { var richness = (int) SampleHeightMap(plot, richnessColors, richnessMapSize, 3); if (RandUtils.BoolWeighted(RandomRichnessChance) && !IgnoreRandomRichness.Contains(plotGrid.Name)) richness = Rand.RangeInclusive(0, 3); var heightAdjustment = SampleHeightMap(plot, heightColors, heightMapSize, HeightMapMagnitude); StartCoroutine(GenerateBuilding(plot, settings.Select(richness), heightAdjustment, transform1 => { transform1.parent = transform; children.Add(transform1); transform1.gameObject.name += $"__{richness}"; })); yield return new WaitForSecondsRealtime(0); } } public float SampleHeightMap(PlotData plot, Color[] colors, int mapSize, float maxValue) { var center = plot.Bounds.center.Map(-200, 200, 0, mapSize).ToV2I(false, true); var radiusVec = (plot.Bounds.size / 2.0f).Map(0, 400, 0, mapSize); var radius = radiusVec.magnitude; var r = (int) radius; var r2 = (int) (radius * radius); int count = 0; float value = 0f; for (int i = center.y - r; i <= center.y + r; i++) { // test upper half of circle, stopping when top reached for (int j = center.x; (j - center.x) * (j - center.x) + (i - center.y) * (i - center.y) <= r2; j--) { value += colors[i * mapSize + j].grayscale; count++; } // test bottom half of circle, stopping when bottom reached for (int j = center.x + 1; (j - center.x) * (j - center.x) + (i - center.y) * (i - center.y) <= r2; j++) { value += colors[i * mapSize + j].grayscale; count++; } } value /= count; return Mathf.RoundToInt(value * maxValue); } } [CustomEditor(typeof(PlotBuildingGenerator))] public class PlotBuildingGeneratorEditor : Editor { public override void OnInspectorGUI() { base.OnInspectorGUI(); var plotter = target as PlotBuildingGenerator; if (GUILayout.Button("Fix Refs")) { plotter.Fix(); } if (GUILayout.Button("Generate")) { plotter.Generate(); } } }
a8f842d4cdf2f0b91b1577cc8b3c2a4e460c8ae9
[ "Markdown", "C#" ]
51
C#
TeodorVecerdi/saxion_procedural_art
11eecd7fd652465c21a1b9c867c13932478abab2
f23fe28c1aeec92adc930213b47803ee085b1ae2
refs/heads/master
<file_sep>const router = require('express').Router(); const Medico = require('../models/medico'); let { verificaToken } = require('../middlewares/middleware'); router.get('/', (req, res) => { Medico.find({}) .populate('usuario ','nombre email') .populate('hospital') .exec( ( err, medicosDB ) => { if( err ){ return res.status(500) .json({ ok: false, err }); } if( !medicosDB ){ return res.status(401) .json({ ok: false, message: 'Empty database' }); } return res.json({ ok: true, medicos: medicosDB }); }); }); router.post('/', verificaToken, (req, res) => { let body = req.body; console.log(body) let newMedico = new Medico({ nombre: body.nombre, usuario: req.usuario._id, hospital: body.hospital }); newMedico.save( (err, medicoDB) => { if( err ){ return res.status(500) .json({ ok: false, err }); } return res.json({ ok: true, medico: medicoDB }); }); }); router.put('/', verificaToken, (req, res) => { let id = req.body.id; let body = req.body; Medico.findByIdAndUpdate(id) .exec( (err, medicoUpdated) => { if( err ){ return res.status(500) .json({ ok: false, err }); } if( !medicoUpdated ){ return res.status(401) .json({ ok: false, message: 'No hay coincidencias con el id.'}) } medicoUpdated.nombre = body.nombre; medicoUpdated.img = body.img; medicoUpdated.usuario = req.usuario._id; medicoUpdated.hospital = body.hospital; medicoUpdated.save((err, medicoGuardado) => { if( err ){ return res.status(400) .json({ ok:false, message: 'Error al guardar cambios', err }) } return res.json({ ok:true, medico_actualizado: medicoGuardado }) }); }); }); router.delete('/:id', (req, res) => { let id = req.query.id; Medico.findOneAndRemove(id) .exec( (err, medicoDel) => { if( err ){ return res.status(500) .json({ ok: false, err }) } if( !medicoDel ){ res.status(400) .json({ ok:false, message: 'Error al borrar, id no encontrado' }) } return res.json({ ok: true, hospital: medicoDel, borrado: true }) }); }) module.exports = router;<file_sep>const router = require('express').Router(); const path = require('path'); const fs = require('fs-extra'); router.get( '/:tipo/:img', async(req, res) => { let tipo = req.params.tipo; let img = req.params.img; let imgpath = path.join( __dirname + `../../uploads/${ tipo }/${ img }` ); if( !await fs.pathExistsSync(imgpath) ){ imgpath = path.join(__dirname + '../../assets/' + 'no-img.jpg' ); } res.sendFile(imgpath); }); // router.get( '/:tipo/:img', async(req, res) => { // let tipo = req.params.tipo; // let img = req.params.img; // let imgpath = path.join( __dirname + `../../uploads/${ tipo }/${ img }` ); // console.log(imgpath) // if( !await fs.pathExistsSync(imgpath) ){ // // return res.json({ ok:true, path: imgpath }) // imgpath = path.join(__dirname + '../../assets/' + 'no-img.jpg' ); // } // // return res.json({ // // ok: false, // // default: imgpath // // }) // res.sendFile(imgpath); // }); module.exports = router;<file_sep>const { Schema, model } = require('mongoose'); let hospitalSchema = new Schema({ nombre: { type: String, required:[true, 'El nombre es requerido'] }, imgpath: { type: String }, usuario: { type: Schema.Types.ObjectId, ref: 'Usuario' } }); module.exports = model('Hospital', hospitalSchema);<file_sep>var { Schema, model } = require('mongoose'); //Validador para campos var uniqueValidator = require('mongoose-unique-validator'); //asignamos un array roles validos let rolesValidos = { values: ['ADMIN_ROLE','USER_ROLE'], message: '{VALUE} no es un rol valido' } var usuarioSchema = new Schema({ nombre: { type: String, required: [true, 'El nombre es necesario'] }, email: { type: String, unique:true, required: [true, 'El correo es necesario'] }, pass: { type: String, required: [true, 'La contraseña es necesario'] }, imgpath: { type: String, required:false }, role: { type: String, required: true, default: 'USER_ROLE', enum: rolesValidos}, google: { type: Boolean, default: false } }); //Aplicamos el validador de campo unico a este esquema usuarioSchema.plugin( uniqueValidator, { message: 'El {PATH} debe ser unico'} ); module.exports = model('Usuario', usuarioSchema);<file_sep>var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var app = express(); /* * RUTAS */ var routeUsuario = require('./routes/usuario'); var routeMedico = require('./routes/medico'); var routeHospital = require('./routes/hospital'); var routeBusqueda = require('./routes/busqueda'); var routeIndex = require('./routes/index'); var uploadsRoute = require('./routes/upload'); var imgRoute = require('./routes/imagenes'); var loginRoute = require('./routes/login'); //Conexion mongoose.connect('mongodb://localhost:27017/Hospital', (err, res) => { if( err ){ throw new err; } console.log('Database: \x1b[34m%s\x1b[0m','run') }); //Carpeta estatica publica app.use( express.static( __dirname + '/uploads') ); //Body Parser app.use(bodyParser.urlencoded({ extended: false})); app.use(bodyParser.json()); //Midlewares app.use( express.urlencoded({ extended: false }) ); //Rutas app.use('/login', loginRoute); app.use('/img', imgRoute); app.use('/uploads', uploadsRoute); app.use('/busqueda', routeBusqueda ); app.use('/usuario' , routeUsuario ); app.use('/medico' , routeMedico ); app.use('/hospital' , routeHospital ); //index page app.use( routeIndex ); app.listen( 3000 , () => { console.log('Servidor corriendo: \x1b[34m%s\x1b[0m','online') });<file_sep>const { Schema, model } = require('mongoose'); const imagenSchema = new Schema({ titulo: { type: String, required: [true, 'El titulo es necesario'] }, descripcion: { type: String }, nombreArchivo: { type: String }, path: { type: String }, mimetype: { type: String }, creado: { type: Date, default: Date.now() } }); module.exports = model('Imagen', imagenSchema);<file_sep>const router = require('express').Router(); const bcrypt = require('bcryptjs'); let Usuario = require('../models/usuario'); let jwt = require('jsonwebtoken'); const SEED = require('../condig/config').SEED; let { verificaToken } = require('../middlewares/middleware'); router.get( '/', (req, res) => { let desde = req.query.desde || 0; desde = Number( desde ); let cantidad = 0; let pagina = desde/5; //Validar que sea un numero if( isNaN(desde) ){ return res.status(400) .json({ ok: false, message: 'El parametro no es valido, ingrese un numero' }) } //Asignar la cantidad de documentos o registros Usuario.count({}, (err, count) => { cantidad = count || err; }) if( desde === 0 ){ pagina = 1; } Usuario.find({}, 'nombre email img role') .skip(desde) .limit(5) .exec((err, data) => { if(err){ return res.json({err}) } res.json({ ok: true, usuarios: data, total:cantidad, cantidad: 5, pagina }); if( !res ){ return res.status(500) .json({ ok:false, message: 'Sin datos' }) } }); }); router.post('/', verificaToken, (req, res) => { let body = req.body; let usuarioN = new Usuario({ nombre: body.nombre, email: body.email, pass: <PASSWORD>.hashSync(body.pass, 10), imgpath: body.img }); usuarioN.save( (err, usuarioDB) => { if( err ){ return res.status(400).json({ ok: false, err }) } return res.status(201).json({ usuarioDB }) }); }); router.put('/', (req, res) => { let id = req.body.id; let body = req.body; Usuario.findById(id, (err, UsuarioDB) => { if( err ){ return res.status(500) .json({ ok:false, message: 'Error al buscar usuario', err }) } if( !UsuarioDB ){ return res.status(400) .json({ ok:false, message: 'No existe usuario' }) } UsuarioDB.nombre = body.nombre; UsuarioDB.role = body.role; UsuarioDB.email = body.email; UsuarioDB.save((err, usuarioGuardado) => { if( err ){ return res.status(400) .json({ ok:false, message: 'Error al guardar cambios', err }) } return res.json({ ok:true, usuarioGuardado }) }); }) }); router.delete('/:id', (req, res) => { let id = req.query.id; Usuario.findByIdAndRemove(id, (err, userDeleted) =>{ if(err){ return res.status(500) .json({ ok:false, err }) } if(!userDeleted){ res.status(400) .json({ ok:false, message: 'Error al borrar, id no encontrado' }) } return res.json({ ok: true, userDeleted }) }); }); module.exports = router;<file_sep>const jwt = require('jsonwebtoken'); const SEED = require('../condig/config'); //Middleware de autorizacion exports.verificaToken = ( (req, res, next) => { let token = req.query.token; jwt.verify( token, '<PASSWORD>', ( err, decoded ) => { if( err ){ return res.status(401) .json({ ok: false, message: 'Token incorrecto.', err }) } console.log(decoded) req.usuario = decoded.usuario; next(); }) }); <file_sep>const router = require('express').Router(); const {OAuth2Client} = require('google-auth-library'); const CLIENT_ID = '268116512482-jektv3bs04l4sivnba8g9je0vi3t8a0f.apps.googleusercontent.com'; const Usuario = require('../models/usuario'); const jwt = require('jsonwebtoken'); const bcrypt = require('bcryptjs'); const client = new OAuth2Client(CLIENT_ID); async function verify(token) { const ticket = await client.verifyIdToken({ idToken: token, audience: CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend // Or, if multiple clients access the backend: //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3] }); const payload = ticket.getPayload(); // If request specified a G Suite domain: //const domain = payload['hd']; return { nombre: payload.name, email: payload.email, imgpath: payload.picture, google: true } } router.post('/', (req, res) => { let body = req.body; if( !body ){ return res.status(400) .json({ ok:false, message: 'Ingresa los parametros' }) } Usuario.findOne({ email: body.email }, (err, usuarioDB) => { if( err ){ return res.status(500) .json({ ok: false, err }) } if( !usuarioDB ){ return res.status(400) .json({ ok: false, message: 'Contraseña o usuario incorrecto' }) } //CRear Token let token = jwt.sign({ usuario: usuarioDB }, 'Bzcocho-17-03',{ expiresIn: 14000 }); if( bcrypt.compareSync( body.pass, usuarioDB.pass ) ){ return res.json({ ok:true, usuario: usuarioDB, token }) }else{ return res.status(500) .json({ ok:false, message: 'Contraseña o usuario incorrecto' }) } }); }); router.post('/google', async (req, res) => { let token = req.body.token; let googleuser = await verify( token ) .catch(e => { return res.status(403) .json({ ok:false, message: 'Token no valido', e }) }); Usuario.findOne({ email: googleuser.email }, (err, usuarioDB) => { if(err){ return res.status(500).json({ ok: false }) } if( usuarioDB ){ if( !usuarioDB.google ){ return res.status(400).json({ ok: false, message: 'Cuenta de correo en uso' }) }else{ let token = jwt.sign({ usuario: usuarioDB }, 'Bzcocho-17-03',{ expiresIn: 14000 }); return res.json({ ok: true, usuarioDB, token }) } }else{ let newUsuario = new Usuario({ nombre: googleuser.nombre, email: googleuser.email, imgpath: googleuser.imgpath, google: googleuser.google, pass: '<PASSWORD>' }); newUsuario.save( (err, usuarioGuardado) => { if(err){ return res.status(400).json({ ok: false, err }) } return res.json({ ok: true, usuarioGuardado }) }); } }); }) module.exports = router;<file_sep>var multer = require('multer') var upload = require('../condig/files'); const router = require('express').Router(); const Medico = require('../models/medico'); const Imagen = require('../models/imagen'); const Hospital = require('../models/hospital'); const Usuario = require('../models/usuario'); const path = require('path'); const fs = require('fs-extra'); router.put( '/:tipo/:id', upload, (req, res) => { let file = req.file; let id = req.params.id; let tipo = req.params.tipo; let path = file.filename; subirPorTipo( tipo, id, path, res ) }); let subirPorTipo = async (tipo, id, pathimg, res) => { if( tipo === 'usuario' ){ const usuarioDB = await Usuario.findById(id); let pathDelete = path.join( __dirname + `../../uploads/usuario/`+ usuarioDB.imgpath ); //Si existe el archivo lo eliminamos if( usuarioDB.imgpath && await fs.pathExists( pathDelete ) ){ await fs.unlink( pathDelete ); } usuarioDB.imgpath = pathimg; usuarioDB.save( (err, doc) => { if( err ){ return res.status(500).json({ ok: false, err }) } return res.json({ ok: true, message:'Ok', doc }) }); } if( tipo === 'medico' ){ const medicoDB = await Medico.findById(id); let pathDelete = path.join( __dirname + `../../uploads/medico/`+ medicoDB.imgpath ); //Si existe el archivo lo eliminamos if( await fs.pathExists( pathDelete ) ){ await fs.unlink( pathDelete ); } medicoDB.imgpath = pathimg; medicoDB.save( (err, doc) => { if( err ){ return res.status(500).json({ ok: false, err }) } return res.json({ ok: true, message:'Ok', doc }) }); } if( tipo === 'hospital' ){ const hospitalDB = await Hospital.findById(id); let pathDelete = path.join( __dirname + `../../uploads/hospital/`+ hospitalDB.imgpath ); console.log(pathDelete) //Si existe el archivo lo eliminamos if( await fs.pathExists( pathDelete ) ){ await fs.unlink( pathDelete ); } hospitalDB.imgpath = pathimg; hospitalDB.save( (err, doc) => { if( err ){ return res.status(500).json({ ok: false, err }) } return res.json({ ok: true, message:'Ok', doc }) }); } } module.exports = router;
268c3ff952fd26aa03a262e2dde20d6cdbbc7160
[ "JavaScript" ]
10
JavaScript
ya1k96/backHtal
be96e37c7c38671a7889f5d4572feb583ad4e8b8
cc2e9db434bafa5cdfc70b79ef8d753527e24b6d
refs/heads/master
<repo_name>uehara1962/elocc_frontend<file_sep>/src/App.js import React, { useState, useEffect } from "react"; import "./App.css"; import axios from "axios"; import { MDBDataTable } from "mdbreact"; function App() { const [dados, setDados] = useState([]); useEffect(() => { const data = { columns: [ { label: "Origem", field: "origem", sort: "asc", width: 200 }, { label: "Destino", field: "destino", sort: "asc", width: 200 }, { label: "Empresa", field: "airlineAttr", sort: "asc", width: 200 }, { label: "Dia", field: "dia", sort: "asc", width: 200 }, { label: "Mes", field: "mes", sort: "asc", width: 200 }, { label: "Preço", field: "preco", sort: "asc", width: 200 } ] // rows: [] }; axios.get("http://localhost:3333/").then( // res.data.forEach(() => { // data // }) res => { res.data.shift(); const objData = { rows: [...res.data] }; const objData1 = Object.assign(data, objData); setDados(objData1); } ); }, []); return ( <> {/* {JSON.stringify(dados)} */} <MDBDataTable striped bordered small data={dados} /> </> ); } export default App;
ca8779e6de6799866713ead642ce7d9a574522fb
[ "JavaScript" ]
1
JavaScript
uehara1962/elocc_frontend
fb4ceefa0ce51105bd34a236509ae682c2ea5ef7
bbdd7da1a2b7bf601733effcd37b1049b8c9b3e5
refs/heads/main
<file_sep>package Part_3; /** * Represents things that go inside separation bins. */ public class Thing { private String type; private Material material; private Material material2 = Material.UNDEFINED; public Thing(String type, String material, String material2) { this.type = type; this.material = Material.get(material); this.material2 = Material.get(material2); } public Thing(String type, String material) { this.type = type; this.material = Material.get(material); } public String getType() { return type; } public void setType(String type) { this.type = type; } public Material getMaterial() { return material; } public void setMaterial(String material) { this.material = Material.get(material); } public Material getMaterial2() { return material2; } public void setMaterial2(String material2) { this.material2 = Material.get(material2); } } <file_sep>package Part_1; import org.junit.Test; import static org.junit.Assert.*; /** * Class for testing solution class from package Part_1. Methods ending in * "Solution1" test first method, methods ending with "Solution2" are * identical, but test the second method in the class. */ public class SolutionTest { private Solution sol = new Solution(); @Test public void isASuffixSolution1() { assertTrue(sol.solution("abcd", "cd")); } @Test public void isNotASuffixSingleCharacterSolution1() { assertFalse(sol.solution("abcd", "e")); } @Test public void isNotSuffixMultipleCharactersSolution1() { assertFalse(sol.solution("abcd", "ecg")); } @Test public void isNotSuffixButSubstringSolution1() { assertFalse(sol.solution("pourtyg", "urty")); } @Test public void repeatedSubstringAndSuffixSolution1() { assertTrue(sol.solution("alenoaledoale", "ale")); } @Test public void suffixIsEmptySolution1() { assertTrue(sol.solution("abcd", "")); } @Test public void stringIsEmptySolution1() { assertFalse(sol.solution("", "bc")); } @Test public void stringAndSuffixAreEmptySolution1() { assertTrue(sol.solution("", "")); } @Test public void stringsAreEqualSolution1() { assertTrue(sol.solution("abcd", "abcd")); } @Test public void suffixDiffersInLastCharacterSolution1() { assertFalse(sol.solution("abcd", "bce")); } @Test public void suffixIsLongerThanStringSolution1() { assertFalse(sol.solution("abcd", "abcde")); } @Test public void suffixIsNullSolution1() { assertFalse(sol.solution("abcd", null)); } @Test public void stringIsNullSolution1() { assertFalse(sol.solution(null, "bc")); } // Tests for solution2 @Test public void isASuffixSolution2() { assertTrue(sol.solution2("abcd", "cd")); } @Test public void isNotASuffixSingleCharacterSolution2() { assertFalse(sol.solution2("abcd", "e")); } @Test public void isNotSuffixMultipleCharactersSolution2() { assertFalse(sol.solution2("abcd", "ecg")); } @Test public void isNotSuffixButSubstringSolution2() { assertFalse(sol.solution2("pourtyg", "urty")); } @Test public void repeatedSubstringAndSuffixSolution2() { assertTrue(sol.solution2("alenoaledoale", "ale")); } @Test public void suffixIsEmptySolution2() { assertTrue(sol.solution2("abcd", "")); } @Test public void stringIsEmptySolution2() { assertFalse(sol.solution2("", "bc")); } @Test public void stringAndSuffixAreEmptySolution2() { assertTrue(sol.solution2("", "")); } @Test public void stringsAreEqualSolution2() { assertTrue(sol.solution2("abcd", "abcd")); } @Test public void suffixDiffersInLastCharacterSolution2() { assertFalse(sol.solution2("abcd", "bce")); } @Test public void suffixIsLongerThanStringSolution2() { assertFalse(sol.solution2("abcd", "abcde")); } @Test public void suffixIsNullSolution2() { assertFalse(sol.solution2("abcd", null)); } @Test public void stringIsNullSolution2() { assertFalse(sol.solution2(null, "bc")); } } <file_sep># ProjectOKsystem Includes three parts given in the assignment. <file_sep>package Part_2; import java.time.DayOfWeek; import java.time.LocalDate; public class YearInfo { /** * Get the number of Friday 13 days in a year. * @param year in which year we want to find unlucky days * @return number of unlucky days */ public int getUnluckyDaysInAYear(int year) { int unluckyDays = 0; LocalDate dayInAYear; for (int month = 1; month <= 12; month++) { dayInAYear = LocalDate.of(year, month, 13); DayOfWeek day = dayInAYear.getDayOfWeek(); if (day.getValue() == 5) { unluckyDays++; } } return unluckyDays; } } <file_sep>package Part_1; public class Solution { /** * Determines if String str2 is a suffix of String str1. * Returns false if one of them is null. * @param str1 given string * @param str2 possible suffix * @return if str2 is a suffix of str1 */ public boolean solution(String str1, String str2) { if (str1 == null || str2 == null) return false; return str1.endsWith(str2); } public boolean solution2(String str1, String str2) { if (str1 == null || str2 == null) return false; if (str2.length() > str1.length()) return false; int startIdx = str1.length() - str2.length(); for (int i = 0; i < str2.length(); i++) { if (str2.charAt(i) != str1.charAt(startIdx + i)) return false; } return true; } }
a819d7b05f9704799ab3b38c0c6dbfec08b0f7f0
[ "Markdown", "Java" ]
5
Java
anna-petrakova/ProjectOKsystem
c8f1be493c52816d34ab2cc11a3143bc547fee9f
406d26c1ef955f7cf2dc8c4bde51ce0b69c31070
refs/heads/master
<repo_name>CSpector/Computer-Science-II<file_sep>/lightsoutgame/LightsOut.java package lightsoutgame; /** * Controls the exceptions and the pression on the game board * @author <NAME> * @author <NAME> */ class LightsOut { /** Is used in the LightsOut method to set the size of the board */ private int size; /** Is used in the LightsOut method to set the size of the boolean array */ private boolean[][] grid; /** Initializes the size of the board and the size of the grid @param gSize How big the grid is going to be */ public LightsOut(int gSize) { if (gSize == 0) { } size = gSize; grid = new boolean[gSize][gSize]; } /** @return the size */ public int getSize() { return size; } /** * Records the press of a square * @param row The row of the pressed square * @param col The column of the pressed square */ public void press(int row, int col) { grid[row][col] = !grid[row][col]; toggle(row,col); } /** * Checks to see if a square is already lit * @param row Row of the square * @param col Column of the square * @return Boolean returns true if lit, False if not lit */ public boolean isLit(int row, int col) { if (grid[row][col] == true) { return true; } else { return false; } } /** * Forces a square to become lit when pressed * @param row Row of the square that needs to be lit * @param col Column of the square that needs to be lit * @param value True or False */ public void forceLit(int row, int col, boolean value) { grid[row][col] = value; grid[row][col] = !grid[row][col]; } /** * Asks for forgiveness when a square is pressed * @param row Row of the square toggled * @param col Column of the square toggled */ private void toggle(int row, int col) { try { grid[row + 1][col] = !grid[row+1][col]; } catch(ArrayIndexOutOfBoundsException ex) { } try { grid[row-1][col] = !grid[row-1][col]; } catch(ArrayIndexOutOfBoundsException ex) { } try { grid[row][col+1] = !grid[row][col+1]; } catch(ArrayIndexOutOfBoundsException ex) { } try { grid[row][col-1] = !grid[row][col-1]; } catch(ArrayIndexOutOfBoundsException ex) { } } }<file_sep>/lightsoutgame/UnsupportedLightsOutFileException.java package lightsoutgame; /** * Class for the Unsupported Lights Out File Exception * @author cbs262 */ public class UnsupportedLightsOutFileException extends Exception { } <file_sep>/rpg/Arena.java package rpg; import java.util.ArrayList; import java.util.Random; class Arena { public ArrayList<Combatant> combatants = new ArrayList(); public Arena() { } public void add(Combatant contestant) { combatants.add(contestant); } public void playRound() { } public String getDescription() { } public Combatant getWinner() { } // Private private void checkVictor() { } } <file_sep>/Sudoku.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sudokuplayer; /** * * @author <NAME> */ public class Sudoku { // Initalize a 9X9 Array of characters char[][] sudoku = new char[9][9]; public Sudoku(String starting_configuartion) { int xCoord = 0; int yCoord = 0; // < 90 because of the \n at the end of each statement for (int index = 0; index < 90; index++) { if( starting_configuartion.charAt(index) != '\n') { // Iterates through every sqaure and assigns the value sudoku[xCoord / 9][yCoord % 9] = starting_configuartion.charAt(index); xCoord++; yCoord++; } } } // Get sqaure method that return the row and column public char getSquare(int row, int col) { return sudoku[row][col]; } // Set sqaure method that assigns the value inputted to the sqaure public void setSquare(int row, int col, char value) { sudoku[row][col] = value; } // Method that sees that the row is valid public boolean isRowValid(int row) { int val = 0; for (int i = 0; i < 8; i++) { if(sudoku[row][i] != ' ') { val = sudoku[row][i]; } for(int j = i+1; j < 9; j++) { if(val == sudoku[row][j]) { return false; } } } return true; } // Searches through each row to make sure that all rows are valid public boolean allRowsValid() { for(int i = 0; i < 9; i++) { if(!isRowValid(i)) { return false; } } return true; } // Checks if an individual column is valid public boolean isColumnValid(int col) { int val = 0; for (int i = 0; i < 8; i++) { if(sudoku[i][col] != ' ') { val = sudoku[i][col]; } for (int j = i + 1; j < 9; j++) { if (val == sudoku[j][col]) { return false; } } } return true; } // Seaches the boards columns to make sure that all inputs are valid public boolean allColValid() { for(int i = 0; i < 9; i++) { if(!isColumnValid(i)) { return false; } } return true; } // Checks to see if the whole board is valid public boolean isValid(){ return allRowsValid() && allColValid(); } // Unable to get this method to work correctly /* public boolean isBoxValid() { char val = 0; int j = 0; for (int i = 0; i < 9; i+=3 ) { for(int k = 0; k < 3; k++) { if(sudoku[k][j] != ' ') { val = sudoku[k][j]; } if(i % 3 == 0 && j %3 == 0) { j++; } if(sudoku[k][j] == val) { return false; } j++; if(j > ) } } return true; } */ // Checks to see if the whole board has been solved public boolean isSolved() { for(int i = 0; i < 9; i ++) { for (int j = 0; j < 9; j++) { if(sudoku[i][j] == ' ') { return false; } } } return allRowsValid() && allColValid(); } } <file_sep>/rpg/Beserker.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rpg; import java.util.Random; import rpg.Arena; /** * * @author cbs262 */ public class Berserker extends Combatant { public Berserker() { health = 35; damageType = 1; } public void takeDamage(int damage, int type) { int toTake; if (type == 2) { toTake = 2*damage; } if (type == 3) { toTake = (damage/2); } else { toTake = damage; } super.setHealth(toTake); } public void doDamage(Combatant[] combatants) { int damage = 20; Random rand = new Random(); int target = rand.nextInt(6); combatants[target].takeDamage(damage, damageType); } }
1e8209616cad69c84925bc7c38332d12628d0dc5
[ "Java" ]
5
Java
CSpector/Computer-Science-II
994ceabe3161af60edbcb1e3196cf519ef3edb45
ab94055d746881271a4748f69666caf6abd7feab
refs/heads/master
<file_sep>print("<NAME>ado 0907-21-15261") print("Ingresa tu nombre") nombre=input() print("Bienvenido " + nombre + "este programa calcula el 15% y se lo resta al numero que indiques") numero=int(input("Ingresa el numero:")) print("Descuento del 15% su total es:", numero-(numero*15)/100)
33a3b2243002e52e41669809013542ae8d7ffc9c
[ "Python" ]
1
Python
JhonatanAlva/ExamenAlgoritmos1
90274fc9f2007dd58a63f9e5328b644247f91575
8a3f9f621bd831edb4331efd10363c252f4bea12
refs/heads/master
<repo_name>mahamniaz/TicTacToe<file_sep>/computer.h #ifndef COMPUTER_H #define COMPUTER_H #include <iostream> // allows program to output data to th using namespace std; class computer{ private: int pos; public: // memeber functions. void AI(grid& G); }; #endif <file_sep>/driver.h #ifndef DRIVER_H #define DRIVER_H #include <iostream> // allows program to output data to th #include "grid.h" #include "computer.h" //#include "driver.h" using namespace std; class driver{ private: int pos; int player; grid G; computer C; public: void Human_turn(); void AI_turn(); void Game_play(); string m1; string p1; }; #endif <file_sep>/problem.cpp #include <cstdlib> #include <iostream> #include "grid.h" #include "computer.h" #include "driver.h" using namespace std; int main() { int ans; driver D;// d is a variable of type driver cout<<"Welcome:"<<endl<<"1) New Game"<<endl<<"2) Load Game"<<endl; cin>>ans; switch (ans) { case 1: D.Game_play(); break; case 2: break; } // to prevent disappearing windows char c; // declaring a char variable cout<<"enter a character to exit..."; cin>>c; // capturing the input return 0; // imdicate that program ended successfully } //end function main <file_sep>/grid.h #ifndef GRID_H #define GRID_H #include <iostream> // allows program to output data to th using namespace std; class grid{ private: char grid_array[9]; public: // memeber function void initialize(); void add(int pos,int player); void display(); void update(int pos); char get(int pos); int check_win(); }; #endif <file_sep>/computer.cpp #include <iostream> // allows program to output data to th #include "grid.h" #include "computer.h" #include <ctime> using namespace std; void computer::AI(grid& G) { // generates random position for the computer. gives computer its turn srand ( time (NULL) ); //seeding rand() do { pos = (rand() % 9)+1; }while(G.get(pos) != '_'); G.update(pos); } <file_sep>/grid.cpp #include <iostream> // allows program to output data to the screen #include "grid.h" using namespace std; void grid::initialize() { //initaializes the array to blanks for (int i(0); i < 9; i++) {grid_array[i] = '_';} } void grid::add(int pos,int player) { // adds a 'o' for player one and a 'x' for // player two at the position pos for player = player (pos and player // arguments of this function. if (grid_array[pos-1] != '_') { cout<<"Error: position already filled. enter another position."<<endl; } else { if (player==1) {grid_array[pos - 1] = 'o';} else if (player==2) {grid_array[pos - 1] = 'x';} } } void grid::update(int pos) //updates the position for the computer { grid_array[pos-1] = 'x'; } void grid::display() { // displayes the grid on the screen cout<<grid_array[0]<<" " <<grid_array[1]<<" "<<grid_array[2]<<endl; cout<<grid_array[3]<<" " <<grid_array[4]<<" "<<grid_array[5]<<endl; cout<<grid_array[6]<<" " <<grid_array[7]<<" "<<grid_array[8]<<endl; } char grid::get(int pos) // gets the character of grid at position pos { return(grid_array[pos-1]); } int grid::check_win() { // checks wether one of the players has won or // if it is a draw. int count(0); //char x; if((grid_array[0]=='o' && grid_array[1]== 'o' && grid_array[2] == 'o')||(grid_array[3]=='o' && grid_array[4]== 'o' && grid_array[5] == 'o')||(grid_array[6]=='o' && grid_array[7]== 'o' && grid_array[8] == 'o')||(grid_array[0]=='o' && grid_array[4]== 'o' && grid_array[8] == 'o')||(grid_array[2]=='o' && grid_array[4]== 'o' && grid_array[6] == 'o')||(grid_array[0]=='o' && grid_array[3]== 'o' && grid_array[6] == 'o')||(grid_array[1]=='o' && grid_array[4]== 'o' && grid_array[7] == 'o')||(grid_array[2]=='o' && grid_array[5]== 'o' && grid_array[8] == 'o')) {cout<<"Player 1 wins "; return(1);} if((grid_array[0]=='x' && grid_array[1]== 'x' && grid_array[2] == 'x')||(grid_array[3]=='x' && grid_array[4]== 'x' && grid_array[5] == 'x')||(grid_array[6]=='x' && grid_array[7]== 'x' && grid_array[8] == 'x')||(grid_array[0]=='x' && grid_array[4]== 'x' && grid_array[8] == 'x')||(grid_array[2]=='x' && grid_array[4]== 'x' && grid_array[6] == 'x')||(grid_array[0]=='x' && grid_array[3]== 'x' && grid_array[6] == 'x')||(grid_array[1]=='x' && grid_array[4]== 'x' && grid_array[7] == 'x')||(grid_array[2]=='x' && grid_array[5]== 'x' && grid_array[8] == 'x')) {cout<<"player 2 wins "; return(1);} for (int i(0); i < 9; i++) {if( grid_array[i] != '_') count++;} if(count == 9) {cout<<"DRAW"; return(1);} }
dd338dd12a025334163ead1c08b7eb805a0c6e78
[ "C++" ]
6
C++
mahamniaz/TicTacToe
112c3cbaa8e42be95ef365482215f891571efddd
b89f0a013df049badf2551393641c53dd9bad77b
refs/heads/master
<file_sep>package models; import javax.persistence.*; import java.util.ArrayList; import java.util.List; /** * Created by Alan on 28/11/2014. */ @Entity public class Semana { @Id @GeneratedValue private Long id; private String semana; @OneToMany @JoinTable private List<Meta> metas; public Semana() { this.metas = new ArrayList<Meta>(); } public Semana(String semana) { this.semana = semana; } public String getSemana() { return semana; } public void setSemana(String semana) { this.semana = semana; } public List<Meta> getMetas() { return metas; } public void setMetas(List<Meta> metas) { this.metas = metas; } } <file_sep> import static org.fest.assertions.Assertions.*; import static play.test.Helpers.callAction; import static play.test.Helpers.fakeRequest; import controllers.Application; import models.Meta; import models.dao.GenericDAO; import org.junit.Test; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Alan on 21/11/2014. */ public class MinhasMetasTest extends AbstractTest { private GenericDAO dao = new GenericDAO(); @Test public void deveIniciarSemMetas() throws Exception { List<Meta> metas = dao.findAllByClassName(Meta.class.getName()); assertThat(metas).isEmpty(); } @Test public void deveSalvarMetaNoBD() { Meta meta = new Meta("Estudar PLP", "Baixa", "1"); dao.persist(meta); List<Meta> metas = dao.findAllByClassName(Meta.class.getName()); assertThat(metas.size()).isEqualTo(1); } @Test public void deveSalvarMetaNaSemana1() throws Exception { Meta meta = new Meta("Estudar PLP", "Baixa", "1"); dao.persist(meta); assertThat(meta.getSemana()).isEqualTo("1"); } @Test public void deveSalvarMetaNaSemana2() throws Exception { Meta meta = new Meta("Estudar Lógica", "Baixa", "2"); dao.persist(meta); assertThat(meta.getSemana()).isEqualTo("2"); } @Test public void deveRemoverMetaDoBD() throws Exception { Map<String, String> form = new HashMap<>(); form.put("descricao", "Estudar SI1"); form.put("prioridades", "1"); form.put("semanas", "1"); callAction(controllers.routes.ref.Application.criaMeta(), fakeRequest().withFormUrlEncodedBody(form)); List<Meta> metas = dao.findAllByClassName(Meta.class.getName()); assertThat(metas.size()).isEqualTo(1); callAction(controllers.routes.ref.Application.deletaMeta(metas.get(0).getId()), fakeRequest()); metas = dao.findAllByClassName(Meta.class.getName()); assertThat(metas.size()).isEqualTo(0); } @Test public void deveDestacarMeta() throws Exception { Map<String, String> form = new HashMap<>(); form.put("descricao", "Estudar SI1"); form.put("prioridades", "1"); form.put("semanas", "1"); callAction(controllers.routes.ref.Application.criaMeta(), fakeRequest().withFormUrlEncodedBody(form)); List<Meta> metas = dao.findAllByClassName(Meta.class.getName()); assertThat(metas.get(0).alcancada()).isFalse(); metas.get(0).setAlcancada(); assertThat(metas.get(0).alcancada()).isTrue(); } } <file_sep>Lab2 de SI1. CRUD de metas.
925a57bf3a71754e9a5fab206832625dfd32a66e
[ "Markdown", "Java" ]
3
Java
AlanCintra/si1-lab2-parte2
65b111a7a5f6a9df4d5bf2272bdb375aa66cab08
0e51f73f0035240f412102f1a503b2a18f621e99
refs/heads/master
<repo_name>KiJou/UnityCommon<file_sep>/Assets/Scripts/TestSerializableMapDrawer.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityCommon; public class TestSerializableMapDrawer : MonoBehaviour { public SerializableLiteralStringMap Map; } <file_sep>/Assets/UnityCommon/Runtime/Tween/ColorTween.cs using System; using UnityEngine; namespace UnityCommon { /// <summary> /// Represents available tween modes for <see cref="Color"/> values. /// </summary> public enum ColorTweenMode { All, RGB, Alpha } public readonly struct ColorTween : ITweenValue { public EasingType EasingType { get; } public float TweenDuration { get; } public bool TimeScaleIgnored { get; } public bool TargetValid => onTween != null && (!targetProvided || target); private readonly Color startColor; private readonly Color targetColor; private readonly ColorTweenMode tweenMode; private readonly Action<Color> onTween; private readonly EasingFunction easingFunction; private readonly UnityEngine.Object target; private readonly bool targetProvided; public ColorTween (Color from, Color to, ColorTweenMode mode, float time, Action<Color> onTween, bool ignoreTimeScale = false, EasingType easingType = default, UnityEngine.Object target = default) { startColor = from; targetColor = to; tweenMode = mode; TweenDuration = time; EasingType = easingType; TimeScaleIgnored = ignoreTimeScale; this.onTween = onTween; targetProvided = this.target = target; easingFunction = EasingType.GetEasingFunction(); } public void TweenValue (float tweenPercent) { if (!TargetValid) return; var newColor = default(Color); newColor.r = tweenMode == ColorTweenMode.Alpha ? startColor.r : easingFunction(startColor.r, targetColor.r, tweenPercent); newColor.g = tweenMode == ColorTweenMode.Alpha ? startColor.g : easingFunction(startColor.g, targetColor.g, tweenPercent); newColor.b = tweenMode == ColorTweenMode.Alpha ? startColor.b : easingFunction(startColor.b, targetColor.b, tweenPercent); newColor.a = tweenMode == ColorTweenMode.RGB ? startColor.a : easingFunction(startColor.a, targetColor.a, tweenPercent); onTween.Invoke(newColor); } } } <file_sep>/Assets/Scripts/TestAsync.cs using UniRx.Async; using UnityCommon; using UnityEngine; public class TestAsync : MonoBehaviour { public class EternalYeild : CustomYieldInstruction { public override bool keepWaiting => Application.isPlaying; } private void Start () { EndOfFrame(); CustomYeild(); } private async void EndOfFrame () { while (Application.isPlaying) await AsyncUtils.WaitEndOfFrame; } private async void CustomYeild () { while (Application.isPlaying) await UniTask.WaitWhile(() => Time.time % 2 == 0); } } <file_sep>/Assets/UnityCommon/Runtime/ScriptableUI/ScriptableGridSlot.cs using UnityEngine; using UnityEngine.EventSystems; namespace UnityCommon { [RequireComponent(typeof(CanvasGroup)), RequireComponent(typeof(UnityEngine.UI.Button))] public class ScriptableGridSlot : ScriptableButton, IPointerEnterHandler, IPointerExitHandler, ISelectHandler, IDeselectHandler { public class Constructor<TSlot> where TSlot : ScriptableGridSlot { public readonly TSlot ConstructedSlot; public Constructor (TSlot prototype, string id, OnClicked onClicked = null) { ConstructedSlot = Instantiate(prototype); ConstructedSlot.Id = id; ConstructedSlot.onClickedAction = onClicked; } } /// <summary> /// Action to invoke when the slot body is clicked by the user. /// </summary> /// <param name="slotId">ID of the clicked slot.</param> public delegate void OnClicked (string slotId); public string Id { get; private set; } public int NumberInGrid => transform.GetSiblingIndex() + 1; [SerializeField] private float hoverOpacityFade = .25f; private Tweener<FloatTween> fadeTweener; private OnClicked onClickedAction; protected override void Awake () { base.Awake(); fadeTweener = new Tweener<FloatTween>(); } protected override void Start () { base.Start(); SetOpacity(1 - hoverOpacityFade); } public virtual void OnPointerEnter (PointerEventData eventData) => FadeInSlot(); public virtual void OnPointerExit (PointerEventData eventData) => FadeOutSlot(); public virtual void OnSelect (BaseEventData eventData) => FadeInSlot(); public virtual void OnDeselect (BaseEventData eventData) => FadeOutSlot(); protected override void OnButtonClick () { base.OnButtonClick(); onClickedAction?.Invoke(Id); } protected virtual void FadeInSlot () { if (fadeTweener.Running) fadeTweener.CompleteInstantly(); var tween = new FloatTween(Opacity, 1f, FadeTime, SetOpacity, true, target: this); fadeTweener.Run(tween); } protected virtual void FadeOutSlot () { if (fadeTweener.Running) fadeTweener.CompleteInstantly(); var tween = new FloatTween(Opacity, 1f - hoverOpacityFade, FadeTime, SetOpacity, true, target: this); fadeTweener.Run(tween); } } } <file_sep>/Assets/Editor/EditorTestScript.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; public class EditorTestScript { //[MenuItem("Test/Install Shader")] private static void InstallShader () { //BlendModes.ExtensionsManager.InstallShaderExtension("UIDefault"); } } <file_sep>/Assets/UnityCommon/Runtime/Utilities/EventUtils.cs using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; namespace UnityCommon { public static class EventUtils { /// <summary> /// Get top-most hovered gameobject. /// </summary> public static GameObject GetHoveredGameObject (this EventSystem eventSystem) { #if ENABLE_LEGACY_INPUT_MANAGER var pointerEventData = new PointerEventData(EventSystem.current); pointerEventData.position = Input.touchCount > 0 ? (Vector3)Input.GetTouch(0).position : Input.mousePosition; var raycastResults = new List<RaycastResult>(); EventSystem.current.RaycastAll(pointerEventData, raycastResults); if (raycastResults.Count > 0) return raycastResults[0].gameObject; else return null; #else Debug.LogWarning("`UnityCommon.GetHoveredGameObject` requires legacy input system, which is disabled; the method will always return null."); return null; #endif } public static void SafeInvoke (this Action action) { if (action != null) action.Invoke(); } public static void SafeInvoke<T0> (this Action<T0> action, T0 arg0) { if (action != null) action.Invoke(arg0); } public static void SafeInvoke<T0, T1> (this Action<T0, T1> action, T0 arg0, T1 arg1) { if (action != null) action.Invoke(arg0, arg1); } public static void SafeInvoke<T0, T1, T2> (this Action<T0, T1, T2> action, T0 arg0, T1 arg1, T2 arg2) { if (action != null) action.Invoke(arg0, arg1, arg2); } } } <file_sep>/Assets/UnityCommon/Runtime/Tween/FloatTween.cs using System; namespace UnityCommon { public readonly struct FloatTween : ITweenValue { public float TweenDuration { get; } public EasingType EasingType { get; } public bool TimeScaleIgnored { get; } public bool TargetValid => onTween != null && (!targetProvided || target); private readonly float startValue; private readonly float targetValue; private readonly Action<float> onTween; private readonly EasingFunction easingFunction; private readonly UnityEngine.Object target; private readonly bool targetProvided; public FloatTween (float from, float to, float time, Action<float> onTween, bool ignoreTimeScale = false, EasingType easingType = default, UnityEngine.Object target = default) { startValue = from; targetValue = to; TweenDuration = time; EasingType = easingType; TimeScaleIgnored = ignoreTimeScale; this.onTween = onTween; targetProvided = this.target = target; easingFunction = EasingType.GetEasingFunction(); } public void TweenValue (float tweenPercent) { if (!TargetValid) return; var newValue = easingFunction(startValue, targetValue, tweenPercent); onTween.Invoke(newValue); } } } <file_sep>/Assets/UnityCommon/Runtime/ResourceProvider/ProjectFolderLocator.cs using System.Collections.Generic; using System.Linq; using UniRx.Async; namespace UnityCommon { public class ProjectFolderLocator : LocateFoldersRunner { public readonly string RootPath; private readonly ProjectResources projectResources; public ProjectFolderLocator (IResourceProvider provider, string rootPath, string resourcesPath, ProjectResources projectResources) : base (provider, resourcesPath ?? string.Empty) { RootPath = rootPath; this.projectResources = projectResources; } public override UniTask RunAsync () { var locatedFolders = LocateProjectFolders(RootPath, Path, projectResources); SetResult(locatedFolders); return UniTask.CompletedTask; } public static List<Folder> LocateProjectFolders (string rootPath, string resourcesPath, ProjectResources projectResources) { var path = string.IsNullOrEmpty(rootPath) ? resourcesPath : string.IsNullOrEmpty(resourcesPath) ? rootPath : $"{rootPath}/{resourcesPath}"; return projectResources.ResourcePaths.LocateFolderPathsAtFolder(path) .Select(p => new Folder(string.IsNullOrEmpty(rootPath) ? p : p.GetAfterFirst(rootPath + "/"))).ToList(); } } } <file_sep>/Assets/UnityCommon/Runtime/Utilities/AsyncUtils.cs using UniRx.Async; namespace UnityCommon { public static class AsyncUtils { public static YieldAwaitable WaitEndOfFrame => UniTask.Yield(PlayerLoopTiming.PostLateUpdate); public static UniTask.Awaiter GetAwaiter (this UniTask? task) => task.HasValue ? task.Value.GetAwaiter() : UniTask.CompletedTask.GetAwaiter(); public static UniTask<T>.Awaiter GetAwaiter<T> (this UniTask<T>? task) => task.HasValue ? task.Value.GetAwaiter() : UniTask.FromResult<T>(default).GetAwaiter(); } }
ec452ecb041e320bccc9f54f10f200c72f588ff6
[ "C#" ]
9
C#
KiJou/UnityCommon
78dd9fdfae5498db43bc8044277a6a22ddc91d5e
e19fb0b2dfd0bccab4be5eaef6a3decfd524903c
refs/heads/master
<repo_name>felipework/aulazend<file_sep>/application/forms/AulaZend.php <?php class Application_Form_AulaZend extends Zend_Form { public function __construct($options = null) { parent::__construct($options); } public function setAllDecorators() { $elements = $this->getElements(); if ($elements) { foreach ($elements as $e) { $e->removeDecorator('HtmlTag'); $e->addDecorator(array('wrapper' => 'HtmlTag'), array('tag' => 'div', 'class' => 'form-group col-sm-3')); $e->addDecorator('HtmlTag', array('tag' => 'div')); if ($e->getType() != 'Zend_Form_Element_Submit') { $e->addDecorator('Label', array('tag' => null)); } } } return $this; } } <file_sep>/application/controllers/IndexController.php <?php class IndexController extends Zend_Controller_Action { public function init() { $this->table = new Application_Model_DbTable_Cliente(); $this->form = new Application_Form_Cliente(); $this->model = new Application_Model_Cliente(); } public function indexAction() { $params = $this->getRequest()->getParams(); $select = $this->table->selectCliente(); if (isset($params['nome'])) { $select->where('nome LIKE ?', '%'.$params['nome'].'%'); } if (isset($params['telefone'])) { $select->where('telefone LIKE ?', '%'.$params['telefone'].'%'); } $this->view->form = $this->form->elementsForFilter(); $this->view->clientes = $this->table->getDefaultAdapter() ->fetchAll($select); } public function saveAction() { $params = $this->getRequest()->getParams(); $id = $this->getRequest()->getParam('id'); $data = ''; if ($this->getRequest()->isPost() && $this->form->isValid($params)) { $id = $this->model->save($this->form->getValues()); } if ($id) { $data = $this->table->find($id)->current()->toArray(); } if ($data) { $this->form->populate($data); } $this->view->form = $this->form; } public function deleteAction() { $id = $this->getRequest()->getParam('id'); if ($id) { $this->table->delete(['id = ?' => $id]); } $this->redirect('index'); } } <file_sep>/application/models/DbTable/Cliente.php <?php class Application_Model_DbTable_Cliente extends Zend_Db_Table { protected $_name = "cliente"; public function selectCliente() { $select = $this->select() ->from('cliente'); return $select; } }<file_sep>/application/forms/Cliente.php <?php class Application_Form_Cliente extends Application_Form_AulaZend { public function init() { $this->setMethod('POST'); $this->setAttrib('id', 'form-cliente'); $element = (new Zend_Form_Element_Text('nome'))->setLabel('Nome:'); $element->setAttrib('class', 'form-control'); $this->addElement($element); $this->addElement('hidden', 'id'); $this->addElement('text', 'telefone', ['label' => 'Telefone:']); $this->addElement('text', 'endereco', ['label' => 'Endereço:']); $this->addElement('submit', 'Enviar'); $this->setAllDecorators(); } public function elementsForFilter() { $this->removeElement('telefone'); $this->removeElement('endereco'); $this->Enviar->setValue('Salvar'); return $this; } } <file_sep>/application/models/Cliente.php <?php class Application_Model_Cliente { public function save($data) { $table = new Application_Model_DbTable_Cliente(); if ($data['id']) { $table->update($data, ['id = ?' => $data['id']]); return $data['id']; } if (!$data['id'] || !isset($data['id'])) { return $table->insert($data); } return false; } }
c60f87b84d0b1daf8641db63f260c6de8f609ede
[ "PHP" ]
5
PHP
felipework/aulazend
d5f97076935d213024f470d7ca5106c2b6dd2185
807a91a7c2d4fc87182e9282064169f455a5941a
refs/heads/master
<file_sep>package CabInvoiceGenerator; public class CabInvoiceService { private static final double MINIMUM_COST_PER_KM = 10; private static final int MIN_COST_PER_TIME = 1; private static final double MIN_TOTAL_FARE = 5; private RideRepository rideRepository; public CabInvoiceService() { this.rideRepository = new RideRepository(); } public double calculateFare(double distance, int time) { double totalFare = (distance * MINIMUM_COST_PER_KM) + (time * MIN_COST_PER_TIME); return Math.max(totalFare, MIN_TOTAL_FARE); } public InvoiceSummary calculateFare(Ride[] rides) { double totalFare = 0; for (Ride ride : rides) { totalFare = totalFare + calculateFare(ride.getDistance(), ride.getTime()); } ; return new InvoiceSummary(rides.length, totalFare); } public void addRides(String userId, Ride[] rides) { rideRepository.addRides(userId, rides); ; } public InvoiceSummary getInvoiceSummary(String userId) { return this.calculateFare(rideRepository.getRides(userId)); } public void setRideRepository(RideRepository rideRepository) { this.rideRepository = rideRepository; } } <file_sep>package CabInvoiceGenerator; public class InvoiceSummary { private double totalFare; private int rides; private double averageFare; public InvoiceSummary(int numOfRides, double totalFare) { this.totalFare = totalFare; this.rides = numOfRides; this.averageFare = totalFare/numOfRides; } @Override public boolean equals(Object o) { if (this ==o) return true; if (o == null || getClass() != o.getClass()) return false; InvoiceSummary that = (InvoiceSummary) o; return rides == that.rides && Double.compare(that.totalFare, totalFare) == 0 && Double.compare(that.averageFare, averageFare) == 0; } } <file_sep>package CabInvoiceGenerator; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class InvoiceServiceTest { Ride[] rides = null; CabInvoiceService invoiceService = null; InvoiceSummary expectedSummary = null; private RideRepository rideRepository = null; @Before public void setUp() throws Exception { invoiceService = new CabInvoiceService(); rideRepository = new RideRepository(); invoiceService.setRideRepository(rideRepository); rides = new Ride[] { new Ride(CabRide.NORMAL, 2.0, 5), new Ride(CabRide.PREMIUM, 0.1, 1) }; expectedSummary = new InvoiceSummary(2, 45); } @Test public void givenDistanceAndTime_ShouldReturnTotalFare() { double distance = 2.0; int time = 5; double fare = invoiceService.calculateFare(distance, time); Assert.assertEquals(25, fare, 0.0); } @Test public void givenLessDistanceAndTime_ShouldReturnMinFare() { double distance = 0.1; int time = 1; double fare = invoiceService.calculateFare(distance, time); Assert.assertEquals(5, fare, 0.0); } @Test public void givenMultipleRides_shouldReturnInvoiceSummary() { InvoiceSummary summary = invoiceService.calculateFare(rides); InvoiceSummary expectedSummary = new InvoiceSummary(2, 30.0); Assert.assertEquals(expectedSummary, summary); } @Test public void givenUserIdAndRides_shouldReturnInvoiceSummary() { String userId = "<EMAIL>"; invoiceService.addRides(userId, rides); InvoiceSummary summary = invoiceService.getInvoiceSummary(userId); InvoiceSummary expectedSummary = new InvoiceSummary(2, 30.0); Assert.assertEquals(expectedSummary, summary); } }
f846e43bc322e7609b59bdfc08e26fca02a2f5d5
[ "Java" ]
3
Java
jagriti04/Cab-Invoice-Generator
c2d33daee444d2b8c97e154ec0a098f3d15ececd
7891697cc858feac9322009d615fbe61f9f6659b
refs/heads/master
<repo_name>sirmmo/Android-OsCar<file_sep>/OsCarProject/settings.gradle include ':OsCar' <file_sep>/OsCarProject/OsCar/src/main/java/it/mmo/oscar/Collector.java package it.mmo.oscar; /** * Created by admin on 27/11/13. */ public class Collector { } <file_sep>/README.md Android-OsCar ============= Open Source Car Tracker - App and web platform to track a car with sensor support
b8f236ab97459ffff8bf0873a10eb9dffdf79607
[ "Markdown", "Java", "Gradle" ]
3
Gradle
sirmmo/Android-OsCar
0348241b1568897845ff43e3b54c3a869bc00a44
395a44db7bfd3e9bd17bf531fbac54e07c08cb61
refs/heads/master
<repo_name>AntonioCS/puppet-development-stack<file_sep>/Vagrantfile # Vagrantfile API/syntax version. Don't touch unless you know what you're doing! VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| #http://docs.vagrantup.com/v2/vagrantfile/machine_settings.html config.vm.box_url = "https://oss-binaries.phusionpassenger.com/vagrant/boxes/latest/ubuntu-14.04-amd64-vbox.box" config.vm.box = "ubuntu14_64" config.vm.hostname = "acs.dev" #http://stackoverflow.com/questions/17845637/vagrant-default-name #define a name for the machine (no more default) config.vm.define "acs_dev" do |acs_dev| end #http://docs.vagrantup.com/v2/virtualbox/networking.html config.vm.network "private_network", ip: "192.168.33.10", virtualbox__intnet: true config.vm.network "forwarded_port", guest: 80, host: 80 #RabbitMQ Config page config.vm.network "forwarded_port", guest: 15672, host: 15672 #http://docs.vagrantup.com/v2/synced-folders/basic_usage.html config.vm.synced_folder "C:/Users/antoniocs/Projects", "/vagrant_data", :mount_options => ['dmode=775', 'fmode=775'] config.vm.synced_folder '.', '/vagrant', :mount_options => ['dmode=770', 'fmode=770'] #prevent syncing of the vagrant folder #config.vm.synced_folder '.', '/vagrant', disabled: true config.vm.provider "virtualbox" do |vb| vb.gui = false vb.memory = 2048 #vb.name = "acs_dev" end # Enable the Puppet provisioner, with will look in manifests config.vm.provision :puppet do |puppet| puppet.manifests_path = "manifests" puppet.manifest_file = "default.pp" puppet.module_path = "modules" #http://blog.doismellburning.co.uk/2013/01/19/upgrading-puppet-in-vagrant-boxes/ #http://stackoverflow.com/questions/28234437/trying-to-use-hiera-with-vagrant-and-puppet #puppet.options = "--hiera_config /etc/hiera.yaml" end end
97786951dfd06850980b2f30a1e78f6d5406b327
[ "Ruby" ]
1
Ruby
AntonioCS/puppet-development-stack
52573b271409d8ff2466a79325695c93fc2bd77f
0ad2ec29f0ca938b2be4d4ec1e96b2971dd6b75d
refs/heads/master
<file_sep># ybb-cli supply templates to create your application ## Installation ```bash npm i ybb-cli g ``` ## help to help you how to use it ```bash ybb-cli ``` ## test ```bash ybb-cli init vue-webpack-mpa test ```<file_sep>'use strict' const exec = require('child_process').exec const co = require('co') const prompt = require('co-prompt') const ora = require('ora') const inquirer = require('inquirer') const rm = require('rimraf') const config = require('../templates') const chalk = require('chalk') const fs = require('fs') const path = require('path') module.exports = () => { co(function *() { // 处理用户输入 // let tplName = yield prompt('Template name: ') // let projectName = yield prompt('Project name: ') let tplName = process.argv[3]; let projectName = (yield prompt(`Project name: ${process.argv[4]?'('+process.argv[4]+') ':''}`)) || process.argv[4] ; let gitUrl let branch let isDir = fs.existsSync(projectName); let installPak = ''; if (!config.tpl[tplName]) { console.log(chalk.red('\n × Template does not exit!')) process.exit() } gitUrl = config.tpl[tplName].url branch = config.tpl[tplName].branch // 问题 let inPlace = !projectName || projectName === '.' if (inPlace || isDir) { inquirer.prompt([{ type: 'confirm', message: inPlace ? 'Do you want to create project in current directory?' : 'Target directory exists. Continue?', name: 'ok' }]).then(answers => { if (answers.ok) { handle() } }).catch() } else { handle() } function handle (){ co(function *(){ //问问题 // 是否安装fis3 let answers = yield inquirer.prompt([{ type: 'confirm',message: 'Install fis3?',name: 'ok'}]) if (answers.ok) installPak += 'fis3 '; if(isDir) { rm(path.join(`${projectName}`,'./'),err=>{ run(); }) } else { run(); } }) } function run (){ let cmdStr = `git clone ${gitUrl} ${!inPlace||isDir?projectName:'.'}`; console.log(`\n`); const spinner = ora('Start generating...') spinner.start(); // 先clone exec(cmdStr,(error,stdout,stderr)=>{ rm(path.join(`${projectName}`,'.git'),er=>{ spinner.stop(); if (error) { console.log(error) process.exit() } console.log(chalk.green(' √ Generation completed!')); let installStr = `${isDir?'cd '+projectName+' && ':''}npm install ${installPak?'&& npm install '+installPak+'-D':''}`; console.log(`\n`); const install = ora('Installing project dependencie...'); install.start(); // 开始下载依赖 exec(installStr,(err,stdo,stderr)=>{ // 下载后处理 if(installPak.indexOf('fis3')!=-1) { let data = fs.readFileSync(path.join(__dirname,'../lib/fis-conf.js'), 'utf8'); fs.writeFileSync(path.join(projectName||'','./fis-conf.js'),data); } install.stop(); console.log(chalk.white(`\n To get started: `),chalk.yellow(`\n\n ${isDir?'cd '+projectName+'\n':''} npm run dev \n`)); }) }) //process.exit() }) } // return; // // 判断当前文件夹是否存在 // if(fs.existsSync(projectName)) { // let inPlace = yield prompt(`target`) // console.log(chalk.red(`\n Error: path '${projectName}' has already exists and is not an empty directory`)); // return; // } // // git命令,远程拉取项目并自定义项目名 // // let cmdStr = `git clone ${gitUrl} ${projectName} && cd ${projectName} && git checkout ${branch}` // let cmdStr = `git clone ${gitUrl} ${projectName}`; // console.log(`\n`); // const spinner = ora('Start generating...') // spinner.start() // exec(cmdStr, (error, stdout, stderr) => { // // 删除 // rm(path.join(`${projectName}`,'.git'),function(err){ // if(err) throw err; // spinner.stop(); // if (error) { // console.log(error) // process.exit() // } // console.log(chalk.green('\n √ Generation completed!')) // console.log(chalk.white(`\n To get started: `),chalk.yellow(`\n\n cd ${projectName} \n npm install \n npm run dev \n`)); // process.exit() // }) // }) }) }<file_sep>'use strict' const config = require('../templates') const chalk = require('chalk') module.exports = () => { console.log(`\n The following templates:\n`) let tpl = config['tpl']; for(let i in tpl) { console.log(chalk.yellow(' ★'),chalk.hex('#ff7100')(` ${i}`),chalk.white(` - ${tpl[i].desc}`)) } console.log('\n'); process.exit() }<file_sep> // default settings. fis3 release fis.match('**', { release: false }) fis.match('/dist/(**)', { release: '$1' }) // 测试 fis.media('test') .match('**', { deploy: fis.plugin('http-push', { receiver: '', to: '', }), }) // // 发布到正服 fis.media('jenkins') .match('**', { deploy: [ fis.plugin('http-push', { receiver: '', to: '' }) ], });
0b6c4a1d34e5a99ee030a42270c483c6ee42358c
[ "Markdown", "JavaScript" ]
4
Markdown
yellowbeee/ybb-cli
b1a50631be388c0c5f0f892d48a1eee5d774191b
1f8aafd5fd97dbaf536966e456b7399d6fd314e2
refs/heads/master
<repo_name>albertohenri/Projeto-de-Web1<file_sep>/app/controllers/default.py from flask import render_template, flash, redirect, url_for, session, request from app import app , db, lm from flask_login import login_user, logout_user from app.models.tables import User from app.models.forms import LoginForms import functools @lm.user_loader def load_user(id): return User.query.filter_by(id=id).first() @app.route('/') @app.route("/index") def index(): return render_template('index.html') @app.route("/login", methods=["GET", "POST"]) def login(): form = LoginForms() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user and user.password == form.password.data: login_user(user) flash("Logged in.") return redirect(url_for("index")) else: flash("Invalid login. ") return render_template("login.html", form=form) @app.route('/logout') def logout(): session.clear() return redirect(url_for('index')) @app.route("/cadastrar") def cadastrar(): return render_template("cadastro.html") @app.route("/cadastro", methods=['GET', 'POST']) def cadastro(): form = RegisterForms() if request.method == "POST" : username = request.form.get("username") password = request.form.get("<PASSWORD>") name = request.form.get("name") email = request.form.get("email") if username and password and name and email: user = User(username,password,name,email) db.session.add(user) db.session.commit() return redirect(url_for("index")) @app.route("/lista") def lista(): user = User.query.all() return render_template("lista.html",user=user) @app.route("/excluir/<int:id>") def excluir(id): user = User.query.filter_by(id=id).first() db.session.delete(user) db.session.commit() user = User.query.all() return render_template("lista.html", user=user) @app.route("/alterar/<int:id>", methods=['GET','POST']) def alterar(id): user = User.query.filter_by(id=id).first() if request.method == "POST" : username = request.form.get("username") password = request.form.get("password") name = request.form.get("name") email = request.form.get("email") if username and password and name and email: user.username = username user.password = <PASSWORD> user.name = name user.email = email db.session.commit() return redirect(url_for("lista")) return render_template("alterar.html", user=user) #Crud exemplos# #@<EMAIL>("/teste/<info>") #@app.route("/teste", defaults={"info":None}) #def teste(info): # r = User.query.filter_by(username="Arthur").first() #print(r.username, r.name) #return "Ok" #i = User("Arthur", "1234", "<NAME>" , "<EMAIL>") #db.session.add(i) #db.session.commit() #@<EMAIL>("/test/") #def test(): # return "Oi!" <file_sep>/app/__init__.py from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from flask_login import LoginManager def create_app(config_name): from.auth import auth as auth_blueprint app.register_blueprint(auth_blueprint,url_prefix='/auth') return app app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) lm = LoginManager() lm.init_app(app) from app.models import tables ,forms from app.controllers import default def create_app(config_name): from.auth import auth as auth_blueprint app.register_blueprint(auth_blueprint,url_prefix='/auth') return app
f44bd15f862149580263f9fcb54120b77823b84c
[ "Python" ]
2
Python
albertohenri/Projeto-de-Web1
d053c8aa028dd6bf44858c06b60433b63c32b28f
17cc42f3ea84ef4f7956432c214db803a3155099
refs/heads/master
<repo_name>Artik292/homework<file_sep>/index(old).php <?php require 'vendor/autoload.php'; $app = new \atk4\ui\App('Нажмите на любую кнопку!'); $app->initLayout('Centered'); If (isset($_GET['max'])) { $max = $_GET['max']; $min = $_GET['min']; } else { $max = 100; $min = 0; } $med = round(($max+$min)/2); $label = $app->layout->add(['Label','Ваше число больше '.$med.' ?']); $label->addClass('massive orange'); $button_yes = $app->layout->add(['Button','Да']); $button_yes->addClass('massive green'); $button_yes->link(['index','max'=>$max,'min'=>$med]); $button_no = $app->layout->add(['Button','Нет']); $button_no->addClass('massive red'); $button_no->link(['index','max'=>$med,'min'=>$min]); $button_win = $app->layout->add(['Button','Это моё число!']); $button_win->addClass('massive violet'); $button_win->link(['win','number'=>$med]); $button_win = $app->layout->add(['Button','Сыграть ещё раз']); $button_win->addClass('small brown'); $button_win->link(['index']); <file_sep>/index.php <?php require 'vendor/autoload.php'; $app = new \atk4\ui\App('Эксперементы'); $app->initLayout('Centered'); $app->add(['Label','You use '.$_SERVER['REMOTE_PORT'].' port.','big']); $app->add(['Label','Your IP is '.$_SERVER['REMOTE_ADDR'].'.','big']); <file_sep>/main.php <?php require 'vendor/autoload.php'; $app = new \atk4\ui\App('Вы нажали на кнопку:'); $app->initLayout('Centered'); $number = $_GET['number']; $button1 = $app->layout->add(['Button', $number]); $button1->link(['index']);
2fae1334d2417b1d5ca70002dc083850326d3e3c
[ "PHP" ]
3
PHP
Artik292/homework
4052a5b7fd520320c8c066bdd07da39553fd7fe3
45ae777aa4f61dbc408542490308f5c0bec4ee02
refs/heads/master
<file_sep>package main import ( "encoding/json" "errors" "fmt" "github.com/hyperledger/fabric/core/chaincode/shim" ) // SampleChaincode example Sample Chaincode implementation type SampleChaincode struct { } // Init create tables for tests func (t *SampleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) { // Create table one err := createTableOne(stub) if err != nil { return nil, errors.New("Error creating table one during init.") } return nil, nil } // // Invoke callback representing the invocation of a chaincode // This chaincode will manage two accounts A and B and will transfer X units from A to B upon invoke func (t *SampleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) { if function == "insertTableOne" { return insertTableOne(stub, args) } return nil, nil } func insertTableOne(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) { if len(args) < 5 { return nil, errors.New("insertTableOne failed. Must include 5 column values") } col1Val := args[0] col2Val := args[1] col3Val := args[2] col4Val := args[3] col5Val := args[4] var columns []*shim.Column col1 := shim.Column{Value: &shim.Column_String_{String_: col1Val}} col2 := shim.Column{Value: &shim.Column_String_{String_: col2Val}} col3 := shim.Column{Value: &shim.Column_String_{String_: col3Val}} col4 := shim.Column{Value: &shim.Column_String_{String_: col4Val}} col5 := shim.Column{Value: &shim.Column_String_{String_: col5Val}} columns = append(columns, &col1) columns = append(columns, &col2) columns = append(columns, &col3) columns = append(columns, &col4) columns = append(columns, &col5) row := shim.Row{Columns: columns} ok, err := stub.InsertRow("tableOne", row) if err != nil { fmt.Printf("insertTableOne operation failed. %s", err) return nil, err } if !ok { fmt.Printf("insertTableOne operation failed. Row with given key already exists") return nil, err } return nil, nil } // Query callback representing the query of a chaincode func (t *SampleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) { switch function { case "getRowTableOne": if len(args) < 1 { fmt.Printf("getRowTableOne failed. Must include key values") return nil, errors.New("Expected atleast 1 arguments for query") } col1Val := args[0] var columns []shim.Column col1 := shim.Column{Value: &shim.Column_String_{String_: col1Val}} columns = append(columns, col1) row, err := stub.GetRow("tableOne", columns) if err != nil { fmt.Printf("getRowTableOne operation failed. %s", err) return nil, err } rowString := fmt.Sprintf("%s", row) return []byte(rowString), nil /* var columns []shim.Column var op = args[1] if( op == "1" ) { col1Val:=args[0] col1 := shim.Column{Value: &shim.Column_String_{String_: col1Val}} columns = append(columns, col1) } else if( op == "2" ) { col2Val:=args[0] col2 := shim.Column{Value: &shim.Column_String_{String_: col2Val}} columns = append(columns, col2) } else if ( op == "3" ) { col3Val:=args[0] col3 := shim.Column{Value: &shim.Column_String_{String_: col3Val}} columns = append(columns, col3) } else if ( op == "4" ) { col4Val:=args[0] col4 := shim.Column{Value: &shim.Column_String_{String_: col4Val}} columns = append(columns, col4) } else { col5Val:=args[0] col5 := shim.Column{Value: &shim.Column_String_{String_: col5Val}} columns = append(columns, col5) } row, err := stub.GetRow("tableOne", columns) if err != nil { fmt.Printf("getRowTableOne operation failed. %s", err) return nil, err } rowString := fmt.Sprintf("%s", row) return []byte(rowString), nil */ case "getRowsTableOne": if len(args) < 1 { return nil, errors.New("getRowsTableOne failed. Must include at least 1 key values") } var columns []shim.Column col1Val := args[0] col1 := shim.Column{Value: &shim.Column_String_{String_: col1Val}} columns = append(columns, col1) if len(args) > 1 { col2Val := args[1] col2 := shim.Column{Value: &shim.Column_String_{String_: col2Val}} columns = append(columns, col2) } rowChannel, err := stub.GetRows("tableOne", columns) if err != nil { return nil, errors.New("getRowsTableOne operation failed. ") } var rows []shim.Row for { select { case row, ok := <-rowChannel: if !ok { rowChannel = nil } else { rows = append(rows, row) } } if rowChannel == nil { break } } jsonRows, err := json.Marshal(rows) if err != nil { return nil, errors.New("getRowsTableOne operation failed. Error marshaling JSON:") } return jsonRows, nil } return nil, nil } func main() { err := shim.Start(new(SampleChaincode)) if err != nil { fmt.Printf("Error starting Sample chaincode: %s", err) } } func createTableOne(stub shim.ChaincodeStubInterface) error { // Create table one var columnDefsTableOne []*shim.ColumnDefinition columnOneTableOneDef := shim.ColumnDefinition{Name: "colOneTableOne", Type: shim.ColumnDefinition_STRING, Key: true} columnTwoTableOneDef := shim.ColumnDefinition{Name: "colTwoTableOne", Type: shim.ColumnDefinition_STRING, Key: true} columnThreeTableOneDef := shim.ColumnDefinition{Name: "colThreeTableOne", Type: shim.ColumnDefinition_STRING, Key: true} columnFourTableOneDef := shim.ColumnDefinition{Name: "colFourTableOne", Type: shim.ColumnDefinition_STRING, Key: true} columnFiveTableOneDef := shim.ColumnDefinition{Name: "colFiveTableOne", Type: shim.ColumnDefinition_STRING, Key: true} columnDefsTableOne = append(columnDefsTableOne, &columnOneTableOneDef) columnDefsTableOne = append(columnDefsTableOne, &columnTwoTableOneDef) columnDefsTableOne = append(columnDefsTableOne, &columnThreeTableOneDef) columnDefsTableOne = append(columnDefsTableOne, &columnFourTableOneDef) columnDefsTableOne = append(columnDefsTableOne, &columnFiveTableOneDef) return stub.CreateTable("tableOne", columnDefsTableOne) }
cfac635287ba835cf6f33dc1c21315f2ea754722
[ "Go" ]
1
Go
suffiasameera/table
10ab191cdf760251342039e82c26b2b4f39c9913
aea960977490d3d895294720db77be7d8e34b5cb
refs/heads/master
<repo_name>HerronTech/soajs.tidbit.demo<file_sep>/import/products/index.js var devProducts = { "code": "TIDDEV", "name": "TidBit Dev Product", "description": "This is a product for TidBit demo", "packages": [ { "code": "TIDDEV_PACK1", "name": "Package 1", "description": "This package is admin. It contains 2 public APIs: get & post for each service (hapi,java & express)", "acl": { "dev": { "express": { "access": false }, "hapi": { "access": false }, "java": { "access": false } } }, "_TTL": 21600000 }, { "code": "TIDDEV_PACK2", "name": "Package 2", "description": "This package have access to 1 API: post. Get is restricted", "acl": { "dev": { "express": { "access": false, "apisPermission": "restricted", "post": { "apis": { "/tidbit/hello": { "access": false } } }, }, "hapi": { "access": false, "apisPermission": "restricted", "post": { "apis": { "/tidbit/hello": { "access": false } } }, }, "java": { "access": false, "apisPermission": "restricted", "post": { "apis": { "/tidbit/hello": { "access": false } } }, } } }, "_TTL": 21600000 } ] }; module.exports = devProducts;<file_sep>/import/tenants/index.js var tenants = [ { "type": "client", "code": "TID1", "name": "TIDBIT 1", "description": "This tenant will use package 1 which gives access to all APIs and have service config 1", "oauth": {}, "applications": [ { "product": "DEV", "package": "TIDDEV_PACK1", "appId": '<KEY>', "description": null, "_TTL": 21600000, "keys": [ { "key": "<KEY>", "extKeys": [ { "extKey": "", "device": {}, "geo": {}, "env": "DEV" } ], "config": { "dev": { "commonFields":{ "data": "This is service config 1" } } } } ] } ] }, { "type": "client", "code": "TID2", "name": "TIDBIT 2", "description": "This tenant will use package 1 which gives access to all APIs and have service config 2", "oauth": {}, "applications": [ { "product": "DEV", "package": "TIDDEV_PACK1", "appId": '<KEY>', "description": null, "_TTL": 21600000, "keys": [ { "key": "<KEY>", "extKeys": [ { "extKey": "", "device": {}, "geo": {}, "env": "DEV" } ], "config": { "dev": { "commonFields":{ "data": "This is service config 2" } } } } ] } ] }, { "type": "client", "code": "TID3", "name": "TIDBIT 3", "description": "This tenant will use package 2 which gives access to the post API only and have service config 3", "oauth": {}, "applications": [ { "product": "DEV", "package": "TIDDEV_PACK2", "appId": '<KEY>', "description": null, "_TTL": 21600000, "keys": [ { "key": "c05ff3faf3456547c60386a339a41db8", "extKeys": [ { "extKey": "", "device": {}, "geo": {}, "env": "DEV" } ], "config": { "dev": { "commonFields":{ "data": "This is service config 3" } } } } ] } ] }, { "type": "client", "code": "TID4", "name": "TIDBIT 4", "description": "This tenant will use package 2 which gives access to the post API only and have service config 4", "oauth": {}, "applications": [ { "product": "DEV", "package": "TIDDEV_PACK2", "appId": '58bd23e806f3698ba308dc1e', "description": null, "_TTL": 21600000, "keys": [ { "key": "<KEY>", "extKeys": [ { "extKey": "", "device": {}, "geo": {}, "env": "DEV" } ], "config": { "dev": { "commonFields":{ "data": "This is service config 4" } } } } ] } ] }, { "type": "client", "code": "TID5", "name": "TIDBIT 5", "description": "This tenant will use package 2 which gives access to the post API, however, its acl is overriden and the get API is also available. And it have service config 5", "oauth": {}, "applications": [ { "product": "DEV", "package": "TIDDEV_PACK2", "appId": '5<KEY>', "description": null, "_TTL": 21600000, "keys": [ { "key": "10c4f67eab523fdfba900dea5480947c", "extKeys": [ { "extKey": "", "device": {}, "geo": {}, "env": "DEV" } ], "config": { "dev": { "commonFields":{ "data": "This is service config 5" } } } } ], "acl": { "dev": { "express": { "access": false }, "hapi": { "access": false }, "java": { "access": false } } } } ] } ]; module.exports = tenants;<file_sep>/README.md # TidBit Demo This repository contains the configuration data for the the TIDBIT demo. The TIDBIT demo illustrates how to deploy services written in multiple programing languages on top of SOAJS. https://soajsorg.atlassian.net/wiki/display/TID/TIDBIT ## Usage Import the configuration data after deploying SOAJS Dashboard ```sh $ cd soajs.tidbit.demo $ npm install $ cd import $ node . ``` ## Help The importer is equiped with a manual ```sh $ cd soajs.tidbit.demo/import $ node . --help ```
f1af909947440b18742a00b18162c046db9f2ee4
[ "JavaScript", "Markdown" ]
3
JavaScript
HerronTech/soajs.tidbit.demo
6afe753c6b75d3dc2567a6922c0631fdb47250c4
1e98287ecd07cfe4925c9ee81cea8a28d36a13d2
refs/heads/master
<repo_name>mangeshrane/pyautomation<file_sep>/pyautomation/mobile/mobile_element.py ''' Created on Apr 15, 2019 @author: mrane ''' class MobileElement(object): def __init__(self, by, locator, wait=10): ''' Constructor: Parameters: ---------- by : selenium.webdriver.common.by.By locator: string locator value wait: [optional] default=10 ''' self._by = by self._locator = locator self._wait = wait def __get__(self, instance, owner): if self._wait: return WebDriverWait(instance.driver, self._wait).until( EC.presence_of_element_located((self._by, self._locator))) else: return instance.driver.find_element(self._by, self._locator) LOG.info("returning element {}={} ".format(self._by, self._locator)) def __set__(self, instance, name): pass def __delete__(self): pass<file_sep>/pyautomation/data_providers/excel_reader.py import xlrd import os from pyautomation.file_manager.file_manager import FileManager from pyautomation import LOG class ExcelReader(object): def __init__(self): pass @staticmethod def get_data_map(filename, data_filter, headers=True, sheet_no=0): workbook = xlrd.open_workbook(os.path.join(FileManager.get_test_datadir(), filename)) LOG.info("using excel sheet " + filename) data_filter = data_filter sheet = workbook.sheet_by_index(sheet_no) flag = False for row in range(sheet.nrows): if sheet.cell(row, 0).value == data_filter: s_index = row + 1 flag = True elif flag and sheet.cell(row, 0).value == "END": e_index = row flag = False keys = [sheet.cell(s_index, col_index).value for col_index in range(sheet.ncols)] dict_list = [] for row_index in range(s_index + 1, e_index): d = {keys[col_index]: sheet.cell(row_index, col_index).value for col_index in range(sheet.ncols)} d = {key: d[key] for key in [key for key in d.keys() if key ]} dict_list.append(d) LOG.info("returning data from excel") return dict_list <file_sep>/pyautomation/mobile/application.py from abc import ABC class Application(ABC): def forceStop(self): pass def clearData(self): pass def open(self): pass def packageID(self): pass def activityID(self): pass <file_sep>/pyautomation/web/element.py ''' Created on Feb 11, 2019 @author: mrane ''' from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from pyautomation import LOG class Element(object): ''' WebElement descriptor to define webelements in page objects This will returns Webelement when it is accessed ''' def __init__(self, by, locator, wait=10): ''' Constructor: Parameters: ---------- by : selenium.webdriver.common.by.By locator: string locator value wait: [optional] default=10 ''' self._by = by self._locator = locator self._wait = wait def __get__(self, instance, owner): if self._wait: return WebDriverWait(instance.driver, self._wait).until( EC.presence_of_element_located((self._by, self._locator))) else: return instance.driver.find_element(self._by, self._locator) LOG.info("returning element {}={} ".format(self._by, self._locator)) def __set__(self, instance, name): pass def __delete__(self): pass <file_sep>/setup.py from setuptools import setup setup( name='pyautomation', version='1.0', author='mrane', author_email='<EMAIL>', packages=['pyautomation', 'pyautomation.api', 'pyautomation.browsers', 'pyautomation.configuration', 'pyautomation.data_providers', 'pyautomation.file_manager', 'pyautomation.web', ], scripts=[], #Entry point to found by pytest entry_points={'pytest11': ['pytest-pyautomation=pyautomation.plugin',], 'console_scripts': ['pyautomation=pyautomation.project_setup:main'],}, url='', license='', description='', long_description=open('README.md').read(), install_requires=[ "allure-pytest==2.6.2", "allure-python-commons==2.6.2", "apipkg==1.5", "atomicwrites==1.3.0", "attrs==19.1.0", "certifi==2019.3.9", "chardet==3.0.4", "colorama==0.4.1", "execnet==1.6.0", "idna==2.8", "more-itertools==7.0.0", "pluggy==0.9.0", "py==1.8.0", "pytest==4.4.0", "pytest-forked==1.0.2", "pytest-xdist==1.28.0", "PyYAML==5.1", "requests==2.21.0", "selenium==3.141.0", "six==1.12.0", "urllib3==1.24.1", "xlrd==1.2.0", "pytest-html==1.20.0", ], classifiers=["Framework :: Pytest"], )<file_sep>/pyautomation/__init__.py from pyautomation.logger import LOG from pyautomation.configuration.config_reader import Config DATA_FILE_LOCATION = "testData" CONFIG_FILE_LOCATION = "config" SCREENSHOT_LOCATION = "sceenshot" REPORT_LOCATION = "results" LOG = LOG CONFIG = Config() __version__ = "1.0.1"<file_sep>/pyautomation/data_providers/csv_reader.py import csv import os from pyautomation.file_manager.file_manager import FileManager from pyautomation import LOG class CSVReader(object): def __init__(self): pass @staticmethod def get_data_map(filename, header=None): with open(os.path.join(FileManager.get_test_datadir(), filename)) as csvfile: reader = csv.DictReader(csvfile, fieldnames=header) LOG.info("returning CSV data") return list(reader)<file_sep>/pyautomation/api/response.py ''' Created on Mar 20, 2019 @author: mrane ''' import json from requests.models import Response as rp from collections import namedtuple from pprint import pformat class Response(object): ''' classdocs ''' def __init__(self, response): ''' Constructor ''' print("API Response body : \n\t" + pformat(str(response.text))) print("API Response headers : \n\t" + pformat(str(response.headers))) print("API Response cookies : \n\t" + pformat(str(response.cookies))) print("API Response status code : \n\t" + pformat(str(response.status_code))) if not isinstance(response, rp): raise ValueError self.url = response.url self.status_code = response.status_code self._request = response.request try: self.body = PyJSON(response.text) except Exception: self.body = None self.reason = response.reason self.cookies = response.cookies self.headers = response.headers def assert_response_code(self, response_code): assert self.status_code == response_code, "Response code does not match, expected {0} but found {1}".format( response_code, self.status_code) return self def _json_object_hook(self, d): return namedtuple('response', d.keys())(*d.values()) def json2obj(self, data): return json.loads(data, object_hook=self._json_object_hook) def assert_status_code(self, status_code): assert status_code == self.status_code, "Status code doesn't match expected {} found {}".format(self.status_code, status_code) def assert_response_contains(self, text): assert text in self.body, "Response body doesn't contains " + text def assert_response_header_contains(self, key, value): assert self.headers.get(key, None) == value, "Response headers doesn't contains {}:{}".format( key, value) class PyJSON(object): def __init__(self, d): if type(d) is str: d = json.loads(d) self.from_dict(d) def from_dict(self, d): self.__dict__ = {} for key, value in d.items(): if type(value) is dict: value = PyJSON(value) self.__dict__[key] = value def to_dict(self): d = {} for key, value in self.__dict__.items(): if type(value) is PyJSON: value = value.to_dict() d[key] = value return d def __repr__(self): return str(self.to_dict()) def __setitem__(self, key, value): self.__dict__[key] = value def __getitem__(self, key): return self.__dict__[key] <file_sep>/pyautomation/data_providers/data_provider.py import pprint from pyautomation.data_providers.csv_reader import CSVReader from pyautomation.data_providers.excel_reader import ExcelReader from pyautomation.data_providers.json_reader import JSONReader def get_data(filename, data_filter="", fields=None, headers=True): if str(filename).endswith("csv"): dataset = CSVReader.get_data_map(filename) print() if headers: dataset = dataset[1:] elif str(filename).endswith("xls") or str(filename).endswith("xlsx"): dataset = ExcelReader.get_data_map(filename, data_filter, headers) elif str(filename).endswith("json"): dataset = JSONReader.get_data_map(filename) else: raise UnsupportedFileFormat("Datafile must be csv, xls or json") edata = [] if fields: for data in dataset: edata.append( tuple(data[f] for f in fields) ) data = (",".join(fields), edata) return data else: for data in dataset: keys = list(dataset[0].keys()) edata.append(tuple(data[f] for f in keys)) data = (",".join(keys), edata) return data class UnsupportedFileFormat(Exception): pass pprint.pprint(get_data("users.csv")) <file_sep>/pyautomation/project_setup.py import yaml config_file = {"application": {"username": "<EMAIL>", "password": "<PASSWORD>"}, "webdriver": {"sauce": {"username": None, "key": None, "browserName": None, "caps": {"browserName": "chrome", "version": 66.0, "platform": "macOS 10.13"}}, "remote": {"url": None, "platform": None}, "type": "local", "chrome": {"driver": "C:\\chromedriver.exe", "arguments": ["--disable-extensions", "--headless"]}, "firefox": {"driver": "path", "preferences": {"browser.download.dir": "H:\\Downloads", "browser.download.manager.showWhenStarting": False}}, "wait": {"short": 10, "long": 30}, "implicit_wait": 10}, "tests": {"browser": {"name": "chrome", "scope": "class"}}, "api": {"request": {"timeout": 20}}} page = ''' # @auther :generated by pyautomation from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from pyautomation.web.webpage import WebPage from pyautomation.web.element import Element class SearchPage(WebPage): def __init__(self, driver): self.driver = driver search_field = Element(By.NAME, "q") def load(self): self.driver.get("http://google.com") def is_loaded(self): pass def search(self, query): self.search_field.send_keys(query + Keys.ENTER) ''' tests = ''' # @auther :generated by pyautomation from tests.pages.search_page import SearchPage from pyautomation.web.webtest import WebTest from pyautomation.web.create_page import CreatePage class TestSearch(WebTest): def test_search(self): page = CreatePage.get(SearchPage, self.driver) print(page.search_field.text) page.search("test") assert self.driver.title.startswith("test"), "title does not match" ''' api = ''' # @auther :generated by pyautomation from pyautomation.api.request import Request, ContentType import pytest @pytest.mark.api def test_post_request(): # POST Request headers = { 'cache-control': "no-cache", 'postman-token': "<PASSWORD>" } response = Request().header(ContentType.URLENC).set_base_url("https://postman-echo.com/post").add_param("strange", "boom").add_headers(headers ).post("post") print(response.body) @pytest.mark.api def test_delete_request(): # DELETE Request resp = Request().set_base_url("http://fakerestapi.azurewebsites.net").set_path_param("id", 20).delete("/api/Books/{id}") print(resp.body) @pytest.mark.api def test_put_request(): # PUT Request req = """ {"ID":182,"Title":"vog","Description":"bwb","PageCount":786,"Excerpt":"jwmbtifn","PublishDate":"2019-03-24T11:46:01.452Z"} """ resp = Request().header(ContentType.JSON).set_base_url("http://fakerestapi.azurewebsites.net").set_body(req).set_path_param("id", 20).put("/api/Books/{id}") print(resp.body) ''' # importing the required modules import os import argparse # error messages INVALID_FILETYPE_MSG = "Error: Invalid file format. %s must be a .txt file." INVALID_PATH_MSG = "Error: Invalid file path/name. Path %s does not exist." def main(): # create parser object parser = argparse.ArgumentParser(description = "A text file manager!") # defining arguments for parser object parser.add_argument("-n", "--name", type = str, nargs = 1, metavar = "project_name", default = None, help = "project name.") parser.add_argument("-d", "--directory", type = str, nargs = 1, metavar = "file_name", default = None, help = "Deletes the specified text file.") # parse the arguments from standard input args = parser.parse_args() # calling functions depending on type of argument if args.name != None: project_name = args.name if args.directory is None: project_dir = os.getcwd() elif args.directory != None and os.path.isdir(args.directory[0]): project_dir = args.directory[0] else: raise ValueError print("Creating project...") project = os.path.join(project_dir, project_name[0]) os.mkdir(project) os.chdir(project) with open(".rootfile", 'w') as f: f.write("# created by pyautomation...\nDo not remove this file it used to get root directory.\nproject root directory can be changed by moving this file") config = os.path.join(project, "config") os.makedirs(config) os.makedirs(os.path.join(project, "testdata")) pages = os.path.join(project, "tests", "pages") os.makedirs(pages) test_suites = os.path.join(project, "tests", "test_suites") os.makedirs(test_suites) os.chdir(config) with open("default.yml", 'w') as f: yaml.dump(config_file, f, default_flow_style=False) os.chdir(pages) with open("__init__.py", "w") as f: f.write("# Page objects place in this directory") with open("search_page.py", "w") as f: f.write(page) os.chdir(test_suites) with open("__init__.py", "w") as f: f.write("# test_suites place in this directory") with open("test_search.py", "w") as f: f.write(tests) with open("test_api.py", "w") as f: f.write(api) os.chdir(os.path.join(project, "tests")) with open("__init__.py", "w") as f: pass print("project created successfully.") if __name__ == "__main__": # calling the main function main() <file_sep>/pyautomation/mobile/activity.py from abc import ABC class Activity(ABC): def waitToLoad(self): pass <file_sep>/pyautomation/mobile/adb.py import subprocess import os from pyautomation import CONFIG class Adb(object): adb = None def __init__(self): self.adb = self.command("adb start-server") def command(self, command): if command.startsWith("adb"): command = command.replace("adb ", os.path.join(CONFIG.get("android.home") + "/platform-tools/adb")) else: raise RuntimeError("This method is designed to run ADB commands only!") output = subprocess.Popen(command); if output is None: return ""; else: return output.strip(); def get_connected_devices(self): devices = []; output = self.command("adb devices"); for line in str(output).split("\n"): line = line.strip(); if line.endsWith("device"): devices.append(line.replace("device", "").strip()); return devices; def get_foreground_activity(self, deviceid): return self.command("adb -s "+ deviceid +" shell dumpsys window windows | grep mCurrentFocus") def get_android_version(self, deviceid): output = self.command("adb -s "+ deviceid +" shell getprop ro.build.version.release") if(output.length() == 3): output+=".0" return output def get_installed_packages(self, deviceid): packages = [] output = self.command("adb -s "+ deviceid +" shell pm list packages").split("\n") for packageID in output: packages.append(packageID.replace("package:","").trim()) return packages def open_apps_activity(self, deviceid, packageid, activityid): self.command("adb -s "+ deviceid +" shell am start -c api.android.intent.category.LAUNCHER -a api.android.intent.action.MAIN -n " + packageid + "/" +activityid) def clear_apps_data(self, device_id, package_id): self.command("adb -s " + device_id + " shell pm clear " + package_id) def force_stop_app(self, deviceid, packageid): self.command("adb -s " + deviceid +" shell am force-stop "+packageid) def install_app(self, deviceid, apkpath): self.command("adb -s "+ deviceid +" install " + apkpath); def uninstall_app(self, deviceid, packageid): self.command("adb -s "+ deviceid +" uninstall " + packageid); def clear_log_buffer(self, deviceid): self.command("adb -s "+ deviceid +" shell -c") def push_file(self, deviceid, source, target): self.command("adb -s "+ deviceid +" push "+source+" "+target); def pull_file(self, deviceid, source, target): self.command("adb -s " + deviceid + " pull "+source+" "+target); def delete_file(self, deviceid, target): self.command("adb -s " + deviceid + " shell rm "+ target) def move_file(self, deviceid, source, target): self.command("adb -s " + deviceid + " shell mv "+source+" "+target) def take_screenshot(self, deviceid, target): self.command("adb -s " + deviceid + " shell screencap "+target) def reboot_device(self, deviceid): self.command("adb -s " + deviceid + " reboot") def get_device_model(self, deviceid): return self.command("adb -s " + deviceid + " shell getprop ro.product.model") def get_device_serial_number(self, deviceid): return self.command("adb -s " + deviceid + " shell getprop ro.serialno") def get_device_carrier(self, deviceid): return self.command("adb -s " + deviceid + " shell getprop gsm.operator.alpha") def __del__(self): self.command("adb kill-server")<file_sep>/pyautomation/logger.py ''' Created on Feb 13, 2019 @author: mrane ''' import logging import os from pyautomation.file_manager.file_manager import FileManager _log = logging.getLogger('CORE') _log.setLevel(logging.DEBUG) fh = logging.FileHandler(os.path.join(FileManager.get_project_root(), "logs.log")) fh.setLevel(logging.INFO) ch = logging.StreamHandler() ch.setLevel(logging.ERROR) formatter = logging.Formatter('%(name)s-%(filename)s-%(lineno)d-%(funcName)s: %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) # add the handlers to the logger _log.addHandler(fh) _log.addHandler(ch) LOG = _log<file_sep>/pyautomation/mobile/locator_type.py ''' Created on Apr 15, 2019 @author: mrane ''' class Locator(object): RESOURCE_ID = 'resourceId("{}")' CLASS_NAME = 'className("{}")' TEXT = 'text("{}")' PARTIAL_TEXT = 'textContains("{}")' INDEX = 'index("{}")' CLICKABLE = 'clickable("{}")' CHECKED = 'checked("{}")' ENABLED = 'enabled("{}")' DESCRIPTION = 'description("{}")' PARTIAL_DESCRIPTION = 'descriptionContains("{}")' XPATH = "" <file_sep>/pyautomation/data_providers/json_reader.py import json from collections import namedtuple from builtins import staticmethod import os from pyautomation.file_manager.file_manager import FileManager from pyautomation import LOG class JSONReader(object): @staticmethod def get_data_map(filename): with open(os.path.join(FileManager.get_test_datadir(), filename)) as f: raw = f.read() j = json.loads(raw) LOG.info("returning data from json file : " + filename) return j @staticmethod def json2obj(name, data): return json.loads(data, object_hook=lambda d: namedtuple(name, d.keys())(*d.values()))
a03f949f57db29e2d112e6d91d4d11538ad88f6a
[ "Python" ]
15
Python
mangeshrane/pyautomation
df210523a3444f8633e81e0b6dcd632edd1a477c
bfe40f017859ee0df9f17641003bdfe2804f3694
refs/heads/master
<file_sep>#pragma once #include<iostream> #include<assert.h> #include<vector> #include<thread> #include<mutex> #include<map> #ifdef _WIN32 #include<Windows.h> #endif //管理对象自由链表的长度 #define NLIST 240 //最大支持提供内存的大小 #define MAXBYTES 64*1024 #define NPAGES 129 #define PAGE_SHIFT 12 typedef size_t PageID; //获得可以存放或取出一个指针的内存截断 static void*& GetAddr(void* list) { return *((void**)list); } class FreeList { public: bool IsEmpty() { if (list == nullptr) return true; return false; } void* Pop() { void* obj = list; list = GetAddr(list); size--; return obj; } void Push(void* obj) { GetAddr(obj) = list; list = obj; size++; } size_t Size() { return size; } size_t MaxSize() { return maxsize; } void* clear() { size = 0; void* _list = list; list = nullptr; return _list; } void PushRange(void* start, void* end, size_t num) { GetAddr(end) = list; list = start; size += num; } void SetMaxSize(size_t size) { maxsize = size; } private: void* list = nullptr; size_t size = 0; size_t maxsize = 1; }; //用于内存对齐,将不规范的内存大小转换成规范(规定)的大小 class Sizeclass { //内存碎片控制在该内存大小的12%左右 //[1,128] 8byte对齐 freelist[0,16) //[129,1024] 16byte对齐 freelist[16,72) //[1025,8*1024] 128byte对齐 freelist[72,128) //[8*1024+1,64*1024] 512byte对齐 freelist[128,240) public: static size_t _RoundUp(size_t size, size_t align) { //先进位,再将对齐所对应的位置0,就实现了对齐位的倍数 return (size + align - 1)&~(align - 1); } static size_t RoundUp(size_t bytes) { assert(bytes <= MAXBYTES); if (bytes <= 128) { return _RoundUp(bytes, 8); } else if (bytes <= 1024) { return _RoundUp(bytes, 16); } else if (bytes <= 8192) { return _RoundUp(bytes, 128); } else if (bytes <= 65536) { return _RoundUp(bytes, 512); } else { return -1; } } static size_t _Index(size_t bytes, size_t align_shift) { return ((bytes + (1 << align_shift) - 1) >> align_shift) - 1; } static size_t Index(size_t bytes) { assert(bytes < MAXBYTES); if (bytes <= 128) { return _Index(bytes, 3); } else if (bytes <= 1024) { return _Index(bytes - 128, 4) + 16; } else if (bytes <= 8192) { return _Index(bytes - 1024, 7) + 16 + 56; } else if (bytes <= 65536) { return _Index(bytes - 8192, 9) + 16 + 56 + 56; } else return -1; } static size_t NumMoveSize(size_t size) { if (size == 0) return 0; int num = static_cast<int>(MAXBYTES / size); if (num < 2) num = 2; if (num > 512) num = 512; return num; } static size_t NumMovePage(size_t size) { size_t num = NumMoveSize(size); size_t npage = num * size; npage >>= 12; if (npage == 0) npage = 1; return npage; } }; struct Span { PageID id; //页号 size_t npage; //页的数量 Span* next; Span* prev; void* list = nullptr; //自由链表 size_t objsize = 0; //对象大小 size_t usecount = 0; //使用计数 }; class SpanList { public: SpanList() { head = new Span; head->next = head; head->prev = head; } Span* begin() { return head->next; } Span* end() { return head; } bool Empty() { return head->next == head; } void Insert(Span* cur,Span* newspan) { assert(cur); Span* prev = cur->prev; prev->next = newspan; newspan->prev = prev; newspan->next = cur; cur->prev = newspan; } void Erase(Span* cur) { assert(cur != nullptr && cur!= head); Span* prev = cur->prev; Span* next = cur->next; prev->next = next; next->prev = prev; } void PushFront(Span* cur) { Insert(begin(), cur); } Span* PopFront() { Span* span= begin(); Erase(span); return span; } std::mutex mtx; private: Span * head; };<file_sep>#include<iostream> #include<vector> using std::endl; using std::cout; using std::vector; using std::cin; bool find(vector<vector<int> >& v,int _x,int _y,int n) { int x=0; int y=0; while(x<_x && v[x][_y-1]<=n) { if(v[x][0]==n) return true; x++; } if(x==_x) return false; while(y<_y && v[_x-1][y]<=n) { if(v[x][y]==n) return true; y++; } if(y==_y) return false; int a=x,b=y; for(;a<_x;a++) { b=y; for(;b<_y;b++) { if(v[a][b]==n) return true; } } return false; } int main() { int x,y; vector<int> _v; cout<<"please entry x: "; cin>>x; cout<<"please entry y: "; cin>>y; vector<vector<int> > v; int n=1; //初始化vector<vector<int> > >>之间要有空格 for(int i=0;i<x;i++) { _v.clear(); for(int j=0;j<y;j++) { _v.push_back(n); n++; } v.push_back(_v); } int num; cout<<"please entry find: "; cin>>num; bool r=find(v,x,y,num); if(r==true) cout<<"true"<<endl; else cout<<"false"<<endl; return 0; } <file_sep>#include"central_cache.h" #include"common.h" #include"PageCache.h" CentralCache CentralCache::Inst; size_t CentralCache::FetchRangeObj(void*& start, void*& end, size_t n, size_t byte) { size_t index = Sizeclass::Index(byte); SpanList* _spanlist = &spanlist[index]; Span* span = GetOneSpan(_spanlist, byte); void* cur = span->list; void* prev = cur; size_t fetchnum = 0; while (cur != nullptr&&fetchnum < n) { prev = cur; cur = GetAddr(cur); ++fetchnum; } start = span->list; end = prev; GetAddr(end) = nullptr; span->list = cur; span->usecount += fetchnum; return fetchnum; } void CentralCache::ReleaseListToSpans(void* start, size_t byte_size) { size_t index = Sizeclass::Index(byte_size); SpanList* _spanlist = &spanlist[index]; //加锁 std::unique_lock<std::mutex> lock(_spanlist->mtx); while (start) { void* next = GetAddr(start); Span* span = PageCache::GetInstance()->MapObjectToSpan(start); GetAddr(start) = span->list; span->list = start; //usecount==0时,代表该span切除的对象已被全部回收,可释放span到pagecache里进行合并 if (--(span->usecount) == 0) { _spanlist->Erase(span); span->list = nullptr; span->objsize = 0; span->prev = nullptr; span->next = nullptr; PageCache::GetInstance()->ReleaseSpanToPageCache(span); } start = next; } } Span* CentralCache::GetOneSpan(SpanList* spanlist, size_t size) { Span* span = spanlist->begin(); while (span!=spanlist->end()) { if (span->list != nullptr) { return span; } span = span->next; } //向pagecache申请一个合适的span size_t npage = Sizeclass::NumMovePage(size); Span* newspan = PageCache::GetInstance()->NewSpan(npage); //将span内存分割成一个个byte大小的对象挂起来 char* start = (char*)(newspan->id << PAGE_SHIFT);//在pagecache中定义的id为实际地址>>PAGE_SHIFT char* end = start + (newspan->npage << PAGE_SHIFT); char* cur = start; char* next = cur + size; while (next < end) { GetAddr(cur) = next; cur = next; next = cur + size; } GetAddr(cur) = nullptr; newspan->list = start; newspan->objsize = size; newspan->usecount = 0; //将newspan插入spanlist spanlist->PushFront(newspan); return newspan; } <file_sep>#pragma once #include"common.h" class ThreadCache { public: void* Allocate(size_t size); void Deallocate(void* ptr, size_t size); //从中心缓存获取所需对象 void* FetchFromCentralCache(size_t index, size_t size); //链表中对象太多,开始回收内存 void ListTooLong(FreeList* freelist,size_t size); private: FreeList _freelist[NLIST]; }; //使用单件机制,告诉编译器此变量为线程内部使用,每个线程都copy一份,避免线程安全和效率问题 static _declspec(thread) ThreadCache* tls_threadcache = nullptr;<file_sep>#include "book.h" void print() { printf("********************************\n"); printf("******* 1. 添加 2. 删除 ******\n"); printf("******* 3. 查找 4. 修改 ******\n"); printf("*** 5.显示全部 6.清空全部 ***\n"); printf("******* 7.按名字排序 ******\n"); printf("******* 0.退出程序 ******\n"); printf("********************************\n"); printf("请选择下一步进行的操作:"); } int add_m(struct data* s, int n) { printf("请输入姓名:\n"); scanf_s("%s", (s + n)->name,20); printf("请输入性别:\n"); scanf_s("%s", (s + n)->sex,10); printf("请输入年龄:\n"); scanf_s("%d", &((s + n)->age)); printf("请输入电话号码\n"); scanf_s("%d", &((s + n)->phone_number)); printf("请输入地址:\n"); scanf_s("%s", (s + n)->address,30); return n + 1; } void show_m(struct data* s, int n) { if (n != 0) { int i = 0; printf("名字 性别 年龄 电话号码 地址\n"); for (i = 0; i < n; i++) { printf("%-15s,%-9s,%-9d,%-20d,%-9s\n", (s + i)->name, (s + i)->sex, (s + i)->age, (s + i)->phone_number, (s + i)->address); } } else { printf("电话薄暂无数据\n"); } } int find_f(char name_f[20],struct data* s, int n) { int i = 0; int j = 0; for (i = 0; i < n; i++) { for(j=0;j<20;j++) { if (name_f[i] != s->name[i]) break; } if (j == 20) { return i; } } return -1; } int mod_m(struct data* s, int f) { int a1 = 0; while (1) { printf("要修改的是\n 1.性别 2.年龄 3.电话号码 4.地址 0.确认修改\n"); scanf_s("%d", &a1); switch (a1) { case 1: { printf("请输入更改值:"); scanf_s("%s", (s + f)->sex, 10); printf("修改成功\n"); break; } case 2: { printf("请输入更改值:"); scanf_s("%d", &((s + f)->age)); printf("修改成功\n"); break; } case 3: { printf("请输入更改值:"); scanf_s("%d", &((s + f)->phone_number)); printf("修改成功\n"); break; } case 4: { printf("请输入更改值:"); scanf_s("%s", (s + f)->address, 30); printf("修改成功\n"); break; } case 0: { printf("完成修改\n"); system("pause"); return 0; } } } } void del_d(struct data* s, int f, int n) { int i = 0; int j = 0; i = f; for (i; i < n; i++) { for (j = 0; j < 20; j++) { (s + i)->name[j] = (s + i + 1)->name[j]; } for (j = 0; j < 10; j++) { (s + i)->sex[j] = (s + i + 1)->sex[j]; } (s + i)->age = (s + i + 1)->age; (s + i)->phone_number = (s + i + 1)->phone_number; for (j = 0; j < 30; j++) { (s + i)->address[j] = (s + i + 1)->address[j]; } } } void sort_s(struct data* s,int n) { qsort(s, n, sizeof(struct data), struct_cmp); } int struct_cmp(const struct data* s1, const struct data* s2) { int i = 0; while (i < 20 && (s1->name[i] != '\0') && (s2->name[i] != '\0')) { if (s1->name[i] != s2->name[i]) { if (s1->name[i] > s2->name[i]) return 1; else if (s1->name[i] < s2->name[i]) return -1; } i++; } return 0; } void initial(FILE* pf, const struct data* s,int* n) { errno_t err1; err1 = fopen_s(&pf, "book.txt", "rb"); if (pf != NULL) { while(fread(s+(*n), sizeof(struct data), 1, pf)) { *n=(*n)+1; } fclose(pf); } else { perror("open file"); exit(1); } } <file_sep>#include<iostream> using std::cout; using std::cin; using std::endl; struct ListNode { int key; ListNode* next; }; class List { public: List() { head=new ListNode; head->key=0; head->next=NULL; last=head; } ~List() { ListNode* cur=head; while(head) { cur=head; head=cur->next; delete cur; } last=NULL; } void Add(int i) { ListNode* cur=new ListNode; cur->key=i; cur->next=NULL; last->next=cur; last=cur; return; } void Reverse_print() { List::Reverse(head->next); } void Print() { ListNode* cur=head->next; while(cur) { cout<<cur->key<<" "; cur=cur->next; } cout<<endl; } static void Reverse(ListNode* head) { if(head==NULL) return; Reverse(head->next); cout<<head->key<<" "; return; } private: //带头链表的头 ListNode* head; ListNode* last; }; int main() { List list; for(int i=0;i<5;i++) { list.Add(i+1); } list.Print(); list.Reverse_print(); cout<<endl; return 0; } <file_sep>#include<iostream> #include<vector> #include<unordered_map> #include<map> using std::cout; using std::endl; using std::cin; using std::unordered_map; using std::pair; int find_hash(int n,std::vector<int>& v) { unordered_map<int,int> hs; for(int i=0;i<n;i++) { if(v[i]<0||v[i]>=n) return -1; auto pos=hs.find(v[i]); if(pos==hs.end()) { hs.insert(pair<int,int>(v[i],1)); continue; } pos->second++; } auto it=hs.begin(); while(it!=hs.end()) { if(it->second!=1) return it->first; it++; } return -1; } //因为所有数都在0-n之内,可以将所有数放在下标对应的位置(合法下标),一定有位置满足条件的下标和其他合法下标是重复的,在比较时可发现重复。 int find_dup(int n,std::vector<int>& v) { int i=0; for(;i<n;) { if(v[i]<0||v[i]>=n) return -1; if(v[i]==i) { i++; continue; } int index=v[i]; if(v[index]==v[i]) return v[i]; int tmp=v[index]; v[index]=v[i]; v[i]=tmp; } return -1; } int main() { int n; std::vector<int> v; cin>>n; int i=0; while(i<n) { int a; cin>>a; v.push_back(a); i++; } int num=find_dup(n,v); cout<<num<<endl; return 0; } <file_sep>#pragma once #include"common.h" #include"thread_cache.h" #include"PageCache.h" void* ConcurrentAlloc(size_t size) { if (size > MAXBYTES) { int RoundSize = Sizeclass::_RoundUp(size, 1<<PAGE_SHIFT); int npage = RoundSize >> PAGE_SHIFT; Span* span = PageCache::GetInstance()->NewSpan(npage); return (void*)span->id; return malloc(size); } else { if (tls_threadcache == nullptr) { tls_threadcache = new ThreadCache; } return tls_threadcache->Allocate(size); } } void ConcurrentFree(void* ptr) { Span* span = PageCache::GetInstance()->MapObjectToSpan(ptr); size_t size = span->objsize; if (size > MAXBYTES) { /*return free(ptr);*/ PageCache::GetInstance()->ReleaseSpanToPageCache(span); } else { tls_threadcache->Deallocate(ptr, size); } } <file_sep>#include<iostream> #include<netinet/in.h> #include<sys/socket.h> #include<stdlib.h> #include<unistd.h> #include<arpa/inet.h> #include<sys/epoll.h> #include<vector> #include<string> using std::cout; using std::endl; using std::cerr; int StartTcp(int _port) { int sock=socket(AF_INET,SOCK_STREAM,0); if(sock<0) { cerr<<"sock error!"<<endl; return 1; } int opt=1; setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(void*)&opt,sizeof(int)); sockaddr_in addr; addr.sin_port=htons(_port); addr.sin_family=AF_INET; addr.sin_addr.s_addr=htonl(INADDR_ANY); if(bind(sock,(sockaddr*)&addr,sizeof(addr))) { cerr<<"bind error!"<<endl; return 2; } if(listen(sock,10)) { cerr<<"listen error"<<endl; return 3; } return sock; } void EpollServer() { int ser_sock=StartTcp(6060); int epoll_fd_=epoll_create(10); cout<<"epoll_fd is "<<epoll_fd_<<endl; epoll_event ev; ev.data.fd=ser_sock; ev.events=EPOLLIN; epoll_ctl(epoll_fd_,EPOLL_CTL_ADD,ser_sock,&ev); for(;;) { std::vector<int> _fd; epoll_event event[100]; _fd.clear(); int i = epoll_wait(epoll_fd_,event,sizeof(event)/sizeof(event[0]),-1); for(int j=0;j<i;j++) { //当受到一个新客户端连接请求 if(event[j].data.fd==ser_sock) { sockaddr_in cli_addr; socklen_t len=sizeof(cli_addr); epoll_event e; int cli_sock = accept(ser_sock,(sockaddr*)&cli_addr,&len); e.data.fd=cli_sock; e.events=EPOLLIN; epoll_ctl(epoll_fd_,EPOLL_CTL_ADD,cli_sock,&e); continue; } //当是其中一个客户端普通请求 else { char buf[10240]; ssize_t s = read(event[j].data.fd,buf,10240); if(s==0) { epoll_ctl(epoll_fd_,EPOLL_CTL_DEL,event[j].data.fd,NULL); cout<<"one client out!"<<endl; } else { cout<<buf<<endl; std::string rsp="HTTP/1.0 200 OK\r\n\r\n<html><h3>hallow new client!</h3></html>\r\n"; write(event[j].data.fd,rsp.c_str(),rsp.length()); epoll_ctl(epoll_fd_,EPOLL_CTL_DEL,event[j].data.fd,NULL); close(event[j].data.fd); cout<<"over"<<endl; } continue; } continue; } continue; } close(epoll_fd_); } int main() { EpollServer(); return 0; } <file_sep>#pragma once #include<iostream> #include<string> #include<vector> #include<unordered_map> using namespace std; class Solution { public: //给定只含 "I"(增大)或 "D"(减小)的字符串 S ,令 N = S.length。返回[0, 1, ..., N] 的任意排列 A 使得对于所有 i = 0, ..., N - 1,都有:1.如果 S[i] == "I",那么 A[i] < A[i + 1],2.如果 S[i] == "D",那么 A[i] > A[i + 1] vector<int> diStringMatch(string S) { vector<int> n; int max = S.size(); int min = 0; for (int i = 0; i < S.size(); i++){ if (i == S.size() - 1){ if (S[i] == 'I'){ n.push_back(min); n.push_back(max); } else{ n.push_back(max); n.push_back(min); } } else{ if (S[i] == 'I'){ n.push_back(min); min++; } else{ n.push_back(max); max--; } } } return n; } //给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。 //暴力解法,有缺陷 vector<int> findAnagrams_1(string s, string p) { int len = p.size(); vector<int> v; vector<int> arr; if (s.size() == 0 || s.size() < p.size()) return v; for (int i = 0; i < len; i++) { arr.push_back(0); } for (int i = 0; i <= s.size() - len; i++) { for (int j = i; j < i + len; j++) { for (int k = 0; k < len; k++) { if (s[j] == p[k] && arr[k] == 0) { arr[k] = 1; break; } } } int num = 0; for (int j = 0; j < len; j++) { num += arr[j]; } if (num == len) v.push_back(i); for (int i = 0; i < len; i++) { arr[i] = 0; } } return v; } //滑动窗口思想 vector<int> findAnagrams_2(string s, string p) { vector<int> v; int len = p.size(); int left = 0, right = 0; int num = 0; unordered_map<char, int> window; unordered_map<char, int> needs; for (int i = 0; i < len; i++) needs[p[i]]++; while (right < s.size()) { char c1 = s[right]; if (needs.count(c1)) { window[c1]++; if (window[c1] == needs[c1]) num++; } right++; while (num == needs.size()) { if (right - left == len) { v.push_back(left); } char c2 = s[left]; if (needs.count(c2)) { window[c2]--; if (window[c2] < needs[c2]) num--; } left++; } } return v; } };<file_sep>#include<iostream> #include<string> #include<string.h> using std::endl; using std::cout; using std::cin; using std::string; void Replace(char* str) { int num=0; int i=0; int len=strlen(str); for(;i<len;i++) { if(str[i] == ' ') num++; } num=num*2; int newlen = len+num; while(len!=newlen) { if(str[len-1]!=' ') { str[newlen-1]=str[len-1]; newlen--; len--; continue; } else { str[newlen-1]='0'; newlen--; str[newlen-1]='2'; newlen--; str[newlen-1]='%'; newlen--; len--; continue; } } } int main() { char str[100]; cout<<"please entry a string:"; //C/C++中cin和scanf以空格或回车作为空格符,当要在字符串中输入空格时,使用cin.getline()函数 cin.getline(str,100); Replace(str); cout<<"after replace :"<<str<<endl; return 0; } <file_sep>#pragma once #include"common.h" class PageCache { public: static PageCache* GetInstance() { return &Inst; } Span* NewSpan(size_t npage); Span* _NewSpan(size_t npage); //获得从对象到span的映射 Span* MapObjectToSpan(void* obj); //释放空间span回Pagecache,并合并相邻的span void ReleaseSpanToPageCache(Span* span); private: SpanList pagelist[NPAGES]; private: static PageCache Inst; PageCache() = default; PageCache(const PageCache&) = delete; PageCache& operator=(const PageCache&) = delete; std::mutex _mtx; std::map<PageID, Span*> _id_span_map; }; <file_sep>#include"common.h" #include"thread_cache.h" #include"central_cache.h" //向线程缓存申请内存 void* ThreadCache::Allocate(size_t size) { assert(size < MAXBYTES); size_t _size = Sizeclass::RoundUp(size); size_t _index = Sizeclass::Index(size); if (this->_freelist[_index].IsEmpty()) { return FetchFromCentralCache(_index, _size); } else { void* list = _freelist[_index].Pop(); return list; } } //向线程缓存释放内存 void ThreadCache::Deallocate(void* ptr, size_t size) { size_t _index = Sizeclass::Index(size); _freelist[_index].Push(ptr); //当自由链表对象超过一次批量申请的数量时 //开始回收对象到中心缓存 if (_freelist[_index].Size() >= _freelist[_index].MaxSize()) { ListTooLong(&_freelist[_index], size); } } //线程缓存向中心缓存申请内存 void* ThreadCache::FetchFromCentralCache(size_t index, size_t size) { //根据所申请的对象的大小和要的频率获得申请的数量 size_t num = min(Sizeclass::NumMoveSize(size),this->_freelist->MaxSize()); void* start, *end; size_t fetchnum = CentralCache::GetInstance()->FetchRangeObj(start, end, num, size); if (fetchnum > 1) { _freelist[index].PushRange(GetAddr(start), end, fetchnum - 1); } if(num==_freelist->MaxSize()) { _freelist->SetMaxSize(num + 1); } return start; } void ThreadCache::ListTooLong(FreeList* freelist, size_t size) { void* start = freelist->clear(); CentralCache::GetInstance()->ReleaseListToSpans(start, size); }<file_sep>#include "CommentConvert.h" void test(char *cn) { FILE * pfin = NULL; FILE * pfout = NULL; errno_t err1; errno_t err2; err1 = fopen_s(&pfin, cn, "r"); if (pfin == NULL) { perror("open file"); exit(EXIT_FAILURE); } err2 = fopen_s(&pfout, "D://比特科技//作业//Project22CommentConvert//haha//get.c", "w"); if (pfout == NULL) { perror("open file"); free(pfin); pfin = NULL; exit(EXIT_FAILURE); } CommentConvert(pfin, pfout); fclose(pfin); pfin = NULL; fclose(pfout); pfout = NULL; } int main() { long handle; struct _finddata_t find; char *cn; const char *ch = "D://比特科技//作业//Project22CommentConvert//haha//*.c"; handle = _findfirst(ch, &find); if (handle != -1) { cn = find.name; printf("%s", cn); /*test(cn);*/ } else return 0; while (!(_findnext(handle, &find))) { cn = find.name; test(cn); } _findclose(handle); printf("转换完成\n"); system("pause"); return 0; }<file_sep>#include"Test.h"<file_sep>#include<iostream> #include<stdlib.h> #include<string> #include<sys/socket.h> #include<sys/select.h> #include<arpa/inet.h> #include<netinet/in.h> #include<unistd.h> using std::cerr; using std::endl; using std::cout; #define INIT -1; int Strat(int port) { int sock; sock=socket(AF_INET,SOCK_STREAM,0); if(sock<0) { cerr<<"socket error"<<endl; exit(0); } sockaddr_in ser_addr; ser_addr.sin_family=AF_INET; ser_addr.sin_port=htons(port); ser_addr.sin_addr.s_addr=htonl(INADDR_ANY); if(bind(sock,(sockaddr*)&ser_addr,sizeof(ser_addr))) { cerr<<"bind error"<<endl; exit(1); } if(listen(sock,5)) { cerr<<"listen error"<<endl; exit(2); } cout<<"readly to work!"<<endl; return sock; } void InitFD_ADDR(int* addr) { for(int i=0;i<1024;i++) { addr[i]=INIT; } } void InputAddr(int sock,int& size,int& max_fd,int* fd_addr,fd_set* readfds) { FD_SET(sock,readfds); fd_addr[size]=sock; size++; for(int i=0;i<size;i++) { if(max_fd < fd_addr[i]) max_fd=fd_addr[i]; } } void DelAddr(int* fd_addr,int i,int& size,int& max_fd,fd_set* readfds) { FD_CLR(fd_addr[i],readfds); fd_addr[i]=fd_addr[size-1]; fd_addr[size-1]=INIT; size--; for(int i=0;i<size;i++) { if(max_fd < fd_addr[i]) max_fd=fd_addr[i]; } } void InitFds(int size,int* fd_addr,fd_set* readfds) { for(int i=0;i<size;i++) { FD_SET(fd_addr[i],readfds); } } int main() { int size=0; struct timeval time; time.tv_sec=10; time.tv_usec=0; int ser_sock=Strat(8888); int fd_addr[1024]; InitFD_ADDR(fd_addr); fd_addr[0]=ser_sock; size++; int max_fd=ser_sock; for(;;) { int sock; fd_set readfds; FD_ZERO(&readfds); InitFds(size,fd_addr,&readfds); int tmp=select(max_fd+1,&readfds,NULL,NULL,NULL); if(tmp>0) { for(int i=0;i<size;i++) { if(FD_ISSET(fd_addr[i],&readfds)) { if(fd_addr[i]==ser_sock) { struct sockaddr_in cli_addr; socklen_t len; sock=accept(ser_sock,(sockaddr*)&cli_addr,&len); cout<<"have a new link"<<endl; InputAddr(sock,size,max_fd,fd_addr,&readfds); continue; } else { char buf[10240]; ssize_t s=recv(fd_addr[i],buf,sizeof(buf),0); cout<<buf<<endl; std::string rsp="HTTP/1.0 200 OK\r\n\r\n<html><h3>hallow new client!</h3></html>\r\n"; send(fd_addr[i],rsp.c_str(),rsp.length(),0); DelAddr(fd_addr,i,size,max_fd,&readfds); continue; } } continue; } continue; } else if(tmp==0) { cout<<"time out!"<<endl; continue; } else { cerr<<"select error!"<<endl; continue; } } return 0; } <file_sep>#pragma once #pragma warning(disable:4996) #include<iostream> #include<stdio.h> #include<string.h> #define _CRT_SECURE_NO_WARNINGS using namespace std; typedef unsigned int size_t; class String { public: typedef char* iterator; public: String(const char* str = "") { if (str == nullptr) return; _size = strlen(str); _capacity = _size; _str = new char[_size + 1]; strcpy(_str, str); } String(const String& str) { if (&str == this) return; _size = str._size; _capacity = str._capacity; _str = new char[str._capacity + 1]; strcpy(_str, str._str); } String& operator=(const String& str) { if (&str == this) return *this; char* pstr = new char[str._capacity + 1]; strcpy(pstr, str._str); if(_str) delete[] _str; _str = pstr; _size = str._size; _capacity = str._capacity; return *this; } ~String() { if (_str) { delete[] _str; _str = nullptr; } } iterator Begin() { return _str; } iterator End() { return _str + _size; } void Push_Back(char c) { if (_size == _capacity) Reserve(2 * _capacity); _str[_size] = c; _size++; _str[_size] = '\0'; } void Append(size_t n, char c) { for (int i = 0; i < n; i++) { Push_Back(c); } } String& operator+=(char c) { Push_Back(c); return *this; } void Append(const char* str) { int len = strlen(str); if (len + _size >= _capacity) Reserve(2 * _capacity); for (int i = 0; i < len; i++) { _str[_size + i] = str[i]; } _size = _size + len; _str[_size] = '\0'; } void Clear() { _size = 0; _capacity = 0; if (_str) { delete[] _str; } } void Swap(String& str) { char* pstr = str._str; str._str = _str; _str = pstr; int num = str._size; str._size = _size; _size = num; num = str._capacity; str._capacity = _capacity; _capacity = num; } const char* C_STR()const { return _str; } size_t Size()const { return _size; } size_t Capacity()const { return _capacity; } bool Empty()const { if (_str == nullptr) return true; return false; } void Resize(size_t newsize, char c = char()) { if (newsize < _size) { _size = newsize; _str[_size] = '\0'; } else if (newsize > _size) { if (newsize >= _capacity) Reserve(2 * _capacity); for (int i = _size; i < newsize; i++) { _str[i] = c; } _str[newsize] = '\0'; } } void Reserve(size_t newCapacity) { if (newCapacity > _capacity) { char* pstr = new char[newCapacity + 1]; strcpy(pstr, _str); if(_str) delete[] _str; _str = pstr; _capacity = newCapacity; } } char& operator[](size_t index) { return _str[index]; } const char& operator[](size_t index)const { return _str[index]; } bool operator<(const String& str) { if (strcmp(_str, str._str) < 0) { return true; } return false; } bool operator<=(const String& str) { if (strcmp(_str, str._str) <= 0) { return true; } return false; } bool operator>(const String& str) { if (strcmp(_str, str._str) > 0) { return true; } return false; } bool operator>=(const String& str) { if (strcmp(_str, str._str) >= 0) { return true; } return false; } bool operator==(const String& str) { if (strcmp(_str, str._str) == 0) { return true; } return false; } bool operator!=(const String& str) { if (strcmp(_str, str._str) != 0) { return true; } return false; } //µعز»¸ِ size_t Find(char c, size_t pos = 0)const { for (int i = pos; i < _size; i++) { if (_str[i] == c) { return i; } } return -1; } size_t Find(const char* s, size_t pos = 0)const { for (int i = pos; i < _size; i++) { if (strcmp(_str, s) == 0) { return pos; } } return -1; } String SubStr(size_t pos, size_t n) { char* pstr = new char[n + 1]; for (int i = 0; i < n; i++) { pstr[i] = _str[pos + i]; } pstr[n] = '\0'; String str(pstr); return str; } String& Insert(size_t pos, char c) { if (_size + 1 >= _capacity) Reserve(_capacity * 2); for (int i = _size; i >= pos; i--) { _str[i + 1] = _str[i]; } _str[pos] = c; _size += 1; return *this; } String& Insert(size_t pos, const char* str) { int len = strlen(str); if (len + _size >= _capacity) Reserve(2 * (len + _size)); for (int i = _size; i >= (int)pos; i--) { _str[i + len] = _str[i]; } for (int i = 0; i < len; i++) { _str[pos + i] = str[i]; } _size = _size + len; return *this; } String& Erase(size_t pos, size_t len) { for (int i = pos; i < _size; i++) { if (i + len > _size) { _str[i - 1] = '\0'; break; } _str[i] = _str[i + len]; } _size = strlen(_str); return *this; } private: char* _str; size_t _size; size_t _capacity; }; <file_sep>#include "CommentConvert.h" void CommentConvert(FILE * pfin, FILE * pfout) { enum state s; s = nulstate; while (s != endstate) { switch (s) { case nulstate: { Donul(pfin, pfout, &s); break; } case cstate: { Doc(pfin, pfout, &s); break; } case cppstate: { Docpp(pfin, pfout, &s); break; } } } } void Donul(FILE *pfin, FILE *pfout, enum state* s) { int frist = getc(pfin); int second; switch (frist) { case '/': { second = getc(pfin); switch(second) { case '*': { putc('/', pfout); putc('/', pfout); *s = cstate; break; } case '/': { putc(frist, pfout); putc(frist, pfout); *s = cppstate; break; } default: { putc(frist, pfout); putc(frist, pfout); break; } } break; } case EOF: { *s = endstate; break; } default: { putc(frist, pfout); break; } } } void Doc(FILE *pfin, FILE *pfout, enum state* s) { int frist = getc(pfin); int second; int thirdly; int fourth; switch (frist) { case '*': { second = getc(pfin); switch (second) { case '/': { thirdly = getc(pfin); if (thirdly == '\n') { putc(thirdly, pfout); } else if (thirdly == '/') { fourth = getc(pfin); if (fourth == '*') { putc('\n', pfout); ungetc('*', pfin); ungetc('/', pfin); } else { ungetc(fourth, pfin); ungetc('/', pfin); } } else if (thirdly == EOF) { *s = endstate; } else { putc('\n', pfout); putc(thirdly, pfout); } *s = nulstate; break; } default: { ungetc(second, pfin); putc(frist, pfout); } } break; } case '\n': { putc(frist, pfout); putc('/', pfout); putc('/', pfout); break; } default: { putc(frist, pfout); break; } } } void Docpp(FILE *pfin, FILE *pfout, enum state* s) { int frist = getc(pfin); switch (frist) { case '\n': { putc(frist, pfout); *s = nulstate; break; } case EOF: { *s = endstate; break; } default: { putc(frist, pfout); break; } } }<file_sep>#include"String.h" int main() { String str_1 = "hallo"; String str_2("world!\n"); String str_3 = str_2.SubStr(0, 5); char str[] = "hahaha"; //str_1.Swap(str_2); //str_1 += 'h'; //str_2.Append(str); //str_1.Resize(3, 'h'); //str_2.Resize(10, 'h'); //cout << str_2.Find('d') << endl; str_1.Insert(0, str); str_1.Erase(0, 7); cout << str_1.C_STR() << endl; cout << str_2.C_STR() << endl; cout << str_3.C_STR() << endl; system("pause"); return 0; }<file_sep>#include "book.h" int main() { int i = 0; int a = 0; int n = 0; int b = 5; int f = 0; char name_f[20] = ""; FILE* pf = NULL; errno_t err; struct data* p = (struct data*)malloc(sizeof(struct data)*b); initial(pf, p, &n); while (1) { system("cls"); print(); scanf_s("%d", &a); system("cls"); switch (a) { case add: { if (n != b) { n = add_m(p, n); } else { b = b + 5; struct data* p2 = (struct data*) realloc(p, sizeof(struct data)*b); if (p2 != NULL) { struct data* p = p2; } n = add_m(p, n); } break; } case del: { printf("请输入要删除的人的名字:"); scanf_s("%s", name_f, 20); f = find_f(name_f, p, n); if (f != -1) { del_d(p, f, n); n = n - 1; printf("删除成功\n"); system("pause"); } else { printf("查无此人\n"); system("pause"); } break; } case find: { printf("请输入要查找的人的名字:"); scanf_s("%s", name_f, 20); f = find_f(name_f, p, n); if (f != -1) { printf("%-9s,%-9s,%-9d,%-9d,%-9s\n", (p + f)->name, (p + f)->sex, (p + f)->age, (p + f)->phone_number, (p + f)->address); } else { printf("\n查无此人\n\n"); } system("pause"); break; } case mod: { printf("请输入要修改的人的名字:"); scanf_s("%s", name_f, 20); f = find_f(name_f, p, n); if (f != -1) { mod_m(p, f); } else { printf("\n查无此人\n\n"); system("pause"); } break; } case show: { show_m(p, n); system("pause"); break; } case emp: { free(p); b = 5; n = 0; struct data* p = (struct data*)malloc(sizeof(struct data)*b); printf("清除成功\n"); break; } case sort: { sort_s(p, n); break; } case exi: { err = fopen_s(&pf, "book.txt", "wb"); if (pf != NULL) { fwrite((p + i), sizeof(struct data), n, pf); fclose(pf); } else { perror("open file"); exit(1); } free(p); p = NULL; return 0; } default: { printf("输入无效,即将返回上一步\n"); system("pause"); } } } }<file_sep>#pragma once #include"common.h" //考虑线程安全,采用单例模式 class CentralCache { public: static CentralCache* GetInstance() { return &Inst; } //从中心缓存取出一定量内存给线程缓存 size_t FetchRangeObj(void*& start, void*& end, size_t n, size_t byte); //将一定数量内存释放到span跨度 void ReleaseListToSpans(void* strat, size_t byte_size); Span* GetOneSpan(SpanList* spanlist, size_t size); private: SpanList spanlist[NLIST]; // private: static CentralCache Inst; CentralCache() = default; CentralCache(const CentralCache&) = delete; CentralCache& operator= (const CentralCache&) = delete; }; <file_sep>#ifndef __BOOK_H__ #define __BOOK_H__ #include <stdio.h> #include <string.h> #include <Windows.h> #include <assert.h> #include <stdlib.h> struct data { char name[20]; char sex[10]; short age; unsigned long int phone_number; char address[30]; }; enum choice { exi, add, del, find, mod, show, emp, sort }; void print(void); void show_m(struct data* s, int n); int add_m(struct data* s, int n); int find_f(char name_f[20], struct data* s, int n); int mod_m(struct data* s, int f); void del_d(struct data* s, int f, int n); void sort_s(struct data* s,int n); int struct_cmp(const struct data* s1, const struct data* s2); void initial(FILE* pf, const struct data* s, int* n); #endif // __BOOK_H__ <file_sep>#include"PageCache.h" PageCache PageCache::Inst; Span* PageCache::NewSpan(size_t npage) { //避免递归加锁 //std::unique_lock<std::mutex> lock(_mtx); //该位置正好有内存 _mtx.lock(); Span* span = _NewSpan(npage); _mtx.unlock(); return span; } Span* PageCache::_NewSpan(size_t npage) { //若申请页数比NPAGES多,直接申请一个相应大小的span给它 if (npage >= NPAGES) { void* ptr = VirtualAlloc(NULL, (npage) << PAGE_SHIFT, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); Span* newspan = new Span; newspan->id = (PageID)ptr >> PAGE_SHIFT; newspan->npage = npage; newspan->objsize = npage << PAGE_SHIFT; for (size_t i = 0; i < npage; i++) { _id_span_map[newspan->id + i] = newspan; } return newspan; } if (!pagelist[npage].Empty()) { return pagelist->PopFront(); } //向下遍历,找到有内存的位置,将内存进行重分配 for (size_t i = npage + 1; i < NPAGES; i++) { if (!pagelist[i].Empty()) { Span* span = pagelist[i].PopFront(); Span* newspan = new Span; newspan->id = span->id + span->npage - npage; newspan->npage = npage; span->npage -= npage; for (size_t i = 0; i < newspan->npage; i++) { _id_span_map[newspan->id + i] = newspan; } pagelist[span->npage].PushFront(span); //std::cout << "fengehou" << span->id<<std::endl; return newspan; } } //没有空余内存需要向系统申请内存 void* ptr = VirtualAlloc(NULL, (NPAGES - 1) << PAGE_SHIFT, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (ptr == nullptr) { throw std::bad_alloc(); } Span* largespan = new Span; largespan->id = (PageID)ptr >> PAGE_SHIFT; largespan->npage = NPAGES - 1; //建立映射关系 for (size_t i = 0; i < NPAGES; i++) { _id_span_map[largespan->id + i] = largespan; } pagelist[NPAGES - 1].PushFront(largespan); //std::cout << "diyicihuoqu" << largespan->id<<std::endl; return _NewSpan(npage); } Span* PageCache::MapObjectToSpan(void* obj) { //通过地址获得页号,一个页占4k PageID pageid = (PageID)obj >> PAGE_SHIFT; //通过页号找到span对象 auto it = _id_span_map.find(pageid); assert(it != _id_span_map.end()); return it->second; } void PageCache::ReleaseSpanToPageCache(Span* span) { std::unique_lock<std::mutex> lock(_mtx); if (span->npage >= NPAGES) { void* ptr = (void*)(span->id << PAGE_SHIFT); VirtualFree(ptr,0,MEM_RELEASE); _id_span_map.erase(span->id); delete span; return; } //找到参数前一个span auto previt = _id_span_map.find(span->id - 1); while (previt != _id_span_map.end()) { Span* prevspan = previt->second; //不是闲置的直接跳出 if (prevspan->usecount != 0) break; //合并超出NPAGES页的span也进行忽略 if (prevspan->npage + span->npage >= NPAGES) break; pagelist[prevspan->npage].Erase(prevspan); prevspan->npage += span->npage; delete span; span = prevspan; //找上一个span previt = _id_span_map.find(span->id - 1); } //找该span地址后面紧跟的span auto nextit = _id_span_map.find(span->id + span->npage); while (nextit != _id_span_map.end()) { Span* nextspan = nextit->second; if (nextspan->usecount != 0) break; if (nextspan->npage + span->npage >= NPAGES) break; pagelist[nextspan->npage].Erase(nextspan); span->npage += nextspan->npage; delete nextspan; //找下一个span nextit = _id_span_map.find(span->id+span->npage); } //建立新的映射关系 for (size_t i = 0; i < span->npage; ++i) { _id_span_map[span->id + i] = span; } //std::cout << "hebinghou" << span->id << std::endl; pagelist[span->npage].PushFront(span); } <file_sep>#ifndef __CommentConvert_H__ #define __CommentConvert_H__ #include <stdio.h> #include <string.h> #include <Windows.h> #include <assert.h> #include <stdlib.h> #include<io.h> enum state { nulstate, cstate, cppstate, endstate }; void test(char *cn); void CommentConvert(pfin, pfout); void Donul(FILE *pfin, FILE *pfout, enum state* s); void Doc(FILE *pfin, FILE *pfout, enum state* s); void Docpp(FILE *pfin, FILE *pfout, enum state* s); #endif // __CommentConvert_H__
78450e4c233ae887041936d95f268b9512089b26
[ "C", "C++" ]
24
C++
WyatWang/hahaha
e7e71cb006a49c07a83e7cf337ef299e9b005891
918ca6e332681fb4bcfeb60efdcb9232816c40a3
refs/heads/master
<repo_name>researchgate/unidriver<file_sep>/test-suite/src/index.ts import { UniDriver } from '@unidriver/core'; import { TestAppProps } from './test-app'; export type SetupFn = (data: TestAppProps) => Promise<{driver: UniDriver, tearDown: () => Promise<void>}>; export type TestSuiteParams = { setup: SetupFn; before?: () => Promise<void>, after?: () => Promise<void>, }; export {renderTestApp} from './test-app' export {startServer as startTestAppServer, getTestAppUrl} from './server'; export {runTestSuite} from './run-test-suite';
03579f0dbb5b1a66f918d3fe1f4022a274e59511
[ "TypeScript" ]
1
TypeScript
researchgate/unidriver
cf59c1a531c97374818a8d61825facc1bf10ec9b
dda198b319f933e8b9cabc9e5b374c9693787c88
refs/heads/master
<file_sep>// // Created by twer on 5/15/15. // #include "LengthUnit.h" #include "Length.h" const int CM_CON_FACTOR = 1; const int M_CON_FACTOR = 100; LengthUnit::LengthUnit(unsigned int _conversionFactor) : _conversionFactor(_conversionFactor) { } unsigned int LengthUnit::toAmountInBaseUnit(Amount amount) const { return amount * _conversionFactor; } LengthUnit LengthUnit::CM(CM_CON_FACTOR); LengthUnit LengthUnit::M(M_CON_FACTOR); <file_sep>// // Created by twer on 5/15/15. // #ifndef LENGTH_LENGTH_H #define LENGTH_LENGTH_H #include <iosfwd> #include <string> #include "LengthUnit.h" class Length { public: Length(Amount n); Length(Amount n, LengthUnit const &unit); Length(); public: bool operator == (const Length & other)const; private: Amount getAmountInBaseUnit()const; private: Amount _value; LengthUnit _unit; }; #endif //LENGTH_LENGTH_H <file_sep>#include <iostream> #include "../lib/gtest/gtest.h" using namespace std; #define TEST_SWITCH int main(int argc, char **argv) { #ifndef TEST_SWITCH return 0; #else testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); #endif }<file_sep>// // Created by twer on 5/15/15. // #include "LengthTest.h" #include "../src/Length.h" TEST_F(LengthTest, should_be_equal_when_compare_two_lengths) { Length lengthA; Length lengthB; ASSERT_TRUE(lengthA == lengthB); } TEST_F(LengthTest, should_be_equal_when_compare_two_lengths_with_same_length) { Length lengthA(100000); Length lengthB(100000); ASSERT_TRUE(lengthA == lengthB); } TEST_F(LengthTest, should_not_be_equal_when_compare_two_lengths_with_different_length) { Length lengthA(1000); Length lengthB(100000); ASSERT_FALSE(lengthA == lengthB); } TEST_F(LengthTest, should_be_equal_when_compare_two_lengths_with_same_length_and_unit) { Length lengthA(2, LengthUnit::CM); Length lengthB(2, LengthUnit::CM); ASSERT_TRUE(lengthA == lengthB); } TEST_F(LengthTest, should_not_be_equal_when_compare_two_lengths_with_same_length_and_different_unit) { Length lengthA(2, LengthUnit::M); Length lengthB(2, LengthUnit::CM); ASSERT_FALSE(lengthA == lengthB); } TEST_F(LengthTest, should_not_be_equal_when_compare_two_lengths_with_different_length_and_same_unit) { Length lengthA(2, LengthUnit::CM); Length lengthB(1, LengthUnit::CM); ASSERT_FALSE(lengthA == lengthB); } TEST_F(LengthTest, should_not_be_equal_when_compare_two_lengths_with_different_length_and_different_unit) { Length lengthA(1, LengthUnit::M); Length lengthB(2, LengthUnit::CM); ASSERT_FALSE(lengthA == lengthB); } TEST_F(LengthTest, should_be_equal_when_compare_two_length_with_same_logic_length_but_with_different_unit) { Length lengthA(1, LengthUnit::M); Length lengthB(100, LengthUnit::CM); ASSERT_TRUE(lengthA == lengthB); } TEST_F(LengthTest, should_not_be_equal_when_compare_two_length_with_different_logic_length) { Length lengthA(2 , LengthUnit::M); Length lengthB(100, LengthUnit::CM); ASSERT_FALSE(lengthA == lengthB); }<file_sep>// // Created by twer on 5/15/15. // #ifndef LENGTH_LENGTHTEST_H #define LENGTH_LENGTHTEST_H #include "../lib/gtest/gtest.h" class LengthTest: public ::testing::Test { }; #endif //LENGTH_LENGTHTEST_H <file_sep>cmake_minimum_required(VERSION 3.1) project(length) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") set(GTEST_FILES lib/gtest/gtest.h) set(GMOCK_FILES lib/gmock/gmock.h lib/gmock-gtest-all.cc) set(SOURCE_FILES src/main.cpp) add_executable(length ${SOURCE_FILES} ${GTEST_FILES} ${GMOCK_FILES} test/LengthTest.cpp test/LengthTest.h src/Length.cpp src/Length.h src/LengthUnit.cpp src/LengthUnit.h)<file_sep>// // Created by twer on 5/15/15. // #ifndef LENGTH_LENGTHUNIT_H #define LENGTH_LENGTHUNIT_H typedef unsigned int Amount; class LengthUnit { public: LengthUnit(unsigned int _conversionFactor); unsigned int toAmountInBaseUnit(Amount amount) const; public: static LengthUnit CM; static LengthUnit M; private: unsigned int _conversionFactor; }; #endif //LENGTH_LENGTHUNIT_H <file_sep>// // Created by twer on 5/15/15. // #include "Length.h" bool Length::operator == (const Length &other)const { return getAmountInBaseUnit() == other.getAmountInBaseUnit(); } Amount Length::getAmountInBaseUnit()const { return _unit.toAmountInBaseUnit(_value); } Length::Length(Amount n) :Length(n, LengthUnit::M){ } Length::Length():Length(0) { } Length::Length(Amount n, LengthUnit const &unit) : _value(n), _unit(unit) { }
9c24daa956d82721441237c6c8739fb6ae2f271e
[ "CMake", "C++" ]
8
C++
dwpplayer/LengthCpp
e807525b3019edad9fca70d8169dddb75edb311f
f312b73d2c17b4a13e0c7e3aec8095b0504bb3f8
refs/heads/master
<file_sep>## 1 - saveRDS nrOfRows <- 1e7 x <- data.frame( Integers = 1:nrOfRows, # integer Logicals = sample(c(TRUE, FALSE, NA), nrOfRows, replace = TRUE), # logical Text = factor(sample(state.name , nrOfRows, replace = TRUE)), # text Numericals = runif(nrOfRows, 0.0, 100), # numericals stringsAsFactors = FALSE) head(x) tail(x) ## Gravando com saveRDS comprimido tw_saveRDS <- system.time({ saveRDS(x, "c:/R/Github/saveRDS.rds") }) tw_saveRDS ## Gravando saveRDS não comprimido tw_saveRDS_nc <- system.time({ saveRDS(x, "c:/R/Github/saveRDS_nc.rds", compress = F) }) tw_saveRDS_nc ## Lendo saveRDS comprimido tr_saveRDS <- system.time({ readRDS("c:/R/Github/saveRDS.rds") }) ## Lendo saveRDS não comprimido tr_saveRDS_nc <- system.time({ readRDS("c:/R/Github/saveRDS_nc.rds") }) tw_saveRDS tw_saveRDS_nc tr_saveRDS tr_saveRDS_nc ## ----------------------------------------------------- ## ## 2 - feather install.packages("feather") library(feather) ## Gravando com feather tw_feather <- system.time({ write_feather(x, "c:/R/Github/feather.feather") }) tw_feather ## Lendo com feather tr_feather <- system.time({ read_feather("c:/R/Github/feather.feather") }) tr_feather ## Lendo alguns registros com feather a <- feather("c:/R/Github/feather.feather") b <- a[5000:6000, 1:3] b ## ----------------------------------------------------- ## ## 3 - fst install.packages("fst") library(fst) # Gravando fst tw_fst <- system.time ({ write.fst(x, "c:/R/Github/datafst.fst") }) tw_fst ## Lendo fst tr_fst <- system.time ({ a <- read.fst("c:/R/Github/datafst.fst") }) tr_fst head(a) tail(b) ## Lendo alguns registros com fst tr_fst_slice <- system.time ({ b <- read.fst("c:/R/Github/datafst.fst", c("Logicals", "Text"), 2000, 4990) }) tr_fst_slice b head(b) tail(b) ## -------------------------------------------------------------------- ## ## Gravando com fwrite library(data.table) tw_fwrite <- system.time ({ fwrite(x, "c:/R/Github/fwrite.csv") }) tw_fwrite ## Lendo com fread tr_fread <- system.time ({ fread("c:/R/Github/fwrite.csv") }) tr_fread ## -------------------------------------------------------------------- ## ## Conclusão ## ## - Use sempre saveRDS e readRDS, se precisar de velocidade, salve com o argumento compress = FALSE para não comprimir o arquivo. ## - Se você for ler a base em python ou Julia e quiser um formato padronizado, use o feather. ## - Se você for realmente ler e escrever os seus dados muitas vezes e você precisar de velocidade, use o fst, mas tome cuidado com os valores com formato date. <file_sep># 3 formas de ler e gravar data frames ## Criando um dataframe para as leituras e gravações nrOfRows <- 1e7 x <- data.frame( Integers = 1:nrOfRows, # integer Logicals = sample(c(TRUE, FALSE, NA), nrOfRows, replace = TRUE), # logical Text = factor(sample(state.name , nrOfRows, replace = TRUE)), # text Numericals = runif(nrOfRows, 0.0, 100), # numericals stringsAsFactors = FALSE) head(x) tail(x) # 1 - saveRDS ## Gravando com saveRDS comprimido tw_saveRDS <- system.time({ saveRDS(x, "c:/R/Github/saveRDS.rds") }) tw_saveRDS ## Gravando saveRDS não comprimido tw_saveRDS_nc <- system.time({ saveRDS(x, "c:/R/Github/saveRDS_nc.rds", compress = F) }) tw_saveRDS_nc ## Lendo saveRDS comprimido tr_saveRDS <- system.time({ readRDS("c:/R/Github/saveRDS.rds") }) ## Lendo saveRDS não comprimido tr_saveRDS_nc <- system.time({ readRDS("c:/R/Github/saveRDS_nc.rds") }) tw_saveRDS tw_saveRDS_nc tr_saveRDS tr_saveRDS_nc # 2 - feather install.packages("feather") library(feather) ## Gravando com feather tw_feather <- system.time({ write_feather(x, "c:/R/Github/feather.feather") }) tw_feather ## Lendo com feather tr_feather <- system.time({ read_feather("c:/R/Github/feather.feather") }) tr_feather ## Lendo alguns registros com feather a <- feather("c:/R/Github/feather.feather") b <- a[5000:6000, 1:3] b # 3 - fst install.packages("fst") library(fst) ## Gravando fst tw_fst <- system.time ({ write.fst(x, "c:/R/Github/datafst.fst") }) tw_fst ## Lendo fst tr_fst <- system.time ({ a <- read.fst("c:/R/Github/datafst.fst") }) tr_fst head(a) tail(b) ## Lendo alguns registros com fst tr_fst_slice <- system.time ({ b <- read.fst("c:/R/Github/datafst.fst", c("Logicals", "Text"), 2000, 4990) }) tr_fst_slice b head(b) tail(b) # 4 - fwrite e fread ## Gravando com fwrite library(data.table) tw_fwrite <- system.time ({ fwrite(x, "c:/R/Github/fwrite.csv") }) tw_fwrite ## Lendo com fread tr_fread <- system.time ({ fread("c:/R/Github/fwrite.csv") }) tr_fread ![estatisticas de leituras e gravacoes de data frames](https://user-images.githubusercontent.com/25511099/28483487-e87a18da-6e43-11e7-87c3-f2cc9ae1fae1.jpg) # Conclusão ## 1 - Use sempre saveRDS e readRDS, se precisar de velocidade, salve com o argumento compress = FALSE para não comprimir o arquivo. ## 2 - Se você for ler a base em python ou Julia e quiser um formato padronizado, use o feather. ## 3 - Se você for realmente ler e escrever os seus dados muitas vezes e você precisar de velocidade, use o fst, mas tome cuidado com os valores com formato date.
723f239e88cb761830c3bc9fcc3a3d95898e4411
[ "Markdown", "R" ]
2
R
leonafonte/write_read_data_frames
7df5337447a70cae82342984dfcda77b601945f1
e01d2439a01318df0096231530ec4b23faf4d7c7
refs/heads/master
<repo_name>meMuhammadkamal/CurrencyConverter<file_sep>/CurrencyConverter/Screens/Converter/ConvertViewController.swift // // ViewController.swift // CurrencyConverter // // Created by <NAME> on 11/23/19. // Copyright © 2019 SwensonHe. All rights reserved. // import UIKit import IQKeyboardManager class ConvertViewController: BaseViewController,ConvertInteractor { @IBOutlet weak var eurValueField: UITextField! @IBOutlet weak var baseCurrencyValue: UILabel! @IBOutlet weak var equivlantValueLbl: UILabel! @IBOutlet weak var convertedValelbl: UILabel! var convertToCurrency:String? var baseCurrency:String? var convertPresenterImpl:ConvertPresenterImpl! override func viewDidLoad() { super.viewDidLoad() convertPresenterImpl = ConvertPresenterImpl(convertInteractor: self) if let currency = convertToCurrency , let base = baseCurrency{ equivlantValueLbl.text = currency baseCurrencyValue.text = base } eurValueField.keyboardToolbar.doneBarButton.setTarget(self, action: #selector(doneButtonClicked)) } func convertSuccess(convertResult:ConvertedCurrecny) { dismissProgressDialog() if let result = convertResult.result { convertedValelbl.text = result.description }else{ showAlert(message: "Something went wrong!") } } @objc func doneButtonClicked(_ sender: Any) { showProgressDialog() if let convertToCurrency = convertToCurrency , let eur = eurValueField.text{ let params = ["from":Constants.BASE_CURRENCY,"to":convertToCurrency,"amount":eur] as [String : Any] convertPresenterImpl.start(params: params) } } func convertError(message: String) { dismissProgressDialog() showAlert(message: message) } override func viewDidDisappear(_ animated: Bool) { convertPresenterImpl.stop() } } <file_sep>/CurrencyConverter/Screens/Rates/RatesViewController.swift // // ViewController.swift // CurrencyConverter // // Created by <NAME> on 11/23/19. // Copyright © 2019 SwensonHe. All rights reserved. // import UIKit class ViewController: BaseViewController,RatesInteractor,UITableViewDelegate,UITableViewDataSource { var rates:[Rate] = [] var latest: LatestRates? @IBOutlet weak var baseCurrencyLbl: UILabel! @IBOutlet weak var ratesTable: UITableView! var ratesPresenterImpl:RatesPresenterImpl! override func viewDidLoad() { super.viewDidLoad() rates = [Rate]() ratesTable.register(UINib(nibName: "Rates", bundle: nil), forCellReuseIdentifier: "rateCell") ratesTable.delegate = self ratesTable.dataSource = self ratesPresenterImpl = RatesPresenterImpl(ratesInteractor: self) ratesPresenterImpl.start() showProgressDialog() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "rateCell") as? RatesTableViewCell{ cell.configureCell(rate: rates[indexPath.row]) return cell }else{ return UITableViewCell() } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "showConverter", sender: self) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return rates.count } override func viewDidDisappear(_ animated: Bool) { ratesPresenterImpl.stop() } func ratesSuccess(latest: LatestRates) { dismissProgressDialog() self.latest = latest baseCurrencyLbl.text = latest.base if let aud = latest.rates?.aUD?.description, let cad = latest.rates?.cAD?.description, let mxn = latest.rates?.mXN?.description, let pln = latest.rates?.pLN?.description, let usd = latest.rates?.uSD?.description { var rate = Rate() rate.rate = aud rate.currency = latest.rates?.AUD var rate1 = Rate() rate1.rate = cad rate1.currency = latest.rates?.CAD var rate2 = Rate() rate2.rate = mxn rate2.currency = latest.rates?.MXN var rate3 = Rate() rate3.rate = pln rate3.currency = latest.rates?.PLN var rate4 = Rate() rate4.rate = usd rate4.currency = latest.rates?.USD rates.append(rate) rates.append(rate1) rates.append(rate2) rates.append(rate3) rates.append(rate4) } ratesTable.reloadData() } func ratesError(message: String) { dismissProgressDialog() showAlert(message: message) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "showConverter") { let indexPath = self.ratesTable.indexPathForSelectedRow let rate = rates[(indexPath?.row)!] if let convertViewController = segue.destination as? ConvertViewController{ convertViewController.convertToCurrency = rate.currency convertViewController.baseCurrency = latest?.base } } } } <file_sep>/CurrencyConverter/Screens/Rates/RatesModel.swift // // RatesModel.swift // CurrencyConverter // // Created by <NAME> on 11/23/19. // Copyright © 2019 SwensonHe. All rights reserved. // import Foundation import Alamofire class RatesModel: ConnectionStatus { var ratesPresenter:RatesPresenter? init(ratesPresenter:RatesPresenter) { self.ratesPresenter = ratesPresenter ApiManager.sharedInstance.setConnectionListener(connectionStatus: self) } func onSuccess(response: Data, path: String) { if let presenter = ratesPresenter,path == Constants.LATEST{ let jsonDecoder = JSONDecoder() let latesetRates = try? jsonDecoder.decode(LatestRates.self, from: response) if let latest=latesetRates{ presenter.ratesSuccess(latest: latest) } } } func onError(error: String, path: String) { if path == Constants.LATEST , let presenter = ratesPresenter{ presenter.ratesError(message: error) } } func start() { ApiManager.sharedInstance.getRequst(path:getLatestURL() ,flag:Constants.LATEST , method: HTTPMethod.get){ } } func start(params: [String : Any]) { } func stop() { ApiManager.sharedInstance.cancelRequest() } func getLatestURL()->String{ return Constants.LATEST + Constants.API_KEY + Constants.CURRENCY_SYMBOLS + Constants.CURRENCY_FORMAT } } <file_sep>/CurrencyConverter/Screens/Base/BaseViewController.swift // // BaseViewController.swift // CurrencyConverter // // Created by <NAME> on 11/23/19. // Copyright © 2019 SwensonHe. All rights reserved. // import UIKit import SVProgressHUD class BaseViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } func showAlert(message:String){ let alert = AlertView() alert.showAlert(vc: self, message: message) } func showProgressDialog(){ SVProgressHUD.show() } func dismissProgressDialog(){ SVProgressHUD.dismiss() } } <file_sep>/CurrencyConverter/Screens/Converter/ConvertModel.swift // // convertModel.swift // CurrencyConverter // // Created by <NAME> on 11/23/19. // Copyright © 2019 SwensonHe. All rights reserved. // import Foundation import Alamofire class ConvertModel: ConnectionStatus { var convertPresenter:ConvertPresenter? init(convertPresenter:ConvertPresenter) { self.convertPresenter = convertPresenter ApiManager.sharedInstance.setConnectionListener(connectionStatus: self) } func onSuccess(response: Data, path: String) { if let presenter = convertPresenter,path == Constants.CONVERT{ let jsonDecoder = JSONDecoder() let convertedCurrency = try? jsonDecoder.decode(ConvertedCurrecny.self, from: response) if let convertedCurrency=convertedCurrency{ presenter.convertSuccess(convertResult: convertedCurrency) } } } func start(params: [String : Any]) { ApiManager.sharedInstance.getRequst(path: getConvertURL(from: params["from"] as! String,to: params["to"] as! String,amount: params["amount"] as! String), flag: Constants.CONVERT, method: HTTPMethod.get){ } } func onError(error: String, path: String) { if path == Constants.CONVERT , let presenter = convertPresenter{ presenter.convertError(message: error) } } func start() { } func stop() { ApiManager.sharedInstance.cancelRequest() } func getConvertURL(from:String,to:String,amount:String)->String{ return Constants.CONVERT + Constants.API_KEY + Constants.FROM + from + Constants.AND + Constants.TO + to + Constants.AND + Constants.AMOUNT + amount } } <file_sep>/CurrencyConverter/Screens/Rates/RatesTableViewCell.swift // // RatesTableViewCell.swift // CurrencyConverter // // Created by <NAME> on 11/23/19. // Copyright © 2019 SwensonHe. All rights reserved. // import UIKit class RatesTableViewCell: UITableViewCell { @IBOutlet weak var currencyLbl: UILabel! @IBOutlet weak var ratelbl: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } func configureCell(rate:Rate){ ratelbl.text = rate.rate currencyLbl.text = rate.currency } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } <file_sep>/CurrencyConverter/Network/ApiManager.swift // // ApiManager.swift // Parts // // Created by <NAME> on 5/24/17. // Copyright © 2017 <NAME>. All rights reserved. // import Foundation import Alamofire import UIKit class ApiManager { var connectionStatus:ConnectionStatus! var request:Request? static let sharedInstance = ApiManager() typealias RequestCompleted = () -> () init() { } func setConnectionListener(connectionStatus:ConnectionStatus) { self.connectionStatus = connectionStatus } func getRequst(path:String,flag:String,method:HTTPMethod,completed:@escaping RequestCompleted){ if (CheckNetwork.isInternetAvailable()){ var headers:HTTPHeaders = [:] headers = ["Content-Type":"application/json"] print("URL \(Constants.BASE_URL)\(path)") request = AF.request("\(Constants.BASE_URL)\(path)", method: method, parameters: nil , encoding: JSONEncoding.prettyPrinted, headers: headers).responseString { [unowned self] response in debugPrint(response) switch response.result { case .success: if let data = response.data{ self.connectionStatus.onSuccess(response:data ,path: flag) }else{ self.connectionStatus.onError(error: "Something went wrong!", path: flag) } case let .failure(error): self.connectionStatus.onError(error: error.errorDescription ?? "",path:flag) } completed() } }else{ self.connectionStatus.onError(error:"No internet Connection!" , path: path) } } func apiRequst(param params:Parameters,path:String,method:HTTPMethod,completed:@escaping RequestCompleted){ if (CheckNetwork.isInternetAvailable()){ var headers:HTTPHeaders = [:] headers = ["Content-Type":"application/json"] print("URL \(Constants.BASE_URL)\(path)") request = AF.request("\(Constants.BASE_URL)\(path)", method: method, parameters: params , encoding: JSONEncoding.prettyPrinted, headers: headers).responseString { [unowned self] response in debugPrint(response) switch response.result { case .success: if let data = response.data{ self.connectionStatus.onSuccess(response:data ,path: path) }else{ self.connectionStatus.onError(error: "Something went wrong!", path: path) } case let .failure(error): self.connectionStatus.onError(error: error.errorDescription ?? "",path:path) } completed() } }else{ self.connectionStatus.onError(error:"No internet Connection!" , path: path) } } func cancelRequest(){ if let request = request{ request.cancel() } } func nullToNil(value : AnyObject?) -> String? { if value is NSNull { return nil } else { return value as? String } } } <file_sep>/CurrencyConverter/Entities/Rate.swift // // Rate.swift // CurrencyConverter // // Created by <NAME> on 11/23/19. // Copyright © 2019 SwensonHe. All rights reserved. // import Foundation struct Rate { var rate:String? var currency:String? } <file_sep>/CurrencyConverter/Screens/Converter/ConvertContract.swift // // RatesContract.swift // CurrencyConverter // // Created by <NAME> on 11/23/19. // Copyright © 2019 SwensonHe. All rights reserved. // import Foundation protocol ConvertPresenter { func convertSuccess(convertResult:ConvertedCurrecny) func convertError(message:String) func start() func start(params:[String:Any]) func stop() } protocol ConvertInteractor { func convertSuccess(convertResult:ConvertedCurrecny) func convertError(message:String) } <file_sep>/CurrencyConverter/Screens/Base/BaseContract.swift // // BaseContract.swift // CurrencyConverter // // Created by <NAME> on 11/23/19. // Copyright © 2019 SwensonHe. All rights reserved. // import Foundation protocol ConnectionStatus { func onSuccess(response:Data,path:String) func onError(error:String,path:String) func start() func start(params:[String:Any]) func stop() } <file_sep>/CurrencyConverter/Utilites/CheckNetwork.swift // // CheckNetwork.swift // Masarat // // Created by <NAME> on 2/6/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation import SystemConfiguration import UIKit class CheckNetwork { static func isInternetAvailable() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) } } var flags = SCNetworkReachabilityFlags() if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) { return false } let isReachable = flags.contains(.reachable) let needsConnection = flags.contains(.connectionRequired) return (isReachable && !needsConnection) } } extension UIColor { convenience init(hex: String) { let scanner = Scanner(string: hex) scanner.scanLocation = 0 var rgbValue: UInt64 = 0 scanner.scanHexInt64(&rgbValue) let r = (rgbValue & 0xff0000) >> 16 let g = (rgbValue & 0xff00) >> 8 let b = rgbValue & 0xff self.init( red: CGFloat(r) / 0xff, green: CGFloat(g) / 0xff, blue: CGFloat(b) / 0xff, alpha: 1 ) } } public enum ColourParsingError: Error { case invalidInput(String) } <file_sep>/CurrencyConverter/Utilites/AlertView.swift // // AlertView.swift // Masarat // // Created by <NAME> on 2/6/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation import UIKit class AlertView { func showAlert(vc:UIViewController,message:String){ let alert = UIAlertController(title: "Alert", message: message, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil)) vc.present(alert, animated: true, completion: nil) } } extension String { var localized: String { return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "") } } <file_sep>/CurrencyConverter/Screens/Rates/RatesPresenterImpl.swift // // RatesPresenterImpl.swift // CurrencyConverter // // Created by <NAME> on 11/23/19. // Copyright © 2019 SwensonHe. All rights reserved. // import Foundation class RatesPresenterImpl:RatesPresenter { var ratesInteractor:RatesInteractor? var ratesModel:RatesModel! init(ratesInteractor:RatesInteractor) { self.ratesInteractor = ratesInteractor ratesModel = RatesModel(ratesPresenter: self) } func start() { ratesModel.start() } func stop() { ratesModel.stop() } func ratesSuccess(latest: LatestRates) { if let ratesInteractor = ratesInteractor{ ratesInteractor.ratesSuccess(latest: latest) } } func ratesError(message: String) { if let ratesInteractor = ratesInteractor{ ratesInteractor.ratesError(message: message) } } } <file_sep>/Questions.playground/Contents.swift import UIKit var sum = (3 + 1) * (9/3) func fibonacciIterative(n: Int) { var f1=1, f2=1, fib=0 for i in 3...n { fib = f1 + f2 print("Fi: \(i) = \(fib)") f1 = f2 f2 = fib } } func fibonacciRecursion(n: Int) -> Int { if (n == 0){ return 0 } else if (n == 1) { return 1 } return fibonacciRecursion(n: n-1) + fibonacciRecursion(n: n-2) } fibonacciIterative(n: 9) fibonacciRecursion(n: 9) func anagramCheck(firstString: String, secondString: String) -> Bool { let first = firstString as NSString let second = secondString as NSString let length = first.length guard length == second.length else { return false } var firstDic = [unichar:Int]() var secondDic = [unichar:Int]() for i in 0..<length { let c = first.character(at: i) firstDic[c] = (firstDic[c] ?? 0) + 1 } for i in 0..<length { let c = second.character(at: i) let count = (secondDic[c] ?? 0) + 1 if count > firstDic[c] ?? 0 { return false } secondDic[c] = count } return true } anagramCheck(firstString: "bad credit", secondString: "debit card") <file_sep>/CurrencyConverter/Entities/Convert.swift // // Convert.swift // CurrencyConverter // // Created by <NAME> on 11/23/19. // Copyright © 2019 SwensonHe. All rights reserved. // import Foundation struct ConvertedCurrecny : Codable { let success : Bool? let query : Query? let info : Info? let historical : String? let date : String? let result : Double? enum CodingKeys: String, CodingKey { case success = "success" case query = "query" case info = "info" case historical = "historical" case date = "date" case result = "result" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) success = try values.decodeIfPresent(Bool.self, forKey: .success) query = try values.decodeIfPresent(Query.self, forKey: .query) info = try values.decodeIfPresent(Info.self, forKey: .info) historical = try values.decodeIfPresent(String.self, forKey: .historical) date = try values.decodeIfPresent(String.self, forKey: .date) result = try values.decodeIfPresent(Double.self, forKey: .result) } } <file_sep>/CurrencyConverter/Entities/LatestRates.swift // // LatestRates.swift // CurrencyConverter // // Created by <NAME> on 11/23/19. // Copyright © 2019 SwensonHe. All rights reserved. // import Foundation struct LatestRates:Codable { let success : Bool? let timestamp : Int? let base : String? let date : String? let rates : Rates? enum CodingKeys: String, CodingKey { case success = "success" case timestamp = "timestamp" case base = "base" case date = "date" case rates = "rates" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) success = try values.decodeIfPresent(Bool.self, forKey: .success) timestamp = try values.decodeIfPresent(Int.self, forKey: .timestamp) base = try values.decodeIfPresent(String.self, forKey: .base) date = try values.decodeIfPresent(String.self, forKey: .date) rates = try values.decodeIfPresent(Rates.self, forKey: .rates) } struct Rates : Codable { let uSD : Double? let aUD : Double? let cAD : Double? let pLN : Double? let mXN : Double? let USD : String? let AUD: String? let CAD : String? let PLN : String? let MXN : String? enum CodingKeys: String, CodingKey { case uSD = "USD" case aUD = "AUD" case cAD = "CAD" case pLN = "PLN" case mXN = "MXN" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) uSD = try values.decodeIfPresent(Double.self, forKey: .uSD) aUD = try values.decodeIfPresent(Double.self, forKey: .aUD) cAD = try values.decodeIfPresent(Double.self, forKey: .cAD) pLN = try values.decodeIfPresent(Double.self, forKey: .pLN) mXN = try values.decodeIfPresent(Double.self, forKey: .mXN) USD = CodingKeys.uSD.rawValue AUD = CodingKeys.aUD.rawValue CAD = CodingKeys.cAD.rawValue PLN = CodingKeys.pLN.rawValue MXN = CodingKeys.mXN.rawValue } } } <file_sep>/CurrencyConverter/Utilites/Constants.swift // // Constants.swift // CurrencyConverter // // Created by <NAME> on 11/23/19. // Copyright © 2019 SwensonHe. All rights reserved. // import Foundation struct Constants { static let BASE_URL = "http://data.fixer.io/api/" static let CONVERT = "convert?" static let LATEST = "latest?" static let FROM = "from=" static let TO = "to=" static let AND = "&" static let AMOUNT = "amount=" static let ACCESS_KEY = "access_key=" static let KEY = "<KEY>" static let API_KEY = ACCESS_KEY + KEY //Limited for free plan static let BASE_CURRENCY = "EUR" static let SYMBOLS = "symbols=" static let SYMBOLS_VALUE = "USD,AUD,CAD,PLN,MXN&" static let CURRENCY_SYMBOLS = SYMBOLS + SYMBOLS_VALUE static let FORMAT = "format=" static let FORMAT_VALUE = "1" static let CURRENCY_FORMAT = FORMAT + FORMAT_VALUE } <file_sep>/CurrencyConverter/Screens/Converter/ConvertPresenterImpl.swift // // convertPresenterImpl.swift // CurrencyConverter // // Created by <NAME> on 11/23/19. // Copyright © 2019 SwensonHe. All rights reserved. // import Foundation class ConvertPresenterImpl:ConvertPresenter { var convertInteractor:ConvertInteractor? var convertModel:ConvertModel! init(convertInteractor:ConvertInteractor) { self.convertInteractor = convertInteractor convertModel = ConvertModel(convertPresenter: self) } func start() { } func start(params: [String : Any]) { convertModel.start(params: params) } func stop() { convertModel.stop() } func convertSuccess(convertResult:ConvertedCurrecny) { if let convertInteractor = convertInteractor{ convertInteractor.convertSuccess(convertResult:convertResult) } } func convertError(message: String) { if let convertInteractor = convertInteractor{ convertInteractor.convertError(message: message) } } } <file_sep>/CurrencyConverter/Screens/Rates/RatesContract.swift // // RatesContract.swift // CurrencyConverter // // Created by <NAME> on 11/23/19. // Copyright © 2019 SwensonHe. All rights reserved. // import Foundation protocol RatesPresenter { func ratesSuccess(latest:LatestRates) func ratesError(message:String) func start() func stop() } protocol RatesInteractor { func ratesSuccess(latest:LatestRates) func ratesError(message:String) }
b46359abd164ea6a1dd24472d9c2ffc3f80994c4
[ "Swift" ]
19
Swift
meMuhammadkamal/CurrencyConverter
68b5f698d5e21e342aec43ce789a8d1da7aee0bb
566e5c776b6a029371593606ffe29ae8ab99af55
refs/heads/master
<repo_name>LazyZhu/azure-http-proxy<file_sep>/src/http_proxy_server_config.cpp /* * http_proxy_server_config.cpp: * * Copyright (C) 2013-2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #include <memory> #include <fstream> #ifdef _WIN32 #include <Windows.h> #else extern "C" { #include <unistd.h> #include <sys/types.h> #include <pwd.h> } #endif #include "authentication.hpp" #include "encrypt.hpp" #include "http_proxy_server_config.hpp" #include "jsonxx/jsonxx.h" namespace azure_proxy { http_proxy_server_config::http_proxy_server_config() { } bool http_proxy_server_config::load_config(const std::string& config_data) { bool rollback = true; std::shared_ptr<bool> auto_rollback(&rollback, [this](bool* rollback) { if (*rollback) { this->config_map.clear(); authentication::get_instance().remove_all_users(); } }); jsonxx::Object json_obj; if (!json_obj.parse(config_data)) { std::cerr << "Failed to parse config" << std::endl; return false; } if (json_obj.has<jsonxx::String>("bind_address")) { this->config_map["bind_address"] = std::string(json_obj.get<jsonxx::String>("bind_address")); } else { this->config_map["bind_address"] = std::string("0.0.0.0"); } if (json_obj.has<jsonxx::Number>("listen_port")) { this->config_map["listen_port"] = static_cast<unsigned short>(json_obj.get<jsonxx::Number>("listen_port")); } else { this->config_map["listen_port"] = static_cast<unsigned short>(8090); } if (!json_obj.has<jsonxx::String>("rsa_private_key")) { std::cerr << "Could not find \"rsa_private_key\" in config or it's value is not a string" << std::endl; return false; } const std::string& rsa_private_key = json_obj.get<jsonxx::String>("rsa_private_key"); try { rsa rsa_pri(rsa_private_key); if (rsa_pri.modulus_size() < 128) { std::cerr << "Must use RSA keys of at least 1024 bits" << std::endl; return false; } } catch (const std::exception&) { std::cerr << "The value of rsa_private_key is bad" << std::endl; return false; } this->config_map["rsa_private_key"] = rsa_private_key; if (json_obj.has<jsonxx::Number>("timeout")) { int timeout = static_cast<int>(json_obj.get<jsonxx::Number>("timeout")); this->config_map["timeout"] = static_cast<unsigned int>(timeout < 30 ? 30 : timeout); } else { this->config_map["timeout"] = 240ul; } if (json_obj.has<jsonxx::Number>("workers")) { int threads = static_cast<int>(json_obj.get<jsonxx::Number>("workers")); this->config_map["workers"] = static_cast<unsigned int>(threads < 1 ? 1 : (threads > 16 ? 16 : threads)); } else { this->config_map["workers"] = 4ul; } if (json_obj.has<jsonxx::Boolean>("auth")) { this->config_map["auth"] = json_obj.get<jsonxx::Boolean>("auth"); if (!json_obj.has<jsonxx::Array>("users")) { std::cerr << "Could not find \"users\" in config or it's value is not a array" << std::endl; return false; } const jsonxx::Array& users_array = json_obj.get<jsonxx::Array>("users"); for (size_t i = 0; i < users_array.size(); ++i) { if (!users_array.has<jsonxx::Object>(i) || !users_array.get<jsonxx::Object>(i).has<jsonxx::String>("username") || !users_array.get<jsonxx::Object>(i).has<jsonxx::String>("username")) { std::cerr << "The value of \"users\" contains unexpected element" << std::endl; return false; } authentication::get_instance().add_user(users_array.get<jsonxx::Object>(i).get<jsonxx::String>("username"), users_array.get<jsonxx::Object>(i).get<jsonxx::String>("password")); } } else { this->config_map["auth"] = false; } rollback = false; return true; } bool http_proxy_server_config::load_config() { std::string config_data; #ifdef _WIN32 wchar_t path_buffer[MAX_PATH]; if (GetModuleFileNameW(NULL, path_buffer, MAX_PATH) == 0 || GetLastError() == ERROR_INSUFFICIENT_BUFFER) { std::cerr << "Failed to get retrieve the path of the executable file" << std::endl; } std::wstring config_file_path(path_buffer); config_file_path.resize(config_file_path.find_last_of(L'\\') + 1); config_file_path += L"server.json"; std::shared_ptr<std::remove_pointer<HANDLE>::type> config_file_handle( CreateFileW(config_file_path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL), [](HANDLE native_handle) { if (native_handle != INVALID_HANDLE_VALUE) { CloseHandle(native_handle); } }); if (config_file_handle.get() == INVALID_HANDLE_VALUE) { std::cerr << "Failed to open config file \"server.json\"" << std::endl; return false; } char ch; DWORD size_read = 0; BOOL read_result = ReadFile(config_file_handle.get(), &ch, 1, &size_read, NULL); while (read_result != FALSE && size_read != 0) { config_data.push_back(ch); read_result = ReadFile(config_file_handle.get(), &ch, 1, &size_read, NULL); } if (read_result == FALSE) { std::cerr << "Failed to read data from config file" << std::endl; return false; } #else auto bufsize = sysconf(_SC_GETPW_R_SIZE_MAX); if (bufsize == -1) { bufsize = 16384; } std::unique_ptr<char[]> buf(new char[bufsize]); passwd pwd, *result = nullptr; getpwuid_r(getuid(), &pwd, buf.get(), bufsize, &result); if (result == nullptr) { return false; } std::string config_path = pwd.pw_dir; config_path += "/.ahps/server.json"; std::ifstream ifile(config_path.c_str()); if (!ifile.is_open()) { std::cerr << "Failed to open \"" << config_path << "\"" << std::endl; return false; } char ch; while (ifile.get(ch)) { config_data.push_back(ch); } #endif return this->load_config(config_data); } const std::string& http_proxy_server_config::get_bind_address() const { return this->get_config_value<const std::string&>("bind_address"); } unsigned short http_proxy_server_config::get_listen_port() const { return this->get_config_value<unsigned short>("listen_port"); } const std::string& http_proxy_server_config::get_rsa_private_key() const { return this->get_config_value<const std::string&>("rsa_private_key"); } unsigned int http_proxy_server_config::get_timeout() const { return this->get_config_value<unsigned int>("timeout"); } unsigned int http_proxy_server_config::get_workers() const { return this->get_config_value<unsigned int>("workers"); } bool http_proxy_server_config::enable_auth() const { return this->get_config_value<bool>("auth"); } http_proxy_server_config& http_proxy_server_config::get_instance() { static http_proxy_server_config instance; return instance; } } // namespace azure_proxy <file_sep>/src/http_proxy_server.hpp /* * http_proxy_server.hpp: * * Copyright (C) 2013-2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #ifndef AZURE_HTTP_PROXY_SERVER_HPP #define AZURE_HTTP_PROXY_SERVER_HPP #include <boost/asio.hpp> namespace azure_proxy { class http_proxy_server { boost::asio::io_service& io_service; boost::asio::ip::tcp::acceptor acceptor; public: http_proxy_server(boost::asio::io_service& io_service); void run(); private: void start_accept(); }; } // namespace azure_proxy #endif <file_sep>/src/http_proxy_client.hpp /* * http_proxy_client.hpp: * * Copyright (C) 2013-2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #ifndef AZURE_HTTP_PROXY_CLIENT_HPP #define AZURE_HTTP_PROXY_CLIENT_HPP #include <boost/asio.hpp> namespace azure_proxy { class http_proxy_client { boost::asio::io_service& io_service; boost::asio::ip::tcp::acceptor acceptor; public: http_proxy_client(boost::asio::io_service& io_service); void run(); private: void start_accept(); }; } // namespace azure_proxy #endif <file_sep>/src/http_proxy_server_connection_context.hpp /* * http_proxy_server_connection_context.hpp: * * Copyright (C) 2013-2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #ifndef AZURE_HTTP_PROXY_SERVER_CONNECTION_CONTEXT_HPP #define AZURE_HTTP_PROXY_SERVER_CONNECTION_CONTEXT_HPP #include <cstdint> #include <boost/asio.hpp> #include <boost/optional.hpp> #include "http_chunk_checker.hpp" namespace azure_proxy { enum class proxy_connection_state { read_cipher_data, resolve_origin_server_address, connect_to_origin_server, tunnel_transfer, read_http_request_header, write_http_request_header, read_http_request_content, write_http_request_content, read_http_response_header, write_http_response_header, read_http_response_content, write_http_response_content, report_connection_established, report_error }; struct http_proxy_server_connection_context { proxy_connection_state connection_state; bool reconnect_on_error; std::string origin_server_name; unsigned short origin_server_port; boost::optional<boost::asio::ip::tcp::endpoint> origin_server_endpoint; }; struct http_proxy_server_connection_read_request_context { bool is_proxy_client_keep_alive; boost::optional<std::uint64_t> content_length; std::uint64_t content_length_has_read; boost::optional<http_chunk_checker> chunk_checker; }; struct http_proxy_server_connection_read_response_context { bool is_origin_server_keep_alive; boost::optional<std::uint64_t> content_length; std::uint64_t content_length_has_read; boost::optional<http_chunk_checker> chunk_checker; }; } // namespace azure_proxy #endif <file_sep>/src/http_proxy_client_connection.cpp /* * http_proxy_client_connection.cpp: * * Copyright (C) 2013-2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #include <algorithm> #include <cstring> #include <utility> #include "http_proxy_client_config.hpp" #include "http_proxy_client_connection.hpp" #include "http_proxy_client_stat.hpp" #include "key_generator.hpp" namespace azure_proxy { http_proxy_client_connection::http_proxy_client_connection(boost::asio::ip::tcp::socket&& ua_socket) : strand(ua_socket.get_io_service()), user_agent_socket(std::move(ua_socket)), proxy_server_socket(this->user_agent_socket.get_io_service()), resolver(this->user_agent_socket.get_io_service()), connection_state(proxy_connection_state::ready), timer(this->user_agent_socket.get_io_service()), timeout(std::chrono::seconds(http_proxy_client_config::get_instance().get_timeout())) { http_proxy_client_stat::get_instance().increase_current_connections(); } http_proxy_client_connection::~http_proxy_client_connection() { http_proxy_client_stat::get_instance().decrease_current_connections(); } std::shared_ptr<http_proxy_client_connection> http_proxy_client_connection::create(boost::asio::ip::tcp::socket&& ua_socket) { return std::shared_ptr<http_proxy_client_connection>(new http_proxy_client_connection(std::move(ua_socket))); } void http_proxy_client_connection::start() { std::array<unsigned char, 86> cipher_info_raw; cipher_info_raw.fill(0); // 0 ~ 2 cipher_info_raw[0] = 'A'; cipher_info_raw[1] = 'H'; cipher_info_raw[2] = 'P'; // 3 zero // 4 zero // 5 cipher code // 0x00 aes-128-cfb // 0x01 aes-128-cfb8 // 0x02 aes-128-cfb1 // 0x03 aes-128-ofb // 0x04 aes-128-ctr // 0x05 aes-192-cfb // 0x06 aes-192-cfb8 // 0x07 aes-192-cfb1 // 0x08 aes-192-ofb // 0x09 aes-192-ctr // 0x0A aes-256-cfb // 0x0B aes-256-cfb8 // 0x0C aes-256-cfb1 // 0x0D aes-256-ofb // 0x0E aes-256-ctr unsigned char cipher_code = 0; const auto& cipher_name = http_proxy_client_config::get_instance().get_cipher(); if (cipher_name.size() > 7 && std::equal(cipher_name.begin(), cipher_name.begin() + 3, "aes")) { // aes std::vector<unsigned char> ivec(16); std::vector<unsigned char> key_vec; assert(cipher_name[3] == '-' && cipher_name[7] == '-'); if (std::strcmp(cipher_name.c_str() + 8, "cfb") == 0 || std::strcmp(cipher_name.c_str() + 8, "cfb128") == 0) { // aes-xxx-cfb if (std::equal(cipher_name.begin() + 4, cipher_name.begin() + 7, "128")) { cipher_code = 0x00; key_vec.resize(128 / 8); } else if (std::equal(cipher_name.begin() + 4, cipher_name.begin() + 7, "192")) { cipher_code = 0x05; key_vec.resize(192 / 8); } else { cipher_code = 0x0A; key_vec.resize(256 / 8); } key_generator::get_instance().generate(ivec.data(), ivec.size()); key_generator::get_instance().generate(key_vec.data(), key_vec.size()); this->encryptor = std::unique_ptr<stream_encryptor>(new aes_cfb128_encryptor(key_vec.data(), key_vec.size() * 8, ivec.data())); this->decryptor = std::unique_ptr<stream_decryptor>(new aes_cfb128_decryptor(key_vec.data(), key_vec.size() * 8, ivec.data())); } else if (std::strcmp(cipher_name.c_str() + 8, "cfb8") == 0) { // aes-xxx-cfb8 if (std::equal(cipher_name.begin() + 4, cipher_name.begin() + 7, "128")) { cipher_code = 0x01; key_vec.resize(128 / 8); } else if (std::equal(cipher_name.begin() + 4, cipher_name.begin() + 7, "192")) { cipher_code = 0x06; key_vec.resize(192 / 8); } else { cipher_code = 0x0B; key_vec.resize(256 / 8); } key_generator::get_instance().generate(ivec.data(), ivec.size()); key_generator::get_instance().generate(key_vec.data(), key_vec.size()); this->encryptor = std::unique_ptr<stream_encryptor>(new aes_cfb8_encryptor(key_vec.data(), key_vec.size() * 8, ivec.data())); this->decryptor = std::unique_ptr<stream_decryptor>(new aes_cfb8_decryptor(key_vec.data(), key_vec.size() * 8, ivec.data())); } else if (std::strcmp(cipher_name.c_str() + 8, "cfb1") == 0) { // aes-xxx-cfb1 if (std::equal(cipher_name.begin() + 4, cipher_name.begin() + 7, "128")) { cipher_code = 0x02; key_vec.resize(128 / 8); } else if (std::equal(cipher_name.begin() + 4, cipher_name.begin() + 7, "192")) { cipher_code = 0x07; key_vec.resize(192 / 8); } else { cipher_code = 0x0C; key_vec.resize(256 / 8); } key_generator::get_instance().generate(ivec.data(), ivec.size()); key_generator::get_instance().generate(key_vec.data(), key_vec.size()); this->encryptor = std::unique_ptr<stream_encryptor>(new aes_cfb1_encryptor(key_vec.data(), key_vec.size() * 8, ivec.data())); this->decryptor = std::unique_ptr<stream_decryptor>(new aes_cfb1_decryptor(key_vec.data(), key_vec.size() * 8, ivec.data())); } else if (std::strcmp(cipher_name.c_str() + 8, "ofb") == 0) { // aes-xxx-ofb if (std::equal(cipher_name.begin() + 4, cipher_name.begin() + 7, "128")) { cipher_code = 0x03; key_vec.resize(128 / 8); } else if (std::equal(cipher_name.begin() + 4, cipher_name.begin() + 7, "192")) { cipher_code = 0x08; key_vec.resize(192 / 8); } else { cipher_code = 0x0D; key_vec.resize(256 / 8); } key_generator::get_instance().generate(ivec.data(), ivec.size()); key_generator::get_instance().generate(key_vec.data(), key_vec.size()); this->encryptor = std::unique_ptr<stream_encryptor>(new aes_ofb128_encryptor(key_vec.data(), key_vec.size() * 8, ivec.data())); this->decryptor = std::unique_ptr<stream_decryptor>(new aes_ofb128_decryptor(key_vec.data(), key_vec.size() * 8, ivec.data())); } else if (std::strcmp(cipher_name.c_str() + 8, "ctr") == 0) { // aes-xxx-ctr if (std::equal(cipher_name.begin() + 4, cipher_name.begin() + 7, "128")) { cipher_code = 0x04; key_vec.resize(128 / 8); } else if (std::equal(cipher_name.begin() + 4, cipher_name.begin() + 7, "192")) { cipher_code = 0x09; key_vec.resize(192 / 8); } else { cipher_code = 0x0E; key_vec.resize(256 / 8); } std::fill(ivec.begin(), ivec.end(), 0); key_generator::get_instance().generate(key_vec.data(), key_vec.size()); this->encryptor = std::unique_ptr<stream_encryptor>(new aes_ctr128_encryptor(key_vec.data(), key_vec.size() * 8, ivec.data())); this->decryptor = std::unique_ptr<stream_decryptor>(new aes_ctr128_decryptor(key_vec.data(), key_vec.size() * 8, ivec.data())); } // 7 ~ 22 ivec // 23 ~ key std::copy(ivec.cbegin(), ivec.cend(), cipher_info_raw.begin() + 7); std::copy(key_vec.cbegin(), key_vec.cend(), cipher_info_raw.begin() + 23); } if (!this->encryptor || !this->decryptor) { return; } // 5 cipher code cipher_info_raw[5] = static_cast<char>(cipher_code); // 6 zero rsa rsa_pub(http_proxy_client_config::get_instance().get_rsa_public_key()); if (rsa_pub.modulus_size() < 128) { return; } this->encrypted_cipher_info.resize(rsa_pub.modulus_size()); if(this->encrypted_cipher_info.size() != rsa_pub.encrypt(cipher_info_raw.size(), cipher_info_raw.data(), this->encrypted_cipher_info.data(), rsa_padding::pkcs1_oaep_padding)) { return; } auto self(this->shared_from_this()); boost::asio::ip::tcp::resolver::query query(http_proxy_client_config::get_instance().get_proxy_server_address(), std::to_string(http_proxy_client_config::get_instance().get_proxy_server_port())); this->connection_state = proxy_connection_state::resolve_proxy_server_address; this->set_timer(); this->resolver.async_resolve(query, [this, self](const boost::system::error_code& error, boost::asio::ip::tcp::resolver::iterator iterator) { if (this->cancel_timer()) { if (!error) { this->connection_state = proxy_connection_state::connecte_to_proxy_server; this->set_timer(); this->proxy_server_socket.async_connect(*iterator, this->strand.wrap([this, self](const boost::system::error_code& error) { if (this->cancel_timer()) { if (!error) { this->on_connection_established(); } else { this->on_error(error); } } })); } else { this->on_error(error); } } }); } void http_proxy_client_connection::async_read_data_from_user_agent() { auto self(this->shared_from_this()); this->set_timer(); this->user_agent_socket.async_read_some(boost::asio::buffer(this->upgoing_buffer_read.data(), this->upgoing_buffer_read.size()), this->strand.wrap([this, self](const boost::system::error_code& error, std::size_t bytes_transferred) { if (this->cancel_timer()) { if (!error) { http_proxy_client_stat::get_instance().on_upgoing_recv(static_cast<std::uint32_t>(bytes_transferred)); this->encryptor->encrypt(reinterpret_cast<const unsigned char*>(&this->upgoing_buffer_read[0]), reinterpret_cast<unsigned char*>(&this->upgoing_buffer_write[0]), bytes_transferred); this->async_write_data_to_proxy_server(this->upgoing_buffer_write.data(), 0, bytes_transferred); } else { this->on_error(error); } } })); } void http_proxy_client_connection::async_read_data_from_proxy_server(bool set_timer) { auto self(this->shared_from_this()); if (set_timer) { this->set_timer(); } this->proxy_server_socket.async_read_some(boost::asio::buffer(this->downgoing_buffer_read.data(), this->downgoing_buffer_read.size()), this->strand.wrap([this, self](const boost::system::error_code& error, std::size_t bytes_transferred) { if (this->cancel_timer()) { if (!error) { http_proxy_client_stat::get_instance().on_downgoing_recv(static_cast<std::uint32_t>(bytes_transferred)); this->decryptor->decrypt(reinterpret_cast<const unsigned char*>(&this->downgoing_buffer_read[0]), reinterpret_cast<unsigned char*>(&this->downgoing_buffer_write[0]), bytes_transferred); this->async_write_data_to_user_agent(this->downgoing_buffer_write.data(), 0, bytes_transferred); } else { this->on_error(error); } } })); } void http_proxy_client_connection::async_write_data_to_user_agent(const char* write_buffer, std::size_t offset, std::size_t size) { auto self(this->shared_from_this()); this->set_timer(); this->user_agent_socket.async_write_some(boost::asio::buffer(write_buffer + offset, size), this->strand.wrap([this, self, write_buffer, offset, size](const boost::system::error_code& error, std::size_t bytes_transferred) { if (this->cancel_timer()) { if (!error) { http_proxy_client_stat::get_instance().on_downgoing_send(static_cast<std::uint32_t>(bytes_transferred)); if (bytes_transferred < size) { this->async_write_data_to_user_agent(write_buffer, offset + bytes_transferred, size - bytes_transferred); } else { this->async_read_data_from_proxy_server(); } } else { this->on_error(error); } } })); } void http_proxy_client_connection::async_write_data_to_proxy_server(const char* write_buffer, std::size_t offset, std::size_t size) { auto self(this->shared_from_this()); this->set_timer(); this->proxy_server_socket.async_write_some(boost::asio::buffer(write_buffer + offset, size), this->strand.wrap([this, self, write_buffer, offset, size](const boost::system::error_code& error, std::size_t bytes_transferred) { if (this->cancel_timer()) { if (!error) { http_proxy_client_stat::get_instance().on_upgoing_send(static_cast<std::uint32_t>(bytes_transferred)); if (bytes_transferred < size) { this->async_write_data_to_proxy_server(write_buffer, offset + bytes_transferred, size - bytes_transferred); } else { this->async_read_data_from_user_agent(); } } else { this->on_error(error); } } }) ); } void http_proxy_client_connection::set_timer() { if (this->timer.expires_from_now(this->timeout) != 0) { assert(false); } auto self(this->shared_from_this()); this->timer.async_wait(this->strand.wrap([this, self](const boost::system::error_code& error) { if (error != boost::asio::error::operation_aborted) { this->on_timeout(); } })); } bool http_proxy_client_connection::cancel_timer() { std::size_t ret = this->timer.cancel(); assert(ret <= 1); return ret == 1; } void http_proxy_client_connection::on_connection_established() { this->async_write_data_to_proxy_server(reinterpret_cast<const char*>(this->encrypted_cipher_info.data()), 0, this->encrypted_cipher_info.size()); this->async_read_data_from_proxy_server(false); } void http_proxy_client_connection::on_error(const boost::system::error_code& error) { this->cancel_timer(); boost::system::error_code ec; if (this->proxy_server_socket.is_open()) { this->proxy_server_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); this->proxy_server_socket.close(ec); } if (this->user_agent_socket.is_open()) { this->user_agent_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); this->user_agent_socket.close(ec); } } void http_proxy_client_connection::on_timeout() { if (this->connection_state == proxy_connection_state::resolve_proxy_server_address) { this->resolver.cancel(); } else { boost::system::error_code ec; if (this->proxy_server_socket.is_open()) { this->proxy_server_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); this->proxy_server_socket.close(ec); } if (this->user_agent_socket.is_open()) { this->user_agent_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); this->user_agent_socket.close(ec); } } } } // namespace azure_proxy <file_sep>/src/http_proxy_client_main.cpp /* * http_proxy_client_main.cpp: * * Copyright (C) 2013-2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #include <iostream> #include <boost/asio.hpp> #include "http_proxy_client.hpp" #include "http_proxy_client_stat.hpp" #include "http_proxy_client_config.hpp" int main() { using namespace azure_proxy; try { auto& config = http_proxy_client_config::get_instance(); if (config.load_config()) { std::cout << "Azure Http Proxy Client" << std::endl; std::cout << "server address: " << config.get_proxy_server_address() << ':' << config.get_proxy_server_port() << std::endl; std::cout << "local address: " << config.get_bind_address() << ':' << config.get_listen_port() << std::endl; std::cout << "cipher: " << config.get_cipher() << std::endl; boost::asio::io_service io_service; http_proxy_client_stat::get_instance().start_stat(io_service); http_proxy_client client(io_service); client.run(); } } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } } <file_sep>/src/http_proxy_client_connection.hpp /* * http_proxy_client_connection.hpp: * * Copyright (C) 2013-2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #ifndef AZURE_HTTP_PROXY_CLIENT_CONNECTION_HPP #define AZURE_HTTP_PROXY_CLIENT_CONNECTION_HPP #include <array> #include <chrono> #include <memory> #include <vector> #include <boost/asio.hpp> #include "encrypt.hpp" const std::size_t BUFFER_LENGTH = 2048; namespace azure_proxy { class http_proxy_client_connection : public std::enable_shared_from_this<http_proxy_client_connection> { enum class proxy_connection_state { ready, resolve_proxy_server_address, connecte_to_proxy_server, tunnel_transfer }; private: boost::asio::io_service::strand strand; boost::asio::ip::tcp::socket user_agent_socket; boost::asio::ip::tcp::socket proxy_server_socket; boost::asio::ip::tcp::resolver resolver; proxy_connection_state connection_state; boost::asio::basic_waitable_timer<std::chrono::steady_clock> timer; std::vector<unsigned char> encrypted_cipher_info; std::array<char, BUFFER_LENGTH> upgoing_buffer_read; std::array<char, BUFFER_LENGTH> upgoing_buffer_write; std::array<char, BUFFER_LENGTH> downgoing_buffer_read; std::array<char, BUFFER_LENGTH> downgoing_buffer_write; std::unique_ptr<stream_encryptor> encryptor; std::unique_ptr<stream_decryptor> decryptor; std::chrono::seconds timeout; private: http_proxy_client_connection(boost::asio::ip::tcp::socket&& ua_socket); public: ~http_proxy_client_connection(); static std::shared_ptr<http_proxy_client_connection> create(boost::asio::ip::tcp::socket&& ua_socket); void start(); private: void async_read_data_from_user_agent(); void async_read_data_from_proxy_server(bool set_timer = true); void async_write_data_to_user_agent(const char* write_buffer, std::size_t offset, std::size_t size); void async_write_data_to_proxy_server(const char* write_buffer, std::size_t offset, std::size_t size); void set_timer(); bool cancel_timer(); void on_connection_established(); void on_error(const boost::system::error_code& error); void on_timeout(); }; } // namespace azure_proxy #endif <file_sep>/src/http_header_parser.cpp /* * http_header_parser.cpp: * * Copyright (C) 2013-2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #include <iterator> #include <boost/regex.hpp> #include "http_header_parser.hpp" namespace azure_proxy { http_request_header::http_request_header() : _port(80) { } const std::string& http_request_header::method() const { return this->_method; } const std::string& http_request_header::scheme() const { return this->_scheme; } const std::string& http_request_header::host() const { return this->_host; } unsigned short http_request_header::port() const { return this->_port; } const std::string& http_request_header::path_and_query() const { return this->_path_and_query; } const std::string& http_request_header::http_version() const { return this->_http_version; } boost::optional<std::string> http_request_header::get_header_value(const std::string& name) const { auto iter = this->_headers_map.find(name); if (iter == this->_headers_map.end()) { return boost::none; } return std::get<1>(*iter); } std::size_t http_request_header::erase_header(const std::string& name) { return this->_headers_map.erase(name); } const http_headers_container& http_request_header::get_headers_map() const { return this->_headers_map; } http_response_header::http_response_header() { } const std::string& http_response_header::http_version() const { return this->_http_version; } unsigned int http_response_header::status_code() const { return this->_status_code; } const std::string& http_response_header::status_description() const { return this->_status_description; } boost::optional<std::string> http_response_header::get_header_value(const std::string& name) const { auto iter = this->_headers_map.find(name); if (iter == this->_headers_map.end()) { return boost::none; } return std::get<1>(*iter); } std::size_t http_response_header::erase_header(const std::string& name) { return this->_headers_map.erase(name); } const http_headers_container& http_response_header::get_headers_map() const { return this->_headers_map; } http_headers_container http_header_parser::parse_headers(std::string::const_iterator begin, std::string::const_iterator end) { http_headers_container headers; auto is_digit = [](char ch) -> bool { return '0' <= ch && ch <= '9'; }; auto is_alpha = [](char ch) -> bool { return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z'); }; auto is_token_char = [&is_alpha, &is_digit](char ch) -> bool { return is_alpha(ch) || is_digit(ch) || ( ch == '!' || ch == '#' || ch == '$' || ch == '%' || ch == '&' || ch == '\'' || ch == '`' || ch == '*' || ch == '+' || ch == '-' || ch == '.' || ch == '^' || ch == '_' || ch == '|' || ch == '~'); }; enum class parse_header_state { header_field_name_start, header_field_name, header_field_value_left_ows, header_field_value, header_field_cr, header_field_crlf, header_field_crlfcr, header_compelete, header_parse_failed }; parse_header_state state = parse_header_state::header_field_name_start; std::string header_field_name; std::string header_field_value; for (std::string::const_iterator iter = begin; iter != end && state != parse_header_state::header_compelete && state != parse_header_state::header_parse_failed; ++iter) { switch (state) { case parse_header_state::header_field_name_start: if (is_token_char(*iter)) { header_field_name.push_back(*iter); state = parse_header_state::header_field_name; } else if (iter == begin && *iter == '\r') { state = parse_header_state::header_field_crlfcr; } else { state = parse_header_state::header_parse_failed; } break; case parse_header_state::header_field_name: if (is_token_char(*iter) || *iter == ' ') { header_field_name.push_back(*iter); } else if (*iter == ':') { state = parse_header_state::header_field_value_left_ows; } else { state = parse_header_state::header_parse_failed; } break; case parse_header_state::header_field_value_left_ows: if (*iter == ' ' || *iter == '\t') { continue; } else if (*iter == '\r') { state = parse_header_state::header_field_cr; } else { header_field_value.push_back(*iter); state = parse_header_state::header_field_value; } break; case parse_header_state::header_field_value: if (*iter == '\r') { state = parse_header_state::header_field_cr; } else { header_field_value.push_back(*iter); } break; case parse_header_state::header_field_cr: if (*iter == '\n') { state = parse_header_state::header_field_crlf; } else { state = parse_header_state::header_parse_failed; } break; case parse_header_state::header_field_crlf: if (*iter == ' ' || *iter == '\t') { header_field_value.push_back(*iter); state = parse_header_state::header_field_value; } else { while (!header_field_name.empty() && (header_field_name[header_field_name.size() - 1] == ' ')) { header_field_name.resize(header_field_name.size() - 1); } assert(!header_field_name.empty()); while (!header_field_value.empty() && (header_field_value[header_field_value.size() - 1] == ' ' || (header_field_value[header_field_value.size() - 1] == '\t'))) { header_field_value.resize(header_field_value.size() - 1); } headers.insert(std::make_pair(std::move(header_field_name), std::move(header_field_value))); if (*iter == '\r') { state = parse_header_state::header_field_crlfcr; } else if (is_token_char(*iter)) { header_field_name.push_back(*iter); state = parse_header_state::header_field_name; } else { state = parse_header_state::header_parse_failed; } } break; case parse_header_state::header_field_crlfcr: if (*iter == '\n') { state = parse_header_state::header_compelete; } break; default: assert(false); } } if (state != parse_header_state::header_compelete) { throw std::runtime_error("failed to parse"); } return headers; } boost::optional<http_request_header> http_header_parser::parse_request_header(std::string::const_iterator begin, std::string::const_iterator end) { auto iter = begin; auto tmp = iter; for (;iter != end && *iter != ' ' && *iter != '\r'; ++iter) ; if (iter == tmp || iter == end || *iter != ' ') return boost::none; http_request_header header; header._method = std::string(tmp, iter); tmp = ++iter; for (;iter != end && *iter != ' ' && *iter != '\r'; ++iter) ; if (iter == tmp || iter == end || *iter != ' ') return boost::none; auto request_uri = std::string(tmp, iter); if (header.method() == "CONNECT") { boost::regex regex("(.+?):(\\d+)"); boost::match_results<std::string::iterator> match_results; if (!boost::regex_match(request_uri.begin(), request_uri.end(), match_results, regex)) { return boost::none; } header._host = match_results[1]; try { header._port = static_cast<unsigned short>(std::stoul(std::string(match_results[2]))); } catch (const std::exception&) { return boost::none; } } else { boost::regex regex("(.+?)://(.+?)(:(\\d+))?(/.*)"); boost::match_results<std::string::iterator> match_results; if (!boost::regex_match(request_uri.begin(), request_uri.end(), match_results, regex)) { return boost::none; } header._scheme = match_results[1]; header._host = match_results[2]; if (match_results[4].matched) { try { header._port = static_cast<unsigned short>(std::stoul(std::string(match_results[4]))); } catch (const std::exception&) { return boost::none; } } header._path_and_query = match_results[5]; } tmp = ++iter; for (;iter != end && *iter != '\r'; ++iter) ; // HTTP/x.y if (iter == end || std::distance(tmp, iter) < 6 || !std::equal(tmp, tmp + 5, "HTTP/")) return boost::none; header._http_version = std::string(tmp + 5, iter); ++iter; if (iter == end || *iter != '\n') return boost::none; ++iter; try { header._headers_map = parse_headers(iter, end); } catch (const std::exception&) { return boost::none; } return header; } boost::optional<http_response_header> http_header_parser::parse_response_header(std::string::const_iterator begin, std::string::const_iterator end) { auto iter = begin; auto tmp = iter; for (;iter != end && *iter != ' ' && *iter != '\r'; ++iter) ; if (std::distance(tmp, iter) < 6 || iter == end || *iter != ' ' || !std::equal(tmp, tmp + 5, "HTTP/")) return boost::none; http_response_header header; header._http_version = std::string(tmp + 5, iter); tmp = ++iter; for (;iter != end && *iter != ' ' && *iter != '\r'; ++iter) ; if (tmp == iter || iter == end) return boost::none; try { header._status_code = std::stoul(std::string(tmp, iter)); } catch(const std::exception&) { return boost::none; } if (*iter == ' ') { tmp = ++iter; for (;iter != end && *iter != '\r'; ++iter) ; if (iter == end || *iter != '\r') return boost::none; header._status_description = std::string(tmp, iter); } if (*iter != '\r') return boost::none; if (iter == end || *(++iter) != '\n') return boost::none; ++iter; try { header._headers_map = parse_headers(iter, end); } catch (const std::exception&) { return boost::none; } return header; } }; // namespace azure_proxy <file_sep>/src/http_proxy_client.cpp /* * http_proxy_client.cpp: * * Copyright (C) 2013-2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #include <iostream> #include <string> #include <thread> #include <utility> #include <vector> #include "http_proxy_client.hpp" #include "http_proxy_client_connection.hpp" #include "http_proxy_client_config.hpp" namespace azure_proxy { http_proxy_client::http_proxy_client(boost::asio::io_service& io_service) : io_service(io_service), acceptor(io_service) { } void http_proxy_client::run() { const auto& config = http_proxy_client_config::get_instance(); boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string(config.get_bind_address()), config.get_listen_port()); this->acceptor.open(endpoint.protocol()); this->acceptor.bind(endpoint); this->acceptor.listen(boost::asio::socket_base::max_connections); this->start_accept(); std::vector<std::thread> td_vec; for (auto i = 0u; i < config.get_workers(); ++i) { td_vec.emplace_back([this]() { try { this->io_service.run(); } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } }); } for (auto& td : td_vec) { td.join(); } } void http_proxy_client::start_accept() { auto socket = std::make_shared<boost::asio::ip::tcp::socket>(this->acceptor.get_io_service()); this->acceptor.async_accept(*socket, [socket, this](const boost::system::error_code& error) { if (!error) { this->start_accept(); auto connection = http_proxy_client_connection::create(std::move(*socket)); connection->start(); } }); } } // namespace azure_proxy <file_sep>/src/http_proxy_client_config.cpp /* * http_proxy_client_config.cpp: * * Copyright (C) 2013-2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #include <algorithm> #include <cctype> #include <fstream> #include <memory> #ifdef _WIN32 #include <Windows.h> #else extern "C" { #include <unistd.h> #include <sys/types.h> #include <pwd.h> } #endif #include "encrypt.hpp" #include "http_proxy_client_config.hpp" #include "jsonxx/jsonxx.h" namespace azure_proxy { http_proxy_client_config::http_proxy_client_config() {} bool http_proxy_client_config::load_config(const std::string& config_data) { bool rollback = true; std::shared_ptr<bool> auto_rollback(&rollback, [this](bool* rollback) { if (*rollback) { this->config_map.clear(); } }); jsonxx::Object json_obj; if (!json_obj.parse(config_data)) { std::cerr << "Failed to parse config" << std::endl; return false; } if (!json_obj.has<jsonxx::String>("proxy_server_address")) { std::cerr << "Could not find \"proxy_server_address\" in config or it's value is not a string" << std::endl; return false; } this->config_map["proxy_server_address"] = std::string(json_obj.get<jsonxx::String>("proxy_server_address")); if (!json_obj.has<jsonxx::Number>("proxy_server_port")) { std::cerr << "Could not find \"proxy_server_port\" in config or it's value is not a number" << std::endl; return false; } this->config_map["proxy_server_port"] = static_cast<unsigned short>(json_obj.get<jsonxx::Number>("proxy_server_port")); if (json_obj.has<jsonxx::String>("bind_address")) { this->config_map["bind_address"] = std::string(json_obj.get<jsonxx::String>("bind_address")); } else { this->config_map["bind_address"] = std::string("127.0.0.1"); } if (json_obj.has<jsonxx::Number>("listen_port")) { this->config_map["listen_port"] = static_cast<unsigned short>(json_obj.get<jsonxx::Number>("listen_port")); } else { this->config_map["listen_port"] = static_cast<unsigned short>(8089); } if (!json_obj.has<jsonxx::String>("rsa_public_key")) { std::cerr << "Could not find \"rsa_public_key\" in config or it's value is not a string" << std::endl; return false; } const std::string& rsa_public_key = json_obj.get<jsonxx::String>("rsa_public_key"); try { rsa rsa_pub(rsa_public_key); if (rsa_pub.modulus_size() < 128) { std::cerr << "Must use RSA keys of at least 1024 bits" << std::endl; return false; } } catch (const std::exception&) { std::cerr << "The value of rsa_public_key is bad" << std::endl; return false; } this->config_map["rsa_public_key"] = rsa_public_key; if (json_obj.has<jsonxx::String>("cipher")) { std::string cipher = std::string(json_obj.get<jsonxx::String>("cipher")); for (auto& ch : cipher) { ch = std::tolower(static_cast<unsigned char>(ch)); } bool is_supported_cipher = false; if (cipher.size() > 3 && std::equal(cipher.begin(), cipher.begin() + 4, "aes-")) { if (cipher.size() > 8 && cipher[7] == '-' && (std::equal(cipher.begin() + 4, cipher.begin() + 7, "128") || std::equal(cipher.begin() + 4, cipher.begin() + 7, "192") || std::equal(cipher.begin() + 4, cipher.begin() + 7, "256") )) { if (std::equal(cipher.begin() + 8, cipher.end(), "cfb") || std::equal(cipher.begin() + 8, cipher.end(), "cfb128") || std::equal(cipher.begin() + 8, cipher.end(), "cfb8") || std::equal(cipher.begin() + 8, cipher.end(), "cfb1") || std::equal(cipher.begin() + 8, cipher.end(), "ofb") || std::equal(cipher.begin() + 8, cipher.end(), "ofb128") || std::equal(cipher.begin() + 8, cipher.end(), "ctr") || std::equal(cipher.begin() + 8, cipher.end(), "ctr128")) { is_supported_cipher = true; } } } if (!is_supported_cipher) { std::cerr << "Unsupported cipher: " << cipher << std::endl; return false; } this->config_map["cipher"] = cipher; } else { this->config_map["cipher"] = std::string("aes-256-ofb"); } if (json_obj.has<jsonxx::Number>("timeout")) { int timeout = static_cast<int>(json_obj.get<jsonxx::Number>("timeout")); this->config_map["timeout"] = static_cast<unsigned int>(timeout < 30 ? 30 : timeout); } else { this->config_map["timeout"] = 240ul; } if (json_obj.has<jsonxx::Number>("workers")) { int threads = static_cast<int>(json_obj.get<jsonxx::Number>("workers")); this->config_map["workers"] = static_cast<unsigned int>(threads < 1 ? 1 : (threads > 16 ? 16 : threads)); } else { this->config_map["workers"] = 2ul; } rollback = false; return true; } bool http_proxy_client_config::load_config() { std::string config_data; #ifdef _WIN32 wchar_t path_buffer[MAX_PATH]; if (GetModuleFileNameW(NULL, path_buffer, MAX_PATH) == 0 || GetLastError() == ERROR_INSUFFICIENT_BUFFER) { std::cerr << "Failed to get retrieve the path of the executable file" << std::endl; } std::wstring config_file_path(path_buffer); config_file_path.resize(config_file_path.find_last_of(L'\\') + 1); config_file_path += L"client.json"; std::shared_ptr<std::remove_pointer<HANDLE>::type> config_file_handle( CreateFileW(config_file_path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL), [](HANDLE native_handle) { if (native_handle != INVALID_HANDLE_VALUE) { CloseHandle(native_handle); } }); if (config_file_handle.get() == INVALID_HANDLE_VALUE) { std::cerr << "Failed to open config file \"client.json\"" << std::endl; return false; } char ch; DWORD size_read = 0; BOOL read_result = ReadFile(config_file_handle.get(), &ch, 1, &size_read, NULL); while (read_result != FALSE && size_read != 0) { config_data.push_back(ch); read_result = ReadFile(config_file_handle.get(), &ch, 1, &size_read, NULL); } if (read_result == FALSE) { std::cerr << "Failed to read data from config file" << std::endl; return false; } #else auto bufsize = sysconf(_SC_GETPW_R_SIZE_MAX); if (bufsize == -1) { bufsize = 16384; } std::unique_ptr<char[]> buf(new char[bufsize]); passwd pwd, *result = nullptr; getpwuid_r(getuid(), &pwd, buf.get(), bufsize, &result); if (result == nullptr) { return false; } std::string config_path = pwd.pw_dir; config_path += "/.ahpc/client.json"; std::ifstream ifile(config_path.c_str()); if (!ifile.is_open()) { std::cerr << "Failed to open \"" << config_path << "\"" << std::endl; return false; } char ch; while (ifile.get(ch)) { config_data.push_back(ch); } #endif return this->load_config(config_data); } const std::string& http_proxy_client_config::get_proxy_server_address() const { return this->get_config_value<const std::string&>("proxy_server_address"); } unsigned short http_proxy_client_config::get_proxy_server_port() const { return this->get_config_value<unsigned short>("proxy_server_port"); } const std::string& http_proxy_client_config::get_bind_address() const { return this->get_config_value<const std::string&>("bind_address"); } unsigned short http_proxy_client_config::get_listen_port() const { return this->get_config_value<unsigned short>("listen_port"); } const std::string& http_proxy_client_config::get_rsa_public_key() const { return this->get_config_value<const std::string&>("rsa_public_key"); } const std::string& http_proxy_client_config::get_cipher() const { return this->get_config_value<const std::string&>("cipher"); } unsigned int http_proxy_client_config::get_timeout() const { return this->get_config_value<unsigned int>("timeout"); } unsigned int http_proxy_client_config::get_workers() const { return this->get_config_value<unsigned int>("workers"); } http_proxy_client_config& http_proxy_client_config::get_instance() { static http_proxy_client_config instance; return instance; } } // namespace azure_proxy <file_sep>/src/http_proxy_server_main.cpp /* * http_proxy_server_main.cpp: * * Copyright (C) 2013-2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #include <iostream> #include "http_proxy_server_config.hpp" #include "http_proxy_server.hpp" int main() { using namespace azure_proxy; try { auto& config = http_proxy_server_config::get_instance(); if (config.load_config()) { std::cout << "Azure Http Proxy Server" << std::endl; std::cout << "bind address: " << config.get_bind_address() << ':' << config.get_listen_port() << std::endl; boost::asio::io_service io_service; http_proxy_server server(io_service); server.run(); } } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } return 0; } <file_sep>/src/encrypt.hpp /* * encrypt.hpp: * * Copyright (C) 2014-2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #ifndef AZURE_ENCRYPT_HPP #define AZURE_ENCRYPT_HPP #include <cassert> #include <cstring> #include <memory> #include <stdexcept> extern "C" { #include <openssl/aes.h> #include <openssl/rsa.h> #include <openssl/pem.h> } namespace azure_proxy { class stream_encryptor { public: virtual void encrypt(const unsigned char* in, unsigned char* out, std::size_t length) = 0; virtual ~stream_encryptor() {} }; class stream_decryptor { public: virtual void decrypt(const unsigned char* in, unsigned char* out, std::size_t length) = 0; virtual ~stream_decryptor() {} }; class copy_encryptor : public stream_encryptor { public: copy_encryptor() {}; virtual void encrypt(const unsigned char* in, unsigned char* out, std::size_t length) { assert(in && out); std::memcpy(out, in, length); } virtual ~copy_encryptor() {} }; class aes_cfb128_encryptor : public stream_encryptor { AES_KEY aes_ctx; int num; unsigned char key[32]; unsigned char ivec[16]; public: aes_cfb128_encryptor(const unsigned char* key, std::size_t key_bits, unsigned char* ivec) : num(0) { assert(key && ivec); assert(key_bits == 128 || key_bits == 192 || key_bits == 256); std::memcpy(this->key, key, key_bits / 8); std::memcpy(this->ivec, ivec, sizeof(this->ivec)); AES_set_encrypt_key(this->key, key_bits, &this->aes_ctx); } virtual void encrypt(const unsigned char* in, unsigned char* out, std::size_t length) { assert(in && out); AES_cfb128_encrypt(in, out, length, &this->aes_ctx, this->ivec, &this->num, AES_ENCRYPT); } virtual ~aes_cfb128_encryptor() {} }; class aes_cfb128_decryptor : public stream_decryptor { AES_KEY aes_ctx; int num; unsigned char key[32]; unsigned char ivec[16]; public: aes_cfb128_decryptor(const unsigned char* key, std::size_t key_bits, unsigned char* ivec) : num(0) { assert(key && ivec); assert(key_bits == 128 || key_bits == 192 || key_bits == 256); std::memcpy(this->key, key, key_bits / 8); std::memcpy(this->ivec, ivec, sizeof(this->ivec)); AES_set_encrypt_key(this->key, key_bits, &this->aes_ctx); } virtual void decrypt(const unsigned char* in, unsigned char* out, std::size_t length) { assert(in && out); AES_cfb128_encrypt(in, out, length, &this->aes_ctx, this->ivec, &this->num, AES_DECRYPT); } virtual ~aes_cfb128_decryptor() {} }; class aes_cfb8_encryptor : public stream_encryptor { AES_KEY aes_ctx; int num; unsigned char key[32]; unsigned char ivec[16]; public: aes_cfb8_encryptor(const unsigned char* key, std::size_t key_bits, unsigned char* ivec) : num(0) { assert(key && ivec); assert(key_bits == 128 || key_bits == 192 || key_bits == 256); std::memcpy(this->key, key, key_bits / 8); std::memcpy(this->ivec, ivec, sizeof(this->ivec)); AES_set_encrypt_key(this->key, key_bits, &this->aes_ctx); } virtual void encrypt(const unsigned char* in, unsigned char* out, std::size_t length) { assert(in && out); AES_cfb8_encrypt(in, out, length, &this->aes_ctx, this->ivec, &this->num, AES_ENCRYPT); } virtual ~aes_cfb8_encryptor() {} }; class aes_cfb8_decryptor : public stream_decryptor{ AES_KEY aes_ctx; int num; unsigned char key[32]; unsigned char ivec[16]; public: aes_cfb8_decryptor(const unsigned char* key, std::size_t key_bits, unsigned char* ivec) : num(0) { assert(key && ivec); assert(key_bits == 128 || key_bits == 192 || key_bits == 256); std::memcpy(this->key, key, key_bits / 8); std::memcpy(this->ivec, ivec, sizeof(this->ivec)); AES_set_encrypt_key(this->key, key_bits, &this->aes_ctx); } virtual void decrypt(const unsigned char* in, unsigned char* out, std::size_t length) { assert(in && out); AES_cfb8_encrypt(in, out, length, &this->aes_ctx, this->ivec, &this->num, AES_DECRYPT); } virtual ~aes_cfb8_decryptor() {} }; class aes_cfb1_encryptor : public stream_encryptor { AES_KEY aes_ctx; int num; unsigned char key[32]; unsigned char ivec[16]; public: aes_cfb1_encryptor(const unsigned char* key, std::size_t key_bits, unsigned char* ivec) : num(0) { assert(key && ivec); assert(key_bits == 128 || key_bits == 192 || key_bits == 256); std::memcpy(this->key, key, key_bits / 8); std::memcpy(this->ivec, ivec, sizeof(this->ivec)); AES_set_encrypt_key(this->key, key_bits, &this->aes_ctx); } virtual void encrypt(const unsigned char* in, unsigned char* out, std::size_t length) { assert(in && out); AES_cfb1_encrypt(in, out, length * 8, &this->aes_ctx, this->ivec, &this->num, AES_ENCRYPT); } virtual ~aes_cfb1_encryptor() { } }; class copy_decryptor : public stream_decryptor { public: copy_decryptor() {}; virtual void decrypt(const unsigned char* in, unsigned char* out, std::size_t length) { assert(in && out); std::memcpy(out, in, length); } virtual ~copy_decryptor() {} }; class aes_cfb1_decryptor : public stream_decryptor { AES_KEY aes_ctx; int num; unsigned char key[32]; unsigned char ivec[16]; public: aes_cfb1_decryptor(const unsigned char* key, std::size_t key_bits, unsigned char* ivec) : num(0) { assert(key && ivec); assert(key_bits == 128 || key_bits == 192 || key_bits == 256); std::memcpy(this->key, key, key_bits / 8); std::memcpy(this->ivec, ivec, sizeof(this->ivec)); AES_set_encrypt_key(this->key, key_bits, &this->aes_ctx); } virtual void decrypt(const unsigned char* in, unsigned char* out, std::size_t length) { assert(in && out); AES_cfb1_encrypt(in, out, length * 8, &this->aes_ctx, this->ivec, &this->num, AES_DECRYPT); } virtual ~aes_cfb1_decryptor() { } }; class aes_ofb128_encryptor : public stream_encryptor { AES_KEY aes_ctx; int num; unsigned char key[32]; unsigned char ivec[16]; public: aes_ofb128_encryptor(const unsigned char* key, std::size_t key_bits, unsigned char* ivec) : num(0) { assert(key && ivec); assert(key_bits == 128 || key_bits == 192 || key_bits == 256); std::memcpy(this->key, key, key_bits / 8); std::memcpy(this->ivec, ivec, sizeof(this->ivec)); AES_set_encrypt_key(this->key, key_bits, &this->aes_ctx); } virtual void encrypt(const unsigned char* in, unsigned char* out, std::size_t length) { assert(in && out); AES_ofb128_encrypt(in, out, length, &this->aes_ctx, this->ivec, &this->num); } virtual ~aes_ofb128_encryptor() {} }; class aes_ofb128_decryptor : public stream_decryptor { AES_KEY aes_ctx; int num; unsigned char key[32]; unsigned char ivec[16]; public: aes_ofb128_decryptor(const unsigned char* key, std::size_t key_bits, unsigned char* ivec) : num(0) { assert(key && ivec); assert(key_bits == 128 || key_bits == 192 || key_bits == 256); std::memcpy(this->key, key, key_bits / 8); std::memcpy(this->ivec, ivec, sizeof(this->ivec)); AES_set_encrypt_key(this->key, key_bits, &this->aes_ctx); } virtual void decrypt(const unsigned char* in, unsigned char* out, std::size_t length) { assert(in && out); AES_ofb128_encrypt(in, out, length, &this->aes_ctx, this->ivec, &this->num); } virtual ~aes_ofb128_decryptor() {} }; class aes_ctr128_encryptor : public stream_encryptor { AES_KEY aes_ctx; unsigned int num; unsigned char key[32]; unsigned char ivec[16]; unsigned char ecount_buf[16]; public: aes_ctr128_encryptor(const unsigned char* key, std::size_t key_bits, unsigned char* ivec) : num(0) { assert(key && ivec); assert(key_bits == 128 || key_bits == 192 || key_bits == 256); std::memcpy(this->key, key, key_bits / 8); std::memcpy(this->ivec, ivec, sizeof(this->ivec)); std::memset(this->ecount_buf, 0, sizeof(this->ecount_buf)); AES_set_encrypt_key(this->key, key_bits, &this->aes_ctx); } virtual void encrypt(const unsigned char* in, unsigned char* out, std::size_t length) { assert(in && out); AES_ctr128_encrypt(in, out, length, &aes_ctx, this->ivec, this->ecount_buf, &this->num); } virtual ~aes_ctr128_encryptor() { } }; class aes_ctr128_decryptor : public stream_decryptor { AES_KEY aes_ctx; unsigned int num; unsigned char key[32]; unsigned char ivec[16]; unsigned char ecount_buf[16]; public: aes_ctr128_decryptor(const unsigned char* key, std::size_t key_bits, unsigned char* ivec) : num(0) { assert(key && ivec); assert(key_bits == 128 || key_bits == 192 || key_bits == 256); std::memcpy(this->key, key, key_bits / 8); std::memcpy(this->ivec, ivec, sizeof(this->ivec)); std::memset(this->ecount_buf, 0, sizeof(this->ecount_buf)); AES_set_encrypt_key(this->key, key_bits, &this->aes_ctx); } virtual void decrypt(const unsigned char* in, unsigned char* out, std::size_t length) { assert(in && out); AES_ctr128_encrypt(in, out, length, &aes_ctx, this->ivec, this->ecount_buf, &this->num); } virtual ~aes_ctr128_decryptor() { } }; enum class rsa_padding { pkcs1_padding, pkcs1_oaep_padding, sslv23_padding, no_padding }; class rsa { bool is_pub; std::shared_ptr<RSA> rsa_handle; public: rsa(const std::string& key) { if (key.size() > 26 && std::equal(key.begin(), key.begin() + 26, "-----BEGIN PUBLIC KEY-----")) { this->is_pub = true; } else if (key.size() > 31 && std::equal(key.begin(), key.begin() + 31, "-----BEGIN RSA PRIVATE KEY-----")) { this->is_pub = false; } else { throw std::invalid_argument("invalid argument"); } auto bio_handle = std::shared_ptr<BIO>(BIO_new_mem_buf(const_cast<char*>(key.data()), key.size()), BIO_free); if (bio_handle) { if (this->is_pub) { this->rsa_handle = std::shared_ptr<RSA>(PEM_read_bio_RSA_PUBKEY(bio_handle.get(), nullptr, nullptr, nullptr), RSA_free); } else { this->rsa_handle = std::shared_ptr<RSA>(PEM_read_bio_RSAPrivateKey(bio_handle.get(), nullptr, nullptr, nullptr), RSA_free); } } if (!this->rsa_handle) { throw std::invalid_argument("invalid argument"); } } int encrypt(int flen, unsigned char* from, unsigned char* to, rsa_padding padding) { assert(from && to); int pad = this->rsa_padding2int(padding); if (this->is_pub) { return RSA_public_encrypt(flen, from, to, this->rsa_handle.get(), pad); } else { return RSA_private_encrypt(flen, from, to, this->rsa_handle.get(), pad); } } int decrypt(int flen, unsigned char* from, unsigned char* to, rsa_padding padding) { assert(from && to); int pad = this->rsa_padding2int(padding); if (this->is_pub) { return RSA_private_decrypt(flen, from, to, this->rsa_handle.get(), pad); } else { return RSA_private_decrypt(flen, from, to, this->rsa_handle.get(), pad); } } int modulus_size() const { return RSA_size(this->rsa_handle.get()); } private: int rsa_padding2int(rsa_padding padding) { switch (padding) { case rsa_padding::pkcs1_padding: return RSA_PKCS1_PADDING; break; case rsa_padding::pkcs1_oaep_padding: return RSA_PKCS1_OAEP_PADDING; break; case rsa_padding::sslv23_padding: return RSA_SSLV23_PADDING; break; default: return RSA_NO_PADDING; } } }; } // namespace azure_proxy #endif <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 2.6) project(azure-http-proxy) set(Boost_USE_MULTITHREAD ON) find_package(Boost REQUIRED COMPONENTS system regex) find_package(OpenSSL REQUIRED) include_directories(${Boost_INCLUDE_DIR}) link_directories(${Boost_LIBRARY_DIR}) include_directories(${OPENSSL_INCLUDE_DIR}) link_directories(${OPENSSL_LIBRARY_DIR}) if("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") add_definitions(-DBOOST_ASIO_HAS_MOVE) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") endif() add_executable(ahpc src/http_proxy_client_main.cpp src/http_proxy_client.cpp src/http_proxy_client_stat.cpp src/http_proxy_client_config.cpp src/http_proxy_client_connection.cpp src/jsonxx/jsonxx.cc) target_link_libraries(ahpc ${Boost_SYSTEM_LIBRARY} ${OPENSSL_LIBRARIES}) add_executable(ahps src/http_proxy_server_main.cpp src/http_proxy_server.cpp src/http_proxy_server_config.cpp src/http_proxy_server_connection.cpp src/http_header_parser.cpp src/base64.cpp src/authentication.cpp src/jsonxx/jsonxx.cc) target_link_libraries(ahps ${Boost_SYSTEM_LIBRARY} ${Boost_REGEX_LIBRARY} ${OPENSSL_LIBRARIES}) if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") target_link_libraries(ahpc atomic) endif() if(UNIX) target_link_libraries(ahpc pthread) target_link_libraries(ahps pthread) endif() if(WIN32) if(MINGW) target_link_libraries(ahpc ws2_32 wsock32) target_link_libraries(ahps ws2_32 wsock32) endif() endif()<file_sep>/src/http_proxy_server_connection.hpp /* * http_proxy_server_connection.hpp: * * Copyright (C) 2013-2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #ifndef AZURE_HTTP_PROXY_SERVER_CONNECTION_HPP #define AZURE_HTTP_PROXY_SERVER_CONNECTION_HPP #include <array> #include <chrono> #include <boost/asio.hpp> #include <boost/optional.hpp> #include "encrypt.hpp" #include "http_header_parser.hpp" #include "http_proxy_server_connection_context.hpp" namespace azure_proxy { const std::size_t BUFFER_LENGTH = 2048; class http_proxy_server_connection : public std::enable_shared_from_this<http_proxy_server_connection> { boost::asio::io_service::strand strand; boost::asio::ip::tcp::socket proxy_client_socket; boost::asio::ip::tcp::socket origin_server_socket; boost::asio::ip::tcp::resolver resolver; boost::asio::basic_waitable_timer<std::chrono::steady_clock> timer; std::array<char, BUFFER_LENGTH> upgoing_buffer_read; std::array<char, BUFFER_LENGTH> upgoing_buffer_write; std::array<char, BUFFER_LENGTH> downgoing_buffer_read; std::array<char, BUFFER_LENGTH> downgoing_buffer_write; rsa rsa_pri; std::vector<unsigned char> encrypted_cipher_info; std::unique_ptr<stream_encryptor> encryptor; std::unique_ptr<stream_decryptor> decryptor; std::string request_data; std::string modified_request_data; std::string response_data; std::string modified_response_data; boost::optional<http_request_header> request_header; boost::optional<http_response_header> response_header; http_proxy_server_connection_context connection_context; http_proxy_server_connection_read_request_context read_request_context; http_proxy_server_connection_read_response_context read_response_context; private: http_proxy_server_connection(boost::asio::ip::tcp::socket&& proxy_client_socket); public: ~http_proxy_server_connection(); static std::shared_ptr<http_proxy_server_connection> create(boost::asio::ip::tcp::socket&& client_socket); void start(); private: void async_read_data_from_proxy_client(std::size_t at_least_size = 1, std::size_t at_most_size = BUFFER_LENGTH); void async_read_data_from_origin_server(bool set_timer = true, std::size_t at_least_size = 1, std::size_t at_most_size = BUFFER_LENGTH); void async_connect_to_origin_server(); void async_write_request_header_to_origin_server(); void async_write_response_header_to_proxy_client(); void async_write_data_to_origin_server(const char* write_buffer, std::size_t offset, std::size_t size); void async_write_data_to_proxy_client(const char* write_buffer, std::size_t offset, std::size_t size); void start_tunnel_transfer(); void report_error(const std::string& status_code, const std::string& status_description, const std::string& error_message); void report_authentication_failed(); void set_timer(); bool cancel_timer(); void on_resolved(boost::asio::ip::tcp::resolver::iterator endpoint_iterator); void on_connect(); void on_proxy_client_data_arrived(std::size_t bytes_transferred); void on_origin_server_data_arrived(std::size_t bytes_transferred); void on_proxy_client_data_written(); void on_origin_server_data_written(); void on_error(const boost::system::error_code& error); void on_timeout(); }; } // namespace azure_proxy #endif <file_sep>/src/http_proxy_client_config.hpp /* * http_proxy_client_config.hpp: * * Copyright (C) 2013-2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #ifndef AZURE_HTTP_PROXY_CLIENT_CONFIG_HPP #define AZURE_HTTP_PROXY_CLIENT_CONFIG_HPP #include <cassert> #include <map> #include <stdexcept> #include <string> #include <boost/any.hpp> namespace azure_proxy { class http_proxy_client_config { std::map<std::string, boost::any> config_map; private: template<typename T> T get_config_value(const std::string& key) const { assert(!this->config_map.empty()); auto iter = this->config_map.find(key); if (iter == this->config_map.end()) { throw std::invalid_argument("invalid argument"); } return boost::any_cast<T>(iter->second); } http_proxy_client_config(); bool load_config(const std::string& config_data); public: bool load_config(); const std::string& get_proxy_server_address() const; unsigned short get_proxy_server_port() const; const std::string& get_bind_address() const; unsigned short get_listen_port() const; const std::string& get_rsa_public_key() const; const std::string& get_cipher() const; unsigned int get_timeout() const; unsigned int get_workers() const; static http_proxy_client_config& get_instance(); }; } // namespace azure_proxy #endif <file_sep>/src/http_header_parser.hpp /* * http_header_parser.hpp: * * Copyright (C) 2013-2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #ifndef AZURE_HTTP_HEADER_PARSER_HPP #define AZURE_HTTP_HEADER_PARSER_HPP #include <algorithm> #include <cctype> #include <map> #include <string> #include <boost/optional.hpp> namespace azure_proxy { struct default_filed_name_compare { bool operator() (const std::string& str1, const std::string& str2) const { return std::lexicographical_compare(str1.begin(), str1.end(), str2.begin(), str2.end(), [](const char ch1, const char ch2) -> bool { return std::tolower(static_cast<unsigned char>(ch1)) < std::tolower(static_cast<unsigned char>(ch2)); }); } }; typedef std::multimap<const std::string, std::string, default_filed_name_compare> http_headers_container; class http_request_header { friend class http_header_parser; std::string _method; std::string _scheme; std::string _host; unsigned short _port; std::string _path_and_query; std::string _http_version; http_headers_container _headers_map; http_request_header(); public: const std::string& method() const; const std::string& scheme() const; const std::string& host() const; unsigned short port() const; const std::string& path_and_query() const; const std::string& http_version() const; boost::optional<std::string> get_header_value(const std::string& name) const; std::size_t erase_header(const std::string& name); const http_headers_container& get_headers_map() const; }; class http_response_header { friend class http_header_parser; std::string _http_version; unsigned int _status_code; std::string _status_description; http_headers_container _headers_map; http_response_header(); public: const std::string& http_version() const; unsigned int status_code() const; const std::string& status_description() const; boost::optional<std::string> get_header_value(const std::string& name) const; std::size_t erase_header(const std::string& name); const http_headers_container& get_headers_map() const; }; class http_header_parser { static http_headers_container parse_headers(std::string::const_iterator begin, std::string::const_iterator end); public: static boost::optional<http_request_header> parse_request_header(std::string::const_iterator begin, std::string::const_iterator end); static boost::optional<http_response_header> parse_response_header(std::string::const_iterator begin, std::string::const_iterator end); }; }; // namespace azure_proxy #endif <file_sep>/src/http_proxy_server_connection.cpp /* * http_proxy_server_connection.cpp: * * Copyright (C) 2013-2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #include <cctype> #include <algorithm> #include <cassert> #include <cstring> #include "authentication.hpp" #include "http_proxy_server_config.hpp" #include "http_proxy_server_connection.hpp" static const std::size_t MAX_REQUEST_HEADER_LENGTH = 10240; static const std::size_t MAX_RESPONSE_HEADER_LENGTH = 10240; namespace azure_proxy { http_proxy_server_connection::http_proxy_server_connection(boost::asio::ip::tcp::socket&& proxy_client_socket) : strand(proxy_client_socket.get_io_service()), proxy_client_socket(std::move(proxy_client_socket)), origin_server_socket(this->proxy_client_socket.get_io_service()), resolver(this->proxy_client_socket.get_io_service()), timer(this->proxy_client_socket.get_io_service()), rsa_pri(http_proxy_server_config::get_instance().get_rsa_private_key()) { this->connection_context.connection_state = proxy_connection_state::read_cipher_data; } http_proxy_server_connection::~http_proxy_server_connection() { } std::shared_ptr<http_proxy_server_connection> http_proxy_server_connection::create(boost::asio::ip::tcp::socket&& client_socket) { return std::shared_ptr<http_proxy_server_connection>(new http_proxy_server_connection(std::move(client_socket))); } void http_proxy_server_connection::start() { this->connection_context.connection_state = proxy_connection_state::read_cipher_data; this->async_read_data_from_proxy_client(1, std::min<std::size_t>(this->rsa_pri.modulus_size(), BUFFER_LENGTH)); } void http_proxy_server_connection::async_read_data_from_proxy_client(std::size_t at_least_size, std::size_t at_most_size) { assert(at_least_size <= at_most_size && at_most_size <= BUFFER_LENGTH); auto self(this->shared_from_this()); this->set_timer(); boost::asio::async_read(this->proxy_client_socket, boost::asio::buffer(&this->upgoing_buffer_read[0], at_most_size), boost::asio::transfer_at_least(at_least_size), this->strand.wrap([this, self](const boost::system::error_code& error, std::size_t bytes_transferred) { if (this->cancel_timer()) { if (!error) { this->on_proxy_client_data_arrived(bytes_transferred); } else { this->on_error(error); } } }) ); } void http_proxy_server_connection::async_read_data_from_origin_server(bool set_timer, std::size_t at_least_size, std::size_t at_most_size) { auto self(this->shared_from_this()); if (set_timer) { this->set_timer(); } boost::asio::async_read(this->origin_server_socket, boost::asio::buffer(&this->downgoing_buffer_read[0], at_most_size), boost::asio::transfer_at_least(at_least_size), this->strand.wrap([this, self](const boost::system::error_code& error, std::size_t bytes_transferred) { if (this->cancel_timer()) { if (!error) { this->on_origin_server_data_arrived(bytes_transferred); } else { this->on_error(error); } } }) ); } void http_proxy_server_connection::async_connect_to_origin_server() { this->connection_context.reconnect_on_error = false; if (this->origin_server_socket.is_open()) { if (this->request_header->method() == "CONNECT") { boost::system::error_code ec; this->origin_server_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); this->origin_server_socket.close(ec); } } if (this->origin_server_socket.is_open() && this->request_header->host() == this->connection_context.origin_server_name && this->request_header->port() == this->connection_context.origin_server_port) { this->connection_context.reconnect_on_error = true; this->on_connect(); } else { this->connection_context.origin_server_name = this->request_header->host(); this->connection_context.origin_server_port = this->request_header->port(); boost::asio::ip::tcp::resolver::query query(this->request_header->host(), std::to_string(this->request_header->port())); auto self(this->shared_from_this()); this->connection_context.connection_state = proxy_connection_state::resolve_origin_server_address; this->set_timer(); this->resolver.async_resolve(query, this->strand.wrap([this, self](const boost::system::error_code& error, boost::asio::ip::tcp::resolver::iterator iterator) { if (this->cancel_timer()) { if (!error) { this->on_resolved(iterator); } else { this->on_error(error); } } }) ); } } void http_proxy_server_connection::async_write_request_header_to_origin_server() { auto request_content_begin = this->request_data.begin() + this->request_data.find("\r\n\r\n") + 4; this->modified_request_data = this->request_header->method(); this->modified_request_data.push_back(' '); this->modified_request_data += this->request_header->path_and_query(); this->modified_request_data += " HTTP/"; this->modified_request_data += this->request_header->http_version(); this->modified_request_data += "\r\n"; this->request_header->erase_header("Proxy-Connection"); this->request_header->erase_header("Proxy-Authorization"); for (const auto& header: this->request_header->get_headers_map()) { this->modified_request_data += std::get<0>(header); this->modified_request_data += ": "; this->modified_request_data += std::get<1>(header); this->modified_request_data += "\r\n"; } this->modified_request_data += "\r\n"; this->modified_request_data.append(request_content_begin, this->request_data.end()); this->connection_context.connection_state = proxy_connection_state::write_http_request_header; this->async_write_data_to_origin_server(this->modified_request_data.data(), 0, this->modified_request_data.size()); } void http_proxy_server_connection::async_write_response_header_to_proxy_client() { auto response_content_begin = this->response_data.begin() + this->response_data.find("\r\n\r\n") + 4; this->modified_response_data = "HTTP/"; this->modified_response_data += this->response_header->http_version(); this->modified_response_data.push_back(' '); this->modified_response_data += std::to_string(this->response_header->status_code()); if (!this->response_header->status_description().empty()) { this->modified_response_data.push_back(' '); this->modified_response_data += this->response_header->status_description(); } this->modified_response_data += "\r\n"; for (const auto& header: this->response_header->get_headers_map()) { this->modified_response_data += std::get<0>(header); this->modified_response_data += ": "; this->modified_response_data += std::get<1>(header); this->modified_response_data += "\r\n"; } this->modified_response_data += "\r\n"; this->modified_response_data.append(response_content_begin, this->response_data.end()); unsigned char temp_buffer[256]; std::size_t blocks = this->modified_response_data.size() / 256; if (this->modified_response_data.size() % 256 != 0) { blocks += 1; } for (std::size_t i = 0; i < blocks; ++i) { std::size_t block_length = 256; if ((i + 1) * 256 > this->modified_response_data.size()) { block_length = this->modified_response_data.size() % 256; } std::copy(reinterpret_cast<const unsigned char*>(&this->modified_response_data[i * 256]), reinterpret_cast<const unsigned char*>(&this->modified_response_data[i * 256 + block_length]), temp_buffer); this->encryptor->encrypt(temp_buffer, reinterpret_cast<unsigned char*>(&this->modified_response_data[i * 256]), block_length); } this->connection_context.connection_state = proxy_connection_state::write_http_response_header; this->async_write_data_to_proxy_client(this->modified_response_data.data(), 0, this->modified_response_data.size()); } void http_proxy_server_connection::async_write_data_to_origin_server(const char* write_buffer, std::size_t offset, std::size_t size) { auto self(this->shared_from_this()); this->set_timer(); this->origin_server_socket.async_write_some(boost::asio::buffer(write_buffer + offset, size), this->strand.wrap([this, self, write_buffer, offset, size](const boost::system::error_code& error, std::size_t bytes_transferred) { if (this->cancel_timer()) { if (!error) { this->connection_context.reconnect_on_error = false; if (bytes_transferred < size) { this->async_write_data_to_origin_server(write_buffer, offset + bytes_transferred, size - bytes_transferred); } else { this->on_origin_server_data_written(); } } else { this->on_error(error); } } }) ); } void http_proxy_server_connection::async_write_data_to_proxy_client(const char* write_buffer, std::size_t offset, std::size_t size) { auto self(this->shared_from_this()); this->set_timer(); this->proxy_client_socket.async_write_some(boost::asio::buffer(write_buffer + offset, size), this->strand.wrap([this, self, write_buffer, offset, size](const boost::system::error_code& error, std::size_t bytes_transferred) { if (this->cancel_timer()) { if (!error) { if (bytes_transferred < size) { this->async_write_data_to_proxy_client(write_buffer, offset + bytes_transferred, size - bytes_transferred); } else { this->on_proxy_client_data_written(); } } else { this->on_error(error); } } }) ); } void http_proxy_server_connection::start_tunnel_transfer() { this->connection_context.connection_state = proxy_connection_state::tunnel_transfer; this->async_read_data_from_proxy_client(); this->async_read_data_from_origin_server(false); } void http_proxy_server_connection::report_error(const std::string& status_code, const std::string& status_description, const std::string& error_message) { this->modified_response_data.clear(); this->modified_response_data += "HTTP/1.1 "; this->modified_response_data += status_code; if (!status_description.empty()) { this->modified_response_data.push_back(' '); this->modified_response_data += status_description; } this->modified_response_data += "\r\n"; this->modified_response_data += "Content-Type: text/html\r\n"; this->modified_response_data += "Server: AzureHttpProxy\r\n"; this->modified_response_data += "Content-Length: "; std::string response_content; response_content = "<!DOCTYPE html><html><head><title>"; response_content += status_code; response_content += ' '; response_content += status_description; response_content += "</title></head><body bgcolor=\"white\"><center><h1>"; response_content += status_code; response_content += ' '; response_content += status_description; response_content += "</h1>"; if (!error_message.empty()) { response_content += "<br/>"; response_content += error_message; response_content += "</center>"; } response_content += "<hr><center>"; response_content += "azure http proxy server"; response_content += "</center></body></html>"; this->modified_response_data += std::to_string(response_content.size()); this->modified_response_data += "\r\n"; this->modified_response_data += "Proxy-Connection: close\r\n"; this->modified_response_data += "\r\n"; if (!this->request_header || this->request_header->method() != "HEAD") { this->modified_response_data += response_content; } unsigned char temp_buffer[16]; for (std::size_t i = 0; i * 16 < this->modified_response_data.size(); ++i) { std::size_t block_length = 16; if (this->modified_response_data.size() - i * 16 < 16) { block_length = this->modified_response_data.size() % 16; } this->encryptor->encrypt(reinterpret_cast<const unsigned char*>(&this->modified_response_data[i * 16]), temp_buffer, block_length); std::copy(temp_buffer, temp_buffer + block_length, reinterpret_cast<unsigned char*>(&this->modified_response_data[i * 16])); } this->connection_context.connection_state = proxy_connection_state::report_error; auto self(this->shared_from_this()); this->async_write_data_to_proxy_client(this->modified_response_data.data(), 0 ,this->modified_response_data.size()); } void http_proxy_server_connection::report_authentication_failed() { std::string content = "<!DOCTYPE html><html><head><title>407 Proxy Authentication Required</title></head>"; content += "<body bgcolor=\"white\"><center><h1>407 Proxy Authentication Required</h1></center><hr><center>azure http proxy server</center></body></html>"; this->modified_response_data = "HTTP/1.1 407 Proxy Authentication Required\r\n"; this->modified_response_data += "Server: AzureHttpProxy\r\n"; this->modified_response_data += "Proxy-Authenticate: Basic realm=\"AzureHttpProxy\"\r\n"; this->modified_response_data += "Content-Type: text/html\r\n"; this->modified_response_data += "Connection: Close\r\n"; this->modified_response_data += "Content-Length: "; this->modified_response_data += std::to_string(content.size()); this->modified_response_data += "\r\n\r\n"; this->modified_response_data += content; unsigned char temp_buffer[16]; for (std::size_t i = 0; i * 16 < this->modified_response_data.size(); ++i) { std::size_t block_length = 16; if (this->modified_response_data.size() - i * 16 < 16) { block_length = this->modified_response_data.size() % 16; } this->encryptor->encrypt(reinterpret_cast<const unsigned char*>(&this->modified_response_data[i * 16]), temp_buffer, block_length); std::copy(temp_buffer, temp_buffer + block_length, reinterpret_cast<unsigned char*>(&this->modified_response_data[i * 16])); } this->connection_context.connection_state = proxy_connection_state::report_error; this->async_write_data_to_proxy_client(this->modified_response_data.data(), 0, this->modified_response_data.size()); } void http_proxy_server_connection::set_timer() { if (this->timer.expires_from_now(std::chrono::seconds(http_proxy_server_config::get_instance().get_timeout())) != 0) { assert(false); } auto self(this->shared_from_this()); this->timer.async_wait(this->strand.wrap([this, self](const boost::system::error_code& error) { if (error != boost::asio::error::operation_aborted) { this->on_timeout(); } })); } bool http_proxy_server_connection::cancel_timer() { std::size_t ret = this->timer.cancel(); assert(ret <= 1); return ret == 1; } void http_proxy_server_connection::on_resolved(boost::asio::ip::tcp::resolver::iterator endpoint_iterator) { if (this->origin_server_socket.is_open()) { for (auto iter = endpoint_iterator; iter != boost::asio::ip::tcp::resolver::iterator(); ++iter) { if (this->connection_context.origin_server_endpoint == iter->endpoint()) { this->connection_context.reconnect_on_error = true; this->on_connect(); return; } boost::system::error_code ec; this->origin_server_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); this->origin_server_socket.close(ec); } } this->connection_context.origin_server_endpoint = endpoint_iterator->endpoint(); auto self(this->shared_from_this()); this->connection_context.connection_state = proxy_connection_state::connect_to_origin_server; this->set_timer(); this->origin_server_socket.async_connect(endpoint_iterator->endpoint(), this->strand.wrap([this, self, endpoint_iterator](const boost::system::error_code& error) mutable { if (this->cancel_timer()) { if (!error) { this->on_connect(); } else { boost::system::error_code ec; this->origin_server_socket.close(ec); if (++endpoint_iterator != boost::asio::ip::tcp::resolver::iterator()) { this->on_resolved(endpoint_iterator); } else { this->on_error(error); } } } }) ); } void http_proxy_server_connection::on_connect() { if (this->request_header->method() == "CONNECT") { const unsigned char response_message[] = "HTTP/1.1 200 Connection Established\r\nConnection: Close\r\n\r\n"; this->modified_response_data.resize(sizeof(response_message) - 1); this->encryptor->encrypt(response_message, const_cast<unsigned char*>(reinterpret_cast<const unsigned char*>(&this->modified_response_data[0])), this->modified_response_data.size()); this->connection_context.connection_state = proxy_connection_state::report_connection_established; this->async_write_data_to_proxy_client(&this->modified_response_data[0], 0, this->modified_response_data.size()); } else { this->async_write_request_header_to_origin_server(); } } void http_proxy_server_connection::on_proxy_client_data_arrived(std::size_t bytes_transferred) { if (this->connection_context.connection_state == proxy_connection_state::read_cipher_data) { std::copy(this->upgoing_buffer_read.begin(), this->upgoing_buffer_read.begin() + bytes_transferred, std::back_inserter(this->encrypted_cipher_info)); if (this->encrypted_cipher_info.size() < this->rsa_pri.modulus_size()) { this->async_read_data_from_proxy_client(1, std::min(static_cast<std::size_t>(this->rsa_pri.modulus_size()) - this->encrypted_cipher_info.size(), BUFFER_LENGTH)); return; } assert(this->encrypted_cipher_info.size() == this->rsa_pri.modulus_size()); std::vector<unsigned char> decrypted_cipher_info(this->rsa_pri.modulus_size()); if (86 != this->rsa_pri.decrypt(this->rsa_pri.modulus_size(), this->encrypted_cipher_info.data(), decrypted_cipher_info.data(), rsa_padding::pkcs1_oaep_padding)) { return; } if (decrypted_cipher_info[0] != 'A' || decrypted_cipher_info[1] != 'H' || decrypted_cipher_info[2] != 'P' || decrypted_cipher_info[3] != 0 || decrypted_cipher_info[4] != 0 || decrypted_cipher_info[6] != 0 ) { return; } // 5 cipher code // 0x00 aes-128-cfb // 0x01 aes-128-cfb8 // 0x02 aes-128-cfb1 // 0x03 aes-128-ofb // 0x04 aes-128-ctr // 0x05 aes-192-cfb // 0x06 aes-192-cfb8 // 0x07 aes-192-cfb1 // 0x08 aes-192-ofb // 0x09 aes-192-ctr // 0x0A aes-256-cfb // 0x0B aes-256-cfb8 // 0x0C aes-256-cfb1 // 0x0D aes-256-ofb // 0x0E aes-256-ctr unsigned char cipher_code = decrypted_cipher_info[5]; if (cipher_code == '\x00' || cipher_code == '\x05' || cipher_code == '\x0A') { // aes-xxx-cfb std::size_t ivec_size = 16; std::size_t key_bits = 256; // <KEY> if (cipher_code == '\x00') { // aes-128-cfb key_bits = 128; } else if (cipher_code == '\x05') { // aes-192-cfb key_bits = 192; } this->encryptor = std::unique_ptr<stream_encryptor>(new aes_cfb128_encryptor(&decrypted_cipher_info[23], key_bits, &decrypted_cipher_info[7])); this->decryptor = std::unique_ptr<stream_decryptor>(new aes_cfb128_decryptor(&decrypted_cipher_info[23], key_bits, &decrypted_cipher_info[7])); } else if (cipher_code == '\x01' || cipher_code == '\x06' || cipher_code == '\x0B') { // ase-xxx-cfb8 std::size_t ivec_size = 16; std::size_t key_bits = 256; // <KEY> if (cipher_code == '\x01') { // aes-128-cfb8 key_bits = 128; } else if (cipher_code == '\x06') { // aes-192-cfb8 key_bits = 192; } this->encryptor = std::unique_ptr<stream_encryptor>(new aes_cfb8_encryptor(&decrypted_cipher_info[23], key_bits, &decrypted_cipher_info[7])); this->decryptor = std::unique_ptr<stream_decryptor>(new aes_cfb8_decryptor(&decrypted_cipher_info[23], key_bits, &decrypted_cipher_info[7])); } else if (cipher_code == '\x02' || cipher_code == '\x07' || cipher_code == '\x0C') { // ase-xxx-cfb1 std::size_t ivec_size = 16; std::size_t key_bits = 256; // <KEY> if (cipher_code == '\x02') { // aes-128-cfb1 key_bits = 128; } else if (cipher_code == '\x07') { // aes-192-cfb1 key_bits = 192; } this->encryptor = std::unique_ptr<stream_encryptor>(new aes_cfb1_encryptor(&decrypted_cipher_info[23], key_bits, &decrypted_cipher_info[7])); this->decryptor = std::unique_ptr<stream_decryptor>(new aes_cfb1_decryptor(&decrypted_cipher_info[23], key_bits, &decrypted_cipher_info[7])); } else if (cipher_code == '\x03' || cipher_code == '\x08' || cipher_code == '\x0D') { // ase-xxx-ofb std::size_t ivec_size = 16; std::size_t key_bits = 256; // aes-256-ofb if (cipher_code == '\x03') { // aes-128-ofb key_bits = 128; } else if (cipher_code == '\x08') { // aes-192-ofb key_bits = 192; } this->encryptor = std::unique_ptr<stream_encryptor>(new aes_ofb128_encryptor(&decrypted_cipher_info[23], key_bits, &decrypted_cipher_info[7])); this->decryptor = std::unique_ptr<stream_decryptor>(new aes_ofb128_decryptor(&decrypted_cipher_info[23], key_bits, &decrypted_cipher_info[7])); } else if (cipher_code == '\x04' || cipher_code == '\x09' || cipher_code == '\x0E') { // ase-xxx-ctr std::size_t ivec_size = 16; std::size_t key_bits = 256; // aes-256-ctr if (cipher_code == '\x04') { // aes-128-ctr key_bits = 128; } else if (cipher_code == '\x09') { // aes-192-ctr key_bits = 192; } std::vector<unsigned char> ivec(ivec_size, 0); this->encryptor = std::unique_ptr<stream_encryptor>(new aes_ctr128_encryptor(&decrypted_cipher_info[23], key_bits, ivec.data())); this->decryptor = std::unique_ptr<stream_decryptor>(new aes_ctr128_decryptor(&decrypted_cipher_info[23], key_bits, ivec.data())); } if (this->encryptor == nullptr || this->decryptor == nullptr) { return; } this->connection_context.connection_state = proxy_connection_state::read_http_request_header; this->async_read_data_from_proxy_client(); return; } assert(this->encryptor != nullptr && this->decryptor != nullptr); this->decryptor->decrypt(reinterpret_cast<const unsigned char*>(&this->upgoing_buffer_read[0]), reinterpret_cast<unsigned char*>(&this->upgoing_buffer_write[0]), bytes_transferred); if (this->connection_context.connection_state == proxy_connection_state::read_http_request_header) { const auto& decripted_data_buffer = this->upgoing_buffer_write; this->request_data.append(decripted_data_buffer.begin(), decripted_data_buffer.begin() + bytes_transferred); auto double_crlf_pos = this->request_data.find("\r\n\r\n"); if (double_crlf_pos == std::string::npos) { if (this->request_data.size() < MAX_REQUEST_HEADER_LENGTH) { this->async_read_data_from_proxy_client(); } else { this->report_error("400", "Bad Request", "Request header too long"); } return; } this->request_header = http_header_parser::parse_request_header(this->request_data.begin(), this->request_data.begin() + double_crlf_pos + 4); if (!this->request_header) { this->report_error("400", "Bad Request", "Failed to parse the http request header"); return; } if (this->request_header->method() != "GET" // && this->request_header->method() != "OPTIONS" && this->request_header->method() != "HEAD" && this->request_header->method() != "POST" && this->request_header->method() != "PUT" && this->request_header->method() != "DELETE" // && this->request_header->method() != "TRACE" && this->request_header->method() != "CONNECT") { this->report_error("405", "Method Not Allowed", std::string()); return; } if (this->request_header->http_version() != "1.1" && this->request_header->http_version() != "1.0") { this->report_error("505", "HTTP Version Not Supported", std::string()); return; } if (http_proxy_server_config::get_instance().enable_auth()) { auto proxy_authorization_value = this->request_header->get_header_value("Proxy-Authorization"); bool auth_success = false; if (proxy_authorization_value) { if (authentication::get_instance().auth(*proxy_authorization_value) == auth_result::ok) { auth_success = true; } } if (!auth_success) { this->report_authentication_failed(); return; } } if (this->request_header->method() == "CONNECT") { this->async_connect_to_origin_server(); return; } else { if (this->request_header->scheme() != "http") { this->report_error("400", "Bad Request", "Unsupported scheme"); return; } auto proxy_connection_value = this->request_header->get_header_value("Proxy-Connection"); auto connection_value = this->request_header->get_header_value("Connection"); auto string_to_lower_case = [](std::string& str) { for (auto iter = str.begin(); iter != str.end(); ++iter) { *iter = std::tolower(static_cast<unsigned char>(*iter)); } }; if (proxy_connection_value) { string_to_lower_case(*proxy_connection_value); if (this->request_header->http_version() == "1.1") { this->read_request_context.is_proxy_client_keep_alive = true; if (*proxy_connection_value == "close") { this->read_request_context.is_proxy_client_keep_alive = false; } } else { assert(this->request_header->http_version() == "1.0"); this->read_request_context.is_proxy_client_keep_alive = false; if (*proxy_connection_value == "keep-alive") { this->read_request_context.is_proxy_client_keep_alive = true; } } } else { if (this->request_header->http_version() == "1.1") { this->read_request_context.is_proxy_client_keep_alive = true; } else { this->read_request_context.is_proxy_client_keep_alive = false; } if (connection_value) { string_to_lower_case(*connection_value); if (this->request_header->http_version() == "1.1" && *connection_value == "close") { this->read_request_context.is_proxy_client_keep_alive = false; } else if (this->request_header->http_version() == "1.0" && *connection_value == "keep-alive") { this->read_request_context.is_proxy_client_keep_alive = true; } } } this->read_request_context.content_length = boost::optional<std::uint64_t>(); this->read_request_context.content_length_has_read = 0; this->read_request_context.chunk_checker = boost::optional<http_chunk_checker>(); if (this->request_header->method() == "GET" || this->request_header->method() == "HEAD" || this->request_header->method() == "DELETE") { this->read_request_context.content_length = boost::optional<std::uint64_t>(0); } else if (this->request_header->method() == "POST" || this->request_header->method() == "PUT") { auto content_length_value = this->request_header->get_header_value("Content-Length"); auto transfer_encoding_value = this->request_header->get_header_value("Transfer-Encoding"); if (content_length_value) { try { this->read_request_context.content_length = boost::optional<std::uint64_t>(std::stoull(*content_length_value)); } catch (const std::exception&) { this->report_error("400", "Bad Request", "Invalid Content-Length in request"); return; } this->read_request_context.content_length_has_read = this->request_data.size() - (double_crlf_pos + 4); } else if (transfer_encoding_value) { string_to_lower_case(*transfer_encoding_value); if (*transfer_encoding_value == "chunked") { if (!this->read_request_context.chunk_checker->check(this->request_data.begin() + double_crlf_pos + 4, this->request_data.end())) { this->report_error("400", "Bad Request", "Failed to check chunked response"); return; } return; } else { this->report_error("400", "Bad Request", "Unsupported Transfer-Encoding"); return; } } else { this->report_error("411", "Length Required", std::string()); return; } } else { assert(false); return; } } this->async_connect_to_origin_server(); } else if (this->connection_context.connection_state == proxy_connection_state::read_http_request_content) { if (this->read_request_context.content_length) { this->read_request_context.content_length_has_read += bytes_transferred; } else { assert(this->read_request_context.chunk_checker); if (!this->read_request_context.chunk_checker->check(this->upgoing_buffer_write.begin(), this->upgoing_buffer_write.begin() + bytes_transferred)) { return; } } this->connection_context.connection_state = proxy_connection_state::write_http_request_content; this->async_write_data_to_origin_server(this->upgoing_buffer_write.data(), 0, bytes_transferred); } else if (this->connection_context.connection_state == proxy_connection_state::tunnel_transfer) { this->async_write_data_to_origin_server(this->upgoing_buffer_write.data(), 0, bytes_transferred); } } void http_proxy_server_connection::on_origin_server_data_arrived(std::size_t bytes_transferred) { if (this->connection_context.connection_state == proxy_connection_state::read_http_response_header) { this->response_data.append(this->downgoing_buffer_read.begin(), this->downgoing_buffer_read.begin() + bytes_transferred); auto double_crlf_pos = this->response_data.find("\r\n\r\n"); if (double_crlf_pos == std::string::npos) { if (this->response_data.size() < MAX_RESPONSE_HEADER_LENGTH) { this->async_read_data_from_origin_server(); } else { this->report_error("502", "Bad Gateway", "Response header too long"); } return; } this->response_header = http_header_parser::parse_response_header(this->response_data.begin(), this->response_data.begin() + double_crlf_pos + 4); if (!this->response_header) { this->report_error("502", "Bad Gateway", "Failed to parse response header"); return; } if (this->response_header->http_version() != "1.1" && this->response_header->http_version() != "1.0") { this->report_error("502", "Bad Gateway", "HTTP version not supported"); return; } if (this->response_header->status_code() < 100 || this->response_header->status_code() > 700) { this->report_error("502", "Bad Gateway", "Unexpected status code"); return; } this->read_response_context.content_length = boost::optional<std::uint64_t>(); this->read_response_context.content_length_has_read = 0; this->read_response_context.is_origin_server_keep_alive = false; this->read_response_context.chunk_checker = boost::optional<http_chunk_checker>(); auto connection_value = this->response_header->get_header_value("Connection"); if (this->response_header->http_version() == "1.1") { this->read_response_context.is_origin_server_keep_alive = true; } else { this->read_response_context.is_origin_server_keep_alive = false; } auto string_to_lower_case = [](std::string& str) { for (auto iter = str.begin(); iter != str.end(); ++iter) { *iter = std::tolower(static_cast<unsigned char>(*iter)); } }; if (connection_value) { string_to_lower_case(*connection_value); if (*connection_value == "close") { this->read_response_context.is_origin_server_keep_alive = false; } else if (*connection_value == "keep-alive") { this->read_response_context.is_origin_server_keep_alive = true; } else { this->report_error("502", "Bad Gateway", std::string()); return; } } if (this->request_header->method() == "HEAD") { this->read_response_context.content_length = boost::optional<std::uint64_t>(0); } else if (this->response_header->status_code() == 204 || this->response_header->status_code() == 304) { // 204 No Content // 304 Not Modified this->read_response_context.content_length = boost::optional<std::uint64_t>(0); } else { auto content_length_value = this->response_header->get_header_value("Content-Length"); auto transfer_encoding_value = this->response_header->get_header_value("Transfer-Encoding"); if (content_length_value) { try { this->read_response_context.content_length = boost::optional<std::uint64_t>(std::stoull(*content_length_value)); } catch(const std::exception&) { this->report_error("502", "Bad Gateway", "Invalid Content-Length in response"); return; } this->read_response_context.content_length_has_read = this->response_data.size() - (double_crlf_pos + 4); } else if (transfer_encoding_value) { string_to_lower_case(*transfer_encoding_value); if (*transfer_encoding_value == "chunked") { this->read_response_context.chunk_checker = boost::optional<http_chunk_checker>(http_chunk_checker()); if (!this->read_response_context.chunk_checker->check(this->response_data.begin() + double_crlf_pos + 4, this->response_data.end())) { this->report_error("502", "Bad Gateway", "Failed to check chunked response"); return; } } else { this->report_error("502", "Bad Gateway", "Unsupported Transfer-Encoding"); return; } } else if (this->read_response_context.is_origin_server_keep_alive) { this->report_error("502", "Bad Gateway", "Miss response length info"); return; } } this->async_write_response_header_to_proxy_client(); } else if (this->connection_context.connection_state == proxy_connection_state::read_http_response_content) { if (this->read_response_context.content_length) { this->read_response_context.content_length_has_read += bytes_transferred; } else if (this->read_response_context.chunk_checker) { if (!this->read_response_context.chunk_checker->check(this->downgoing_buffer_read.begin(), this->downgoing_buffer_read.begin() + bytes_transferred)) { return; } } this->connection_context.connection_state = proxy_connection_state::write_http_response_content; this->encryptor->encrypt(reinterpret_cast<const unsigned char*>(&this->downgoing_buffer_read[0]), reinterpret_cast<unsigned char*>(&this->downgoing_buffer_write[0]), bytes_transferred); this->async_write_data_to_proxy_client(this->downgoing_buffer_write.data(), 0, bytes_transferred); } else if (this->connection_context.connection_state == proxy_connection_state::tunnel_transfer) { this->encryptor->encrypt(reinterpret_cast<const unsigned char*>(&this->downgoing_buffer_read[0]), reinterpret_cast<unsigned char*>(&this->downgoing_buffer_write[0]), bytes_transferred); this->async_write_data_to_proxy_client(this->downgoing_buffer_write.data(), 0, bytes_transferred); } } void http_proxy_server_connection::on_proxy_client_data_written() { if (this->connection_context.connection_state == proxy_connection_state::tunnel_transfer) { this->async_read_data_from_origin_server(); } else if (this->connection_context.connection_state == proxy_connection_state::write_http_response_header || this->connection_context.connection_state == proxy_connection_state::write_http_response_content) { if ((this->read_response_context.content_length && this->read_response_context.content_length_has_read >= *this->read_response_context.content_length) || (this->read_response_context.chunk_checker && this->read_response_context.chunk_checker->is_complete())) { boost::system::error_code ec; if (!this->read_response_context.is_origin_server_keep_alive) { this->origin_server_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); this->origin_server_socket.close(ec); } if (this->read_request_context.is_proxy_client_keep_alive) { this->request_data.clear(); this->response_data.clear(); this->request_header = boost::optional<http_request_header>(); this->response_header = boost::optional<http_response_header>(); this->read_request_context.content_length = boost::optional<std::uint64_t>(); this->read_request_context.chunk_checker = boost::optional<http_chunk_checker>(); this->read_response_context.content_length = boost::optional<std::uint64_t>(); this->read_response_context.chunk_checker = boost::optional<http_chunk_checker>(); this->connection_context.connection_state = proxy_connection_state::read_http_request_header; this->async_read_data_from_proxy_client(); } else { this->proxy_client_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); this->proxy_client_socket.close(ec); } } else { this->connection_context.connection_state = proxy_connection_state::read_http_response_content; this->async_read_data_from_origin_server(); } } else if (this->connection_context.connection_state == proxy_connection_state::report_connection_established) { this->start_tunnel_transfer(); } else if (this->connection_context.connection_state == proxy_connection_state::report_error) { boost::system::error_code ec; if (this->origin_server_socket.is_open()) { this->origin_server_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); this->origin_server_socket.close(ec); } if (this->proxy_client_socket.is_open()) { this->proxy_client_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); this->proxy_client_socket.close(ec); } } } void http_proxy_server_connection::on_origin_server_data_written() { if (this->connection_context.connection_state == proxy_connection_state::tunnel_transfer) { this->async_read_data_from_proxy_client(); } else if (this->connection_context.connection_state == proxy_connection_state::write_http_request_header || this->connection_context.connection_state == proxy_connection_state::write_http_request_content) { if (this->read_request_context.content_length) { if (this->read_request_context.content_length_has_read < *this->read_request_context.content_length) { this->connection_context.connection_state = proxy_connection_state::read_http_request_content; this->async_read_data_from_proxy_client(); } else { this->connection_context.connection_state = proxy_connection_state::read_http_response_header; this->async_read_data_from_origin_server(); } } else { assert(this->read_request_context.chunk_checker); if (!this->read_request_context.chunk_checker->is_complete()) { this->connection_context.connection_state = proxy_connection_state::read_http_request_content; this->async_read_data_from_proxy_client(); } else { this->connection_context.connection_state = proxy_connection_state::read_http_response_header; this->async_read_data_from_origin_server(); } } } } void http_proxy_server_connection::on_error(const boost::system::error_code& error) { if (this->connection_context.connection_state == proxy_connection_state::resolve_origin_server_address) { this->report_error("504", "Gateway Timeout", "Failed to resolve the hostname"); } else if (this->connection_context.connection_state == proxy_connection_state::connect_to_origin_server) { this->report_error("502", "Bad Gateway", "Failed to connect to origin server"); } else if (this->connection_context.connection_state == proxy_connection_state::write_http_request_header && this->connection_context.reconnect_on_error) { boost::system::error_code ec; this->origin_server_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); this->origin_server_socket.close(ec); this->async_connect_to_origin_server(); } else { boost::system::error_code ec; if (this->origin_server_socket.is_open()) { this->origin_server_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); this->origin_server_socket.close(ec); } if (this->proxy_client_socket.is_open()) { this->proxy_client_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); this->proxy_client_socket.close(ec); } } } void http_proxy_server_connection::on_timeout() { boost::system::error_code ec; if (this->origin_server_socket.is_open()) { this->origin_server_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); this->origin_server_socket.close(ec); } if (this->proxy_client_socket.is_open()) { this->proxy_client_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); this->proxy_client_socket.close(ec); } } } // namespace azure_proxy <file_sep>/README.md # azure-http-proxy [![Build Status](https://travis-ci.org/lxrite/azure-http-proxy.svg?branch=master)](https://travis-ci.org/lxrite/azure-http-proxy) ## 简介 AHP(Azure Http Proxy)是一款高速、安全、轻量级和跨平台的HTTP代理,使用对称加密算法AES对传输的数据进行加密,使用非对称加密算法RSA传输密钥。 ## 特性 - 一连接一密钥,AHP会对每个连接使用一个随机生成的密钥和初始化向量,避免重复使用同一密钥 - 使用非对称加密算法RSA传输密钥,只需对客户端公开RSA公钥 - 对目标域名的解析在服务端进行,可以解决本地DNS污染的问题 - 服务端同时支持多种数据加密方式,数据加密方式可由客户端任意指定,客户端可以权衡机器性能以及安全需求选择合适的加密方式 - 多线程并发处理,充分利用多处理器的优势,能同时处理成千上万的并发连接 - 多用户支持,允许为每个用户使用独立的帐号和密码 ## 编译和安装 Windows平台可以从 https://github.com/lxrite/azure-http-proxy/releases 下载已经编译好的(win32-binary.zip)。 ### 编译器 AHP使用了部分C++11特性,所以对编译器的版本有较高要求,下面列出了部分已测试过可以用来编译AHP的编译器 - Microsoft Visual Studio >= 2013 - GCC >= 4.8 - Clang >= 3.2 - MinGW >= 4.8 参考:http://en.cppreference.com/w/cpp/compiler_support ### 安装依赖 AHP依赖Boost和OpenSSL库,且要求Boost库版本不低于1.52 绝大多数Linux发行版都可以通过包管理安装Boost和OpenSSL #### Ubuntu $ apt-get install libboost-system-dev $ apt-get install libboost-regex-dev $ apt-get install libssl-dev #### Fedora $ yum install boost-devel $ yum install boost-system $ yum install boost-regex $ yum install openssl $ yum install openssl-devel Windows则需要自己编译Boost库,而OpenSSL库可以从 https://www.openssl.org/related/binaries.html 下载到编译好的。 ### 编译 AHP使用自动化构建工具CMake来实现跨平台构建 - CMake >= 2.8 Windows下可以使用cmake-gui.exe,Linux或其他类Unix系统可以使用下面的命令编译 $ cd azure-http-proxy $ mkdir build $ cd build $ cmake .. $ make 如果编译成功会生成ahpc(客户端)和ahps(服务端)。 ## 配置和运行 完整的配置示例见这里: https://github.com/lxrite/azure-http-proxy/tree/master/example 注意:不要使用示例配置中的RSA私钥和公钥,因为私钥一公开就是不安全的了。 如果你要运行的是服务端,那么你首先需要生成一对RSA密钥对,AHP支持任意长度不小于1024位的RSA密钥。下面的命令使用openssl生成2048位的私钥和公钥 $ openssl genrsa -out rsa_private_key.pem 2048 $ openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem 服务端保留私钥并将公钥告诉客户端。 ### 配置服务端 编辑server.json文件,Windows下应将此文件放到ahps.exe同目录下,Linux或其他类Unix系统将此文件放到~/.ahps/server.json。 { "bind_address": "0.0.0.0", "listen_port": 8090, "rsa_private_key": "-----BEGIN RSA PRIVATE KEY----- ...... -----END RSA PRIVATE KEY-----", "timeout": 240, "workers": 4, "auth": true, "users": [ { "username": "username1", "password": "<PASSWORD>" }, { "username": "foobar", "password": "<PASSWORD>" } ] } 字段名 | 描述 | 是否必选 | 默认值 | ----------------|--------------------|------------------|-----------| bind_address | 服务端绑定的IP地址 | 否 | "0.0.0.0" | listen_port | 服务端绑定的端口 | 否 | 8090 | rsa_private_key | RSA私钥 | 是 | 无 | timeout | 超时时间(秒) | 否 | 240 | workers | 并发工作线程数 | 否 | 4 | auth | 启用代理身份验证 | 否 | false | users | 用户列表 | auth为true时必选 | 无 | ### 配置客户端 编辑client.json文件,Windows下应将此文件放到ahpc.exe或ahpc-gui.exe同目录下,Linux或其他类Unix系统将此文件放到~/.ahpc/client.json。 { "proxy_server_address": "127.0.0.1", "proxy_server_port": 8090, "bind_address": "127.0.0.1", "listen_port": 8089, "rsa_public_key": "-----BEGIN PUBLIC KEY----- ...... -----END PUBLIC KEY-----", "cipher": "aes-256-ofb", "timeout": 240, "workers": 2 } 字段名 | 描述 | 是否必选 | 默认值 | ---------------------|----------------------|------------------|---------------| proxy_server_address | 服务端的IP地址或域名 | 是 | 无 | proxy_server_port | 服务端的端口 | 是 | 无 | bind_address | 客户端绑定的IP地址 | 否 | "127.0.0.1" | listen_port | 客户端的监听端口 | 否 | 8089 | rsa_public_key | RSA公钥 | 是 | 无 | cipher | 加密方法 | 否 | "aes-256-ofb" | timeout | 超时时间(秒) | 否 | 240 | workers | 并发工作线程数 | 否 | 2 | #### 支持的加密方法 - aes-xyz-cfb - aes-xyz-cfb8 - aes-xyz-cfb1 - aes-xyz-ofb - aes-xyz-ctr 中间的xyz可以为128、192或256。 ## 运行 确定配置无误后就可以运行AHP了。 ### 运行服务端 Linux或其他类Unix系统 $ ./ahps Windows $ ahps.exe ### 运行客户端 Linux或其他类Unix系统 $ ./ahpc Windows $ ahpc.exe Enjoy!
bffde890142733e92c36a0782cb1651da701929c
[ "Markdown", "CMake", "C++" ]
18
C++
LazyZhu/azure-http-proxy
2541b51a5c11fb14f0e1347041e6a863bff7bbc8
2e6fb53054b393d4b0b93077ad5698105693cb84
refs/heads/master
<file_sep># midpoint-filter This function will filter the image by the nonlinear midpoint filter method. This function works only for monochrome images, 8 bit per bixel and 24 bit per pixel. The midpoint filter is typically used to filter images containing short tail noises such as Gaussian noise and uniform type. The midpoint filter output is the average of the maximum and minimum gray level values ​​within a local region of the image determined by a specified mask.<file_sep> // #include <stdio.h> #include <stdlib.h> #include "image.h" void image_in(struct Image *IMAGE){ FILE *file; int i, row, column, size, value; char type, file_name, some_thing; char teste[IMAGE->rows]; file = fopen("teste_out.pgm", "r"); if (file == NULL) { printf("Erro na abertura do arquivo de imagem de leitura \n"); } fscanf(file, "%s\r\n", &type); printf("%s", &type); fscanf(file, "%s", &type); printf("%s", &type); fscanf(file, "%s", &type); printf("%s", &type); fscanf(file, "%s", &type); printf("%s", &type); fscanf(file, "%s\r\n", &type); printf("%s\n", &type); fscanf(file, "%d", &row); printf("%d ", row); fscanf(file, "%d", &column); printf("%d\n", column); fscanf(file, "%d", &size); printf("%d\n", size); for(i=0; i<(row*column); i++){ fscanf(file, "%d", &value); IMAGE->data[i] = value; } fclose(file); } void saveImg(struct Image *image) { int i,j, chars = 0; FILE *arq; //ponteiro para arquivo de saída arq = fopen("out_teste.ascii.pgm","w"); if (arq == NULL) { printf("Não criou o arquivo de saida"); } fprintf(arq,"P2\n"); fprintf(arq, "# Created by IrfanView created by PGMA_IO::PGMA_WRITE.\n"); fprintf(arq,"%d %d\n",96,98) ; //cabeçalho do arquivo de saída fprintf(arq,"%d\n",255); int line = 0; for (i=1; i<(9408); i++){ if (line == 511) { fprintf(arq, "\n"); line = 0; } //printf("%d\n", i); // printf("%d", image->data[i*j]); // fprintf(arq, "%d ", image->data[i * j]); chars++; if (chars == 12) { fprintf(arq, "%d \n", image->data[i]); chars = 0; }else{ fprintf(arq, "%d ", image->data[i]); } line++; } // for(i=1; i <= 512; i++) // { // for(j=1; j <= 512; j++) // { // printf("%d\n", ((i * j) - 1)); //// printf("%d", image->data[i*j]); //// fprintf(arq, "%d ", image->data[i * j]); // chars++; // if (chars == 12) { // fprintf(arq, "%d \n", image->data[(i * j) - 1]); // chars = 0; // }else{ // fprintf(arq, "%d ", image->data[(i * j) - 1]); // } // } // fprintf(arq, "\n"); // } fclose(arq); } void image_out(struct Image *IMAGE){ FILE *file,*file2; int i, row, column, size, value = 0,cont = 0; char type, file_name; char teste; file = fopen("out_teste.ascii.pgm", "wb"); file2 = fopen("image001.pgm", "rb"); if (file == NULL) { printf("Erro na abertura do arquivo de imagem de leitura \n"); } fscanf(file2, "%s", &type); printf("%s", &type); fprintf(file,"%s\r\n",&type); fscanf(file2, "%s", &file_name); printf("%s", &file_name); fprintf(file,"%s ",&file_name); fscanf(file2, "%s", &file_name); printf("%s", &file_name); fprintf(file,"%s ",&file_name); fscanf(file2, "%s", &file_name); printf("%s", &file_name); fprintf(file,"%s ",&file_name); fscanf(file2, "%s", &file_name); printf("%s", &file_name); fprintf(file,"%s",&file_name); fscanf(file2, "%d", &row); printf("%d \n", row); fprintf(file,"%d ",row); fscanf(file2, "%d", &column); printf("%d\n", column); fprintf(file,"%d\r\n",column); fscanf(file2, " %d", &size); printf("%d\n", size); fprintf(file,"%d\r\n",size); for(i=0; i<(row * column); i++){ if(cont < 16) { // value = IMAGE->data; fprintf(file,"%d ",value); cont++; } else{ IMAGE->data[i] = value; fprintf(file,"%d \r\n",value); cont=0; } } fclose(file); fclose(file2); } <file_sep> // #ifndef IMAGE_H #define IMAGE_H #include <stdio.h> #include <stdlib.h> struct Image{ int rows; int columns; int data[12000]; unsigned char type; }; void image_in(struct Image *IMAGE); void image_out(struct Image *IMAGE); void saveImg(struct Image *image); #define BASIC 0 #define UINT 1 #endif /*IMAGE_H*/ <file_sep>#include <stdio.h> #include <memory.h> #include<time.h> #include "image.h" //be carefull with the image size, tested image size is 96x98 void midpoint(struct Image *IMAGE, struct Image *IMAGE1){ int x, y, i, j, w, z, smin, smax, n; int a[3][3]; n = 3; for(y=0; y < IMAGE->rows; y++){ for(x=0; x < IMAGE->columns; x++){ smin=255; smax=0; // printf("%d %d\n", x,y); for(j=-n/2; j<=n/2; j++){ for(i=-n/2; i<=n/2; i++){ // if((x+i) <= 0 || (x+i) > IMAGE->columns || (y+j) <= 0 || (y+j) > IMAGE->rows){ a[j+n/2][i+n/2] = -1; }else{ a[j+n/2][i+n/2] = IMAGE->data[x+i+(long)(y+j) * IMAGE->columns]; } } } for(w=0; w<=n-1;w++){ for(z=0; z<=n-1; z++){ if(a[w][z] < smin && a[w][z] >= 0){ smin = a[w][z]; } if(a[w][z] > smax && a[w][z] >= 0){ if (a[w][z] > 255) { smax = 255; }else{ smax = a[w][z]; } } } } IMAGE1->data[x + (long) y * IMAGE->columns] = (smin + smax)/2; //printf("%d\n", (smin + smax)/2); } } } int main() { struct Image in,out; in.rows = out.rows = 96; in.columns = out.columns = 98; clock_t start_Time,end_Time; double time; start_Time = clock(); image_in(&in); midpoint(&in,&out); saveImg(&out); end_Time = clock(); time = ( (end_Time - start_Time) / (CLOCKS_PER_SEC/1000) ); printf("\ntime spend = %f\n", time); return 1; }
77275bc1c7a9f15eda2cc0d908cbdc86bd2d6aa2
[ "Markdown", "C" ]
4
Markdown
yurilimace/midpoint-filter
b962acd76f0dedcd570125ead04892ee53d5b883
fc86ad9ffd45f55c4bf3a550e656b0f5be087ada
refs/heads/master
<repo_name>qdbest/study<file_sep>/auth/spring-auth/src/main/java/com/yucn/config/YucnAuthorizationServerConfig.java package com.yucn.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; /** * Created by Administrator on 2018/12/3. */ @Configuration @EnableAuthorizationServer public class YucnAuthorizationServerConfig{ } <file_sep>/auth/README.md # Spring Security Oauth2 ## 后端 - 加入依赖包 ``` <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> </dependency> ``` - 启动认证服务器 ``` @Configuration @EnableAuthorizationServer public class YucnAuthorizationServerConfig{ } ``` 注意:先实现最原始的功能,所有设置全部采用默认,不要在继承AuthorizationServerConfigurerAdapter,一旦继承,就需要在类中进行相应配置 - 启动资源服务器 ``` @Configuration @EnableResourceServer public class YuCnResourceServerConfig{ } ``` - 运行程序 ![avatar](img/1543924510.png) - postman测试 ![avatar](img/1543924956.png) ![avatar](img/1543925057.png) ## 前端Vue ``` methods: { hello(){ getRequest(`api/hello`,{ headers: {'Authorization': 'bearer ' + this.access_token} }) .then(response=>{ console.log(response.data); }) }, login() { postRequest(`api/oauth/token`, qs.stringify({ grant_type: 'password', username: 'user', password: '<PASSWORD>', scope: 'all' }), { headers: {'content-type': 'application/x-www-form-urlencoded'}, auth: { username: '1ddd7db7-4190-4b7b-88c9-8e4d3a87485f', password: '<PASSWORD>' } }) .then(response => { // localStorage.setItem('token',response.data.access_token); this.access_token=response.data.access_token; console.log(this.access_token); }); } }, ```
39e7d27e8881e87f47f8833166856f87f1e5100d
[ "Markdown", "Java" ]
2
Java
qdbest/study
80684866c187f3348c31731f00b19ee3922ac400
57331c95b0f815372a185998eba9726c1aa8f232
refs/heads/master
<repo_name>bsatrom/wall-of-things<file_sep>/wot-firmware/wot-neopixel-strips/src/soundtocolor.h #ifndef SOUNDCOLOR_H #define SOUNDCOLOR_H struct color { unsigned int Red = 0; unsigned int Green = 0; unsigned int Blue = 0; }; color mapNoteToColor(double soundFrequency); #endif<file_sep>/wot-firmware/wot-neopixel-strips/src/wot-neopixel-strips.cpp #include "application.h" #include "soundtocolor.h" #include "neopixel.h" #include "JsonParserGeneratorRK.h" JsonParserStatic<2048, 100> jsonParser; // IMPORTANT: Set pixel COUNT, PIN and TYPE #define PIXEL_PIN D2 // wot-strip-1 and 3 have 60 lights, 2 and 4 have 30 #define PIXEL_COUNT 30 // NUM of lights #define PIXEL_TYPE WS2812B #define BRIGHTNESS 150 // 0 - 255 #define CHASE_DELAY 30 // Pub/Sub strings for each device // For wot-strip-1 // #define SUB_STRING "startOne" // #define PUB_STRING "startTwo" // For wot-strip-2 #define SUB_STRING "startTwo" #define PUB_STRING "startThree" // For wot-strip-3 // #define SUB_STRING "startThree" // #define PUB_STRING "startFour" // For wot-strip-4 // #define SUB_STRING "startFour" // #define PUB_STRING "startOne" // Strip One is also mounted backwards, so it needs to count up, not down // #define ITERATE_REVERSE true // Set for strips 2-4 #define ITERATE_REVERSE false /* OPTIONS * 0 = RANDOM * 1 = COLOR_OF_SOUND * 2 = TRELLIS * 3 = TRELLIS_PIXEL * 4 = RAINBOW * 5 = CHASE * 6 = BREATHE * 7 = FIRE */ int animationMode = 0; bool useWheel = false; int wheelPos; Adafruit_NeoPixel strip(PIXEL_COUNT, PIXEL_PIN, PIXEL_TYPE); // Cyan by default int redValue = 0; int greenValue = 255; int blueValue = 255; bool lightUp = false; // Animation forward delcarations void rainbow(uint8_t wait); uint16_t Wheel(byte WheelPos); void FadeInOut(byte red, byte green, byte blue); void setAll(byte red, byte green, byte blue); void Fire(int Cooling, int Sparking, int SpeedDelay); void setPixelHeatColor(int Pixel, byte temperature); void playColorOfSound(const char *data) { char *ptr; double freq = strtod(data, &ptr); useWheel = false; if (data && freq != 0) { struct color noteColors; noteColors = mapNoteToColor(freq); redValue = noteColors.Red; greenValue = noteColors.Green; blueValue = noteColors.Blue; } else { greenValue = random(1, 256); redValue = random(1, 256); blueValue = random(1, 256); } } void setColor(const char *event, const char *data) { // Split the comma-delimited list into RGB values jsonParser.clear(); jsonParser.addString(data); if (jsonParser.parse()) { // set to R, G and B redValue = jsonParser.getReference().key("red").valueInt(); greenValue = jsonParser.getReference().key("green").valueInt(); blueValue = jsonParser.getReference().key("blue").valueInt(); } else { Particle.publish("parse-fail", String(data)); } } void playTrellis(const char *data) { wheelPos = atoi(data); useWheel = true; } void playRandom() { useWheel = false; greenValue = random(1, 256); redValue = random(1, 256); blueValue = random(1, 256); } void playTone(const char *event, const char *data) { lightUp = true; switch (animationMode) { case 0: playRandom(); break; case 1: playColorOfSound(data); break; case 2: playTrellis(data); break; default: playRandom(); break; } } void stopTone(const char *event, const char *data) { lightUp = false; } void setAllPixels(u_int16_t red, u_int16_t green, u_int16_t blue) { for (int i = 0; i < strip.numPixels(); i++) { if (useWheel && lightUp) { strip.setPixelColor(i, Wheel(wheelPos)); } else { strip.setPixelColor(i, red, green, blue); } } strip.show(); } int setModeCloud(String args) { int mode = args.toInt(); animationMode = mode; return 1; } void setModeMesh(const char *event, const char *data) { int mode = String(data).toInt(); animationMode = mode; } void chase(uint8_t wait) { if (ITERATE_REVERSE) { for (uint16_t i = strip.numPixels(); i > 0; i--) { strip.setPixelColor(i, strip.Color(redValue, greenValue, blueValue)); strip.show(); delay(wait); } } else { for (uint16_t i = 0; i < strip.numPixels(); i++) { strip.setPixelColor(i, strip.Color(redValue, greenValue, blueValue)); strip.show(); delay(wait); } } } void chaseOff(uint8_t wait) { if (ITERATE_REVERSE) { for (uint16_t i = strip.numPixels(); i > 0; i--) { strip.setPixelColor(i, 0, 0, 0); // Off strip.show(); delay(wait); } } else { for (uint16_t i = 0; i < strip.numPixels(); i++) { strip.setPixelColor(i, 0, 0, 0); // Off strip.show(); delay(wait); } } } void startStrip(const char *event, const char *data) { if (animationMode == 5) { chase(CHASE_DELAY); Mesh.publish(PUB_STRING, NULL); delay(50); chaseOff(CHASE_DELAY); } } void setup() { Serial.begin(9600); strip.setBrightness(BRIGHTNESS); strip.begin(); strip.show(); setAllPixels(0, 0, 255); delay(1000); Mesh.subscribe("tone", playTone); Mesh.subscribe("no-tone", stopTone); Particle.function("setMode", setModeCloud); Particle.variable("mode", animationMode); Mesh.subscribe(SUB_STRING, startStrip); Mesh.subscribe("setMode", setModeMesh); Mesh.subscribe("setColor", setColor); } void loop() { if (animationMode != 4 && animationMode != 5 && animationMode != 6 && animationMode != 7) { if (!lightUp) { setAllPixels(0, 0, 0); } } else if (animationMode == 4) { rainbow(20); } else if (animationMode == 6) { FadeInOut(0xff, 0x77, 0x00); } else if (animationMode == 7) { Fire(55, 120, 15); } } void rainbow(uint8_t wait) { uint16_t i, j; for (j = 0; j < 256; j++) { for (i = 0; i < strip.numPixels(); i++) { strip.setPixelColor(i, Wheel((i + j) & 255)); } strip.show(); delay(wait); } } // Set all pixels in the strip to a solid color, then wait (ms) void colorAll(uint32_t c, uint8_t wait) { uint16_t i; for (i = 0; i < strip.numPixels(); i++) { strip.setPixelColor(i, c); } strip.show(); delay(wait); } uint16_t Wheel(byte WheelPos) { WheelPos = 255 - WheelPos; if (WheelPos < 85) { return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3); } if (WheelPos < 170) { WheelPos -= 85; return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3); } WheelPos -= 170; return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0); } void FadeInOut(byte red, byte green, byte blue) { float r, g, b; for (int k = 0; k < 256; k = k + 1) { r = (k / 256.0) * red; g = (k / 256.0) * green; b = (k / 256.0) * blue; setAll(r, g, b); strip.show(); delay(5); } for (int k = 255; k >= 0; k = k - 2) { r = (k / 256.0) * red; g = (k / 256.0) * green; b = (k / 256.0) * blue; setAll(r, g, b); strip.show(); delay(5); } } void setAll(byte red, byte green, byte blue) { for (int i = 0; i < PIXEL_COUNT; i++) { strip.setPixelColor(i, strip.Color(red, green, blue)); } strip.show(); } void Fire(int Cooling, int Sparking, int SpeedDelay) { static byte heat[PIXEL_COUNT]; int cooldown; // Step 1. Cool down every cell a little for (int i = 0; i < PIXEL_COUNT; i++) { cooldown = random(0, ((Cooling * 10) / PIXEL_COUNT) + 2); if (cooldown > heat[i]) { heat[i] = 0; } else { heat[i] = heat[i] - cooldown; } } // Step 2. Heat from each cell drifts 'up' and diffuses a little for (int k = PIXEL_COUNT - 1; k >= 2; k--) { heat[k] = (heat[k - 1] + heat[k - 2] + heat[k - 2]) / 3; } // Step 3. Randomly ignite new 'sparks' near the bottom if (random(255) < Sparking) { int y = random(7); heat[y] = heat[y] + random(160, 255); //heat[y] = random(160,255); } // Step 4. Convert heat to LED colors for (int j = 0; j < PIXEL_COUNT; j++) { setPixelHeatColor(j, heat[j]); } strip.show(); delay(SpeedDelay); } void setPixelHeatColor(int Pixel, byte temperature) { // Scale 'heat' down from 0-255 to 0-191 byte t192 = round((temperature / 255.0) * 191); // calculate ramp up from byte heatramp = t192 & 0x3F; // 0..63 heatramp <<= 2; // scale up to 0..252 // figure out which third of the spectrum we're in: if (t192 > 0x80) { // hottest strip.setPixelColor(Pixel, 255, 255, heatramp); } else if (t192 > 0x40) { // middle strip.setPixelColor(Pixel, 255, heatramp, 0); } else { // coolest strip.setPixelColor(Pixel, heatramp, 0, 0); } }<file_sep>/wot-firmware/wot-neopixel-strips/src/soundtocolor.cpp #include "soundtocolor.h" #include "math.h" // Color frequency constants, in Hertz double lightFreqRedLower = 400000000000000; double speedOfLightVacuum = 299792458; // m/sec double wavelength(double frequency, double speedOfLight); double frequency(double wavelength, double speedOfLight); color getColorFromWavelength(double wavelength); double factorAdjust(int color, double factor, int intensityMax, double gamma); color mapNoteToColor(double soundFrequency) { struct color noteColor; double lightWavelength, lightWavelengthNM; double lightFrequency = soundFrequency; while (lightFrequency < lightFreqRedLower) { lightFrequency *= 2; } lightWavelength = wavelength(lightFrequency, speedOfLightVacuum); lightWavelengthNM = lightWavelength * 1000000000; noteColor = getColorFromWavelength(lightWavelengthNM); return noteColor; } color getColorFromWavelength(double wavelength) { struct color RGBVals; double gamma = 1.00; int intensityMax = 255; double factor; double Red, Green, Blue; if (wavelength >= 350 && wavelength < 440) { // From Purple (1, 0, 1) to Blue (0, 0, 1), with increasing intensity (set below) Red = -(wavelength - 440) / (440 - 350); Green = 0.0; Blue = 1.0; } else if (wavelength >= 440 && wavelength < 490) { // From Blue (0, 0, 1) to Cyan (0, 1, 1) Red = 0.0; Green = (wavelength - 440) / (490 - 440); Blue = 1.0; } else if (wavelength >= 490 && wavelength < 510) { // From Cyan (0, 1, 1) to Green (0, 1, 0) Red = 0.0; Green = 1.0; Blue = -(wavelength - 510) / (510 - 490); } else if (wavelength >= 510 && wavelength < 580) { // From Green (0, 1, 0) to Yellow (1, 1, 0) Red = (wavelength - 510) / (580 - 510); Green = 1.0; Blue = 0.0; } else if (wavelength >= 580 && wavelength < 645) { // From Yellow (1, 1, 0) to Red (1, 0, 0) Red = 1.0; Green = -(wavelength - 645) / (645 - 580); Blue = 0.0; } else if (wavelength >= 645 && wavelength <= 780) { // Solid Red (1, 0, 0), with decreasing intensity (set below) Red = 1.0; Green = 0.0; Blue = 0.0; } else { Red = 0.0; Green = 0.0; Blue = 0.0; } // Intensity factor goes through the range: // 0.1 (350-420 nm) 1.0 (420-645 nm) 1.0 (645-780 nm) 0.2 if (wavelength >= 350 && wavelength < 420) { factor = 0.1 + 0.9 * (wavelength - 350) / (420 - 350); } else if (wavelength >= 420 && wavelength < 645) { factor = 1.0; } else if (wavelength >= 645 && wavelength <= 780) { factor = 0.2 + 0.8 * (780 - wavelength) / (780 - 645); } else { factor = 0.0; } RGBVals.Red = factorAdjust(Red, factor, intensityMax, gamma); RGBVals.Green = factorAdjust(Green, factor, intensityMax, gamma); RGBVals.Blue = factorAdjust(Blue, factor, intensityMax, gamma); return RGBVals; } double factorAdjust(int color, double factor, int intensityMax, double gamma) { if (color == 0.0) { return 0; } else { return round(intensityMax * pow(color * factor, gamma)); } } double wavelength(double frequency, double speedOfLight) { return (speedOfLight / frequency); } double frequency(double wavelength, double speedOfLight) { return (speedOfLight / wavelength); }<file_sep>/wot-firmware/wot-controller/src/wot-controller.cpp #include "application.h" /* * Project wot-controller * Description: * Author: * Date: */ int stripMode = 0; int setStripMode(String args); int setColors(String args); int startChase(String args); void setup() { // Put initialization like pinMode and begin functions here. Particle.function("setMode", setStripMode); Particle.function("setColors", setColors); Particle.function("chase", startChase); Particle.variable("stripMode", stripMode); } void loop() { } int setStripMode(String args) { Mesh.publish("setMode", args); stripMode = args.toInt(); return 1; } int setColors(String args) { Mesh.publish("setColors", args); return 1; } int startChase(String args) { Mesh.publish("startOne", args); return 1; }<file_sep>/wot-firmware/wot-marquee/README.md # wot-marquee Marquee Firmware for the Particle Wall of Things ## Marquee Features 1. Particle Logo and text "Wall of Things" 2. Scrolling Particle Logos 3. "Now Live on Twitch" 4. Plasma Demo <file_sep>/wot-firmware/wot-neopixel-strips/README.md # Wall of Things Neopixel Strips ### Features 1. Rainbow animation 2. Set to single color and flicker 3. Fade in and out of single color 4. Light chase with Mesh pub/sub between strips - Chase up, chase down - Chase each light - How to set color - Set the pixel count correctly on each - Use the name to determine if its 1, 2, 3 or 4 <file_sep>/wot-firmware/wot-neopixel-strips/project.properties name=wot-neopixel-strips dependencies.neopixel=1.0.0 dependencies.JsonParserGeneratorRK=0.0.6 <file_sep>/README.md # wall-of-things Master repo for software and firmware related to the Wall Of Things project
0f840e04a96c4a904a843db1e816d23c0bf67f14
[ "Markdown", "C", "C++", "INI" ]
8
C
bsatrom/wall-of-things
fb7f635125dec7005e83e225306226ed831e5200
735aaf823329ce8efb0fabb5d4b1cbc738d03bfe
refs/heads/master
<file_sep>import java.util.Date; public class HallBooking { private Hall hall; private Event event; public HallBooking(){} public HallBooking(Hall hall, Event event) { this.hall = hall; this.event = event; } public Hall getHall() { return hall; } public void setHall(Hall hall) { this.hall = hall; } public Event getEvent() { return event; } public void setEvent(Event event) { this.event = event; } public String toString() { return "Evnet Details\n"+this.event+"\nHall Details\n"+this.hall; } }<file_sep>public class Hall { private String name; private String contact; private Double costPerDay; private String owner; public Hall(){} public Hall(String name, String contact, Double costPerDay, String owner) { this.name = name; this.contact = contact; this.costPerDay = costPerDay; this.owner = owner; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public Double getCostPerDay() { return costPerDay; } public void setCostPerDay(Double costPerDay) { this.costPerDay = costPerDay; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String toString() { return "Name: "+this.name+"\nContact: "+this.contact+"\nCost per Day: "+this.costPerDay+"\nOwner: "+this.owner; } }<file_sep>public class Event { private String name; private String detail; private String type; private String organiser; private Integer attendeesCount; private Double projectedExpense; public Event(){} public Event(String name,String detail, String type, String organiser,Integer attendeesCount, Double projectedExpense) { this.name = name; this.detail = detail; this.type = type; this.organiser = organiser; this.attendeesCount = attendeesCount; this.projectedExpense = projectedExpense; } public String getName() { return name; } public void setName(String name) { this.name=name; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getOrganiser() { return organiser; } public void setOrganiser(String organiser) { this.organiser = organiser; } public Integer getAttendeesCount() { return attendeesCount; } public void setAttendeesCount(Integer attendeesCount) { this.attendeesCount = attendeesCount; } public Double getProjectedExpense() { return projectedExpense; } public void setProjectedExpense(Double projectedExpense) { this.projectedExpense = projectedExpense; } public String toString() { return "Name: "+this.name+"\nDetails: "+this.detail+"\nType: "+this.type+"\nOrganiser: "+this.organiser+"\nAttendees count: "+this.attendeesCount+"\nProjected Expense: "+this.projectedExpense; } }
2efd2f1f5ff69766f59f50d433b271809011a9a0
[ "Java" ]
3
Java
ebox-online/pipelineUbuntu
c72e0746d1bf4d6c7fba90e00e7bc2c8b1f7b292
1664de3077778e5c1859d5bf82e5e95970ec5bae
refs/heads/master
<file_sep>class CreateSearches < ActiveRecord::Migration[5.0] def change create_table :searches do |t| t.string :keywords t.string :country t.date :arrival_date_from t.date :arrival_date_to t.date :visa_expiry_date_from t.date :visa_expiry_date_to t.integer :status t.integer :level t.timestamps end end end <file_sep>class MehmenController < ApplicationController before_action :authenticate_user!, except: [:index, :show] before_action :set_mehman, only: [:show, :edit, :update, :destroy, :return, :back] def index @q = Mehman.ransack(params[:q]) @results = @q.result(distinct: true) @results = @results.where(status: :staying) unless params[:q] @mehmen = @results.paginate(:page => params[:page], :per_page => 50) end def show end def new @mehman = Mehman.new get_session_data end def create @mehman = Mehman.new(mehman_params.merge(user: current_user)) if @mehman.save set_session_data redirect_to :back, notice: 'Successfully created new Mehman!' else render 'new' end end def edit end def update if @mehman.update(mehman_params.merge(user: current_user)) redirect_to :back, notice: 'Successfully updated Mehman!' else render 'edit' end end def destroy @mehman.destroy redirect_to :back, notice: 'Successfully deleted the Mehman!' end def return @mehman.update_attributes(user: current_user, status: :returned) redirect_to :back, notice: 'Successfully changed status to Returned!' end def back @mehman.update_attributes(user: current_user, status: :staying) redirect_to :back, notice: 'Successfully changed status to Staying!' end private def set_mehman @mehman = Mehman.find_by(id: params[:id]) end def mehman_params params.require(:mehman).permit(:code, :full_name, :passport_no, :country, :arrival_date, :departure_date, :visa_expiry_date, :status, :level) end def set_session_data session[:mehman] = {} unless session[:mehman] session[:mehman]['country'] = @mehman.country session[:mehman]['arrival_date'] = @mehman.arrival_date end def get_session_data return unless session[:mehman] @mehman.country = session[:mehman]['country'] @mehman.arrival_date = session[:mehman]['arrival_date'] end end <file_sep>class ChangeDefaultLevelToMehmen < ActiveRecord::Migration[5.0] def change change_column_default :mehmen, :level, default: nil end end <file_sep>class Mehman < ApplicationRecord has_one :visa enum status: [:staying, :returned] enum level: [:normal, :safe, :danger] before_save :set_level validates :code, length: { in: 2..8 }, presence: true validates :passport_no, :full_name, :country, :arrival_date, :visa_expiry_date, presence: true validates_uniqueness_of :code, case_sensitive: false validates_uniqueness_of :passport_no, case_sensitive: false validate :visa_expiry_date_cannot_be_in_the_past validate :visa_expiry_date_must_be_greater_than_arrival_date def country_name ISO3166::Country[country] end # VALIDATION def visa_expiry_date_cannot_be_in_the_past if visa_expiry_date.present? && visa_expiry_date < Date.today errors.add(:visa_expiry_date, "can't be in the past") end end def visa_expiry_date_must_be_greater_than_arrival_date if visa_expiry_date <= arrival_date errors.add(:visa_expiry_date, "must be greater than arrival date ") end end ### private def set_level if visa_expiry_date - arrival_date > 119 self.level = :safe elsif departure_date == nil self.level = :normal elsif visa_expiry_date >= departure_date self.level = :safe elsif visa_expiry_date < departure_date self.level = :danger else self.level = :normal end end end <file_sep>class AddStatusToMehmen < ActiveRecord::Migration[5.0] def change add_column :mehmen, :status, :integer, default: 0 end end <file_sep>class RemoveCategoryAndSerialFromMehmen < ActiveRecord::Migration[5.0] def change remove_column :mehmen, :category, :string remove_column :mehmen, :serial, :integer end end <file_sep>class Search < ApplicationRecord def mehmen @mehmen ||= find_mehmen end private def find_mehmen mehmen = Mehman.all mehmen = mehmen.where('status = ?', status) if status.present? mehmen = mehmen.where('level = ?', level) if level.present? mehmen = mehmen.where(['code LIKE ? OR full_name LIKE ? OR passport_no LIKE ?' , "%#{keywords}%", "%#{keywords}%", "%#{keywords}%"]) if keywords.present? mehmen = mehmen.where('country LIKE ?', country) if country.present? mehmen = mehmen.where('arrival_date >= ?', arrival_date_from) if arrival_date_from.present? mehmen = mehmen.where('arrival_date <= ?', arrival_date_to) if arrival_date_to.present? mehmen = mehmen.where('visa_expiry_date >= ?', visa_expiry_date_from) if visa_expiry_date_from.present? mehmen = mehmen.where('visa_expiry_date <= ?', visa_expiry_date_to) if visa_expiry_date_to.present? return mehmen end end <file_sep>class VisasController < ApplicationController before_action :set_visa, only: [:show, :edit, :update, :destroy, :return, :back] def index @q = Mehman.ransack(params[:q]) @results = @q.result(distinct: true) @visas = @results.paginate(:page => params[:page], :per_page => 25) end def show end def new @mehman = Mehman.find_by(id: params[:mehman_id]) @visa = Visa.new end def create @visa = Visa.new(visa_params) if @visa.save? redirect_to :back, notice: 'Successfully created new Visa!' else render 'new' end end private def set_visa @visa = Visa.find_by(id: params[:id]) end def visa_params params.require(:visa).permit(:file_no, :submission_date, :apply_date, :code, :status) end end <file_sep>class UpdateMehmenCodeColumn < ActiveRecord::Migration[5.0] def change remove_column :mehmen, :code, :string add_column :mehmen, :category, :string, default: 'english' add_column :mehmen, :serial, :integer end end <file_sep>class AddUserReferencesToMehmen < ActiveRecord::Migration[5.0] def change add_reference :mehmen, :user, foreign_key: true end end <file_sep>class AddIndexToMehmen < ActiveRecord::Migration[5.0] def change add_index :mehmen, :code, unique: true add_index :mehmen, :passport_no, unique: true end end <file_sep>class Visa < ApplicationRecord belongs_to :mehman enum status: [:applied, :confirmed] end <file_sep>class SearchesController < ApplicationController before_action :find_search, only: [:show] def new @search = Search.new @countries = Mehman.uniq.pluck(:country) @statuses = Mehman.uniq.pluck(:status) @levels = Mehman.uniq.pluck(:level) end def create @search = Search.create!(search_params) redirect_to @search end def show end private def find_search @search = Search.find_by(id: params[:id]) end def search_params params.require(:search).permit(:keywords, :country, :arrival_date_from, :arrival_date_to, :visa_expiry_date_from, :visa_expiry_date_to, :status, :level) end end <file_sep>class CreateVisas < ActiveRecord::Migration[5.0] def change create_table :visas do |t| t.string :file_no t.date :submission_date t.date :apply_date t.integer :status, default: 0 t.timestamps end end end <file_sep>class AddMehmanToVisas < ActiveRecord::Migration[5.0] def change add_reference :visas, :mehman, foreign_key: true end end <file_sep>class CreateMehmen < ActiveRecord::Migration[5.0] def change create_table :mehmen do |t| t.string :code t.string :full_name t.string :passport_no t.string :country t.date :arrival_date t.string :arrival_info t.date :departure_date t.string :departure_info t.date :visa_expiry_date t.timestamps end end end
8557686db9ae4a228b787aab5ada7b0e4460f3d8
[ "Ruby" ]
16
Ruby
neerajmaurya07/amanat1
40608c2c4a103a4484d027b92f2218f32d084d76
ad27c9ca02c07319eb908fcd161c03d8ce5e3a50
refs/heads/master
<file_sep> # Uga\_Uga Don't use this. Use [Parslet](http://kschiess.github.io/parslet/) or [OMeta](https://github.com/alexwarth/ometa-js). Here is a video on creating your own external DSL: [Writing DSL's with Parslet by <NAME>](https://www.youtube.com/watch?v=ET_POMJNWNs) ## Installation gem 'uga_uga' ## Usage ```ruby require "uga_uga" code = <<-EOF bobby { howie { :funny } mandel { "comedian" } } EOF results = [] Uga_Uga.new code do case when rex?("(white*)(word) { ") line = shift results << "#{captures.last} was called" {:raw=>grab_until(bracket(line, '}'))} when rex?(" (word) { (...) } ") results << "#{captures.first} called with #{captures.last}" else fail ArgumentError, "Command not found: #{l!.inspect}" end # === case name end # === .new results ``` <file_sep>require "rex_dots" class Uga_Uga NEW_LINE_REGEXP = /\n/ NOTHING = ''.freeze module String_Refines refine String do def blank? strip.empty? end end end class << self # # This method is used mainly used in # tests/specs to remove the "noise" # (whitespace, empty lines, etc) # during parsing. # def clean arg case arg when String str = arg.strip return nil if str.empty? str when Array arg.map { |unknown| clean unknown }.compact else arg end end # === def clean end # === class self === attr_reader :stack, :line_num, :parent, :captures def initialize str_or_arr = nil, *args @origin = str_or_arr @instruct = block_given? ? Proc.new : nil @stack = [] @captures = nil @parent = nil file_or_number = nil args.each { |o| case o when Uga_Uga @parent = o file_or_number ||= o.line_num when Numeric file_or_number = o when String file_or_number = o else fail ArgumentError, "Unknown argument: #{o.inspect}" end } return unless @origin if str_or_arr.is_a?(String) str = str_or_arr @lines = str_or_arr.split(NEW_LINE_REGEXP) else str = nil @lines = str_or_arr end @origin = str_or_arr @old = [] @line_num = if file_or_number.is_a? Numeric file_or_number else contents = File.read(file_or_number || __FILE__ ) index = contents.index(str || @lines.join("\n")) if index contents[0,index + 1].split("\n").size else 1 end end run end # === def uga def l! @lines.first end private # =============================================== def rex? str, *args reg_exp = Rex_Dots.exp(str, *args) match = l!.match reg_exp @captures = match ? match.captures : nil !!match end def bracket l, close index = l.index(/[^\ ]/) "#{" " * index}#{close}" end def skip throw :skip end def white? l!.strip.empty? end def first *args l!.split.first.split(*args).first.strip end def split *args l!.split *args end def save_as cmd, data = nil @stack.last[:type] = cmd if data @stack.<<( @stack.pop.merge(data) ) end @stack.last end def shift @old << @lines.shift @line_num = @line_num + 1 @old.last end def head? str_or_rxp rxp = if str_or_rxp.is_a?(String) e = Regexp.escape str_or_rxp /\A\ *#{e}/ else str_or_rxp end l![rxp] end def tail? str_or_rxp rxp = if str_or_rxp.is_a?(String) e = Regexp.escape str_or_rxp /#{e}\ *\z/ else str_or_rxp end l![rxp] end def grab_all blok = [] while !@lines.empty? blok << shift end blok end def grab_all_or_until period grab_until period, :close_optional end def grab_until period, *opts new_cmd = nil blok = [] found = false line_num = @line_num is_line = period.is_a?(Regexp) ? period : /\A#{Regexp.escape period}\ *\Z/ while !found && (l = shift) if !(found =l[is_line]) blok << l end end if !found && !opts.include?(:close_optional) fail ArgumentError, "Missing from around line number: #{line_num}: #{period.inspect}\n#{blok.join "\n"}" end blok end public def run *args return(Uga_Uga.new(*args, &@instruct)) unless args.empty? return @stack unless @stack.empty? while !@lines.empty? size = @lines.size num = line_num catch(:skip) do result = instance_eval(&@instruct) if result.is_a?(Hash) @stack << result @stack.last[:line_num] = num end end shift if size == @lines.size end @stack.each { |h| next if !h[:raw] || h[:done?] if h[:type] == String h[:output] = h[:raw].join("\n") h.delete :raw next end if h[:type] == Array h[:output] = h[:raw] h.delete :raw next end h[:output] = Uga_Uga.new(h.delete(:raw), h[:line_num], self, &@instruct).stack } end # === def run end # === class Uga_Uga === <file_sep> require 'Bacon_Colored' require 'uga_uga' require 'pry' require 'awesome_print' module Bacon class Context def clean o return o.strip if o.is_a?(String) return o unless o.is_a?(Array) || o.is_a?(Uga_Uga) return clean(o.stack) if o.respond_to?(:stack) o.inject([]) do |memo, hash| memo << hash[:type] unless hash[:type] == String memo << clean(hash[:output]) memo end end def uga *args SAMPLE.run *args end end # === class Context end # === module Bacon SAMPLE = Uga_Uga.new do skip if white? case when rex?("(white*)(...) { ") # === multi-line css close = captures.first shift final = { :type => :css, :selectors => captures.last, :raw => grab_until(/\A#{close}\}\ *\Z/) } when rex?(" (!{) {(...)} ") # === css one-liner selectors , content = captures shift final = { :type => :css, :selectors => selectors, :raw => [content], :one_liner => true } when rex?(" String (word) ") # === Multi-line String close = captures.first shift final = { :type => String, :output => grab_until(/\A\ *#{Regexp.escape close}\ *\Z/).join("\n") } when rex?(" color (word) ") # l![/\A\ *color\ *([a-zA-Z0-9\-\_\#]+)\ *\Z/] val = captures.first final = { :type => :css_property, :name => :color, :output=> val } when rex?(" id (word) ") # l![/\A\ *id\ *([a-zA-Z0-9\-\_\#]+)\ *\Z/] val = captures.first final = { :type => :id!, :output=> val } else tag = first('.') if tail?("/#{tag}") {:type=>:html, :tag=>tag.to_sym, :one_liner=>true, :output => shift} else tag = tag.to_sym case tag when :p, :a line = shift bracket = bracket(line, "/#{tag}") final = {:type=>:html, :tag=>tag, :selector => line, :raw=>grab_until(bracket)} final else if stack.empty? {:type=>String, :raw=>grab_all} elsif rex?(" (_) ", /\-{4,}/) # Start of multi-line string -------------------- eos = l!.rstrip shift {:type=>String, :raw=>grab_all_or_until(/\A#{eos}\ *|Z/)} else fail ArgumentError, "Unknown command: #{line_num}: #{l!.inspect}" end end end end # === case end # === .new <file_sep> describe :uga.inspect do it "runs" do code = <<-EOF p { "my paragraph" } EOF o = Uga_Uga.new(code) do case when rex?(" (word) { ") final = { :type =>captures.first, :raw =>grab_until(bracket shift, '}') } when stack.empty? final = { :type=>String, :output=>grab_all.join("\n") } else fail ArgumentError, "Unknown common: #{l!}" end end clean(o).should == [ 'p', ['"my paragraph"'] ] end it "runs code from README.md" do file = File.expand_path(File.dirname(__FILE__) + '/../README.md') contents = File.read( file ) code = (contents[/```ruby([^`]+)```/] && $1).gsub('puts ','') result = eval(code, nil, file, contents.split("\n").index('```ruby') + 1) result.should == [ "bobby was called", "howie called with :funny", 'mandel called with "comedian"' ] end # === it it "parses lines without blocks" do code = <<-EOF a :href => addr /a a :href addr /a p { } EOF clean(uga code). should == [ :html, "a :href => addr /a", :html, "a :href addr /a", :css, [] ] end it "parses inner blocks" do code = <<-EOF p { span { inner { "my" } } } EOF clean(uga code). should == [ :css, [ :css, [ :css, ['"my"'] ] ] ] end it "passes all text before a block start: cmd, cmd {" do result = [] code = %^ cmd, cmd { inner, inner { } } ^ uga(code).stack.first[:selectors] .should == "cmd, cmd" end # === it it "does not parse mustaches as blocks: {{ }}" do code = " p { {{code}} } " clean(uga(code)).should == [:css, ['{{code}}']] end # === it end # === describe :uga
333df24600fd41b392a2ed74a16ad9d8c8dfa301
[ "Markdown", "Ruby" ]
4
Markdown
da99/uga_uga
0cde36226736e764eb53753ac3650dda2a09f237
ea828f82e10a42fd8adf5e698aabb8afe7e4c424
refs/heads/master
<repo_name>xiaxianyue/PyProject<file_sep>/day01.py i = 8 i= str(i) print(i)
d957564ed961080341e442b31b438ce0e79e1f4b
[ "Python" ]
1
Python
xiaxianyue/PyProject
dc68761f544de2a3c923f6d0fa77cd88211d6200
b589b3ff58a2dc10033cde8c4abbd4d3bed6ca8a
refs/heads/master
<repo_name>pincanna/investors-portal<file_sep>/app/views/encrypted_memos/_encrypted_memo.json.jbuilder json.extract! encrypted_memo, :id, :uid, :title, :body, :created_at, :updated_at json.url encrypted_memo_url(encrypted_memo, format: :json) <file_sep>/test/decorators/users/role_decorator_test.rb require 'test_helper' class Users::RoleDecoratorTest < Draper::TestCase end <file_sep>/app/helpers/users/verification_codes_helper.rb module Users::VerificationCodesHelper end <file_sep>/app/models/user.rb class User < ApplicationRecord rolify # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :invitable, :password_archivable, :session_limitable, :paranoid_verification, :masqueradable, :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :omniauthable after_create :generate_paranoid_code has_person_name acts_as_messageable has_many :notifications, foreign_key: :recipient_id has_many :login_activities, as: :user has_many :services has_many :encrypted_memos has_many :access_grants, class_name: 'Doorkeeper::AccessGrant', foreign_key: :resource_owner_id, dependent: :delete_all # or :destroy if you need callbacks has_many :access_tokens, class_name: 'Doorkeeper::AccessToken', foreign_key: :resource_owner_id, dependent: :delete_all # or :destroy if you need callbacks def self.invite_key_fields [:email] end def mailboxer_email(object) email end def invitation_limit if self.has_role?(:user_inviter) return nil else return 0 end end end <file_sep>/app/policies/mailboxer/conversation_policy.rb class Mailboxer::ConversationPolicy < ApplicationPolicy def index? true end def show? record.recipients.include?(user) || user.has_role?(:messages_admin) end def create? true end def reply? true end class Scope < Scope def resolve scope.all end end end <file_sep>/db/migrate/20191015050013_create_encrypted_memos.rb class CreateEncryptedMemos < ActiveRecord::Migration[6.0] def change create_table :encrypted_memos do |t| t.string :uid t.string :title t.text :encrypted_body t.string :encrypted_body_iv t.timestamps end add_index :encrypted_memos, :uid, unique: true end end <file_sep>/test/controllers/encrypted_memos_controller_test.rb require 'test_helper' class EncryptedMemosControllerTest < ActionDispatch::IntegrationTest setup do @encrypted_memo = encrypted_memos(:one) end test "should get index" do get encrypted_memos_url assert_response :success end test "should get new" do get new_encrypted_memo_url assert_response :success end test "should create encrypted_memo" do assert_difference('EncryptedMemo.count') do post encrypted_memos_url, params: { encrypted_memo: { body: @encrypted_memo.body, title: @encrypted_memo.title, uid: @encrypted_memo.uid } } end assert_redirected_to encrypted_memo_url(EncryptedMemo.last) end test "should show encrypted_memo" do get encrypted_memo_url(@encrypted_memo) assert_response :success end test "should get edit" do get edit_encrypted_memo_url(@encrypted_memo) assert_response :success end test "should update encrypted_memo" do patch encrypted_memo_url(@encrypted_memo), params: { encrypted_memo: { body: @encrypted_memo.body, title: @encrypted_memo.title, uid: @encrypted_memo.uid } } assert_redirected_to encrypted_memo_url(@encrypted_memo) end test "should destroy encrypted_memo" do assert_difference('EncryptedMemo.count', -1) do delete encrypted_memo_url(@encrypted_memo) end assert_redirected_to encrypted_memos_url end end <file_sep>/test/decorators/users/verification_code_decorator_test.rb require 'test_helper' class Users::VerificationCodeDecoratorTest < Draper::TestCase end <file_sep>/app/helpers/users/login_activities_helper.rb module Users::LoginActivitiesHelper end <file_sep>/app/controllers/users/verification_codes_controller.rb class Users::VerificationCodesController < ApplicationController before_action :authenticate_user! def index @users = User.where("paranoid_verification_code IS NOT NULL") redirect_to root_path, notice: "You don't have access." unless current_user.has_role?(:verifier) end end <file_sep>/test/decorators/api/v1/base_decorator_test.rb require 'test_helper' class Api::V1::BaseDecoratorTest < Draper::TestCase end <file_sep>/app/controllers/users/registrations_controller.rb class Users::RegistrationsController < Devise::RegistrationsController def new redirect_to controller: 'devise/sessions', action: 'new' end def create render plain: 'This is not allowed.' end end<file_sep>/test/decorators/messages/inbox_decorator_test.rb require 'test_helper' class Messages::InboxDecoratorTest < Draper::TestCase end <file_sep>/app/controllers/encrypted_memos_controller.rb # frozen_string_literal: true class EncryptedMemosController < ApplicationController before_action :authenticate_user! before_action :set_encrypted_memo, only: %i[show edit update destroy] rescue_from Pundit::NotAuthorizedError, with: :not_authorized # GET /encrypted_memos # GET /encrypted_memos.json def index @encrypted_memos = EncryptedMemo.all authorize @encrypted_memos end # GET /encrypted_memos/1 # GET /encrypted_memos/1.json def show; end # GET /encrypted_memos/new def new @encrypted_memo = EncryptedMemo.new authorize @encrypted_memo end # GET /encrypted_memos/1/edit def edit; end # POST /encrypted_memos # POST /encrypted_memos.json def create @encrypted_memo = current_user.encrypted_memos.new(encrypted_memo_params) authorize @encrypted_memo respond_to do |format| if @encrypted_memo.save format.html { redirect_to @encrypted_memo, notice: 'Encrypted memo was successfully created.' } format.json { render :show, status: :created, location: @encrypted_memo } else format.html { render :new } format.json { render json: @encrypted_memo.errors, status: :unprocessable_entity } end end end # PATCH/PUT /encrypted_memos/1 # PATCH/PUT /encrypted_memos/1.json def update respond_to do |format| if @encrypted_memo.update(encrypted_memo_params) format.html { redirect_to @encrypted_memo, notice: 'Encrypted memo was successfully updated.' } format.json { render :show, status: :ok, location: @encrypted_memo } else format.html { render :edit } format.json { render json: @encrypted_memo.errors, status: :unprocessable_entity } end end end # DELETE /encrypted_memos/1 # DELETE /encrypted_memos/1.json def destroy @encrypted_memo.destroy respond_to do |format| format.html { redirect_to encrypted_memos_url, notice: 'Encrypted memo was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_encrypted_memo @encrypted_memo = EncryptedMemo.find(params[:id]) authorize @encrypted_memo end # Never trust parameters from the scary internet, only allow the white list through. def encrypted_memo_params params.require(:encrypted_memo).permit(:title, :body) end def not_authorized redirect_to root_url, notice: "You are not authorized. <strong>Action</strong>: #{action_name} <strong>Object</strong>: EncryptedMemo" end end <file_sep>/app/views/encrypted_memos/show.json.jbuilder json.partial! "encrypted_memos/encrypted_memo", encrypted_memo: @encrypted_memo <file_sep>/app/controllers/messages/inbox_controller.rb class Messages::InboxController < ApplicationController before_action :authenticate_user! def index @conversations = current_user.mailbox.inbox end end <file_sep>/app/controllers/users/roles_controller.rb class Users::RolesController < ApplicationController before_action :authenticate_user! def create @user = User.find(params[:profile_id]) authorize Role if @user.add_role(role_params[:name]) redirect_to users_profile_path(@user), notice: "Success!" else redirect_to users_profile_path(@user), notice: "Role was not added." end end def destroy @user = User.find(params[:profile_id]) @role = Role.find(params[:id]) authorize @role if @user.remove_role(@role.name) redirect_to users_profile_path(@user), notice: 'Role removed.' else redirect_to users_profile_path(@user), notice: 'Role could not be removed.' end end private def role_params params.require(:role).permit(:name) end end <file_sep>/test/decorators/users/directory_decorator_test.rb require 'test_helper' class Users::DirectoryDecoratorTest < Draper::TestCase end <file_sep>/test/decorators/encrypted_memo_decorator_test.rb require 'test_helper' class EncryptedMemoDecoratorTest < Draper::TestCase end <file_sep>/test/decorators/messages/conversation_decorator_test.rb require 'test_helper' class Messages::ConversationDecoratorTest < Draper::TestCase end <file_sep>/app/controllers/users/invitations_controller.rb class Users::InvitationsController < Devise::InvitationsController before_action :authorize , only: [:new, :create] private def authorize redirect_to root_url, notice: 'You cannot do that' unless current_user.has_role?(:user_inviter) end end<file_sep>/app/helpers/messages/conversations_helper.rb module Messages::ConversationsHelper end <file_sep>/app/models/encrypted_memo.rb class EncryptedMemo < ApplicationRecord has_secure_token :uid attr_encrypted :body, key: Rails.application.credentials.dig(:encryption_key) belongs_to :user, optional: true validates :title, :body, presence: true end <file_sep>/app/controllers/messages/sentbox_controller.rb class Messages::SentboxController < ApplicationController before_action :authenticate_user! def index @conversations = current_user.mailbox.sentbox end end <file_sep>/app/controllers/messages/conversations_controller.rb # frozen_string_literal: true class Messages::ConversationsController < ApplicationController before_action :authenticate_user! def show @conversation = Mailboxer::Conversation.find(params[:id]) authorize @conversation @receipts = @conversation.receipts_for current_user @conversation.mark_as_read(current_user) end def new; end def create authorize Mailboxer::Conversation recipient = User.find(conversation_params[:recipient]) if receipt = current_user.send_message(recipient, conversation_params[:body], conversation_params[:subject]) redirect_to messages_conversation_url(receipt.conversation), notice: 'Message sent.' else render :new end end def reply @conversation = Mailboxer::Conversation.find(params[:id]) authorize @conversation if current_user.reply_to_conversation(@conversation, reply_params[:body]) redirect_to messages_conversation_url(@conversation) else render :show end end private def conversation_params params.require(:conversation).permit(:subject, :body, :recipient) end def reply_params params.require(:reply).permit(:body) end end <file_sep>/config/initializers/cloudinary.rb Cloudinary.config do |config| config.cloud_name = Rails.application.credentials.dig(:cloudinary, :cloud_name) config.api_key = Rails.application.credentials.dig(:cloudinary, :api_key) config.api_secret = Rails.application.credentials.dig(:cloudinary, :api_secret) config.secure = true config.cdn_subdomain = false end<file_sep>/app/policies/document_policy.rb class DocumentPolicy < ApplicationPolicy def index? user.has_role?(:document_reader) end def show? user.has_role?(:document_reader) end def update? user.has_role?(:document_editor) end def create? user.has_role?(:document_creator) end def destroy? user.has_role?(:document_destroyer) end class Scope < Scope def resolve if user.has_role?(:document_read_all) || user.id == record.user.id scope.all elsif user.has_role?(:document_reader) scope.with_role(:viewer, user) else [Document.new] end end end end <file_sep>/test/decorators/messages/sentbox_decorator_test.rb require 'test_helper' class Messages::SentboxDecoratorTest < Draper::TestCase end <file_sep>/app/views/encrypted_memos/index.json.jbuilder json.array! @encrypted_memos, partial: "encrypted_memos/encrypted_memo", as: :encrypted_memo <file_sep>/app/helpers/messages/inbox_helper.rb module Messages::InboxHelper end <file_sep>/app/helpers/messages/sentbox_helper.rb module Messages::SentboxHelper end <file_sep>/test/system/encrypted_memos_test.rb require "application_system_test_case" class EncryptedMemosTest < ApplicationSystemTestCase setup do @encrypted_memo = encrypted_memos(:one) end test "visiting the index" do visit encrypted_memos_url assert_selector "h1", text: "Encrypted Memos" end test "creating a Encrypted memo" do visit encrypted_memos_url click_on "New Encrypted Memo" fill_in "Body", with: @encrypted_memo.body fill_in "Title", with: @encrypted_memo.title fill_in "Uid", with: @encrypted_memo.uid click_on "Create Encrypted memo" assert_text "Encrypted memo was successfully created" click_on "Back" end test "updating a Encrypted memo" do visit encrypted_memos_url click_on "Edit", match: :first fill_in "Body", with: @encrypted_memo.body fill_in "Title", with: @encrypted_memo.title fill_in "Uid", with: @encrypted_memo.uid click_on "Update Encrypted memo" assert_text "Encrypted memo was successfully updated" click_on "Back" end test "destroying a Encrypted memo" do visit encrypted_memos_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Encrypted memo was successfully destroyed" end end <file_sep>/test/decorators/users/profile_decorator_test.rb require 'test_helper' class Users::ProfileDecoratorTest < Draper::TestCase end <file_sep>/config/routes.rb # frozen_string_literal: true require 'sidekiq/web' Rails.application.routes.draw do use_doorkeeper_openid_connect use_doorkeeper resources :encrypted_memos namespace :admin do resources :documents resources :users resources :announcements resources :notifications resources :services root to: 'users#index' end namespace :api do namespace :v1 do resources :users do get 'me', on: :collection end end end get '/privacy', to: 'home#privacy' get '/terms', to: 'home#terms' authenticate :user, ->(u) { u.has_role?(:admin_portal) } do mount Sidekiq::Web => '/sidekiq' end resources :documents namespace :users do resources :verification_codes, only: [:index] resources :login_activities get 'directory', to: 'directory#index' resources :profiles, only: [:show] do resources :roles, only: [:create, :destroy] end end namespace :messages do get 'inbox', to: 'inbox#index' get 'sent', to: 'sentbox#index' resources :conversations do post 'reply', on: :member end end resources :notifications, only: [:index] resources :announcements, only: [:index] devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks', invitations: 'users/invitations', registrations: 'users/registrations' } get '/go/:id' => "shortener/shortened_urls#show" root to: 'home#index' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end <file_sep>/app/models/document.rb class Document < ApplicationRecord resourcify belongs_to :attachable, polymorphic: true, optional: true has_secure_token has_one_attached :download before_create :set_default_attachable after_create :set_viewers attribute :viewers, :string, array: true private def set_default_attachable self.attachable_id ||= 0 self.attachable_type ||= 'User' end def set_viewers if viewers.size > 0 viewers.each do |viewer| next if viewer.empty? user = User.find(viewer) user.add_role(:viewer, self) end end end end <file_sep>/app/controllers/api/v1/users_controller.rb # frozen_string_literal: true class Api::V1::UsersController < Api::V1::BaseController respond_to :json def me respond_with current_resource_owner end end <file_sep>/test/decorators/users/login_activity_decorator_test.rb require 'test_helper' class Users::LoginActivityDecoratorTest < Draper::TestCase end <file_sep>/app/controllers/users/directory_controller.rb class Users::DirectoryController < ApplicationController before_action :authenticate_user! def index @directory = User.all.order(last_name: :asc, first_name: :asc) authorize @directory, policy_class: UserPolicy end end <file_sep>/app/controllers/documents_controller.rb class DocumentsController < ApplicationController before_action :authenticate_user! before_action :set_document, only: [:show] def index @documents = DocumentDecorator.decorate_collection(policy_scope(Document)) #authorize @documents end def show end def new @document = Document.new authorize @document end def create @document = Document.new(document_params) authorize @document @document.attachable = current_user if @document.save redirect_to @document, notice: 'Document created successfully.' else render :new end end private def set_document @document = DocumentDecorator.decorate(policy_scope(Document).find(params[:id])) #authorize @document end def document_params params.require(:document).permit(:title, :description, :download, viewers: []) end end <file_sep>/app/controllers/users/login_activities_controller.rb class Users::LoginActivitiesController < ApplicationController before_action :authenticate_user! def index @login_activities = current_user.login_activities end end <file_sep>/app/helpers/users/directory_helper.rb module Users::DirectoryHelper end
7dfc412cd9ab3162ab09be22cd36769f97b7c846
[ "Ruby" ]
41
Ruby
pincanna/investors-portal
ab58f73064f8f6c5e64233660006f6b06efb2b77
b0c7e8d44034bdc57bde0e28a1209c804c90e05c
refs/heads/master
<repo_name>jingyaqian2338893965/VI-Management-System<file_sep>/index.js $(function(){ $(".liebiao li").click(function(){ var text=$(this).children().children()[1].innerHTML; if (text=="首页") { $(".right-2").load('pages/shouye.html') }else if(text=="栏目管理"){ $(".right-2").load('pages/lanmu.html') }else if(text=="资讯管理"){ $(".right-2").load('pages/zixun.html') }else if(text=="用户管理"){ $(".right-2").load('pages/yonghu.html') } }); //默认点击首页 $(".liebiao li:first").trigger('click'); })
a33483da25a6ff1e8d6d45ad8d5b783968ff1f4e
[ "JavaScript" ]
1
JavaScript
jingyaqian2338893965/VI-Management-System
577ddcfaa96985e993e04b73801ff21ceb8020a5
b0741c0e364b7391f9ac9a417488b5f31b0587fd
refs/heads/master
<repo_name>tpdi/posa2014w5a4test<file_sep>/README.md I've put a lot of comments in the source to explain what the tests do and how they do it. Please give it a read. Some tests will fail until you modify your AndroidPlatformStrategy code. Code is copyright (c) 2014, <NAME>. You are granted a non-exclusive, non-transferable license to use the code, as an enrolled student in Coursera 2014 POSA MOOC course. To set up the test, you'll need to \1. get the PowerMock, Mockito, and JUnit jars, and put them into the libs/ directory of the project. A zip file containing all those jars can be can be found at: https://code.google.com/p/powermock/wiki/Downloads?tm=2 You need the zip powermock-mockito-junit-1.5.5.zip Don't add the zip as an external jar. Unzip the zip into the lib directory. \2. Link to a copy of the android.jar in your Android by editing the .classpath file in the same directory as this read.me. Please note that the android.jar must come AFTER the junit classpath entry. If your Android sdk setup is the same as mine, you won't need to edit this. Unfortunately, I can't find a good, portable way to reference android.jar; adding the android Classpath Container doesn't work, because javanature projects apparently don't read the android project.properties file to find the android version. \3. Reference your W5-A4-Android project in the .classpath file. This is already done in the .classpath file, and should work as-is if you import this project into the same workspace that contains the W5-A4-Android project. \4. Either edit your AndroidPlatformStrategy to conform to checkNullWeakReference, or comment out NullWeakReferenceIsLoggedButNotCalled, and GarbageCollectedWeakReferenceIsLogged in AndroidPlatformStrategyTest. In fact, AndroidPlatformStrategy should probably throw rather than log. \5. When you first run the test from within Eclipse, you may have to specify the Eclipse JUnit test runner, and the Junit4 test runner.<file_sep>/test/org/diffenbach/posa2014/w5_a4/test/AndroidPlatformStrategyTest.java package org.diffenbach.posa2014.w5_a4.test; import static org.junit.Assert.assertEquals; import java.util.concurrent.Semaphore; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import android.app.Activity; import android.util.Log; import android.widget.TextView; import edu.vuum.mocca.AndroidPlatformStrategy; /** * Unit test of AndroidPlatformStrategy, * using Junit4, Mockito, and PowerMock * * Runs on the standard Java, not on an Android device or emulator, * so it's a bit faster, and really is a unit test. * * It needs to use the PowerMock runner, and we need to tell it * about the Android classes PowerMockito will mock. * * Because we make the test runner explicit, we don't have to derive * our test class from any particular parent class. * * For both of these we have annotations: * */ @RunWith(org.powermock.modules.junit4.PowerMockRunner.class) @PrepareForTest({Activity.class, Log.class, TextView.class}) public class AndroidPlatformStrategyTest { /* * JUnit4, so setup is no longer a magic name. * Instead, we use the Before annotation */ @Before public void setup() { /* * As we are not testing on a device or an emulator, we just have the * version of the android.jar, which throws an exception ("Stub!") * for EVERY method call. * * So we need to mock ANY Android class we construct or call. * * And to create those mocks, we need to use PowerMockito.mock, not Mockito.mock. * * For the static methods, we need to use mockStatic. */ //mockStatic(Activity.class); PowerMockito.mockStatic(Log.class); } /* * While not a requirement of the assignment, we'll test that * a null Activity or TextView results in a log message in * the ctor, and when WeakReference.get() is called. * * This test depends on your having defined public static final error * messages in AndroidPlatformStrategy. * * It will test that you don't try to dereference a null Activity. * To also test that nulls are logged (not a requirement of the * assignment), uncomment the lines that define the log messages. */ @Test // check one Activity that is always null public void NullWeakReferenceIsLoggedButNotCalled() { checkNullWeakReference(new AndroidPlatformStrategy(null, null), new String[]{ // uncomment these lines to actually test something // note, uncommenting will cause compilation errors // unless you've changed AndroidPlatformStrategy // to have the referenced public static strings //AndroidPlatformStrategy.OUTPUT_IS_NULL, //AndroidPlatformStrategy.ACTIVITYPARAM_IS_NULL, //AndroidPlatformStrategy.ACTIVITY_IS_NULL }); } /* * It turns out I can't get a test of an actual garbage collected * reference to work: we get a "Stub!" exception from Context if we don't mock * and (?) PowerMock seems to hold on to the reference if we do mock. * * Note that with the @Test annotation commented out, the test won't be run. * This is a JUnit4 annotation, which means tests don't have to be named "test..." * as in JUnit3. */ //@Test // check another Activity that isn't initially null // This is not possible, public void GarbageCollectedWeakReferenceIsLogged() { checkNullWeakReference(new AndroidPlatformStrategy(null, PowerMockito.mock(Activity.class)), new String[]{ //AndroidPlatformStrategy.OUTPUT_IS_NULL, //AndroidPlatformStrategy.ACTIVITY_IS_NULL }); } private void checkNullWeakReference( final AndroidPlatformStrategy uut, String[] expectedLogs) { //System.gc(); String className = AndroidPlatformStrategy.class.getSimpleName(); uut.done(); System.out.println(className); for(String e: expectedLogs) { // we need to call this before EVERY verification of a static method PowerMockito.verifyStatic(); // Now what looks like a call to Log.e is actually a verification that // the call was made by the class under test (directly or indirectly). // eq and startsWith are Mockito Argument Matchers. // We could statically import Mockito if we wanted to leave off "Mockito." // but to make the code easier to understand, we'll be explicit: Log.e(Mockito.eq(className), Mockito.startsWith(e + " in " + className)); } } /* * In testDoneIsRunOnUIThread we won't actually run the runnable, * which means we won't actually get an NPE if begin isn't called. * Here, we'll run the runnable we get back, and get the NPE. * * In concert with the tests that do call begin, this should verify * that begin is doing what it is supposed to do. * * NOTE: THIS TEST WILL FAIL * if you use the assignment version where mLatch is static * unless you run this test FIRST or by itself. * Thus it comes before the other tests which do call begin. */ // Tell Junit4 that we're a test and we success if we throw an NPE: @Test(expected=NullPointerException.class) public void DoneWillCauseNPEIfBeginNotCalled() { // create a PowerMock mock. Normally we'd just use a Mockito mock, // but all Android methods throw exceptions when using the JAVA SE Android.jar: final Activity mockActivity = PowerMockito.mock(Activity.class); // create the Unit Under Test, or uut: this is the class we are testing: final AndroidPlatformStrategy uut = new AndroidPlatformStrategy(null, mockActivity); // create an ArgumentCaptor, a kind of argument matcher that // keeps a copy of the argument: final ArgumentCaptor<Runnable> runnableArg = ArgumentCaptor.forClass(Runnable.class); // we won't call uut.begin() before calling done(); uut.done(); // Verifying a mock is more clear than verifying a static. // In this case, we're also going to capture the Runnable argument // AndroidPlatformStrategy passes to runOnUIThread, with the // Mockito ArgumentCaptor we created above: // Mockito.verify(mock).methodOnMock(argmentMatcher) Mockito.verify(mockActivity).runOnUiThread(runnableArg.capture()); // And now if we run the runnable, we should throw. // Note that we don't need or want to run it in a separate thread. // There is no actual UI thread here, there doesn't need to be: // this is a UNIT test, not an integration test. // runnableArg is the Argument captor // getValue() returns the last thing captured // which is a runnable we can call run() on. runnableArg.getValue().run(); } /* * Test that AndroidPlatformStrategy.print actually calls runOnUiThread, * with a Runnable, and that that runnable appends to the output object. * * It would be "better" practice to make this two tests, but that would * duplicate most of the test fixtures, so I won't. */ @Test public void PrintIsRunOnUIThreadAndAppendsToTextView() { // arrange final Activity mockActivity = PowerMockito.mock(Activity.class); final TextView textView = PowerMockito.mock(TextView.class); final AndroidPlatformStrategy uut = new AndroidPlatformStrategy(textView, mockActivity); final String stringToPrint = "stringToPrint"; final ArgumentCaptor<Runnable> runnableArg = ArgumentCaptor.forClass(Runnable.class); // act uut.print(stringToPrint); // assert Mockito.verify(mockActivity).runOnUiThread(runnableArg.capture()); runnableArg.getValue().run(); Mockito.verify(textView).append(stringToPrint + "\n"); } /* * Test that AndroidPlatformStrategy.done is call runOnUIThread. */ @Test public void DoneIsRunOnUIThread() { final Activity mockActivity = PowerMockito.mock(Activity.class); final AndroidPlatformStrategy uut = new AndroidPlatformStrategy(null, mockActivity); uut.begin(); //class is a little fragile uut.done(); Mockito.verify(mockActivity).runOnUiThread(Mockito.any(Runnable.class)); } /* * Test that AndroidPlatformStrategy.done must be called twice before * AndroidPlatformStrategy.awairDone returns. */ @Test public void DoneMustBeCalledTwiceToUnblock() throws InterruptedException { final Activity mockActivity = PowerMockito.mock(Activity.class); final AndroidPlatformStrategy uut = new AndroidPlatformStrategy(null, mockActivity); final ArgumentCaptor<Runnable> runnableArg = ArgumentCaptor.forClass(Runnable.class); // Unfortunately, PlatformStrategy.NUMBER_OF_THREADS is not public // this makes PlatformStrategy's public interface cleaner, but makes testing harder // final int numberOfTimes = AndroidPlatformStrategy.NUMBER_OF_THREADS final int numberOfTimes = 2; uut.begin(); // reset the AndroidPlatformStrategy for(int i = 0 ; i < numberOfTimes; ++i) { uut.done(); // we're calling done(), but note that the Runnables won't yet be run // because Activity is a mock } // verify and capture the calls to Activity which pass the Runnables Mockito.verify(mockActivity, Mockito.times(numberOfTimes)).runOnUiThread(runnableArg.capture()); // I need something that is final, so it's in the anonymous class's closure // and yet mutable //final Boolean[] blocked = new Boolean[]{true}; final Semaphore semaphore = new Semaphore(0); // create a thread to call awaitDone and, well, await. // when it stops awaiting, it'll release a permit on the Semaphore final Thread thread = new Thread() { @Override public void run() { uut.awaitDone(); semaphore.release(); } }; thread.start(); // now we'll run the Runnables for( Runnable r: runnableArg.getAllValues()) { // until we've run all done() Runnables, the available permits should be zero assertEquals(0, semaphore.availablePermits()); r.run(); } thread.join(); // after we've run all Runnables (and allowed the awaiting thread to finish) // available permits should be 1 assertEquals(1, semaphore.availablePermits()); } }
3ba47cdafd05e2a4f0e4fd1ae7cc8cd581e2e5d0
[ "Markdown", "Java" ]
2
Markdown
tpdi/posa2014w5a4test
42bd7349bc6813c1cef4c101e5125a0780d6a347
1be3ae7ea19d8ff537cac2f879394958367b171a
refs/heads/master
<file_sep>RoboLang This project supposed to become a game that teaches programming one day. PROJECT_HALT err code: 0xe1b586e70f47d60d3463e851d49191e9 msg: non-free dependency 'Unity 3D' found call stack: [call stack dump removed for sedqurity reasons] <file_sep>using UnityEngine; using UnityEngine.EventSystems; using System.Collections; /// <summary> /// A scroll rect with mouse dragging disabled. /// </summary> public class UndraggableScrollRect : UnityEngine.UI.ScrollRect { public override void OnBeginDrag(PointerEventData eventData) { } public override void OnDrag(PointerEventData eventData) { } public override void OnEndDrag(PointerEventData eventData) { } }
fee8afda7876579ee9c0639ca615b468026ba61c
[ "C#", "Text" ]
2
Text
mongoose11235813/RoboLang
ef455c957f5b3372f95340740f3fba0243f16340
516d7150a7ff433f786df16e42b5346ac4f93c5a
refs/heads/master
<repo_name>cdanz/CPSC_5051<file_sep>/CPSC_5051/driver.cs // AUTHOR: <NAME> // FILENAME: driver.cs // DATE: 4/29/2018 // REVISION HISTORY: 1.0 // REFERENCES (optional): EncryptWord.h EncryptWord.cpp // www.tutorialspoint.com/csharp/csharp_quick_guide.htm using System; using ProgrammingAssignments5051; namespace CPSC_5051 { /* Description: -- takes inputs from main and corrdinates appropriate use * of objects. */ class Driver { /* Description: -- takes in user defined string to use for encryption. */ public string word(string x) { EncryptWord e = new EncryptWord(); e.Initiate(); return e.encrypt(x); } /* Description: -- takes in user defined int guess of the shift * applied by the cipher. */ public bool guess(int y) { bool guessTruth = false; EncryptWord e = new EncryptWord(); e.Initiate(); guessTruth = e.makeGuess(y); return guessTruth; } } }<file_sep>/README.md # CPSC_5051 Classroom assignments <file_sep>/CPSC_5051/main.cs // AUTHOR: <NAME> // FILENAME: main.cs // DATE: 4/29/2018 // REVISION HISTORY: 1.0 // REFERENCES (optional): EncryptWord.h EncryptWord.cpp // www.tutorialspoint.com/csharp/csharp_quick_guide.htm using System; using ProgrammingAssignments5051; namespace CPSC_5051 { /* Description: -- does the basic main function and offloads most of the * coordination between objects to the driver. */ class Program { static void Main(string[] args) { string userWord; int userGuess; Console.WriteLine("Please provide a word to encrypt: "); userWord = Console.ReadLine(); Console.WriteLine("Your word is: "+userWord); Driver driver = new Driver(); Console.WriteLine("Encrpted it is: " + driver.word(userWord)); do { Console.WriteLine("Guess the shift applied to Encrypt: "); userGuess = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Your guess is: " + driver.guess(userGuess)); } while (!driver.guess(userGuess)); Console.ReadKey(); } } } <file_sep>/CPSC_5051/EncryptWord.cs // AUTHOR: <NAME> // FILENAME: EncryptWord.cs // DATE: 4/15/2018 // REVISION HISTORY: 1.0 // REFERENCES (optional): EncryptWord.h EncryptWord.cpp // www.tutorialspoint.com/csharp/csharp_quick_guide.htm using System; namespace ProgrammingAssignments5051 { /* Description: -- this class creates an object that can perform a caesar shift cipher on text and allows the client to guess the shift. The function that performs the caesar cipher returns encrypted text. There is a function that takes in a guess, updates stats based on the guess and returns a boolean value indicating if the client is correct or not. Assumptions: An EncryptedWord object is considered "on" if its encrypt function is in use, otherwise it is off. Resetting an EncryptedWord object re-initializes the stats back to zero. */ class EncryptWord { // member variables const int MIN_CHARS = 4; //arbitrary minimum number of characters allowed int SHIFT = 3; //the number used to shift by in the caesar shift. int LETTERS = 26; //Number of letters in the alphabet int UP_LOW = 65; //Lowerbound of ASCII Uppercase letter characters int UP_HIGH = 90; //Upperbound of ASCII Uppercase letter characters int LOW_LOW = 97; //Lowerbound of ASCII Lowercase letter characters int LOW_HIGH = 122; //Upperbound of ASCII Lowercase letter characters int guesses; //accumulator of guesses made. int highGuess; //tracks highest guess made. int lowGuess; //tracks lowest guess made. double averageGuess; //tracks calculated average of guesses bool on; //whether the encryption has been used yet or not. // Acts as a pseudo contructor, setting each objects member variables // to their proper starting state. // preconditions: None // postconditions: All tracking variables are set at zero. On is true. public void Initiate() { guesses = 0; highGuess = 0; lowGuess = 0; averageGuess = 0; on = false; } // Give the object a word to encrypt, the method returns it in its // encrypted form. Provided string must have the minimum number of // charaters set in the MIN_CHARS constant. // preconditions: Must be off. // postconditions: All tracking variables are set at zero. On is true. public string encrypt(String x) { if (x.Length < MIN_CHARS) return "ERROR"; on = true; string xEnd = ""; //go through text character by character for (int i = 0; i < x.Length; i++) { //check to see if character is uppercase and return a shift that is //also uppercase if it is. if (x[i] >= UP_LOW && x[i] <= UP_HIGH) xEnd += (char)(((int)(x[i])+SHIFT-UP_LOW)%LETTERS +UP_LOW); //if not upper, check if lower and shift to another lowercase value. else if (x[i] >= LOW_LOW && x[i] <= LOW_HIGH) xEnd += (char)(((int)(x[i])+SHIFT-LOW_LOW)%LETTERS +LOW_LOW); //to stop any phrases, detection of a space will throw an error. else return "ERROR"; } return xEnd; } // Decrypt a word as a means of getting more information on what the // encryption method may be. Provided string must have the minimum // number of charaters set in the MIN_CHARS constant. // preconditions: Must be on. // postconditions: Still on. public string decrypt(string x) { if (!on) return "ERROR"; if (x.Length < MIN_CHARS) return "ERROR"; string xEnd = ""; //go through text character by character for (int i = 0; i < x.Length; i++) { //check to see if character is uppercase and return a shift that is //also uppercase if it is. if (x[i] >= UP_LOW && x[i] <= UP_HIGH) xEnd += (char)(((int)(x[i]) + (LETTERS - SHIFT) - UP_LOW) % LETTERS + UP_LOW); //if not upper, check if lower and shift to another lowercase value. else if (x[i] >= LOW_LOW && x[i] <= LOW_HIGH) xEnd += (char)(((int)(x[i]) + (LETTERS - SHIFT) - LOW_LOW) % LETTERS + LOW_LOW); //Any non-letters will throw an error. else return "ERROR"; } return xEnd; } //Process a guess at what the shift is. takes in a number "guess", adjusts //the statics of the guesses accordingly by incrementing the number of //guesses, adjusting the high guess if it is a new high, adjusting low if //new low and recalculating the average guess. Finally a boolean is returned //true if and only if the guess is equal to the shift. // preconditions: Must be on. // postconditions: Still on. public bool makeGuess(int g) { //check to see if encryption has been used yet. if (!on) return false; //first guess is both the high and low guess if (guesses == 0) { highGuess = g; lowGuess = g; } //check for new high if (g > highGuess) highGuess = g; //check for new low if (g < lowGuess) lowGuess = g; //increment guesses++; //recalculate average averageGuess = ((averageGuess * (guesses - 1)) + g) / guesses; return g == SHIFT; } // Getter for high guess. // preconditions: Must be on. // postconditions: Still on. public int getHighGuess() { //check to see if encryption has been used yet. if (!on) return -1; return highGuess; } // Getter for low guess. // preconditions: Must be on. // postconditions: Still on. public int getLowGuess() { //check to see if encryption has been used yet. if (!on) return -1; return lowGuess; } // Getter for average of guesses. // preconditions: Must be on. // postconditions: Still on. public double getAverageGuess() { //check to see if encryption has been used yet. if (!on) return -1; return averageGuess; } // Getter for number of guesses. // preconditions: Must be on. // postconditions: Still on. int getGuesses() { //check to see if encryption has been used yet. if (!on) return -1; return guesses; } // Find out if the object is on. // preconditions: Either on or off. // postconditions: No change. public bool getOn(){ return on; } // Find the minimum allowed number of characters in a gstrin meant // for encryption. // preconditions: On or off. // postconditions: No change. public int getMin() { return MIN_CHARS; } // Reset the object for another word. // preconditions: On or off. // postconditions: No change. public void reset() { //check to see if encryption has been used yet. if (!on) return; //reset all guess stats back to zero. guesses = 0; highGuess = 0; lowGuess = 0; averageGuess = 0; on = false; } } }
d870898cba1e7300ba0963d7396d27df8cc00e63
[ "Markdown", "C#" ]
4
C#
cdanz/CPSC_5051
cb25f806bf4c70e58f56955e6e79290931914173
5f4a9c8736ca9de6ccb9953a452ce6a630fc8a22
refs/heads/master
<file_sep>import numpy as np import cv2 def order_points(pts): rect = np.zeros((4, 2), dtype = 'float32') s = pts.sum(axis = 1) rect[0] = pts[np.argmin(s)] rect[2] = pts[np.argmax(s)] diff = np.diff(pts, axis = 1) rect[1] = pts[np.argmin(diff)] rect[3] = pts[np.argmax(diff)] return rect def four_point_transform(imag, pts): rect = order_points(pts) (tl, tr, br, bl) = rect widthA = np.sqrt(((br - bl) ** 2).sum()) widthB = np.sqrt(((tr - tl) ** 2).sum()) heightA = np.sqrt(((bl - tl) ** 2).sum()) heightB = np.sqrt(((br - tr) ** 2).sum()) maxWidth = max(int(widthA), int(widthB)) maxHeight = max(int(heightA), int(heightB)) dst = np.array([ [0, 0], [maxWidth - 1, 0], [maxWidth - 1, maxHeight - 1], [0, maxHeight - 1]], dtype = 'float32') M = cv2.getPerspectiveTransform(rect, dst) warped = cv2.warpPerspective(imag, M, (maxWidth, maxHeight)) return warped <file_sep>from transform import four_point_transform from
54e453b68b3f9344146071b1ac15fe31722259e1
[ "Python" ]
2
Python
DennisLZL/opencvtest
38405f256499f58419cb0d020db5840c434a456d
50d81b2446a4896e3af012226cc11d2e7d2de264
refs/heads/master
<repo_name>dichque/sample-api<file_sep>/restapi/configure_minimal_pet_store_example.go // This file is safe to edit. Once it exists it will not be overwritten package restapi import ( "crypto/tls" "github.com/dichque/sample-api/models" "github.com/go-openapi/swag" "net/http" errors "github.com/go-openapi/errors" runtime "github.com/go-openapi/runtime" middleware "github.com/go-openapi/runtime/middleware" "github.com/dichque/sample-api/restapi/operations" "github.com/dichque/sample-api/restapi/operations/pet" ) //go:generate swagger generate server --target ../../sample-api --name MinimalPetStoreExample --spec ../swagger.yaml var petList = []*models.Pet{ {ID: 0, Name: swag.String("Bobby"), Kind: "dog"}, {ID: 1, Name: swag.String("Lola"), Kind: "cat"}, {ID: 2, Name: swag.String("Bella"), Kind: "dog"}, {ID: 3, Name: swag.String("Maggie"), Kind: "cat"}, } func configureFlags(api *operations.MinimalPetStoreExampleAPI) { // api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... } } func configureAPI(api *operations.MinimalPetStoreExampleAPI) http.Handler { // configure the api here api.ServeError = errors.ServeError // Set your custom logger if needed. Default one is log.Printf // Expected interface func(string, ...interface{}) // // Example: // api.Logger = log.Printf api.JSONConsumer = runtime.JSONConsumer() api.JSONProducer = runtime.JSONProducer() if api.PetCreateHandler == nil { api.PetCreateHandler = pet.CreateHandlerFunc(func(params pet.CreateParams) middleware.Responder { return middleware.NotImplemented("operation pet.Create has not yet been implemented") }) } if api.PetGetHandler == nil { api.PetGetHandler = pet.GetHandlerFunc(func(params pet.GetParams) middleware.Responder { return middleware.NotImplemented("operation pet.Get has not yet been implemented") }) } api.PetListHandler = pet.ListHandlerFunc(func(params pet.ListParams) middleware.Responder { if params.Kind == nil { return pet.NewListOK().WithPayload(petList) } var pets []*models.Pet for _, pet := range petList { if *params.Kind == pet.Kind { pets = append(pets, pet) } } return pet.NewListOK().WithPayload(pets) }) api.ServerShutdown = func() {} return setupGlobalMiddleware(api.Serve(setupMiddlewares)) } // The TLS configuration before HTTPS server starts. func configureTLS(tlsConfig *tls.Config) { // Make all necessary changes to the TLS configuration here. } // As soon as server is initialized but not run yet, this function will be called. // If you need to modify a config, store server instance to stop it individually later, this is the place. // This function can be called multiple times, depending on the number of serving schemes. // scheme value will be set accordingly: "http", "https" or "unix" func configureServer(s *http.Server, scheme, addr string) { } // The middleware configuration is for the handler executors. These do not apply to the swagger.json document. // The middleware executes after routing but before authentication, binding and validation func setupMiddlewares(handler http.Handler) http.Handler { return handler } // The middleware configuration happens before anything, this middleware also applies to serving the swagger.json document. // So this is a good place to plug in a panic handling middleware, logging and metrics func setupGlobalMiddleware(handler http.Handler) http.Handler { return handler } <file_sep>/README.md Reference: https://posener.github.io/openapi-intro/
05dd49da104bacbc4bfc48b02444b0d23258af37
[ "Markdown", "Go" ]
2
Go
dichque/sample-api
448c919b5f95f174a99de0b8736ac53877452828
874802c337c1010f4324546f611948939f343285
refs/heads/master
<repo_name>G-MercyT/microposts<file_sep>/app/models/micropost.rb class Micropost < ActiveRecord::Base belongs_to :user validates :user_id, presence: true validates :content, presence: true, length: { maximum: 140 } has_many :favorites, dependent: :destroy has_many :favorite_users, class_name: "User", foreign_key: "user_id", through: :favorites, source: :user end
a7e710e8f93144c20b9a6e5cd071b488481c305d
[ "Ruby" ]
1
Ruby
G-MercyT/microposts
e202b595633cec581527fee5a597e65164fa248f
8e15721e656e0b12fbcf4aa94fb8601a4dfc74e8
refs/heads/master
<repo_name>alaminzju/eQTLQC-1<file_sep>/ImputationScripts/Imputation_main_script.sh # Steps for preparation of imputation based on Michigan Imputation Server, and post-imputation QC # Author: <NAME> # Step 1, run data preparation script, HRC-1000G-check-bim.pl # perl /home/tw83/twang/AMP/tools/HRC-1000G-check-bim.pl -b DATA.QC.bim -f DATA.QC.frq -r /home/tw83/twang/AMP/tools/HRC.r1-1.GRCh37.wgs.mac5.sites.tab -h ########################## # VCFQC.sh #!/bin/bash # remove SNPs with imputation R2 < 0.3 # remove SNPs with MAF < 0.05 # remove SNPs with more than 2 alleles [[ ! -d QC ]] && mkdir QC for (( i = 2; i <= 22; i++ )); do zcat chr${i}.info.gz | awk 'NR!= 1 && $7>=0.3 {print $1}' > QC/chr${i}.R2.txt # extract snps with r2 >= 0.3 vcftools --gzvcf chr${i}.dose.vcf.gz --snps QC/chr${i}.R2.txt --maf 0.05 --min-alleles 2 --max-alleles 2 --recode --stdout| gzip -c > QC/chr${i}.dos.postQC.vcf.gz done<file_sep>/README.md # Introduction Advances in the expression quantitative trait loci (eQTL) studies have provided valuable insights into the mechanism of diseases and traits-associated genetic variants. However, it remains computationally challenging to evaluate and control the data quality required in eQTL analysis for researcher with a limited background in programming. There is an urgent need to develop a powerful and user-friendly tool to automatically process the raw dataset and perform the eQTL mapping afterwards. In this work, we present a pipeline for eQTL analysis, termed as eQTLQC, with automated data preprocessing of both genotype data and gene expression data, especially RNA-seq based. Our pipeline provides comprehensive quality control and normalization approaches. Multiple automated techniques are used to concatenate the pipeline to reduce manual interventions. And a configuration file is provided to adjust parameters and control the processing logic. The source code, demo data and instructions are freely available <a href="https://github.com/stormlovetao/eQTLQC" target="_blank">**here**</a>. # Preliminaries This tool is written in R 3.5 and Python 3.7, please double check your computing environment. The "Tool.config" file is in JSON format, and required to configurate parameters and control the processes. Before using this tool, run the following R script to install dependencies: ``` Rscript dependence.R ``` # Configuration The configuration file, named "Tool.config" and in JSON format, is used to setup parameters and control the pipeline. JSON is a human-readable text format to store "attribute-value" pairs. More details introducing JOSN could be found at <a href="https://en.wikipedia.org/wiki/JSON" target="_blank">**wikipedia**</a>. The Tool.config file consists of two main sub-objects: "transcriptome" and "genotyping". The key named **"usage"** is used as switch to turn on or off the processing sections of gene expression data ("transcriptome") and genotype data ("genotyping"). For example, if the usage in "transcriptome" is set to "FALSE" and in "genotyping" is set to "TRUE", then the tool will only run the genotyping processing part, all parameters in transcriptome will be ignored. The details of parameters are introduced as follows. ## Transcriptome data preprocessing If **usage** in transcriptome is TRUE *(or true, T, t)*, one and only one of the following formats is required: **Fastq**, **BAM**, **Readcounts** or **normalized metrics(TPM/FPKM/RPKM)**. Note that if the input is a readcounts file, additional gene length file is also needed. ### FASTQ/BAM inputs If input sources are in FASTQ or BAM format, FASTQ or BAM files should be under same folder path. For example: "fastq":"/home/rawdata/fastq/" or "bam":"/home/rawdata/bam/". For pair-ended reads, filenames of FASTQ should be ended with "_1.fastq" and "_2.fastq". eQTLQC will process the raw inputs into the TPM (Transcripts per million reads) metrics using <a href="https://github.com/deweylab/RSEM" target="_blank">**RSEM**</a>. Parameters of RSEM could be setup in configuration file by following keys: | Keys| Mandatory/optional| Defaults| Remarks | | -------- | -----: | --------| :---- | |rsem_path | Mandatory | NA |string, the directory of RSEM installation| |pnum | optional | 8 |string, number of threads to use| |paired-end | Mandatory | TRUE| boolean, TRUE or FALSE| |reffile | Mandatory | NA | string, the name of the reference used| |mapping_software|Mandatory|bowtie2| string, choose alignment software: "bowtie","bowtie2" or "star"| |mapping_software_path|optional| NA|string, Path of mapping software chosen. If not given, the path to the executables is assumed to be in the user's PATH environment variable| |output_genome_bam|optional|TRUE|boolean, alignments in genomic coordinates instead in transcript| |estimate-rspd|optional|TRUE|boolean, set this option if you want to estimate the read start position distribution (RSPD) from data. Otherwise, RSEM will use a uniform RSPD| |append_names|optional|boolean, append gene_name/transcript_name to the result files| |add_parameters|optional|| ### Readcounts/Normalized metrics inputs If readcounts table is provided for key "readcounts", eQTLQC will scale it into TPM values. A gene length file is also requested from user with key "gene_length_file". See gene length demo file format: Sample/readcount/gencode.v24.annotation.gtf.gene_length_unionexon. If users do not want to transform read counts into TPM, users could directly assign readcounts file path to the key "metrics". If normalized metrics are provided for the key "metrics", such as TPM/RPKM/FPKM or even readcounts, eQTLQC will directly turn into downstream preprocessing procedures. ReadCount/Metrics file format requirements: The input file should has sample ID as column name; the first column is gene ID (If ENGSID is used, the version behind '.' will be ignored), and the following columns are samples; Fields in each row should be separated by tab separator. ### Quality control on gene expression profiles Quality control procedures will be applied on the "metrics" user provided or eQTLQC generated. The following three methods will be used to identify outliers with problematic expression profiles. #### RLE The RLE (Relative Log Expression) analysis is based on the hypothesis that in a sample, the expression of most genes should be at similar level, and only a small portion of genes show very high or low expression levels. Suppose the gene expression matrix *G* with genes on the rows and samples on the columns, RLE analysis first calculate the median expression value across samples for every gene. Then each expression value in the matrix is subtracted by the median expression value of the corresponding gene. For each sample (column), the distribution of residuals of expression values should be centered close to zero, and has small variations. The RLE plot aligns the expression distributions of all samples, in the form of boxplots, side by side in increasing order of the interquartile range (IQR). The samples locate at the right most side are more likely to be outliers. In default, we set the right most 5% samples as candidate outliers. #### Hierarchical clustering Hierarchical clustering is also a widely used approach to exclude sample outliers. Similarity between each pair of samples is first measured by metrics such as Pearson's correlation coefficient or Spearman's correlation coefficient. The sample distance matrix, obtained by one minus similarity scores, is used to perform hierarchical clustering. Usually, samples with problematic expression profiles will be far from other samples with normal expression profiles in the clustering dendrogram. We measure the Mahalanobis distances between each sample and the distribution of all samples. The chi-squared P value is calculated for each sample in each cluster. Clusters with <= *cluster_percent* (60% in default) samples with Bonferroni-corrected P-values <= *pvalues_cut* (0.05 in default) are marked as outlying clusters, and all samples included will be marked as candidate outliers. #### D-statistic The D-statistic of each sample is defined as the median Spearman's correlation coefficients with other samples, which reflects the distance to other samples. The outliers will be likely far from the peak of D-statistics distribution. We consider the left most 5\% samples as candidate outliers. And conducting the analysis of above analysis, eQTLQC considers the intersection of candidate outliers reported by the three methods as final set of sample outliers. ### Normalization and covariates adjustment In eQTLQC, we use SVA to adjust the known and hidden covariates. To be specified, we use the *combat* function in SVA to adjust the batch effects, and use the *fsva* function to adjust other known covariates and latent covariates. Covariates file format requirements: columns should be sperated by tab. The first column should be sample's ID which should be consistant with sample ID in expression data. "sex" and "batch" are two reserved covariate column names, which will be used in gender-mismatch check and adjusting batch effects respectively. Other covariates could be named arbitrarily. Sex, batch and other covariates in string will be treated as factors, and other covariates in numbers will be treated as numeric. | Keys| Mandatory/optional| Defaults| Remarks | | ----| ----- | ----- | --- | |RLEFilterPercent|Mandatory| 0.05 |numeric, RLE distribution, right-most percentage| |DSFilterPercent |Mandatory| 0.05 |numeric, D-statistic distribution, left-most percentage| |pvalues_cut |Mandatory| 0.05 |numeric, cutoff p-value| |cluster_level |Mandatory| 5 |numeric, The maximum level of hcluster when detecting outlying clusters| |covariates |Mandatory|FALSE |boolean, covariates available or not | |covariates_file |Optional |NA |string, covariates file path, necessary when covariates is TRUE| ## Genotype data preprocessing If the key "usage" is set to "TRUE", the genotype preprocessing part will be activited. eQTLQC accepts genotype data in PLINK and VCF formats, and VCF files will be converted to PLINK formats for further processing. eQTLQC adopts PLINK for genotype QC, and <a href="https://www.cog-genomics.org/plink/" target="_blank">**Plink1.9+**</a> is required. To specify population stratification, eQTLQC adopts SmartPCA in <a href="https://www.hsph.harvard.edu/alkes-price/software/" target="_blank">**EIGENSOFT**</a>, which is also required. | Keys| Mandatory/optional| Remarks | | -------- | -----: | :----: | |PLINK |Optional|Raw data in PLINK format, mandatory if VCF is null| |VCF |Optional|Raw data in VCF format, mandatory if PLINK is null| |work_dir |Optional|Set the work directory| |genotyping_rate|Mandatory|the cutoff of genotyping rate| |call_rate |Mandatory|the cutoff of call rate| |HWE |Mandatory|HWE Test's cutoff p-value| |MAF |Mandatory|Minor Allele Frequency| |F_outlier_n_sd |Mandatory|determind F outlier with fmean $\pm$F_outlier_n_sd\*fsd| |population |Optional|Remove population outlier| #### PCA | parameter for smartpca| remark | | ------ | :----: | |m|default(5)maximum number of outlier removal iterations.To turn off outlier removal, set -m 0.| |k|default(10)number of principal components to output| |t|default(10)number of principal components along which to remove outliers during each outlier removal iteration| #### Imputation If the usage of Imputation is TRUE, the tool will use <a href="https://www.well.ox.ac.uk/~wrayner/tools/" target="_blank">**McCarthy's tool**</a> to do prepreparing checking. The tool can use three kinds of reference panel: HRC, 1000G and CAAPA, use the parameter in config file to select and determind the reference panel. ## Run Demo data To show how eQTLQC works, we use the E-GEUV-1's data as a demo and run the QC pipeline on it. In /Sample/fastq/ there is an *run_demo.sh*, which can automatically download three sample's RNA-seq data in fastq format in to /fastq/ and download reference to /ref/, than create reference files and use RSEM to calculate the expression data for each sample. The tool will create a */TranscriptomeWorkplace" directory and place the result including mapped bam file, which can also be used to create a TPM matrix, and each sample's expression data. After calculate expression for each sample, the results will be distilled and generate a TPM_matrix.csv file under /Sample/fastq/ and read for downstream analysis. However, three samples are too less to run the downstream pipeline. To show the whole function of the tool, we use summary of alignment (read count) as another demo which is placed in /Sample/readcount/, by running *run_demo.sh*, a read count file will be download and calculate expression levels in tpm with a gene length file. it will also create a TPM_matrix.csv file and can be used for downstream analysis. The result will be stored in *expression.postQC.xls* and generate a *Report.html* to show the details of preprocessing under the working directory. As for genotype data, we also create a demo in /Sample/VCF/, by running *run_demo.sh* it will download a <a href="https://www.ebi.ac.uk/arrayexpress/files/E-GEUV-1/GEUVADIS.chr1.PH1PH2_465.IMPFRQFILT_BIALLELIC_PH.annotv2.genotypes.vcf.gz" target="_blank">genotype data</a> in VCF format and preprocess it with QC tool. It will generate PLINK format data for each step of preprocessing and create a table in markdown named *GeneReport.md* containing details of each step. Here is an example: |step|SNPs removed|SNP pass|sample removed|sample pass| | -------- | :-----: | :----: | :-----:| :---: | |genotyping rate|84133|409726|0|465| |call rate|0|409726|0|465| |sex check|0|409726|0|465| |HWE test|5000|404726|0|465| |Mishap|0|404726|0|465| |MAF|239983|164743|0|465| |F-outlier and IBD|0|164743|140|325| |PCA outliers|0|164743|0|325| # eQTLQC <file_sep>/Sample/readcount/run_demo.sh wget https://www.ebi.ac.uk/arrayexpress/files/E-GEUV-1/GD660.GeneQuantCount.txt.gz gunzip GD660.GeneQuantCount.txt.gz # Format the readcount file: # Tab seperator, has header name, the first column is gene ID, and following columns are samples echo 'data = read.table("GD660.GeneQuantCount.txt", header=T, sep = "\t", stringsAsFactors=F, check.names=F)' > format_input.R echo 'names(data)[1] = "feature"' >> format_input.R echo 'data = data[,-c(2:4)] # remove not to use columns' >> format_input.R echo 'write.table(data, file="GD660.GeneQuantCount.txt", row.names=F, col.names=T, sep = "\t", quote=F)' >> format_input.R Rscript format_input.R rm format_input.R #python3 Tool.py <file_sep>/readcounts2TPM.R ########################################################### ### This R script transform read count file to TPM metrics ### Input: read count file (first column is gene ID, following columns ### are samples' IDs; separated by tab), gene length file (two columns, separated by tab) ### Output: TPM metrics file ########################################################### #load config file library(rjson) json_data<-fromJSON(file="Tool.config") gene_length_file = json_data$config$transcriptome$gene_length_file Read_count_file = json_data$config$transcriptome$readcounts library(tidyverse) library(dplyr) #custom setting parameter counts_to_tpm <- function(counts, featureLength) { # Ensure valid arguments. stopifnot(length(featureLength) == nrow(counts)) # Compute effective lengths of features in each library. effLen <- featureLength # Process one column at a time. tpm <- do.call(cbind, lapply(1:ncol(counts), function(i) { rate = log(counts[,i]) - log(effLen) denom = log(sum(exp(rate))) exp(rate - denom + log(1e6)) })) # Copy the row and column names from the original matrix. colnames(tpm) <- colnames(counts) rownames(tpm) <- rownames(counts) return(tpm) } ############### Transform from counts to TPMs ############## gene_length =read.table(gene_length_file, header=F, sep = "\t", stringsAsFactors=F) names(gene_length)[1:2] = c("ENSGID", "length") # remove gene version gene_length$ENSGID= do.call(rbind, strsplit(gene_length$ENSGID, '.', fixed=T))[,1] #Read_count_file load Read_count = read.table(Read_count_file, header=T, sep = "\t", stringsAsFactors=F, check.names=F) names(Read_count)[1] = "feature" # remove gene version Read_count$feature = do.call(rbind, strsplit(Read_count$feature, '.', fixed=T))[,1] comm = intersect(gene_length$ENSGID, Read_count$feature) rownames(Read_count) = Read_count$feature; Read_count = Read_count[,-1] rownames(gene_length) = gene_length$ENSGID; Read_count = Read_count[comm,] gene_length = gene_length[comm,] tpm = counts_to_tpm(Read_count, gene_length$length) write.csv(tpm,"TPM_matrix.csv",header = T)
1007580f6ae4769c3a114452601c68cff8fd7320
[ "Markdown", "R", "Shell" ]
4
Shell
alaminzju/eQTLQC-1
86dcc388c8da7f1bd5b223f4b9b26f09c907eb15
35a17601fc2a15428ee3195e8079b67c1f2e4ebf
refs/heads/master
<file_sep>def count_substring(string, sub_string): count = 0 string_part = string while string_part != '': position = string_part.find(sub_string) if position != -1: count += 1 string_part = string_part[position+1:] else: string_part = '' return count if __name__ == '__main__': string = input().strip() sub_string = input().strip() count = count_substring(string, sub_string) print(count)<file_sep>def print_rangoli(size): max_length = 1 + 4 * (size - 1) print(max_length) for i in range(1, size + 1): value = '' for j in range(0, i): value += chr(97 + size - 1 - j) + '-' firstRun = True for j in range(i, 1, -1): if firstRun: value += chr(97 + size + 1 - j) firstRun = False else: value += '-' + chr(97 + size + 1 - j) print(value.center(max_length, '-')) for i in range(size, 1, -1): value = '' for j in range(1, i): value += chr(97 + size - j) + '-' firstRun = True for j in range(i - 2, 0, -1): if firstRun: value += chr(97 + size - j) firstRun = False else: value += '-' + chr(97 + size - j) print(value.center(max_length, '-')) if __name__ == '__main__': n = int(input()) print_rangoli(n)<file_sep># python-test practice for python programs. This is time pass repository to practice python programs. These programs are taken from hacker rank website. SETUP 1. Install python, pip and pipenv tools. 2. Run command pipenv install 3. Start the virtualenv shell using pipenv shell<file_sep>if __name__ == '__main__': n = int(input()) arr = map(int, input().split()) top = -101 runnerUp = -101 for i in arr: if i > top: runnerUp = top top = i print('top: ', top) print('runner up : ', runnerUp) elif i > runnerUp and i < top: runnerUp = i print('runner up : ', runnerUp) print(runnerUp) <file_sep>(n, m) = (int(i) for i in input().split()) pattern = '.|.' welcome = 'WELCOME' for i in range(1, ((n-1)//2) + 1): patternLength = len(pattern) * (i*2 - 1) dashLength = (m - patternLength) // 2 print('-'*dashLength, end='') print(pattern* (i*2 - 1), end='') print('-'*dashLength) print('-' * ((m - len(welcome)) // 2), end='') print(welcome, end='') print('-' * ((m - len(welcome)) // 2)) for i in range(((n-1)//2), 0, -1): patternLength = len(pattern) * (i*2 - 1) dashLength = (m - patternLength) // 2 print('-'*dashLength, end='') print(pattern* (i*2 - 1), end='') print('-'*dashLength)<file_sep>if __name__ == '__main__': N = int(input()) output_list = [] for i in range(N): command, *args = input().split() args = list(map(int, args)) if (command == 'print'): print(output_list) else: method = getattr(output_list, command, lambda: 'invalid command') method(*args) <file_sep>if __name__ == '__main__': students = [] for _ in range(int(input())): name = input() score = float(input()) students.append([name, score]) bottom = 101 secondLowest = 101 for s in students: if s[1] < bottom: secondLowest = bottom bottom = s[1] elif s[1] < secondLowest and s[1] > bottom: secondLowest = s[1] ans = sorted([s[0] for s in students if s[1] == secondLowest]) for name in ans: print(name)
74fd1f876bd2fbde71036e1a1ac835df3cf7235a
[ "Markdown", "Python" ]
7
Python
chetankhilosiya/python-test
b32fffdf8b31d26a4b3dea380079d3f7bfd846ed
80c2f59c4ec64309c1cd8f2cc42ee4decb34db73
refs/heads/gh-pages
<repo_name>mcanthony/Ammo.lab<file_sep>/demos/demo03.js CLEAR({broadphase:"BVT", timer:false, timestep:1/60, iteration:2, G:-10}); function initDemo() { NAME("Ball pool"); // ground ADD({ type:"ground", size:[20,3,20], pos:[0,-1.5,0] }); // wall ADD({ type:"boxbasic", size:[20,10,1], pos:[0,5,-9.5] }); ADD({ type:"boxbasic", size:[20,10,1], pos:[ 0,5,9.5] }); ADD({ type:"boxbasic", size:[1,10,18], pos:[-9.5,5,0] }); ADD({ type:"boxbasic", size:[1,10,18], pos:[ 9.5,5,0] }); var max = 333; var px, pz, py, s; for (var i=0; i!==max; ++i ){ s = 0.1+Math.random(); px = -5+Math.random()*10; pz = -5+Math.random()*10; py = 1+i+(i*0.2); ADD({ type:"sphere", size:[s], pos:[px,py,pz], phy:[0.5, 0.1], mass:s }); } }<file_sep>/demos/demo02.js CLEAR({broadphase:"BVT", timer:false, timestep:1/60, iteration:2, G:-10}); function initDemo() { NAME("<NAME>"); // ground ADD({ type:"ground", size:[20,3,20], pos:[0,-1.5,0] }); // wall ADD({ type:"boxbasic", size:[20,10,1], pos:[0,5,-9.5] }); ADD({ type:"boxbasic", size:[20,10,1], pos:[0,5,9.5] }); ADD({ type:"boxbasic", size:[1,10,18], pos:[-9.5,5,0] }); ADD({ type:"boxbasic", size:[1,10,18], pos:[ 9.5,5,0] }); var max = 333; var px, pz, py, s; // phy = [friction, restitution]; for (var i=0; i!==max; ++i ){ s = 0.1+Math.random(); px = -1+Math.random()*2; pz = -1+Math.random()*2; py = 1+i; ADD({ type:"dice", size:[s,s,s], pos:[px,py,pz], phy:[0.5, 0], mass:s }); } }<file_sep>/js/AMMO.Three.js /** _ _ _ * | |___| |_| |__ * | / _ \ _| | * |_\___/\__|_||_| * @author LoTh /http://3dflashlo.wordpress.com/ */ // AMMO for three.js // By default, Bullet assumes units to be in meters and time in seconds. // The simulation steps in fraction of seconds (1/60 sec or 60 hertz), // and gravity in meters per square second (9.8 m/s^2). // Bullet was designed for (0.05 to 10). 'use strict'; var AMMO={ REVISION: 0.2 }; AMMO.TORAD = Math.PI / 180; AMMO.STATIC_OBJECT = 1; AMMO.KINEMATIC_OBJECT = 2; AMMO.STATIC = 0; AMMO.DYNAMIC = 1; AMMO.ACTIVE = 1; AMMO.ISLAND_SLEEPING = 2; AMMO.WANTS_DEACTIVATION = 3; AMMO.DISABLE_DEACTIVATION = 4; AMMO.DISABLE_SIMULATION = 5; AMMO.BT_LARGE_FLOAT = 1000000.0; AMMO.WORLD_SCALE = 100; AMMO.INV_SCALE = 0.01; AMMO.MAX_BODY = 1024; AMMO.MAX_JOINT = 200; AMMO.MAX_CAR = 20; AMMO.MAX_CAR_WHEEL = 4; AMMO.V3 = function(x, y, z){ return new Ammo.btVector3(x || 0, y || 0, z || 0); } AMMO.V3A = function(A){ return new Ammo.btVector3(A[0], A[1], A[2]); } AMMO.copyV3 = function (a,b) { b.setX(a[0]); b.setY(a[1]); b.setZ(a[2]); } //-------------------------------------------------- // RIGIDBODY //-------------------------------------------------- AMMO.World = function(obj){ this.mtx = new Float32Array(AMMO.MAX_BODY*8); this.jmtx = new Float32Array(AMMO.MAX_JOINT*8); this.mtxCar = new Float32Array(AMMO.MAX_CAR*(8+(8*AMMO.MAX_CAR_WHEEL))); this.Broadphase = obj.broadphase || "BVT"; this.gravity = obj.G || -100; this.ws = obj.worldScale || 100; this.iteration = obj.iteration || 2; this.solver = null; this.collisionConfig = null; this.dispatcher = null; this.broadphase = null; this.world = null; this.BODYID = 0; this.CARID = 0; this.JOINTID = 0; this.bodys = null; this.joints = null; this.cars = null; this.terrain = null; this.init(); this.last = Date.now(); this.now = 0; this.dt = 0; this.tt = [0 , 0]; this.infos = []; this.key = [0,0,0,0,0,0,0, 0]; } AMMO.World.prototype = { constructor: AMMO.World, init:function(){ if(this.world == null){ //this.last = Date.now(); this.solver = new Ammo.btSequentialImpulseConstraintSolver(); this.collisionConfig = new Ammo.btDefaultCollisionConfiguration(); this.dispatcher = new Ammo.btCollisionDispatcher(this.collisionConfig); switch(this.Broadphase){ case 'SAP': this.broadphase = new Ammo.btAxisSweep3(AMMO.V3(-10*ws,-10*ws,-10*ws),AMMO.V3(10*ws,10*ws,10*ws), 4096); break;//16384; case 'BVT': this.broadphase = new Ammo.btDbvtBroadphase(); break; case 'SIMPLE': this.broadphase = new Ammo.btSimpleBroadphase(); break; } this.world = new Ammo.btDiscreteDynamicsWorld(this.dispatcher, this.broadphase, this.solver, this.collisionConfig); this.world.setGravity(AMMO.V3(0, this.gravity, 0)); this.bodys = []; this.joints = []; this.cars = []; } }, clear:function(){ var i; i = this.BODYID; while (i--) { this.world.removeRigidBody(this.bodys[i].body); Ammo.destroy( this.bodys[i].body ); } i = this.CARID; while (i--) { this.world.removeRigidBody(this.cars[i].body); this.world.removeVehicle(this.cars[i].vehicle); Ammo.destroy( this.cars[i].body ); Ammo.destroy( this.cars[i].vehicle ); } i = this.JOINTID; while (i--) { this.world.removeConstraint(this.joints[i].joint); Ammo.destroy( this.joints[i].joint ); } this.world.clearForces(); if(this.terrain!== null) this.terrain = null; this.bodys.length = 0; this.BODYID = 0; this.cars.length = 0; this.CARID = 0; this.joints.length = 0; this.JOINTID = 0; this.world.getBroadphase().resetPool(this.world.getDispatcher()); this.world.getConstraintSolver().reset(); Ammo.destroy( this.world ); Ammo.destroy( this.solver ); Ammo.destroy( this.collisionConfig ); Ammo.destroy( this.dispatcher ); Ammo.destroy( this.broadphase ); this.world = null; }, worldscale:function(scale){ AMMO.WORLD_SCALE = scale || 100; AMMO.INV_SCALE = 1/AMMO.WORLD_SCALE; }, addBody:function(obj){ var id = this.BODYID++; this.bodys[id] = new AMMO.Rigid(obj, this ); }, addCar:function(obj){ var id = this.CARID++; this.cars[id] = new AMMO.Vehicle(obj, this ); }, addJoint:function(obj){ var id = this.JOINTID++; this.joints[id] = new AMMO.Constraint(obj, this ); }, step:function(dt){ //dt = dt || 1; var now = Date.now(); this.dt = now - this.last; var i; i = this.BODYID; while (i--) { this.bodys[i].getMatrix(i); } i = this.CARID; while (i--) { if(i==this.key[6])this.cars[i].drive(); this.cars[i].getMatrix(i); } this.world.stepSimulation( this.dt, this.iteration); this.last = now; this.upInfo(); }, upInfo:function(){ this.infos[1] = this.BODYID; this.infos[2] = this.CARID; if (this.last - 1000 > this.tt[0]) { this.tt[0] = this.last; this.infos[0] = this.tt[1]; this.tt[1] = 0; } this.tt[1]++; }, getByName:function(name){ var i, result = null; i = this.BODYID; while(i--){ if(this.bodys[i].name == name) result = this.bodys[i]; } /*i = this.JOINTID; while(i--){ if(this.joints[i].name!== "" && this.joints[i].name == name) result = this.joints[i]; }*/ return result; }, setKey:function(k){ this.key = k; } } //-------------------------------------------------- // RIGIDBODY //-------------------------------------------------- AMMO.Rigid = function(obj, Parent){ this.parent = Parent; this.name = obj.name || ""; this.body = null; this.shape = null; this.forceUpdate = false; this.forceState = false; this.limiteY = obj.limiteY || 20; this.init(obj); // get only shape for car if(this.parent == null ) return this.shape; } AMMO.Rigid.prototype = { constructor: AMMO.Rigid, init:function(obj){ var mass = obj.mass || 0; var size = obj.size || [1,1,1]; var dir = obj.dir || [0,1,0]; // for infinite plane var div = obj.div || [64,64]; var pos = obj.pos || [0,0,0]; var rot = obj.rot || [0,0,0]; // phy = [friction, restitution]; var phy = obj.phy || [0.5,0]; var noSleep = obj.noSleep || false; var shape; switch(obj.type){ case 'plane': shape = new Ammo.btStaticPlaneShape(AMMO.V3A(dir), 0);break; case 'box': case 'boxbasic': case 'dice': case 'ground': shape = new Ammo.btBoxShape(AMMO.V3(size[0]*0.5, size[1]*0.5, size[2]*0.5)); break; case 'sphere': shape = new Ammo.btSphereShape(size[0]); break; case 'cylinder': shape = new Ammo.btCylinderShape(AMMO.V3(size[0], size[1]*0.5, size[2]*0.5)); break; case 'cone': shape = new Ammo.btConeShape(size[0], size[1]*0.5); break; case 'capsule': shape = new Ammo.btCapsuleShape(size[0], size[1]*0.5); break; case 'compound': shape = new Ammo.btCompoundShape(); break; case 'mesh': var mTriMesh = new Ammo.btTriangleMesh(); var removeDuplicateVertices = true; var v0 = AMMO.V3(0,0,0); var v1 = AMMO.V3(0,0,0); var v2 = AMMO.V3(0,0,0); var vx = obj.v; for (var i = 0, fMax = vx.length; i < fMax; i+=9){ v0.setValue( vx[i+0], vx[i+1], vx[i+2] ); v1.setValue( vx[i+3], vx[i+4], vx[i+5] ); v2.setValue( vx[i+6], vx[i+7], vx[i+8] ); mTriMesh.addTriangle(v0,v1,v2, removeDuplicateVertices); } if(mass == 0){ // btScaledBvhTriangleMeshShape -- if scaled instances shape = new Ammo.btBvhTriangleMeshShape(mTriMesh, true, true); }else{ // btGimpactTriangleMeshShape -- complex? // btConvexHullShape -- possibly better? shape = new Ammo.btConvexTriangleMeshShape(mTriMesh,true); } break; case 'convex': shape = new Ammo.btConvexHullShape(); var v = AMMO.V3(0,0,0); var vx = obj.v; for (var i = 0, fMax = vx.length; i < fMax; i+=3){ AMMO.copyV3([vx[i+0], vx[i+1], vx[i+2]], v); shape.addPoint(v); } break; case 'terrain': this.parent.terrain = new AMMO.Terrain(div, size); shape = this.parent.terrain.shape; break; } if(this.parent == null ){ this.shape=shape; return;} var transform = new Ammo.btTransform(); transform.setIdentity(); // position transform.setOrigin(AMMO.V3A(pos)); // rotation var q = new Ammo.btQuaternion(); q.setEulerZYX(rot[2]*AMMO.TORAD,rot[1]*AMMO.TORAD,rot[0]*AMMO.TORAD); transform.setRotation(q); // static if(mass == 0){ this.forceUpdate = true; //this.flags = AMMO.STATIC_OBJECT; this.type = AMMO.STATIC; } else { //this.flags = AMMO.KINEMATIC_OBJECT; this.type = AMMO.DYNAMIC; } var localInertia = AMMO.V3(0, 0, 0); shape.calculateLocalInertia(mass, localInertia); this.motionState = new Ammo.btDefaultMotionState(transform); var rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, this.motionState, shape, localInertia); rbInfo.set_m_friction(phy[0]); rbInfo.set_m_restitution(phy[1]); this.body = new Ammo.btRigidBody(rbInfo); //this.body.setLinearVelocity(AMMO.V3(0,0,0)); //this.body.setAngularVelocity(AMMO.V3(0,0,0)); //this.body.setCollisionFlags(this.flags); //this.body.setCollisionFlags //this.body.setTypes(this.type); //this.body.setContactProcessingThreshold(AMMO.BT_LARGE_FLOAT); //this.body.setFriction(phy[0]); //this.body.setRestitution(phy[1]); if(noSleep) this.body.setActivationState(AMMO.DISABLE_DEACTIVATION); this.parent.world.addRigidBody(this.body); this.body.activate(); Ammo.destroy(rbInfo); }, getBody:function(){ return this.body; }, set:function(obj){ var v = AMMO.V3(0,0,0); this.body.setLinearVelocity(v); this.body.setAngularVelocity(v); this.body.clearForces(); if(obj.pos){ this.body.getCenterOfMassTransform().setOrigin(AMMO.V3A(obj.pos));} if(obj.rot){ var q = new Ammo.btQuaternion(); q.setEulerZYX(obj.rot[2]*AMMO.TORAD,obj.rot[1]*AMMO.TORAD,obj.rot[0]*AMMO.TORAD); this.body.getCenterOfMassTransform().setRotation(q); } }, getMatrix:function(id){ var m = this.parent.mtx; var n = id*8; if(this.forceUpdate){ m[n+0] = 1; this.forceUpdate=false; } else{ m[n+0] = this.body.getActivationState(); } if(m[n+0]==2) return; var t = this.body.getWorldTransform(); var r = t.getRotation(); var p = t.getOrigin(); m[n+1] = r.x(); m[n+2] = r.y(); m[n+3] = r.z(); m[n+4] = r.w(); m[n+5] = p.x(); m[n+6] = p.y(); m[n+7] = p.z(); if(this.limiteY !== 0 && m[n+6]<-this.limiteY){ this.set({pos:[0, 3+Math.random()*10, 0]}); } } } //-------------------------------------------------- // TERRAIN //-------------------------------------------------- AMMO.Terrain = function(div, size){ this.div = div; this.size = size; this.fMax = div[0]*div[1]; this.maxHeight = 100; this.ptr = Ammo.allocate(this.fMax*4, "float", Ammo.ALLOC_NORMAL); this.shape = new Ammo.btHeightfieldTerrainShape(this.div[0], this.div[1], this.ptr, 1, -this.maxHeight, this.maxHeight, 1, 0, false); this.shape.setUseDiamondSubdivision(true); var localScaling = AMMO.V3(this.size[0]/this.div[0],1,this.size[2]/this.div[1]); this.shape.setLocalScaling(localScaling); } AMMO.Terrain.prototype = { constructor: AMMO.Terrain, update:function(Hdata){ var i = this.fMax; while(i--){ Ammo.setValue(this.ptr+(i<<2), Hdata[i], 'float'); } } } //-------------------------------------------------- // CONSTRAINT //-------------------------------------------------- AMMO.Constraint = function(obj, Parent){ this.parent = Parent; this.name = obj.name || ""; this.joint = null; var collision = obj.collision || false; if(collision)this.NotAllowCollision = false; else this.NotAllowCollision = true; this.body1 = this.parent.getByName(obj.body1); this.body2 = this.parent.getByName(obj.body2); var p1 = obj.pos1 || [0,0,0]; var p2 = obj.pos2 || [0,0,0]; this.point1 = AMMO.V3A(p1); this.point2 = AMMO.V3A(p2); var a1 = obj.axe1 || [0,1,0]; var a2 = obj.axe2 || [0,1,0]; this.axe1 = AMMO.V3A(a1); this.axe2 = AMMO.V3A(a2); this.damping = obj.damping || 1; this.strength = obj.strength || 0.1; this.min = obj.min || 0; this.max = obj.max || 0; var spring = obj.spring || [0.9, 0.3, 0.1]; this.softness = spring[0]; this.bias = spring[1]; this.relaxation = spring[2]; this.init(obj); } AMMO.Constraint.prototype = { constructor: AMMO.Constraint, init:function(obj){ switch(obj.type){ case "p2p": this.joint = new Ammo.btPoint2PointConstraint(this.body1.getBody(), this.body2.getBody(), this.point1, this.point2); this.joint.get_m_setting().set_m_tau(this.strength); this.joint.get_m_setting().set_m_damping(this.damping); break; case "hinge": this.joint = new Ammo.btHingeConstraint(this.body1.getBody(), this.body2.getBody(), this.point1, this.point2, this.axe1, this.axe2, false); if( this.min!==0 || this.max!==0 )this.joint.setLimit( this.min, this.max, this.softness, this.bias, this.relaxation); break; case "slider": this.joint = new Ammo.btSliderConstraint(this.body1.getBody(),this.body2.getBody(),this.point1,this.point2); break; case "conetwist": this.joint = new Ammo.btConeTwistConstraint(this.body1.getBody(),this.body2.getBody(),this.point1,this.point2); break; case "gear": this.joint = new Ammo.btGearConstraint(this.body1.getBody(),this.body2.getBody(),this.point1,this.point2, this.ratio); break; case "dof": this.joint = new Ammo.btGeneric6DofConstraint(this.body1.getBody(),this.body2.getBody(),this.point1,this.point2); break; } // this.parent.world.addConstraint(this.joint, this.NotAllowCollision); }, getMatrix:function(id){ //var m = this.parent.jmtx; } } //-------------------------------------------------- // VEHICLE //-------------------------------------------------- AMMO.Vehicle = function(obj, Parent){ this.parent = Parent; this.type = obj.type || 'basic'; this.size = obj.size || [1,1,1]; this.pos = obj.pos || [0,0,0]; this.rot = obj.rot || [0,0,0]; this.phy = obj.phy || [0.5,0]; this.limiteY = obj.limiteY || 20; this.massCenter = obj.massCenter || [0,0.05,0]; this.wRadius = obj.wRadius; this.wDeepth = obj.wDeepth; this.nWheels = obj.nWheels || 4; this.wPos = obj.wPos || [20,5,10]; /*this.rightIndex = 0; this.upIndex = 1; this.forwardIndex = 2;*/ this.settings = obj.setting || { engine:600, stiffness: 40, relaxation: 0.85, compression: 0.82, travel: 500, force: 6000, frictionSlip: 20.5, reslength: 0.1, roll: 0.1 }; this.maxEngineForce = this.settings.engine;//obj.maxEngineForce || 2000.0; this.maxBreakingForce = obj.maxBreakingForce || 125.0; this.steeringClamp = obj.steeringClamp || 0.51; this.engine = 0.0; this.breaking = 0.0; this.steering = 0.0; this.gas = 0; this.incEngine = 5; this.maxSteering = Math.PI / 6; this.incSteering = 0.01; this.vehicleRayCaster = null; this.tuning = null; this.vehicle = null; this.wheelDirectionCS0 = AMMO.V3(0, -1, 0); this.wheelAxleCS = AMMO.V3(-1, 0, 0); //this.shape = new Ammo.btBoxShape(AMMO.V3(this.size[0]*0.5, this.size[1]*0.5, this.size[2]*0.5, true)); //if(obj.v) this.shape = new AMMO.Rigid({type:'mesh', v:obj.v, mass:obj.mass }, null); if(obj.v) this.shape = new AMMO.Rigid({type:'convex', v:obj.v, mass:obj.mass}, null); else this.shape = new AMMO.Rigid({type:'box', size:this.size}, null); this.compound = new Ammo.btCompoundShape(); // move center of mass var localTrans = new Ammo.btTransform(); localTrans.setIdentity(); localTrans.setOrigin(AMMO.V3(this.massCenter[0],this.massCenter[1],this.massCenter[2])); this.compound.addChildShape(localTrans, this.shape); this.transform = new Ammo.btTransform(); this.transform.setIdentity(); // position this.transform.setOrigin(AMMO.V3(this.pos[0], this.pos[1], this.pos[2], true)); // rotation var q = new Ammo.btQuaternion(); q.setEulerZYX(this.rot[2]*AMMO.TORAD,this.rot[1]*AMMO.TORAD,this.rot[0]*AMMO.TORAD); this.transform.setRotation(q); this.mass = obj.mass || 400; this.localInertia = AMMO.V3(0, 0, 0); //this.shape.calculateLocalInertia(this.mass, this.localInertia); this.compound.calculateLocalInertia(this.mass, this.localInertia); this.motionState = new Ammo.btDefaultMotionState(this.transform); //this.rbInfo = new Ammo.btRigidBodyConstructionInfo(this.mass, this.motionState, this.shape, this.localInertia); this.rbInfo = new Ammo.btRigidBodyConstructionInfo(this.mass, this.motionState, this.compound, this.localInertia); this.rbInfo.set_m_friction(this.phy[0]); this.rbInfo.set_m_restitution(this.phy[1]); //console.log(this.rbInfo.get_m_linearDamping())//0 //console.log(this.rbInfo.get_m_angularDamping())//0 this.body = new Ammo.btRigidBody(this.rbInfo); this.body.setLinearVelocity([0, 0, 0]); this.body.setAngularVelocity([0, 0, 0]); this.body.setActivationState(AMMO.DISABLE_DEACTIVATION); //this.body.setFriction(this.phy[0]); //this.body.setRestitution(this.phy[1]); //world.addRigidBody(this.body); //this.body.activate(); //this.chassis = world.localCreateRigidBody(50,tr,compound); //this.chassis.setActivationState(AMMO.DISABLE_DEACTIVATION); this.wheelShape = new Ammo.btCylinderShapeX(AMMO.V3( this.wDeepth , this.wRadius, this.wRadius)); // create vehicle this.init(); } AMMO.Vehicle.prototype = { constructor: AMMO.Vehicle, init:function(){ this.vehicleRayCaster = new Ammo.btDefaultVehicleRaycaster(this.parent.world); this.tuning = new Ammo.btVehicleTuning(); // 10 = Offroad buggy, 50 = Sports car, 200 = F1 Car this.tuning.set_m_suspensionStiffness(this.settings.stiffness); //100; // 0.1 to 0.3 are good values this.tuning.set_m_suspensionDamping(this.settings.relaxation);//0.87 this.tuning.set_m_suspensionCompression(this.settings.compression);//0.82 this.tuning.set_m_maxSuspensionTravelCm(this.settings.travel);//500 this.tuning.set_m_maxSuspensionForce(this.settings.force);//6000 this.tuning.set_m_frictionSlip( this.settings.frictionSlip);//10.5 //this.maxEngineForce = this.settings.engine; this.vehicle = new Ammo.btRaycastVehicle(this.tuning, this.body, this.vehicleRayCaster); // choose coordinate system //this.vehicle.setCoordinateSystem(this.rightIndex,this.upIndex,this.forwardIndex); this.vehicle.setCoordinateSystem(0,1,2); var isFrontWheel = true; this.vehicle.addWheel( AMMO.V3(this.wPos[0], this.wPos[1], this.wPos[2]), this.wheelDirectionCS0, this.wheelAxleCS, this.settings.reslength, this.wRadius, this.tuning, isFrontWheel); this.vehicle.addWheel( AMMO.V3(-this.wPos[0], this.wPos[1], this.wPos[2]), this.wheelDirectionCS0, this.wheelAxleCS, this.settings.reslength, this.wRadius, this.tuning, isFrontWheel); this.vehicle.addWheel( AMMO.V3(-this.wPos[0], this.wPos[1], -this.wPos[2]), this.wheelDirectionCS0, this.wheelAxleCS, this.settings.reslength, this.wRadius, this.tuning, false); this.vehicle.addWheel( AMMO.V3(this.wPos[0], this.wPos[1], -this.wPos[2]), this.wheelDirectionCS0, this.wheelAxleCS, this.settings.reslength, this.wRadius, this.tuning, false); for (var i=0; i<this.vehicle.getNumWheels(); i++){ var wheel = this.vehicle.getWheelInfo(i); wheel.set_m_rollInfluence( this.settings.roll);//0.1 //wheel.set_m_suspensionStiffness( this.settings.suspensionStiffness); //wheel.set_m_suspensionRestLength1( this.settings.suspensionRestLength );//0.1 //wheel.set_m_wheelsDampingRelaxation( this.settings.wheelsDampingRelaxation);//0.85 //wheel.set_m_wheelsDampingCompression( this.settings.wheelsDampingCompression);//0.82 //wheel.set_m_frictionSlip( this.settings.frictionSlip);//10.5 } this.parent.world.addVehicle(this.vehicle); //this.parent.world.addVehicle(this.vehicle, this.wheelShape); this.parent.world.addRigidBody(this.body); this.body.activate(); }, getMatrix:function(id){ var m = this.parent.mtxCar; var n = id*40; m[n+0] = parseInt(this.vehicle.getCurrentSpeedKmHour());//.toFixed(0);//this.body.getActivationState(); //var t = this.body.getCenterOfMassTransform(); //var t = this.vehicle.getChassisWorldTransform(); var t = this.body.getWorldTransform(); var r = t.getRotation(); var p = t.getOrigin(); m[n+1] = r.x(); m[n+2] = r.y(); m[n+3] = r.z(); m[n+4] = r.w(); if(this.type=='basic'){ m[n+5] = p.x()+this.massCenter[0]; m[n+6] = p.y()+this.massCenter[1]; m[n+7] = p.z()+this.massCenter[2]; }else{ m[n+5] = p.x(); m[n+6] = p.y(); m[n+7] = p.z(); } var i = this.nWheels; var w; while(i--){ t = this.vehicle.getWheelInfo( i ).get_m_worldTransform(); r = t.getRotation(); p = t.getOrigin(); w = 8*(i+1); if(i==0) m[n+w+0] = this.steering; else m[n+w+0] = i; m[n+w+1] = r.x(); m[n+w+2] = r.y(); m[n+w+3] = r.z(); m[n+w+4] = r.w(); m[n+w+5] = p.x(); m[n+w+6] = p.y(); m[n+w+7] = p.z(); } }, drive:function(){ var key = this.parent.key; //var lus = key[7]; //if (lus>0.1) lus = 0.1; if(key[2]==1)this.steering+=this.incSteering; if(key[3]==1)this.steering-=this.incSteering; if(key[2]==0 && key[3]==0) this.steering *= 0.9;//this.steering = 0; if (this.steering < -this.maxSteering) this.steering = -this.maxSteering; if (this.steering > this.maxSteering) this.steering = this.maxSteering; if(key[0]==1)this.engine+=this.incEngine;//this.gas = 1; // if(key[1]==1)this.engine-=this.incEngine;//this.gas = -1; // if(key[0]==0 && key[1]==0){ if(this.engine>1)this.engine *= 0.9; else if (this.engine<-1)this.engine *= 0.9; else {this.engine = 0; this.breaking=100;} } //this.gas = 0; //console.log(this.engine) /*if (this.gas > 0) { this.engine += 5;//lus*300; } else if (this.gas < 0) { if (this.engine>0) { this.engine *= 0.5//-= this.engine*lus*10.0; } this.engine -= 3;//lus*200.0; } else { //this.engine -= this.engine*lus*2.0; this.engine *= 0.9; //vehicle.setEngineForce(vehicle.getEngineForce()-(vehicle.getEngineForce()*lus*2.0)); }*/ if (this.engine > this.maxEngineForce) this.engine = this.maxEngineForce; if (this.engine < -this.maxEngineForce) this.engine = -this.maxEngineForce; var i = this.nWheels; while(i--){ this.vehicle.applyEngineForce( this.engine, i ); this.vehicle.setBrake( this.breaking, i ); if(i==0 || i==1) this.vehicle.setSteeringValue( this.steering, i ); } //this.steering *= 0.9; } }<file_sep>/demos/demo04.js CLEAR({broadphase:"BVT", timer:false, timestep:1/60, iteration:2, G:-10}); function initDemo() { NAME("Infinite Terrain", "use arrow key to move terrain"); ADD({type:"ground", size:[200,1,200], pos:[0,0.5,0] }); ADD({type:"terrain", size:[200,10,200], pos:[0,0,0], div:[128,128], Move:true }); var max = 50; var px, py, pz, sx, sy, sz; for (var i=0; i!==max; ++i ){ sx = 1 + Math.random(); sy = 1 + Math.random(); sz = 1 + Math.random(); px = -10+Math.random()*20; py = 1+i; pz = -10+Math.random()*20; ADD({type:"box", size:[sx,sy,sz], pos:[px, py, pz], mass:1, noSleep:true }); } }<file_sep>/demos/demo00.js CLEAR({broadphase:"BVT", timer:false, timestep:1/60, iteration:2, G:-10}); function initDemo() { NAME("Basic shapes"); // ground ADD({type:"ground", size:[20,3,20], pos:[0,-1.5,0], mass:0}); // NOTE: // you can choose broadphase BVT, SAP or SIMPLE // use 1 unit for one meter // dynamique object var max = 100; var px, pz, py, t, n = 5; var sx, sy, sz; for (var i=0; i!==max; ++i ){ t = Math.floor(Math.random()*n)+1; px = -1+Math.random()*2; pz = -1+Math.random()*2; py = 2 + i; sx = 0.2+Math.random(); sy = 0.2+Math.random(); sz = 0.2+Math.random(); switch(t){ case 1: ADD({ type:"box", size:[sx,sy,sz], pos:[px,py,pz], mass:1 }); break; case 2: ADD({ type:"sphere", size:[sx*0.5], pos:[px,py,pz], mass:1 }); break; case 3: ADD({ type:"cylinder", size:[sx*0.5,sy,sx*0.5], pos:[px,py,pz], mass:1 }); break; case 4: ADD({ type:"capsule", size:[sx*0.5,sy], pos:[px,py,pz], mass:1 }); break; case 5: ADD({ type:"cone", size:[sx*0.5,sy], pos:[px,py,pz], mass:1 }); break; } } }<file_sep>/demos/demo06.js CLEAR({broadphase:"BVT", timer:false, timestep:1/60, iteration:2, G:-10}); function initDemo() { NAME("<NAME>"); ADD({type:"plane"}); ADD({type:"ground", size:[30,1,20], pos:[0,1,0], rot:[9,0,0], mass:0}); ADD({type:"boxbasic", size:[30,2,1], pos:[0,1,16] }); ADD({type:"box", size:[1,1,1], pos:[9, 10, 0], mass:1, noSleep:true}); ADD({type:"box", size:[1,1,1], pos:[-8, 10, 0], mass:1, noSleep:true}); var max = 50; var px, py, pz, sx, sy, sz; for (var i=0; i!==max; ++i ){ px = -10+Math.random()*20; pz = -10+Math.random()*20; sx = 0.2+Math.random(); sy = 0.2+Math.random(); sz = 0.2+Math.random(); py = 5+(i*6); ADD({type:"convex", name:"L", size:[sx, sy, sz], pos:[px, py, pz], mass:1 }); ADD({type:"convex", name:"T", size:[sx, sy, sz], pos:[px, py+2, pz], mass:1 }); ADD({type:"convex", name:"H", size:[sx, sy, sz], pos:[px, py+4, pz], mass:1 }); } }<file_sep>/demos/demo08.js CLEAR({broadphase:"BVT", timer:false, timestep:1/60, iteration:2, G:-10}); function initDemo() { NAME("Vehicule Terrain"); ADD({type:"plane"}); ADD({type:"terrain", pos:[0,0,0], size:[200,5,200], div:[128,128], Move:true }); // NOTE: use arrow key to control car // select your car with number 0-9 var Setting = { engine:600, stiffness: 40, relaxation: 0.85, compression: 0.82, travel: 500, force: 6000, frictionSlip: 10.5, reslength: 0.1, roll: 0.1 } var max = 10; // maximum 20 var px, t, n=2; for (var i=0; i!==max; ++i ){ t = Math.floor(Math.random()*n)+1; px=-11+(i*2.5); switch(t){ case 1: CAR({type:'c1gt', pos:[px, 8, -7], mass:900, setting:Setting }); break; case 2: CAR({type:'vision', pos:[px, 8, -7], mass:1490, setting:Setting }); break; case 3: CAR({ type:'basic', pos:[px, 10, -7], mass:1000, setting:Setting, size:[2,0.5,5], wPos:[1,0,2], wRadius:0.4, massCenter:[0,0.05,0] }); break; } } }<file_sep>/demos/demo01.js CLEAR({broadphase:"BVT", timer:false, timestep:1/60, iteration:2, G:-10}); function initDemo() { NAME("In the Box"); // ground ADD({type:"ground", size:[5.5,3,5.5], pos:[0,-1.5,0]}); // wall ADD({ type:"boxbasic", size:[4.5,10,0.5], pos:[0,5,-2.5] }); ADD({ type:"boxbasic", size:[4.5,10,0.5], pos:[0,5, 2.5] }); ADD({ type:"boxbasic", size:[0.5,10,5.5], pos:[-2.5,5,0] }); ADD({ type:"boxbasic", size:[0.5,10,5.5], pos:[ 2.5,5,0] }); // dynamique object var max = 200; var px, pz, t, n = 3; var sx, sy, sz; for (var i=0; i!==max; ++i ){ t = Math.floor(Math.random()*n)+1; px = -1+Math.random()*2; pz = -1+Math.random()*2; py = i; sx = 0.2+Math.random(); sy = 0.2+Math.random(); sz = 0.2+Math.random(); if(t==1) ADD({ type:"sphere", size:[sx*0.5], pos:[px,py,pz], mass:1 }); else if(t==2) ADD({ type:"box", size:[sx,sy,sz], pos:[px,py,pz], mass:1 }); else if(t==3) ADD({ type:"cylinder", size:[sx*0.5,sy,sx*0.5], pos:[px,py,pz], mass:1 }); } }<file_sep>/README.md [<img src="http://lo-th.github.io/Ammo.lab/images/logo.jpg"/>](http://lo-th.github.io/Ammo.lab/) ======== Advanced 3d physics for three.js<br> use compressed full version of [ammo.js](https://github.com/kripken/ammo.js)<br> ( Bullet: 6.15 Mb > ammo.js: 3.53 Mb > Ammo.lab: 555 Kb )<br> [HOME PAGE](http://lo-th.github.io/Ammo.lab/)<br> <file_sep>/js/loth/Editor.js /** * @author loth / http://3dflashlo.wordpress.com/ */ 'use strict'; var Editor = function (Themes, nDemo) { var maxDemo = nDemo || 7; var themes = Themes || ['1d1f20', '2f3031', '424344']; var fontFamily = "font-family:Consolas, 'ConsolasRegular', 'Courier New', monospace;"; var degrade01 = '#'+themes[0]+';';//'linear-gradient(45deg, #'+themes[0]+', #'+themes[1]+');'; var fullImg = '';//background: url(images/grad.png) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover;' var unselect = '-o-user-select:none; -ms-user-select:none; -khtml-user-select:none; -webkit-user-select:none; -moz-user-select: none;' var textselect = '-o-user-select:text; -ms-user-select:text; -khtml-user-select:text; -webkit-user-select:text; -moz-user-select: text;' var open = false; var container = document.createElement( 'div' ); //container.style.cssText = unselect+'position:absolute; margin:0; padding:0; top:0px; bottom:0px; right:0px; color:#CCCCCC; width:100%; height:100% font-size:12px; font-family:SourceCode; pointer-events:none;'; container.style.cssText = unselect+'position:absolute; margin:0; padding:0; top:0px; left:0px; width:100%; height:100%; font-size:12px; pointer-events:none;' + fontFamily; container.id = 'Editor'; /*var logobb = document.createElement( 'div' ); logobb.style.cssText = 'position:absolute; width:100%; height:100%; background:#FFFFFF'; container.appendChild( logobb ); themes[0] = "FFFFFF";*/ // 25517c//693c28 var introX = document.createElement( 'div' ); introX.style.cssText = '-webkit-filter: drop-shadow( 1px 1px 1px #00ffff ); filter: drop-shadow( 1px 1px 1px #00ffff ); text-align:center; position:absolute; margin:0; padding:0; top:50%; left:50%; width:300px; height:150px; margin-left:-150px; margin-top:-75px; display:block; pointer-events:none'; container.appendChild( introX ); var containerEdit = document.createElement( 'div' ); //containerEdit.style.cssText = unselect+'position:absolute; margin:0; padding:0; top:0px; left:50%; color:#CCCCCC; width:50%; height:100%; font-size:12px; font-family:SourceCode; pointer-events:none; display:none; background:' + degrade01; containerEdit.style.cssText = unselect+fullImg+'position:absolute; margin:0; padding:0; top:0px; left:50%; color:#CCCCCC; width:50%; height:100%; font-size:12px; pointer-events:none; display:none;'+ fontFamily;//' background-image:url(images/grad.png)' containerEdit.id = 'EditorRoot'; container.appendChild( containerEdit ); var line = document.createElement( 'div' ); line.style.cssText = unselect+'position:absolute; margin:0; padding:0; top:-1px; left:-1px; width:1px; height:100%; pointer-events:none; background:#'+themes[2]+';'; containerEdit.appendChild( line ); var iconSize0 = 90; var iconSize = 36; var iconSize2 = 46; var iconColor = '#ffffff'; var icon_libs= [ "<svg version='1.1' id='Calque_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px'", "width='"+iconSize0+"px' height='"+iconSize0+"px' viewBox='0 40 128 50' enable-background='new 0 40 128 50' xml:space='preserve' >", "<g><path id='icon_libs' fill='#"+themes[0]+"' d='M78.881,34.035v-3.054C81.464,30.785,83.5,28.633,83.5,26c0-2.761-2.239-5-5-5c-0.75,0-5.958,0-7.872,4.25", "c-2.123,4.715-1.709,8.826-1.709,8.826c0,21.715,17.59,23.895,17.59,40.494c0,12.389-10.078,22.467-22.467,22.467", "c-12.389,0-22.467-10.079-22.467-22.467c0-16.911,17.59-18.498,17.59-40.494c0,0,0.086-4.41-2.529-8.826", "C54.142,21.039,50,21,49.25,21c-2.761,0-5,2.239-5,5c0,2.717,2.169,4.923,4.869,4.993v3.042c0,17.909-17.59,17.92-17.59,40.494", "C31.528,92.462,46.066,107,64,107s32.471-14.538,32.471-32.471C96.471,52.276,78.881,51.708,78.881,34.035z'/>", "<circle fill='#"+themes[0]+"' cx='64.937' cy='85.463' r='3.87'/>", "<circle fill='#"+themes[0]+"' cx='64.751' cy='72.129' r='3.061'/>", "<circle fill='#"+themes[0]+"' cx='64.589' cy='58.439' r='2.764'/>", "<circle fill='#"+themes[0]+"' cx='76.325' cy='76.663' r='3.518'/>", "<circle fill='#"+themes[0]+"' cx='55.491' cy='65.33' r='2.764'/>", "<circle fill='#"+themes[0]+"' cx='52.726' cy='78.197' r='4.523'/>", "</g></svg>" ].join("\n"); var introStyle = unselect+'color:#'+themes[0]+'; -webkit-filter: drop-shadow( -1px -1px 1px #ff0000 ); filter: drop-shadow( -1px -1px 1px #ff0000 );pointer-events:none; font-size:40px; font-weight:800;'; var logo = document.createElement( 'div' ); logo.style.cssText = introStyle; logo.innerHTML = icon_libs;//+ "<br>Ammo.lab"; introX.appendChild( logo ); var logotext = document.createElement( 'div' ); logotext.style.cssText = introStyle + 'margin-top:-30px;'; logotext.innerHTML = "Ammo.lab"; introX.appendChild( logotext ); var hideIntro = function () { introX.removeChild(logo); container.removeChild( introX ); nMenu0.style.display = "block"; nMenu1.style.display = "block"; nMenu.style.display = "block"; menuDemo.style.display = "block"; }; var icon_sketch = [ "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px'", "width='"+iconSize+"px' height='"+iconSize+"px' viewBox='0 0 512 512' enable-background='new 0 0 512 512' xml:space='preserve'>", "<path id='icon_sketch' fill='"+iconColor+"' d='M406.795,288.699c0,0-150.181-200.667-167.999-223.151C230.815,55.477,218.572,50,203.566,50", "c-18.495,0-41.19,8.311-65.313,26.578c-43.697,33.091-55.152,68.727-37.758,93.333c17.394,24.605,169.059,224.635,169.059,224.635", "L429.28,462L406.795,288.699z M373.723,291.244c-8.167,6.262-19.282,9.627-31.722,9.37c-19.202-0.384-37.061-9.212-47.773-23.615", "c0,0-68.544-91.57-86.417-115.446c22.586-15.522,44.649-19.854,52.812-20.98C299.125,191.673,351.506,261.579,373.723,291.244z", "M246.924,122.409c-13.336,3.071-33.354,9.789-53.55,24.405c-20.146,14.579-32.598,33.948-39.599,47.948", "c-5.425-7.236-10.367-13.843-14.66-19.604c4.867-11.375,16.086-32.71,36.5-47.482c26.535-19.203,53.045-22.577,57.857-23.045", "C237.468,109.898,242,115.89,246.924,122.409z M122.624,136.409c4.455-11.676,16.008-24.997,32.532-37.509", "c17.54-13.283,35.185-20.9,48.41-20.9c6.219,0,10.689,1.661,13.286,4.938c0.673,0.85,1.557,1.982,2.607,3.34", "c-13.267,2.82-34.427,9.446-55.782,24.901c-18.947,13.712-31.086,31.659-38.29,45.395c-0.801-1.104-1.489-2.062-2.028-2.825", "C122.053,151.901,118.585,146.995,122.624,136.409z M167.747,213.368c3.66-9.166,12.858-28.557,30.038-43.972", "c15.447,20.63,67.472,90.116,86.398,115.472c9.793,13.118,13.633,30.794,10.538,48.497c-2.126,12.165-7.493,22.905-14.357,29.086", "C257.658,332.479,205.973,264.208,167.747,213.368z M374.452,408.451l-85.889-36.271c9.184-8.109,16.028-21.378,18.694-36.625", "c1.876-10.726,1.581-21.477-0.707-31.549c10.535,5.77,22.633,9.081,35.196,9.333c0.515,0.01,1.025,0.015,1.537,0.015", "c14.185,0,27.071-3.956,37.028-11.152l12.146,93.604C383.894,396.664,377.805,400.766,374.452,408.451z'/></svg>" ].join("\n"); var icon_github= [ "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px'", "width='"+iconSize+"px' height='"+iconSize+"px' viewBox='0 0 128 128' enable-background='new 0 0 128 128' xml:space='preserve'>", "<path id='icon_github' fill='"+iconColor+"' d='M64.606,16.666c-26.984,0-48.866,21.879-48.866,48.872", "c0,21.589,14.001,39.905,33.422,46.368c2.444,0.448,3.335-1.06,3.335-2.356c0-1.16-0.042-4.233-0.066-8.312", "c-13.594,2.953-16.462-6.551-16.462-6.551c-2.222-5.645-5.426-7.148-5.426-7.148c-4.437-3.032,0.336-2.971,0.336-2.971", "c4.904,0.346,7.485,5.036,7.485,5.036c4.359,7.468,11.438,5.312,14.222,4.061c0.444-3.158,1.706-5.312,3.103-6.533", "c-10.852-1.233-22.26-5.426-22.26-24.152c0-5.335,1.904-9.697,5.03-13.113c-0.503-1.236-2.18-6.205,0.479-12.933", "c0,0,4.103-1.314,13.438,5.01c3.898-1.084,8.078-1.626,12.234-1.645c4.15,0.019,8.331,0.561,12.234,1.645", "c9.33-6.324,13.425-5.01,13.425-5.01c2.666,6.728,0.989,11.697,0.486,12.933c3.132,3.416,5.023,7.778,5.023,13.113", "c0,18.773-11.426,22.904-22.313,24.114c1.755,1.509,3.318,4.491,3.318,9.05c0,6.533-0.06,11.804-0.06,13.406", "c0,1.307,0.88,2.827,3.36,2.35c19.402-6.475,33.391-24.779,33.391-46.363C113.478,38.545,91.596,16.666,64.606,16.666z'/></svg>" ].join("\n"); var icon_gear = [ "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px'", "width='"+iconSize+"px' height='"+iconSize+"px' viewBox='0 0 512 512' enable-background='new 0 0 512 512' xml:space='preserve'>", "<path id='icon_gear' fill='"+iconColor+"' d='M462,283.742v-55.485l-49.249-17.514c-3.4-11.792-8.095-23.032-13.919-33.563l22.448-47.227", "l-39.234-39.234l-47.226,22.449c-10.53-5.824-21.772-10.52-33.564-13.919L283.741,50h-55.484l-17.515,49.25", "c-11.792,3.398-23.032,8.094-33.563,13.918l-47.227-22.449l-39.234,39.234l22.45,47.227c-5.824,10.531-10.521,21.771-13.919,33.563", "L50,228.257v55.485l49.249,17.514c3.398,11.792,8.095,23.032,13.919,33.563l-22.45,47.227l39.234,39.234l47.227-22.449", "c10.531,5.824,21.771,10.52,33.563,13.92L228.257,462h55.484l17.515-49.249c11.792-3.398,23.034-8.095,33.564-13.919l47.226,22.448", "l39.234-39.234l-22.448-47.226c5.824-10.53,10.521-21.772,13.919-33.564L462,283.742z M256,331.546", "c-41.724,0-75.548-33.823-75.548-75.546s33.824-75.547,75.548-75.547c41.723,0,75.546,33.824,75.546,75.547", "S297.723,331.546,256,331.546z'/></svg>" ].join("\n"); var icon_update = [ "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px'", "width='"+iconSize2+"px' height='"+iconSize2+"px' viewBox='0 0 512 512' enable-background='new 0 0 512 512' xml:space='preserve'>", "<path id='icon_update' fill='"+iconColor+"' d='M373.223,142.573l-37.252,37.253c-20.225-20.224-48.162-32.731-79.021-32.731", "c-61.719,0-111.752,50.056-111.752,111.776c0,0.016,0-0.016,0,0h43.412l-69.342,69.315L50,258.871h42.514c0-0.008,0,0.006,0,0", "c0-90.816,73.621-164.46,164.436-164.46C302.357,94.411,343.467,112.816,373.223,142.573z M462,253.129l-69.268-69.316", "l-69.342,69.316h43.412c0,0.016,0-0.017,0,0c0,61.72-50.033,111.776-111.752,111.776c-30.859,0-58.797-12.508-79.021-32.731", "l-37.252,37.253c29.758,29.757,70.867,48.162,116.273,48.162c90.814,0,164.436-73.644,164.436-164.459c0-0.007,0,0.008,0,0H462z'/></svg>" ].join("\n"); var outColor = 'ffffff'; var selColor = '1a94ff';//7fdbff' var nMenu = document.createElement( 'div' ); nMenu.style.cssText = "position:absolute; width:"+iconSize+"px; height:"+iconSize+"px; margin-bottom:0px; pointer-events:auto; top:6px; right:6px; display:none;"; nMenu.innerHTML = icon_gear; container.appendChild( nMenu ); nMenu.addEventListener( 'mouseover', function ( event ) { event.preventDefault(); document.getElementById("icon_gear").setAttribute('fill','#'+selColor); updateTimer = setInterval(rotateUpdate, 10, this); }, false ); nMenu.addEventListener( 'mouseout', function ( event ) { event.preventDefault(); document.getElementById("icon_gear").setAttribute('fill','#'+outColor); clearInterval(updateTimer);}, false ); nMenu.addEventListener( 'mousedown', function ( event ) { event.preventDefault(); showCode(); }, false ); var nMenu0 = document.createElement( 'div' ); nMenu0.style.cssText = "position:absolute; width:"+iconSize+"px; height:"+iconSize+"px; margin-bottom:0px; pointer-events:auto; top:6px; left:6px; display:none;"; nMenu0.innerHTML = "<a href='https://github.com/lo-th/Ammo.lab' target='_blank' >"+icon_github+"</a>";//icon_github; container.appendChild( nMenu0 ); nMenu0.addEventListener( 'mouseover', function ( event ) { event.preventDefault(); document.getElementById("icon_github").setAttribute('fill','#'+selColor); }, false ); nMenu0.addEventListener( 'mouseout', function ( event ) { event.preventDefault(); document.getElementById("icon_github").setAttribute('fill','#'+outColor); }, false ); nMenu0.addEventListener( 'mousedown', function ( event ) { event.preventDefault(); showCode(); }, false ); var nMenu1 = document.createElement( 'div' ); nMenu1.style.cssText = "position:absolute; width:"+iconSize+"px; height:"+iconSize+"px; margin-bottom:0px; pointer-events:auto; top:56px; right:6px; display:none;"; nMenu1.innerHTML = icon_sketch; container.appendChild( nMenu1 ); nMenu1.addEventListener( 'mouseover', function ( event ) { event.preventDefault(); document.getElementById("icon_sketch").setAttribute('fill','#'+selColor); }, false ); nMenu1.addEventListener( 'mouseout', function ( event ) { event.preventDefault(); document.getElementById("icon_sketch").setAttribute('fill','#'+outColor); }, false ); nMenu1.addEventListener( 'mousedown', function ( event ) { event.preventDefault(); sketchMode(); }, false ); var sketchMode = function () { View.sketchMode(); if(View.isSketch){ textColor('111111'); outColor = '111111'; selColor = 'ab0dd8'; containerEdit.style.backgroundImage = 'url(images/sketch/paper.jpg)'; document.getElementById("info").style.color = '#111111'; document.getElementById("stats").style.color = '#111111'; MainEditor.contentWindow.changeTheme(0); }else{ textColor('cccccc'); containerEdit.style.backgroundImage = 'none'; document.getElementById("info").style.color = '#ffffff'; document.getElementById("stats").style.color = '#909090' outColor = 'ffffff'; selColor = '1a94ff'; MainEditor.contentWindow.changeTheme(1); } document.getElementById("icon_sketch").setAttribute('fill','#'+outColor); document.getElementById("icon_gear").setAttribute('fill','#'+outColor); document.getElementById("icon_github").setAttribute('fill','#'+outColor); document.getElementById("icon_update").setAttribute('fill','#'+outColor); } var showCode = function () { if(open){ hide(); View.viewSize.mw = 1; View.viewSize.mh = 1; }else{ if(self.innerWidth>self.innerHeight){ show('v'); if(stats) stats.style.bottom = '0px'; View.viewSize.mw = 0.5; View.viewSize.mh = 1; } else { show('h'); if(stats) stats.style.bottom = '50%'; View.viewSize.mw = 1; View.viewSize.mh = 0.5; } } View.resize(); } var show = function(mode){ open = true; if(mode === 'v'){ containerEdit.style.top = "0px"; containerEdit.style.left = "50%"; containerEdit.style.height = "100%"; containerEdit.style.width = "50%"; line.style.height = "100%"; line.style.width = "1px"; //line.style.left = "-1px"; } else{ containerEdit.style.top = "50%"; containerEdit.style.left = "0px"; containerEdit.style.height = "50%"; containerEdit.style.width = "100%"; line.style.height = "1px"; line.style.width = "100%"; } containerEdit.style.display = "block"; } var hide = function(){ open = false; containerEdit.style.display = "none"; if(MainEditor)MainEditor.contentWindow.close() window.focus(); } var colors = ['#303030', '#b10dc9', '#0074d9', '#ff851b']; var buttonActif = 'position:relative; display:inline-block; cursor:pointer; pointer-events:auto;'; var effect= '';//-webkit-filter: drop-shadow( 1px 1px 2px #'+themes[2]+' ); filter: drop-shadow( 1px 1px 2px #'+themes[2]+' );'; var bstyle = unselect + effect +' font-size:14px; -webkit-border-radius:40px; border-radius:40px; border:1px solid #'+themes[2]+'; height:19px; padding:0px 0px; text-align:center;';// background:'+ degrade01; var bstyleMenu = unselect + effect +' font-size:12px; -webkit-border-radius:20px; border-radius:20px; border:1px solid #'+themes[2]+'; height:19px; padding:0px 0px; text-align:center; '; var bbMenu = []; var bbColor = []; var nscript; var currentDemo; var rvalue = 0; var updateTimer; // RUN BUTTON var bRun = document.createElement( 'div' ); bRun.id = 'Editor-Run'; bRun.style.cssText = bstyle + buttonActif + 'top:10px; left:10px; position:absolute; width:46px; height:46px;'; var icColor = document.createElement( 'div' ); icColor.style.cssText = "-webkit-border-radius:40px; border-radius:40px; position:absolute; width:46px; height:46px; pointer-events:none; background-color: rgba(0,0,0,0); pointer-events:none;"; var icRun = document.createElement( 'div' ); icRun.style.cssText = "position:absolute; width:46px; height:46px; pointer-events:none;"; icRun.innerHTML = icon_update; containerEdit.appendChild( bRun ); bRun.appendChild(icColor); bRun.appendChild(icRun); bRun.addEventListener( 'mousedown', function ( event ) { event.preventDefault(); update(); icColor.style.backgroundColor = 'rgba(0,116,217,0.7)'; }, false ); bRun.addEventListener( 'mouseover', function ( event ) { event.preventDefault(); icColor.style.backgroundColor = 'rgba(0,116,217,0.1)'; updateTimer = setInterval(rotateUpdate, 10, icRun); document.getElementById("icon_update").setAttribute('fill','#'+selColor);}, false ); bRun.addEventListener( 'mouseout', function ( event ) { event.preventDefault(); icColor.style.backgroundColor = 'rgba(0,0,0,0)'; clearInterval(updateTimer); document.getElementById("icon_update").setAttribute('fill','#'+outColor);}, false ); var rotateUpdate = function (dom) { rvalue -= 5; dom.style.webkitTransform = 'rotate('+rvalue+'deg)'; dom.style.oTransform = 'rotate('+rvalue+'deg)'; dom.style.transform = 'rotate('+rvalue+'deg)'; } // MENU DEMO var menuDemo = document.createElement( 'div' ); menuDemo.id = 'menuDemo'; menuDemo.style.cssText = unselect + 'top:12px; left:180px; position:absolute; display:block; width:'+(maxDemo*28)+'px; height:60px; overflow:hidden; padding:0; display:none'; container.appendChild( menuDemo ); for(var i=0;i!==maxDemo;i++){ bbMenu[i] = document.createElement( 'div' ); bbColor[i] = document.createElement( 'div' ); bbMenu[i].style.cssText = bstyle + buttonActif + "width:20px; margin-right:2px; padding:2px 2px;"; bbColor[i].style.cssText = "-webkit-border-radius:40px; border-radius:40px; position:absolute; top:0; left:0; width:24px; height:24px; pointer-events:none; background-color: rgba(0,0,0,0);"; if(i<10){ bbMenu[i].textContent = '0'+i; bbMenu[i].name = 'demo0'+i; }else{ bbMenu[i].textContent = i; bbMenu[i].name = 'demo'+i; } bbMenu[i].addEventListener( 'mousedown', function ( event ) { event.preventDefault(); importScript(this.name); this.childNodes[1].style.backgroundColor = 'rgba(0,116,217,0.7)';}, false ); bbMenu[i].addEventListener( 'mouseover', function ( event ) { event.preventDefault(); this.childNodes[1].style.backgroundColor = 'rgba(0,116,217,0.3)'; }, false ); bbMenu[i].addEventListener( 'mouseout', function ( event ) { event.preventDefault(); this.childNodes[1].style.backgroundColor = 'rgba(0,0,0,0)'; testCurrentDemo(); }, false ); menuDemo.appendChild( bbMenu[i] ); bbMenu[i].appendChild( bbColor[i] ); } // MAIN EDITOR var MainEditor = document.createElement( 'iframe' ); MainEditor.id = 'mEditor'; MainEditor.name = 'editor'; MainEditor.src = "editor.html"; MainEditor.style.cssText =unselect+" top:70px; bottom:0px; left:10px; right:0; margin:0; padding:0; position:absolute; height:calc(100% - 70px); width:calc(100% - 10px); display:block; pointer-events:auto; border:none;" containerEdit.appendChild( MainEditor ); var importScript = function(name, Test){ currentDemo = name; var test = Test || false; MainEditor.contentWindow.setBase(Editor); MainEditor.contentWindow.loadfileJS("demos/"+name+".js"); if(test)testCurrentDemo(); } var close = function(){ MainEditor.contentWindow.close(); window.focus(); } var textColor = function(cc){ for(var i=0, j=bbMenu.length;i!==j;i++){ bbMenu[i].style.color = "#"+cc; } } var testCurrentDemo = function(){ for(var i=0, j=bbMenu.length;i!==j;i++){ if(bbMenu[i].name === currentDemo)bbMenu[i].childNodes[1].style.backgroundColor = 'rgba(177,13,201,0.5)'; else bbMenu[i].childNodes[1].style.backgroundColor = 'rgba(0,0,0,0)'; } } var update = function (){ var head = document.getElementsByTagName('head')[0]; nscript = document.createElement("script"); nscript.type = "text/javascript"; nscript.name = "topScript"; nscript.id = "topScript"; nscript.charset = "utf-8"; nscript.text = MainEditor.contentWindow.codeEditor.getValue(); head.appendChild(nscript); } return { update:update, importScript: importScript, domElement: container, hideIntro: hideIntro, close:close, getScript: function () { return nscript; }, getOpen: function () { return open; } } } <file_sep>/js/vehicle/Vision.js /** _ _ _ * | |___| |_| |__ * | / _ \ _| | * |_\___/\__|_||_| * @author LoTh /http://3dflashlo.wordpress.com/ */ // BMW Vision Efficient Dynamics // 1490 kg / 349 chevaux / max speed 250 km/h // largeur 1.9m / hauteur 1.24m / longeur 4.6m AAA.ToRad = Math.PI / 180; AAA.Vision = function(){ this.name = ['body_top', 'body_side', 'body_back', 'glass_top', 'chassisPlus', 'interiorPlus', 'capot', 'crome', 'interiorSymetrie', 'glass_wheel_window', 'light_red', 'chassisSymetrie', 'interiorWheelAxe', 'Plaques', 'Bouchon', 'driveMain', 'interiorDeco', 'frontLight', 'frontLightContour', 'frontLightBack', 'grille++', 'radiateur', 'wheel', 'wheel_j1', 'wheel_j2',//24 'sit', 'sit_j1', 'sit_j2', 'full', 'steering', 'steering_j1',//top 'door_l', 'door_l_j1', 'door_l_j2', 'door_l_glass',//31-34 'door_r', 'door_r_j1', 'door_r_j2', 'door_r_glass',//35-38 ]; this.mats = null; this.meshs = null; this.geos = null; this.Pool = null; this.timerTest = null; this.car = null; this.wheel = null; this.shape = null; this.cars = []; //this.load(); this.init(); } AAA.Vision.prototype = { constructor: AAA.Vision, /*load:function(){ var _this = this; this.Pool = new SEA3D.Pool('models/vision.sea', function() { _this.init() }); },*/ init:function(){ this.geos = []; for(var i=0;i<this.name.length;i++){ this.geos[i] = Pool.getGeometry('vision_' + this.name[i], 0.006); } this.construct(); }, construct:function(){ this.mats = []; this.mats[0] = new THREE.MeshBasicMaterial({ name:'wheelGumb', color:0x050505, reflectivity:0.1, envMap:View.sky, combine:THREE.MixOperation }); this.mats[1] = new THREE.MeshBasicMaterial({ name:'bodyWhite', color:0xeeeeee, reflectivity:0.3, envMap:View.sky, combine:THREE.MixOperation }); this.mats[2] = new THREE.MeshBasicMaterial({ name:'bodyBlack', color:0x373536, reflectivity:0.3, envMap:View.sky, combine:THREE.MixOperation }); this.mats[3] = new THREE.MeshBasicMaterial({ name:'chrome', color:0x909090, reflectivity:0.8, envMap:View.sky, combine:THREE.MixOperation}); this.mats[4] = new THREE.MeshBasicMaterial({ name:'glass', color:0x202020, reflectivity:0.8, envMap:View.sky, combine:THREE.MixOperation, transparent:true, opacity:0.3, side:THREE.DoubleSide}); this.mats[5] = new THREE.MeshBasicMaterial({ name:'lightBack', color: 0xFF0000, reflectivity:0.2, envMap:View.sky, combine:THREE.MixOperation, transparent:true, opacity:0.9}); this.mats[6] = new THREE.MeshBasicMaterial({ name:'lightFront', color:0xFFFFFF, reflectivity:0.2, envMap:View.sky, combine:THREE.MixOperation, transparent:true, opacity:0.9}); this.mats[7] = new THREE.MeshBasicMaterial({ name:'lightFront', color:0xFFFFFF, reflectivity:0.2, envMap:View.sky, combine:THREE.MixOperation, transparent:true, opacity:0.5}); this.meshs = []; var g = new THREE.Geometry(); g.merge(this.geos[0]); g.merge(this.geos[1]); g.merge(this.geos[2]); g.merge(this.geos[13]); this.meshs[0] = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(g), this.mats[1] ); g = new THREE.Geometry(); g.merge(this.geos[3]); g.merge(this.geos[9]); var meshGlass = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(g), this.mats[4] ); g = new THREE.Geometry(); g.merge(this.geos[5]); g.merge(this.geos[8]); g.merge(this.geos[11]); g.merge(this.geos[12]); g.merge(this.geos[15]); g.merge(this.geos[16]); g.merge(this.geos[19]); var meshBlack = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(g), this.mats[2] ); g = new THREE.Geometry(); g.merge(this.geos[7]); g.merge(this.geos[14]); g.merge(this.geos[20]); g.merge(this.geos[21]); var meshChrome = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(g), this.mats[3] ); var meshLightBack = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[10]), this.mats[5] ); var meshLightFront = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry( this.geos[17]), this.mats[6] ); var meshLightFront2 = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry( this.geos[18]), this.mats[7] ); this.meshs[0].add(meshBlack); this.meshs[0].add(meshGlass); this.meshs[0].add(meshChrome); this.meshs[0].add(meshLightBack); this.meshs[0].add(meshLightFront); this.meshs[0].add(meshLightFront2); // hood this.meshs[1] = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[6]), this.mats[1] ); // door L var dglass = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[34]), this.mats[4] ); var ddeco = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[32]), this.mats[1] ); var dcc = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[33]), this.mats[3] ); this.meshs[2] = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[31]), this.mats[2] ); this.meshs[2].add(dglass); this.meshs[2].add(ddeco); this.meshs[2].add(dcc); // door R dglass = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[38]), this.mats[4] ); ddeco = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[36]), this.mats[1] ); dcc = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[37]), this.mats[3] ); this.meshs[3] = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[35]), this.mats[2] ); this.meshs[3].add(dglass); this.meshs[3].add(ddeco); this.meshs[3].add(dcc); // sit var sit1 = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[26]), this.mats[1] ); var sit2 = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[27]), this.mats[2] ); var sit = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[25]), this.mats[3] ); sit.add(sit1); sit.add(sit2); this.meshs[4]= new THREE.Object3D(); var s; var spos = [0.4, 0, -0.75] for(var j = 0; j<4 ; j++){ s = sit.clone(); this.meshs[4].add(s); switch(j){ case 0: s.position.set(spos[0], 0, spos[1]); break; case 1: s.position.set(-spos[0], 0, spos[1]); break; case 2: s.position.set(spos[0], 0, spos[2]); break; case 3: s.position.set(-spos[0], 0, spos[2]); break; } } this.meshs[5]= new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[29]), this.mats[2] ); var mm= new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[30]), this.mats[4] ); this.meshs[5].add(mm); this.meshs[5].name = "steering"; this.car = new THREE.Object3D(); var i = this.meshs.length; var mesh; while(i--){ mesh = this.meshs[i]; this.car.add(mesh) if(mesh.name=='steering'){ mesh.position.set(0.42,0.75,0.6); mesh.rotation.set(20*AAA.ToRad,0,0*AAA.ToRad) } } // create wheel var j1 = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[23]), this.mats[1] ); var j2 = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[24]), this.mats[2] ); this.wheel = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[22]), this.mats[0] ); this.wheel.add(j1); this.wheel.add(j2); this.wheel.name = "wheel"; g = new THREE.Geometry(); g.merge(this.geos[28]); // g.applyMatrix( new THREE.Matrix4().makeRotationY( 180* (Math.PI / 180) ) ); this.shape = new THREE.Mesh( g ); //this.car.add(this.shape); this.name.length = 0; } }<file_sep>/demos/demo11.js CLEAR({broadphase:"BVT", timer:false, timestep:1/60, iteration:2, G:-10}); function initDemo() { NAME("Ragdoll"); // ground ADD({type:"ground", size:[100,5,100], pos:[0,-2.5,0]}); var Max = 20; var s = 0.2; var collision = true; var distribution = 1; var l = 0; var m = 0; var j = 0; var px,py,pz; var jtype = "hinge"; var spring = [2, 0.3, 0.1]; while (Max--){ l++; if(distribution===1){ px = -4.5+(l); py = 2; pz = -3.5+(m); if(l>7){m++; l=0} }else { px = 0; py = 2 + (Max*1.5); pz = 0; } ADD({type:"box", size:[0.2,0.1,0.15], pos:[px,py-0.2,pz], mass:s, name:'pelvis'+j }); ADD({type:"box", size:[0.2,0.1,0.15], pos:[px,py-0.1,pz], mass:s, name:'spine1_'+j }); ADD({type:"box", size:[0.2,0.1,0.15], pos:[px,py,pz], mass:s, name:'spine2_'+j }); ADD({type:"box", size:[0.2,0.1,0.15], pos:[px,py+0.1,pz], mass:s, name:'spine3_'+j }); ADD({type:"sphere", size:[0.1], pos:[px,py+0.3,pz], mass:s, name:'head'+j }); JOINT({type:jtype, body1:'pelvis'+j, body2:'spine1_'+j, pos1:[0,0.05,0], pos2:[0,-0.05,0], min:2, max:20, collision:collision, spring:spring}); JOINT({type:jtype, body1:'spine1_'+j, body2:'spine2_'+j, pos1:[0,0.05,0], pos2:[0,-0.05,0], min:2, max:20, collision:collision, spring:spring}); JOINT({type:jtype, body1:'spine2_'+j, body2:'spine3_'+j, pos1:[0,0.05,0], pos2:[0,-0.05,0], min:2, max:20, collision:collision, spring:spring}); JOINT({type:jtype, body1:'spine3_'+j, body2:'head'+j, pos1:[0,0.05,0], pos2:[0,-0.1,0], min:2, max:20, collision:collision, spring:spring}); // arm ADD({type:"box", size:[0.2,0.1,0.1], pos:[px-0.2,py+0.08,pz], rot:[0,0,20], mass:s, name:'L_arm'+j }); ADD({type:"box", size:[0.2,0.08,0.08], pos:[px-0.4,py,pz], rot:[0,0,20], mass:s, name:'LF_arm'+j }); ADD({type:"box", size:[0.2,0.1,0.1], pos:[px+0.2,py+0.08,pz], rot:[0,0,-20], mass:s, name:'R_arm'+j }); ADD({type:"box", size:[0.2,0.08,0.08], pos:[px+0.4,py,pz], rot:[0,0,-20], mass:s, name:'RF_arm'+j }); JOINT({type:jtype, body1:'spine3_'+j, body2:'L_arm'+j, pos1:[-0.1,0,0], pos2:[0.1,0,0], axe1:[0,1,1], axe2:[0,1,1], collision:collision}); JOINT({type:jtype, body1:'spine3_'+j, body2:'R_arm'+j, pos1:[0.1,0,0], pos2:[-0.1,0,0], axe1:[0,1,1], axe2:[0,1,1], collision:collision}); JOINT({type:jtype, body1:'L_arm'+j, body2:'LF_arm'+j, pos1:[-0.1,0,0], pos2:[0.1,0,0], axe1:[0,1,0], axe2:[0,1,0], collision:collision}); JOINT({type:jtype, body1:'R_arm'+j, body2:'RF_arm'+j, pos1:[0.1,0,0], pos2:[-0.1,0,0], axe1:[0,1,0], axe2:[0,1,0], collision:collision}); // leg ADD({type:"box", size:[0.1,0.2,0.1], pos:[px-0.06,py-0.4,pz], rot:[0,0,-20], mass:s, name:'L_leg'+j }); ADD({type:"box", size:[0.08,0.2,0.08], pos:[px-0.15,py-0.7,pz], rot:[0,0,-20], mass:s, name:'LF_leg'+j }); ADD({type:"box", size:[0.1,0.2,0.1], pos:[px+0.06,py-0.4,pz], rot:[0,0,20], mass:s, name:'R_leg'+j }); ADD({type:"box", size:[0.08,0.2,0.08], pos:[px+0.15,py-0.7,pz], rot:[0,0,20], mass:s, name:'RF_leg'+j }); JOINT({type:jtype, body1:'pelvis'+j, body2:'L_leg'+j, pos1:[-0.06,-0.05,0], pos2:[0,0.1,0], min:2, max:60, collision:collision}); JOINT({type:jtype, body1:'pelvis'+j, body2:'R_leg'+j, pos1:[0.06,-0.05,0], pos2:[0,0.1,0], min:2, max:60, collision:collision}); JOINT({type:jtype, body1:'L_leg'+j, body2:'LF_leg'+j, pos1:[0,-0.1,0], pos2:[0,0.1,0], axe1:[1,0,0], axe2:[1,0,0], min:2, max:60, collision:collision}); JOINT({type:jtype, body1:'R_leg'+j, body2:'RF_leg'+j, pos1:[0,-0.1,0], pos2:[0,0.1,0], axe1:[1,0,0], axe2:[1,0,0], min:2, max:60, collision:collision}); j+=11; } }<file_sep>/js/vehicle/C1gt.js /** _ _ _ * | |___| |_| |__ * | / _ \ _| | * |_\___/\__|_||_| * @author LoTh /http://3dflashlo.wordpress.com/ */ // GT-C1 <NAME> // 900 kg / 1600 cm3 / 125 chevaux // largeur 1.85m / hauteur 1.5m / longeur 3.44m AAA.ToRad = Math.PI / 180; AAA.C1gt = function(){ this.name = ['bottomCar', 'MotorAndBorder', 'doorGlassLeft', 'doorGlassRight', 'trunk', 'glass', 'hood', 'headLight', 'doorRight', 'doorLeft', 'interior', 'body', 'steeringWheel', 'wheel', 'shape']; this.c1gtMats = []; this.geos = []; this.meshs = null; this.textures = null; this.Pool = null; this.car = null; this.wheel = null; this.shape = null; //this.cars = []; //this.load(); this.init(); } AAA.C1gt.prototype = { constructor: AAA.C1gt, /*load:function(){ var _this = this; //if(this.isHighModel)this.Pool = new SEA3D.Pool('models/c1gt.high.sea', function() { _this.init() }); //else this.Pool = new SEA3D.Pool('models/c1gt.sea', function() { _this.init() }); },*/ init:function(){ var i = this.name.length; while(i--){ this.geos[i] = Pool.getGeometry('c1gt_' +this.name[i], 0.02); } console.log(this.geos.length) this.c1gtMats[0] = new THREE.MeshBasicMaterial({ name:'body', map:Pool.getTexture("body", true), reflectivity:0.6, envMap:View.sky, combine:THREE.MixOperation }); this.c1gtMats[1] = new THREE.MeshBasicMaterial({ name:'door', map:Pool.getTexture("bodydoor", true), reflectivity:0.6, envMap:View.sky, combine:THREE.MixOperation }); this.c1gtMats[2] = new THREE.MeshBasicMaterial({ name:'intern', map:Pool.getTexture("intern", true), reflectivity:0.3, envMap:View.sky, combine:THREE.MixOperation }); this.c1gtMats[3] = new THREE.MeshBasicMaterial({ name:'glass', map:Pool.getTexture("body", true), reflectivity:0.9, envMap:View.sky, combine:THREE.MixOperation, transparent:true, opacity:0.3, side:THREE.DoubleSide}); this.c1gtMats[4] = new THREE.MeshBasicMaterial({ name:'light', map:Pool.getTexture("light", true), reflectivity:0.3, envMap:View.sky, combine:THREE.MixOperation}); this.c1gtMats[5] = new THREE.MeshBasicMaterial({ name:'wheel', map:Pool.getTexture("wheels", true), reflectivity:0.2, envMap:View.sky, combine:THREE.MixOperation}); this.c1gtMats[6] = new THREE.MeshBasicMaterial({ name:'steering', color:0x333333, reflectivity:0.3, envMap:View.sky, combine:THREE.MixOperation}); this.c1gtMatLib = {}; this.meshs = []; var bodyGlass = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[5]), this.c1gtMats[3] ); var doorLGlass = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[2]), this.c1gtMats[3] ); var doorRGlass = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[3]), this.c1gtMats[3] ); var intern = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[10]), this.c1gtMats[2] ); var headlight = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[7]), this.c1gtMats[4] ); var geobody = new THREE.Geometry(); geobody.merge(this.geos[1]); geobody.merge(this.geos[0]); geobody.merge(this.geos[11]); this.meshs[0] = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(geobody), this.c1gtMats[0] ); this.meshs[0].add(bodyGlass); this.meshs[0].add(headlight); this.meshs[0].add(intern); this.meshs[0].name = "body"; this.meshs[1] = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[6]), this.c1gtMats[0] ); this.meshs[1].name = "hood"; this.meshs[2] = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[4]), this.c1gtMats[3] ); this.meshs[2].name = "trunk"; this.meshs[3] = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[9]), this.c1gtMats[1] ); this.meshs[3].add(doorLGlass); this.meshs[3].name = "doorL"; this.meshs[4] = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[8]), this.c1gtMats[1] ); this.meshs[4].add(doorRGlass); this.meshs[4].name = "doorR"; this.meshs[5] = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[12]), this.c1gtMats[6] ); this.meshs[5].name = "steering"; //this.steering = this.meshs[5]; //this.meshs[6] = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(new THREE.CubeGeometry( 1.8,1.465,3.44 )), this.c1gtMats[3] ); this.car = new THREE.Object3D(); i = this.meshs.length; var mesh; while(i--){ mesh = this.meshs[i]; this.car.add(mesh); mesh.castShadow = true; mesh.receiveShadow = true; if(mesh.name=='hood'){ mesh.position.set(0,0.2935*2,-0.55*2); mesh.rotation.set(0*AAA.ToRad,0,0) } if(mesh.name=='trunk'){ mesh.position.set(0,0.44225*2,0.595*2); mesh.rotation.set(-0*AAA.ToRad,0,0) } if(mesh.name=='doorL'){ mesh.position.set(-0.075*2,0.54225*2,-0.025*2); mesh.rotation.set(-5*AAA.ToRad,0,-0*AAA.ToRad) } if(mesh.name=='doorR'){ mesh.position.set(0.075*2,0.54225*2,-0.025*2); mesh.rotation.set(-5*AAA.ToRad,0,0*AAA.ToRad) } if(mesh.name=='steering'){ mesh.position.set(-0.40,0.58,-0.3*2); mesh.rotation.set(-20*AAA.ToRad,0,0*AAA.ToRad) } } //var w = this.geos[13]// this.wheel = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(this.geos[13]), this.c1gtMats[5] ); this.wheel.name = "wheel"; var g = new THREE.Geometry(); g.merge(this.geos[14]); g.applyMatrix( new THREE.Matrix4().makeRotationY( 180* (Math.PI / 180) ) ); this.shape = new THREE.Mesh( new THREE.BufferGeometry().fromGeometry(g) ); //this.car.add(this.shape); this.name.length = 0; } }<file_sep>/js/AAA.View.js /** _ _ _ * | |___| |_| |__ * | / _ \ _| | * |_\___/\__|_||_| * @author LoTh /http://3dflashlo.wordpress.com/ */ // THREE for ammo.js // use 1 three unit for 1 meter var AAA={ REVISION: 0.2 }; //----------------------------------------------------- // 3D VIEW //----------------------------------------------------- AAA.View = function(Themes){ this.container = null; this.renderer = null; this.scene = null; this.camera = null; this.center = null; this.content = null; this.clock = null; this.lights = null; this.fog = null; this.ground = null; this.postEffect = null; this.sky = null; this.sky2 = null; this.cars = []; this.objs = []; this.cam = { fov:50, horizontal: 90, vertical: 70, distance: 30, automove: false }; this.mouse = { ox:0, oy:0, h:0, v:0, rx:0, ry:0, dx:0, dy:0, down:false, moving:false, ray:false, direction:false }; this.viewSize = { w:window.innerWidth, h:window.innerHeight, mw:1, mh:1}; this.key = [0,0,0,0,0,0,0, 0]; this.themes = Themes || ['1d1f20', '2f3031', '424344', '68696b']; this.bgColor = parseInt("0x" + this.themes[0]); this.debugColor = parseInt("0x" + this.themes[2]); this.debugAlpha = 0.5; this.isShadow = false; this.isSketch = false; this.mats = []; this.geos = []; this.geoBasic = []; this.tt = [0 , 0]; // for draw sketch //this.tx01 = THREE.ImageUtils.loadTexture('images/sketch/noise.png'); //this.tx02 = THREE.ImageUtils.loadTexture('images/sketch/paper.jpg'); //this.tx01 = null; //this.tx02 = null; this.init(); } AAA.View.prototype = { constructor: AAA.View, init:function(){ this.container = document.getElementById("container"); this.renderer = new THREE.WebGLRenderer( {precision: "lowp", antialias: false, alpha:false } ); this.renderer.setSize( this.viewSize.w, this.viewSize.h ); this.renderer.setClearColor( this.bgColor, 1 ); //this.renderer.autoClearColor = false; //this.renderer.autoClear = false; //this.renderer.sortObjects = false; //this.renderer.autoClear = false; //this.renderer.autoClearStencil = false; //this.renderer.gammaInput = true; //this.renderer.gammaOutput = true; this.renderer.shadowMapEnabled = this.isShadow; //this.renderer.shadowMapCullFace = THREE.CullFaceBack; //this.renderer.shadowMapType = THREE.BasicShadowMap; //this.container.appendChild( this.renderer.domElement ); this.scene = new THREE.Scene(); //this.scene.fog = new THREE.FogExp2( this.bgColor, 0.0025 ); this.fog = new THREE.Fog( this.bgColor, 10, 100 ); this.scene.fog = this.fog; this.camera = new THREE.PerspectiveCamera( this.cam.fov, this.viewSize.w / this.viewSize.h, 0.1, 200 ); this.center = new THREE.Vector3(); this.moveCamera(); this.scene.add( this.camera ); this.content = new THREE.Object3D(); this.scene.add(this.content); this.clock = new THREE.Clock(); this.delta = 0; if(this.isShadow){ var light = new THREE.DirectionalLight( 0xffffff, 2 ); light.position.set( 10, 30, 5 ); light.target.position.set( 0, 0, 0 ); light.castShadow = this.isShadow; light.onlyShadow = true; light.shadowDarkness = 0.7; light.shadowBias = -0.00002; light.shadowMapWidth = 1024; light.shadowMapHeight = 1024; light.shadowCameraNear = 10; light.shadowCameraFar = 40; //light.shadowCameraVisible = true; var d = 20; light.shadowCameraLeft = -d; light.shadowCameraRight = d; light.shadowCameraTop = d; light.shadowCameraBottom = -d; this.scene.add(light); } /*this.lights = []; this.lights[0] = new THREE.AmbientLight( this.bgColor ); this.lights[1] = new THREE.DirectionalLight( 0xffffff, 2 ); this.lights[1].position.set( 100, 300, 50 ); this.lights[1].castShadow = this.isShadow; this.lights[1].shadowMapWidth = this.lights[1].shadowMapHeight = 512; this.lights[2] = new THREE.PointLight( 0xAACCff, 3); this.lights[2].position.set(0, 0, 0); var i = this.lights.length; while(i--){ this.scene.add(this.lights[i]); }*/ var groundMat = new THREE.MeshBasicMaterial( { color: this.bgColor, transparent:true, opacity:this.debugAlpha } ); var groundGeo = new THREE.PlaneBufferGeometry( 1, 1 );//new THREE.BufferGeometry().fromGeometry( new THREE.PlaneGeometry( 1, 1 ) ); groundGeo.applyMatrix(new THREE.Matrix4().makeRotationX(-Math.PI / 2)); this.ground = new THREE.Mesh( groundGeo, groundMat ); this.ground.position.y = -0.1 this.ground.castShadow = false; this.ground.receiveShadow = true; this.scene.add( this.ground ); var body = document.body; var _this = this; window.addEventListener( 'resize', function(e) { _this.resize() }, false ); this.container.addEventListener( 'mousemove', function(e) { _this.onMouseMove(e) }, false ); this.container.addEventListener( 'mousedown', function(e) { _this.onMouseDown(e) }, false ); this.container.addEventListener( 'mouseout', function(e) { _this.onMouseUp(e) }, false ); this.container.addEventListener( 'mouseup', function(e) { _this.onMouseUp(e); if(Editor.getOpen())Editor.close(); }, false ); document.addEventListener( 'keydown', function(e) { _this.onKeyDown(e) }, false ); document.addEventListener( 'keyup', function(e) { _this.onKeyUp(e) }, false ); if( body.addEventListener ){ body.addEventListener( 'mousewheel', function(e) { _this.onMouseWheel(e) }, false ); //chrome body.addEventListener( 'DOMMouseScroll', function(e) { _this.onMouseWheel(e) }, false ); // firefox }else if( body.attachEvent ){ body.attachEvent("onmousewheel" , function(e) { _this.onMouseWheel(e) }); // ie } this.initBasicMaterial(); this.initBasicGeometry(); //this.render(); }, sketchMode:function(){ if(this.isSketch){ this.renderer.setClearColor( this.bgColor, 1); this.ground.material.color.setHex( this.bgColor ); this.fog.color.setHex( this.bgColor ); this.postEffect.clear(); this.isSketch = false; } else{ this.renderer.setClearColor(0xffffff, 1); this.ground.material.color.setHex( 0xffffff ); this.fog.color.setHex( 0xffffff ); this.postEffect = new AAA.PostEffect(this); //this.postEffect = new AAA.PostEffect(); this.postEffect.init(); this.isSketch = true; } }, initBasicMaterial:function(){ this.debugMaterial = new THREE.MeshBasicMaterial( { color:this.debugColor, wireframe:true, transparent:true, opacity:0, fog: false, depthTest: false, depthWrite: false}); this.mats[0] = new THREE.MeshBasicMaterial({ color: 0x101010 }); this.mats[1] = new THREE.MeshBasicMaterial({ color: 0xFFEEEE, name:"actif" }); this.mats[2] = new THREE.MeshBasicMaterial({ color: 0x101030, name:"static" }); }, initBasicGeometry:function(){ this.geoBasic[0] = new THREE.BufferGeometry().fromGeometry(new THREE.BoxGeometry( 1, 1, 1 )) this.geoBasic[1] = new THREE.BufferGeometry().fromGeometry(new THREE.SphereGeometry( 1, 20, 16 )); this.geoBasic[2] = new THREE.BufferGeometry().fromGeometry(new THREE.CylinderGeometry( 0, 1, 1, 20, 1 ));//cone }, initSky:function(envtexture, texture){ this.sky = envtexture this.sky2 = envtexture var i = this.mats.length; while (i--) { this.mats[i].envMap = this.sky; this.mats[i].reflectivity = 0.8; this.mats[i].combine = THREE.MixOperation; } // test spherical shader /*var SphShader = AAA.SEM; SphShader.uniforms[ "tMatCap" ].value = texture; this.mats[3] = new THREE.ShaderMaterial( { uniforms:SphShader.uniforms, vertexShader: SphShader.vertexShader, fragmentShader:SphShader.fragmentShader, shading: THREE.SmoothShading }); this.mats[4] = new THREE.ShaderMaterial( { uniforms:SphShader.uniforms, vertexShader: SphShader.vertexShader, fragmentShader:SphShader.fragmentShader, shading: THREE.SmoothShading });*/ }, updateSky:function(envtexture){ // this.sky2 = envtexture.clone(); // this.sky = envtexture.clone(); }, render:function(){ this.delta = this.clock.getDelta().toFixed(3); //this.key[7] = this.delta; //this.renderer.clear(); //this.renderer.render( this.scene, this.camera ); if( terrain.mesh != null ){ if(terrain.isAutoMove) terrain.update(this.delta); if(terrain.isMove){ terrain.easing(this.key, 90-this.cam.horizontal, 1); this.follow(new THREE.Vector3( 0, terrain.getZ(0,0)+1, 0 )); if(this.cars.length > 0)terrain.isMove = false; } } if(this.isSketch) this.postEffect.render(); else this.renderer.render( this.scene, this.camera ); var last = Date.now(); if (last - 1000 > this.tt[0]) { this.tt[0] = last; this.fps = this.tt[1]; this.tt[1] = 0; } this.tt[1]++; }, resize:function(){ this.viewSize.w = window.innerWidth; this.viewSize.h = window.innerHeight; this.renderer.setSize( this.viewSize.w*this.viewSize.mw, this.viewSize.h*this.viewSize.mh ); this.camera.aspect = ( this.viewSize.w*this.viewSize.mw ) / ( this.viewSize.h*this.viewSize.mh ); this.camera.updateProjectionMatrix(); if(this.isSketch) this.postEffect.resize(); }, clearAll:function (){ if(terrain.mesh!== null){ terrain.clear(); } var i = this.content.children.length; while (i--) { this.content.remove(this.content.children[ i ]); } this.cars.length = 0; this.objs.length = 0; this.ground.visible = false; this.center.set(0,0,0); this.moveCamera(); this.key[6] = 0; this.key[7] = 0; }, moveCamera:function(){ this.camera.position.copy(AAA.Orbit(this.center, this.cam.horizontal, this.cam.vertical, this.cam.distance)); this.camera.lookAt(this.center); }, follow:function(vec){ this.center.copy(vec); this.moveCamera(); }, onMouseDown:function(e){ e.preventDefault(); this.mouse.ox = e.clientX; this.mouse.oy = e.clientY; this.mouse.h = this.cam.horizontal; this.mouse.v = this.cam.vertical; this.mouse.down = true; }, onMouseUp:function(e){ this.mouse.down = false; document.body.style.cursor = 'auto'; }, onMouseMove:function(e){ e.preventDefault(); if( this.mouse.ray ){ this.mouse.rx = ( e.clientX / this.viewSize.w ) * 2 - 1; this.mouse.ry = -( e.clientY / this.viewSize.h ) * 2 + 1; //this.rayTest(); } if( this.mouse.down ) { document.body.style.cursor = 'move'; this.cam.horizontal = ((e.clientX - this.mouse.ox) * 0.3) + this.mouse.h; this.cam.vertical = (-(e.clientY - this.mouse.oy) * 0.3) + this.mouse.v; this.moveCamera(); } if(this.mouse.direction){ this.mouse.dx = (e.clientX - this.viewSize.w*0.5); this.mouse.dy = (e.clientX - this.viewSize.h*0.5); } }, onMouseWheel:function(e){ e.preventDefault(); var delta = 0; if(e.wheelDelta){delta=e.wheelDelta*-1;} else if(e.detail){delta=e.detail*20;} this.cam.distance+=(delta/100); if(this.cam.distance<0.01)this.cam.distance = 0.01; if(this.cam.distance>50)this.cam.distance = 50; this.moveCamera(); }, addCar:function(obj){ this.cars[this.cars.length] = new AAA.Car(obj, this); }, addObj:function(obj){ this.objs[this.objs.length] = new AAA.Obj(obj, this); }, getVertex:function(name, size, directGeo) { var v = [], n; var pp, i; var isB = false; if(name!=="") pp = this.getGeoByName(name).vertices; else if(directGeo) pp = directGeo.vertices; if(pp == undefined ){//is buffer if(name!=="") pp = this.getGeoByName(name).attributes.position.array; else if(directGeo) pp = directGeo.attributes.position.array; isB = true; i = pp.length/3; } else { i = pp.length } while(i--){ n = i*3; if(isB){// buffer geometry v[n+0]=pp[n+0]*size[0]; v[n+1]=pp[n+1]*size[1]; v[n+2]=pp[n+2]*size[2]; }else{ v[n+0]=pp[i].x*size[0]; v[n+1]=pp[i].y*size[1]; v[n+2]=pp[i].z*size[2]; } } return v; }, getFaces:function(name, size, directGeo) { var v = [], n, face, va, vb, vc; var geo; if(name !== "") geo = this.getGeoByName(name); else if(directGeo) geo = directGeo; var pp = geo.faces; var pv = geo.vertices; var i = pp.length; while(i--){ n = i*9; face = pp[i]; va = pv[face.a]; vb = pv[face.b]; vc = pv[face.c]; v[n+0]=va.x*size[0]; v[n+1]=va.y*size[1]; v[n+2]=va.z*size[2]; v[n+3]=vb.x*size[0]; v[n+4]=vb.y*size[1]; v[n+5]=vb.z*size[2]; v[n+6]=vc.x*size[0]; v[n+7]=vc.y*size[1]; v[n+8]=vc.z*size[2]; } return v; }, getGeoByName:function(name, Buffer) { var g; var i = this.geos.length; var buffer = Buffer || false; while(i--){ if(name==this.geos[i].name) g=this.geos[i]; } if(buffer) g = new THREE.BufferGeometry().fromGeometry(g); return g }, onKeyDown:function( e ) { var key = this.key; switch ( e.keyCode ) { case 38: case 87: case 90: key[0]=1; break; // up, W, Z case 40: case 83: key[1]=1; break; // down, S case 37: case 65: case 81: key[2]=1; break; // left, A, Q case 39: case 68: key[3]=1; break; // right, D case 17: case 67: key[4]=1; break; // ctrl, c case 32: key[5]=1; break; // space case 96:case 48: key[6]=0; break; //0 case 97:case 49: key[6]=1; break; //1 case 98:case 50: key[6]=2; break; //2 case 99:case 51: key[6]=3; break; //3 case 100:case 52: key[6]=4; break; //4 case 101:case 53: key[6]=5; break; //5 case 102:case 54: key[6]=6; break; //6 case 103:case 55: key[6]=7; break; //7 case 104:case 56: key[6]=8; break; //8 case 105:case 57: key[6]=9; break; //9 } KEY(key); }, onKeyUp:function( e ) { var key = this.key; switch( e.keyCode ) { case 38: case 87: case 90: key[0]=0; break; // up, W, Z case 40: case 83: key[1]=0; break; // down, S case 37: case 65: case 81: key[2]=0; break; // left, A, Q case 39: case 68: key[3]=0; break; // right, D case 17: case 67: key[4]=0; break; // ctrl, c case 32: key[5]=0; break; // space } KEY(key); } } //----------------------------------------------------- // MATH //----------------------------------------------------- AAA.ToRad = Math.PI / 180; AAA.Orbit = function(origine, horizontal, vertical, distance) { var p = new THREE.Vector3(); var phi = vertical*AAA.ToRad; var theta = horizontal*AAA.ToRad; p.x = (distance * Math.sin(phi) * Math.cos(theta)) + origine.x; p.z = (distance * Math.sin(phi) * Math.sin(theta)) + origine.z; p.y = (distance * Math.cos(phi)) + origine.y; return p; } //----------------------------------------------------- // AAA OBJECT //----------------------------------------------------- AAA.Obj = function(obj, Parent){ this.parent = Parent; var size = obj.size || [1,1,1]; var div = obj.div || [64,64]; var pos = obj.pos || [0,0,0]; var mesh, helper; var shadow = true; switch(obj.type){ case 'plane': mesh = new THREE.Object3D(); break; case 'boxbasic': case 'ground': mesh=new THREE.Mesh(this.parent.geoBasic[0], this.parent.debugMaterial); mesh.scale.set( size[0], size[1], size[2]); var helper = new THREE.BoxHelper(mesh); helper.material.color.set( this.parent.debugColor ); helper.material.opacity = this.parent.debugAlpha; helper.material.transparent = true; mesh.add( helper ); shadow = false; break; case 'box': mesh = new THREE.Mesh( this.parent.getGeoByName("box", true), this.parent.mats[1] ); mesh.scale.set( size[0], size[1], size[2] ); break; case 'sphere': mesh = new THREE.Mesh( this.parent.geoBasic[1], this.parent.mats[1] ); mesh.scale.set( size[0], size[0], size[0] ); break; case 'cylinder': mesh = new THREE.Mesh( this.parent.getGeoByName("cyl", true), this.parent.mats[1] ); mesh.scale.set( size[0], size[1], size[2] ); break; case 'dice': mesh = new THREE.Mesh( this.parent.getGeoByName("dice", true), this.parent.mats[1] ); mesh.scale.set( size[0], size[1], size[2] ); break; case 'cone': mesh = new THREE.Mesh( this.parent.geoBasic[2], this.parent.mats[1] ); mesh.scale.set( size[0], size[1]*0.5, size[0] ); break; case 'capsule': mesh = new THREE.Mesh( new AAA.CapsuleGeometry(size[0], size[1]*0.5), this.parent.mats[1] ); break; case 'mesh': mesh = new THREE.Mesh( this.parent.getGeoByName(obj.name, true), this.parent.mats[1] ); mesh.scale.set( size[0], size[1], size[2] ); break; case 'convex': mesh = new THREE.Mesh(this.parent.getGeoByName(obj.name, true), this.parent.mats[1] ); mesh.scale.set( size[0], size[1], size[2] ); break; case 'terrain': terrain.init( obj );//new TERRAIN.Generate( obj, this.parent ); //this.parent.terrain.init( window.innerWidth, window.innerHeight ); //this.parent.terrain.anim();// active morph mesh = terrain.container; shadow = false; break; } if(shadow){ mesh.castShadow = true; mesh.receiveShadow = true; } if(obj.type == 'ground'){// ground shadow this.parent.ground.visible = true; this.parent.ground.scale.set( size[0], 1, size[2] ); this.parent.ground.position.set( pos[0], pos[1]+(size[1]*0.5), pos[2]); if(obj.rot)this.parent.ground.rotation.set( (obj.rot[0])*AAA.ToRad, obj.rot[1]*AAA.ToRad, obj.rot[2]*AAA.ToRad ); else this.parent.ground.rotation.set(0,0,0); } this.parent.content.add(mesh); // out of view range mesh.position.y = 20000; this.mesh = mesh; } AAA.Obj.prototype = { constructor: AAA.Obj, update:function(id){ var n = id * 8; var mesh = this.mesh; if(mtx[n+0]==2){ if(mesh.material) if(mesh.material.name=="actif") mesh.material = this.parent.mats[2]; } else { if(mesh.material) if(mesh.material.name=="static") mesh.material = this.parent.mats[1]; mesh.quaternion.set( mtx[n+1], mtx[n+2], mtx[n+3], mtx[n+4] ); mesh.position.set( mtx[n+5], mtx[n+6], mtx[n+7] ); } } } AAA.CapsuleGeometry = function(radius, height, SRadius, SHeight) { var sRadius = SRadius || 20; var sHeight = SHeight || 10; var o0 = Math.PI*2; var o1 = Math.PI/2 var g = new THREE.Geometry(); var m0 = new THREE.CylinderGeometry(radius, radius, height, sRadius, 1, true); var m1 = new THREE.SphereGeometry(radius, sRadius, sHeight, 0, o0, 0, o1); var m2 = new THREE.SphereGeometry(radius, sRadius, sHeight, 0, o0, o1, o1); var mtx0 = new THREE.Matrix4().makeTranslation(0, 0,0); var mtx1 = new THREE.Matrix4().makeTranslation(0, height*0.5,0); var mtx2 = new THREE.Matrix4().makeTranslation(0, -height*0.5,0); g.merge( m0, mtx0); g.merge( m1, mtx1); g.merge( m2, mtx2); return new THREE.BufferGeometry().fromGeometry(g); } //----------------------------------------------------- // AAA JOINT //----------------------------------------------------- AAA.Joint = function(obj, Parent){ } AAA.Joint.prototype = { constructor: AAA.Joint } //----------------------------------------------------- // AAA VEHICLE //----------------------------------------------------- AAA.Car = function(obj, Parent){ this.parent = Parent; this.speed = 0; var size = obj.size || [2,0.5,5]; var wPos = obj.wPos || [1,0,2]; var wRadius = obj.wRadius || 0.4; var wDeepth = obj.wDeepth || 0.3; var nWheels = obj.nWheels || 4; var massCenter = obj.massCenter || [0,0,0]; var shape = null; this.type = obj.type || 'basic'; this.steering = null; this.nWheels = nWheels; var wheelMesh; this.driverPos = new THREE.Object3D(); switch(this.type){ case 'basic': this.mesh = new THREE.Mesh( this.parent.getGeoByName("box", true), this.parent.mats[1] ) || obj.mesh; this.mesh.scale.set( size[0], size[1], size[2] ); wheelMesh = new THREE.Mesh( this.parent.getGeoByName("cyl", true), this.parent.mats[2] ) || obj.wheel; wheelMesh.scale.set( wRadius, wDeepth, wRadius ); break; case 'c1gt': this.mesh= new THREE.Object3D(); var c = c1gt.car.clone(); c.rotation.y = 180*AAA.ToRad; this.mesh.add(c); shape = c1gt.shape; /*shape.geometry.computeBoundingBox(); var bBox = shape.geometry.boundingBox; var y0 = bBox.min.y//y[ 0 ]; var y1 = bBox.max.y//.y[ 1 ]; var bHeight = ( y0 > y1 ) ? y0 - y1 : y1 - y0;*/ var centroidY = -0.23;//-(y0 + ( bHeight *0.5 ))+ 0.226//shape.position.y; //var minY = Math.min (minY, bBox.min.y); // console.log(bHeight, centroidY, shape.position.y) //var d = shape.clone() // this.mesh.add(d); //d.position.y = centroidY; c.position.y = centroidY; this.steering = c.children[0]; wheelMesh = c1gt.wheel; wRadius = 0.34; wDeepth = 0.26; size = [1.85,0.5,3.44];//1.465 wPos = [0.79,centroidY,1.2]; massCenter = [0,centroidY,0]; this.driverPos.position.set(0.40, 0.9+centroidY, -0.2); break; case 'vision': this.mesh= new THREE.Object3D(); var c = vision.car.clone(); this.mesh.add(c); shape = vision.shape; var centroidY = -0.326; c.position.y = centroidY; this.steering = c.children[0]; wheelMesh = vision.wheel; wRadius = 0.38; wDeepth = 0.26; size = [1.9,0.5,4.6];//1.24 wPos = [0.85,0,1.42]; massCenter = [0,centroidY,0]; this.driverPos.position.set(0.42, 0.75, 0); break; } this.mesh.position.y = 20000; this.mesh.add(this.driverPos); //this.mesh.castShadow = true; //this.mesh.receiveShadow = true; this.wheels = []; var i = this.nWheels, w; while(i--){ this.wheels[i] = new THREE.Object3D(); w = wheelMesh.clone(); w.castShadow = true; w.receiveShadow = true; if(this.type=='basic'){ w.rotation.z = -Math.PI / 2; }else if(this.type=='c1gt'){ if(i==0 || i==3) w.rotation.z = 180*AAA.ToRad; }else if(this.type=='vision'){ if(i==1 || i==2) w.rotation.z = 180*AAA.ToRad; } this.wheels[i].add(w); this.parent.content.add(this.wheels[i]); // out of view range this.wheels[i].position.y = 20000; } this.parent.content.add(this.mesh); // out of view range //this.mesh.position.y = 20000; obj.size = size; obj.wPos = wPos; obj.wRadius = wRadius; obj.wDeepth = wDeepth; obj.nWheels = nWheels; obj.massCenter = massCenter; if(shape!==null) obj.v = View.getVertex("", [1,1,1], shape.geometry ); } AAA.Car.prototype = { constructor: AAA.Car, update:function(id){ var m = mtxCar; var n = id * 40; this.speed = m[n+0]; this.mesh.position.set( m[n+5], m[n+6], m[n+7] ); this.mesh.quaternion.set( m[n+1], m[n+2], m[n+3], m[n+4] ); if(id == this.parent.key[6]){ this.steering.rotation.z = m[n+8]*6; this.mesh.updateMatrixWorld(); var pos = new THREE.Vector3(); pos.setFromMatrixPosition( this.driverPos.matrixWorld ); this.parent.follow(pos); } var i = this.nWheels, wm, w; while(i--){ w = 8*(i+1); wm = this.wheels[i]; wm.position.set( m[n+w+5], m[n+w+6], m[n+w+7] ); wm.quaternion.set( m[n+w+1], m[n+w+2], m[n+w+3], m[n+w+4] ); } } } //----------------------------------------------------- // POST EFFECT SKETCH //----------------------------------------------------- AAA.PostEffect = function(){ //this.parent = Parent; this.composer = null; this.colorBuffer = null; this.blurBuffer = null; this.renderPass = null; this.shader = null; this.pass = null; this.parameters={minFilter:THREE.LinearFilter, magFilter:THREE.LinearFilter, format:THREE.RGBFormat, stencilBuffer:false}; } AAA.PostEffect.prototype = { constructor: AAA.PostEffect, init:function(){ this.colorBuffer=new THREE.WebGLRenderTarget(1,1,this.parameters); //this.blurBuffer=new THREE.WebGLRenderTarget(1,1,parameters); this.composer= new THREE.EffectComposer(View.renderer); this.renderPass = new THREE.RenderPass(View.scene, View.camera ); this.composer.addPass( this.renderPass ); this.shader={ uniforms:{ tDiffuse:{type:'t',value:null}, tColor:{ type:'t',value:null}, tBlur:{type:'t',value:null}, tNoise:{type:'t',value:Pool.getTexture("noise")}, tPaper:{type:'t',value:Pool.getTexture("paper")}, resolution:{ type:'v2',value:new THREE.Vector2(1,1)} }, vertexShader:vs_render, fragmentShader:fs_render } this.pass = new THREE.ShaderPass(this.shader); this.pass.renderToScreen=true; this.composer.addPass(this.pass); this.pass.uniforms.tNoise.value.needsUpdate=true; this.pass.uniforms.tPaper.value.needsUpdate=true; this.resize(); }, render:function(){ if(this.pass && this.composer){ //View.renderer.clear(); View.renderer.render(View.scene, View.camera, this.colorBuffer, false); this.pass.uniforms.tColor.value=this.colorBuffer; this.composer.render(); } }, resize:function(){ var w = View.viewSize.w* View.viewSize.mw; var h = View.viewSize.h* View.viewSize.mh; this.composer.setSize(w,h); this.pass.uniforms.resolution.value.set(w,h); //this.pass.uniforms.tNoise.value.needsUpdate=true; //this.pass.uniforms.tPaper.value.needsUpdate=true; this.colorBuffer=new THREE.WebGLRenderTarget(w,h,this.parameters); }, clear:function(){ this.composer = null; this.colorBuffer = null; this.blurBuffer = null; this.renderPass = null; this.shader = null; this.pass = null; } } /* AAA.PostEffect = function(Parent){ this.parent = Parent; this.composer = null; this.colorBuffer = null; this.blurBuffer = null; this.renderPass = null; this.shader = null; this.pass = null; this.parameters={minFilter:THREE.LinearFilter, magFilter:THREE.LinearFilter, format:THREE.RGBFormat, stencilBuffer:false}; } AAA.PostEffect.prototype = { constructor: AAA.PostEffect, init:function(){ this.colorBuffer=new THREE.WebGLRenderTarget(1,1,this.parameters); //this.blurBuffer=new THREE.WebGLRenderTarget(1,1,parameters); this.composer= new THREE.EffectComposer(this.parent.renderer); this.renderPass = new THREE.RenderPass( this.parent.scene, this.parent.camera ); this.composer.addPass( this.renderPass ); this.shader={ uniforms:{ tDiffuse:{type:'t',value:null}, tColor:{ type:'t',value:null}, tBlur:{type:'t',value:null}, tNoise:{type:'t',value:this.parent.tx01}, tPaper:{type:'t',value:this.parent.tx02}, resolution:{ type:'v2',value:new THREE.Vector2(1,1)} }, vertexShader:vs_render, fragmentShader:fs_render } this.pass=new THREE.ShaderPass(this.shader); this.pass.renderToScreen=true; this.composer.addPass(this.pass); this.pass.uniforms.tNoise.value.needsUpdate=true; this.pass.uniforms.tPaper.value.needsUpdate=true; this.resize(); }, render:function(){ if(this.pass && this.composer){ this.parent.renderer.render(this.parent.scene, this.parent.camera, this.colorBuffer); this.pass.uniforms.tColor.value=this.colorBuffer; this.composer.render(); } }, resize:function(){ var w = this.parent.viewSize.w* this.parent.viewSize.mw; var h = this.parent.viewSize.h* this.parent.viewSize.mh; this.composer.setSize(w,h); this.pass.uniforms.resolution.value.set(w,h); this.colorBuffer=new THREE.WebGLRenderTarget(w,h,this.parameters); }, clear:function(){ this.composer = null; this.colorBuffer = null; this.blurBuffer = null; this.renderPass = null; this.shader = null; this.pass = null; } } */ /* AAA.AREA = { uniforms: { "tMatCap": { type: "t", value: null } }, vertexShader: [ "#define NVERTS 4", "varying vec3 vNormal;", "varying vec3 vViewPosition;", "void main() {", "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );", "vNormal = normalize( normalMatrix * normal );", "vViewPosition = -mvPosition.xyz;", "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", "}" ].join("\n"), fragmentShader: [ "#define NVERTS 4", "uniform vec3 color;", "uniform vec3 lightColor;", "uniform float lightIntensity;", "uniform vec3 lightverts[ NVERTS ];", "uniform mat4 lightMatrixWorld;", "varying vec3 vNormal;", "varying vec3 vViewPosition;", "void main() {", "vec3 normal = normalize( vNormal );", "vec4 lPosition[ NVERTS ];", "vec3 lVector[ NVERTS ];", "// stub in some ambient reflectance", "vec3 ambient = color * vec3( 0.2 );", "// direction vectors from point to area light corners", "for( int i = 0; i < NVERTS; i ++ ) {", "lPosition[ i ] = viewMatrix * lightMatrixWorld * vec4( lightverts[ i ], 1.0 );", "lVector[ i ] = normalize( lPosition[ i ].xyz + vViewPosition.xyz );", "}", "// bail if the point is on the wrong side of the light... there must be a better way...", "float tmp = dot( lVector[ 0 ], cross( ( lPosition[ 2 ] - lPosition[ 0 ] ).xyz, ( lPosition[ 1 ] - lPosition[ 0 ] ).xyz ) );", "if ( tmp > 0.0 ) {", "gl_FragColor = vec4( ambient, 1.0 );", "return;", "}", "// vector irradiance at point", "vec3 lightVec = vec3( 0.0 );", "for( int i = 0; i < NVERTS; i ++ ) {", "vec3 v0 = lVector[ i ];", "vec3 v1 = lVector[ int( mod( float( i + 1 ), float( NVERTS ) ) ) ];", "lightVec += acos( dot( v0, v1 ) ) * normalize( cross( v0, v1 ) );", "}", "// irradiance factor at point", "float factor = max( dot( lightVec, normal ), 0.0 ) / ( 2.0 * 3.14159265 );", "// frag color", "vec3 diffuse = color * lightColor * lightIntensity * factor;", "gl_FragColor = vec4( ambient + diffuse, 1.0 );", "}" ].join("\n") }; */ //----------------------------------------------------- // SPHERICAL SHADER //----------------------------------------------------- /* AAA.SEM = { uniforms: { "tMatCap": { type: "t", value: null } }, vertexShader: [ "varying vec2 vN;", "void main() {", "vec3 e = normalize( vec3( modelViewMatrix * vec4( position, 1.0 ) ) );", "vec3 n = normalize( normalMatrix * normal );", "vec3 r = reflect( e, n );", "float m = 2. * sqrt( pow( r.x, 2. ) + pow( r.y, 2. ) + pow( r.z + 1., 2. ) );", "vN = r.xy / m + .5;", "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1. );", "}" ].join("\n"), fragmentShader: [ "uniform sampler2D tMatCap;", "varying vec2 vN;", "void main() {", "vec3 base = texture2D( tMatCap, vN ).rgb;", "gl_FragColor = vec4( base, 1. );", "}" ].join("\n") }; AAA.SEM2 = { uniforms: { "tMatCap": { type: "t", value: null } }, vertexShader: [ "varying vec3 e;", "varying vec3 n;", "void main() {", "e = normalize( vec3( modelViewMatrix * vec4( position, 1.0 ) ) );", "n = normalize( normalMatrix * normal );", "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1. );", "}" ].join("\n"), fragmentShader: [ "uniform sampler2D tMatCap;", "varying vec3 e;", "varying vec3 n;", "void main() {", "vec3 r = reflect( e, n );", "//r = e - 2. * dot( n, e ) * n;", "float m = 2. * sqrt( pow( r.x, 2. ) + pow( r.y, 2. ) + pow( r.z + 1., 2. ) );", "vec2 vN = r.xy / m + .5;", "vec3 base = texture2D( tMatCap, vN ).rgb;", "gl_FragColor = vec4( base, 1. );", "}" ].join("\n") }; */
0a91106f77149d40ad8b2b3fe6194c11c318cfe4
[ "JavaScript", "Markdown" ]
14
JavaScript
mcanthony/Ammo.lab
24246f9864a3b1e5551fe458b2cc46425eb00889
2d59d7343594a9219652ecc7db68f8f74fd08f08
refs/heads/master
<file_sep>package Maekawa; public class CriticalSectionViolationException extends Exception { private static final long serialVersionUID = -5797829304832596538L; } <file_sep>package Maekawa; import java.io.Serializable; public class ScalarClock implements Serializable, Comparable<ScalarClock>, Cloneable{ long clock; private static final long serialVersionUID = -4287341249778633207L; public ScalarClock() { super(); // this.clock = 0; } public long value() { return clock; } public void setClock(long clock) { this.clock = clock; } public void tick() { this.clock++; } public void mergeClock(ScalarClock another_clock) { if(this.clock < another_clock.value()) { this.setClock(another_clock.value()); } this.tick(); } @Override public int compareTo(ScalarClock that) { // TODO Auto-generated method stub if(this.clock > that.clock) return 1; else if(this.clock < that.clock) return -1; else return 0; } public ScalarClock clone() { ScalarClock clk = new ScalarClock(); clk.setClock(this.clock); return clk; } } <file_sep>package Maekawa; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.junit.Test; public class TestContentionWithFailure extends StandardTestConfiguration { public TestContentionWithFailure() { super(); } @Test // When a service is in critical section and a low priority process tries to // lock, it should receive a failed message from the locked node public void runTestcsEnter2PriorityBlockingAndFailed() throws InterruptedException, IOException, NeighborNotFoundExeption { Thread block = new Thread(() -> { try { services[0].csEnter(); services[1].csEnter(); } catch (InterruptedException | IOException e) { e.printStackTrace(); } }); block.start(); Thread.sleep(100); // The request queue is of size 2 assertEquals(services[1].requestMessageQueue.size(), 2); // The request queue has own request at index 1 assertEquals(services[1].requestMessageQueue.get(1).getSenderID(), 1); // Node-0 has sent failed messages as it is inside critical section assertEquals(services[1].failedSet.contains(configs[1].getNode().getNeighborById(0)), true); // block.interrupt(); services[0].csLeave(); services[0].csLeave(); } } <file_sep>package Maekawa; import java.io.EOFException; import java.io.IOException; import java.io.ObjectInputStream; import java.net.SocketException; public class NeighborMonitor extends Thread implements Runnable{ Neighbor neighbor; Service service; boolean runflag; public NeighborMonitor(Neighbor neighbor, Service service) { this.neighbor = neighbor; this.service = service; this.setDaemon(true); } public void run() { runflag=true; ObjectInputStream ois = neighbor.getInputObjectStream(); try { while(runflag) { Message message = null; try { message = (Message) ois.readObject(); }catch(SocketException e) { runflag = false; continue; } Class<? extends Message> klass = message.getClass(); if(klass == RequestMessage.class) { // service.getServiceLock().lock(); RequestMessage requestMessage = (RequestMessage)message; System.out.println( String.format( "\nNeighbor %d sent a Request message(%d)", neighbor.getId(), message.getClock().value() ) ); service.handleRequestMessage(neighbor, requestMessage); // service.getServiceLock().unlock(); }else if(klass == LockedMessage.class) { // service.getServiceLock().lock(); LockedMessage lockedMessage = (LockedMessage)message; System.out.println( String.format( "\nNeighbor %d sent a locked message(%d)", neighbor.getId(), message.getClock().value() ) ); service.handleLockedMessage(neighbor, lockedMessage); // service.getServiceLock().unlock(); }else if(klass == FailedMessage.class) { // service.getServiceLock().lock(); FailedMessage failedMessage = (FailedMessage)message; System.out.println( String.format( "\nNeighbor %d sent a Failed message(%d)", neighbor.getId(), message.getClock().value() ) ); service.handleFailedMessage(neighbor, failedMessage); // service.getServiceLock().unlock(); }else if(klass == RelinquishMessage.class) { // service.getServiceLock().lock(); RelinquishMessage relinquishMessage = (RelinquishMessage)message; System.out.println( String.format( "\nNeighbor %d sent a Relinquish message(%d)", neighbor.getId(), message.getClock().value() ) ); service.handleRelinquishMessage(neighbor, relinquishMessage); // service.getServiceLock().unlock(); }else if(klass == InquireMessage.class) { // service.getServiceLock().lock(); InquireMessage inquireMessage = (InquireMessage)message; System.out.println( String.format( "\nNeighbor %d sent a Inquire message(%d)", neighbor.getId(), message.getClock().value() ) ); service.handleInquireMessage(neighbor, inquireMessage); // service.getServiceLock().unlock(); }else if(klass == ReleaseMessage.class) { // service.getServiceLock().lock(); ReleaseMessage releaseMessage = (ReleaseMessage)message; System.out.println( String.format( "\nNeighbor %d sent a Release message(%d)", neighbor.getId(), message.getClock().value() ) ); service.handleReleaseMessage(neighbor, releaseMessage); // service.getServiceLock().unlock(); }else if(klass == ApplicationMessage.class) { // service.getServiceLock().lock(); ApplicationMessage applicationMessage = (ApplicationMessage)message; System.out.println( String.format( "\nNeighbor %d sent an Application message(%d)", neighbor.getId(), message.getClock().value() ) ); service.handleApplicationMessage(neighbor, applicationMessage); // service.getServiceLock().unlock(); }else if(klass == TerminationMessage.class) { // service.getServiceLock().lock(); TerminationMessage terminationMessage = (TerminationMessage)message; System.out.println( String.format( "\nNeighbor %d sent a Termination message", neighbor.getId() ) ); service.handleTerminationMessage(neighbor, terminationMessage); // service.getServiceLock().unlock(); }else { throw new ClassNotFoundException( String.format( "\nNeighbor %d sent an undefined message", neighbor.getId() ) ); } } }catch(EOFException e) { System.out.println(String.format("Neighbor(%d) has terminated!\n Terminating...Bye!", neighbor.getId())); return; } catch (ClassNotFoundException | IOException e) { e.printStackTrace(); return; } } public void terminate() throws IOException { neighbor.getInputObjectStream().close(); this.runflag=false; } } <file_sep>#!/bin/bash # Change this to your netid netid=sxg177330 # # Root directory of your project PROJDIR=$HOME/aos_maekawa # # This assumes your config file is named "config.txt" # and is located in your project directory # CONFIG=$PROJDIR/Document.txt # # Directory your java classes are in # BINDIR=$PROJDIR/bin LOGDIR=$PROJDIR/logs #/bin #DUMPDIR DUMPDIR=$PROJDIR/dumps # # Your main project class # PROG=Maekawa.Main i=0 cat $CONFIG | sed -e "s/#.//" | sed -e "/^\s$/d" | ( read n n=$( echo $n| awk '{ print $1}' ) echo $n while [ "$i" -ne "$n" ] do read line i=$( echo $line | awk '{ print $1 }' ) host=$( echo $line | awk '{ print $2 }' ) port=$( echo $line | awk '{ print $3 }' ) # echo $i $host $port hosts_list[$i]=$host i=$(( i + 1 )) done i=0 while [ "$i" -ne "$n" ] do host=${hosts_list[$i]} echo host=$host, i=$i # echo "cd $BINDIR; stdbuf -o0 java $PROG $i $CONFIG 1>$DUMPDIR/dump_$i.txt 2>$DUMPDIR/error_$i.txt&" ssh -o StrictHostkeyChecking=no $netid@$host "cd $BINDIR; stdbuf -o0 java $PROG $i $CONFIG $LOGDIR/log_$i.csv 1>$DUMPDIR/dump_$i.txt 2>$DUMPDIR/error_$i.txt&" & i=$(( i + 1 )) done )<file_sep>package Maekawa; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.junit.Test; public class TestRelinquish extends StandardTestConfiguration { public TestRelinquish() { super(); } @Test public void whenHighPriorityRequestComesAfterGivingLock() throws IOException, NeighborNotFoundExeption, InterruptedException { System.out.println("----------------------------------------"); Node node0 = services[0].config.getNode(); Node node1 = services[1].config.getNode(); Node node2 = services[2].config.getNode(); ScalarClock RequestClock0 = services[0].localClock.clone(); ScalarClock RequestClock1 = services[1].localClock.clone(); // Node-0 locks self and node 2 services[0].sendRequestToSelf(); services[0].grantSet.add(configs[0].getSelfAsNeighbor()); services[0].currentLockedNeighbor = configs[0].getSelfAsNeighbor(); node0.getNeighborById(2).sendRequest(RequestClock0); Thread.sleep(50); // node 1 sends request to 0, 1, 3 services[1].sendRequestToSelf(); services[1].grantSet.add(configs[1].getSelfAsNeighbor()); services[1].currentLockedNeighbor = configs[1].getSelfAsNeighbor(); node1.getNeighborById(3).sendRequest(RequestClock1); Thread.sleep(50); // node 3 sends lock // Node-0 tries to lock Node-1 node0.getNeighborById(1).sendRequest(RequestClock0); Thread.sleep(50); assertEquals(services[0].canGetALock, true); // Node-1 tries to lock Node-0 node1.getNeighborById(0).sendRequest(RequestClock1); Thread.sleep(50); assertEquals(services[1].canGetALock, false); } } <file_sep>package Maekawa; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; public class Neighbor extends Node { private int rootId; private Socket OutgoingSocket; private Socket IncomingSocket; private ObjectInputStream objectInputStream; private ObjectOutputStream objectOutputStream; private boolean willingToTerminate; public Neighbor(int nodeId, int rootId) { super(nodeId); this.rootId = rootId; this.setWillingToTerminate(false); } public ObjectInputStream getInputObjectStream() { return objectInputStream; } public ObjectOutputStream getOutputObjectStream() { return objectOutputStream; } public void setOutgoingSocket(Socket outgoingSocket) throws IOException { OutgoingSocket = outgoingSocket; try { this.objectOutputStream = new ObjectOutputStream(OutgoingSocket.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } } public Socket getIncomingSocket() { return IncomingSocket; } public void setIncomingSocket(Socket incomingSocket) { IncomingSocket = incomingSocket; // try { // this.objectInputStream = new ObjectInputStream(IncomingSocket.getInputStream());; // } catch (IOException e) { // e.printStackTrace(); // } } public void sendRequest(ScalarClock clock) throws IOException { System.out.println(String.format("Sending Request Message(%d) to neighbor-%d", clock.value(), getId())); RequestMessage message = new RequestMessage(clock); message.setSenderID(getRootId()); message.setReceiverID(getId()); objectOutputStream.writeObject(message); objectOutputStream.flush(); } public void sendRelease(ScalarClock clock) throws IOException { System.out.println(String.format("Sending Release Message(%d) to neighbor-%d", clock.value(), getId())); ReleaseMessage message = new ReleaseMessage(clock); message.setSenderID(getRootId()); message.setReceiverID(getId()); objectOutputStream.writeObject(message); objectOutputStream.flush(); } public void sendRelinquish(ScalarClock clock) throws IOException { System.out.println(String.format("Sending Relinquish Message(%d) to neighbor-%d", clock.value(), getId())); RelinquishMessage message = new RelinquishMessage(clock); message.setSenderID(getRootId()); message.setReceiverID(getId()); objectOutputStream.writeObject(message); objectOutputStream.flush(); } public void sendLocked(ScalarClock clock) throws IOException { System.out.println(String.format("Sending Locked Message(%d) to neighbor-%d", clock.value(), getId())); LockedMessage message = new LockedMessage(clock); message.setSenderID(getRootId()); message.setReceiverID(getId()); objectOutputStream.writeObject(message); objectOutputStream.flush(); } public void sendInquire(ScalarClock clock) throws IOException { System.out.println(String.format("Sending Inquire Message(%d) to neighbor-%d", clock.value(), getId())); InquireMessage message = new InquireMessage(clock); message.setSenderID(getRootId()); message.setReceiverID(getId()); objectOutputStream.writeObject(message); objectOutputStream.flush(); } public void sendFailed(ScalarClock clock) throws IOException { System.out.println(String.format("Sending Failed Message(%d) to neighbor-%d", clock.value(), getId())); FailedMessage message = new FailedMessage(clock); message.setSenderID(getRootId()); message.setReceiverID(getId()); objectOutputStream.writeObject(message); objectOutputStream.flush(); } public void setIn(Socket connector, ObjectInputStream is) { this.IncomingSocket = connector; this.objectInputStream = is; } public void sendHelloWorld(ScalarClock clock) throws IOException { ApplicationMessage message = new ApplicationMessage(clock); message.setData("Hello World!"); message.setSenderID(getRootId()); message.setReceiverID(getId()); objectOutputStream.writeObject(message); objectOutputStream.flush(); } public int getRootId() { return rootId; } public void setRootId(int rootId) { this.rootId = rootId; } public void sendTerminate(ScalarClock localClock) throws IOException { TerminationMessage message = new TerminationMessage(localClock); message.setSenderID(getRootId()); message.setReceiverID(getId()); objectOutputStream.writeObject(message); objectOutputStream.flush(); } public boolean isWillingToTerminate() { return willingToTerminate; } public void setWillingToTerminate(boolean willingToTerminate) { this.willingToTerminate = willingToTerminate; } } <file_sep>package Maekawa; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.junit.Test; public class TestcsEnterValidQueueTop extends StandardTestConfiguration { public TestcsEnterValidQueueTop() { super(); } @Test // Case: If a service wants to enter critical section, it must put its own // request in the requestMessageQueue public void runTestcsEnterValidQueueTop() throws InterruptedException, IOException { try { services[0].csEnter(); assertEquals(services[0].requestMessageQueue.get(0).getSenderID(), 0); services[0].csLeave(); } catch (InterruptedException | IOException e) { e.printStackTrace(); } } } <file_sep>package Maekawa; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.junit.Test; public class TestCriticalSectionContention extends StandardTestConfiguration { public TestCriticalSectionContention() { super(); } @Test // Case: If a service wants to enter critical section and has contention, // only the service that has earlier lock needs to enter and shall block until // the first locking service leaves public void runTestcsEnter2Blocking() { try { Thread block = new Thread(() -> { try { services[0].csEnter(); services[1].csEnter(); } catch (InterruptedException | IOException e) { e.printStackTrace(); } }); block.start(); Thread.sleep(100); assertEquals(Thread.State.TIMED_WAITING, block.getState()); // block.interrupt(); services[0].csLeave(); Thread.sleep(100); assertEquals(services[1].requestMessageQueue.get(0).getSenderID(), 1); services[1].csLeave(); Thread.sleep(100); assertEquals(services[1].requestMessageQueue.size(), 0); Thread.sleep(100); // Thread that was blocked due to the contending csEnter operations has now // become unlocked and eventually terminated assertEquals(Thread.State.TERMINATED, block.getState()); } catch (InterruptedException | IOException e) { e.printStackTrace(); } } } <file_sep>rm dumps/* -rf; rm logs/* -rf; <file_sep>cd src; javac Maekawa/Main.java -d ../bin/; cd ..; <file_sep># Maekawa Algorithm - Quorum Based Mutual Exclusion in Distributed Systems ### THIS PROJECT IS INTENTIONALLY CRIPPLED. THIS IS AN ACAD. SUBMISSION. ANY DERIVATIVE BASED ON THIS IS AS GOOD AS REWRITING IT. SO DON'T USE THIS PROJECT. #### The details of protocol can be read from the following paper #### https://cseweb.ucsd.edu/classes/wi09/cse223a/p145-maekawa.pdf ## Gist This project implements a use case scenario of Quorum Based Mututal Exclusion algorithm by <NAME>. In a gist... - A fleet of 50 odd systems shall be running a service that share a resource. - Individual nodes may demand exclusive access to the resource. - The nodes consult a limited set of nodes - the quorum - for the mutex. - The quorum will make sure that other quora haven't reserved the mutex and then let the requesting node to progress. - While in mutex - if the node or the quorum receives mutex request from inside or outside, they are made to wait in the queue. ## How it works - The fleet is deployed by a shell script. - This application reads a network/node configuration and becomes aware of other nodes and their own quorum. - Once all systems are up, they report to their respective neighbors of their awake state. - Random nodes at random intervels start requesting for mutex. - Every node has a set number of mutex request calls - once complete - application shall come to halt. - To halt, every system should be willing to halt - no more service requests. - Once a node exhausts it's quota of requests - it reports task completion to neighbors. If the same node receives task completion message from all of it's neighbors - then there will be no more work for this node and the node halts. - The neighbors do the same recursively - effectively bringing the system to a halt. - All of it can be verified on the respective log files of each node.
c183078db20a0ff85b10865b547b731856a16668
[ "Markdown", "Java", "Shell" ]
12
Java
simtron/MamoruMaekawa_DistributedMutex
a3eb92a725f9246306215e58079d552ce24e0386
01d4ca789224520bda89f573041c94c0302e9aa3
refs/heads/master
<file_sep># Scripting This is one of my first attempts at automated web testing using Selenium. ## Usage - Install the ```chromedriver``` - Run ```pip install selenium``` - Run ```python youtube.py``` or ```python facebook.py``` ## Issues See a bug? Feel free to create an issue request and we can look into it together. <file_sep>from selenium import webdriver from selenium.webdriver.common.keys import Keys from os import system, name import time from getpass import getpass def clear(): if name == 'nt': _ = system('cls') else: _ = system('clear') def login(): clear() usr = input('enter user name') pd = getpass('enter pass') browser = webdriver.Chrome() login_url = "http://facebook.com" browser.get(login_url) user_box = browser.find_element_by_id('email') user_box.send_keys(usr) pas_box = browser.find_element_by_id('pass') pas_box.send_keys(pd) pas_box.send_keys(Keys.ENTER) time.sleep(600) login()<file_sep>from selenium import webdriver from os import system, name import time from getpass import getpass def clear(): if name == 'nt': _ = system('cls') else: _ = system('clear') def search(): clear() username = input("Enter username: ") browser = webdriver.Chrome() login_url = "http://youtube.com" browser.get(login_url) search_box = browser.find_element_by_id('search') search_box.send_keys(username) search_bttn = browser.find_element_by_id('search-icon-legacy') search_bttn.click() time.sleep(10) search()
e29f2b2687b3ec72d7b579541459305cd703623e
[ "Markdown", "Python" ]
3
Markdown
vikas623/scripting
8c5d9f3f6717f58bd72e9900411cfa16e1e8f7fd
b177b57923291d3707697f0e5e0d49ecfc235648
refs/heads/master
<file_sep><!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Oberfläche ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!DOCtype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title> PHP Taschenrechner </title> <style type="text/css"> </style> </head> <body> <h1> PHP-Taschenrecher </h1> <h5> Bitte beachten Sie, dass dieser Taschenrechner <br> zunächst nur 2 Werte miteinander berechnen kann. </h5> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Eingabe ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <?php $Eingabe = ""; if (isset($_GET['key'])) { if ($_GET['key'] != "=") { $Eingabe = $_GET['Eingabe'] . $_GET['key']; if (preg_match("/[\*\/]{2}/",$Eingabe)) { $Eingabe = substr($Eingabe, 0, -2) . substr($Eingabe, -1); } } #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Unterteilung in [Zahl, Operator, Zahl] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ else { if ($_GET['Eingabe'] == "") { echo "Sie müssen eine Rechung eingeben um zu rechnen"; } else { preg_match_all("/([0-9]*)([\+\*\/\-]*)/", $_GET["Eingabe"], $zahlen); #https://regex101.com/ "/([0-9]*)([\+\*\/\-]*)/ ([0-9]*[\.]*)*([\+\*\/\-]*)" $numbersSorted = array(); foreach ($zahlen[1] as $index => $value) { #...only from arrays $zahlen[1]&[2]... if ($value != '') { $numbersSorted[] = $value; } if ($zahlen[2][$index] != '') { $numbersSorted[] = $zahlen[2][$index]; } } #end foreach~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Rechenlogik ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #print_r($zahlen) . "<br>"; $summe = ""; $value_1 = $numbersSorted[0]; $operator = $numbersSorted[1]; $value_2 = $numbersSorted[2]; switch($operator){ case "+": $summe = $value_1 + $value_2; $Eingabe = $summe; break; case "-": $summe = $value_1 - $value_2; $Eingabe = $summe; break; case "*": $summe = $value_1 * $value_2; $Eingabe = $summe; break; case "/": if ($value_2 == 0) { $Eingabe = "ERROR Division by 0!"; } else { $summe = $value_1 / $value_2; $Eingabe = $summe; } break; default: echo "please define an calculation" ."<br/>"; } } } #end else } #end isset #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Rechenverlauf ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if (isset($numbersSorted)) { echo "<br>"; print_r($numbersSorted); if ($value_2 == 0) { } else { echo $value_1 . "<br>" . $operator . " " . $value_2 . "<br>" . "__________" . "<br>" . "Summe = " . $summe . "<br>" . "========="; } } else { echo "<br>" . "<br>" . "<br>" . "<br>" . "<br>"; } #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Oberfläche ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ?> <form method="get"> <input type = "text" name = "Eingabe" value = <?php echo $Eingabe?> > <br> <input type="submit" name="key" value="7"> <input type="submit" name="key" value="8"> <input type="submit" name="key" value="9"> <input type="submit" name="key" value="+"> <input type="reset" value="C"> <!-- --> <br> <input type="submit" name="key" value="4"> <input type="submit" name="key" value="5"> <input type="submit" name="key" value="6"> <input type="submit" name="key" value="-"> <br> <input type="submit" name="key" value="1"> <input type="submit" name="key" value="2"> <input type="submit" name="key" value="3"> <input type="submit" name="key" value="*"> <!-- --> <br> <input type="submit" name="key" value="0"> <input type="submit" name="key" value="."> <input type="submit" name="key" value="="> <input type="submit" name="key" value="/"> <!-- --> <br> </form> </body> </html>
558dd17b718f5df5430e0afe3bd9849595b40831
[ "PHP" ]
1
PHP
Timmaaaa/PHP-Calculator
419c645e9416f5231742a5e52231b874060c3dcb
2a23fc57ec69eb70eb97a27fe8fbcd47bb6a1123
refs/heads/main
<repo_name>Svetlana-Ter/goit-react-hw-04-movies<file_sep>/src/pages/MoviesPage.js import { Component } from 'react'; import SearchForm from '../components/SearchForm/SearchForm'; import MoviesGallery from '../components/MoviesGallery/MoviesGallery'; import queryString from 'query-string'; class MoviesPage extends Component { state = { movies: [], }; componentDidMount() { const { query } = queryString.parse(this.props.location.search); if (query) { fetch( `https://api.themoviedb.org/3/search/movie?api_key=<KEY>&query=${query}` ) .then(response => response.json()) .then(data => { this.setState({ movies: data.results, }); }); } } componentDidUpdate(prevProps, prevState) { const { query: currentQuery } = queryString.parse( this.props.location.search ); const { query: prevQuery } = queryString.parse(prevProps.location.search); if (currentQuery !== prevQuery) { fetch( `https://api.themoviedb.org/3/search/movie?api_key=<KEY>&query=${currentQuery}` ) .then(response => response.json()) .then(data => this.setState({ movies: data.results, }) ); } } handleFormSubmit = movieName => { this.props.history.push({ pathname: this.props.location.pathname, search: `query=${movieName}`, }); }; render() { return ( <> <SearchForm onSubmit={this.handleFormSubmit} /> <MoviesGallery movies={this.state.movies} /> </> ); } } export default MoviesPage; <file_sep>/src/components/ReviewsDetails/ReviewsDetails.js import { Component } from 'react'; import ReviewItem from '../ReviewItem/ReviewItem'; export default class ReviewsDetails extends Component { state = { reviews: [], }; componentDidMount() { fetch( `https://api.themoviedb.org/3/movie/${this.props.match.params.movieId}/reviews?api_key=<KEY>` ) .then(response => response.json()) .then(data => this.setState({ reviews: data.results, }) ); } render() { if (this.state?.reviews?.length > 0) { return ( <ul className='Review-list'> {this.state?.reviews.map(review => ( <li key={review.id} className='Review-item'> <ReviewItem name={review?.author} content={review?.content} /> </li> ))} </ul> ); } else { return <p>We don't have reviews for this movie</p>; } } } <file_sep>/src/components/Navigation/Navigation.js import { NavLink } from 'react-router-dom'; export default function Navigation() { return ( <> <ul className='Navigation-list'> <li className='Navigation-item'> <NavLink to='/' exact className='NavLink' activeClassName='NavLink--active' > Home </NavLink> </li> <li className='Navigation-item'> <NavLink to='/movies' className='NavLink' activeClassName='NavLink--active' > Movies </NavLink> </li> </ul> <hr /> </> ); } <file_sep>/src/components/CastItem/CastItem.js import PropTypes from 'prop-types'; export default function CastItem({ src = '', name = '', character = '' }) { return ( <div> {src ? ( <img src={`https://image.tmdb.org/t/p/w500/${src}`} className='CastItem-img' /> ) : ( <p>Actor poster is not found</p> )} <h3>{name}</h3> <p>{character}</p> </div> ); } CastItem.propTypes = { src: PropTypes.string, name: PropTypes.string, character: PropTypes.string, }; <file_sep>/src/components/CastDetails/CastDetails.js import { Component } from 'react'; import CastItem from '../CastItem/CastItem'; export default class CastDetails extends Component { state = { cast: [], }; componentDidMount() { fetch( `https://api.themoviedb.org/3/movie/${this.props.match.params.movieId}/credits?api_key=<KEY>` ) .then(response => response.json()) .then(data => this.setState({ cast: data.cast, }) ); } render() { if (this.state?.cast?.length > 0) { return ( <ul className='Casts-list'> {this.state.cast?.map(castItem => ( <li key={castItem.id} className='Casts-item'> <CastItem src={castItem?.profile_path} name={castItem?.name} character={castItem?.character} /> </li> ))} </ul> ); } else { return <p>We don't have casts for this movie</p>; } } }
5c47ece2919c3c259e75e08fc197b5470c52d2b9
[ "JavaScript" ]
5
JavaScript
Svetlana-Ter/goit-react-hw-04-movies
7bc01a43519f2c5e4f6e38fd8e6112c265e6bba5
8b1820aec074e62249061e90e189c91c0ec03ba1
refs/heads/master
<repo_name>krybicka/valentinesday-card<file_sep>/myScript.js var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); var x = canvas.width/2; var y = canvas.height-30; var dx = 2; var dy = -2; var paddleHeight = 10; var paddleWidth = 120; var paddleX = (canvas.width-paddleWidth)/2; var brickRowCount = 3; var brickColumnCount = 5; var brickWidth = 75; var brickHeight = 20; var brickPadding = 10; var brickOffsetTop = 30; var brickOffsetLeft = 30; var bricks = []; var win = 0; var alertActive = false; // - - - - - keys var rightPressed = false; var leftPressed = false; document.addEventListener("keydown", keyDownHandler, false); document.addEventListener("keyup", keyUpHandler, false); function keyDownHandler(e) { if(e.keyCode == 39) { rightPressed = true; } else if(e.keyCode == 37) { leftPressed = true; } } function keyUpHandler(e) { if(e.keyCode == 39) { rightPressed = false; } else if(e.keyCode == 37) { leftPressed = false; } } function collisionDetection() { for(c=0; c<brickColumnCount; c++) { for(r=0; r<brickRowCount; r++) { var b = bricks[c][r]; if(b.status == 1) { if(x > b.x && x < b.x+brickWidth && y > b.y && y < b.y+brickHeight) { dy = -dy; b.status = 0; win++; if(win == brickRowCount*brickColumnCount) { alertActive = true; swal({ title: "Kochany {imię}", text: "Treść życzeń, może być dłuższa. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", confirmButtonColor: "#C18E87", confirmButtonText: "Dzięki za życzonka, ale pogram jeszcze", closeOnConfirm: true, imageUrl: "assets/pusheen2.png", allowEscapeKey: false }, function(){ document.location.reload(); }); } } } } } } // - - - - - ball var ballRadius = 10; function drawBall() { ctx.beginPath(); ctx.arc(x, y, ballRadius, 0, Math.PI*2); ctx.fillStyle = "#CE375F"; ctx.fill(); ctx.closePath(); } // - - - - - paddle function drawPaddle() { ctx.beginPath(); ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight); ctx.fillStyle = "#C18E87"; ctx.fill(); ctx.closePath(); if(rightPressed && paddleX < canvas.width-paddleWidth) { paddleX += 7; } else if(leftPressed && paddleX > 0) { paddleX -= 7; } } // - - - - - bricks for(c=0; c<brickColumnCount; c++) { bricks[c] = []; for(r=0; r<brickRowCount; r++) { bricks[c][r] = { x: 0, y: 0, status: 1 }; } } function drawBricks() { for(c=0; c<brickColumnCount; c++) { for(r=0; r<brickRowCount; r++) { if(bricks[c][r].status == 1) { var brickX = (c*(brickWidth+brickPadding))+brickOffsetLeft; var brickY = (r*(brickHeight+brickPadding))+brickOffsetTop; bricks[c][r].x = brickX; bricks[c][r].y = brickY; ctx.beginPath(); ctx.rect(brickX, brickY, brickWidth, brickHeight); ctx.fillStyle = "#C18E87"; ctx.fill(); ctx.closePath(); } } } } // - - - - - draw function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); drawBall(); drawBricks(); drawPaddle(); collisionDetection(); x += dx; y += dy; if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) { dx = -dx; } if(y + dy < ballRadius) { dy = -dy; } else if(y + dy > canvas.height-ballRadius) { if(x > paddleX && x < paddleX + paddleWidth) { dy = -dy; } else { if(alertActive){ canvas.freeze(); } else { swal({ title: "Spróbuj jeszcze raz!", text: "Jak zbijesz wszystkie klocki to będzie niespodzianka, nie daj się! Poruszaj strzałkami :)", confirmButtonColor: "#C18E87", confirmButtonText: "Spoko, gram", closeOnConfirm: true, imageUrl: "assets/pusheen1.png", allowEscapeKey: false }, function(){ document.location.reload(); }); }; } } } setInterval(draw, 10); <file_sep>/README.md # valentine-card Valentine's day card with arkanoid game. Full of love, sweetness and pusheens!
26de1adb4a6887de8f51c5219ba4a26f7c83a647
[ "JavaScript", "Markdown" ]
2
JavaScript
krybicka/valentinesday-card
20b48609a5d0b52b62e73faa7e49243ceeddf713
826e13489b0a42c8f0cc8ad449228907e24ab486
refs/heads/master
<file_sep>-- phpMyAdmin SQL Dump -- version 4.8.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Mar 11, 2019 at 10:57 AM -- Server version: 10.1.34-MariaDB -- PHP Version: 7.2.7 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: `listrik` -- -- -------------------------------------------------------- -- -- Table structure for table `admin` -- CREATE TABLE `admin` ( `adminId` int(11) NOT NULL, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `admin` -- INSERT INTO `admin` (`adminId`, `username`, `password`) VALUES (1, 'admin', '<PASSWORD>'); -- -------------------------------------------------------- -- -- Table structure for table `daya` -- CREATE TABLE `daya` ( `id_daya` int(11) NOT NULL, `tegangan` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `daya` -- INSERT INTO `daya` (`id_daya`, `tegangan`) VALUES (1, 250), (2, 450), (3, 900), (4, 1300), (5, 2200), (6, 3500), (7, 4400), (8, 5500), (9, 7700), (10, 11000); -- -------------------------------------------------------- -- -- Table structure for table `user` -- CREATE TABLE `user` ( `id_user` int(11) NOT NULL, `id_daya` int(11) NOT NULL, `username` varchar(255) NOT NULL, `rekening_listrik` varchar(255) NOT NULL, `alamat` varchar(255) NOT NULL, `tanggal` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Indexes for dumped tables -- -- -- Indexes for table `admin` -- ALTER TABLE `admin` ADD PRIMARY KEY (`adminId`); -- -- Indexes for table `daya` -- ALTER TABLE `daya` ADD PRIMARY KEY (`id_daya`); -- -- Indexes for table `user` -- ALTER TABLE `user` ADD PRIMARY KEY (`id_user`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `admin` -- ALTER TABLE `admin` MODIFY `adminId` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `daya` -- ALTER TABLE `daya` MODIFY `id_daya` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12; -- -- AUTO_INCREMENT for table `user` -- ALTER TABLE `user` MODIFY `id_user` int(11) NOT NULL AUTO_INCREMENT; 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>$(document).ready(function(){ $('#pencarian').keyup(function(){ setTimeout(function(){ data = $('#pencarian').val(); window.location.replace('index.php?q='+data); },1000) }); // $('#content').load('list_user.php'); });<file_sep><?php $q = $_GET['q']; $search = $conn->query("SELECT * FROM user INNER JOIN daya ON user.id_daya = daya.id_daya WHERE user.username LIKE '%$q%' OR user.rekening_listrik LIKE '%$q%'"); ?> <div class="card"> <div class="card-header"> <h3 class="card-title">List User</h3> </div> <div class="table-responsive"> <table class="table card-table table-vcenter text-nowrap"> <thead> <tr> <th class="w-1">No.</th> <th>Nama</th> <th>Nomor Rek.</th> <th>Daya</th> <th>Created</th> <th></th> <th></th> </tr> </thead> <tbody> <?php while ($data = $search->fetch_assoc()){ ?> <tr> <td><span class="text-muted"><?php echo $no; ?></span></td> <td><a href="invoice.html" class="text-inherit"><?=$data['username']; ?></a></td> <td> <?=$data['rekening_listrik']; ?> </td> <td> <?=number_format($data['tegangan'],0,',','.'); ?> Volt </td> <td> <?=$data['tanggal'];?> </td> <td class="text-right"> <form id="deleteUser"> <input type="hidden" name="id_user" value="<?=$data['id_user'];?>"> <button type="submit" onclick="return confirm('Are you sure?');" class="btn btn-secondary btn-sm"><i class="fe fe-delete"></i> Delete </button> </form> </td> <td> <a href="edit.php?userId=<?=$data['id_user'];?>" class="btn btn-secondary btn-sm"><i class="fe fe-edit"></i> Edit</a> </td> </tr> <?php $no++; ?> <?php } ?> </tbody> </table> </div> </div><file_sep><?php $config = Array( "base_url" => "http://localhost/", "webname" => "Pengelola Rekening Listrik", "description" => "Aplikasi Pengelola Rekening Listrik untuk mempermudahkan dalam mengelola pembayaran listrik", "db_host" => "localhost", "db_user" => "root", "db_password" => "", "db_name" => "listrik" ); $conn = new mysqli($config['db_host'], $config['db_user'], $config['db_password'], $config['db_name']); if ($conn->connect_error) { echo '<script>alert("Error connecting to database!" );</script>'; } ?><file_sep><?php session_start(); include 'config.php'; if (isset($_SESSION['user'])) { header("location: index.php"); } ?> <!doctype html> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta http-equiv="Content-Language" content="en" /> <meta name="msapplication-TileColor" content="#2d89ef"> <meta name="theme-color" content="#4188c9"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"/> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="mobile-web-app-capable" content="yes"> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <link rel="icon" href="./favicon.ico" type="image/x-icon"/> <link rel="shortcut icon" type="image/x-icon" href="./favicon.ico" /> <!-- Generated: 2018-04-16 09:29:05 +0200 --> <title>Login - tabler.github.io - a responsive, flat and full featured admin template</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,300i,400,400i,500,500i,600,600i,700,700i&amp;subset=latin-ext"> <script src="./assets/js/require.min.js"></script> <script> requirejs.config({ baseUrl: '.' }); </script> <!-- Dashboard Core --> <link href="./assets/css/dashboard.css" rel="stylesheet" /> <script src="./assets/js/dashboard.js"></script> <!-- c3.js Charts Plugin --> <link href="./assets/plugins/charts-c3/plugin.css" rel="stylesheet" /> <script src="./assets/plugins/charts-c3/plugin.js"></script> <!-- Google Maps Plugin --> <link href="./assets/plugins/maps-google/plugin.css" rel="stylesheet" /> <script src="./assets/plugins/maps-google/plugin.js"></script> <!-- Input Mask Plugin --> <script src="./assets/plugins/input-mask/plugin.js"></script> <!-- <script src="http://localhost/dist/js/jquery-3.3.1.min.js"></script> --> </head> <body class=""> <div class="page"> <div class="page-single"> <div class="container"> <div class="row"> <div class="col col-login mx-auto"> <div class="text-center mb-6"> <img src="./demo/brand/tabler.svg" class="h-6" alt=""> </div> <form class="card" id="loginForm"> <div class="card-body p-6"> <div class="card-title">Login to your account</div> <span id="load" class="text-center"></span> <div class="form-group"> <label class="form-label">Username</label> <input type="text" class="form-control" name="username" id="username" aria-describedby="emailHelp" placeholder="Enter username" required> </div> <div class="form-group"> <label class="form-label"> Password </label> <input type="password" class="form-control" name="password" id="password" placeholder="<PASSWORD>" required> </div> <div class="form-group"> <label class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" /> <span class="custom-control-label">Remember me</span> </label> </div> <div class="form-footer"> <button type="submit" class="btn btn-primary btn-block">Sign in</button> </div> </div> </form> </div> </div> </div> </div> </div> <script src="http://localhost/dist/js/jquery-3.3.1.min.js"></script> <script> $(document).ready(function(){ $('#loginForm').submit(function(e){ e.preventDefault(); $('#load').html('<div class="ml-auto mr-auto loader"></div>'); setTimeout(function(){ $.ajax({ type : "POST", url : "loginjs.php", data : $('#loginForm').serialize(), success : function(data){ if (data === 'success') { $('#load').html('<p class="alert alert-success"><i class="fe fe-info"></i> Success Login. Redirecting...</p>'); setTimeout(function(){ window.location.replace('index.php') },1000); }else if(data === 'failed'){ $('#load').html('<p class="alert alert-danger"><i class="fe fe-info"></i> Wrong Password!</p>'); }else if(data === 'unknown'){ $('#load').html('<p class="alert alert-danger"><i class="fe fe-info"></i> Username tidak terdaftar!</p>'); }else{ alert('Error Status: '+data); } } }) },2000); });4 }); </script> </body> </html><file_sep><?php include '../config.php'; if (isset($_POST)) { $username = mysqli_real_escape_string($conn, $_POST['username']); $nomor_rekening = mysqli_real_escape_string($conn, $_POST['nomor_rekening']); $alamat = mysqli_real_escape_string($conn, $_POST['alamat']); $daya_listrik = mysqli_real_escape_string($conn, $_POST['daya_listrik']); //Proses Tambah Data $sql = "INSERT INTO user VALUES('','$daya_listrik', '$username', '$nomor_rekening', '$alamat', now())"; $conn->query($sql); echo "success"; }else{ echo "error"; } ?><file_sep># Sistem Pengelola Rekening Listrik Web aplikasi yang digunakan untuk mengelola data rekening listrik. Aplikasi ini menggunakan template http://tabler.github.io --- Untuk meng-konfigurasi, edit pada bagian file config.php PHP 5.6 or higher Thanks :)<file_sep><?php session_start(); include 'config.php'; if (isset($_POST)) { $username = mysqli_real_escape_string($conn, $_POST['username']); $password = mysqli_real_escape_string($conn, $_POST['password']); /*Proses Login*/ $cek_user = $conn->query("SELECT * FROM admin WHERE username = '$username'"); $user = $cek_user->num_rows; if ($user >= 1) { $data_user = $cek_user->fetch_assoc(); if ($data_user['password'] == $password) { $_SESSION['user'] = $data_user; echo "success"; }else{ echo "failed"; } }else{ echo "unknown"; } }else{ echo "error"; } ?><file_sep><?php session_start(); include 'config.php'; if (!isset($_SESSION['user'])) { header("location: login.php"); } $no=1; ?> <!doctype html> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta http-equiv="Content-Language" content="en" /> <meta name="msapplication-TileColor" content="#2d89ef"> <meta name="theme-color" content="#4188c9"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"/> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="mobile-web-app-capable" content="yes"> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <link rel="icon" href="./favicon.ico" type="image/x-icon"/> <link rel="shortcut icon" type="image/x-icon" href="./favicon.ico" /> <!-- Generated: 2018-04-16 09:29:05 +0200 --> <title><?=$config['webname'];?> - Dashboard</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,300i,400,400i,500,500i,600,600i,700,700i&amp;subset=latin-ext"> <script src="./assets/js/require.min.js"></script> <script> requirejs.config({ baseUrl: '.' }); </script> <!-- Dashboard Core --> <link href="./assets/css/dashboard.css" rel="stylesheet" /> <script src="./assets/js/dashboard.js"></script> <!-- c3.js Charts Plugin --> <link href="./assets/plugins/charts-c3/plugin.css" rel="stylesheet" /> <script src="./assets/plugins/charts-c3/plugin.js"></script> <!-- Google Maps Plugin --> <link href="./assets/plugins/maps-google/plugin.css" rel="stylesheet" /> <script src="./assets/plugins/maps-google/plugin.js"></script> <!-- Input Mask Plugin --> <script src="./assets/plugins/input-mask/plugin.js"></script> </head> <body class=""> <div class="page"> <div class="page-main"> <?php include 'header.html'; ?> <div class="my-3 my-md-5"> <div class="container"> <div class="page-header"> <h1 class="page-title"> Dashboard </h1> </div> <div class="row row-cards row-deck"> <div class="col-12"> <?php if (empty(isset($_GET['q']))): ?> <div id="content"></div> <?php else: ?> <?php include 'search_user.php'; ?> <?php endif ?> </div> </div> </div> </div> </div> </div> <?php include 'footer.html'; ?> </div> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script src="assets/js/script.js"></script> </body> </html><file_sep><?php include '../config.php'; if ($_POST) { $id = $_POST['id_user']; $conn->query("DELETE FROM user WHERE id_user = $id"); echo "success"; }else{ echo "error"; } ?><file_sep><?php include '../config.php'; if (isset($_POST)) { $id = $_POST['id']; $username = mysqli_real_escape_string($conn, $_POST['username']); $nomor_rekening = mysqli_real_escape_string($conn, $_POST['nomor_rekening']); $alamat = mysqli_real_escape_string($conn, $_POST['alamat']); $daya_listrik = mysqli_real_escape_string($conn, $_POST['daya_listrik']); //Proses Update $update = "UPDATE user SET id_daya = '$daya_listrik', username = '$username', rekening_listrik = '$nomor_rekening', alamat = '$alamat', tanggal = now() WHERE id_user = '$id'"; $conn->query($update); echo "success"; }else{ echo "error"; } ?>
745fa6c7d9821c4329c77516bed333ce118e16ff
[ "JavaScript", "SQL", "Markdown", "PHP" ]
11
SQL
Ir001/pengelola-rekening-listrik
5ad78de6f0a86b359709f2ffa525599b19fe4dfb
88fc18fb84a8955d341e92bcfd24beaba6bc54b0
refs/heads/master
<repo_name>fablecode/yugioh-insight<file_sep>/src/wikia/processor/cardprocessor/src/Domain/cardprocessor.domain/Services/CategoryService.cs using System.Collections.Generic; using System.Threading.Tasks; using cardprocessor.core.Models.Db; using cardprocessor.core.Services; using cardprocessor.domain.Repository; namespace cardprocessor.domain.Services { public class CategoryService : ICategoryService { private readonly ICategoryRepository _categoryRepository; public CategoryService(ICategoryRepository categoryRepository) { _categoryRepository = categoryRepository; } public Task<List<Category>> AllCategories() { return _categoryRepository.AllCategories(); } public Task<Category> CategoryById(int id) { return _categoryRepository.CategoryById(id); } public Task<Category> Add(Category category) { return _categoryRepository.Add(category); } } }<file_sep>/src/wikia/data/archetypedata/src/Core/archetypedata.core/Models/ArticleTaskResult.cs using System.Collections.Generic; using System.Linq; namespace archetypedata.core.Models { public class ArticleTaskResult { public bool IsSuccessful => !Errors.Any(); public Article Article { get; set; } public List<string> Errors { get; set; } = new List<string>(); } } <file_sep>/src/wikia/data/archetypedata/src/Domain/archetypedata.domain/Services/Messaging/IQueue.cs using System.Threading.Tasks; namespace archetypedata.domain.Services.Messaging { public interface IQueue<in T> { Task Publish(T message); } }<file_sep>/src/wikia/data/carddata/src/Application/carddata.application/MessageConsumers/CardInformation/CardInformationConsumerHandler.cs using System.Threading; using System.Threading.Tasks; using carddata.core.Models; using carddata.core.Processor; using FluentValidation; using MediatR; using Newtonsoft.Json; namespace carddata.application.MessageConsumers.CardInformation { public class CardInformationConsumerHandler : IRequestHandler<CardInformationConsumer, CardInformationConsumerResult> { private readonly IArticleProcessor _articleProcessor; private readonly IValidator<CardInformationConsumer> _validator; public CardInformationConsumerHandler(IArticleProcessor articleProcessor, IValidator<CardInformationConsumer> validator) { _articleProcessor = articleProcessor; _validator = validator; } public async Task<CardInformationConsumerResult> Handle(CardInformationConsumer request, CancellationToken cancellationToken) { var cardInformationTaskResult = new CardInformationConsumerResult(); var validationResults = _validator.Validate(request); if (validationResults.IsValid) { var cardArticle = JsonConvert.DeserializeObject<Article>(request.Message); var results = await _articleProcessor.Process(cardArticle); cardInformationTaskResult.ArticleConsumerResult = results; } return cardInformationTaskResult; } } }<file_sep>/src/wikia/processor/cardprocessor/src/Infrastructure/cardprocessor.infrastructure/Services/Messaging/Cards/CardImageQueue.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using cardprocessor.application.Configuration; using cardprocessor.core.Models; using cardprocessor.domain.Queues.Cards; using cardprocessor.domain.Services.Messaging.Cards; using Microsoft.Extensions.Options; using Newtonsoft.Json; using RabbitMQ.Client; namespace cardprocessor.infrastructure.Services.Messaging.Cards { public class CardImageQueue : ICardImageQueue { private readonly IOptions<RabbitMqSettings> _rabbitMqConfig; public CardImageQueue(IOptions<RabbitMqSettings> rabbitMqConfig) { _rabbitMqConfig = rabbitMqConfig; } public Task<CardImageCompletion> Publish(DownloadImage downloadImage) { var cardImageCompletion = new CardImageCompletion(); try { var messageBodyBytes = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(downloadImage)); var factory = new ConnectionFactory() { HostName = _rabbitMqConfig.Value.Host }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { var props = channel.CreateBasicProperties(); props.ContentType = _rabbitMqConfig.Value.ContentType; props.DeliveryMode = _rabbitMqConfig.Value.Exchanges[RabbitMqExchangeConstants.YugiohHeadersImage].PersistentMode; props.Headers = _rabbitMqConfig.Value.Exchanges[RabbitMqExchangeConstants.YugiohHeadersImage].Headers.ToDictionary(k => k.Key, k => (object)k.Value); channel.BasicPublish ( RabbitMqExchangeConstants.YugiohHeadersImage, "", props, messageBodyBytes ); } cardImageCompletion.IsSuccessful = true; } catch (Exception ex) { cardImageCompletion.Errors = new List<string>{ $"Unable to send image: {downloadImage.RemoteImageUrl} to download queue"}; cardImageCompletion.Exception = ex; } return Task.FromResult(cardImageCompletion); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Core/cardprocessor.core/Services/ILimitService.cs using System.Collections.Generic; using System.Threading.Tasks; using cardprocessor.core.Models.Db; namespace cardprocessor.core.Services { public interface ILimitService { Task<List<Limit>> AllLimits(); } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Helpers/Cards/TrapCardHelper.cs using System.Collections.Generic; using cardprocessor.application.Enums; using cardprocessor.application.Mappings.Mappers; using cardprocessor.application.Models.Cards.Input; using cardprocessor.core.Models; using cardprocessor.core.Models.Db; namespace cardprocessor.application.Helpers.Cards { public static class TrapCardHelper { public static CardInputModel MapSubCategoryIds(YugiohCard yugiohCard, CardInputModel cardInputModel, ICollection<Category> categories, ICollection<SubCategory> subCategories) { cardInputModel.SubCategoryIds = new List<int> { SubCategoryMapper.SubCategoryId(categories, subCategories, YgoCardType.Trap, yugiohCard.Property) }; return cardInputModel; } } }<file_sep>/src/services/Cards.API/src/Application/Cards.Application/MessageConsumers/CardData/CardInformationConsumerResult.cs namespace Cards.Application.MessageConsumers.CardData { public record CardInformationConsumerResult { public bool IsSuccessful { get; init; } } }<file_sep>/src/wikia/data/cardsectiondata/src/Infrastructure/cardsectiondata.infrastructure/Services/Messaging/Constants/RabbitMqExchangeConstants.cs namespace cardsectiondata.infrastructure.Services.Messaging.Constants { public static class RabbitMqExchangeConstants { public const string YugiohHeadersData = "yugioh.headers.data"; } }<file_sep>/src/wikia/data/cardsectiondata/src/Domain/cardsectiondata.domain/ArticleList/Processor/CardSectionProcessor.cs using System; using System.Collections.Generic; using System.Threading.Tasks; using cardsectiondata.core.Models; using cardsectiondata.core.Processor; using cardsectiondata.domain.Helpers; using wikia.Api; namespace cardsectiondata.domain.ArticleList.Processor { public class CardSectionProcessor : ICardSectionProcessor { private readonly IWikiArticle _wikiArticle; public CardSectionProcessor(IWikiArticle wikiArticle) { _wikiArticle = wikiArticle; } public async Task<CardSectionMessage> ProcessItem(Article article) { var cardSections = new List<CardSection>(); var contentResult = await _wikiArticle.Simple(article.Id); foreach (var section in contentResult.Sections) { if (section.Title.Equals("References", StringComparison.OrdinalIgnoreCase)) continue; var rulingSection = new CardSection { Name = section.Title, ContentList = SectionHelper.GetSectionContentList(section) }; cardSections.Add(rulingSection); } var cardSectionMessage = new CardSectionMessage { Name = article.Title, CardSections = cardSections }; return cardSectionMessage; } } }<file_sep>/src/wikia/data/carddata/src/Infrastructure/carddata.infrastructure/WebPages/Cards/CardHtmlDocument.cs using carddata.core.Helpers; using carddata.domain.WebPages.Cards; using HtmlAgilityPack; using System.Text.RegularExpressions; using System.Threading; namespace carddata.infrastructure.WebPages.Cards { public class CardHtmlDocument : ICardHtmlDocument { private readonly ICardHtmlTable _cardHtmlTable; public CardHtmlDocument(ICardHtmlTable cardHtmlTable) { _cardHtmlTable = cardHtmlTable; } public string ImageUrl(HtmlDocument htmlDocument) { var imageUrl = htmlDocument.DocumentNode.SelectSingleNode("//td[@class='cardtable-cardimage']/a/img")?.Attributes["src"]?.Value; return ImageHelper.ExtractImageUrl(imageUrl); } public string Name(HtmlDocument htmlDocument) { var htmlTableNode = ExtractHtmlCardTableNode(htmlDocument); return _cardHtmlTable.GetValue(CardHtmlTable.Name, htmlTableNode); } public string Description(HtmlDocument htmlDocument) { const string pattern = @"(?!</?br>)<.*?>"; var descNode = htmlDocument.DocumentNode.SelectSingleNode("//b[text()[contains(., 'Card descriptions')]]/../table[1]/tbody/tr[1]/td[1]/table[1]/tbody/tr[3]/td")?.InnerHtml; if (descNode != null) { descNode = Regex.Replace(descNode, pattern, string.Empty, RegexOptions.Multiline); return descNode.Trim(); } return string.Empty; } public string CardNumber(HtmlDocument htmlDocument) { return ExtractHtmlCardTableValue(CardHtmlTable.Number, htmlDocument); } public string CardType(HtmlDocument htmlDocument) { return ExtractHtmlCardTableValue(CardHtmlTable.CardType, htmlDocument); } public string Property(HtmlDocument htmlDocument) { return ExtractHtmlCardTableValue(CardHtmlTable.Property, htmlDocument); } public string Attribute(HtmlDocument htmlDocument) { var attribute = ExtractHtmlCardTableValue(CardHtmlTable.Attribute, htmlDocument); if (string.IsNullOrWhiteSpace(attribute)) return string.Empty; var cultureInfo = Thread.CurrentThread.CurrentCulture; var textInfo = cultureInfo.TextInfo; return textInfo.ToTitleCase(attribute.Trim().ToLower()); } public int? Level(HtmlDocument htmlDocument) { var level = ExtractHtmlCardTableValue(CardHtmlTable.Level, htmlDocument); return int.TryParse(level, out var cardLevel) ? cardLevel : null; } public int? Rank(HtmlDocument htmlDocument) { var rank = ExtractHtmlCardTableValue(CardHtmlTable.Rank, htmlDocument); return int.TryParse(rank, out var cardRank) ? cardRank : null; } public string AtkDef(HtmlDocument htmlDocument) { return ExtractHtmlCardTableValue(CardHtmlTable.AtkAndDef, htmlDocument); } public string AtkLink(HtmlDocument htmlDocument) { return ExtractHtmlCardTableValue(CardHtmlTable.AtkAndLink, htmlDocument); } public string LinkArrows(HtmlDocument htmlDocument) { return ExtractHtmlCardTableValue(CardHtmlTable.LinkArrows, htmlDocument); } public string Types(HtmlDocument htmlDocument) { return ExtractHtmlCardTableValue(CardHtmlTable.Types, htmlDocument); } public string Materials(HtmlDocument htmlDocument) { return ExtractHtmlCardTableValue(CardHtmlTable.Materials, htmlDocument); } public string CardEffectTypes(HtmlDocument htmlDocument) { return ExtractHtmlCardTableValue(CardHtmlTable.CardEffectTypes, htmlDocument); } public long? PendulumScale(HtmlDocument htmlDocument) { var scale = ExtractHtmlCardTableValue(CardHtmlTable.PendulumScale, htmlDocument); return long.TryParse(scale, out var cardScale) ? cardScale : null; } #region private helpers private static HtmlNode ExtractHtmlCardTableNode(HtmlDocument htmlDocument) { return htmlDocument.DocumentNode.SelectSingleNode("//table[contains(@class, 'cardtable')]"); } private string ExtractHtmlCardTableValue(string key, HtmlDocument htmlDocument) { return ExtractHtmlCardTableValue(new[] { key }, htmlDocument); } private string ExtractHtmlCardTableValue(string[] key, HtmlDocument htmlDocument) { var htmlTableNode = ExtractHtmlCardTableNode(htmlDocument); return _cardHtmlTable.GetValue(key, htmlTableNode); } #endregion } }<file_sep>/src/wikia/processor/cardprocessor/src/Core/cardprocessor.core/Services/IFormatService.cs using System.Threading.Tasks; using cardprocessor.core.Models.Db; namespace cardprocessor.core.Services { public interface IFormatService { Task<Format> FormatByAcronym(string acronym); } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Application/cardsectionprocessor.application/ApplicationInstaller.cs using AutoMapper; using cardsectionprocessor.core.Processor; using cardsectionprocessor.core.Service; using cardsectionprocessor.core.Strategy; using cardsectionprocessor.domain.Processor; using cardsectionprocessor.domain.Service; using cardsectionprocessor.domain.Strategy; using MediatR; using Microsoft.Extensions.DependencyInjection; using System.Reflection; using cardsectionprocessor.application.MessageConsumers.CardInformation; using FluentValidation; namespace cardsectionprocessor.application { public static class ApplicationInstaller { public static IServiceCollection AddApplicationServices(this IServiceCollection services) { services .AddCqrs() .AddDomainServices() .AddValidation() .AddAutoMapper(); return services; } private static IServiceCollection AddCqrs(this IServiceCollection services) { services.AddMediatR(typeof(ApplicationInstaller).GetTypeInfo().Assembly); return services; } private static IServiceCollection AddDomainServices(this IServiceCollection services) { services.AddTransient<ICardService, CardService>(); services.AddTransient<ICardTipService, CardTipService>(); services.AddTransient<ICardRulingService, CardRulingService>(); services.AddTransient<ICardTriviaService, CardTriviaService>(); services.AddTransient<ICardSectionProcessor, CardSectionProcessor>(); services.AddTransient<ICardSectionProcessorStrategy, CardTipsProcessorStrategy>(); services.AddTransient<ICardSectionProcessorStrategy, CardRulingsProcessorStrategy>(); services.AddTransient<ICardSectionProcessorStrategy, CardTriviaProcessorStrategy>(); return services; } private static IServiceCollection AddValidation(this IServiceCollection services) { services.AddTransient<IValidator<CardInformationConsumer>, CardInformationConsumerValidator>(); return services; } } }<file_sep>/src/wikia/processor/cardprocessor/src/Domain/cardprocessor.domain/Repository/IAttributeRepository.cs using System.Collections.Generic; using System.Threading.Tasks; using cardprocessor.core.Models.Db; namespace cardprocessor.domain.Repository { public interface IAttributeRepository { Task<List<Attribute>> AllAttributes(); } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Tests/Unit/archetypeprocessor.domain.unit.tests/ServicesTests/ArchetypeServiceTests/AddTests.cs using System.Threading.Tasks; using archetypeprocessor.core.Models.Db; using archetypeprocessor.domain.Repository; using archetypeprocessor.domain.Services; using archetypeprocessor.tests.core; using NSubstitute; using NUnit.Framework; namespace archetypeprocessor.domain.unit.tests.ServicesTests.ArchetypeServiceTests { [TestFixture] [Category(TestType.Unit)] public class AddTests { private IArchetypeRepository _archetypeRepository; private ArchetypeService _sut; [SetUp] public void SetUp() { _archetypeRepository = Substitute.For<IArchetypeRepository>(); _sut = new ArchetypeService(_archetypeRepository); } [Test] public async Task Given_An_Archetype_Should_Invoke_Add_Method_Once() { // Arrange var archetype = new Archetype(); // Act await _sut.Add(archetype); // Assert await _archetypeRepository.Received(1).Add(Arg.Is(archetype)); } } }<file_sep>/src/wikia/data/carddata/src/Application/carddata.application/Configuration/QueuesSetting.cs namespace carddata.application.Configuration { public record QueuesSetting { public string CardArticleQueue { get; init; } public string SemanticArticleQueue { get; init; } } }<file_sep>/src/wikia/processor/cardprocessor/src/Tests/Unit/cardprocessor.domain.unit.tests/StrategiesTests/SpellCardTypeStrategyTests/HandlesTests.cs using cardprocessor.core.Enums; using cardprocessor.domain.Repository; using cardprocessor.domain.Strategies; using cardprocessor.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace cardprocessor.domain.unit.tests.StrategiesTests.SpellCardTypeStrategyTests { [TestFixture] [Category(TestType.Unit)] public class HandlesTests { private ICardRepository _cardRepository; private SpellCardTypeStrategy _sut; [SetUp] public void SetUp() { _cardRepository = Substitute.For<ICardRepository>(); _sut = new SpellCardTypeStrategy(_cardRepository); } [Test] public void Given_A_Spell_YugiohCardType_Should_Return_True() { // Arrange // Act var result = _sut.Handles(YugiohCardType.Spell); // Assert result.Should().BeTrue(); } [TestCase(YugiohCardType.Monster)] [TestCase(YugiohCardType.Trap)] public void Given_An_Invalid_YugiohCardType_Should_Return_False(YugiohCardType yugiohCardType) { // Arrange // Act var result = _sut.Handles(yugiohCardType); // Assert result.Should().BeFalse(); } } }<file_sep>/src/wikia/article/src/Tests/Unit/article.domain.unit.tests/ArticleListTests/ProcessorTests/ArticleCategoryProcessorTests/ProcessCategoryTests.cs using article.core.ArticleList.DataSource; using article.core.ArticleList.Processor; using article.domain.ArticleList.Processor; using article.tests.core; using NSubstitute; using NUnit.Framework; using System.Threading.Tasks; namespace article.domain.unit.tests.ArticleListTests.ProcessorTests.ArticleCategoryProcessorTests { [TestFixture] [Category(TestType.Unit)] public class ProcessCategoryTests { private IArticleCategoryDataSource _articleCategoryDataSource; private IArticleBatchProcessor _articleBatchProcessor; private ArticleCategoryProcessor _sut; [SetUp] public void SetUp() { _articleCategoryDataSource = Substitute.For<IArticleCategoryDataSource>(); _articleBatchProcessor = Substitute.For<IArticleBatchProcessor>(); _sut = new ArticleCategoryProcessor(_articleCategoryDataSource, _articleBatchProcessor); } [Test] public async Task Given_A_Category_And_PageSize_Should_Invoke_Producer_Method_Once() { // Arrange const string category = "category"; const int pageSize = 10; // Act await _sut.Process(category, pageSize); // Assert await _articleCategoryDataSource.Received(1).Producer(Arg.Any<string>(), Arg.Any<int>()).ToListAsync(); } } }<file_sep>/src/wikia/article/src/Application/article.application/ScheduledTasks/Articles/ArticleInformationTask.cs using MediatR; namespace article.application.ScheduledTasks.Articles { public class ArticleInformationTask : IRequest<ArticleInformationTaskResult> { public string Category { get; set; } public int PageSize { get; set; } } }<file_sep>/src/wikia/article/src/Tests/Unit/article.domain.unit.tests/ArticleProcessorTests.cs using System.Collections.Generic; using System.Threading.Tasks; using article.core.ArticleList.Processor; using article.core.Models; using article.domain.ArticleList.Processor; using article.tests.core; using NSubstitute; using NUnit.Framework; using wikia.Models.Article.AlphabeticalList; namespace article.domain.unit.tests { [TestFixture] [Category(TestType.Unit)] public class ArticleProcessorTests { private ArticleProcessor _sut; private IArticleItemProcessor _processor; [SetUp] public void SetUp() { _processor = Substitute.For<IArticleItemProcessor>(); _processor.Handles(Arg.Any<string>()).Returns(true); _processor.ProcessItem(Arg.Any<UnexpandedArticle>()).Returns(new ArticleTaskResult()); _sut = new ArticleProcessor(new List<IArticleItemProcessor> { _processor }); } [Test] public async Task Given_A_Category_And_An_Article_Should_Invoke_ProcessItem_Method_Once() { // Arrange const int expected = 1; const string category = "category"; // Act await _sut.Process(category, new UnexpandedArticle()); // Assert await _processor.Received(expected).ProcessItem(Arg.Any<UnexpandedArticle>()); } } }<file_sep>/src/wikia/article/src/Infrastructure/article.infrastructure/Services/Messaging/RabbitMqExchangeConstants.cs namespace article.infrastructure.Services.Messaging { public static class RabbitMqExchangeConstants { public const string YugiohHeadersArticleExchange = "yugioh.headers.article"; } }<file_sep>/src/wikia/processor/cardprocessor/src/Domain/cardprocessor.domain/Strategies/MonsterCardTypeStrategy.cs using System.Threading.Tasks; using cardprocessor.core.Enums; using cardprocessor.core.Models; using cardprocessor.core.Models.Db; using cardprocessor.core.Strategies; using cardprocessor.domain.Mappers; using cardprocessor.domain.Repository; namespace cardprocessor.domain.Strategies { public class MonsterCardTypeStrategy : ICardTypeStrategy { private readonly ICardRepository _cardRepository; public MonsterCardTypeStrategy(ICardRepository cardRepository) { _cardRepository = cardRepository; } public async Task<Card> Add(CardModel cardModel) { var newMonsterCard = CardMapper.MapToMonsterCard(cardModel); return await _cardRepository.Add(newMonsterCard); } public async Task<Card> Update(CardModel cardModel) { var cardToUpdate = await _cardRepository.CardById(cardModel.Id); if (cardToUpdate != null) { CardMapper.UpdateMonsterCardWith(cardToUpdate, cardModel); return await _cardRepository.Update(cardToUpdate); } return null; } public bool Handles(YugiohCardType yugiohCardType) { return yugiohCardType == YugiohCardType.Monster; } } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Tests/Unit/archetypeprocessor.domain.unit.tests/ServicesTests/ArchetypeCardsServiceTests.cs using System.Collections.Generic; using System.Threading.Tasks; using archetypeprocessor.domain.Repository; using archetypeprocessor.domain.Services; using archetypeprocessor.tests.core; using NSubstitute; using NUnit.Framework; namespace archetypeprocessor.domain.unit.tests.ServicesTests { [TestFixture] [Category(TestType.Unit)] public class ArchetypeCardsServiceTests { private IArchetypeCardsRepository _archetypeCardsRepository; private ArchetypeCardsService _sut; [SetUp] public void SetUp() { _archetypeCardsRepository = Substitute.For<IArchetypeCardsRepository>(); _sut = new ArchetypeCardsService(_archetypeCardsRepository); } [Test] public async Task Given_An_ArchetypeId_And_Cards_Should_Invoke_Update_Method_Once() { // Arrange const long archetypeId = 234243; var cards = new List<string>(); // Act await _sut.Update(archetypeId, cards); // Assert await _archetypeCardsRepository.Received(1).Update(Arg.Is(archetypeId), Arg.Any<IEnumerable<string>>()); } } }<file_sep>/src/wikia/data/cardsectiondata/src/Application/cardsectiondata.application/MessageConsumers/CardTipInformation/CardTipInformationConsumerHandler.cs using cardsectiondata.application.MessageConsumers.CardInformation; using cardsectiondata.core.Constants; using MediatR; using System.Threading; using System.Threading.Tasks; namespace cardsectiondata.application.MessageConsumers.CardTipInformation { public class CardTipInformationConsumerHandler : IRequestHandler<CardTipInformationConsumer, CardTipInformationConsumerResult> { private readonly IMediator _mediator; public CardTipInformationConsumerHandler(IMediator mediator) { _mediator = mediator; } public async Task<CardTipInformationConsumerResult> Handle(CardTipInformationConsumer request, CancellationToken cancellationToken) { var cardTipInformationConsumerResult = new CardTipInformationConsumerResult(); var cardInformation = new CardInformationConsumer { Category = ArticleCategory.CardTips, Message = request.Message}; var result = await _mediator.Send(cardInformation, cancellationToken); if (!result.IsSuccessful) { cardTipInformationConsumerResult.Errors = result.Errors; } return cardTipInformationConsumerResult; } } }<file_sep>/src/wikia/data/carddata/src/Application/carddata.application/ApplicationInstaller.cs using carddata.application.MessageConsumers.CardInformation; using carddata.core.Processor; using carddata.domain.Processor; using FluentValidation; using MediatR; using Microsoft.Extensions.DependencyInjection; using System.Reflection; namespace carddata.application { public static class ApplicationInstaller { public static IServiceCollection AddApplicationServices(this IServiceCollection services) { services .AddCqrs() .AddValidation() .AddDomainServices(); return services; } private static IServiceCollection AddCqrs(this IServiceCollection services) { services.AddMediatR(typeof(ApplicationInstaller).GetTypeInfo().Assembly); return services; } private static IServiceCollection AddDomainServices(this IServiceCollection services) { services.AddTransient<IArticleProcessor, ArticleProcessor>(); services.AddSingleton<IArticleDataFlow, ArticleDataFlow>(); return services; } private static IServiceCollection AddValidation(this IServiceCollection services) { services.AddTransient<IValidator<CardInformationConsumer>, CardInformationConsumerValidator>(); return services; } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Application/cardsectionprocessor.application/MessageConsumers/CardInformation/CardInformationConsumerHandler.cs using System.Linq; using System.Threading; using System.Threading.Tasks; using cardsectionprocessor.core.Models; using cardsectionprocessor.core.Processor; using FluentValidation; using MediatR; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace cardsectionprocessor.application.MessageConsumers.CardInformation { public class CardInformationConsumerHandler : IRequestHandler<CardInformationConsumer, CardInformationConsumerResult> { private readonly ICardSectionProcessor _cardSectionProcessor; private readonly IValidator<CardInformationConsumer> _validator; private readonly ILogger<CardInformationConsumerHandler> _logger; public CardInformationConsumerHandler(ICardSectionProcessor cardSectionProcessor, IValidator<CardInformationConsumer> validator, ILogger<CardInformationConsumerHandler> logger) { _cardSectionProcessor = cardSectionProcessor; _validator = validator; _logger = logger; } public async Task<CardInformationConsumerResult> Handle(CardInformationConsumer request, CancellationToken cancellationToken) { var cardInformationResult = new CardInformationConsumerResult(); var validationResults = _validator.Validate(request); if (validationResults.IsValid) { var cardSectionData = JsonConvert.DeserializeObject<CardSectionMessage>(request.Message); _logger.LogInformation("Processing category {@Category} '{@Name}'", request.Category, cardSectionData.Name); var results = await _cardSectionProcessor.Process(request.Category, cardSectionData); _logger.LogInformation("Finished processing category {@Category} '{@Name}'", request.Category, cardSectionData.Name); if (!results.IsSuccessful) { cardInformationResult.Errors.AddRange(results.Errors); } } else { cardInformationResult.Errors = validationResults.Errors.Select(err => err.ErrorMessage).ToList(); } return cardInformationResult; } } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Core/archetypeprocessor.core/Models/DownloadImage.cs using System; namespace archetypeprocessor.core.Models { public class DownloadImage { public Uri RemoteImageUrl { get; set; } public string ImageFileName { get; set; } public string ImageFolderPath { get; set; } } }<file_sep>/src/wikia/data/cardsectiondata/src/Application/cardsectiondata.application/MessageConsumers/CardTipInformation/CardTipInformationConsumer.cs using MediatR; namespace cardsectiondata.application.MessageConsumers.CardTipInformation { public class CardTipInformationConsumer : IRequest<CardTipInformationConsumerResult> { public string Message { get; set; } } }<file_sep>/src/wikia/data/cardsectiondata/src/Application/cardsectiondata.application/MessageConsumers/CardTriviaInformation/CardTriviaInformationConsumer.cs using MediatR; namespace cardsectiondata.application.MessageConsumers.CardTriviaInformation { public class CardTriviaInformationConsumer : IRequest<CardTriviaInformationConsumerResult> { public string Message { get; set; } } }<file_sep>/src/wikia/article/src/Infrastructure/article.infrastructure/Services/Messaging/RabbitMqQueueConstants.cs namespace article.infrastructure.Services.Messaging { public static class RabbitMqQueueConstants { public const string CardArticleQueue = "cardarticle"; public const string SemanticQueue = "semanticcard"; } }<file_sep>/src/wikia/article/src/Domain/article.domain/Banlist/Processor/IBanlistProcessor.cs using System.Threading.Tasks; using article.core.Enums; using article.core.Models; namespace article.domain.Banlist.Processor { public interface IBanlistProcessor { Task<ArticleBatchTaskResult> Process(BanlistType banlistType); } }<file_sep>/src/services/Cards.API/src/Domain/Cards.Domain/Models/Monsters/LinkMonster.cs using System.Collections.Generic; namespace Cards.Domain.Models.Monsters { public sealed class LinkMonster { public string Name { get; set; } public string Attribute { get; set; } public int LinkRating { get; set; } public IReadOnlySet<string> LinkArrows { get; } = new HashSet<string>(); public IReadOnlySet<string> Types { get; } = new HashSet<string>(); public string Effect { get; set; } public int Attack { get; set; } } }<file_sep>/src/services/Cards.API/src/Domain/Cards.Domain/Enums/SpellCardType.cs namespace Cards.Domain.Enums { public enum SpellCardType { Normal, QuickPlay, Continuous, Ritual, Equip, Field } }<file_sep>/src/wikia/processor/cardprocessor/src/Core/cardprocessor.core/Services/ISubCategoryService.cs using System.Collections.Generic; using System.Threading.Tasks; using cardprocessor.core.Models.Db; namespace cardprocessor.core.Services { public interface ISubCategoryService { Task<List<SubCategory>> AllSubCategories(); } }<file_sep>/src/wikia/data/carddata/src/Presentation/carddata/Program.cs using carddata.application; using carddata.application.Configuration; using carddata.infrastructure; using carddata.Services; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using System; namespace carddata { internal class Program { internal static void Main(string[] args) { try { CreateHostBuilder(args).Build().Run(); } catch (Exception ex) { if (Log.Logger == null || Log.Logger.GetType().Name == "SilentLogger") { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Console() .CreateLogger(); } Log.Fatal(ex, "Host terminated unexpectedly"); throw; } finally { Log.CloseAndFlush(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { services.AddLogging(); //configuration settings services.Configure<AppSettings>(hostContext.Configuration.GetSection(nameof(AppSettings))); services.Configure<RabbitMqSettings>(hostContext.Configuration.GetSection(nameof(RabbitMqSettings))); // hosted service //services.AddHostedService<CardDataHostedService>(); services.AddHostedService<SemanticCardDataHostedService>(); services.AddApplicationServices(); services.AddInfrastructureServices(); }) .UseSerilog((hostingContext, loggerConfiguration) => { loggerConfiguration .ReadFrom.Configuration(hostingContext.Configuration) .Enrich.WithProperty("ApplicationName", typeof(Program).Assembly.GetName().Name) .Enrich.WithProperty("Environment", hostingContext.HostingEnvironment); }); } // internal class Program // { // static async Task Main(string[] args) // { // AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper; // var hostBuilder = CreateHostBuilder(args); // var isService = !(Debugger.IsAttached || args.Contains("--console")); // if (isService) // { // var pathToExe = Process.GetCurrentProcess().MainModule?.FileName; // var pathToContentRoot = Path.GetDirectoryName(pathToExe); // Directory.SetCurrentDirectory(pathToContentRoot); // } // if (isService) // await hostBuilder.RunAsServiceAsync(); // else // await hostBuilder.RunConsoleAsync(); // } // private static IHostBuilder CreateHostBuilder(string[] args) // { // var hostBuilder = new HostBuilder() // .ConfigureLogging((hostContext, config) => // { // config.AddConsole(); // config.AddDebug(); // }) // .ConfigureHostConfiguration(config => // { //#if DEBUG // config.AddEnvironmentVariables(prefix: "ASPNETCORE_"); //#else // config.AddEnvironmentVariables(); //#endif // }) // .ConfigureAppConfiguration((hostContext, config) => // { // config.SetBasePath(Directory.GetCurrentDirectory()); // config.AddJsonFile("appsettings.json", false, true); // config.AddCommandLine(args); //#if DEBUG // config.AddUserSecrets<Program>(); //#endif // }) // .ConfigureServices((hostContext, services) => // { // services.AddLogging(); // //configuration settings // services.Configure<AppSettings>(hostContext.Configuration.GetSection(nameof(AppSettings))); // services.Configure<RabbitMqSettings>(hostContext.Configuration.GetSection(nameof(RabbitMqSettings))); // // hosted service // services.AddHostedService<CardDataHostedService>(); // services.AddApplicationServices(); // services.AddInfrastructureServices(); // }) // .UseConsoleLifetime() // .UseSerilog(); // return hostBuilder; // } // private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs ex) // { // Log.Logger.Error("Unhandled exception occurred. Exception: {@Exception}", ex); // } // } }<file_sep>/src/wikia/data/banlistdata/src/Domain/banlistdata.domain/Processor/ArticleDataFlow.cs using banlistdata.core.Models; using banlistdata.core.Processor; using banlistdata.domain.Services.Messaging; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; namespace banlistdata.domain.Processor { public class ArticleDataFlow : IArticleDataFlow { private readonly BufferBlock<Article> _articleBufferBlock; private readonly ConcurrentDictionary<Guid, TaskCompletionSource<ArticleCompletion>> _jobs; public ArticleDataFlow(IBanlistProcessor banlistProcessor, IBanlistDataQueue banlistDataQueue) { _jobs = new ConcurrentDictionary<Guid, TaskCompletionSource<ArticleCompletion>>(); // Data flow options var maxDegreeOfParallelism = Environment.ProcessorCount; var nonGreedy = new ExecutionDataflowBlockOptions { BoundedCapacity = maxDegreeOfParallelism, MaxDegreeOfParallelism = maxDegreeOfParallelism }; // Pipeline members _articleBufferBlock = new BufferBlock<Article>(); var banlistProcessorTransformBlock = new TransformBlock<Article, ArticleProcessed>(article => banlistProcessor.Process(article), nonGreedy); var publishBanlistTransformBlock = new TransformBlock<ArticleProcessed, YugiohBanlistCompletion>(articleProcessed => banlistDataQueue.Publish(articleProcessed), nonGreedy); var publishToQueueActionBlock = new ActionBlock<YugiohBanlistCompletion>(yugiohCardCompletion => FinishedProcessing(yugiohCardCompletion)); // Form the pipeline _articleBufferBlock.LinkTo(banlistProcessorTransformBlock); banlistProcessorTransformBlock.LinkTo(publishBanlistTransformBlock); publishBanlistTransformBlock.LinkTo(publishToQueueActionBlock); } public async Task<ArticleCompletion> ProcessDataFlow(Article article) { var taggedData = TagInputData(article); var (jobId, taskCompletionSource) = CreateJob(taggedData); var isJobAdded = _jobs.TryAdd(jobId, taskCompletionSource); if (isJobAdded) await _articleBufferBlock.SendAsync(article); else { taskCompletionSource.SetResult(new ArticleCompletion { Message = article, Exception = new Exception($"Job not created for item with id {article.Id}") }); } return await taskCompletionSource.Task; } #region private helper private static KeyValuePair<Guid, Article> TagInputData(Article data) { return new KeyValuePair<Guid, Article>(data.CorrelationId, data); } private static KeyValuePair<Guid, TaskCompletionSource<ArticleCompletion>> CreateJob(KeyValuePair<Guid, Article> taggedData) { var id = taggedData.Key; var jobCompletionSource = new TaskCompletionSource<ArticleCompletion>(); return new KeyValuePair<Guid, TaskCompletionSource<ArticleCompletion>>(id, jobCompletionSource); } private void FinishedProcessing(YugiohBanlistCompletion yugiohBanlistCompletion) { _jobs.TryRemove(yugiohBanlistCompletion.Article.CorrelationId, out var job); if (yugiohBanlistCompletion.IsSuccessful) { job.SetResult(new ArticleCompletion { IsSuccessful = true, Message = yugiohBanlistCompletion.Article }); } else { var exceptionMessage = $"Card Article with id '{yugiohBanlistCompletion.Article.Id}' and correlation id {yugiohBanlistCompletion.Article.CorrelationId} not processed."; job.SetException(new Exception(exceptionMessage)); } } #endregion } }<file_sep>/src/wikia/article/src/Domain/article.domain/Settings/AppSettings.cs namespace article.domain.Settings { public record AppSettings { public string WikiaDomainUrl { get; init; } public string Category { get; init; } public int PageSize { get; init; } } }<file_sep>/src/wikia/data/archetypedata/src/Presentation/archetypedata/Services/ArchetypeCardDataHostedService.cs using archetypedata.application.Configuration; using archetypedata.application.MessageConsumers.ArchetypeCardInformation; using MediatR; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Text; using System.Threading; using System.Threading.Tasks; namespace archetypedata.Services { public sealed class ArchetypeCardDataHostedService : BackgroundService { private const string ArchetypeCardArticleQueue = "archetype-cards-article"; private readonly ILogger<ArchetypeCardDataHostedService> _logger; private readonly IOptions<RabbitMqSettings> _rabbitMqOptions; private readonly IOptions<AppSettings> _appSettingsOptions; private readonly IMediator _mediator; private ConnectionFactory _factory; private IConnection _connection; private IModel _channel; public ArchetypeCardDataHostedService ( ILogger<ArchetypeCardDataHostedService> logger, IOptions<RabbitMqSettings> rabbitMqOptions, IOptions<AppSettings> appSettingsOptions, IMediator mediator ) { _logger = logger; _rabbitMqOptions = rabbitMqOptions; _appSettingsOptions = appSettingsOptions; _mediator = mediator; } protected override Task ExecuteAsync(CancellationToken stoppingToken) { stoppingToken.ThrowIfCancellationRequested(); _factory = new ConnectionFactory { HostName = _rabbitMqOptions.Value.Host, UserName = _rabbitMqOptions.Value.Username, Password = _<PASSWORD>.Value.<PASSWORD>, DispatchConsumersAsync = true }; _connection = _factory.CreateConnection(); _channel = _connection.CreateModel(); _channel.BasicQos(0, 1, false); var consumer = new AsyncEventingBasicConsumer(_channel); consumer.Received += async (model, ea) => { try { var body = ea.Body.ToArray(); var message = Encoding.UTF8.GetString(body); var result = await _mediator.Send(new ArchetypeCardInformationConsumer { Message = message }, stoppingToken); if (result.IsSuccessful) { _channel.BasicAck(ea.DeliveryTag, false); } else { _channel.BasicNack(ea.DeliveryTag, false, false); } } catch (Exception ex) { _logger.LogError("RabbitMq Consumer: " + ArchetypeCardArticleQueue + " exception. Exception: {@Exception}", ex); } }; consumer.Shutdown += OnArchetypeCardArticleConsumerShutdown; consumer.Registered += OnArchetypeCardArticleConsumerRegistered; consumer.Unregistered += OnArchetypeCardArticleConsumerUnregistered; consumer.ConsumerCancelled += OnArchetypeCardArticleConsumerCancelled; _channel.BasicConsume(ArchetypeCardArticleQueue, false, consumer); return Task.CompletedTask; } #region private helper private Task OnArchetypeCardArticleConsumerCancelled(object sender, ConsumerEventArgs e) { _logger.LogInformation("Consumer '{ArchetypeCardArticleQueue}' Cancelled", ArchetypeCardArticleQueue); return Task.CompletedTask; } private Task OnArchetypeCardArticleConsumerUnregistered(object sender, ConsumerEventArgs e) { _logger.LogInformation("Consumer '{ArchetypeCardArticleQueue}' Unregistered", ArchetypeCardArticleQueue); return Task.CompletedTask; } private Task OnArchetypeCardArticleConsumerRegistered(object sender, ConsumerEventArgs e) { _logger.LogInformation("Consumer '{ArchetypeCardArticleQueue}' Registered", ArchetypeCardArticleQueue); return Task.CompletedTask; } private Task OnArchetypeCardArticleConsumerShutdown(object sender, ShutdownEventArgs e) { _logger.LogInformation("Consumer '{ArchetypeCardArticleQueue}' Shutdown", ArchetypeCardArticleQueue); return Task.CompletedTask; } #endregion public override void Dispose() { _channel.Close(); _connection.Close(); base.Dispose(); } } }<file_sep>/src/services/Cards.API/src/Tests/Unit/Cards.Domain.Unit.Tests/Class1.cs using System; namespace Cards.Domain.Unit.Tests { public class Class1 { } } <file_sep>/src/wikia/processor/imageprocessor/src/Tests/Unit/imageprocessor.core.unit.tests/HelpersTests/StringHelpersTests.cs using FluentAssertions; using imageprocessor.core.Helpers; using imageprocessor.tests.core; using NUnit.Framework; namespace imageprocessor.core.unit.tests.HelpersTests { [TestFixture] [Category(TestType.Unit)] public class StringHelpersTests { [TestCase("image*.png", "image.png")] [TestCase("image<.png", "image.png")] [TestCase("image>.png", "image.png")] [TestCase("image|.png", "image.png")] public void Given_An_Invalid_FileName_Should_Return_Santized_FileName(string filename, string expected) { // Arrange // Act var result = filename.SanitizeFileName(); // Assert result.Should().BeEquivalentTo(expected); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Configuration/ExchangeSetting.cs using System.Collections.Generic; namespace cardprocessor.application.Configuration { public class ExchangeSetting { public Dictionary<string, string> Headers { get; set; } public byte PersistentMode { get; set; } } }<file_sep>/src/wikia/semanticsearch/README.md ![alt text](https://fablecode.visualstudio.com/Yugioh%20Insight/_apis/build/status/Build-SemanticSearch "Visual studio team services build status") # Semantic Search For complex card searches<file_sep>/src/wikia/data/archetypedata/README.md ![alt text](https://fablecode.visualstudio.com/Yugioh%20Insight/_apis/build/status/Build-ArchetypeData "Visual studio team services build status") # Archetype Data Amalgamates data about a [Yu-Gi-Oh](http://www.yugioh-card.com/uk/) archetypes, from different sources. <file_sep>/src/wikia/processor/banlistprocessor/src/Domain/banlistprocessor.domain/banlistprocessor.domain/Mappings/Profiles/BanlistProfile.cs using AutoMapper; using banlistprocessor.core.Models; using banlistprocessor.core.Models.Db; namespace banlistprocessor.domain.Mappings.Profiles { public class BanlistProfile : Profile { public BanlistProfile() { CreateMap<YugiohBanlist, Banlist>() .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.ArticleId)) .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Title)) .ForMember(dest => dest.ReleaseDate, opt => opt.MapFrom(src => src.StartDate)); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Infrastructure/cardprocessor.infrastructure/Repository/TypeRepository.cs using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using cardprocessor.core.Models.Db; using cardprocessor.domain.Repository; using cardprocessor.infrastructure.Database; using Microsoft.EntityFrameworkCore; namespace cardprocessor.infrastructure.Repository { public class TypeRepository : ITypeRepository { private readonly YgoDbContext _dbContext; public TypeRepository(YgoDbContext dbContext) { _dbContext = dbContext; } public Task<List<Type>> AllTypes() { return _dbContext.Type.OrderBy(t => t.Name).ToListAsync(); } } }<file_sep>/src/wikia/data/cardsectiondata/src/Core/cardsectiondata.core/Processor/IArticleProcessor.cs using cardsectiondata.core.Models; using System.Threading.Tasks; namespace cardsectiondata.core.Processor { public interface IArticleProcessor { Task<ArticleTaskResult> Process(string category, Article article); } } <file_sep>/src/wikia/semanticsearch/src/Core/semanticsearch.core/Model/SemanticCardPublishResult.cs using semanticsearch.core.Exceptions; namespace semanticsearch.core.Model { public class SemanticCardPublishResult { public bool IsSuccessful { get; set; } public SemanticCard Card { get; set; } public SemanticCardPublishException Exception { get; set; } } }<file_sep>/src/wikia/article/src/Tests/Unit/article.application.unit.tests/ScheduledTasksTests/ArchetypeInformationTaskHandlerTests.cs using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using article.application.ScheduledTasks.Archetype; using article.core.ArticleList.Processor; using article.core.Models; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace article.application.unit.tests.ScheduledTasksTests { [TestFixture] public class ArchetypeInformationTaskHandlerTests { private ArchetypeInformationTaskHandler _sut; private IArticleCategoryProcessor _articleCategoryProcessor; [SetUp] public void Setup() { _articleCategoryProcessor = Substitute.For<IArticleCategoryProcessor>(); _sut = new ArchetypeInformationTaskHandler(_articleCategoryProcessor, new ArchetypeInformationTaskValidator()); } [Test] public async Task Given_An_Invalid_ArchetypeInformationTask_Should_Return_Errors() { // Arrange var task = new ArchetypeInformationTask(); // Act var result = await _sut.Handle(task, CancellationToken.None); // Assert result.Errors.Should().NotBeEmpty(); } [Test] public async Task Given_An_Invalid_ArchetypeInformationTask_Should_Not_Execute_Process() { // Arrange var task = new ArchetypeInformationTask(); // Act await _sut.Handle(task, CancellationToken.None); // Assert await _articleCategoryProcessor.DidNotReceive().Process(Arg.Any<IEnumerable<string>>(), Arg.Any<int>()); } [Test] public async Task Given_An_Valid_ArchetypeInformationTask_Should_Execute_Process() { // Arrange var task = new ArchetypeInformationTask { Category = "category", PageSize = 1 }; _articleCategoryProcessor.Process(Arg.Any<string>(), Arg.Any<int>()).Returns(new ArticleBatchTaskResult()); // Act await _sut.Handle(task, CancellationToken.None); // Assert await _articleCategoryProcessor.Received(1).Process(Arg.Any<string>(), Arg.Any<int>()); } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Application/cardsectionprocessor.application/MessageConsumers/CardRulingInformation/CardRulingInformationConsumer.cs using MediatR; namespace cardsectionprocessor.application.MessageConsumers.CardRulingInformation { public class CardRulingInformationConsumer : IRequest<CardRulingInformationConsumerResult> { public string Message { get; set; } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Application/cardsectionprocessor.application/MessageConsumers/CardRulingInformation/CardRulingInformationConsumerResult.cs using System.Collections.Generic; using System.Linq; namespace cardsectionprocessor.application.MessageConsumers.CardRulingInformation { public class CardRulingInformationConsumerResult { public bool IsSuccessful => !Errors.Any(); public string Message { get; set; } public List<string> Errors { get; set; } = new List<string>(); } }<file_sep>/src/wikia/processor/cardprocessor/src/Tests/Unit/cardprocessor.application.unit.tests/HelperTests/CardTests/MapBasicCardInformationTests.cs using cardprocessor.application.Enums; using cardprocessor.application.Helpers.Cards; using cardprocessor.application.Models.Cards.Input; using cardprocessor.core.Models; using cardprocessor.tests.core; using FluentAssertions; using NUnit.Framework; namespace cardprocessor.application.unit.tests.HelperTests.CardTests { [TestFixture] [Category(TestType.Unit)] public class MapBasicCardInformationTests { [TestCase("Spell", YgoCardType.Spell)] [TestCase("Trap", YgoCardType.Trap)] [TestCase("speLl", YgoCardType.Spell)] [TestCase("traP", YgoCardType.Trap)] public void Given_A_Valid_SpellOrTrap_CardType_Should_Map_CardType_To_Correct_YgoCardType(string cardType, YgoCardType expected) { // Arrange var yugiohCard = new YugiohCard { Property = "Normal", CardType = cardType }; var cardInputModel = new CardInputModel(); // Act var result = CardHelper.MapBasicCardInformation(yugiohCard, cardInputModel); // Assert result.CardType.Should().Be(expected); } [TestCase("Monster", YgoCardType.Monster)] [TestCase("monsTer", YgoCardType.Monster)] public void Given_A_Valid_Monster_CardType_Should_Map_CardType_To_Correct_YgoCardType(string cardType, YgoCardType expected) { // Arrange var yugiohCard = new YugiohCard { Attribute = "Dark", Types = "Effect/Ritual", CardType = cardType }; var cardInputModel = new CardInputModel(); // Act var result = CardHelper.MapBasicCardInformation(yugiohCard, cardInputModel); // Assert result.CardType.Should().Be(expected); } [Test] public void Given_A_Valid_YugiohCard_With_A_Name_Should_Map_To_CardInputModel_Name_Property() { // Arrange const string expected = "Darkness Dragon"; var yugiohCard = new YugiohCard { Name = "<NAME>", CardNumber = "543534", Attribute = "Dark", Types = "Effect/Ritual", CardType = "Monster", ImageUrl = "https://vignette.wikia.nocookie.net/yugioh/images/b/b4/BlueEyesWhiteDragon-LED3-EN-C-1E.png/revision/latest/scale-to-width-down/300?cb=20180928161125" }; var cardInputModel = new CardInputModel(); // Act var result = CardHelper.MapBasicCardInformation(yugiohCard, cardInputModel); // Assert result.Name.Should().Be(expected); } [Test] public void Given_A_Valid_YugiohCard_With_A_Description_Should_Map_To_CardInputModel_Description_Property() { // Arrange const string expected = "Amazing card!"; var yugiohCard = new YugiohCard { Name = "<NAME>", Description = "Amazing card!", CardNumber = "543534", Attribute = "Dark", Types = "Effect/Ritual", CardType = "Monster", ImageUrl = "https://vignette.wikia.nocookie.net/yugioh/images/b/b4/BlueEyesWhiteDragon-LED3-EN-C-1E.png/revision/latest/scale-to-width-down/300?cb=20180928161125" }; var cardInputModel = new CardInputModel(); // Act var result = CardHelper.MapBasicCardInformation(yugiohCard, cardInputModel); // Assert result.Description.Should().Be(expected); } } }<file_sep>/src/wikia/processor/imageprocessor/src/Application/imageprocessor.application/Configuration/RabbitMqSettings.cs using System.Collections.Generic; namespace imageprocessor.application.Configuration { public class RabbitMqSettings { public string Host { get; set; } public string Username { get; set; } public string Password { get; set; } public string ContentType { get; set; } public Dictionary<string, QueueSetting> Queues { get; set; } public Dictionary<string, ExchangeSetting> Exchanges { get; set; } } }<file_sep>/src/wikia/data/carddata/src/Application/carddata.application/MessageConsumers/CardInformation/CardInformationConsumerResult.cs using System.Collections.Generic; using carddata.core.Models; namespace carddata.application.MessageConsumers.CardInformation { public class CardInformationConsumerResult { public ArticleConsumerResult ArticleConsumerResult { get; set; } public List<string> Errors { get; set; } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Core/cardsectionprocessor.core/Service/ICardTriviaService.cs using System.Collections.Generic; using System.Threading.Tasks; using cardsectionprocessor.core.Models.Db; namespace cardsectionprocessor.core.Service { public interface ICardTriviaService { Task DeleteByCardId(long id); Task Update(List<TriviaSection> triviaSections); } }<file_sep>/src/wikia/semanticsearch/src/Tests/Integration/semanticsearch.infrastructure.integration.tests/WebPageTests/SemanticSearchResultsWebPageTests/LoadTests.cs using FluentAssertions; using NUnit.Framework; using semanticsearch.infrastructure.WebPage; using semanticsearch.tests.core; using System; namespace semanticsearch.infrastructure.integration.tests.WebPageTests.SemanticSearchResultsWebPageTests { [TestFixture] [Category(TestType.Integration)] public class LoadTests { private SemanticSearchResultsWebPage _sut; [SetUp] public void SetUp() { _sut = new SemanticSearchResultsWebPage(new HtmlWebPage()); } [Test] public void Given_Semantic_WebPage_Url_Should_Load_WebPage_Without_Throwing_Any_Exceptions() { // Arrange const string url = "http://yugioh.fandom.com/index.php?title=Special%3AAsk&q=%5B%5BClass+1%3A%3AOfficial%5D%5D+%5B%5BCard+type%3A%3ANormal+Monster%5D%5D&po=%3FJapanese+name%0D%0A%3FRank%0D%0A%3FLevel%0D%0A%3FAttribute%0D%0A%3FType%0D%0A%3FMonster+type%0D%0A%3FATK+string%3DATK%0D%0A%3FDEF+string%3DDEF%0D%0A&eq=yes&p%5Bformat%5D=broadtable&sort_num=&order_num=ASC&p%5Blimit%5D=500&p%5Boffset%5D=&p%5Blink%5D=all&p%5Bsort%5D=&p%5Bheaders%5D=show&p%5Bmainlabel%5D=&p%5Bintro%5D=&p%5Boutro%5D=&p%5Bsearchlabel%5D=%E2%80%A6+further+results&p%5Bdefault%5D=&p%5Bclass%5D=+sortable+wikitable+smwtable+card-list&eq=yes"; // Act Action act = () => _sut.Load(url); // Assert act.Should().NotThrow(); } [Test] public void Given_Semantic_WebPage_Url_Should_Load_WebPage_And_All_Card_TableRows() { // Arrange const string url = "http://yugioh.fandom.com/index.php?title=Special%3AAsk&q=%5B%5BClass+1%3A%3AOfficial%5D%5D+%5B%5BCard+type%3A%3ANormal+Monster%5D%5D&po=%3FJapanese+name%0D%0A%3FRank%0D%0A%3FLevel%0D%0A%3FAttribute%0D%0A%3FType%0D%0A%3FMonster+type%0D%0A%3FATK+string%3DATK%0D%0A%3FDEF+string%3DDEF%0D%0A&eq=yes&p%5Bformat%5D=broadtable&sort_num=&order_num=ASC&p%5Blimit%5D=500&p%5Boffset%5D=&p%5Blink%5D=all&p%5Bsort%5D=&p%5Bheaders%5D=show&p%5Bmainlabel%5D=&p%5Bintro%5D=&p%5Boutro%5D=&p%5Bsearchlabel%5D=%E2%80%A6+further+results&p%5Bdefault%5D=&p%5Bclass%5D=+sortable+wikitable+smwtable+card-list&eq=yes"; // Act _sut.Load(url); // Assert _sut.TableRows.Should().HaveCountGreaterOrEqualTo(181); } [Test] public void Given_Semantic_WebPage_Url_Should_Next_Page_Should_Not_Be_Null() { // Arrange const string url = "http://yugioh.fandom.com/index.php?title=Special%3AAsk&q=%5B%5BClass+1%3A%3AOfficial%5D%5D+%5B%5BCard+type%3A%3ANormal+Monster%5D%5D&po=%3FJapanese+name%0D%0A%3FRank%0D%0A%3FLevel%0D%0A%3FAttribute%0D%0A%3FType%0D%0A%3FMonster+type%0D%0A%3FATK+string%3DATK%0D%0A%3FDEF+string%3DDEF%0D%0A&eq=yes&p%5Bformat%5D=broadtable&sort_num=&order_num=ASC&p%5Blimit%5D=500&p%5Boffset%5D=&p%5Blink%5D=all&p%5Bsort%5D=&p%5Bheaders%5D=show&p%5Bmainlabel%5D=&p%5Bintro%5D=&p%5Boutro%5D=&p%5Bsearchlabel%5D=%E2%80%A6+further+results&p%5Bdefault%5D=&p%5Bclass%5D=+sortable+wikitable+smwtable+card-list&eq=yes"; // Act _sut.Load(url); // Assert _sut.NextPage.Should().NotBeNull(); } [Test] public void Given_Semantic_WebPage_Url_Should_Next_Page_Should_Not_Be_Null_Or_Empty() { // Arrange const string url = "http://yugioh.fandom.com/index.php?title=Special%3AAsk&q=%5B%5BClass+1%3A%3AOfficial%5D%5D+%5B%5BCard+type%3A%3ANormal+Monster%5D%5D&po=%3FJapanese+name%0D%0A%3FRank%0D%0A%3FLevel%0D%0A%3FAttribute%0D%0A%3FType%0D%0A%3FMonster+type%0D%0A%3FATK+string%3DATK%0D%0A%3FDEF+string%3DDEF%0D%0A&eq=yes&p%5Bformat%5D=broadtable&sort_num=&order_num=ASC&p%5Blimit%5D=500&p%5Boffset%5D=&p%5Blink%5D=all&p%5Bsort%5D=&p%5Bheaders%5D=show&p%5Bmainlabel%5D=&p%5Bintro%5D=&p%5Boutro%5D=&p%5Bsearchlabel%5D=%E2%80%A6+further+results&p%5Bdefault%5D=&p%5Bclass%5D=+sortable+wikitable+smwtable+card-list&eq=yes"; // Act _sut.Load(url); // Assert _sut.NextPageLink().Should().NotBeNullOrEmpty(); } [Test] public void Given_Semantic_WebPage_Url_HasNextPage_Should_Be_True() { // Arrange const string url = "http://yugioh.fandom.com/index.php?title=Special%3AAsk&q=%5B%5BClass+1%3A%3AOfficial%5D%5D+%5B%5BCard+type%3A%3ANormal+Monster%5D%5D&po=%3FJapanese+name%0D%0A%3FRank%0D%0A%3FLevel%0D%0A%3FAttribute%0D%0A%3FType%0D%0A%3FMonster+type%0D%0A%3FATK+string%3DATK%0D%0A%3FDEF+string%3DDEF%0D%0A&eq=yes&p%5Bformat%5D=broadtable&sort_num=&order_num=ASC&p%5Blimit%5D=500&p%5Boffset%5D=&p%5Blink%5D=all&p%5Bsort%5D=&p%5Bheaders%5D=show&p%5Bmainlabel%5D=&p%5Bintro%5D=&p%5Boutro%5D=&p%5Bsearchlabel%5D=%E2%80%A6+further+results&p%5Bdefault%5D=&p%5Bclass%5D=+sortable+wikitable+smwtable+card-list&eq=yes"; // Act _sut.Load(url); // Assert _sut.HasNextPage.Should().BeTrue(); } } }<file_sep>/src/services/Cards.API/src/Application/Cards.Application/ApplicationInstaller.cs using System; using System.Reflection; using MediatR; using Microsoft.Extensions.DependencyInjection; namespace Cards.Application { public static class ApplicationInstaller { public static IServiceCollection AddApplicationServices(this IServiceCollection services) { return services .AddCqrs(); } private static IServiceCollection AddCqrs(this IServiceCollection services) { services.AddMediatR(typeof(ApplicationInstaller).GetTypeInfo().Assembly); return services; } } } <file_sep>/src/wikia/article/src/Domain/article.domain/ArticleList/Processor/ArticleBatchProcessor.cs using article.core.ArticleList.Processor; using article.core.Exceptions; using article.core.Models; using System; using System.Threading.Tasks; using wikia.Models.Article.AlphabeticalList; namespace article.domain.ArticleList.Processor { public sealed class ArticleBatchProcessor : IArticleBatchProcessor { private readonly IArticleProcessor _articleProcessor; public ArticleBatchProcessor(IArticleProcessor articleProcessor) { _articleProcessor = articleProcessor; } public async Task<ArticleBatchTaskResult> Process(string category, UnexpandedArticle[] articles) { if (string.IsNullOrWhiteSpace(category)) throw new ArgumentException(nameof(category)); if (articles == null) throw new ArgumentException(nameof(articles)); var response = new ArticleBatchTaskResult(); foreach (var article in articles) { try { var result = await _articleProcessor.Process(category, article); if (result.IsSuccessfullyProcessed) response.Processed += 1; } catch (Exception ex) { response.Failed.Add(new ArticleException { Article = article, Exception = ex }); } } return response; } } }<file_sep>/src/wikia/article/src/Tests/Unit/article.application.unit.tests/DecoratorsTests/LoggerTests/ArticleProcessorLoggerDecoratorTests.cs using System; using System.Threading.Tasks; using article.application.Decorators.Loggers; using article.core.ArticleList.Processor; using article.core.Models; using article.domain.ArticleList.Processor; using article.tests.core; using Microsoft.Extensions.Logging; using NSubstitute; using NSubstitute.ExceptionExtensions; using NUnit.Framework; using wikia.Models.Article.AlphabeticalList; namespace article.application.unit.tests.DecoratorsTests.LoggerTests { [TestFixture] [Category(TestType.Unit)] public class ArticleProcessorLoggerDecoratorTests { private IArticleProcessor _articleProcessor; private ILogger<ArticleProcessor> _logger; private ArticleProcessorLoggerDecorator _sut; [SetUp] public void SetUp() { _articleProcessor = Substitute.For<IArticleProcessor>(); _logger = Substitute.For<ILogger<ArticleProcessor>>(); _sut = new ArticleProcessorLoggerDecorator(_articleProcessor, _logger); } [Test] public async Task Given_A_Category_And_A_Article_Should_Invoke_LogInformation_Method_Twice() { // Arrange const int expected = 2; _articleProcessor.Process(Arg.Any<string>(), Arg.Any<UnexpandedArticle>()).Returns(new ArticleTaskResult()); // Act await _sut.Process("category", new UnexpandedArticle()); // Assert _logger.Received(expected).Log(LogLevel.Information, Arg.Any<EventId>(), Arg.Any<object>(), Arg.Any<Exception>(), Arg.Any<Func<object, Exception, string>>()); } [Test] public async Task Given_A_Category_And_A_Article_If_ArgumentNullException_Is_Thrown_Should_Invoke_LogError_Method_Once() { // Arrange const int expected = 1; _articleProcessor.Process(Arg.Any<string>(), Arg.Any<UnexpandedArticle>()).Throws<ArgumentNullException>(); // Act try { await _sut.Process("category", new UnexpandedArticle()); } catch (ArgumentNullException) { } // Assert _logger.Received(expected).Log(LogLevel.Error, Arg.Any<EventId>(), Arg.Any<object>(), Arg.Any<Exception>(), Arg.Any<Func<object, Exception, string>>()); } [Test] public async Task Given_A_Category_And_A_Article_If_InvalidOperationException_Is_Thrown_Should_Invoke_LogError_Method_Once() { // Arrange const int expected = 1; _articleProcessor.Process(Arg.Any<string>(), Arg.Any<UnexpandedArticle>()).Throws<InvalidOperationException>(); // Act try { await _sut.Process("category", new UnexpandedArticle()); } catch (InvalidOperationException) { } // Assert _logger.Received(expected).Log(LogLevel.Error, Arg.Any<EventId>(), Arg.Any<object>(), Arg.Any<Exception>(), Arg.Any<Func<object, Exception, string>>()); } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Core/cardsectionprocessor.core/Processor/ICardSectionProcessor.cs using System.Threading.Tasks; using cardsectionprocessor.core.Models; namespace cardsectionprocessor.core.Processor { public interface ICardSectionProcessor { Task<CardSectionDataTaskResult<CardSectionMessage>> Process(string category, CardSectionMessage cardSectionData); } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Mappings/Profiles/AttributeProfile.cs using AutoMapper; using cardprocessor.application.Dto; using cardprocessor.core.Models.Db; namespace cardprocessor.application.Mappings.Profiles { public class AttributeProfile : Profile { public AttributeProfile() { CreateMap<Attribute, AttributeDto>(); } } }<file_sep>/src/wikia/data/cardsectiondata/README.md ![alt text](https://fablecode.visualstudio.com/Yugioh%20Insight/_apis/build/status/Build-CardSectionData "Visual studio team services build status") # Card Section Data Amalgamates [Yu-Gi-Oh](http://www.yugioh-card.com/uk/) card sections, from different sources. <file_sep>/src/wikia/processor/archetypeprocessor/src/Infrastructure/archetypeprocessor.infrastructure/Messaging/RabbitMqQueueConstants.cs namespace archetypeprocessor.infrastructure.Messaging { public static class RabbitMqQueueConstants { public const string ArchetypeImage = "archetype-image"; } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Mappings/Profiles/LimitProfile.cs using AutoMapper; using cardprocessor.application.Dto; using cardprocessor.core.Models.Db; namespace cardprocessor.application.Mappings.Profiles { public class LimitProfile : Profile { public LimitProfile() { CreateMap<Limit, LimitDto>(); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/MessageConsumers/CardData/CardDataConsumerHandler.cs using cardprocessor.application.Commands; using cardprocessor.core.Models; using cardprocessor.core.Services; using MediatR; using Newtonsoft.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace cardprocessor.application.MessageConsumers.CardData { public class CardDataConsumerHandler : IRequestHandler<CardDataConsumer, CardDataConsumerResult> { private readonly ICardService _cardService; private readonly IMediator _mediator; private readonly ICardCommandMapper _cardCommandMapper; private readonly ILogger<CardDataConsumerHandler> _logger; public CardDataConsumerHandler(ICardService cardService, IMediator mediator, ICardCommandMapper cardCommandMapper, ILogger<CardDataConsumerHandler> logger) { _cardService = cardService; _mediator = mediator; _cardCommandMapper = cardCommandMapper; _logger = logger; } public async Task<CardDataConsumerResult> Handle(CardDataConsumer request, CancellationToken cancellationToken) { var cardDataConsumerResult = new CardDataConsumerResult(); var yugiohCard = JsonConvert.DeserializeObject<YugiohCard>(request.Message); try { _logger.LogInformation($"{yugiohCard.Name} processing..."); var existingCard = await _cardService.CardByName(yugiohCard.Name); var result = existingCard == null ? await _mediator.Send(await _cardCommandMapper.MapToAddCommand(yugiohCard), cancellationToken) : await _mediator.Send(await _cardCommandMapper.MapToUpdateCommand(yugiohCard, existingCard), cancellationToken); if (result.IsSuccessful) { _logger.LogInformation($"{yugiohCard.Name} processed successfully."); cardDataConsumerResult.IsSuccessful = result.IsSuccessful; } else { _logger.LogError(yugiohCard.Name + " error. Validation errors: {ValidationErrors}", result.Errors); } } catch (System.Exception ex) { cardDataConsumerResult.Exception = ex; _logger.LogError(yugiohCard.Name + " error. Exception: {@Exception}", ex); } return cardDataConsumerResult; } } }<file_sep>/src/wikia/data/cardsectiondata/src/Infrastructure/cardsectiondata.infrastructure/WebPages/TipRelatedHtmlDocument.cs using cardsectiondata.application.Configuration; using cardsectiondata.domain.WebPages; using HtmlAgilityPack; using Microsoft.Extensions.Options; namespace cardsectiondata.infrastructure.WebPages { public class TipRelatedHtmlDocument : ITipRelatedHtmlDocument { private readonly IOptions<AppSettings> _appsettingsOptions; public TipRelatedHtmlDocument(IOptions<AppSettings> appsettingsOptions) { _appsettingsOptions = appsettingsOptions; } public HtmlNode GetTable(HtmlDocument document) { return document.DocumentNode.SelectSingleNode("//table[@class='sortable wikitable smwtable']"); } public string GetUrl(HtmlDocument document) { var furtherResultsUrl = document.DocumentNode.SelectSingleNode("//span[@class='smw-table-furtherresults']/a")?.Attributes["href"]?.Value; if (!string.IsNullOrWhiteSpace(furtherResultsUrl) && !furtherResultsUrl.Contains("http://")) furtherResultsUrl = _appsettingsOptions.Value.WikiaDomainUrl + furtherResultsUrl; return furtherResultsUrl; } } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Commands/ICardCommandMapper.cs using System.Threading.Tasks; using cardprocessor.application.Commands.AddCard; using cardprocessor.application.Commands.UpdateCard; using cardprocessor.core.Models; using cardprocessor.core.Models.Db; namespace cardprocessor.application.Commands { public interface ICardCommandMapper { Task<AddCardCommand> MapToAddCommand(YugiohCard yugiohCard); Task<UpdateCardCommand> MapToUpdateCommand(YugiohCard yugiohCard, Card card); } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Mappings/Profiles/CardSubCategoryProfile.cs using AutoMapper; using cardprocessor.application.Dto; using cardprocessor.core.Models.Db; namespace cardprocessor.application.Mappings.Profiles { public class CardSubCategoryProfile : Profile { public CardSubCategoryProfile() { CreateMap<CardSubCategory, CardSubCategoryDto>(); } } }<file_sep>/src/wikia/data/archetypedata/src/Application/archetypedata.application/ApplicationInstaller.cs using System.Net.Http; using System.Reflection; using archetypedata.application.MessageConsumers.ArchetypeCardInformation; using archetypedata.application.MessageConsumers.ArchetypeInformation; using archetypedata.core.Processor; using archetypedata.domain.Processor; using FluentValidation; using MediatR; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using wikia.Api; namespace archetypedata.application { public static class ApplicationInstaller { public static IServiceCollection AddApplicationServices(this IServiceCollection services) { services .AddCqrs() .AddValidation() .AddDomainServices(); return services; } private static IServiceCollection AddCqrs(this IServiceCollection services) { services.AddMediatR(typeof(ApplicationInstaller).GetTypeInfo().Assembly); return services; } private static IServiceCollection AddDomainServices(this IServiceCollection services) { services.AddTransient<IArchetypeCardProcessor, ArchetypeCardProcessor>(); services.AddSingleton<IArchetypeProcessor, ArchetypeProcessor>(); var buildServiceProvider = services.BuildServiceProvider(); var appSettings = buildServiceProvider.GetService<IOptions<Configuration.AppSettings>>(); services.AddSingleton<IWikiArticle>(new WikiArticle(appSettings.Value.WikiaDomainUrl, buildServiceProvider.GetService<IHttpClientFactory>())); return services; } private static IServiceCollection AddValidation(this IServiceCollection services) { services.AddTransient<IValidator<ArchetypeInformationConsumer>, ArchetypeInformationConsumerValidator>(); services.AddTransient<IValidator<ArchetypeCardInformationConsumer>, ArchetypeCardInformationConsumerValidator>(); return services; } } }<file_sep>/src/wikia/article/src/Application/article.application/ScheduledTasks/LatestBanlist/BanlistInformationTaskResult.cs using System.Collections.Generic; using article.core.Models; namespace article.application.ScheduledTasks.LatestBanlist { public class BanlistInformationTaskResult { public ArticleBatchTaskResult ArticleTaskResults { get; set; } public List<string> Errors { get; set; } public bool IsSuccessful { get; set; } } }<file_sep>/src/wikia/semanticsearch/src/Infrastructure/semanticsearch.infrastructure/Messaging/RabbitMqExchangeConstants.cs namespace semanticsearch.infrastructure.Messaging { public static class RabbitMqExchangeConstants { public const string YugiohHeadersArticle = "yugioh.headers.article"; } }<file_sep>/src/wikia/data/banlistdata/src/Tests/Unit/banlistdata.domain.unit.tests/ArticleDataFlowTests.cs using System; using System.Threading.Tasks; using banlistdata.core.Models; using banlistdata.core.Processor; using banlistdata.domain.Processor; using banlistdata.domain.Services.Messaging; using banlistdata.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace banlistdata.domain.unit.tests { [TestFixture] [Category(TestType.Unit)] public class ArticleDataFlowTests { private IBanlistProcessor _banlistProcessor; private IBanlistDataQueue _banlistDataQueue; private ArticleDataFlow _sut; [SetUp] public void SetUp() { _banlistProcessor = Substitute.For<IBanlistProcessor>(); _banlistDataQueue = Substitute.For<IBanlistDataQueue>(); _sut = new ArticleDataFlow(_banlistProcessor, _banlistDataQueue); } [Test] public async Task Given_An_Article_Should_Invoke_Process_Once() { // Arrange var article = new Article { Id = 3242423, CorrelationId = Guid.NewGuid() }; _banlistProcessor.Process(Arg.Any<Article>()).Returns(new ArticleProcessed() {Article = article, IsSuccessful = true}); _banlistDataQueue.Publish(Arg.Any<ArticleProcessed>()).Returns(new YugiohBanlistCompletion { Article = article, IsSuccessful = true }); // Act await _sut.ProcessDataFlow(article); // Assert await _banlistProcessor.Received(1).Process(Arg.Any<Article>()); } [Test] public async Task Given_An_Article_Should_Invoke_Publish_Once() { // Arrange var article = new Article { Id = 3242423, CorrelationId = Guid.NewGuid() }; _banlistProcessor.Process(Arg.Any<Article>()).Returns(new ArticleProcessed() { Article = article, IsSuccessful = true }); _banlistDataQueue.Publish(Arg.Any<ArticleProcessed>()).Returns(new YugiohBanlistCompletion { Article = article, IsSuccessful = true}); // Act await _sut.ProcessDataFlow(article); // Assert await _banlistDataQueue.Received(1).Publish(Arg.Any<ArticleProcessed>()); } [Test] public void Given_An_Article_If_Not_Successfully_Processed_Should_Exception() { // Arrange var article = new Article{Id = 3242423, CorrelationId = Guid.NewGuid()}; _banlistProcessor.Process(Arg.Any<Article>()).Returns(new ArticleProcessed {Article = article}); _banlistDataQueue.Publish(Arg.Any<ArticleProcessed>()).Returns(new YugiohBanlistCompletion {Article = article}); // Act Func<Task<ArticleCompletion>> act = () => _sut.ProcessDataFlow(article); // Assert act.Should().Throw<Exception>(); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Domain/cardprocessor.domain/Queues/Cards/ICardImageQueue.cs using System.Threading.Tasks; using cardprocessor.core.Models; namespace cardprocessor.domain.Queues.Cards { public interface ICardImageQueue { Task<CardImageCompletion> Publish(DownloadImage downloadImage); } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Dto/TriviaSectionDto.cs using System.Collections.Generic; namespace cardprocessor.application.Dto { public class TriviaSectionDto { public string Name { get; set; } public List<string> Trivia { get; set; } } }<file_sep>/src/wikia/article/src/Domain/article.domain/Services/Messaging/Cards/ISemanticCardArticleQueue.cs using System.Threading.Tasks; using wikia.Models.Article.AlphabeticalList; namespace article.domain.Services.Messaging.Cards { public interface ISemanticCardArticleQueue { Task Publish(UnexpandedArticle article); } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Domain/archetypeprocessor.domain/Services/ArchetypeService.cs using archetypeprocessor.core.Models.Db; using archetypeprocessor.core.Services; using archetypeprocessor.domain.Repository; using System.Threading.Tasks; namespace archetypeprocessor.domain.Services { public class ArchetypeService : IArchetypeService { private readonly IArchetypeRepository _archetypeRepository; public ArchetypeService(IArchetypeRepository archetypeRepository) { _archetypeRepository = archetypeRepository; } public Task<Archetype> ArchetypeByName(string name) { return _archetypeRepository.ArchetypeByName(name); } public Task<Archetype> ArchetypeById(long id) { return _archetypeRepository.ArchetypeById(id); } public Task<Archetype> Add(Archetype archetype) { return _archetypeRepository.Add(archetype); } public Task<Archetype> Update(Archetype archetype) { return _archetypeRepository.Update(archetype); } } }<file_sep>/src/wikia/data/carddata/README.md ![alt text](https://fablecode.visualstudio.com/Yugioh%20Insight/_apis/build/status/Build-CardData "Visual studio team services build status") # Card Data Amalgamates basic information about a [Yu-Gi-Oh](http://www.yugioh-card.com/uk/) card, from different sources. <file_sep>/src/wikia/processor/archetypeprocessor/src/Application/archetypeprocessor.application/ApplicationInstaller.cs using archetypeprocessor.core.Services; using archetypeprocessor.domain.Services; using AutoMapper; using MediatR; using Microsoft.Extensions.DependencyInjection; using System.Reflection; using archetypeprocessor.application.MessageConsumers.ArchetypeCardInformation; using archetypeprocessor.application.MessageConsumers.ArchetypeInformation; using archetypeprocessor.core.Processor; using archetypeprocessor.domain.Processor; using FluentValidation; namespace archetypeprocessor.application { public static class ApplicationInstaller { public static IServiceCollection AddApplicationServices(this IServiceCollection services) { services .AddCqrs() .AddDomainServices() .AddValidation() .AddAutoMapper(); return services; } private static IServiceCollection AddCqrs(this IServiceCollection services) { services.AddMediatR(typeof(ApplicationInstaller).GetTypeInfo().Assembly); return services; } private static IServiceCollection AddDomainServices(this IServiceCollection services) { services.AddTransient<IArchetypeService, ArchetypeService>(); services.AddTransient<IArchetypeCardsService, ArchetypeCardsService>(); services.AddTransient<IArchetypeProcessor, ArchetypeProcessor>(); services.AddTransient<IArchetypeCardProcessor, ArchetypeCardProcessor>(); return services; } private static IServiceCollection AddValidation(this IServiceCollection services) { services.AddTransient<IValidator<ArchetypeInformationConsumer>, ArchetypeInformationConsumerValidator>(); services.AddTransient<IValidator<ArchetypeCardInformationConsumer>, ArchetypeCardInformationConsumerValidator>(); return services; } } } <file_sep>/src/wikia/processor/cardprocessor/src/Infrastructure/cardprocessor.infrastructure/Services/Messaging/RabbitMqExchangeConstants.cs namespace cardprocessor.infrastructure.Services.Messaging { public static class RabbitMqExchangeConstants { public const string YugiohHeadersImage = "yugioh.headers.image"; } }<file_sep>/src/wikia/data/archetypedata/src/Core/archetypedata.core/Models/ArchetypeCard.cs using System.Collections.Generic; namespace archetypedata.core.Models { public class ArchetypeCard { public string ArchetypeName { get; set; } public IEnumerable<string> Cards { get; set; } } }<file_sep>/src/wikia/data/banlistdata/src/Application/banlistdata.application/ApplicationInstaller.cs using System.Net.Http; using System.Reflection; using banlistdata.application.MessageConsumers.BanlistInformation; using banlistdata.core.Processor; using banlistdata.domain.Processor; using FluentValidation; using MediatR; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using wikia; using wikia.Api; namespace banlistdata.application { public static class ApplicationInstaller { public static IServiceCollection AddApplicationServices(this IServiceCollection services) { services .AddCqrs() .AddValidation() .AddDomainServices(); return services; } private static IServiceCollection AddCqrs(this IServiceCollection services) { services.AddMediatR(typeof(ApplicationInstaller).GetTypeInfo().Assembly); return services; } private static IServiceCollection AddDomainServices(this IServiceCollection services) { services.AddTransient<IArticleProcessor, ArticleProcessor>(); services.AddTransient<IBanlistProcessor, BanlistProcessor>(); services.AddSingleton<IArticleDataFlow, ArticleDataFlow>(); var buildServiceProvider = services.BuildServiceProvider(); var appSettings = buildServiceProvider.GetService<IOptions<Configuration.AppSettings>>(); services.AddSingleton<IWikiArticle>(new WikiArticle(appSettings.Value.WikiaDomainUrl, buildServiceProvider.GetService<IHttpClientFactory>())); return services; } private static IServiceCollection AddValidation(this IServiceCollection services) { services.AddTransient<IValidator<BanlistInformationConsumer>, BanlistInformationConsumerValidator>(); return services; } } }<file_sep>/src/wikia/data/cardsectiondata/src/Presentation/cardsectiondata/Services/CardSectionDataHostedService.cs using cardsectiondata.application.Configuration; using cardsectiondata.application.MessageConsumers.CardRulingInformation; using cardsectiondata.application.MessageConsumers.CardTipInformation; using MediatR; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using RabbitMQ.Client; using RabbitMQ.Client.Events; using Serilog; using Serilog.Events; using Serilog.Formatting.Json; using System; using System.Text; using System.Threading; using System.Threading.Tasks; using cardsectiondata.application.MessageConsumers.CardTriviaInformation; namespace cardsectiondata.Services { public class CardSectionDataHostedService : BackgroundService { private const string CardTipArticleQueue = "card-tips-article"; private const string CardRulingArticleQueue = "card-rulings-article"; private const string CardTriviaArticleQueue = "card-trivia-article"; public IServiceProvider Services { get; } private readonly IOptions<RabbitMqSettings> _rabbitMqOptions; private readonly IOptions<AppSettings> _appSettingsOptions; private readonly IMediator _mediator; private ConnectionFactory _factory; private IConnection _cardTipConnection; private IModel _cardTipArticleChannel; private EventingBasicConsumer _cardTipArticleConsumer; private EventingBasicConsumer _cardRulingArticleConsumer; private IModel _cardRulingArticleChannel; private IConnection _cardRulingConnection; private IConnection _cardTriviaConnection; private EventingBasicConsumer _cardTriviaArticleConsumer; private IModel _cardTriviaArticleChannel; public CardSectionDataHostedService ( IServiceProvider services, IOptions<RabbitMqSettings> rabbitMqOptions, IOptions<AppSettings> appSettingsOptions, IMediator mediator ) { Services = services; _rabbitMqOptions = rabbitMqOptions; _appSettingsOptions = appSettingsOptions; _mediator = mediator; ConfigureSerilog(); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { await StartConsumer(); } public override void Dispose() { _cardTipArticleChannel.Close(); _cardTipConnection.Close(); _cardRulingArticleChannel.Close(); _cardRulingConnection.Close(); _cardTriviaArticleChannel.Close(); _cardTriviaConnection.Close(); base.Dispose(); } #region private helper private Task StartConsumer() { _factory = new ConnectionFactory() { HostName = _rabbitMqOptions.Value.Host }; _cardTipConnection = _factory.CreateConnection(); _cardRulingConnection = _factory.CreateConnection(); _cardTriviaConnection = _factory.CreateConnection(); _cardTipArticleConsumer = CreateCardTipArticleConsumer(_cardTipConnection); _cardRulingArticleConsumer = CreateCardRulingArticleConsumer(_cardRulingConnection); _cardTriviaArticleConsumer = CreateCardTriviaArticleConsumer(_cardTriviaConnection); return Task.CompletedTask; } private EventingBasicConsumer CreateCardTriviaArticleConsumer(IConnection connection) { _cardTriviaArticleChannel = connection.CreateModel(); _cardTriviaArticleChannel.BasicQos(0, 20, false); var consumer = new EventingBasicConsumer(_cardTriviaArticleChannel); consumer.Received += async (model, ea) => { try { var body = ea.Body; var message = Encoding.UTF8.GetString(body); var result = await _mediator.Send(new CardTriviaInformationConsumer { Message = message }); if (result.IsSuccessful) { _cardTriviaArticleChannel.BasicAck(ea.DeliveryTag, false); } else { _cardTriviaArticleChannel.BasicNack(ea.DeliveryTag, false, false); } } catch (Exception ex) { Log.Logger.Error("RabbitMq Consumer: " + CardTriviaArticleQueue + " exception. Exception: {@Exception}", ex); } }; consumer.Shutdown += OnCardTriviaArticleConsumerShutdown; consumer.Registered += OnCardTriviaArticleConsumerRegistered; consumer.Unregistered += OnCardTriviaArticleConsumerUnregistered; consumer.ConsumerCancelled += OnCardTriviaArticleConsumerCancelled; _cardTriviaArticleChannel.BasicConsume ( queue: CardTriviaArticleQueue, autoAck: false, consumer: consumer ); return consumer; } private EventingBasicConsumer CreateCardTipArticleConsumer(IConnection connection) { _cardTipArticleChannel = connection.CreateModel(); _cardTipArticleChannel.BasicQos(0, 20, false); var consumer = new EventingBasicConsumer(_cardTipArticleChannel); consumer.Received += async (model, ea) => { try { var body = ea.Body; var message = Encoding.UTF8.GetString(body); var result = await _mediator.Send(new CardTipInformationConsumer { Message = message }); if (result.IsSuccessful) { _cardTipArticleChannel.BasicAck(ea.DeliveryTag, false); } else { _cardTipArticleChannel.BasicNack(ea.DeliveryTag, false, false); } } catch (Exception ex) { Log.Logger.Error("RabbitMq Consumer: " + CardTipArticleQueue + " exception. Exception: {@Exception}", ex); } }; consumer.Shutdown += OnCardTipArticleConsumerShutdown; consumer.Registered += OnCardTipArticleConsumerRegistered; consumer.Unregistered += OnCardTipArticleConsumerUnregistered; consumer.ConsumerCancelled += OnCardTipArticleConsumerCancelled; _cardTipArticleChannel.BasicConsume ( queue: CardTipArticleQueue, autoAck: false, consumer: consumer ); return consumer; } private EventingBasicConsumer CreateCardRulingArticleConsumer(IConnection connection) { _cardRulingArticleChannel = connection.CreateModel(); _cardRulingArticleChannel.BasicQos(0, 20, false); var consumer = new EventingBasicConsumer(_cardRulingArticleChannel); consumer.Received += async (model, ea) => { try { var body = ea.Body; var message = Encoding.UTF8.GetString(body); var result = await _mediator.Send(new CardRulingInformationConsumer { Message = message }); if (result.IsSuccessful) { _cardRulingArticleChannel.BasicAck(ea.DeliveryTag, false); } else { _cardRulingArticleChannel.BasicNack(ea.DeliveryTag, false, false); } } catch (Exception ex) { Log.Logger.Error("RabbitMq Consumer: " + CardRulingArticleQueue + " exception. Exception: {@Exception}", ex); } }; consumer.Shutdown += OnCardRulingArticleConsumerShutdown; consumer.Registered += OnCardRulingArticleConsumerRegistered; consumer.Unregistered += OnCardRulingArticleConsumerUnregistered; consumer.ConsumerCancelled += OnCardRulingArticleConsumerCancelled; _cardRulingArticleChannel.BasicConsume ( queue: CardRulingArticleQueue, autoAck: false, consumer: consumer ); return consumer; } private static void OnCardTipArticleConsumerCancelled(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{CardTipArticleQueue}' Cancelled"); } private static void OnCardTipArticleConsumerUnregistered(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{CardTipArticleQueue}' Unregistered");} private static void OnCardTipArticleConsumerRegistered(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{CardTipArticleQueue}' Registered"); } private static void OnCardTipArticleConsumerShutdown(object sender, ShutdownEventArgs e) { Log.Logger.Information($"Consumer '{CardTipArticleQueue}' Shutdown"); } private static void OnCardRulingArticleConsumerCancelled(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{CardRulingArticleQueue}' Cancelled"); } private static void OnCardRulingArticleConsumerUnregistered(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{CardRulingArticleQueue}' Unregistered");} private static void OnCardRulingArticleConsumerRegistered(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{CardRulingArticleQueue}' Registered"); } private static void OnCardRulingArticleConsumerShutdown(object sender, ShutdownEventArgs e) { Log.Logger.Information($"Consumer '{CardRulingArticleQueue}' Shutdown"); } private static void OnCardTriviaArticleConsumerCancelled(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{CardTriviaArticleQueue}' Cancelled"); } private static void OnCardTriviaArticleConsumerUnregistered(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{CardTriviaArticleQueue}' Unregistered");} private static void OnCardTriviaArticleConsumerRegistered(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{CardTriviaArticleQueue}' Registered"); } private static void OnCardTriviaArticleConsumerShutdown(object sender, ShutdownEventArgs e) { Log.Logger.Information($"Consumer '{CardTriviaArticleQueue}' Shutdown"); } private void ConfigureSerilog() { // Create the logger Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Console() .WriteTo.File(new JsonFormatter(renderMessage: true), (_appSettingsOptions.Value.LogFolder + $@"/archetypedata.{Environment.MachineName}.txt"), fileSizeLimitBytes: 100000000, rollOnFileSizeLimit: true, rollingInterval: RollingInterval.Day) .CreateLogger(); } #endregion } } <file_sep>/src/wikia/article/src/Core/article.core/ArticleList/Processor/IArticleProcessor.cs using System.Threading.Tasks; using article.core.Models; using wikia.Models.Article.AlphabeticalList; namespace article.core.ArticleList.Processor { public interface IArticleProcessor { Task<ArticleTaskResult> Process(string category, UnexpandedArticle article); } }<file_sep>/src/wikia/article/src/Tests/Unit/article.domain.unit.tests/ArticleListTests/ProcessorTests/ArticleCategoryProcessorTests/ProcessCategoryListTests.cs using article.core.ArticleList.DataSource; using article.core.ArticleList.Processor; using article.domain.ArticleList.Processor; using article.tests.core; using NSubstitute; using NUnit.Framework; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using article.core.Models; using FluentAssertions; using wikia.Models.Article.AlphabeticalList; namespace article.domain.unit.tests.ArticleListTests.ProcessorTests.ArticleCategoryProcessorTests { [TestFixture] [Category(TestType.Unit)] public class ProcessCategoryListTests { private IArticleCategoryDataSource _articleCategoryDataSource; private IArticleBatchProcessor _articleBatchProcessor; private ArticleCategoryProcessor _sut; [SetUp] public void SetUp() { _articleCategoryDataSource = Substitute.For<IArticleCategoryDataSource>(); _articleBatchProcessor = Substitute.For<IArticleBatchProcessor>(); _sut = new ArticleCategoryProcessor(_articleCategoryDataSource, _articleBatchProcessor); } [Test] public async Task Given_A_CategoryList_And_PageSize_Should_Invoke_Producer_Method_3_Times() { // Arrange const int expected = 3; var categories = new List<string> { "category1", "category2", "category3" }; const int pageSize = 10; // Act await _sut.Process(categories, pageSize); // Assert await _articleCategoryDataSource.Received(expected).Producer(Arg.Any<string>(), Arg.Any<int>()).ToListAsync(); } [Test] public async Task Given_A_CategoryList_And_PageSize_Should_Invoke_Process_Method_3_Times() { // Arrange const int expected = 3; var categories = new List<string> { "category1", "category2", "category3" }; const int pageSize = 10; _articleCategoryDataSource .Producer(Arg.Any<string>(), Arg.Any<int>()) .Returns ( new List<UnexpandedArticle[]>{ new UnexpandedArticle[0] }.ToAsyncEnumerable(), new List<UnexpandedArticle[]> { new UnexpandedArticle[0] }.ToAsyncEnumerable(), new List<UnexpandedArticle[]> { new UnexpandedArticle[0] }.ToAsyncEnumerable() ); _articleBatchProcessor.Process(Arg.Any<string>(), Arg.Any<UnexpandedArticle[]>()) .Returns(new ArticleBatchTaskResult()); // Act await _sut.Process(categories, pageSize); // Assert await _articleBatchProcessor.Received(expected).Process(Arg.Any<string>(), Arg.Any<UnexpandedArticle[]>()); } [Test] public async Task Given_A_CategoryList_And_PageSize_Number_Of_Processed_Items_Should_Be_3() { // Arrange const int expected = 3; var categories = new List<string> { "category1", "category2", "category3" }; const int pageSize = 10; _articleCategoryDataSource .Producer(Arg.Any<string>(), Arg.Any<int>()) .Returns ( new List<UnexpandedArticle[]>{ new UnexpandedArticle[0] }.ToAsyncEnumerable(), new List<UnexpandedArticle[]> { new UnexpandedArticle[0] }.ToAsyncEnumerable(), new List<UnexpandedArticle[]> { new UnexpandedArticle[0] }.ToAsyncEnumerable() ); _articleBatchProcessor.Process(Arg.Any<string>(), Arg.Any<UnexpandedArticle[]>()) .Returns(new ArticleBatchTaskResult { Processed = 1 }); // Act var result = await _sut.Process(categories, pageSize); // Assert result.Sum(a => a.Processed).Should().Be(expected); } } }<file_sep>/src/wikia/data/archetypedata/src/Presentation/archetypedata/Program.cs using archetypedata.application; using archetypedata.application.Configuration; using archetypedata.infrastructure; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using System; using archetypedata.Services; namespace archetypedata { internal class Program { internal static void Main(string[] args) { try { CreateHostBuilder(args).Build().Run(); } catch (Exception ex) { if (Log.Logger == null || Log.Logger.GetType().Name == "SilentLogger") { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Console() .CreateLogger(); } Log.Fatal(ex, "Host terminated unexpectedly"); throw; } finally { Log.CloseAndFlush(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { services.AddLogging(); //configuration settings services.Configure<AppSettings>(hostContext.Configuration.GetSection(nameof(AppSettings))); services.Configure<RabbitMqSettings>(hostContext.Configuration.GetSection(nameof(RabbitMqSettings))); // hosted service services.AddHostedService<ArchetypeDataHostedService>(); services.AddHostedService<ArchetypeCardDataHostedService>(); services.AddHostedService<ArchetypeSupportCardDataHostedService>(); services.AddHttpClient(); services.AddApplicationServices(); services.AddInfrastructureServices(); }) .UseSerilog((hostingContext, loggerConfiguration) => { loggerConfiguration .ReadFrom.Configuration(hostingContext.Configuration) .Enrich.WithProperty("ApplicationName", typeof(Program).Assembly.GetName().Name) .Enrich.WithProperty("Environment", hostingContext.HostingEnvironment); }); } } <file_sep>/src/wikia/processor/archetypeprocessor/src/Infrastructure/archetypeprocessor.infrastructure/Messaging/ImageQueueService.cs using System; using System.Linq; using archetypeprocessor.core.Models; using archetypeprocessor.domain.Messaging; using System.Threading.Tasks; using archetypeprocessor.application.Configuration; using Microsoft.Extensions.Options; using Newtonsoft.Json; using RabbitMQ.Client; namespace archetypeprocessor.infrastructure.Messaging { public class ImageQueueService : IImageQueueService { private readonly IOptions<RabbitMqSettings> _rabbitMqConfig; public ImageQueueService(IOptions<RabbitMqSettings> rabbitMqConfig) { _rabbitMqConfig = rabbitMqConfig; } public Task Publish(DownloadImage downloadImage) { try { var messageBodyBytes = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(downloadImage)); var factory = new ConnectionFactory() { HostName = _rabbitMqConfig.Value.Host }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { var props = channel.CreateBasicProperties(); props.ContentType = _rabbitMqConfig.Value.ContentType; props.DeliveryMode = _rabbitMqConfig.Value.Exchanges[RabbitMqExchangeConstants.YugiohHeadersImage].PersistentMode; props.Headers = _rabbitMqConfig.Value .Exchanges[RabbitMqExchangeConstants.YugiohHeadersImage] .Queues[RabbitMqQueueConstants.ArchetypeImage] .Headers.ToDictionary(k => k.Key, k => (object)k.Value); channel.BasicPublish ( RabbitMqExchangeConstants.YugiohHeadersImage, "", props, messageBodyBytes ); } } catch (Exception ex) { Console.WriteLine(ex); throw; } return Task.CompletedTask; } } }<file_sep>/src/wikia/processor/cardprocessor/README.md ![alt text](https://fablecode.visualstudio.com/Yugioh%20Insight/_apis/build/status/Build-CardProcessor "Visual studio team services build status") # Card Processor Persists card related data.<file_sep>/src/wikia/data/carddata/src/Tests/Unit/carddata.application.unit.tests/CardInformationConsumerHandlerTests.cs using carddata.application.MessageConsumers.CardInformation; using carddata.core.Models; using carddata.core.Processor; using carddata.tests.core; using FluentAssertions; using FluentValidation; using NSubstitute; using NUnit.Framework; using System.Threading; using System.Threading.Tasks; namespace carddata.application.unit.tests { [TestFixture] [Category(TestType.Unit)] public class CardInformationConsumerHandlerTests { private IArticleProcessor _articleProcessor; private IValidator<CardInformationConsumer> _validator; private CardInformationConsumerHandler _sut; [SetUp] public void SetUp() { _articleProcessor = Substitute.For<IArticleProcessor>(); _validator = Substitute.For<IValidator<CardInformationConsumer>>(); _sut = new CardInformationConsumerHandler(_articleProcessor,_validator); } [Test] public async Task Given_An_Invalid_CardInformationConsumer_ArticleConsumerResult_Should_Be_Null() { // Arrange var cardInformationConsumer = new CardInformationConsumer(); _validator .Validate(Arg.Is(cardInformationConsumer)) .Returns(new CardInformationConsumerValidator().Validate(cardInformationConsumer)); // Act var result = await _sut.Handle(cardInformationConsumer, CancellationToken.None); // Assert result.ArticleConsumerResult.Should().BeNull(); } [Test] public async Task Given_An_Valid_CardInformationConsumer_IsSuccessful_Should_BeTrue() { // Arrange var cardInformationConsumer = new CardInformationConsumer { Message = "{\"Id\":10917,\"Title\":\"Amazoness Archer\",\"Url\":\"https://yugioh.fandom.com/wiki/Amazoness_Archer\"}" }; _validator .Validate(Arg.Is(cardInformationConsumer)) .Returns(new CardInformationConsumerValidator().Validate(cardInformationConsumer)); _articleProcessor.Process(Arg.Any<Article>()) .Returns(new ArticleConsumerResult {IsSuccessfullyProcessed = true}); // Act var result = await _sut.Handle(cardInformationConsumer, CancellationToken.None); // Assert result.ArticleConsumerResult.IsSuccessfullyProcessed.Should().BeTrue(); } [Test] public async Task Given_An_Valid_CardInformationConsumer_Should_Invoke_ArticleProcessor_Process_Once() { // Arrange var cardInformationConsumer = new CardInformationConsumer { Message = "{\"Id\":10917,\"Title\":\"Amazoness Archer\",\"Url\":\"https://yugioh.fandom.com/wiki/Amazoness_Archer\"}" }; _validator .Validate(Arg.Is(cardInformationConsumer)) .Returns(new CardInformationConsumerValidator().Validate(cardInformationConsumer)); _articleProcessor.Process(Arg.Any<Article>()) .Returns(new ArticleConsumerResult {IsSuccessfullyProcessed = true}); // Act await _sut.Handle(cardInformationConsumer, CancellationToken.None); // Assert await _articleProcessor.Received(1).Process(Arg.Any<Article>()); } } } <file_sep>/src/services/Cards.API/src/Application/Cards.Application/MessageConsumers/CardData/CardInformationConsumer.cs using MediatR; namespace Cards.Application.MessageConsumers.CardData { public record CardInformationConsumer : IRequest<CardInformationConsumerResult> { public string Message { get; } public CardInformationConsumer(string message) { Message = message; } } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Core/archetypeprocessor.core/Models/ArchetypeDataTaskResult.cs using System.Collections.Generic; using System.Linq; namespace archetypeprocessor.core.Models { public class ArchetypeDataTaskResult<T> { public bool IsSuccessful => !Errors.Any(); public T ArchetypeData { get; set; } public List<string> Errors { get; set; } = new List<string>(); } }<file_sep>/src/wikia/processor/cardprocessor/src/Domain/cardprocessor.domain/Strategies/TrapCardTypeStrategy.cs using System.Threading.Tasks; using cardprocessor.core.Enums; using cardprocessor.core.Models; using cardprocessor.core.Models.Db; using cardprocessor.core.Strategies; using cardprocessor.domain.Mappers; using cardprocessor.domain.Repository; namespace cardprocessor.domain.Strategies { public class TrapCardTypeStrategy : ICardTypeStrategy { private readonly ICardRepository _cardRepository; public TrapCardTypeStrategy(ICardRepository cardRepository) { _cardRepository = cardRepository; } public async Task<Card> Add(CardModel cardModel) { var newTrapCard = CardMapper.MapToSpellOrTrapCard(cardModel); return await _cardRepository.Add(newTrapCard); } public async Task<Card> Update(CardModel cardModel) { var cardToUpdate = await _cardRepository.CardById(cardModel.Id); if (cardToUpdate != null) { CardMapper.UpdateTrapCardWith(cardToUpdate, cardModel); return await _cardRepository.Update(cardToUpdate); } return null; } public bool Handles(YugiohCardType yugiohCardType) { return yugiohCardType == YugiohCardType.Trap; } } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Tests/Unit/archetypeprocessor.domain.unit.tests/ProcessorTests/ArchetypeCardProcessorTests.cs using System.Collections.Generic; using System.Threading.Tasks; using archetypeprocessor.core.Models; using archetypeprocessor.core.Models.Db; using archetypeprocessor.core.Services; using archetypeprocessor.domain.Processor; using archetypeprocessor.tests.core; using NSubstitute; using NUnit.Framework; namespace archetypeprocessor.domain.unit.tests.ProcessorTests { [TestFixture] [Category(TestType.Unit)] public class ArchetypeCardProcessorTests { private IArchetypeService _archetypeService; private IArchetypeCardsService _archetypeCardsService; private ArchetypeCardProcessor _sut; [SetUp] public void SetUp() { _archetypeService = Substitute.For<IArchetypeService>(); _archetypeCardsService = Substitute.For<IArchetypeCardsService>(); _sut = new ArchetypeCardProcessor(_archetypeService, _archetypeCardsService); } [Test] public async Task Given_An_ArchetypeCardMessage_If_Archetype_Is_Not_Found_Should_Invoke_Update_Method() { // Arrange var archetypeCardMessage = new ArchetypeCardMessage { ArchetypeName = "Blue-Eyes White Dragon" }; // Act await _sut.Process(archetypeCardMessage); // Assert await _archetypeCardsService.DidNotReceive().Update(Arg.Any<long>(), Arg.Any<IEnumerable<string>>()); } [Test] public async Task Given_An_ArchetypeCardMessage_If_Archetype_Is_Found_Should_Invoke_Update_Method_Once() { // Arrange var archetypeCardMessage = new ArchetypeCardMessage { ArchetypeName = "Blue-Eyes White Dragon", Cards = new List<string> { "Blue-Eyes White Dragon"} }; _archetypeService.ArchetypeByName(Arg.Any<string>()).Returns(new Archetype()); // Act await _sut.Process(archetypeCardMessage); // Assert await _archetypeCardsService.Received(1).Update(Arg.Any<long>(), Arg.Any<IEnumerable<string>>()); } [Test] public async Task Given_An_ArchetypeCardMessage_Should_Always_Invoke_ArchetypeByName_Method_Once() { // Arrange var archetypeCardMessage = new ArchetypeCardMessage { ArchetypeName = "Blue-Eyes White Dragon" }; _archetypeService.ArchetypeByName(Arg.Any<string>()).Returns(new Archetype()); // Act await _sut.Process(archetypeCardMessage); // Assert await _archetypeService.Received(1).ArchetypeByName(Arg.Any<string>()); } } }<file_sep>/src/wikia/data/carddata/src/Core/carddata.core/Models/ArticleCompletion.cs using System; namespace carddata.core.Models { public class ArticleCompletion { public bool IsSuccessful { get; set; } public Article Message { get; set; } public Exception Exception { get; set; } } public class ArticleProcessed { public Article Article { get; set; } public YugiohCard Card { get; set; } } }<file_sep>/src/wikia/article/src/Infrastructure/article.infrastructure/Services/Messaging/ArchetypeArticleQueue.cs using article.core.Models; using article.domain.Services.Messaging; using System.Threading.Tasks; using wikia.Models.Article.AlphabeticalList; namespace article.infrastructure.Services.Messaging { public class ArchetypeArticleQueue : IArchetypeArticleQueue { private readonly IQueue<Article> _queue; public ArchetypeArticleQueue(IQueue<Article> queue) { _queue = queue; } public Task Publish(UnexpandedArticle article) { return _queue.Publish(article); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Mappings/Mappers/SubCategoryMapper.cs using System; using System.Collections.Generic; using System.Linq; using cardprocessor.application.Enums; using cardprocessor.core.Models.Db; namespace cardprocessor.application.Mappings.Mappers { public class SubCategoryMapper { public static int SubCategoryId(IEnumerable<Category> categories, IEnumerable<SubCategory> subCategories, YgoCardType cardType, string subCategory) { return (int) ( from sc in subCategories join c in categories on sc.CategoryId equals c.Id where c.Name.Equals(cardType.ToString(), StringComparison.OrdinalIgnoreCase) && sc.Name.Equals(subCategory, StringComparison.OrdinalIgnoreCase) select sc.Id ) .Single(); } } }<file_sep>/src/wikia/data/carddata/src/Domain/carddata.domain/Processor/ArticleDataFlow.cs using carddata.core.Models; using carddata.core.Processor; using carddata.domain.Exceptions; using carddata.domain.Services.Messaging; using carddata.domain.WebPages.Cards; using System.Threading.Tasks; namespace carddata.domain.Processor { public class ArticleDataFlow : IArticleDataFlow { private readonly ICardWebPage _cardWebPage; private readonly IYugiohCardQueue _yugiohCardQueue; public ArticleDataFlow(ICardWebPage cardWebPage, IYugiohCardQueue yugiohCardQueue) { _cardWebPage = cardWebPage; _yugiohCardQueue = yugiohCardQueue; } public async Task<ArticleCompletion> ProcessDataFlow(Article article) { var articleProcessed = _cardWebPage.GetYugiohCard(article); var yugiohCardCompletion = await _yugiohCardQueue.Publish(articleProcessed); if (yugiohCardCompletion.IsSuccessful) { return new ArticleCompletion { IsSuccessful = true, Message = yugiohCardCompletion.Article }; } var exceptionMessage = $"Card Article with id '{yugiohCardCompletion.Article.Id}' and correlation id {yugiohCardCompletion.Article.CorrelationId} not processed."; throw new ArticleCompletionException(exceptionMessage); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Mappings/Profiles/CategoryProfile.cs using AutoMapper; using cardprocessor.application.Dto; using cardprocessor.core.Models.Db; namespace cardprocessor.application.Mappings.Profiles { public class CategoryProfile : Profile { public CategoryProfile() { CreateMap<Category, CategoryDto>(); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Commands/DownloadImage/DownloadImageCommandHandler.cs using cardprocessor.core.Services.Messaging.Cards; using FluentValidation; using MediatR; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace cardprocessor.application.Commands.DownloadImage { public class DownloadImageCommandHandler : IRequestHandler<DownloadImageCommand, CommandResult> { private readonly ICardImageQueueService _cardImageQueueService; private readonly IValidator<DownloadImageCommand> _validator; public DownloadImageCommandHandler(ICardImageQueueService cardImageQueueService, IValidator<DownloadImageCommand> validator) { _cardImageQueueService = cardImageQueueService; _validator = validator; } public async Task<CommandResult> Handle(DownloadImageCommand request, CancellationToken cancellationToken) { var commandResult = new CommandResult(); var validationResult = _validator.Validate(request); if (validationResult.IsValid) { var result = await _cardImageQueueService.Publish(new core.Models.DownloadImage { RemoteImageUrl = request.RemoteImageUrl, ImageFileName = request.ImageFileName, ImageFolderPath = request.ImageFolderPath }); commandResult.IsSuccessful = result.IsSuccessful; } else { commandResult.Errors = validationResult.Errors.Select(err => err.ErrorMessage).ToList(); } return commandResult; } } }<file_sep>/src/wikia/processor/imageprocessor/src/Tests/Unit/imageprocessor.application.unit.tests/CommandsTests/DownloadImageCommandHandlerTests.cs using System; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using FluentValidation; using FluentValidation.Results; using imageprocessor.application.Commands.DownloadImage; using imageprocessor.core.Models; using imageprocessor.core.Services; using imageprocessor.tests.core; using NSubstitute; using NUnit.Framework; namespace imageprocessor.application.unit.tests.CommandsTests { [TestFixture] [Category(TestType.Unit)] public class DownloadImageCommandHandlerTests { private IValidator<DownloadImageCommand> _validator; private IFileSystemService _fileSystemService; private DownloadImageCommandHandler _sut; [SetUp] public void SetUp() { _validator = Substitute.For<IValidator<DownloadImageCommand>>(); _fileSystemService = Substitute.For<IFileSystemService>(); _sut = new DownloadImageCommandHandler(_fileSystemService, _validator); } [Test] public async Task Given_An_Invalid_DownloadImageCommand_Validation_Should_Fail() { // Arrange var downloadImageCommand = new DownloadImageCommand(); _validator.Validate(Arg.Is(downloadImageCommand)).Returns(new ValidationResult { Errors = { new ValidationFailure("property", "Failed")}}); // Act var result = await _sut.Handle(downloadImageCommand, CancellationToken.None); // Assert result.IsSuccessful.Should().BeFalse(); } [Test] public async Task Given_An_Invalid_DownloadImageCommand_Error_Should_Not_Be_Null_Or_Empty() { // Arrange var downloadImageCommand = new DownloadImageCommand(); _validator.Validate(Arg.Is(downloadImageCommand)).Returns(new ValidationResult { Errors = { new ValidationFailure("property", "Failed")}}); // Act var result = await _sut.Handle(downloadImageCommand, CancellationToken.None); // Assert result.Errors.Should().NotBeNullOrEmpty(); } [Test] public async Task Given_An_Valid_DownloadImageCommand_Should_Process_Command_Successfully() { // Arrange var downloadImageCommand = new DownloadImageCommand { ImageFileName = "Adreus, Keeper of Armageddon", ImageFolderPath = @"D:\Apps\ygo-api\Images\Cards", RemoteImageUrl = new Uri("https://vignette.wikia.nocookie.net/yugioh/images/f/f6/AdreusKeeperofArmageddon-BP01-EN-R-1E.png") }; _validator.Validate(Arg.Is(downloadImageCommand)).Returns(new ValidationResult()); _fileSystemService.Download(Arg.Any<Uri>(), Arg.Any<string>()).Returns(new DownloadedFile{ ContentType = "image/png" }); // Act var result = await _sut.Handle(downloadImageCommand, CancellationToken.None); // Assert result.IsSuccessful.Should().BeTrue(); } [Test] public async Task Given_An_Valid_DownloadImageCommand_Should_Invoke_Download_Method_Once() { // Arrange var downloadImageCommand = new DownloadImageCommand { ImageFileName = "Adreus, Keeper of Armageddon", ImageFolderPath = @"D:\Apps\ygo-api\Images\Cards", RemoteImageUrl = new Uri("https://vignette.wikia.nocookie.net/yugioh/images/f/f6/AdreusKeeperofArmageddon-BP01-EN-R-1E.png") }; _validator.Validate(Arg.Is(downloadImageCommand)).Returns(new ValidationResult()); _fileSystemService.Download(Arg.Any<Uri>(), Arg.Any<string>()).Returns(new DownloadedFile{ ContentType = "image/png" }); // Act await _sut.Handle(downloadImageCommand, CancellationToken.None); // Assert await _fileSystemService.Received(1).Download(Arg.Any<Uri>(), Arg.Any<string>()); } [Test] public async Task Given_An_Valid_DownloadImageCommand_Should_Invoke_Exists_Method_Once() { // Arrange var downloadImageCommand = new DownloadImageCommand { ImageFileName = "Adreus, Keeper of Armageddon", ImageFolderPath = @"D:\Apps\ygo-api\Images\Cards", RemoteImageUrl = new Uri("https://vignette.wikia.nocookie.net/yugioh/images/f/f6/AdreusKeeperofArmageddon-BP01-EN-R-1E.png") }; _validator.Validate(Arg.Is(downloadImageCommand)).Returns(new ValidationResult()); _fileSystemService.Download(Arg.Any<Uri>(), Arg.Any<string>()).Returns(new DownloadedFile{ ContentType = "image/png" }); // Act await _sut.Handle(downloadImageCommand, CancellationToken.None); // Assert _fileSystemService.Received(1).Exists(Arg.Any<string>()); } [Test] public async Task Given_An_Valid_DownloadImageCommand_If_Image_Does_Not_Exist_Should_Not_Invoke_Delete_Method() { // Arrange var downloadImageCommand = new DownloadImageCommand { ImageFileName = "Adreus, Keeper of Armageddon", ImageFolderPath = @"D:\Apps\ygo-api\Images\Cards", RemoteImageUrl = new Uri("https://vignette.wikia.nocookie.net/yugioh/images/f/f6/AdreusKeeperofArmageddon-BP01-EN-R-1E.png") }; _validator.Validate(Arg.Is(downloadImageCommand)).Returns(new ValidationResult()); _fileSystemService.Download(Arg.Any<Uri>(), Arg.Any<string>()).Returns(new DownloadedFile{ ContentType = "image/png" }); // Act await _sut.Handle(downloadImageCommand, CancellationToken.None); // Assert _fileSystemService.DidNotReceive().Delete(Arg.Any<string>()); } [Test] public async Task Given_An_Valid_DownloadImageCommand_If_Image_Exists_Should_Invoke_Delete_Method_Once() { // Arrange var downloadImageCommand = new DownloadImageCommand { ImageFileName = "Adreus, Keeper of Armageddon", ImageFolderPath = @"D:\Apps\ygo-api\Images\Cards", RemoteImageUrl = new Uri("https://vignette.wikia.nocookie.net/yugioh/images/f/f6/AdreusKeeperofArmageddon-BP01-EN-R-1E.png") }; _validator.Validate(Arg.Is(downloadImageCommand)).Returns(new ValidationResult()); _fileSystemService.Download(Arg.Any<Uri>(), Arg.Any<string>()).Returns(new DownloadedFile{ ContentType = "image/png" }); _fileSystemService.Exists(Arg.Any<string>()).Returns(true); // Act await _sut.Handle(downloadImageCommand, CancellationToken.None); // Assert _fileSystemService.Received(1).Delete(Arg.Any<string>()); } } }<file_sep>/src/wikia/article/src/Tests/Unit/article.domain.unit.tests/ArticleListTests/ItemTests/BanlistItemProcessorTests/ProcessItemTests.cs using article.core.Models; using article.domain.ArticleList.Item; using article.domain.Services.Messaging; using article.tests.core; using FluentAssertions; using NSubstitute; using NSubstitute.ExceptionExtensions; using NUnit.Framework; using System; using System.Threading.Tasks; using wikia.Models.Article.AlphabeticalList; namespace article.domain.unit.tests.ArticleListTests.ItemTests.BanlistItemProcessorTests { [TestFixture] [Category(TestType.Unit)] public class ProcessItemTests { private IBanlistArticleQueue _banlistArticleQueue; private BanlistItemProcessor _sut; [SetUp] public void SetUp() { _banlistArticleQueue = Substitute.For<IBanlistArticleQueue>(); _sut = new BanlistItemProcessor(_banlistArticleQueue); } [Test] public async Task Given_A_Valid_Article_Should_Process_Article_Successfully() { // Arrange var article = new UnexpandedArticle(); // Act var result = await _sut.ProcessItem(article); // Assert result.IsSuccessfullyProcessed.Should().BeTrue(); } [Test] public async Task Given_A_Valid_Article_If_An_Exception_Is_Thrown_IsSuccessfullyProcessed_Variable_Should_False() { // Arrange var article = new UnexpandedArticle(); _banlistArticleQueue.Publish(Arg.Any<UnexpandedArticle>()).Throws(new Exception()); // Act var result = await _sut.ProcessItem(article); // Assert result.IsSuccessfullyProcessed.Should().BeFalse(); } [Test] public async Task Given_A_Valid_Article_If_An_Exception_Is_Thrown_Exception_Variable_Should_Be_Initialised() { // Arrange var article = new UnexpandedArticle(); _banlistArticleQueue.Publish(Arg.Any<UnexpandedArticle>()).Throws(new Exception()); // Act var result = await _sut.ProcessItem(article); // Assert result.Failed.Should().NotBeNull(); } [Test] public void Given_A_Invalid_Article_Should_Throw_NullArgument() { // Arrange // Act Func<Task<ArticleTaskResult>> act = () => _sut.ProcessItem(null); // Assert act.Should().ThrowAsync<ArgumentNullException>(); } } }<file_sep>/src/wikia/processor/banlistprocessor/src/Infrastructure/banlistprocessor.infrastructure/InfrastructureInstaller.cs using banlistprocessor.domain.Repository; using banlistprocessor.infrastructure.Database; using banlistprocessor.infrastructure.Repository; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; namespace banlistprocessor.infrastructure { public static class InfrastructureInstaller { public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, string connectionString) { services.AddYgoDatabase(connectionString) .AddRepositories(); return services; } public static IServiceCollection AddYgoDatabase(this IServiceCollection services, string connectionString) { services.AddDbContext<YgoDbContext>(c => c.UseSqlServer(connectionString), ServiceLifetime.Transient); return services; } public static IServiceCollection AddRepositories(this IServiceCollection services) { services.AddTransient<IBanlistCardRepository, BanlistCardRepository>(); services.AddTransient<IBanlistRepository, BanlistRepository>(); services.AddTransient<ICardRepository, CardRepository>(); services.AddTransient<IFormatRepository, FormatRepository>(); services.AddTransient<ILimitRepository, LimitRepository>(); return services; } } }<file_sep>/src/wikia/article/src/Infrastructure/article.infrastructure/Services/Messaging/Cards/CardArticleQueue.cs using article.core.Models; using article.domain.Services.Messaging; using article.domain.Services.Messaging.Cards; using article.domain.Settings; using Microsoft.Extensions.Options; using System.Threading.Tasks; using wikia.Models.Article.AlphabeticalList; namespace article.infrastructure.Services.Messaging.Cards { public class CardArticleQueue : ICardArticleQueue { private readonly IQueue<Article> _queue; public CardArticleQueue(IOptions<AppSettings> appSettings, IQueue<Article> queue) { _queue = queue; } public Task Publish(UnexpandedArticle article) { return _queue.Publish(article); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Dto/SubCategoryDto.cs namespace cardprocessor.application.Dto { public class SubCategoryDto { public long? Id { get; set; } public long CategoryId { get; set; } public string Name { get; set; } } }<file_sep>/src/wikia/processor/cardprocessor/src/Infrastructure/cardprocessor.infrastructure/Repository/LimitRepository.cs using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using cardprocessor.core.Models.Db; using cardprocessor.domain.Repository; using cardprocessor.infrastructure.Database; using Microsoft.EntityFrameworkCore; namespace cardprocessor.infrastructure.Repository { public class LimitRepository : ILimitRepository { private readonly YgoDbContext _dbContext; public LimitRepository(YgoDbContext dbContext) { _dbContext = dbContext; } public Task<List<Limit>> AllLimits() { return _dbContext.Limit.OrderBy(c => c.Name).ToListAsync(); } } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Application/archetypeprocessor.application/MessageConsumers/ArchetypeInformation/ArchetypeInformationConsumerHandler.cs using System.Linq; using System.Threading; using System.Threading.Tasks; using archetypeprocessor.core.Models; using archetypeprocessor.core.Processor; using FluentValidation; using MediatR; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace archetypeprocessor.application.MessageConsumers.ArchetypeInformation { public class ArchetypeInformationConsumerHandler : IRequestHandler<ArchetypeInformationConsumer, ArchetypeInformationConsumerResult> { private readonly IArchetypeProcessor _archetypeProcessor; private readonly IValidator<ArchetypeInformationConsumer> _validator; private readonly ILogger<ArchetypeInformationConsumerHandler> _logger; public ArchetypeInformationConsumerHandler(IArchetypeProcessor archetypeProcessor, IValidator<ArchetypeInformationConsumer> validator, ILogger<ArchetypeInformationConsumerHandler> logger) { _archetypeProcessor = archetypeProcessor; _validator = validator; _logger = logger; } public async Task<ArchetypeInformationConsumerResult> Handle(ArchetypeInformationConsumer request, CancellationToken cancellationToken) { var archetypeInformationConsumerResult = new ArchetypeInformationConsumerResult(); var validationResults = _validator.Validate(request); if (validationResults.IsValid) { var archetypeArticle = JsonConvert.DeserializeObject<ArchetypeMessage>(request.Message); _logger.LogInformation("Processing archetype '{@Title}'", archetypeArticle.Name); var results = await _archetypeProcessor.Process(archetypeArticle); _logger.LogInformation("Finished processing archetype '{@Title}'", archetypeArticle.Name); if (!results.IsSuccessful) { archetypeInformationConsumerResult.Errors.AddRange(results.Errors); } } else { archetypeInformationConsumerResult.Errors = validationResults.Errors.Select(err => err.ErrorMessage).ToList(); } return archetypeInformationConsumerResult; } } }<file_sep>/src/wikia/semanticsearch/src/Tests/Unit/semanticsearch.domain.unit.tests/SemanticSearchConsumerTests/ProcessTests.cs using System.Threading.Tasks; using FluentAssertions; using Microsoft.Extensions.Logging; using NSubstitute; using NUnit.Framework; using semanticsearch.core.Model; using semanticsearch.domain.Messaging.Exchanges; using semanticsearch.domain.Search.Consumer; using semanticsearch.tests.core; namespace semanticsearch.domain.unit.tests.SemanticSearchConsumerTests { [TestFixture] [Category(TestType.Unit)] public class ProcessTests { private SemanticSearchConsumer _sut; private IArticleHeaderExchange _articleHeaderExchange; [SetUp] public void SetUp() { _articleHeaderExchange = Substitute.For<IArticleHeaderExchange>(); _sut = new SemanticSearchConsumer(Substitute.For<ILogger<SemanticSearchConsumer>>(), _articleHeaderExchange); } [Test] public async Task Given_A_SemanticCard_Should_Invoke_Publish_Once() { // Arrange var semanticCard = new SemanticCard(); // Act await _sut.Process(semanticCard); // Assert await _articleHeaderExchange.Received(1).Publish(Arg.Is(semanticCard)); } [Test] public async Task Given_A_SemanticCard_If_Process_Executed_Successful_IsSuccessful_Should_Be_True() { // Arrange var semanticCard = new SemanticCard(); // Act var result = await _sut.Process(semanticCard); // Assert result.IsSuccessful.Should().BeTrue(); } } } <file_sep>/src/wikia/processor/banlistprocessor/src/Tests/Unit/banlistprocessor.domain.unit.tests/BanlistServiceTests/BanlistExistTests.cs using System.Threading.Tasks; using AutoMapper; using banlistprocessor.core.Services; using banlistprocessor.domain.Mappings.Profiles; using banlistprocessor.domain.Repository; using banlistprocessor.domain.Services; using banlistprocessor.tests.core; using NSubstitute; using NUnit.Framework; namespace banlistprocessor.domain.unit.tests.BanlistServiceTests { [TestFixture] [Category(TestType.Unit)] public class BanlistExistTests { private BanlistService _sut; private IBanlistRepository _banlistRepository; private IBanlistCardService _banlistCardService; private IFormatRepository _formatRepository; [SetUp] public void SetUp() { var config = new MapperConfiguration ( cfg => { cfg.AddProfile(new BanlistProfile()); } ); var mapper = config.CreateMapper(); _banlistRepository = Substitute.For<IBanlistRepository>(); _banlistCardService = Substitute.For<IBanlistCardService>(); _formatRepository = Substitute.For<IFormatRepository>(); _sut = new BanlistService ( _banlistCardService, _banlistRepository, _formatRepository, mapper ); } [Test] public async Task Given_A_Banlist_Id_Should_Invoke_BanlistExist_Method_Once() { // Arrange const int expected = 1; const int id = 123; // Act await _sut.BanlistExist(id); // Assert await _banlistRepository.Received(expected).BanlistExist(Arg.Any<int>()); } } } <file_sep>/src/wikia/processor/cardsectionprocessor/src/Infrastructure/cardsectionprocessor.infrastructure/Database/IYgoDbContext.cs using cardsectionprocessor.core.Models.Db; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; namespace cardsectionprocessor.infrastructure.Database { public interface IYgoDbContext { DbSet<Category> Category { get; set; } DatabaseFacade Database { get; } int SaveChanges(); } }<file_sep>/src/wikia/processor/cardprocessor/src/Tests/Unit/cardprocessor.domain.unit.tests/ServiceTests/CardServiceTests/AddTests.cs using System.Collections.Generic; using System.Threading.Tasks; using cardprocessor.core.Enums; using cardprocessor.core.Models; using cardprocessor.core.Models.Db; using cardprocessor.core.Strategies; using cardprocessor.domain.Repository; using cardprocessor.domain.Services; using cardprocessor.tests.core; using NSubstitute; using NUnit.Framework; namespace cardprocessor.domain.unit.tests.ServiceTests.CardServiceTests { [TestFixture] [Category(TestType.Unit)] public class AddTests { private IEnumerable<ICardTypeStrategy> _cardTypeStrategies; private ICardRepository _cardRepository; private CardService _sut; [SetUp] public void SetUp() { _cardTypeStrategies = Substitute.For<IEnumerable<ICardTypeStrategy>>(); _cardRepository = Substitute.For<ICardRepository>(); _sut = new CardService(_cardTypeStrategies, _cardRepository); } [Test] public async Task Given_A_Card_Should_Invoke_Add_Method_Once() { // Arrange var cardModel = new CardModel { CardType = YugiohCardType.Monster }; var handler = Substitute.For<ICardTypeStrategy>(); handler.Handles(Arg.Any<YugiohCardType>()).Returns(true); handler.Add(Arg.Any<CardModel>()).Returns(new Card()); _cardTypeStrategies.GetEnumerator().Returns(new List<ICardTypeStrategy>{ handler }.GetEnumerator()); // Act await _sut.Add(cardModel); // Assert await handler.Received(1).Add(Arg.Is(cardModel)); } } }<file_sep>/src/wikia/data/archetypedata/src/Tests/Integration/archetypedata.infrastructure.integration.tests/WebPagesTests/ArchetypeThumbnailTests/FromWebPageTests.cs using archetypedata.application.Configuration; using archetypedata.infrastructure.WebPages; using archetypedata.tests.core; using FluentAssertions; using Microsoft.Extensions.Options; using NSubstitute; using NUnit.Framework; using wikia.Api; namespace archetypedata.infrastructure.integration.tests.WebPagesTests.ArchetypeThumbnailTests { [TestFixture] [Category(TestType.Integration)] public class FromWebPageTests { private ArchetypeThumbnail _sut; private IOptions<AppSettings> _appsettings; [SetUp] public void SetUp() { _appsettings = Substitute.For<IOptions<AppSettings>>(); _sut = new ArchetypeThumbnail(Substitute.For<IWikiArticle>(), new HtmlWebPage(), _appsettings); } [TestCase("/wiki/Metaphys", "https://static.wikia.nocookie.net/yugioh/images/0/0a/Metaphys.png")] public void Given_An_Archetype_Web_Page_Url_Should_Return_Thumbnail_Url(string archetypeUrl, string expected) { // Arrange _appsettings.Value.Returns(new AppSettings {WikiaDomainUrl = "https://yugioh.fandom.com"}); // Act var result = _sut.FromWebPage(archetypeUrl); // Assert result.Should().BeEquivalentTo(expected); } } }<file_sep>/src/wikia/data/archetypedata/src/Tests/Integration/archetypedata.infrastructure.integration.tests/WebPagesTests/ArchetypeWebPageTests/CardsTests.cs using System; using archetypedata.application.Configuration; using archetypedata.domain.WebPages; using archetypedata.infrastructure.WebPages; using archetypedata.tests.core; using FluentAssertions; using Microsoft.Extensions.Options; using NSubstitute; using NUnit.Framework; namespace archetypedata.infrastructure.integration.tests.WebPagesTests.ArchetypeWebPageTests { [TestFixture] [Category(TestType.Integration)] public class CardsTests { private ArchetypeWebPage _sut; [SetUp] public void SetUp() { _sut = new ArchetypeWebPage(Substitute.For<IOptions<AppSettings>>(), new HtmlWebPage(), Substitute.For<IArchetypeThumbnail>()); } [TestCase("https://yugioh.fandom.com/wiki/List_of_%22/Assault_Mode%22_cards", new [] {"Stardust Dragon/Assault Mode", "Colossal Fighter/Assault Mode", "Arcanite Magician/Assault Mode" })] [TestCase("https://yugioh.fandom.com/wiki/List_of_%22Elemental_HERO%22_cards", new [] { "Contrast HERO Chaos", "Elemental HERO Plasma Vice", "Elemental HERO Voltic" })] public void Given_An_Archetype_Web_Page_Uri_Should_Extract_Card_Names_From_Web_Page(string archetypeUrl, string[] expected) { // Arrange var archetypeUri = new Uri(archetypeUrl); // Act var result = _sut.Cards(archetypeUri); // Assert result.Should().Contain(expected); } } }<file_sep>/src/wikia/data/carddata/src/Infrastructure/carddata.infrastructure/Services/Messaging/Cards/YugiohCardQueue.cs using carddata.application.Configuration; using carddata.core.Exceptions; using carddata.core.Models; using carddata.domain.Services.Messaging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using RabbitMQ.Client; using System.Linq; using System.Threading.Tasks; namespace carddata.infrastructure.Services.Messaging.Cards { public class YugiohCardQueue : IYugiohCardQueue { private readonly IOptions<RabbitMqSettings> _rabbitMqConfig; public YugiohCardQueue(IOptions<RabbitMqSettings> rabbitMqConfig) { _rabbitMqConfig = rabbitMqConfig; } public Task<YugiohCardCompletion> Publish(ArticleProcessed articleProcessed) { var yugiohCardCompletion = new YugiohCardCompletion(); yugiohCardCompletion.Card = articleProcessed.Card; yugiohCardCompletion.Article = articleProcessed.Article; try { var messageBodyBytes = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(articleProcessed.Card)); var factory = new ConnectionFactory() { HostName = _rabbitMqConfig.Value.Host, Port = _rabbitMqConfig.Value.Port}; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { var props = channel.CreateBasicProperties(); props.ContentType = _rabbitMqConfig.Value.ContentType; props.DeliveryMode = _rabbitMqConfig.Value.Exchanges[RabbitMqExchangeConstants.YugiohHeadersData].PersistentMode; props.Headers = _rabbitMqConfig.Value.Exchanges[RabbitMqExchangeConstants.YugiohHeadersData].Headers.ToDictionary(k => k.Key, k => (object)k.Value); channel.BasicPublish ( RabbitMqExchangeConstants.YugiohHeadersData, "", props, messageBodyBytes ); } yugiohCardCompletion.IsSuccessful = true; } catch (System.Exception ex) { yugiohCardCompletion.Exception = new YugiohCardException { Card = articleProcessed.Card, Exception = ex }; } return Task.FromResult(yugiohCardCompletion); } } }<file_sep>/src/wikia/article/src/Infrastructure/article.infrastructure/Services/Messaging/ArticleQueue.cs using article.core.Models; using article.domain.Services.Messaging; using article.domain.Settings; using Microsoft.Extensions.Options; using Newtonsoft.Json; using RabbitMQ.Client; using System; using System.Linq; using System.Threading.Tasks; using wikia.Models.Article.AlphabeticalList; namespace article.infrastructure.Services.Messaging { public class ArticleQueue : IQueue<Article> { private readonly IOptions<RabbitMqSettings> _rabbitMqConfig; private readonly IOptions<AppSettings> _appSettings; public ArticleQueue(IOptions<RabbitMqSettings> rabbitMqConfig, IOptions<AppSettings> appSettings) { _rabbitMqConfig = rabbitMqConfig; _appSettings = appSettings; } public Task Publish(UnexpandedArticle message) { var messageToBeSent = new Article { Id = message.Id, CorrelationId = Guid.NewGuid(), Title = message.Title, Url = new Uri(new Uri(_appSettings.Value.WikiaDomainUrl), message.Url).AbsoluteUri }; return Publish(messageToBeSent); } public Task Publish(Article message) { var messageBodyBytes = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)); var factory = new ConnectionFactory() { HostName = _rabbitMqConfig.Value.Host, Port = _rabbitMqConfig.Value.Port }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { var props = channel.CreateBasicProperties(); props.ContentType = _rabbitMqConfig.Value.ContentType; props.DeliveryMode = _rabbitMqConfig.Value.Exchanges[RabbitMqExchangeConstants.YugiohHeadersArticleExchange].PersistentMode; props.Headers = _rabbitMqConfig.Value.Exchanges[RabbitMqExchangeConstants.YugiohHeadersArticleExchange].Headers.ToDictionary(k => k.Key, k => (object)k.Value); channel.BasicPublish ( RabbitMqExchangeConstants.YugiohHeadersArticleExchange, string.Empty, props, messageBodyBytes ); } return Task.CompletedTask; } } }<file_sep>/src/wikia/article/src/Domain/article.domain/ArticleList/DataSource/ArticleCategoryDataSource.cs using article.core.ArticleList.DataSource; using System; using System.Collections.Generic; using wikia.Api; using wikia.Models.Article; using wikia.Models.Article.AlphabeticalList; namespace article.domain.ArticleList.DataSource { public class ArticleCategoryDataSource : IArticleCategoryDataSource { private readonly IWikiArticleList _articleList; public ArticleCategoryDataSource(IWikiArticleList articleList) { _articleList = articleList; } public async IAsyncEnumerable<UnexpandedArticle[]> Producer(string category, int pageSize) { if (string.IsNullOrWhiteSpace(category)) throw new ArgumentException("Article Category cannot be null or empty", nameof(category)); var nextBatch = await _articleList.AlphabeticalList(new ArticleListRequestParameters { Category = category, Limit = pageSize }); bool isNextBatchAvailable; yield return nextBatch.Items; do { isNextBatchAvailable = !string.IsNullOrEmpty(nextBatch.Offset); if (isNextBatchAvailable) { nextBatch = await _articleList.AlphabeticalList(new ArticleListRequestParameters { Category = category, Limit = pageSize, Offset = nextBatch.Offset }); yield return nextBatch.Items; } } while (isNextBatchAvailable); } } }<file_sep>/src/wikia/article/src/Application/article.application/ScheduledTasks/Articles/ArticleInformationTaskValidator.cs using FluentValidation; namespace article.application.ScheduledTasks.Articles { public class ArticleInformationTaskValidator : AbstractValidator<ArticleInformationTask> { private const int MaxPageSize = 500; public ArticleInformationTaskValidator() { RuleFor(bl => bl.Category) .Cascade(CascadeMode.Stop) .NotNull() .NotEmpty(); RuleFor(bl => bl.PageSize) .GreaterThan(0) .LessThanOrEqualTo(MaxPageSize); } } }<file_sep>/src/wikia/semanticsearch/src/Infrastructure/semanticsearch.infrastructure/WebPage/SemanticSearchResultsWebPage.cs using System; using System.Net; using HtmlAgilityPack; using semanticsearch.domain.WebPage; namespace semanticsearch.infrastructure.WebPage { public class SemanticSearchResultsWebPage : ISemanticSearchResultsWebPage { private readonly IHtmlWebPage _htmlWebPage; private HtmlDocument _currentWebPage; public Uri CurrentWebPageUri { get; private set; } public SemanticSearchResultsWebPage(IHtmlWebPage htmlWebPage) { _htmlWebPage = htmlWebPage; } public void Load(string url) { CurrentWebPageUri = new Uri(url); _currentWebPage = _htmlWebPage.Load(url); } public HtmlNodeCollection TableRows => _currentWebPage .DocumentNode .SelectNodes("//table[contains(@class, 'sortable wikitable smwtable')]/tbody/tr") ?? _currentWebPage.DocumentNode.SelectNodes("//table[contains(@class, 'sortable wikitable smwtable card-list')]/tbody/tr"); public bool HasNextPage => NextPage != null; public HtmlNode NextPage => _currentWebPage.DocumentNode.SelectSingleNode("//a[contains(text(), 'next') and contains(@title, 'Next 500 results')]"); public string NextPageLink() { var hrefLink = $"{CurrentWebPageUri.GetLeftPart(UriPartial.Authority)}{NextPage.Attributes["href"].Value}"; return WebUtility.HtmlDecode(hrefLink); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Tests/Unit/cardprocessor.application.unit.tests/HelperTests/CardTests/MonsterCardHelperTests/MonsterTypeIdsTests.cs using System.Collections.Generic; using cardprocessor.application.Helpers.Cards; using cardprocessor.core.Models; using cardprocessor.tests.core; using FluentAssertions; using NUnit.Framework; namespace cardprocessor.application.unit.tests.HelperTests.CardTests.MonsterCardHelperTests { [TestFixture] [Category(TestType.Unit)] public class MonsterTypeIdsTests { [Test] public void Given_A_Valid_A_Link_Monster_YugiohCard_With_Types_Should_Map_To_TypeIds_Property() { // Arrange var expected = new List<int> { 5 }; var yugiohCard = new YugiohCard { Name = "<NAME>", Description = "Amazing card!", CardNumber = "01861629", Attribute = "Dark", Types = "Cyberse / Link / Effect", CardType = "Monster", LinkArrows = " Bottom-Left, Top, Bottom-Right", ImageUrl = "https://vignette.wikia.nocookie.net/yugioh/images/5/5d/DecodeTalker-YS18-EN-C-1E.png/revision/latest/scale-to-width-down/300?cb=20180712163921" }; // Act var result = MonsterCardHelper.MonsterTypeIds(yugiohCard, TestData.AllTypes()); // Assert result.Should().BeEquivalentTo(expected); } } }<file_sep>/src/wikia/data/archetypedata/src/Infrastructure/archetypedata.infrastructure/InfrastructureInstaller.cs using archetypedata.core.Models; using archetypedata.domain.Services.Messaging; using archetypedata.domain.WebPages; using archetypedata.infrastructure.Services.Messaging; using archetypedata.infrastructure.WebPages; using Microsoft.Extensions.DependencyInjection; namespace archetypedata.infrastructure { public static class InfrastructureInstaller { public static IServiceCollection AddInfrastructureServices(this IServiceCollection services) { services.AddMessagingServices(); return services; } public static IServiceCollection AddMessagingServices(this IServiceCollection services) { services.AddTransient<IHtmlWebPage, HtmlWebPage>(); services.AddTransient<IArchetypeThumbnail, ArchetypeThumbnail>(); services.AddTransient<IArchetypeWebPage, ArchetypeWebPage>(); services.AddTransient<IQueue<Archetype>, ArchetypeQueue>(); services.AddTransient<IQueue<ArchetypeCard>, ArchetypeCardQueue>(); return services; } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Domain/cardsectionprocessor.domain/Strategy/CardTriviaProcessorStrategy.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using cardsectionprocessor.core.Constants; using cardsectionprocessor.core.Models; using cardsectionprocessor.core.Models.Db; using cardsectionprocessor.core.Service; using cardsectionprocessor.core.Strategy; namespace cardsectionprocessor.domain.Strategy { public class CardTriviaProcessorStrategy : ICardSectionProcessorStrategy { private readonly ICardService _cardService; private readonly ICardTriviaService _cardTriviaService; public CardTriviaProcessorStrategy(ICardService cardService, ICardTriviaService cardTriviaService) { _cardService = cardService; _cardTriviaService = cardTriviaService; } public async Task<CardSectionDataTaskResult<CardSectionMessage>> Process(CardSectionMessage cardSectionData) { var cardSectionDataTaskResult = new CardSectionDataTaskResult<CardSectionMessage> { CardSectionData = cardSectionData }; var card = await _cardService.CardByName(cardSectionData.Name); if (card != null) { await _cardTriviaService.DeleteByCardId(card.Id); var triviaSections = new List<TriviaSection>(); foreach (var cardSection in cardSectionData.CardSections) { var triviaSection = new TriviaSection { CardId = card.Id, Name = cardSection.Name, Created = DateTime.UtcNow, Updated = DateTime.UtcNow }; foreach (var trivia in cardSection.ContentList) { triviaSection.Trivia.Add(new Trivia { TriviaSection = triviaSection, Text = trivia, Created = DateTime.UtcNow, Updated = DateTime.UtcNow }); } triviaSections.Add(triviaSection); } if (triviaSections.Any()) { await _cardTriviaService.Update(triviaSections); } } else { cardSectionDataTaskResult.Errors.Add($"Card Trivia: card '{cardSectionData.Name}' not found."); } return cardSectionDataTaskResult; } public bool Handles(string category) { return category == ArticleCategory.CardTrivia; } } }<file_sep>/src/wikia/article/src/Core/article.core/ArticleList/Processor/IArticleItemProcessor.cs using System.Threading.Tasks; using article.core.Models; using wikia.Models.Article.AlphabeticalList; namespace article.core.ArticleList.Processor { public interface IArticleItemProcessor { Task<ArticleTaskResult> ProcessItem(UnexpandedArticle item); bool Handles(string category); } }<file_sep>/src/wikia/data/cardsectiondata/src/Domain/cardsectiondata.domain/WebPages/ITipRelatedWebPage.cs using cardsectiondata.core.Models; namespace cardsectiondata.domain.WebPages { public interface ITipRelatedWebPage { void GetTipRelatedCards(CardSection section, Article article); } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Domain/cardsectionprocessor.domain/Service/CardService.cs using System.Threading.Tasks; using cardsectionprocessor.core.Models.Db; using cardsectionprocessor.core.Service; using cardsectionprocessor.domain.Repository; namespace cardsectionprocessor.domain.Service { public class CardService : ICardService { private readonly ICardRepository _cardRepository; public CardService(ICardRepository cardRepository) { _cardRepository = cardRepository; } public Task<Card> CardByName(string name) { return _cardRepository.CardByName(name); } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Infrastructure/cardsectionprocessor.infrastructure/Repository/CardRulingRepository.cs using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using cardsectionprocessor.core.Models.Db; using cardsectionprocessor.domain.Repository; using cardsectionprocessor.infrastructure.Database; using Microsoft.EntityFrameworkCore; namespace cardsectionprocessor.infrastructure.Repository { public class CardRulingRepository : ICardRulingRepository { private readonly YgoDbContext _context; public CardRulingRepository(YgoDbContext context) { _context = context; } public async Task DeleteByCardId(long cardId) { var rulingSections = await _context .RulingSection .Include(t => t.Card) .Include(t => t.Ruling) .Where(ts => ts.CardId == cardId) .ToListAsync(); if (rulingSections.Any()) { _context.Ruling.RemoveRange(rulingSections.SelectMany(t => t.Ruling)); _context.RulingSection.RemoveRange(rulingSections); await _context.SaveChangesAsync(); } } public async Task Update(List<RulingSection> rulingSections) { _context.RulingSection.UpdateRange(rulingSections); await _context.SaveChangesAsync(); } } }<file_sep>/src/wikia/semanticsearch/src/Core/semanticsearch.core/Search/ISemanticSearchProducer.cs using semanticsearch.core.Model; using System.Collections.Generic; namespace semanticsearch.core.Search { public interface ISemanticSearchProducer { IEnumerable<SemanticCard> Producer(string url); } }<file_sep>/src/wikia/article/src/Domain/article.domain/ArticleList/Processor/ArticleProcessor.cs using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using article.core.ArticleList.Processor; using article.core.Models; using wikia.Models.Article.AlphabeticalList; namespace article.domain.ArticleList.Processor { public sealed class ArticleProcessor : IArticleProcessor { private readonly IEnumerable<IArticleItemProcessor> _articleItemProcessors; public ArticleProcessor(IEnumerable<IArticleItemProcessor> articleItemProcessors) { _articleItemProcessors = articleItemProcessors; } public Task<ArticleTaskResult> Process(string category, UnexpandedArticle article) { var handler = _articleItemProcessors.Single(h => h.Handles(category)); return handler.ProcessItem(article); } } }<file_sep>/src/wikia/data/banlistdata/src/Tests/Unit/banlistdata.domain.unit.tests/HelpersTests/StringHelpersTests/RemoveBetweenTests.cs using System; using banlistdata.domain.Helpers; using banlistdata.tests.core; using FluentAssertions; using NUnit.Framework; namespace banlistdata.domain.unit.tests.HelpersTests.StringHelpersTests { [TestFixture] [Category(TestType.Unit)] public class RemoveBetweenTests { [TestCase("Fishborg Blaster 「フィッシュボーグ-ガンナー」", "Fishborg Blaster")] [TestCase("Majespecter Unicorn - Kirin 「マジェスペクター・ユニコーン」", "Majespecter Unicorn - Kirin")] [TestCase("The Tyrant Neptune 「The tyrant NEPTUNEザ・タイラント・ネプチューン」", "The Tyrant Neptune")] public void Given_A_CardName_With_Japanese_Characters_Should_Remove_Invalid_Characters(string cardName, string expected) { // Arrange const char beginChar = '「'; const char endChar = '」'; // Act var result = StringHelpers.RemoveBetween(cardName, beginChar, endChar); // Assert result.Should().BeEquivalentTo(expected); } [TestCase("List of \"Fire King\" cards", "Fire King")] [TestCase("List of \"Gravekeeper's\" cards", "Gravekeeper's")] [TestCase("List of \"/Assault Mode\" cards", "/Assault Mode")] public void Given_An_Archetype_ListTitle_Should_Return_Archetype_Name(string archetypeListTitle, string expected) { // Arrange // Act var result = StringHelpers.ArchetypeNameFromListTitle(archetypeListTitle); // Assert result.Should().BeEquivalentTo(expected); } [Test] public void Given_An_Invalid_Archetype_ListTitle_Should_Throw_ArgumentNullException() { // Arrange // Act Action act = () => StringHelpers.ArchetypeNameFromListTitle(null); // Assert act.Should().Throw<ArgumentNullException>(); } [Test] public void Given_An_Invalid_Archetype_ListTitle_Should_Return_Null() { // Arrange // Act var result = StringHelpers.ArchetypeNameFromListTitle("title"); // Assert result.Should().BeNull(); } } }<file_sep>/src/wikia/article/src/Infrastructure/article.infrastructure/Services/Messaging/Cards/SemanticCardArticleQueue.cs using article.core.Models; using article.domain.Services.Messaging; using article.domain.Services.Messaging.Cards; using System; using System.Threading.Tasks; using wikia.Models.Article.AlphabeticalList; namespace article.infrastructure.Services.Messaging.Cards { public class SemanticCardArticleQueue : ISemanticCardArticleQueue { private readonly IQueue<Article> _queue; public SemanticCardArticleQueue(IQueue<Article> queue) { _queue = queue; } public Task Publish(UnexpandedArticle article) { var messageToBeSent = new Article { Id = article.Id, CorrelationId = Guid.NewGuid() }; return _queue.Publish(messageToBeSent); } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Presentation/cardsectionprocessor/Services/CardSectionProcessorHostedService.cs using System; using System.Text; using System.Threading; using System.Threading.Tasks; using cardsectionprocessor.application.Configuration; using cardsectionprocessor.application.MessageConsumers.CardRulingInformation; using cardsectionprocessor.application.MessageConsumers.CardTipInformation; using cardsectionprocessor.application.MessageConsumers.CardTriviaInformation; using MediatR; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using RabbitMQ.Client; using RabbitMQ.Client.Events; using Serilog; using Serilog.Events; using Serilog.Formatting.Json; namespace cardsectionprocessor.Services { public class CardSectionProcessorHostedService : BackgroundService { private const string CardTipDataQueue = "card-tips-data"; private const string CardRulingDataQueue = "card-rulings-data"; private const string CardTriviaDataQueue = "card-trivia-data"; public IServiceProvider Services { get; } private readonly IOptions<RabbitMqSettings> _rabbitMqOptions; private readonly IOptions<AppSettings> _appSettingsOptions; private readonly IMediator _mediator; private ConnectionFactory _factory; private IConnection _cardTipConnection; private IModel _cardTipDataChannel; private EventingBasicConsumer _cardTipDataConsumer; private EventingBasicConsumer _cardRulingDataConsumer; private IModel _cardRulingDataChannel; private IConnection _cardRulingConnection; private IConnection _cardTriviaConnection; private EventingBasicConsumer _cardTriviaDataConsumer; private IModel _cardTriviaDataChannel; public CardSectionProcessorHostedService ( IServiceProvider services, IOptions<RabbitMqSettings> rabbitMqOptions, IOptions<AppSettings> appSettingsOptions, IMediator mediator ) { Services = services; _rabbitMqOptions = rabbitMqOptions; _appSettingsOptions = appSettingsOptions; _mediator = mediator; ConfigureSerilog(); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { await StartConsumer(); } public override void Dispose() { _cardTipDataChannel.Close(); _cardTipConnection.Close(); _cardRulingDataChannel.Close(); _cardRulingConnection.Close(); _cardTriviaDataChannel.Close(); _cardTriviaConnection.Close(); base.Dispose(); } #region private helper private Task StartConsumer() { _factory = new ConnectionFactory() { HostName = _rabbitMqOptions.Value.Host }; _cardTipConnection = _factory.CreateConnection(); _cardRulingConnection = _factory.CreateConnection(); _cardTriviaConnection = _factory.CreateConnection(); _cardTipDataConsumer = CreateCardTipDataConsumer(_cardTipConnection); _cardRulingDataConsumer = CreateCardRulingDataConsumer(_cardRulingConnection); _cardTriviaDataConsumer = CreateCardTriviaDataConsumer(_cardTriviaConnection); return Task.CompletedTask; } private EventingBasicConsumer CreateCardTriviaDataConsumer(IConnection connection) { _cardTriviaDataChannel = connection.CreateModel(); _cardTriviaDataChannel.BasicQos(0, 1, false); var consumer = new EventingBasicConsumer(_cardTriviaDataChannel); consumer.Received += async (model, ea) => { try { var body = ea.Body; var message = Encoding.UTF8.GetString(body); var result = await _mediator.Send(new CardTriviaInformationConsumer { Message = message }); if (result.IsSuccessful) { _cardTriviaDataChannel.BasicAck(ea.DeliveryTag, false); } else { _cardTriviaDataChannel.BasicNack(ea.DeliveryTag, false, false); } } catch (Exception ex) { Log.Logger.Error("RabbitMq Consumer: " + CardTriviaDataQueue + " exception. Exception: {@Exception}", ex); } }; consumer.Shutdown += OnCardTriviaDataConsumerShutdown; consumer.Registered += OnCardTriviaDataConsumerRegistered; consumer.Unregistered += OnCardTriviaDataConsumerUnregistered; consumer.ConsumerCancelled += OnCardTriviaDataConsumerCancelled; _cardTriviaDataChannel.BasicConsume ( queue: CardTriviaDataQueue, autoAck: false, consumer: consumer ); return consumer; } private EventingBasicConsumer CreateCardTipDataConsumer(IConnection connection) { _cardTipDataChannel = connection.CreateModel(); _cardTipDataChannel.BasicQos(0, 1, false); var consumer = new EventingBasicConsumer(_cardTipDataChannel); consumer.Received += async (model, ea) => { try { var body = ea.Body; var message = Encoding.UTF8.GetString(body); var result = await _mediator.Send(new CardTipInformationConsumer { Message = message }); if (result.IsSuccessful) { _cardTipDataChannel.BasicAck(ea.DeliveryTag, false); } else { _cardTipDataChannel.BasicNack(ea.DeliveryTag, false, false); } } catch (Exception ex) { Log.Logger.Error("RabbitMq Consumer: " + CardTipDataQueue + " exception. Exception: {@Exception}", ex); } }; consumer.Shutdown += OnCardTipDataConsumerShutdown; consumer.Registered += OnCardTipDataConsumerRegistered; consumer.Unregistered += OnCardTipDataConsumerUnregistered; consumer.ConsumerCancelled += OnCardTipDataConsumerCancelled; _cardTipDataChannel.BasicConsume ( queue: CardTipDataQueue, autoAck: false, consumer: consumer ); return consumer; } private EventingBasicConsumer CreateCardRulingDataConsumer(IConnection connection) { _cardRulingDataChannel = connection.CreateModel(); _cardRulingDataChannel.BasicQos(0, 1, false); var consumer = new EventingBasicConsumer(_cardRulingDataChannel); consumer.Received += async (model, ea) => { try { var body = ea.Body; var message = Encoding.UTF8.GetString(body); var result = await _mediator.Send(new CardRulingInformationConsumer { Message = message }); if (result.IsSuccessful) { _cardRulingDataChannel.BasicAck(ea.DeliveryTag, false); } else { _cardRulingDataChannel.BasicNack(ea.DeliveryTag, false, false); } } catch (Exception ex) { Log.Logger.Error("RabbitMq Consumer: " + CardRulingDataQueue + " exception. Exception: {@Exception}", ex); } }; consumer.Shutdown += OnCardRulingDataConsumerShutdown; consumer.Registered += OnCardRulingDataConsumerRegistered; consumer.Unregistered += OnCardRulingDataConsumerUnregistered; consumer.ConsumerCancelled += OnCardRulingDataConsumerCancelled; _cardRulingDataChannel.BasicConsume ( queue: CardRulingDataQueue, autoAck: false, consumer: consumer ); return consumer; } private static void OnCardTipDataConsumerCancelled(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{CardTipDataQueue}' Cancelled"); } private static void OnCardTipDataConsumerUnregistered(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{CardTipDataQueue}' Unregistered");} private static void OnCardTipDataConsumerRegistered(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{CardTipDataQueue}' Registered"); } private static void OnCardTipDataConsumerShutdown(object sender, ShutdownEventArgs e) { Log.Logger.Information($"Consumer '{CardTipDataQueue}' Shutdown"); } private static void OnCardRulingDataConsumerCancelled(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{CardRulingDataQueue}' Cancelled"); } private static void OnCardRulingDataConsumerUnregistered(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{CardRulingDataQueue}' Unregistered");} private static void OnCardRulingDataConsumerRegistered(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{CardRulingDataQueue}' Registered"); } private static void OnCardRulingDataConsumerShutdown(object sender, ShutdownEventArgs e) { Log.Logger.Information($"Consumer '{CardRulingDataQueue}' Shutdown"); } private static void OnCardTriviaDataConsumerCancelled(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{CardTriviaDataQueue}' Cancelled"); } private static void OnCardTriviaDataConsumerUnregistered(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{CardTriviaDataQueue}' Unregistered");} private static void OnCardTriviaDataConsumerRegistered(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{CardTriviaDataQueue}' Registered"); } private static void OnCardTriviaDataConsumerShutdown(object sender, ShutdownEventArgs e) { Log.Logger.Information($"Consumer '{CardTriviaDataQueue}' Shutdown"); } private void ConfigureSerilog() { // Create the logger Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Console() .WriteTo.File(new JsonFormatter(renderMessage: true), (_appSettingsOptions.Value.LogFolder + $@"/cardsectionprocessor.{Environment.MachineName}.txt"), fileSizeLimitBytes: 100000000, rollOnFileSizeLimit: true, rollingInterval: RollingInterval.Day) .CreateLogger(); } #endregion } } <file_sep>/src/wikia/article/src/Domain/article.domain/ArticleList/Item/ArticleItemProcessor.cs using System; using System.Threading.Tasks; using article.core.ArticleList.Processor; using article.core.Constants; using article.core.Exceptions; using article.core.Models; using article.domain.Services.Messaging; using wikia.Models.Article.AlphabeticalList; namespace article.domain.ArticleList.Item { public sealed class ArticleItemProcessor : IArticleItemProcessor { private readonly IQueue<Article> _queue; public ArticleItemProcessor(IQueue<Article> queue) { _queue = queue; } public async Task<ArticleTaskResult> ProcessItem(UnexpandedArticle item) { if (item == null) throw new ArgumentNullException(nameof(item)); var articleTaskResult = new ArticleTaskResult { Article = item }; try { await _queue.Publish(item); articleTaskResult.IsSuccessfullyProcessed = true; } catch (Exception ex) { articleTaskResult.Failed = new ArticleException { Article = item, Exception = ex }; } return articleTaskResult; } public bool Handles(string category) { return category is ArticleCategory.CardTips or ArticleCategory.CardRulings or ArticleCategory.CardTrivia; } } }<file_sep>/src/wikia/article/src/Application/article.application/Configuration/QueueSetting.cs using System.Collections.Generic; namespace article.application.Configuration { public record QueueSetting { public Dictionary<string, string> Headers { get; init; } public byte PersistentMode { get; init; } } }<file_sep>/src/wikia/semanticsearch/src/Domain/semanticsearch.domain/Search/SemanticSearchProcessor.cs using semanticsearch.core.Model; using semanticsearch.core.Search; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace semanticsearch.domain.Search { public class SemanticSearchProcessor : ISemanticSearchProcessor { private readonly ILogger<SemanticSearchProcessor> _logger; private readonly ISemanticSearchProducer _semanticSearchProducer; private readonly ISemanticSearchConsumer _semanticSearchConsumer; public SemanticSearchProcessor ( ILogger<SemanticSearchProcessor> logger, ISemanticSearchProducer semanticSearchProducer, ISemanticSearchConsumer semanticSearchConsumer ) { _logger = logger; _semanticSearchProducer = semanticSearchProducer; _semanticSearchConsumer = semanticSearchConsumer; } public async Task<SemanticSearchCardTaskResult> ProcessUrl(string url) { var response = new SemanticSearchCardTaskResult { Url = url }; foreach (var semanticCard in _semanticSearchProducer.Producer(url)) { _logger.LogInformation("Processing semantic card '{CardName}'", semanticCard.Title); var result = await _semanticSearchConsumer.Process(semanticCard); if (result.IsSuccessful) response.Processed += 1; else { response.Failed.Add(result.Exception); } _logger.LogInformation("Finished processing semantic card '{CardName}'", semanticCard.Title); } response.IsSuccessful = true; return response; } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Core/cardsectionprocessor.core/Service/ICardService.cs using System.Threading.Tasks; using cardsectionprocessor.core.Models.Db; namespace cardsectionprocessor.core.Service { public interface ICardService { Task<Card> CardByName(string name); } }<file_sep>/src/wikia/data/cardsectiondata/src/Core/cardsectiondata.core/Models/SemanticCard.cs namespace cardsectiondata.core.Models { public class SemanticCard { public string Name { get; set; } public string Url { get; set; } } }<file_sep>/src/wikia/processor/cardprocessor/src/Tests/Unit/cardprocessor.application.unit.tests/HelperTests/CardTests/MonsterCardHelperTests/MonsterSubCategoryIdsTests.cs using System; using System.Collections.Generic; using System.Linq; using cardprocessor.application.Enums; using cardprocessor.application.Helpers.Cards; using cardprocessor.core.Models; using cardprocessor.tests.core; using FluentAssertions; using NUnit.Framework; namespace cardprocessor.application.unit.tests.HelperTests.CardTests.MonsterCardHelperTests { [TestFixture] [Category(TestType.Unit)] public class MonsterSubCategoryIdsTests { [Test] public void Given_A_Valid_A_Link_Monster_YugiohCard_With_Types_Should_Map_To_SubCategoryIds_Property() { // Arrange var expected = new List<int> { 2, 14 }; var yugiohCard = new YugiohCard { Name = "<NAME>", Description = "Amazing card!", CardNumber = "01861629", Attribute = "Dark", Types = "Cyberse / Link / Effect", CardType = "Monster", LinkArrows = " Bottom-Left, Top, Bottom-Right", ImageUrl = "https://vignette.wikia.nocookie.net/yugioh/images/5/5d/DecodeTalker-YS18-EN-C-1E.png/revision/latest/scale-to-width-down/300?cb=20180712163921" }; var monsterCategory = TestData.AllCategories().Single(c => c.Name.Equals(YgoCardType.Monster.ToString(), StringComparison.OrdinalIgnoreCase)); var monsterSubCategories = TestData.AllSubCategories().Select(sc => sc).Where(sc => sc.CategoryId == monsterCategory.Id); // Act var result = MonsterCardHelper.MonsterSubCategoryIds(yugiohCard, monsterSubCategories); // Assert result.Should().BeEquivalentTo(expected); } } }<file_sep>/src/wikia/semanticsearch/src/Infrastructure/semanticsearch.infrastructure/Messaging/Exchanges/ArticleHeaderExchange.cs using Microsoft.Extensions.Options; using Newtonsoft.Json; using RabbitMQ.Client; using semanticsearch.application.Configuration; using semanticsearch.core.Model; using System.Linq; using System.Threading.Tasks; using semanticsearch.domain.Messaging.Exchanges; namespace semanticsearch.infrastructure.Messaging.Exchanges { public class ArticleHeaderExchange : IArticleHeaderExchange { private readonly IOptions<RabbitMqSettings> _rabbitMqConfig; public ArticleHeaderExchange(IOptions<RabbitMqSettings> rabbitMqConfig) { _rabbitMqConfig = rabbitMqConfig; } public Task Publish(SemanticCard semanticCard) { var messageBodyBytes = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(semanticCard)); var factory = new ConnectionFactory() { HostName = _rabbitMqConfig.Value.Host, Port = _rabbitMqConfig.Value.Port, UserName = _rabbitMqConfig.Value.Username, Password = _rabbit<PASSWORD>.Password }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { var props = channel.CreateBasicProperties(); props.ContentType = _rabbitMqConfig.Value.ContentType; props.DeliveryMode = _rabbitMqConfig.Value.Exchanges[RabbitMqExchangeConstants.YugiohHeadersArticle].PersistentMode; props.Headers = _rabbitMqConfig.Value.Exchanges[RabbitMqExchangeConstants.YugiohHeadersArticle].Headers.ToDictionary(k => k.Key, k => (object)k.Value); channel.BasicPublish ( RabbitMqExchangeConstants.YugiohHeadersArticle, string.Empty, props, messageBodyBytes ); } return Task.CompletedTask; } } }<file_sep>/src/wikia/article/src/Tests/Unit/article.domain.unit.tests/ArticleListTests/ItemTests/BanlistItemProcessorTests/HandlesTests.cs using article.core.Constants; using article.domain.ArticleList.Item; using article.domain.Services.Messaging; using article.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace article.domain.unit.tests.ArticleListTests.ItemTests.BanlistItemProcessorTests { [TestFixture] [Category(TestType.Unit)] public class HandlesTests { private IBanlistArticleQueue _banlistArticleQueue; private BanlistItemProcessor _sut; [SetUp] public void SetUp() { _banlistArticleQueue = Substitute.For<IBanlistArticleQueue>(); _sut = new BanlistItemProcessor(_banlistArticleQueue); } [TestCase(ArticleCategory.ForbiddenAndLimited)] public void Given_A_Valid_Category_Should_Return_True(string category) { // Arrange // Act var result = _sut.Handles(category); // Assert result.Should().BeTrue(); } [TestCase("category")] public void Given_A_Valid_Category_Should_Return_False(string category) { // Arrange // Act var result = _sut.Handles(category); // Assert result.Should().BeFalse(); } } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Infrastructure/archetypeprocessor.infrastructure/Repository/ArchetypeCardsRepository.cs using archetypeprocessor.core.Models.Db; using archetypeprocessor.domain.Repository; using archetypeprocessor.infrastructure.Database; using archetypeprocessor.infrastructure.Database.TableValueParameter; using Microsoft.EntityFrameworkCore; using Microsoft.SqlServer.Server; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading.Tasks; namespace archetypeprocessor.infrastructure.Repository { public class ArchetypeCardsRepository : IArchetypeCardsRepository { private readonly YgoDbContext _dbContext; public ArchetypeCardsRepository(YgoDbContext dbContext) { _dbContext = dbContext; } public async Task<IEnumerable<ArchetypeCard>> Update(long archetypeId, IEnumerable<string> cards) { var archetypeCards = await _dbContext.ArchetypeCard.Where(ac => ac.ArchetypeId == archetypeId).ToArrayAsync(); if (archetypeCards.Any()) { _dbContext.ArchetypeCard.RemoveRange(archetypeCards); await _dbContext.SaveChangesAsync(); } var tvp = new TableValuedParameterBuilder ( "tvp_ArchetypeCardsByCardName", new SqlMetaData("ArchetypeId", SqlDbType.BigInt), new SqlMetaData("CardName", SqlDbType.NVarChar, 255) ); foreach (var card in cards) { tvp.AddRow(archetypeId, card); } var cardsParameter = tvp.CreateParameter("@TvpArchetypeCards"); return await _dbContext .ArchetypeCard .FromSql("EXECUTE usp_AddCardsToArchetype @TvpArchetypeCards", cardsParameter) .ToListAsync(); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Tests/Unit/cardprocessor.application.unit.tests/ValidatorsTests/Commands/AddCardCommandValidatorTests.cs using System; using cardprocessor.application.Enums; using cardprocessor.application.Models.Cards.Input; using cardprocessor.application.Validations.Cards; using cardprocessor.tests.core; using FluentValidation.TestHelper; using NUnit.Framework; namespace cardprocessor.application.unit.tests.ValidatorsTests.Commands { [TestFixture] [Category(TestType.Unit)] public class AddCardCommandValidatorTests { private CardValidator _sut; [SetUp] public void SetUp() { _sut = new CardValidator(); } [TestCase(-1)] [TestCase(3)] public void Given_An_Invalid_CardType_Validation_Should_Fail(YgoCardType cardType) { // Arrange var cardInputModel = new CardInputModel { CardType = cardType }; // Act Action act = () => _sut.ShouldHaveValidationErrorFor(c => c.CardType, cardInputModel); // Assert act.Invoke(); } [Test] public void Given_A_Null_CardType_Validation_Should_Fail() { // Arrange var cardInputModel = new CardInputModel(); // Act Action act = () => _sut.ShouldHaveValidationErrorFor(c => c.CardType, cardInputModel); // Assert act.Invoke(); } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/cardsectionprocessor.domain.unit.tests/ProcessorTests/CardSectionProcessorTests.cs using System.Collections.Generic; using System.Threading.Tasks; using cardsectionprocessor.core.Models; using cardsectionprocessor.core.Strategy; using cardsectionprocessor.domain.Processor; using cardsectionprocessor.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace cardsectionprocessor.domain.unit.tests.ProcessorTests { [TestFixture] [Category(TestType.Unit)] public class CardSectionProcessorTests { private IEnumerable<ICardSectionProcessorStrategy> _cardSectionProcessorStrategies; private CardSectionProcessor _sut; [SetUp] public void SetUp() { _cardSectionProcessorStrategies = Substitute.For<IEnumerable<ICardSectionProcessorStrategy>>(); _sut = new CardSectionProcessor(_cardSectionProcessorStrategies); } [Test] public async Task Given_A_Category_And_CardSectionMessage_IsSuccessful_Should_Be_True() { // Arrange const string category = "category"; var cardSectionMessage = new CardSectionMessage(); var handler = Substitute.For<ICardSectionProcessorStrategy>(); handler.Handles(Arg.Any<string>()).Returns(true); handler.Process(Arg.Any<CardSectionMessage>()).Returns(new CardSectionDataTaskResult<CardSectionMessage> ()); _cardSectionProcessorStrategies.GetEnumerator().Returns(new List<ICardSectionProcessorStrategy> { handler }.GetEnumerator()); // Act var result = await _sut.Process(category, cardSectionMessage); // Assert result.IsSuccessful.Should().BeTrue(); } [Test] public async Task Given_A_Category_And_CardSectionMessage_Should_Invoke_Process_Method_Once() { // Arrange const string category = "category"; var cardSectionMessage = new CardSectionMessage(); var handler = Substitute.For<ICardSectionProcessorStrategy>(); handler.Handles(Arg.Any<string>()).Returns(true); handler.Process(Arg.Any<CardSectionMessage>()).Returns(new CardSectionDataTaskResult<CardSectionMessage> ()); _cardSectionProcessorStrategies.GetEnumerator().Returns(new List<ICardSectionProcessorStrategy> { handler }.GetEnumerator()); // Act await _sut.Process(category, cardSectionMessage); // Assert await handler.Received(1).Process(Arg.Any<CardSectionMessage>()); } } }<file_sep>/src/services/Cards.API/src/Domain/Cards.Domain/Enums/TrapCardType.cs namespace Cards.Domain.Enums { public enum TrapCardType { Normal, Continuous, Counter } }<file_sep>/src/wikia/semanticsearch/src/Domain/semanticsearch.domain/WebPage/ISemanticSearchResultsWebPage.cs using System; using HtmlAgilityPack; namespace semanticsearch.domain.WebPage { public interface ISemanticSearchResultsWebPage { void Load(string url); HtmlNodeCollection TableRows { get; } bool HasNextPage { get; } HtmlNode NextPage { get; } Uri CurrentWebPageUri { get; } string NextPageLink(); } }<file_sep>/src/wikia/data/banlistdata/src/Tests/Unit/banlistdata.domain.unit.tests/ArticleProcessorTests.cs using System; using System.Threading.Tasks; using banlistdata.core.Models; using banlistdata.core.Processor; using banlistdata.domain.Processor; using banlistdata.tests.core; using FluentAssertions; using Microsoft.Extensions.Logging; using NSubstitute; using NSubstitute.ExceptionExtensions; using NUnit.Framework; namespace banlistdata.domain.unit.tests { [TestFixture] [Category(TestType.Unit)] public class ArticleProcessorTests { private IArticleDataFlow _articleDataFlow; private ArticleProcessor _sut; [SetUp] public void SetUp() { _articleDataFlow = Substitute.For<IArticleDataFlow>(); _sut = new ArticleProcessor(_articleDataFlow, Substitute.For<ILogger<ArticleProcessed>>()); } [Test] public async Task Given_An_Article_If_Processed_And_Errors_Do_Not_Occur_IsSuccessfullyProcessed_Should_Be_True() { // Arrange var article = new Article(); _articleDataFlow.ProcessDataFlow(article).Returns(new ArticleCompletion { IsSuccessful = true}); // Act var result = await _sut.Process(article); // Assert result.IsSuccessfullyProcessed.Should().BeTrue(); } [Test] public async Task Given_An_Article_If_Processed_And_Errors_Occur_IsSuccessfullyProcessed_Should_Be_False() { // Arrange var article = new Article(); _articleDataFlow.ProcessDataFlow(article).Returns(new ArticleCompletion( )); // Act var result = await _sut.Process(article); // Assert result.IsSuccessfullyProcessed.Should().BeFalse(); } [Test] public async Task Given_An_Article_If_Processed_And_An_Exception_Occur_IsSuccessfullyProcessed_Should_Be_False() { // Arrange var article = new Article(); _articleDataFlow.ProcessDataFlow(article).Throws(new Exception()); // Act var result = await _sut.Process(article); // Assert result.IsSuccessfullyProcessed.Should().BeFalse(); } } } <file_sep>/src/wikia/article/README.md ![alt text](https://fablecode.visualstudio.com/Yugioh%20Insight/_apis/build/status/Build_ArticleData "Visual studio team services build status") # Article Queries the [Wikia Api](https://yugioh.fandom.com/api/v1/#!/Articles) for [Yu-Gi-Oh](http://www.yugioh-card.com/uk/) related articles.<file_sep>/src/wikia/data/banlistdata/src/Core/banlistdata.core/Models/BanlistArticleSummary.cs using System; using banlistdata.core.Enums; namespace banlistdata.core.Models { public class BanlistArticleSummary { public int ArticleId { get; set; } public BanlistType BanlistType { get; set; } public DateTime StartDate { get; set; } } }<file_sep>/src/wikia/processor/imageprocessor/src/Infrastructure/imageprocessor.infrastructure/InfrastructureInstaller.cs using imageprocessor.domain.SystemIO; using imageprocessor.infrastructure.SystemIO; using Microsoft.Extensions.DependencyInjection; namespace imageprocessor.infrastructure { public static class InfrastructureInstaller { public static IServiceCollection AddInfrastructureServices(this IServiceCollection services) { services.AddTransient<IFileSystem, FileSystem>(); return services; } } }<file_sep>/src/wikia/data/carddata/src/Infrastructure/carddata.infrastructure/Services/Messaging/RabbitMqExchangeConstants.cs namespace carddata.infrastructure.Services.Messaging { public static class RabbitMqExchangeConstants { public const string YugiohHeadersData = "yugioh.headers.data"; } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Mappings/Mappers/CardCommandMapper.cs using cardprocessor.application.Commands; using cardprocessor.application.Commands.AddCard; using cardprocessor.application.Commands.UpdateCard; using cardprocessor.application.Enums; using cardprocessor.application.Helpers.Cards; using cardprocessor.application.Models.Cards.Input; using cardprocessor.core.Models; using cardprocessor.core.Models.Db; using cardprocessor.core.Services; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Attribute = cardprocessor.core.Models.Db.Attribute; using Type = cardprocessor.core.Models.Db.Type; namespace cardprocessor.application.Mappings.Mappers { public class CardCommandMapper : ICardCommandMapper { private readonly ICategoryService _categoryService; private readonly ISubCategoryService _subCategoryService; private readonly ITypeService _typeService; private readonly IAttributeService _attributeService; private readonly ILinkArrowService _linkArrowService; public CardCommandMapper ( ICategoryService categoryService, ISubCategoryService subCategoryService, ITypeService typeService, IAttributeService attributeService, ILinkArrowService linkArrowService ) { _categoryService = categoryService; _subCategoryService = subCategoryService; _typeService = typeService; _attributeService = attributeService; _linkArrowService = linkArrowService; } public async Task<AddCardCommand> MapToAddCommand(YugiohCard yugiohCard) { ICollection<Category> categories = await _categoryService.AllCategories(); ICollection<SubCategory> subCategories = await _subCategoryService.AllSubCategories(); var command = new AddCardCommand { Card = await MapToCardInputModel(yugiohCard, new CardInputModel(), categories, subCategories) }; return command; } public async Task<UpdateCardCommand> MapToUpdateCommand(YugiohCard yugiohCard, Card cardToUpdate) { ICollection<Category> categories = await _categoryService.AllCategories(); ICollection<SubCategory> subCategories = await _subCategoryService.AllSubCategories(); var command = new UpdateCardCommand { Card = await MapToCardInputModel(yugiohCard, new CardInputModel(), categories, subCategories, cardToUpdate) }; return command; } #region private helpers private async Task<CardInputModel> MapToCardInputModel(YugiohCard yugiohCard, CardInputModel cardInputModel, ICollection<Category> categories, ICollection<SubCategory> subCategories, Card cardToUpdate) { cardInputModel.Id = cardToUpdate.Id; return await MapToCardInputModel(yugiohCard, cardInputModel, categories, subCategories); } private async Task<CardInputModel> MapToCardInputModel(YugiohCard yugiohCard, CardInputModel cardInputModel, ICollection<Category> categories, ICollection<SubCategory> subCategories) { CardHelper.MapBasicCardInformation(yugiohCard, cardInputModel); CardHelper.MapCardImageUrl(yugiohCard, cardInputModel); if (cardInputModel.CardType.Equals(YgoCardType.Spell)) { SpellCardHelper.MapSubCategoryIds(yugiohCard, cardInputModel, categories, subCategories); } else if (cardInputModel.CardType.Equals(YgoCardType.Trap)) { TrapCardHelper.MapSubCategoryIds(yugiohCard, cardInputModel, categories, subCategories); } else { ICollection<Type> types = await _typeService.AllTypes(); ICollection<Attribute> attributes = await _attributeService.AllAttributes(); ICollection<LinkArrow> linkArrows = await _linkArrowService.AllLinkArrows(); var monsterCategory = categories.Single(c => c.Name.Equals(YgoCardType.Monster.ToString(), StringComparison.OrdinalIgnoreCase)); var monsterSubCategories = subCategories.Select(sc => sc).Where(sc => sc.CategoryId == monsterCategory.Id); MonsterCardHelper.MapMonsterCard(yugiohCard, cardInputModel, attributes, monsterSubCategories, types, linkArrows); } return cardInputModel; } #endregion } }<file_sep>/src/wikia/processor/banlistprocessor/src/Infrastructure/banlistprocessor.infrastructure/Repository/BanlistRepository.cs using System; using System.Threading.Tasks; using banlistprocessor.core.Models.Db; using banlistprocessor.domain.Repository; using banlistprocessor.infrastructure.Database; using Microsoft.EntityFrameworkCore; namespace banlistprocessor.infrastructure.Repository { public class BanlistRepository : IBanlistRepository { private readonly YgoDbContext _context; public BanlistRepository(YgoDbContext context) { _context = context; } public Task<bool> BanlistExist(int id) { return _context.Banlist.AnyAsync(b => b.Id == id); } public async Task<Banlist> Add(Banlist banlist) { banlist.Created = banlist.Updated = DateTime.UtcNow; _context.Banlist.Add(banlist); await _context.SaveChangesAsync(); return banlist; } public async Task<Banlist> Update(Banlist banlist) { banlist.Updated = DateTime.UtcNow; _context.Banlist.Update(banlist); await _context.SaveChangesAsync(); return banlist; } public Task<Banlist> GetBanlistById(int id) { return _context .Banlist .Include(b => b.Format) .Include(b => b.BanlistCard) .AsNoTracking() .SingleOrDefaultAsync(b => b.Id == id); } } }<file_sep>/src/wikia/article/src/Domain/article.domain/ArticleList/Item/ArchetypeItemProcessor.cs using article.core.ArticleList.Processor; using article.core.Constants; using article.core.Exceptions; using article.core.Models; using article.domain.Services.Messaging; using System; using System.Threading.Tasks; using wikia.Models.Article.AlphabeticalList; namespace article.domain.ArticleList.Item { public sealed class ArchetypeItemProcessor : IArticleItemProcessor { private readonly IArchetypeArticleQueue _archetypeArticleQueue; public ArchetypeItemProcessor(IArchetypeArticleQueue archetypeArticleQueue) { _archetypeArticleQueue = archetypeArticleQueue; } public async Task<ArticleTaskResult> ProcessItem(UnexpandedArticle item) { if (item == null) throw new ArgumentNullException(nameof(item)); var articleTaskResult = new ArticleTaskResult { Article = item }; try { await _archetypeArticleQueue.Publish(item); articleTaskResult.IsSuccessfullyProcessed = true; } catch (Exception ex) { articleTaskResult.Failed = new ArticleException { Article = item, Exception = ex }; } return articleTaskResult; } public bool Handles(string category) { return category is ArticleCategory.Archetype or ArticleCategory.CardsByArchetype or ArticleCategory.CardsByArchetypeSupport; } } }<file_sep>/src/wikia/data/cardsectiondata/src/Core/cardsectiondata.core/Processor/ICardSectionProcessor.cs using System.Threading.Tasks; using cardsectiondata.core.Models; namespace cardsectiondata.core.Processor { public interface ICardSectionProcessor { Task<CardSectionMessage> ProcessItem(Article article); } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Infrastructure/archetypeprocessor.infrastructure/InfrastructureInstaller.cs using archetypeprocessor.domain.Messaging; using archetypeprocessor.domain.Repository; using archetypeprocessor.infrastructure.Database; using archetypeprocessor.infrastructure.Messaging; using archetypeprocessor.infrastructure.Repository; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; namespace archetypeprocessor.infrastructure { public static class InfrastructureInstaller { public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, string connectionString) { services .AddYgoDatabase(connectionString) .AddRepositories() .AddMessaging(); return services; } public static IServiceCollection AddYgoDatabase(this IServiceCollection services, string connectionString) { services.AddDbContext<YgoDbContext>(c => c.UseSqlServer(connectionString), ServiceLifetime.Transient); return services; } public static IServiceCollection AddRepositories(this IServiceCollection services) { services.AddTransient<IArchetypeRepository, ArchetypeRepository>(); services.AddTransient<IArchetypeCardsRepository, ArchetypeCardsRepository>(); return services; } public static IServiceCollection AddMessaging(this IServiceCollection services) { services.AddTransient<IImageQueueService, ImageQueueService>(); services.AddTransient<IArchetypeImageQueueService, ArchetypeImageQueueService>(); return services; } } }<file_sep>/src/wikia/data/archetypedata/src/Application/archetypedata.application/MessageConsumers/ArchetypeCardInformation/ArchetypeCardInformationConsumerValidator.cs using FluentValidation; namespace archetypedata.application.MessageConsumers.ArchetypeCardInformation { public class ArchetypeCardInformationConsumerValidator : AbstractValidator<ArchetypeCardInformationConsumer> { public ArchetypeCardInformationConsumerValidator() { RuleFor(ci => ci.Message) .NotNull() .NotEmpty(); } } }<file_sep>/src/wikia/data/banlistdata/src/Core/banlistdata.core/Processor/IArticleProcessor.cs using System.Threading.Tasks; using banlistdata.core.Models; namespace banlistdata.core.Processor { public interface IArticleProcessor { Task<ArticleConsumerResult> Process(Article article); } }<file_sep>/src/wikia/data/carddata/src/Presentation/carddata/Services/CardDataHostedService.cs using carddata.application.Configuration; using carddata.application.MessageConsumers.CardInformation; using MediatR; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Text; using System.Threading; using System.Threading.Tasks; namespace carddata.Services { public sealed class CardDataHostedService : BackgroundService { private readonly ILogger<CardDataHostedService> _logger; private readonly IOptions<RabbitMqSettings> _rabbitMqOptions; private readonly IMediator _mediator; private ConnectionFactory _factory; private IConnection _connection; private IModel _channel; public CardDataHostedService ( ILogger<CardDataHostedService> logger, IOptions<RabbitMqSettings> rabbitMqOptions, IMediator mediator ) { _logger = logger; _rabbitMqOptions = rabbitMqOptions; _mediator = mediator; } protected override Task ExecuteAsync(CancellationToken stoppingToken) { stoppingToken.ThrowIfCancellationRequested(); _factory = new ConnectionFactory { HostName = _rabbitMqOptions.Value.Host, UserName = _rabbitMqOptions.Value.Username, Password = _rabbit<PASSWORD>, DispatchConsumersAsync = true }; _connection = _factory.CreateConnection(); _channel = _connection.CreateModel(); _channel.BasicQos(0, 1, false); var consumer = new AsyncEventingBasicConsumer(_channel); consumer.Received += async (_, ea) => { try { var body = ea.Body.ToArray(); var message = Encoding.UTF8.GetString(body); var result = await _mediator.Send(new CardInformationConsumer { Message = message }, stoppingToken); if (result.ArticleConsumerResult.IsSuccessfullyProcessed) { _channel.BasicAck(ea.DeliveryTag, false); } else { _channel.BasicNack(ea.DeliveryTag, false, false); } await Task.Yield(); } catch (Exception ex) { _logger.LogError("RabbitMq Consumer: '{CardArticleQueue}' exception. Exception: {@Exception}", _rabbitMqOptions.Value.Queues.CardArticleQueue, ex); } }; consumer.Shutdown += OnCardArticleConsumerShutdown; consumer.Registered += OnCardArticleConsumerRegistered; consumer.Unregistered += OnCardArticleConsumerUnregistered; consumer.ConsumerCancelled += OnCardArticleConsumerCancelled; _channel.BasicConsume(_rabbitMqOptions.Value.Queues.CardArticleQueue, false, consumer); return Task.CompletedTask; } public override void Dispose() { _channel.Close(); _connection.Close(); base.Dispose(); } #region private helper private Task OnCardArticleConsumerCancelled(object sender, ConsumerEventArgs e) { _logger.LogInformation("RabbitMq Consumer '{CardArticleQueue}' Cancelled", _rabbitMqOptions.Value.Queues.CardArticleQueue); return Task.CompletedTask; } private Task OnCardArticleConsumerUnregistered(object sender, ConsumerEventArgs e) { _logger.LogInformation("RabbitMq Consumer '{CardArticleQueue}' Unregistered", _rabbitMqOptions.Value.Queues.CardArticleQueue); return Task.CompletedTask; } private Task OnCardArticleConsumerRegistered(object sender, ConsumerEventArgs e) { _logger.LogInformation("RabbitMq Consumer '{CardArticleQueue}' Registered", _rabbitMqOptions.Value.Queues.CardArticleQueue); return Task.CompletedTask; } private Task OnCardArticleConsumerShutdown(object sender, ShutdownEventArgs e) { _logger.LogInformation("RabbitMq Consumer '{CardArticleQueue}' Shutdown", _rabbitMqOptions.Value.Queues.CardArticleQueue); return Task.CompletedTask; } #endregion } } <file_sep>/src/wikia/article/src/Tests/Unit/article.application.unit.tests/ScheduledTasksTests/ArticleInformationTaskHandlerTests.cs using article.application.ScheduledTasks.Articles; using article.core.ArticleList.Processor; using article.tests.core; using FluentAssertions; using FluentValidation; using FluentValidation.Results; using NSubstitute; using NUnit.Framework; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace article.application.unit.tests.ScheduledTasksTests { [TestFixture] [Category(TestType.Unit)] public class ArticleInformationTaskHandlerTests { private IArticleCategoryProcessor _articleCategoryProcessor; private IValidator<ArticleInformationTask> _validator; private ArticleInformationTaskHandler _sut; [SetUp] public void SetUp() { _articleCategoryProcessor = Substitute.For<IArticleCategoryProcessor>(); _validator = Substitute.For<IValidator<ArticleInformationTask>>(); _sut = new ArticleInformationTaskHandler ( _articleCategoryProcessor, _validator ); } [Test] public async Task Given_A_ArticleInformationTask_If_Validation_Fails_Should_Return_Errors() { // Arrange _validator.Validate(Arg.Any<ArticleInformationTask>()).Returns(new ValidationResult(new List<ValidationFailure> { new ValidationFailure("propertyName", "failed") })); // Act var result = await _sut.Handle(new ArticleInformationTask(), CancellationToken.None); // Assert result.Errors.Should().NotBeNullOrEmpty(); } [Test] public async Task Given_A_ArticleInformationTask_If_Validation_Fails_Should_Not_Invoke_ArticleCategoryProcessor_Process_Method() { // Arrange _validator.Validate(Arg.Any<ArticleInformationTask>()).Returns(new ValidationResult(new List<ValidationFailure> { new ValidationFailure("propertyName", "failed") })); // Act await _sut.Handle(new ArticleInformationTask(), CancellationToken.None); // Assert await _articleCategoryProcessor.DidNotReceive().Process(Arg.Any<string>(), Arg.Any<int>()); } [Test] public async Task Given_A_ArticleInformationTask_If_Validation_Is_Successful_Should_Be_true() { // Arrange var banlistInformationTask = new ArticleInformationTask { Category = "banlist", PageSize = 8}; _validator.Validate(Arg.Any<ArticleInformationTask>()).Returns(new ArticleInformationTaskValidator().Validate(banlistInformationTask)); // Act var result = await _sut.Handle(banlistInformationTask, CancellationToken.None); // Assert result.IsSuccessful.Should().BeTrue(); } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/cardsectionprocessor.domain.unit.tests/ServicesTests/CardRulingServiceTests.cs using System.Collections.Generic; using System.Threading.Tasks; using cardsectionprocessor.core.Models.Db; using cardsectionprocessor.domain.Repository; using cardsectionprocessor.domain.Service; using cardsectionprocessor.tests.core; using NSubstitute; using NUnit.Framework; namespace cardsectionprocessor.domain.unit.tests.ServicesTests { [TestFixture] [Category(TestType.Unit)] public class CardRulingServiceTests { private ICardRulingRepository _cardRulingRepository; private CardRulingService _sut; [SetUp] public void SetUp() { _cardRulingRepository = Substitute.For<ICardRulingRepository>(); _sut = new CardRulingService(_cardRulingRepository); } [Test] public async Task Given_A_CardId_Should_Invoke_DeleteByCardId_Once() { // Arrange const int cardId = 2342; // Act await _sut.DeleteByCardId(cardId); // Assert await _cardRulingRepository.Received(1).DeleteByCardId(Arg.Any<long>()); } [Test] public async Task Given_A_Collection_Of_Rulings_Should_Invoke_Update_Once() { // Arrange var rulingSections = new List<RulingSection>(); // Act await _sut.Update(rulingSections); // Assert await _cardRulingRepository.Received(1).Update(Arg.Any<List<RulingSection>>()); } } }<file_sep>/src/wikia/semanticsearch/src/Presentation/semanticsearch.card/QuartzConfiguration/SemanticSearchCardJobFactory.cs using System; using Microsoft.Extensions.DependencyInjection; using Quartz; using Quartz.Spi; namespace semanticsearch.card.QuartzConfiguration { public class SemanticSearchCardJobFactory : IJobFactory { private readonly IServiceProvider _serviceProvider; public SemanticSearchCardJobFactory(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler) { return _serviceProvider.GetRequiredService<IJob>(); } public void ReturnJob(IJob job) { } } }<file_sep>/src/wikia/article/src/Domain/article.domain/ArticleList/Processor/ArticleCategoryProcessor.cs using article.core.ArticleList.DataSource; using article.core.ArticleList.Processor; using article.core.Models; using System.Collections.Generic; using System.Threading.Tasks; namespace article.domain.ArticleList.Processor { public sealed class ArticleCategoryProcessor : IArticleCategoryProcessor { private readonly IArticleBatchProcessor _articleBatchProcessor; private readonly IArticleCategoryDataSource _articleCategoryDataSource; public ArticleCategoryProcessor(IArticleCategoryDataSource articleCategoryDataSource, IArticleBatchProcessor articleBatchProcessor) { _articleCategoryDataSource = articleCategoryDataSource; _articleBatchProcessor = articleBatchProcessor; } public async Task<IEnumerable<ArticleBatchTaskResult>> Process(IEnumerable<string> categories, int pageSize) { var results = new List<ArticleBatchTaskResult>(); foreach (var category in categories) { results.Add(await Process(category, pageSize)); } return results; } public async Task<ArticleBatchTaskResult> Process(string category, int pageSize) { var response = new ArticleBatchTaskResult { Category = category }; await foreach (var unexpandedArticleBatch in _articleCategoryDataSource.Producer(category, pageSize)) { var articleBatchTaskResult = await _articleBatchProcessor.Process(category, unexpandedArticleBatch); response.Processed += articleBatchTaskResult.Processed; response.Failed.AddRange(articleBatchTaskResult.Failed); } return response; } } }<file_sep>/src/wikia/processor/cardprocessor/src/Domain/cardprocessor.domain/Strategies/SpellCardTypeStrategy.cs using System.Threading.Tasks; using cardprocessor.core.Enums; using cardprocessor.core.Models; using cardprocessor.core.Models.Db; using cardprocessor.core.Strategies; using cardprocessor.domain.Mappers; using cardprocessor.domain.Repository; namespace cardprocessor.domain.Strategies { public class SpellCardTypeStrategy : ICardTypeStrategy { private readonly ICardRepository _cardRepository; public SpellCardTypeStrategy(ICardRepository cardRepository) { _cardRepository = cardRepository; } public async Task<Card> Add(CardModel cardModel) { var newSpellCard = CardMapper.MapToSpellOrTrapCard(cardModel); return await _cardRepository.Add(newSpellCard); } public async Task<Card> Update(CardModel cardModel) { var cardToUpdate = await _cardRepository.CardById(cardModel.Id); if (cardToUpdate != null) { CardMapper.UpdateSpellCardWith(cardToUpdate, cardModel); return await _cardRepository.Update(cardToUpdate); } return null; } public bool Handles(YugiohCardType yugiohCardType) { return yugiohCardType == YugiohCardType.Spell; } } }<file_sep>/src/wikia/data/archetypedata/src/Tests/Unit/archetypedata.application.unit.tests/ArchetypeCardInformationConsumerHandlerTests.cs using archetypedata.application.MessageConsumers.ArchetypeCardInformation; using archetypedata.core.Models; using archetypedata.core.Processor; using archetypedata.tests.core; using FluentAssertions; using FluentValidation; using Microsoft.Extensions.Logging; using NSubstitute; using NUnit.Framework; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace archetypedata.application.unit.tests { [TestFixture] [Category(TestType.Unit)] public class ArchetypeCardInformationConsumerHandlerTests { private IValidator<ArchetypeCardInformationConsumer> _validator; private IArchetypeCardProcessor _archetypeCardProcessor; private ArchetypeCardInformationConsumerHandler _sut; private ILogger<ArchetypeCardInformationConsumerHandler> _logger; [SetUp] public void SetUp() { _validator = Substitute.For<IValidator<ArchetypeCardInformationConsumer>>(); _archetypeCardProcessor = Substitute.For<IArchetypeCardProcessor>(); _logger = Substitute.For<ILogger<ArchetypeCardInformationConsumerHandler>>(); _sut = new ArchetypeCardInformationConsumerHandler(_archetypeCardProcessor, _validator, _logger); } [Test] public async Task Given_An_Invalid_ArchetypeCardInformationConsumer_IsSuccessful_Should_Be_False() { // Arrange var archetypeCardInformationConsumer = new ArchetypeCardInformationConsumer(); _validator.Validate(Arg.Any<ArchetypeCardInformationConsumer>()) .Returns(new ArchetypeCardInformationConsumerValidator().Validate(archetypeCardInformationConsumer)); // Act var result = await _sut.Handle(archetypeCardInformationConsumer, CancellationToken.None); // Assert result.IsSuccessful.Should().BeFalse(); } [Test] public async Task Given_An_Invalid_ArchetypeCardInformationConsumer_Errors_List_Should_Not_Be_Null_Or_Empty() { // Arrange var archetypeCardInformationConsumer = new ArchetypeCardInformationConsumer(); _validator.Validate(Arg.Any<ArchetypeCardInformationConsumer>()) .Returns(new ArchetypeCardInformationConsumerValidator().Validate(archetypeCardInformationConsumer)); // Act var result = await _sut.Handle(archetypeCardInformationConsumer, CancellationToken.None); // Assert result.Errors.Should().NotBeNullOrEmpty(); } [Test] public async Task Given_A_Valid_ArchetypeCardInformationConsumer_IsSuccessful_Should_Be_True() { // Arrange var archetypeCardInformationConsumer = new ArchetypeCardInformationConsumer { Message = "{\"Id\":703544,\"CorrelationId\":\"3e2bf3ca-d903-440c-8cd5-be61c95ae1fc\",\"Title\":\"Tenyi\",\"Url\":\"https://yugioh.fandom.com/wiki/Tenyi\"}" }; _validator.Validate(Arg.Any<ArchetypeCardInformationConsumer>()) .Returns(new ArchetypeCardInformationConsumerValidator().Validate(archetypeCardInformationConsumer)); _archetypeCardProcessor.Process(Arg.Any<Article>()).Returns(new ArticleTaskResult()); // Act var result = await _sut.Handle(archetypeCardInformationConsumer, CancellationToken.None); // Assert result.IsSuccessful.Should().BeTrue(); } [Test] public async Task Given_A_Valid_ArchetypeCardInformationConsumer_Should_Execute_Process_Method_Once() { // Arrange var archetypeCardInformationConsumer = new ArchetypeCardInformationConsumer { Message = "{\"Id\":703544,\"CorrelationId\":\"3e2bf3ca-d903-440c-8cd5-be61c95ae1fc\",\"Title\":\"Tenyi\",\"Url\":\"https://yugioh.fandom.com/wiki/Tenyi\"}" }; _validator.Validate(Arg.Any<ArchetypeCardInformationConsumer>()) .Returns(new ArchetypeCardInformationConsumerValidator().Validate(archetypeCardInformationConsumer)); _archetypeCardProcessor.Process(Arg.Any<Article>()).Returns(new ArticleTaskResult()); // Act await _sut.Handle(archetypeCardInformationConsumer, CancellationToken.None); // Assert await _archetypeCardProcessor.Received(1).Process(Arg.Any<Article>()); } [Test] public async Task Given_A_Valid_ArchetypeCardInformationConsumer_If_Not_Processed_Successfully_Errors_Should_Not_Be_Null_Or_Empty() { // Arrange var archetypeCardInformationConsumer = new ArchetypeCardInformationConsumer { Message = "{\"Id\":703544,\"CorrelationId\":\"3e2bf3ca-d903-440c-8cd5-be61c95ae1fc\",\"Title\":\"Tenyi\",\"Url\":\"https://yugioh.fandom.com/wiki/Tenyi\"}" }; _validator.Validate(Arg.Any<ArchetypeCardInformationConsumer>()) .Returns(new ArchetypeCardInformationConsumerValidator().Validate(archetypeCardInformationConsumer)); _archetypeCardProcessor.Process(Arg.Any<Article>()).Returns(new ArticleTaskResult{ Errors = new List<string>{ "Something went horribly wrong"}}); // Act var result = await _sut.Handle(archetypeCardInformationConsumer, CancellationToken.None); // Assert result.Errors.Should().NotBeNullOrEmpty(); } } } <file_sep>/src/wikia/processor/banlistprocessor/src/Infrastructure/banlistprocessor.infrastructure/Repository/LimitRepository.cs using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using banlistprocessor.core.Models.Db; using banlistprocessor.domain.Repository; using banlistprocessor.infrastructure.Database; using Microsoft.EntityFrameworkCore; namespace banlistprocessor.infrastructure.Repository { public class LimitRepository : ILimitRepository { private readonly YgoDbContext _dbContext; public LimitRepository(YgoDbContext dbContext) { _dbContext = dbContext; } public Task<List<Limit>> GetAll() { return _dbContext.Limit.OrderBy(c => c.Name).ToListAsync(); } } }<file_sep>/src/wikia/data/cardsectiondata/src/Tests/Unit/cardsectiondata.domain.unit.tests/ArticleListTests/ArticleProcessorTests.cs using cardsectiondata.core.Models; using cardsectiondata.domain.ArticleList.Processor; using cardsectiondata.tests.core; using NSubstitute; using NUnit.Framework; using System.Collections.Generic; using System.Threading.Tasks; using cardsectiondata.core.Processor; namespace cardsectiondata.domain.unit.tests.ArticleListTests { [TestFixture] [Category(TestType.Unit)] public class ArticleProcessorTests { private ArticleProcessor _sut; private IArticleItemProcessor _processor; [SetUp] public void SetUp() { _processor = Substitute.For<IArticleItemProcessor>(); _sut = new ArticleProcessor(new List<IArticleItemProcessor> {_processor}); } [Test] public async Task Given_A_Category_And_An_Article_Should_Invoke_ProcessItem_Method_Once() { // Arrange const int expected = 1; const string category = "category"; _processor.Handles(Arg.Any<string>()).Returns(true); _processor.ProcessItem(Arg.Any<Article>()).Returns(new ArticleTaskResult()); // Act await _sut.Process(category, new Article()); // Assert await _processor.Received(expected).ProcessItem(Arg.Any<Article>()); } } } <file_sep>/src/wikia/data/cardsectiondata/src/Tests/Unit/cardsectiondata.domain.unit.tests/ArticleListTests/ItemTests/CardTriviaItemProcessorTests/HandlesTests.cs using System.Collections.Generic; using cardsectiondata.core.Constants; using cardsectiondata.core.Processor; using cardsectiondata.domain.ArticleList.Item; using cardsectiondata.domain.Services.Messaging; using cardsectiondata.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace cardsectiondata.domain.unit.tests.ArticleListTests.ItemTests.CardTriviaItemProcessorTests { [TestFixture] [Category(TestType.Unit)] public class HandlesTests { private IEnumerable<IQueue> _queues; private CardTriviaItemProcessor _sut; [SetUp] public void SetUp() { _queues = Substitute.For<IEnumerable<IQueue>>(); _sut = new CardTriviaItemProcessor(Substitute.For<ICardSectionProcessor>(), _queues); } [TestCase(ArticleCategory.CardTrivia)] public void Given_A_Valid_Category_Should_Return_True(string category) { // Arrange // Act var result = _sut.Handles(category); // Assert result.Should().BeTrue(); } [TestCase("category")] public void Given_A_Valid_Category_Should_Return_False(string category) { // Arrange // Act var result = _sut.Handles(category); // Assert result.Should().BeFalse(); } } }<file_sep>/src/wikia/data/cardsectiondata/src/Tests/Unit/cardsectiondata.domain.unit.tests/ArticleListTests/ItemTests/CardTipItemProcessorTests/HandlesTests.cs using System.Collections.Generic; using cardsectiondata.core.Constants; using cardsectiondata.domain.ArticleList.Item; using cardsectiondata.domain.Services.Messaging; using cardsectiondata.domain.WebPages; using cardsectiondata.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; using wikia.Api; using wikia.Models.Article.AlphabeticalList; namespace cardsectiondata.domain.unit.tests.ArticleListTests.ItemTests.CardTipItemProcessorTests { [TestFixture] [Category(TestType.Unit)] public class HandlesTests { private IWikiArticle _wikiArticle; private ITipRelatedWebPage _tipRelatedWebPage; private IEnumerable<IQueue> _queues; private CardTipItemProcessor _sut; [SetUp] public void SetUp() { _wikiArticle = Substitute.For<IWikiArticle>(); _tipRelatedWebPage = Substitute.For<ITipRelatedWebPage>(); _queues = Substitute.For<IEnumerable<IQueue>>(); _sut = new CardTipItemProcessor(_wikiArticle, _tipRelatedWebPage, _queues); } [TestCase(ArticleCategory.CardTips)] public void Given_A_Valid_Category_Should_Return_True(string category) { // Arrange // Act var result = _sut.Handles(category); // Assert result.Should().BeTrue(); } [TestCase("category")] public void Given_A_Valid_Category_Should_Return_False(string category) { // Arrange // Act var result = _sut.Handles(category); // Assert result.Should().BeFalse(); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Domain/cardprocessor.domain/Services/LimitService.cs using System.Collections.Generic; using System.Threading.Tasks; using cardprocessor.core.Models.Db; using cardprocessor.core.Services; using cardprocessor.domain.Repository; namespace cardprocessor.domain.Services { public class LimitService : ILimitService { private readonly ILimitRepository _limitRepository; public LimitService(ILimitRepository limitRepository) { _limitRepository = limitRepository; } public Task<List<Limit>> AllLimits() { return _limitRepository.AllLimits(); } } }<file_sep>/src/wikia/data/banlistdata/src/Core/banlistdata.core/Models/ArticleProcessed.cs namespace banlistdata.core.Models { public class ArticleProcessed { public Article Article { get; set; } public YugiohBanlist Banlist { get; set; } public bool IsSuccessful { get; set; } } }<file_sep>/src/wikia/data/carddata/src/Infrastructure/carddata.infrastructure/InfrastructureInstaller.cs using carddata.domain.Services.Messaging; using carddata.domain.WebPages; using carddata.domain.WebPages.Cards; using carddata.infrastructure.Services.Messaging.Cards; using carddata.infrastructure.WebPages; using carddata.infrastructure.WebPages.Cards; using Microsoft.Extensions.DependencyInjection; namespace carddata.infrastructure { public static class InfrastructureInstaller { public static IServiceCollection AddInfrastructureServices(this IServiceCollection services) { services.AddMessagingServices(); return services; } public static IServiceCollection AddMessagingServices(this IServiceCollection services) { services.AddTransient<IYugiohCardQueue, YugiohCardQueue>(); services.AddTransient<ICardWebPage, CardWebPage>(); services.AddTransient<ICardHtmlTable, CardHtmlTable>(); services.AddTransient<ICardHtmlDocument, CardHtmlDocument>(); services.AddTransient<IHtmlWebPage, HtmlWebPage>(); return services; } } }<file_sep>/README.md |**Applications**|**Description** |:-----:|:-----:| [Article](https://github.com/fablecode/yugioh-insight/tree/master/src/wikia/article)| Articles to process [Data](https://github.com/fablecode/yugioh-insight/tree/master/src/wikia/data)| Amalgamate article data [Processor](https://github.com/fablecode/yugioh-insight/tree/master/src/wikia/processor)| Persist article # Yugioh-Insight Yugioh Insight is a collection of solutions for gathering [Yu-Gi-Oh](http://www.yugioh-card.com/uk/) data from various sources. ## Architecture Overview This application is cross-platform at the server and client side, thanks to .NET 5 services capable of running on Linux or Windows containers depending on your Docker host. The architecture proposes a microservice oriented architecture implementation with multiple autonomous microservices (each one owning its own data/db) and implementing different approaches within each microservice (simple CRUD vs. DDD/CQRS patterns) using Http as the communication protocol between the client apps and the microservices and supports asynchronous communication for data updates propagation across multiple services based on an Event Bus ([RabbitMQ](https://www.rabbitmq.com/)). ## ![ETL Diagram](images/etl_diagram.png) ## Built With * [Visual Studio 2019](https://www.visualstudio.com/downloads/) * [.NET 5.0 ](https://dotnet.microsoft.com/download) * [Onion Architecture](http://jeffreypalermo.com/blog/the-onion-architecture-part-1/) and [CQRS](https://martinfowler.com/bliki/CQRS.html). * [RabbitMq](https://www.rabbitmq.com/) * [Visual Studio Team Services](https://www.visualstudio.com/team-services/release-management/) for CI and deployment. * [Dataflow Blocks (Task Parallel Library)](https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/dataflow-task-parallel-library) * [Mediatr](https://www.nuget.org/packages/MediatR/) for CQRS and the Mediator Design Pattern. Mediator design pattern defines how a set of objects interact with each other. You can think of a Mediator object as a kind of traffic-coordinator, it directs traffic to appropriate parties. * [Fluent Validations](https://www.nuget.org/packages/FluentValidation) * [Fluent Assertions](https://www.nuget.org/packages/FluentAssertions) * [NUnit](https://github.com/nunit/nunit) * [Scrutor](https://github.com/khellang/Scrutor) for decorator pattern implementation * [Dataflow Blocks (Task Parallel Library)](https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/dataflow-task-parallel-library)<file_sep>/src/services/Cards.API/src/Application/Cards.Application/MessageConsumers/CardData/CardInformationConsumerHandler.cs using System.Threading; using System.Threading.Tasks; using MediatR; namespace Cards.Application.MessageConsumers.CardData { public sealed class CardInformationConsumerHandler : IRequestHandler<CardInformationConsumer, CardInformationConsumerResult> { public Task<CardInformationConsumerResult> Handle(CardInformationConsumer request, CancellationToken cancellationToken) { return Task.FromResult(new CardInformationConsumerResult {IsSuccessful = true}); } } }<file_sep>/src/wikia/article/src/Presentation/article.cardinformation/QuartzConfiguration/CardInformationJob.cs using article.application.Configuration; using article.application.ScheduledTasks.Articles; using MediatR; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Quartz; using System.Threading.Tasks; using article.domain.Settings; namespace article.cardinformation.QuartzConfiguration { public class CardInformationJob : IJob { private readonly IMediator _mediator; private readonly ILogger<CardInformationJob> _logger; private readonly IOptions<AppSettings> _options; public CardInformationJob(IMediator mediator, ILogger<CardInformationJob> logger, IOptions<AppSettings> options) { _mediator = mediator; _logger = logger; _options = options; } public async Task Execute(IJobExecutionContext context) { var result = await _mediator.Send(new ArticleInformationTask { Category = _options.Value.Category, PageSize = _options.Value.PageSize }); _logger.LogInformation("Finished processing '{Category}' category.", _options.Value.Category); if (!result.IsSuccessful) { _logger.LogInformation("Errors while processing '{Category}' category. Errors: {Errors}", _options.Value.Category, result.Errors); } } } }<file_sep>/src/wikia/data/cardsectiondata/src/Application/cardsectiondata.application/MessageConsumers/CardTriviaInformation/CardRulingInformationConsumerHandler.cs using cardsectiondata.application.MessageConsumers.CardInformation; using cardsectiondata.core.Constants; using MediatR; using System.Threading; using System.Threading.Tasks; namespace cardsectiondata.application.MessageConsumers.CardTriviaInformation { public class CardTriviaInformationConsumerHandler : IRequestHandler<CardTriviaInformationConsumer, CardTriviaInformationConsumerResult> { private readonly IMediator _mediator; public CardTriviaInformationConsumerHandler(IMediator mediator) { _mediator = mediator; } public async Task<CardTriviaInformationConsumerResult> Handle(CardTriviaInformationConsumer request, CancellationToken cancellationToken) { var cardTriviaInformationConsumerResult = new CardTriviaInformationConsumerResult(); var cardInformation = new CardInformationConsumer { Category = ArticleCategory.CardTrivia, Message = request.Message }; var result = await _mediator.Send(cardInformation, cancellationToken); if (!result.IsSuccessful) { cardTriviaInformationConsumerResult.Errors = result.Errors; } return cardTriviaInformationConsumerResult; } } }<file_sep>/docker-compose.yml version: '3.8' services: # Logging seq: image: datalust/seq:latest ports: - 6341:80 environment: ACCEPT_EULA: "Y" # Microsoft Sql Server sqldata: image: mcr.microsoft.com/mssql/server:2019-latest environment: SA_PASSWORD: "<PASSWORD>" ACCEPT_EULA: "Y" ports: - "5433:1433" # Message Broker rabbitmq: image: rabbitmq:management container_name: 'yugioh_insight_rabbitmq' hostname: yugioh_insight_rabbitmq ports: - "5672:5672" - "15672:15672" volumes: - ./docker-conf/rabbitmq/data/:/var/lib/rabbitmq/ - ./docker-conf/rabbitmq/log/:/var/log/rabbitmq - ./docker-conf/rabbitmq/definitions.json:/etc/rabbitmq/definitions.json - ./docker-conf/rabbitmq/rabbitmq.config:/etc/rabbitmq/rabbitmq.config networks: - rabbitmq_net # Yugioh Archetypes article-archetypes: container_name: article-archetypes build: context: ./src/wikia/article/src dockerfile: ./Presentation/article.archetypes/Dockerfile environment: - AppSettings__WikiaDomainUrl=https://yugioh.fandom.com - AppSettings__Category=Archetypes - AppSettings__PageSize=500 - Quartz__ArchetypeInformationJob=0 0 12 ? * TUE * - RabbitMqSettings__Host=localhost - RabbitMqSettings__Port=5672 - RabbitMqSettings__Username=guest - RabbitMqSettings__Password=<PASSWORD> - RabbitMqSettings__ContentType=application/json - RabbitMqSettings__Exchanges__yugioh.headers.article__Headers__message-type=archetypearticle - RabbitMqSettings__Exchanges__yugioh.headers.article__PersistentMode=2 depends_on: - rabbitmq # Yugioh Archetypes Cards article-archetypes-cards: container_name: article-archetypes-cards build: context: ./src/wikia/article/src dockerfile: ./Presentation/article.archetypes/Dockerfile environment: - AppSettings__WikiaDomainUrl=https://yugioh.fandom.com - AppSettings__Category=Cards by archetype - AppSettings__PageSize=500 - Quartz__ArchetypeInformationJob=0 0 1 ? * TUE * - RabbitMqSettings__Host=localhost - RabbitMqSettings__Port=5672 - RabbitMqSettings__Username=guest - RabbitMqSettings__Password=<PASSWORD> - RabbitMqSettings__ContentType=application/json - RabbitMqSettings__Exchanges__yugioh.headers.article__Headers__message-type=archetypecardsarticle - RabbitMqSettings__Exchanges__yugioh.headers.article__PersistentMode=2 depends_on: - rabbitmq # Yugioh Archetypes Support Cards article-archetypes-support-cards: container_name: article-archetypes-support-cards build: context: ./src/wikia/article/src dockerfile: ./Presentation/article.archetypes/Dockerfile environment: - AppSettings__WikiaDomainUrl=https://yugioh.fandom.com - AppSettings__Category=Cards by archetype support - AppSettings__PageSize=500 - Quartz__ArchetypeInformationJob=0 0 2 ? * TUE * - RabbitMqSettings__Host=localhost - RabbitMqSettings__Port=5672 - RabbitMqSettings__Username=guest - RabbitMqSettings__Password=<PASSWORD> - RabbitMqSettings__ContentType=application/json - RabbitMqSettings__Exchanges__yugioh.headers.article__Headers__message-type=archetypesupportcardsarticle - RabbitMqSettings__Exchanges__yugioh.headers.article__PersistentMode=2 depends_on: - rabbitmq # Yugioh Tcg Cards article-tcg-cards: container_name: article-tcg-cards build: context: ./src/wikia/article/src dockerfile: ./Presentation/article.cardinformation/Dockerfile environment: - AppSettings__WikiaDomainUrl=https://yugioh.fandom.com - AppSettings__Category=TCG cards - AppSettings__PageSize=500 - Quartz__CardInformationJob=0 58 23 ? * SUN * - RabbitMqSettings__Host=localhost - RabbitMqSettings__Port=5672 - RabbitMqSettings__Username=guest - RabbitMqSettings__Password=<PASSWORD> - RabbitMqSettings__ContentType=application/json - RabbitMqSettings__Exchanges__yugioh.headers.article__Headers__message-type=cardarticle - RabbitMqSettings__Exchanges__yugioh.headers.article__PersistentMode=2 depends_on: - rabbitmq # Yugioh Ocg Cards article-ocg-cards: container_name: article-ocg-cards build: context: ./src/wikia/article/src dockerfile: ./Presentation/article.cardinformation/Dockerfile environment: - AppSettings__WikiaDomainUrl=https://yugioh.fandom.com - AppSettings__Category=OCG cards - AppSettings__PageSize=500 - Quartz__CardInformationJob=0 58 23 ? * SUN * - RabbitMqSettings__Host=localhost - RabbitMqSettings__Port=5672 - RabbitMqSettings__Username=guest - RabbitMqSettings__Password=<PASSWORD> - RabbitMqSettings__ContentType=application/json - RabbitMqSettings__Exchanges__yugioh.headers.article__Headers__message-type=cardarticle - RabbitMqSettings__Exchanges__yugioh.headers.article__PersistentMode=2 depends_on: - rabbitmq # Yugioh Card Tips article-card-tips: container_name: article-card-tips build: context: ./src/wikia/article/src dockerfile: ./Presentation/article.cardinformation/Dockerfile environment: - AppSettings__WikiaDomainUrl=https://yugioh.fandom.com - AppSettings__Category=Card Tips - AppSettings__PageSize=500 - Quartz__CardInformationJob=0 0 12 ? 1/1 WED#3 * - RabbitMqSettings__Host=localhost - RabbitMqSettings__Port=5672 - RabbitMqSettings__Username=guest - RabbitMqSettings__Password=<PASSWORD> - RabbitMqSettings__ContentType=application/json - RabbitMqSettings__Exchanges__yugioh.headers.article__Headers__message-type=cardtipsarticle - RabbitMqSettings__Exchanges__yugioh.headers.article__PersistentMode=2 depends_on: - rabbitmq # Yugioh Card Rulings article-card-rulings: container_name: article-card-rulings build: context: ./src/wikia/article/src dockerfile: ./Presentation/article.cardinformation/Dockerfile environment: - AppSettings__WikiaDomainUrl=https://yugioh.fandom.com - AppSettings__Category=Card Rulings - AppSettings__PageSize=500 - Quartz__CardInformationJob=0 0 12 ? 1/1 THU#3 * - RabbitMqSettings__Host=localhost - RabbitMqSettings__Port=5672 - RabbitMqSettings__Username=guest - RabbitMqSettings__Password=<PASSWORD> - RabbitMqSettings__ContentType=application/json - RabbitMqSettings__Exchanges__yugioh.headers.article__Headers__message-type=cardrulingsarticle - RabbitMqSettings__Exchanges__yugioh.headers.article__PersistentMode=2 depends_on: - rabbitmq # Yugioh Card Trivia article-card-trivia: container_name: article-card-trivia build: context: ./src/wikia/article/src dockerfile: ./Presentation/article.cardinformation/Dockerfile environment: - AppSettings__WikiaDomainUrl=https://yugioh.fandom.com - AppSettings__Category=Card Trivia - AppSettings__PageSize=500 - Quartz__CardInformationJob=0 0 12 ? 1/1 FRI#3 * - RabbitMqSettings__Host=localhost - RabbitMqSettings__Port=5672 - RabbitMqSettings__Username=guest - RabbitMqSettings__Password=<PASSWORD> - RabbitMqSettings__ContentType=application/json - RabbitMqSettings__Exchanges__yugioh.headers.article__Headers__message-type=cardtriviaarticle - RabbitMqSettings__Exchanges__yugioh.headers.article__PersistentMode=2 depends_on: - rabbitmq # Yugioh Banlist article-banlist: container_name: article-banlist build: context: ./src/wikia/article/src dockerfile: ./Presentation/article.latestbanlists/Dockerfile environment: - AppSettings__WikiaDomainUrl=https://yugioh.fandom.com - AppSettings__Category=Forbidden & Limited Lists - AppSettings__PageSize=500 - Quartz__BanlistInformationJob=0 0 4 1/1 * ? * - RabbitMqSettings__Host=localhost - RabbitMqSettings__Port=5672 - RabbitMqSettings__Username=guest - RabbitMqSettings__Password=<PASSWORD> - RabbitMqSettings__ContentType=application/json - RabbitMqSettings__Exchanges__yugioh.headers.article__Headers__message-type=banlistarticle - RabbitMqSettings__Exchanges__yugioh.headers.article__PersistentMode=2 depends_on: - rabbitmq # Semantic Card Article semantic-card-article: container_name: semantic-card-article build: context: ./src/wikia/semanticsearch/src dockerfile: ./Presentation/semanticsearch.card/Dockerfile environment: - AppSettings__CardSearchUrls__normalmonster=http://yugioh.fandom.com/index.php?title=Special%3AAsk&q=%5B%5BClass+1%3A%3AOfficial%5D%5D+%5B%5BCard+type%3A%3ANormal+Monster%5D%5D&po=%3FJapanese+name%0D%0A%3FRank%0D%0A%3FLevel%0D%0A%3FAttribute%0D%0A%3FType%0D%0A%3FMonster+type%0D%0A%3FATK+string%3DATK%0D%0A%3FDEF+string%3DDEF%0D%0A&eq=yes&p%5Bformat%5D=broadtable&sort_num=&order_num=ASC&p%5Blimit%5D=500&p%5Boffset%5D=&p%5Blink%5D=all&p%5Bsort%5D=&p%5Bheaders%5D=show&p%5Bmainlabel%5D=&p%5Bintro%5D=&p%5Boutro%5D=&p%5Bsearchlabel%5D=%E2%80%A6+further+results&p%5Bdefault%5D=&p%5Bclass%5D=+sortable+wikitable+smwtable+card-list&eq=yes - AppSettings__CardSearchUrls__flipmonster=http://yugioh.fandom.com/index.php?title=Special%3AAsk&q=%5B%5BClass+1%3A%3AOfficial%5D%5D+%3Cq%3E%5B%5BEffect+type%3A%3AFlip+Effect%7C%7CFlip+Effects%5D%5D+OR+%5B%5BMonster+type%3A%3AFlip+monster%5D%5D%3C%2Fq%3E&po=%3FJapanese+name%0D%0A%3FLevel%0D%0A%3FAttribute%0D%0A%3FType%0D%0A%3FATK%0D%0A%3FDEF%0D%0A&eq=yes&p%5Bformat%5D=broadtable&sort_num=&order_num=ASC&p%5Blimit%5D=500&p%5Boffset%5D=&p%5Blink%5D=all&p%5Bsort%5D=&p%5Bheaders%5D=show&p%5Bmainlabel%5D=&p%5Bintro%5D=&p%5Boutro%5D=&p%5Bsearchlabel%5D=%E2%80%A6+further+results&p%5Bdefault%5D=&p%5Bclass%5D=sortable+wikitable+smwtable&eq=yes" - Quartz__SemanticSearchCardJob=0 0 9 ? * SAT * - RabbitMqSettings__Host=localhost - RabbitMqSettings__Port=5672 - RabbitMqSettings__Username=guest - RabbitMqSettings__Password=<PASSWORD> - RabbitMqSettings__ContentType=application/json - RabbitMqSettings__Exchanges__yugioh.headers.article__Headers__message-type"=semanticcardarticle - RabbitMqSettings__Exchanges__yugioh.headers.article__PersistentMode=2 depends_on: - rabbitmq # Card Article Data card-article-data: container_name: card-article-data build: context: ./src/wikia/data/carddata/src dockerfile: ./Presentation/carddata/Dockerfile environment: - RabbitMqSettings__Host=localhost - RabbitMqSettings__Port=5672 - RabbitMqSettings__Username=guest - RabbitMqSettings__Password=<PASSWORD> - RabbitMqSettings__ContentType=application/json - RabbitMqSettings__Exchanges__yugioh.headers.data__Headers__message-type=carddata - RabbitMqSettings__Exchanges__yugioh.headers.data__PersistentMode=2 - RabbitMqSettings__Queues__CardArticleQueue=card-article - RabbitMqSettings__Queues__SemanticArticleQueue=semantic-card-article depends_on: - rabbitmq networks: rabbitmq_net: driver: bridge<file_sep>/src/wikia/data/carddata/src/Tests/Integration/carddata.infrastructure.integration.tests/WebPagesTests/CardsTests/CardHtmlDocumentTests/AttributeTests.cs using carddata.infrastructure.WebPages; using carddata.infrastructure.WebPages.Cards; using carddata.tests.core; using FluentAssertions; using NUnit.Framework; namespace carddata.infrastructure.integration.tests.WebPagesTests.CardsTests.CardHtmlDocumentTests { [TestFixture] [Category(TestType.Integration)] public class AttributeTests { private CardHtmlDocument _sut; [SetUp] public void SetUp() { _sut = new CardHtmlDocument(new CardHtmlTable()); } [TestCase("https://yugioh.fandom.com/wiki/4-Starred_Ladybug_of_Doom", "WIND")] public void Given_A_Card_Profile_WebPage_Url_Should_Extract_Attribute(string url, string expected) { // Arrange var htmlWebPage = new HtmlWebPage(); var htmlDocument = htmlWebPage.Load(url); // Act var result = _sut.Attribute(htmlDocument); // Assert result.Should().BeEquivalentTo(expected); } } }<file_sep>/src/wikia/semanticsearch/src/Domain/semanticsearch.domain/Messaging/Exchanges/IArticleHeaderExchange.cs using System.Threading.Tasks; using semanticsearch.core.Model; namespace semanticsearch.domain.Messaging.Exchanges { public interface IArticleHeaderExchange { Task Publish(SemanticCard semanticCard); } }<file_sep>/src/wikia/data/archetypedata/src/Application/archetypedata.application/Configuration/QueueSetting.cs using System.Collections.Generic; namespace archetypedata.application.Configuration { public class QueueSetting { public Dictionary<string, string> Headers { get; set; } } }<file_sep>/src/wikia/processor/banlistprocessor/src/Tests/Unit/banlistprocessor.domain.unit.tests/BanlistCardServiceTests.cs using System.Collections.Generic; using System.Threading.Tasks; using banlistprocessor.core.Models; using banlistprocessor.core.Models.Db; using banlistprocessor.domain.Repository; using banlistprocessor.domain.Services; using banlistprocessor.tests.core; using NSubstitute; using NUnit.Framework; namespace banlistprocessor.domain.unit.tests { [TestFixture] [Category(TestType.Unit)] public class BanlistCardServiceTests { private ILimitRepository _limitRepository; private ICardRepository _cardRepository; private IBanlistCardRepository _banlistCardRepository; private BanlistCardService _sut; [SetUp] public void SetUp() { _limitRepository = Substitute.For<ILimitRepository>(); _cardRepository = Substitute.For<ICardRepository>(); _banlistCardRepository = Substitute.For<IBanlistCardRepository>(); _sut = new BanlistCardService ( _limitRepository, _cardRepository, _banlistCardRepository ); } [Test] public async Task Given_A_BanlistId_And_BanlistSections_Should_Invoke_Update_Method_Once() { // Arrange var yugiohBanlistSections = new List<YugiohBanlistSection> { new YugiohBanlistSection { Title = "Forbidden", Content = new List<string>{ "Dark Hole"} }, new YugiohBanlistSection { Title = "Limited", Content = new List<string>{ "Raigeki"} }, new YugiohBanlistSection { Title = "Semi-Limited", Content = new List<string>{ "One For One"} }, new YugiohBanlistSection { Title = "Unlimited", Content = new List<string>{ "Macro"} } }; _limitRepository.GetAll().Returns(new List<Limit> { new Limit { Id = 1, Name = "Forbidden" }, new Limit { Id = 2, Name = "Limited" }, new Limit { Id = 3, Name = "Semi-Limited" }, new Limit { Id = 4, Name = "Unlimited" } }); _cardRepository.CardByName(Arg.Any<string>()).Returns(new Card { Id = 432 }); // Act await _sut.Update(123, yugiohBanlistSections); // Assert await _banlistCardRepository.Received(1).Update(Arg.Any<long>(), Arg.Any<List<BanlistCard>>()); } } }<file_sep>/src/wikia/processor/cardsectionprocessor/README.md ![alt text](https://fablecode.visualstudio.com/Yugioh%20Insight/_apis/build/status/Build-CardSectionProcessor "Visual studio team services build status") # Card Section Processor Persists card section data. <file_sep>/src/wikia/processor/imageprocessor/src/Application/imageprocessor.application/ApplicationInstaller.cs using FluentValidation; using imageprocessor.application.Commands.DownloadImage; using imageprocessor.core.Services; using imageprocessor.domain.Services; using MediatR; using Microsoft.Extensions.DependencyInjection; using System.Reflection; namespace imageprocessor.application { public static class ApplicationInstaller { public static IServiceCollection AddApplicationServices(this IServiceCollection services) { services .AddCqrs() .AddValidation() .AddDomainServices() .AddDecorators(); return services; } private static IServiceCollection AddCqrs(this IServiceCollection services) { services.AddMediatR(typeof(ApplicationInstaller).GetTypeInfo().Assembly); return services; } private static IServiceCollection AddValidation(this IServiceCollection services) { services.AddTransient<IValidator<DownloadImageCommand>, DownloadImageCommandValidator>(); return services; } private static IServiceCollection AddDomainServices(this IServiceCollection services) { services.AddTransient<IFileSystemService, FileSystemService>(); return services; } private static IServiceCollection AddDecorators(this IServiceCollection services) { //services.Decorate<IRequestHandler<DownloadImageCommand, CommandResult>, DownloadImageCommandHandlerLoggerDecorator>(); return services; } } }<file_sep>/src/wikia/article/src/Tests/Unit/article.domain.unit.tests/ArticleListTests/ItemTests/ArchetypeItemProcessorTests/HandlesTests.cs using article.core.Constants; using article.domain.ArticleList.Item; using article.domain.Services.Messaging; using article.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace article.domain.unit.tests.ArticleListTests.ItemTests.ArchetypeItemProcessorTests { [TestFixture] [Category(TestType.Unit)] public class HandlesTests { private IArchetypeArticleQueue _archetypeArticleQueue; private ArchetypeItemProcessor _sut; [SetUp] public void SetUp() { _archetypeArticleQueue = Substitute.For<IArchetypeArticleQueue>(); _sut = new ArchetypeItemProcessor(_archetypeArticleQueue); } [TestCase(ArticleCategory.Archetype)] public void Given_A_Valid_Category_Should_Return_True(string category) { // Arrange // Act var result = _sut.Handles(category); // Assert result.Should().BeTrue(); } [TestCase("category")] public void Given_A_Valid_Category_Should_Return_False(string category) { // Arrange // Act var result = _sut.Handles(category); // Assert result.Should().BeFalse(); } } }<file_sep>/src/wikia/data/banlistdata/src/Domain/banlistdata.domain/Services/Messaging/IBanlistDataQueue.cs using System.Threading.Tasks; using banlistdata.core.Models; namespace banlistdata.domain.Services.Messaging { public interface IBanlistDataQueue { Task<YugiohBanlistCompletion> Publish(ArticleProcessed articleProcessed); } }<file_sep>/src/wikia/semanticsearch/src/Presentation/semanticsearch.card/QuartzConfiguration/SemanticSearchCardJob.cs using MediatR; using Quartz; using System.Threading.Tasks; using semanticsearch.application.ScheduledTasks.CardSearch; namespace semanticsearch.card.QuartzConfiguration { public class SemanticSearchCardJob : IJob { private readonly IMediator _mediator; public SemanticSearchCardJob(IMediator mediator) { _mediator = mediator; } public async Task Execute(IJobExecutionContext context) { await _mediator.Send(new SemanticSearchCardTask()); } } }<file_sep>/src/wikia/data/carddata/src/Domain/carddata.domain/Services/Messaging/IYugiohCardQueue.cs using System.Threading.Tasks; using carddata.core.Models; namespace carddata.domain.Services.Messaging { public interface IYugiohCardQueue { Task<YugiohCardCompletion> Publish(ArticleProcessed articleProcessed); } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Domain/cardsectionprocessor.domain/Repository/ICardTipRepository.cs using System.Collections.Generic; using System.Threading.Tasks; using cardsectionprocessor.core.Models.Db; namespace cardsectionprocessor.domain.Repository { public interface ICardTipRepository { Task DeleteByCardId(long id); Task Update(List<TipSection> tipSections); } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Dto/ArchetypeCardDto.cs namespace cardprocessor.application.Dto { public class ArchetypeCardDto { public long ArchetypeId { get; set; } public long CardId { get; set; } } }<file_sep>/src/wikia/processor/cardprocessor/src/Domain/cardprocessor.domain/Services/TypeService.cs using System.Collections.Generic; using System.Threading.Tasks; using cardprocessor.core.Models.Db; using cardprocessor.core.Services; using cardprocessor.domain.Repository; namespace cardprocessor.domain.Services { public class TypeService : ITypeService { private readonly ITypeRepository _typeRepository; public TypeService(ITypeRepository typeRepository) { _typeRepository = typeRepository; } public Task<List<Type>> AllTypes() { return _typeRepository.AllTypes(); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Domain/cardprocessor.domain/SystemIO/IFileSystem.cs using System; using System.Threading.Tasks; using cardprocessor.core.Models; namespace cardprocessor.domain.SystemIO { public interface IFileSystem { Task<DownloadedFile> Download(Uri remoteFileUrl, string localFileFullPath); void Delete(string localFileFullPath); void Rename(string oldNameFullPath, string newNameFullPath); string[] GetFiles(string path, string searchPattern); bool Exists(string localFileFullPath); } }<file_sep>/src/wikia/data/archetypedata/src/Presentation/archetypedata/Services/ArchetypeDataHostedService.cs using archetypedata.application.Configuration; using archetypedata.application.MessageConsumers.ArchetypeInformation; using MediatR; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Text; using System.Threading; using System.Threading.Tasks; namespace archetypedata.Services { public sealed class ArchetypeDataHostedService : BackgroundService { private const string ArchetypeArticleQueue = "archetype-article"; public IServiceProvider Services { get; } private readonly ILogger<ArchetypeDataHostedService> _logger; private readonly IOptions<RabbitMqSettings> _rabbitMqOptions; private readonly IOptions<AppSettings> _appSettingsOptions; private readonly IMediator _mediator; private ConnectionFactory _factory; private IConnection _connection; private IModel _channel; public ArchetypeDataHostedService ( ILogger<ArchetypeDataHostedService> logger, IServiceProvider services, IOptions<RabbitMqSettings> rabbitMqOptions, IOptions<AppSettings> appSettingsOptions, IMediator mediator ) { Services = services; _logger = logger; _rabbitMqOptions = rabbitMqOptions; _appSettingsOptions = appSettingsOptions; _mediator = mediator; } protected override Task ExecuteAsync(CancellationToken stoppingToken) { stoppingToken.ThrowIfCancellationRequested(); _factory = new ConnectionFactory { HostName = _rabbitMqOptions.Value.Host, UserName = _rabbitMqOptions.Value.Username, Password = _rabbit<PASSWORD>.Value.Password, DispatchConsumersAsync = true }; _connection = _factory.CreateConnection(); _channel = _connection.CreateModel(); _channel.BasicQos(0, 1, false); var consumer = new AsyncEventingBasicConsumer(_channel); consumer.Received += async (ch, ea) => { try { var body = ea.Body.ToArray(); var message = Encoding.UTF8.GetString(body); var result = await _mediator.Send(new ArchetypeInformationConsumer { Message = message }, stoppingToken); if (result.IsSuccessful) { _channel.BasicAck(ea.DeliveryTag, false); } else { _channel.BasicNack(ea.DeliveryTag, false, false); } await Task.Yield(); } catch (Exception ex) { _logger.LogError("RabbitMq Consumer: " + ArchetypeArticleQueue + " exception. Exception: {@Exception}", ex); } }; consumer.Shutdown += OnArchetypeArticleConsumerShutdown; consumer.Registered += OnArchetypeArticleConsumerRegistered; consumer.Unregistered += OnArchetypeArticleConsumerUnregistered; consumer.ConsumerCancelled += OnArchetypeArticleConsumerCancelled; _channel.BasicConsume(ArchetypeArticleQueue, false, consumer); return Task.CompletedTask; } #region private helper private Task OnArchetypeArticleConsumerCancelled(object sender, ConsumerEventArgs @event) { _logger.LogInformation($"Consumer '{ArchetypeArticleQueue}' Cancelled"); return Task.CompletedTask; } private Task OnArchetypeArticleConsumerUnregistered(object sender, ConsumerEventArgs @event) { _logger.LogInformation($"Consumer '{ArchetypeArticleQueue}' Unregistered"); return Task.CompletedTask; } private Task OnArchetypeArticleConsumerRegistered(object sender, ConsumerEventArgs @event) { _logger.LogInformation($"Consumer '{ArchetypeArticleQueue}' Registered"); return Task.CompletedTask; } private Task OnArchetypeArticleConsumerShutdown(object sender, ShutdownEventArgs e) { _logger.LogInformation($"Consumer '{ArchetypeArticleQueue}' Shutdown"); return Task.CompletedTask; } #endregion public override void Dispose() { _channel.Close(); _connection.Close(); base.Dispose(); } } } <file_sep>/src/wikia/article/src/Core/article.core/ArticleList/Processor/IArticleBatchProcessor.cs using article.core.Models; using System.Threading.Tasks; using wikia.Models.Article.AlphabeticalList; namespace article.core.ArticleList.Processor { public interface IArticleBatchProcessor { Task<ArticleBatchTaskResult> Process(string category, UnexpandedArticle[] articles); } }<file_sep>/src/wikia/data/cardsectiondata/src/Domain/cardsectiondata.domain/WebPages/ITipRelatedHtmlDocument.cs using HtmlAgilityPack; namespace cardsectiondata.domain.WebPages { public interface ITipRelatedHtmlDocument { HtmlNode GetTable(HtmlDocument document); string GetUrl(HtmlDocument document); } }<file_sep>/src/wikia/article/src/Presentation/article.archetypes/QuartzConfiguration/ArchetypeInformationJob.cs using article.application.ScheduledTasks.Archetype; using MediatR; using Quartz; using System.Threading.Tasks; using article.application.Configuration; using article.domain.Settings; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace article.archetypes.QuartzConfiguration { [DisallowConcurrentExecution] public class ArchetypeInformationJob : IJob { private readonly IMediator _mediator; private readonly ILogger<ArchetypeInformationJob> _logger; private readonly IOptions<AppSettings> _options; public ArchetypeInformationJob(IMediator mediator, ILogger<ArchetypeInformationJob> logger, IOptions<AppSettings> options) { _mediator = mediator; _logger = logger; _options = options; } public async Task Execute(IJobExecutionContext context) { var result = await _mediator.Send(new ArchetypeInformationTask { Category = _options.Value.Category, PageSize = _options.Value.PageSize }); _logger.LogInformation("Finished processing '{Category}' category.", _options.Value.Category); if (!result.IsSuccessful) { _logger.LogInformation("Errors while processing '{Category}' category. Errors: {Errors}", _options.Value.Category, result.Errors); } } } }<file_sep>/src/wikia/data/archetypedata/src/Core/archetypedata.core/Processor/IArchetypeProcessor.cs using System.Threading.Tasks; using archetypedata.core.Models; namespace archetypedata.core.Processor { public interface IArchetypeProcessor { Task<ArticleTaskResult> Process(Article article); } }<file_sep>/src/wikia/data/archetypedata/src/Application/archetypedata.application/MessageConsumers/ArchetypeInformation/ArchetypeInformationConsumer.cs using MediatR; namespace archetypedata.application.MessageConsumers.ArchetypeInformation { public class ArchetypeInformationConsumer : IRequest<ArchetypeInformationConsumerResult> { public string Message { get; set; } } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Core/archetypeprocessor.core/Processor/IArchetypeProcessor.cs using System.Threading.Tasks; using archetypeprocessor.core.Models; namespace archetypeprocessor.core.Processor { public interface IArchetypeProcessor { Task<ArchetypeDataTaskResult<ArchetypeMessage>> Process(ArchetypeMessage archetypeData); } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Infrastructure/cardsectionprocessor.infrastructure/InfrastructureInstaller.cs using cardsectionprocessor.domain.Repository; using cardsectionprocessor.infrastructure.Database; using cardsectionprocessor.infrastructure.Repository; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; namespace cardsectionprocessor.infrastructure { public static class InfrastructureInstaller { public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, string connectionString) { services.AddYgoDatabase(connectionString); services.AddRepositories(); return services; } public static IServiceCollection AddYgoDatabase(this IServiceCollection services, string connectionString) { services.AddDbContext<YgoDbContext>(c => c.UseSqlServer(connectionString), ServiceLifetime.Transient); return services; } public static IServiceCollection AddRepositories(this IServiceCollection services) { services.AddTransient<ICardRepository, CardRepository>(); services.AddTransient<ICardTipRepository, CardTipRepository>(); services.AddTransient<ICardRulingRepository, CardRulingRepository>(); services.AddTransient<ICardTriviaRepository, CardTriviaRepository>(); return services; } } }<file_sep>/src/wikia/data/cardsectiondata/src/Application/cardsectiondata.application/ApplicationInstaller.cs using cardsectiondata.application.Configuration; using cardsectiondata.core.Processor; using cardsectiondata.domain.ArticleList.Item; using cardsectiondata.domain.ArticleList.Processor; using MediatR; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using System.Net.Http; using System.Reflection; using cardsectiondata.application.MessageConsumers.CardInformation; using cardsectiondata.application.MessageConsumers.CardRulingInformation; using cardsectiondata.application.MessageConsumers.CardTipInformation; using cardsectiondata.application.MessageConsumers.CardTriviaInformation; using FluentValidation; using wikia.Api; namespace cardsectiondata.application { public static class ApplicationInstaller { public static IServiceCollection AddApplicationServices(this IServiceCollection services) { services .AddCqrs() .AddValidation() .AddDomainServices(); return services; } private static IServiceCollection AddCqrs(this IServiceCollection services) { services.AddMediatR(typeof(ApplicationInstaller).GetTypeInfo().Assembly); return services; } private static IServiceCollection AddDomainServices(this IServiceCollection services) { services.AddTransient<IArticleProcessor, ArticleProcessor>(); services.AddTransient<ICardSectionProcessor, CardSectionProcessor>(); services.AddTransient<IArticleItemProcessor, CardTipItemProcessor>(); services.AddTransient<IArticleItemProcessor, CardRulingItemProcessor>(); services.AddTransient<IArticleItemProcessor, CardTriviaItemProcessor>(); var buildServiceProvider = services.BuildServiceProvider(); var appSettings = buildServiceProvider.GetService<IOptions<AppSettings>>(); services.AddSingleton<IWikiArticle>(new WikiArticle(appSettings.Value.WikiaDomainUrl, buildServiceProvider.GetService<IHttpClientFactory>())); return services; } private static IServiceCollection AddValidation(this IServiceCollection services) { services.AddTransient<IValidator<CardInformationConsumer>, CardInformationConsumerValidator>(); return services; } } }<file_sep>/src/wikia/processor/banlistprocessor/src/Tests/Unit/banlistprocessor.domain.unit.tests/BanlistServiceTests/UpdateBanlistTests.cs using System; using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; using banlistprocessor.core.Enums; using banlistprocessor.core.Models; using banlistprocessor.core.Models.Db; using banlistprocessor.core.Services; using banlistprocessor.domain.Mappings.Profiles; using banlistprocessor.domain.Repository; using banlistprocessor.domain.Services; using banlistprocessor.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace banlistprocessor.domain.unit.tests.BanlistServiceTests { [TestFixture] [Category(TestType.Unit)] public class UpdateBanlistTests { private BanlistService _sut; private IBanlistRepository _banlistRepository; private IBanlistCardService _banlistCardService; private IFormatRepository _formatRepository; [SetUp] public void SetUp() { var config = new MapperConfiguration ( cfg => { cfg.AddProfile(new BanlistProfile()); } ); var mapper = config.CreateMapper(); _banlistRepository = Substitute.For<IBanlistRepository>(); _banlistCardService = Substitute.For<IBanlistCardService>(); _formatRepository = Substitute.For<IFormatRepository>(); _sut = new BanlistService ( _banlistCardService, _banlistRepository, _formatRepository, mapper ); } [Test] public async Task Given_A_YugiohBanlist_Should_Invoke_GetBanlistById_Method_Once() { // Arrange const int expected = 1; var yugiohBanlist = new YugiohBanlist{ BanlistType = BanlistType.Tcg}; _formatRepository.FormatByAcronym(Arg.Any<string>()).Returns(new Format()); _banlistRepository.Update(Arg.Any<Banlist>()).Returns(new Banlist()); _banlistRepository.GetBanlistById(Arg.Any<int>()).Returns(new Banlist()); // Act await _sut.Update(yugiohBanlist); // Assert await _banlistRepository.Received(expected).GetBanlistById(Arg.Any<int>()); } [Test] public async Task Given_A_YugiohBanlist_Should_Invoke_FormatByAcronym_Method_Once() { // Arrange const int expected = 1; var yugiohBanlist = new YugiohBanlist{ BanlistType = BanlistType.Tcg}; _formatRepository.FormatByAcronym(Arg.Any<string>()).Returns(new Format()); _banlistRepository.Update(Arg.Any<Banlist>()).Returns(new Banlist()); _banlistRepository.GetBanlistById(Arg.Any<int>()).Returns(new Banlist()); // Act await _sut.Update(yugiohBanlist); // Assert await _formatRepository.Received(expected).FormatByAcronym(Arg.Any<string>()); } [Test] public void Given_A_YugiohBanlist_If_Format_Is_Not_Found_Should_Throw_ArgumentException() { // Arrange var yugiohBanlist = new YugiohBanlist(); _banlistRepository.GetBanlistById(Arg.Any<int>()).Returns(new Banlist()); _banlistRepository.Update(Arg.Any<Banlist>()).Returns(new Banlist()); // Act Func<Task<Banlist>> act = () => _sut.Update(yugiohBanlist); // Assert act.Should().Throw<ArgumentException>(); } [Test] public async Task Given_A_YugiohBanlist_Should_Invoke_BanlistRepository_Update_Method_Once() { // Arrange const int expected = 1; var yugiohBanlist = new YugiohBanlist(); _formatRepository.FormatByAcronym(Arg.Any<string>()).Returns(new Format()); _banlistRepository.Update(Arg.Any<Banlist>()).Returns(new Banlist()); _banlistRepository.GetBanlistById(Arg.Any<int>()).Returns(new Banlist()); // Act await _sut.Update(yugiohBanlist); // Assert await _banlistRepository.Received(expected).Update(Arg.Any<Banlist>()); } [Test] public async Task Given_A_YugiohBanlist_Should_Invoke_BanlistCardService_Update_Method_Once() { // Arrange const int expected = 1; var yugiohBanlist = new YugiohBanlist(); _formatRepository.FormatByAcronym(Arg.Any<string>()).Returns(new Format()); _banlistRepository.Update(Arg.Any<Banlist>()).Returns(new Banlist()); _banlistRepository.GetBanlistById(Arg.Any<int>()).Returns(new Banlist()); // Act await _sut.Update(yugiohBanlist); // Assert await _banlistCardService.Received(expected).Update(Arg.Any<long>(),Arg.Any<List<YugiohBanlistSection>>()); } } }<file_sep>/src/wikia/data/archetypedata/src/Tests/Unit/archetypedata.domain.unit.tests/ArchetypeCardProcessorTests/ProcessTests.cs using System; using System.Threading.Tasks; using archetypedata.core.Models; using archetypedata.domain.Processor; using archetypedata.domain.Services.Messaging; using archetypedata.domain.WebPages; using archetypedata.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace archetypedata.domain.unit.tests.ArchetypeCardProcessorTests { [TestFixture] [Category(TestType.Unit)] public class ProcessTests { private IArchetypeWebPage _archetypeWebPage; private IQueue<ArchetypeCard> _queue; private ArchetypeCardProcessor _sut; [SetUp] public void SetUp() { _archetypeWebPage = Substitute.For<IArchetypeWebPage>(); _queue = Substitute.For<IQueue<ArchetypeCard>>(); _sut = new ArchetypeCardProcessor(_archetypeWebPage, _queue); } [Test] public async Task Given_A_ArchetypeCard_If_Processed_Successfully_IsSuccessful_Property_Should_Be_True() { // Arrange var article = new Article { CorrelationId = Guid.NewGuid(), Id = 423423, Title = "List of \"Clear Wing\" cards", Url = "http://yugioh.wikia.com/wiki/List_of_\"Clear_Wing\"_cards" }; // Act var result = await _sut.Process(article); // Assert result.IsSuccessful.Should().BeTrue(); } [Test] public async Task Given_A_ArchetypeCard_Should_Invoke_Publish_Method_Once() { // Arrange var article = new Article { CorrelationId = Guid.NewGuid(), Id = 423423, Title = "List of \"Clear Wing\" cards", Url = "http://yugioh.wikia.com/wiki/List_of_\"Clear_Wing\"_cards" }; // Act await _sut.Process(article); // Assert await _queue.Received(1).Publish(Arg.Any<ArchetypeCard>()); } [Test] public async Task Given_A_ArchetypeCard_Should_Invoke_Cards_Method_Once() { // Arrange var article = new Article { CorrelationId = Guid.NewGuid(), Id = 423423, Title = "List of \"Clear Wing\" cards", Url = "http://yugioh.wikia.com/wiki/List_of_\"Clear_Wing\"_cards" }; // Act await _sut.Process(article); // Assert _archetypeWebPage.Received(1).Cards(Arg.Any<Uri>()); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Tests/Unit/cardprocessor.application.unit.tests/MappingsTests/MapperTests/CommandMapperHelperTests/MapCardByCardTypeTests.cs using System; using AutoMapper; using cardprocessor.application.Dto; using cardprocessor.application.Enums; using cardprocessor.application.Mappings.Mappers; using cardprocessor.application.Mappings.Profiles; using cardprocessor.core.Models.Db; using cardprocessor.tests.core; using FluentAssertions; using NUnit.Framework; namespace cardprocessor.application.unit.tests.MappingsTests.MapperTests.CommandMapperHelperTests { [TestFixture] [Category(TestType.Unit)] public class MapCardByCardTypeTests { private IMapper _mapper; [SetUp] public void SetUp() { var config = new MapperConfiguration ( cfg => { cfg.AddProfile(new CardProfile()); } ); _mapper = config.CreateMapper(); } [Test] public void Given_An_Invalid_CardType_Should_Throw_ArgumentOutOfRange_Exception() { // Arrange const YgoCardType cardType = (YgoCardType)7; var card = new Card { Id = 23424 }; // Act Action act = () => CommandMapperHelper.MapCardByCardType(_mapper, cardType, card); // Assert act.Should().Throw<ArgumentOutOfRangeException>(); } [Test] public void Given_A_Spell_CardType_Should_Return_Object_Of_Type_SpellCardDto() { // Arrange const YgoCardType cardType = YgoCardType.Spell; var card = new Card { Id = 23424 }; // Act var result = CommandMapperHelper.MapCardByCardType(_mapper, cardType, card); // Assert result.Should().BeOfType<SpellCardDto>(); } [Test] public void Given_A_Trap_CardType_Should_Return_Object_Of_Type_TrapCardDto() { // Arrange const YgoCardType cardType = YgoCardType.Trap; var card = new Card { Id = 23424 }; // Act var result = CommandMapperHelper.MapCardByCardType(_mapper, cardType, card); // Assert result.Should().BeOfType<TrapCardDto>(); } [Test] public void Given_A_Monster_CardType_Should_Return_Object_Of_Type_TrapCardDto() { // Arrange const YgoCardType cardType = YgoCardType.Monster; var card = new Card { Id = 23424 }; // Act var result = CommandMapperHelper.MapCardByCardType(_mapper, cardType, card); // Assert result.Should().BeOfType<MonsterCardDto>(); } } }<file_sep>/src/wikia/data/banlistdata/src/Core/banlistdata.core/Models/YugiohBanlistCompletion.cs using banlistdata.core.Exceptions; namespace banlistdata.core.Models { public class YugiohBanlistCompletion { public bool IsSuccessful { get; set; } public Article Article { get; set; } public YugiohBanlist Banlist { get; set; } public BanlistException Exception { get; set; } } }<file_sep>/src/wikia/semanticsearch/src/Core/semanticsearch.core/Model/SemanticSearchCardTaskResult.cs using semanticsearch.core.Exceptions; using System.Collections.Generic; namespace semanticsearch.core.Model { public class SemanticSearchCardTaskResult { public bool IsSuccessful { get; set; } public string Url { get; set; } public int Processed { get; set; } public List<SemanticCardPublishException> Failed { get; set; } = new(); } }<file_sep>/src/wikia/processor/imageprocessor/src/Application/imageprocessor.application/MessageConsumers/YugiohImage/ImageConsumerHandler.cs using System; using System.IO; using System.Threading; using System.Threading.Tasks; using imageprocessor.application.Commands.DownloadImage; using MediatR; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace imageprocessor.application.MessageConsumers.YugiohImage { public class ImageConsumerHandler : IRequestHandler<ImageConsumer, ImageConsumerResult> { private readonly IMediator _mediator; private readonly ILogger<ImageConsumerHandler> _logger; public ImageConsumerHandler(IMediator mediator, ILogger<ImageConsumerHandler> logger) { _mediator = mediator; _logger = logger; } public async Task<ImageConsumerResult> Handle(ImageConsumer request, CancellationToken cancellationToken) { var cardImageConsumerResult = new ImageConsumerResult(); try { var downloadCommand = JsonConvert.DeserializeObject<DownloadImageCommand>(request.Message); _logger.LogInformation("Downloading image '{@RemoteImageUrl}' to local path '{@LocalPath}'", downloadCommand.RemoteImageUrl, Path.Combine(downloadCommand.ImageFolderPath, downloadCommand.ImageFileName)); var result = await _mediator.Send(downloadCommand, cancellationToken); _logger.LogInformation("Finished downloading image '{@RemoteImageUrl}' to local path '{@LocalPath}'", downloadCommand.RemoteImageUrl, Path.Combine(downloadCommand.ImageFolderPath, downloadCommand.ImageFileName)); cardImageConsumerResult.IsSuccessful = result.IsSuccessful; } catch (Exception ex) { _logger.LogError("Error downloading image '{@MessageJson}'. Exception: {@Exception}", request.Message, ex); cardImageConsumerResult.Exception = ex; } return cardImageConsumerResult; } } }<file_sep>/src/wikia/data/archetypedata/src/Infrastructure/archetypedata.infrastructure/WebPages/ArchetypeThumbnail.cs using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using archetypedata.application.Configuration; using archetypedata.domain.Helpers; using archetypedata.domain.WebPages; using Microsoft.Extensions.Options; using wikia.Api; using wikia.Models.Article.Details; namespace archetypedata.infrastructure.WebPages { public class ArchetypeThumbnail : IArchetypeThumbnail { private readonly IWikiArticle _wikiArticle; private readonly IHtmlWebPage _htmlWebPage; private readonly IOptions<AppSettings> _appsettings; public ArchetypeThumbnail(IWikiArticle wikiArticle, IHtmlWebPage htmlWebPage, IOptions<AppSettings> appsettings) { _wikiArticle = wikiArticle; _htmlWebPage = htmlWebPage; _appsettings = appsettings; } public async Task<string> FromArticleId(int articleId) { var profileDetailsList = await _wikiArticle.Details(articleId); var profileDetails = profileDetailsList.Items.First(); return FromArticleDetails(profileDetails); } public string FromArticleDetails(KeyValuePair<string, ExpandedArticle> articleDetails) { return ImageHelper.ExtractImageUrl(articleDetails.Value.Thumbnail); } public string FromWebPage(string url) { var archetypeWebPage = _htmlWebPage.Load(_appsettings.Value.WikiaDomainUrl + url); var srcElement = archetypeWebPage.DocumentNode.SelectSingleNode("//img[@class='pi-image-thumbnail']"); var srcAttribute = srcElement?.Attributes?["src"].Value; return srcAttribute != null ? ImageHelper.ExtractImageUrl(srcAttribute) : null; } } }<file_sep>/src/wikia/processor/cardprocessor/src/Core/cardprocessor.core/Services/Messaging/Cards/ICardImageQueueService.cs using System.Threading.Tasks; using cardprocessor.core.Models; namespace cardprocessor.core.Services.Messaging.Cards { public interface ICardImageQueueService { Task<CardImageCompletion> Publish(DownloadImage downloadImage); } }<file_sep>/src/wikia/article/src/Application/article.application/ScheduledTasks/Archetype/ArchetypeInformationTaskResult.cs using article.core.Models; using System.Collections.Generic; namespace article.application.ScheduledTasks.Archetype { public class ArchetypeInformationTaskResult { public List<string> Errors { get; set; } public bool IsSuccessful { get; set; } public ArticleBatchTaskResult ArticleTaskResult { get; set; } } }<file_sep>/src/wikia/processor/banlistprocessor/src/Infrastructure/banlistprocessor.infrastructure/Repository/FormatRepository.cs using System.Threading.Tasks; using banlistprocessor.core.Models.Db; using banlistprocessor.domain.Repository; using banlistprocessor.infrastructure.Database; using Microsoft.EntityFrameworkCore; namespace banlistprocessor.infrastructure.Repository { public class FormatRepository : IFormatRepository { private readonly YgoDbContext _dbContext; public FormatRepository(YgoDbContext dbContext) { _dbContext = dbContext; } public Task<Format> FormatByAcronym(string acronym) { return _dbContext .Format .AsNoTracking() .SingleOrDefaultAsync(f => f.Acronym == acronym); } } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Domain/archetypeprocessor.domain/Processor/ArchetypeCardProcessor.cs using System.Linq; using archetypeprocessor.core.Models; using archetypeprocessor.core.Processor; using archetypeprocessor.core.Services; using System.Threading.Tasks; namespace archetypeprocessor.domain.Processor { public class ArchetypeCardProcessor : IArchetypeCardProcessor { private readonly IArchetypeService _archetypeService; private readonly IArchetypeCardsService _archetypeCardsService; public ArchetypeCardProcessor(IArchetypeService archetypeService, IArchetypeCardsService archetypeCardsService) { _archetypeService = archetypeService; _archetypeCardsService = archetypeCardsService; } public async Task<ArchetypeDataTaskResult<ArchetypeCardMessage>> Process(ArchetypeCardMessage archetypeData) { var articleDataTaskResult = new ArchetypeDataTaskResult<ArchetypeCardMessage> { ArchetypeData = archetypeData }; var existingArchetype = await _archetypeService.ArchetypeByName(archetypeData.ArchetypeName); if (existingArchetype != null && archetypeData.Cards.Any()) { await _archetypeCardsService.Update(existingArchetype.Id, archetypeData.Cards); } return articleDataTaskResult; } } }<file_sep>/src/wikia/data/archetypedata/src/Core/archetypedata.core/Models/Archetype.cs using System; namespace archetypedata.core.Models { public class Archetype { public long Id { get; set; } public string Name { get; set; } public string ImageUrl { get; set; } public string ProfileUrl { get; set; } public DateTime Revision { get; set; } } }<file_sep>/src/wikia/article/src/Domain/article.domain/WebPages/IHtmlWebPage.cs using System; using HtmlAgilityPack; namespace article.domain.WebPages { public interface IHtmlWebPage { HtmlDocument Load(string url); HtmlDocument Load(Uri url); } }<file_sep>/src/wikia/data/banlistdata/src/Core/banlistdata.core/Models/ArticleCompletion.cs using System; namespace banlistdata.core.Models { public class ArticleCompletion { public bool IsSuccessful { get; set; } public Article Message { get; set; } public Exception Exception { get; set; } } }<file_sep>/src/wikia/article/src/Tests/Unit/article.domain.unit.tests/ArticleListTests/ItemTests/CardItemProcessorTests/HandlesTests.cs using article.core.Constants; using article.domain.ArticleList.Item; using article.domain.Services.Messaging.Cards; using article.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace article.domain.unit.tests.ArticleListTests.ItemTests.CardItemProcessorTests { [TestFixture] [Category(TestType.Unit)] public class HandlesTests { private ICardArticleQueue _cardArticleQueue; private CardItemProcessor _sut; [SetUp] public void SetUp() { _cardArticleQueue = Substitute.For<ICardArticleQueue>(); _sut = new CardItemProcessor(_cardArticleQueue); } [TestCase(ArticleCategory.TcgCards)] [TestCase(ArticleCategory.OcgCards)] public void Given_A_Valid_Category_Should_Return_True(string category) { // Arrange // Act var result = _sut.Handles(category); // Assert result.Should().BeTrue(); } [TestCase("category")] public void Given_A_Valid_Category_Should_Return_False(string category) { // Arrange // Act var result = _sut.Handles(category); // Assert result.Should().BeFalse(); } } }<file_sep>/src/wikia/processor/banlistprocessor/src/Domain/banlistprocessor.domain/banlistprocessor.domain/Repository/ICardRepository.cs using System.Threading.Tasks; using banlistprocessor.core.Models.Db; namespace banlistprocessor.domain.Repository { public interface ICardRepository { Task<Card> CardByName(string cardName); } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/cardsectionprocessor.domain.unit.tests/StrategyTests/CardTriviaProcessorStrategyTests/HandlesTests.cs using cardsectionprocessor.core.Constants; using cardsectionprocessor.core.Service; using cardsectionprocessor.domain.Strategy; using cardsectionprocessor.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace cardsectionprocessor.domain.unit.tests.StrategyTests.CardTriviaProcessorStrategyTests { [TestFixture] [Category(TestType.Unit)] public class HandlesTests { private ICardTriviaService _cardTriviaService; private ICardService _cardService; private CardTriviaProcessorStrategy _sut; [SetUp] public void SetUp() { _cardTriviaService = Substitute.For<ICardTriviaService>(); _cardService = Substitute.For<ICardService>(); _sut = new CardTriviaProcessorStrategy(_cardService, _cardTriviaService); } [TestCase(ArticleCategory.CardTrivia)] public void Given_A_Valid_Category_Should_Return_True(string category) { // Arrange // Act var result = _sut.Handles(category); // Assert result.Should().BeTrue(); } [TestCase("category")] public void Given_A_Valid_Category_Should_Return_False(string category) { // Arrange // Act var result = _sut.Handles(category); // Assert result.Should().BeFalse(); } } }<file_sep>/src/wikia/article/src/Core/article.core/Models/ArticleTaskResult.cs using article.core.Exceptions; using wikia.Models.Article.AlphabeticalList; namespace article.core.Models { public class ArticleTaskResult { public bool IsSuccessfullyProcessed { get; set; } public UnexpandedArticle Article { get; set; } public ArticleException Failed { get; set; } } }<file_sep>/src/wikia/data/carddata/src/Domain/carddata.domain/WebPages/IHtmlWebPage.cs using System; using HtmlAgilityPack; namespace carddata.domain.WebPages { public interface IHtmlWebPage { HtmlDocument Load(string webPageUrl); HtmlDocument Load(Uri webPageUrl); } }<file_sep>/src/wikia/data/archetypedata/src/Domain/archetypedata.domain/WebPages/IArchetypeWebPage.cs using System; using System.Collections.Generic; using System.Threading.Tasks; using HtmlAgilityPack; using wikia.Models.Article.Details; namespace archetypedata.domain.WebPages { public interface IArchetypeWebPage { IEnumerable<string> Cards(Uri archetypeUrl); string GetFurtherResultsUrl(HtmlDocument archetypeWebPage); List<string> CardsFromFurtherResultsUrl(string furtherResultsUrl); Task<string> ArchetypeThumbnail(long articleId, string archetypeWebPageUrl); string ArchetypeThumbnail(KeyValuePair<string, ExpandedArticle> articleDetails, string archetypeWebPageUrl); string ArchetypeThumbnail(string thumbNailUrl, string archetypeWebPageUrl); } }<file_sep>/src/wikia/processor/cardprocessor/src/Infrastructure/cardprocessor.infrastructure/Repository/AttributeRepository.cs using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using cardprocessor.domain.Repository; using cardprocessor.infrastructure.Database; using Microsoft.EntityFrameworkCore; using Attribute = cardprocessor.core.Models.Db.Attribute; namespace cardprocessor.infrastructure.Repository { public class AttributeRepository : IAttributeRepository { private readonly YgoDbContext _dbContext; public AttributeRepository(YgoDbContext dbContext) { _dbContext = dbContext; } public Task<List<Attribute>> AllAttributes() { return _dbContext.Attribute.OrderBy(c => c.Name).ToListAsync(); } } }<file_sep>/src/wikia/article/src/Application/article.application/Decorators/Loggers/ArticleProcessorLoggerDecorator.cs using System; using article.core.ArticleList.Processor; using article.core.Models; using article.domain.ArticleList.Processor; using Microsoft.Extensions.Logging; using System.Threading.Tasks; using wikia.Models.Article.AlphabeticalList; namespace article.application.Decorators.Loggers { public class ArticleProcessorLoggerDecorator : IArticleProcessor { private readonly IArticleProcessor _articleProcessor; private readonly ILogger<ArticleProcessor> _logger; public ArticleProcessorLoggerDecorator(IArticleProcessor articleProcessor, ILogger<ArticleProcessor> logger) { _articleProcessor = articleProcessor; _logger = logger; } public async Task<ArticleTaskResult> Process(string category, UnexpandedArticle article) { try { _logger.LogInformation("Processing article '{@Title}', category '{@Category}'", article.Title ?? article.Id.ToString(), category); var articleResult = await _articleProcessor.Process(category, article); _logger.LogInformation("Finished processing article '{@Title}', category '{@Category}'", article.Title ?? article.Id.ToString(), category); articleResult.IsSuccessfullyProcessed = true; return articleResult; } catch (ArgumentNullException ex) { _logger.LogError("Error processing article '{@Title}', category '{@Category}'. ArgumentNullException: {@Exception}", article.Title, category, ex); throw; } catch (InvalidOperationException ex) { _logger.LogError("Error processing article '{@Title}', category '{@Category}'. InvalidOperationException, IArticleItemProcessor not found: {@Exception}", article.Title, category, ex); throw; } } } }<file_sep>/src/wikia/article/src/Presentation/article.latestbanlists/Program.cs using article.application; using article.application.Configuration; using article.infrastructure; using article.latestbanlists.QuartzConfiguration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Quartz; using Serilog; using System; using article.domain.Settings; namespace article.latestbanlists { internal class Program { internal static void Main(string[] args) { try { CreateHostBuilder(args).Build().Run(); } catch (Exception ex) { if (Log.Logger == null || Log.Logger.GetType().Name == "SilentLogger") { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Console() .CreateLogger(); } Log.Fatal(ex, "Host terminated unexpectedly"); throw; } finally { Log.CloseAndFlush(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { // Add the required Quartz.NET services services.AddQuartz(q => { // Use a Scoped container to create jobs q.UseMicrosoftDependencyInjectionScopedJobFactory(); // Register the job, loading the schedule from configuration q.AddJobAndTrigger<BanlistInformationJob>(hostContext.Configuration); }); // Add the Quartz.NET hosted service services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true); services.AddLogging(); //configuration settings services.Configure<AppSettings>(hostContext.Configuration.GetSection(nameof(AppSettings))); services.Configure<RabbitMqSettings>(hostContext.Configuration.GetSection(nameof(RabbitMqSettings))); services.AddApplicationServices(); services.AddInfrastructureServices(); }) .UseSerilog((hostingContext, loggerConfiguration) => { loggerConfiguration .ReadFrom.Configuration(hostingContext.Configuration) .Enrich.WithProperty("ApplicationName", typeof(Program).Assembly.GetName().Name) .Enrich.WithProperty("Environment", hostingContext.HostingEnvironment); }); } } <file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/ApplicationInstaller.cs using System.Reflection; using AutoMapper; using cardprocessor.application.Commands; using cardprocessor.application.Commands.DownloadImage; using cardprocessor.application.Mappings.Mappers; using cardprocessor.application.Models.Cards.Input; using cardprocessor.application.Validations.Cards; using cardprocessor.core.Services; using cardprocessor.core.Services.Messaging.Cards; using cardprocessor.core.Strategies; using cardprocessor.domain.Services; using cardprocessor.domain.Services.Messaging.Cards; using cardprocessor.domain.Strategies; using FluentValidation; using MediatR; using Microsoft.Extensions.DependencyInjection; namespace cardprocessor.application { public static class ApplicationInstaller { public static IServiceCollection AddApplicationServices(this IServiceCollection services) { services .AddCqrs() .AddValidation() .AddDomainServices() .AddStrategies() .AddAutoMapper(); return services; } private static IServiceCollection AddCqrs(this IServiceCollection services) { services.AddMediatR(typeof(ApplicationInstaller).GetTypeInfo().Assembly); return services; } private static IServiceCollection AddDomainServices(this IServiceCollection services) { services.AddTransient<ICardService, CardService>(); services.AddTransient<ICategoryService, CategoryService>(); services.AddTransient<IAttributeService, AttributeService>(); services.AddTransient<ILimitService, LimitService>(); services.AddTransient<ILinkArrowService, LinkArrowService>(); services.AddTransient<ISubCategoryService, SubCategoryService>(); services.AddTransient<ITypeService, TypeService>(); services.AddTransient<IFileSystemService, FileSystemService>(); services.AddTransient<ICardCommandMapper, CardCommandMapper>(); services.AddTransient<ICardImageQueueService, CardImageQueueService>(); return services; } private static IServiceCollection AddValidation(this IServiceCollection services) { services.AddTransient<IValidator<CardInputModel>, CardValidator>(); services.AddTransient<IValidator<DownloadImageCommand>, DownloadImageCommandValidator>(); return services; } public static IServiceCollection AddStrategies(this IServiceCollection services) { services.AddTransient<ICardTypeStrategy, MonsterCardTypeStrategy>(); services.AddTransient<ICardTypeStrategy, SpellCardTypeStrategy>(); services.AddTransient<ICardTypeStrategy, TrapCardTypeStrategy>(); return services; } } }<file_sep>/src/wikia/data/banlistdata/src/Presentation/banlistdata/Services/BanlistDataHostedService.cs using System; using System.Text; using System.Threading; using System.Threading.Tasks; using banlistdata.application.Configuration; using banlistdata.application.MessageConsumers.BanlistInformation; using MediatR; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using RabbitMQ.Client; using RabbitMQ.Client.Events; using Serilog; using Serilog.Events; using Serilog.Formatting.Json; namespace banlistdata.Services { public class BanlistDataHostedService : BackgroundService { private const string BanlistArticleQueue = "banlist-article"; public IServiceProvider Services { get; } private readonly IOptions<RabbitMqSettings> _rabbitMqOptions; private readonly IOptions<AppSettings> _appSettingsOptions; private readonly IMediator _mediator; private ConnectionFactory _factory; private IConnection _connection; private IModel _banlistArticleChannel; private EventingBasicConsumer _banlistArticleConsumer; public BanlistDataHostedService ( IServiceProvider services, IOptions<RabbitMqSettings> rabbitMqOptions, IOptions<AppSettings> appSettingsOptions, IMediator mediator ) { Services = services; _rabbitMqOptions = rabbitMqOptions; _appSettingsOptions = appSettingsOptions; _mediator = mediator; ConfigureSerilog(); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { await StartConsumer(); } #region private helper private Task StartConsumer() { _factory = new ConnectionFactory() { HostName = _rabbitMqOptions.Value.Host }; _connection = _factory.CreateConnection(); _banlistArticleConsumer = CreateCardArticleConsumer(_connection); return Task.CompletedTask; } private EventingBasicConsumer CreateCardArticleConsumer(IConnection connection) { _banlistArticleChannel = connection.CreateModel(); _banlistArticleChannel.BasicQos(0, 20, false); var consumer = new EventingBasicConsumer(_banlistArticleChannel); consumer.Received += async (model, ea) => { try { var body = ea.Body; var message = Encoding.UTF8.GetString(body); var result = await _mediator.Send(new BanlistInformationConsumer { Message = message }); if (result.IsSuccessful) { _banlistArticleChannel.BasicAck(ea.DeliveryTag, false); } else { _banlistArticleChannel.BasicNack(ea.DeliveryTag, false, false); } } catch (Exception ex) { Log.Logger.Error("RabbitMq Consumer: " + BanlistArticleQueue + " exception. Exception: {@Exception}", ex); } }; consumer.Shutdown += OnCardArticleConsumerShutdown; consumer.Registered += OnCardArticleConsumerRegistered; consumer.Unregistered += OnCardArticleConsumerUnregistered; consumer.ConsumerCancelled += OnCardArticleConsumerCancelled; _banlistArticleChannel.BasicConsume(queue: BanlistArticleQueue, autoAck: false, consumer: consumer); return consumer; } public override void Dispose() { _banlistArticleChannel.Close(); _connection.Close(); base.Dispose(); } private static void OnCardArticleConsumerCancelled(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{BanlistArticleQueue}' Cancelled"); } private static void OnCardArticleConsumerUnregistered(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{BanlistArticleQueue}' Unregistered");} private static void OnCardArticleConsumerRegistered(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{BanlistArticleQueue}' Registered"); } private static void OnCardArticleConsumerShutdown(object sender, ShutdownEventArgs e) { Log.Logger.Information($"Consumer '{BanlistArticleQueue}' Shutdown"); } private void ConfigureSerilog() { // Create the logger Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Console() .WriteTo.File(new JsonFormatter(renderMessage: true), (_appSettingsOptions.Value.LogFolder + $@"/banlistdata.{Environment.MachineName}.txt"), fileSizeLimitBytes: 100000000, rollOnFileSizeLimit: true, rollingInterval: RollingInterval.Day) .CreateLogger(); } #endregion } } <file_sep>/src/wikia/data/cardsectiondata/src/Domain/cardsectiondata.domain/WebPages/ITipRelatedCardList.cs using System.Collections.Generic; using HtmlAgilityPack; namespace cardsectiondata.domain.WebPages { public interface ITipRelatedCardList { List<string> ExtractCardsFromTable(HtmlNode table); } }<file_sep>/src/wikia/data/archetypedata/src/Application/archetypedata.application/MessageConsumers/ArchetypeInformation/ArchetypeInformationConsumerHandler.cs using System.Linq; using System.Threading; using System.Threading.Tasks; using archetypedata.core.Models; using archetypedata.core.Processor; using FluentValidation; using MediatR; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace archetypedata.application.MessageConsumers.ArchetypeInformation { public class ArchetypeInformationConsumerHandler : IRequestHandler<ArchetypeInformationConsumer, ArchetypeInformationConsumerResult> { private readonly IArchetypeProcessor _archetypeProcessor; private readonly IValidator<ArchetypeInformationConsumer> _validator; private readonly ILogger<ArchetypeInformationConsumerHandler> _logger; public ArchetypeInformationConsumerHandler(IArchetypeProcessor archetypeProcessor, IValidator<ArchetypeInformationConsumer> validator, ILogger<ArchetypeInformationConsumerHandler> logger) { _archetypeProcessor = archetypeProcessor; _validator = validator; _logger = logger; } public async Task<ArchetypeInformationConsumerResult> Handle(ArchetypeInformationConsumer request, CancellationToken cancellationToken) { var archetypeInformationConsumerResult = new ArchetypeInformationConsumerResult(); try { var validationResults = _validator.Validate(request); if (validationResults.IsValid) { var archetypeArticle = JsonConvert.DeserializeObject<Article>(request.Message); _logger.LogInformation("Processing archetype '{@Title}'", archetypeArticle.Title); var results = await _archetypeProcessor.Process(archetypeArticle); _logger.LogInformation("Finished processing archetype '{@Title}'", archetypeArticle.Title); if (!results.IsSuccessful) { archetypeInformationConsumerResult.Errors.AddRange(results.Errors); } } else { archetypeInformationConsumerResult.Errors = validationResults.Errors.Select(err => err.ErrorMessage).ToList(); } } catch (System.Exception ex) { archetypeInformationConsumerResult.Errors.Add(ex.Message); var archetypeArticle = JsonConvert.DeserializeObject<Article>(request.Message); _logger.LogError("Processing archetype '{Archetype}' '{Exception}'", archetypeArticle); } return archetypeInformationConsumerResult; } } }<file_sep>/src/wikia/processor/cardprocessor/src/Core/cardprocessor.core/Services/ICardService.cs using System.Threading.Tasks; using cardprocessor.core.Models; using cardprocessor.core.Models.Db; namespace cardprocessor.core.Services { public interface ICardService { Task<Card> Add(CardModel cardModel); Task<Card> Update(CardModel cardModel); Task<Card> CardById(long cardId); Task<Card> CardByName(string name); Task<bool> CardExists(long id); } }<file_sep>/src/wikia/processor/cardprocessor/src/Tests/Unit/cardprocessor.domain.unit.tests/ServiceTests/MessagingTests/CardsTests/CardImageQueueServiceTests.cs using System.Threading.Tasks; using cardprocessor.core.Models; using cardprocessor.domain.Queues.Cards; using cardprocessor.domain.Services.Messaging.Cards; using cardprocessor.tests.core; using NSubstitute; using NUnit.Framework; namespace cardprocessor.domain.unit.tests.ServiceTests.MessagingTests.CardsTests { [TestFixture] [Category(TestType.Unit)] public class CardImageQueueServiceTests { private ICardImageQueue _cardImageQueue; private CardImageQueueService _sut; [SetUp] public void SetUp() { _cardImageQueue = Substitute.For<ICardImageQueue>(); _sut = new CardImageQueueService(_cardImageQueue); } [Test] public async Task Given_A_DownloadImage_Should_Execute_Publish_Method() { // Arrange const int expected = 1; var downloadImage = new DownloadImage(); // Act await _sut.Publish(downloadImage); // Assert await _cardImageQueue.Received(expected).Publish(Arg.Is(downloadImage)); } } }<file_sep>/src/wikia/semanticsearch/src/Core/semanticsearch.core/Search/ISemanticSearchProcessor.cs using System.Threading.Tasks; using semanticsearch.core.Model; namespace semanticsearch.core.Search { public interface ISemanticSearchProcessor { Task<SemanticSearchCardTaskResult> ProcessUrl(string url); } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Core/archetypeprocessor.core/Services/IArchetypeService.cs using System.Threading.Tasks; using archetypeprocessor.core.Models.Db; namespace archetypeprocessor.core.Services { public interface IArchetypeService { Task<Archetype> ArchetypeByName(string name); Task<Archetype> ArchetypeById(long id); Task<Archetype> Add(Archetype archetype); Task<Archetype> Update(Archetype archetype); } }<file_sep>/src/wikia/article/src/Tests/Unit/article.domain.unit.tests/BanlistUrlDataSourceTests.cs using article.core.Enums; using article.domain.Banlist.DataSource; using article.domain.WebPages; using article.domain.WebPages.Banlists; using article.tests.core; using FluentAssertions; using HtmlAgilityPack; using NSubstitute; using NUnit.Framework; using System; using System.Collections.Generic; namespace article.domain.unit.tests { [TestFixture] [Category(TestType.Unit)] public class BanlistUrlDataSourceTests { private IBanlistWebPage _banlistWebPage; private IHtmlWebPage _htmlWebPage; private BanlistUrlDataSource _sut; [SetUp] public void SetUp() { _banlistWebPage = Substitute.For<IBanlistWebPage>(); _htmlWebPage = Substitute.For<IHtmlWebPage>(); _sut = new BanlistUrlDataSource(_banlistWebPage, _htmlWebPage); } [Test] public void Given_BanlistType_And_A_BanlistUrl_Should_Return_All_Banlists_GroupedBy_Year() { // Arrange var banlistType = BanlistType.Tcg; var banlistUrl = "http://www.youtube.com"; _banlistWebPage .GetBanlistUrlList(Arg.Any<BanlistType>(), Arg.Any<string>()) .Returns(new Dictionary<string, List<Uri>> { ["2017"] = new List<Uri> { new Uri("http://www.youtube.com") } }); var htmlDocument = new HtmlDocument(); htmlDocument.DocumentNode.InnerHtml = "\"<script>wgArticleId=296,</script>\""; _htmlWebPage.Load(Arg.Any<Uri>()).Returns(htmlDocument); // Act var result = _sut.GetBanlists(banlistType, banlistUrl); // Assert result.Should().NotBeEmpty(); } [Test] public void Given_BanlistType_And_A_BanlistUrl_Should_Invoke_GetBanlistUrlList_Method_Once() { // Arrange const int expected = 1; var banlistType = BanlistType.Tcg; var banlistUrl = "http://www.youtube.com"; _banlistWebPage .GetBanlistUrlList(Arg.Any<BanlistType>(), Arg.Any<string>()) .Returns(new Dictionary<string, List<Uri>> { ["2017"] = new List<Uri> { new Uri("http://www.youtube.com") } }); var htmlDocument = new HtmlDocument(); htmlDocument.DocumentNode.InnerHtml = "\"<script>wgArticleId=296,</script>\""; _htmlWebPage.Load(Arg.Any<Uri>()).Returns(htmlDocument); // Act _sut.GetBanlists(banlistType, banlistUrl); // Assert _banlistWebPage.Received(expected).GetBanlistUrlList(Arg.Any<BanlistType>(), Arg.Any<string>()); } [Test] public void Given_BanlistType_And_A_BanlistUrl_Should_Invoke_Load_Method_Once() { // Arrange const int expected = 2; var banlistType = BanlistType.Tcg; var banlistUrl = "http://www.youtube.com"; _banlistWebPage .GetBanlistUrlList(Arg.Any<BanlistType>(), Arg.Any<string>()) .Returns(new Dictionary<string, List<Uri>> { ["2017"] = new List<Uri> { new Uri("http://www.youtube.com") }, ["2018"] = new List<Uri> { new Uri("http://www.youtube.com") } }); var htmlDocument = new HtmlDocument(); htmlDocument.DocumentNode.InnerHtml = "\"<script>wgArticleId=296,</script>\""; _htmlWebPage.Load(Arg.Any<Uri>()).Returns(htmlDocument); // Act _sut.GetBanlists(banlistType, banlistUrl); // Assert _htmlWebPage.Received(expected).Load(Arg.Any<Uri>()); } } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Domain/archetypeprocessor.domain/Services/ArchetypeCardsService.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using archetypeprocessor.core.Models.Db; using archetypeprocessor.core.Services; using archetypeprocessor.domain.Repository; namespace archetypeprocessor.domain.Services { public sealed class ArchetypeCardsService : IArchetypeCardsService { private readonly IArchetypeCardsRepository _archetypeCardsRepository; public ArchetypeCardsService(IArchetypeCardsRepository archetypeCardsRepository) { _archetypeCardsRepository = archetypeCardsRepository; } public Task<IEnumerable<ArchetypeCard>> Update(long archetypeId, IEnumerable<string> cards) { var archetypeCards = cards.Distinct(StringComparer.CurrentCultureIgnoreCase).ToList(); return _archetypeCardsRepository.Update(archetypeId, archetypeCards); } } }<file_sep>/src/wikia/data/cardsectiondata/src/Domain/cardsectiondata.domain/Services/Messaging/IQueue.cs using System.Threading.Tasks; using cardsectiondata.core.Models; namespace cardsectiondata.domain.Services.Messaging { public interface IQueue { Task Publish(CardSectionMessage message); bool Handles(string category); } }<file_sep>/src/wikia/processor/banlistprocessor/src/Infrastructure/banlistprocessor.infrastructure/Database/IYgoDbContext.cs using banlistprocessor.core.Models.Db; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; namespace banlistprocessor.infrastructure.Database { public interface IYgoDbContext { DbSet<Category> Category { get; set; } DatabaseFacade Database { get; } int SaveChanges(); } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Application/cardsectionprocessor.application/MessageConsumers/CardInformation/CardInformationConsumerValidator.cs using FluentValidation; namespace cardsectionprocessor.application.MessageConsumers.CardInformation { public class CardInformationConsumerValidator : AbstractValidator<CardInformationConsumer> { public CardInformationConsumerValidator() { RuleFor(ci => ci.Category) .NotNull() .NotEmpty(); RuleFor(ci => ci.Message) .NotNull() .NotEmpty(); } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Core/cardsectionprocessor.core/Service/ICardTipService.cs using System.Collections.Generic; using System.Threading.Tasks; using cardsectionprocessor.core.Models.Db; namespace cardsectionprocessor.core.Service { public interface ICardTipService { Task DeleteByCardId(long id); Task Update(List<TipSection> tips); } }<file_sep>/src/wikia/semanticsearch/src/Application/semanticsearch.application/ScheduledTasks/CardSearch/SemanticSearchCardTask.cs using MediatR; namespace semanticsearch.application.ScheduledTasks.CardSearch { public class SemanticSearchCardTask : IRequest<SemanticSearchCardTaskResult> { } }<file_sep>/src/wikia/processor/banlistprocessor/src/Tests/Unit/banlistprocessor.application.unit.tests/BanlistDataConsumerHandlerTests.cs using System; using System.Threading; using System.Threading.Tasks; using banlistprocessor.application.MessageConsumers.BanlistData; using banlistprocessor.core.Models; using banlistprocessor.core.Models.Db; using banlistprocessor.core.Services; using banlistprocessor.tests.core; using FluentAssertions; using Microsoft.Extensions.Logging; using NSubstitute; using NUnit.Framework; namespace banlistprocessor.application.unit.tests { [TestFixture] [Category(TestType.Unit)] public class BanlistDataConsumerHandlerTests { private IBanlistService _banlistService; private BanlistDataConsumerHandler _sut; private ILogger<BanlistDataConsumerHandler> _logger; [SetUp] public void SetUp() { _banlistService = Substitute.For<IBanlistService>(); _logger = Substitute.For<ILogger<BanlistDataConsumerHandler>>(); _sut = new BanlistDataConsumerHandler(_banlistService, _logger); } [Test] public async Task Given_An_Invalid_Should_Invoke_LogError_Method_Once() { // Arrange // Act await _sut.Handle(new BanlistDataConsumer(), CancellationToken.None); // Assert _logger.Received().Log(Arg.Any<LogLevel>(), Arg.Any<EventId>(), Arg.Any<object>(), Arg.Any<Exception>(), Arg.Any<Func<object, Exception, string>>()); } [Test] public async Task Given_A_Valid_Message_Banlist_Property_Should_Not_Be_Null() { // Arrange var banlistDataConsumer = new BanlistDataConsumer { Message = "{\"ArticleId\":642752,\"Title\":\"April 2000 Lists\",\"BanlistType\":\"Ocg\",\"StartDate\":\"2000-04-01T00:00:00\",\"Sections\":[{\"Title\":\"April 2000 Lists\",\"Content\":[]},{\"Title\":\"Full Lists\",\"Content\":[]},{\"Title\":\"Limited\",\"Content\":[\"Change of Heart\",\"Dark Hole\",\"Exodia the Forbidden One\",\"Last Will\",\"Left Arm of the Forbidden One\",\"Left Leg of the Forbidden One\",\"Mirror Force\",\"Pot of Greed\",\"Raigeki\",\"Right Arm of the Forbidden One\",\"Right Leg of the Forbidden One\"]},{\"Title\":\"Semi-Limited\",\"Content\":[\"Graceful Charity\",\"Harpie's Feather Duster\",\"Monster Reborn\"]}]}" }; _banlistService.Add(Arg.Any<YugiohBanlist>()).Returns(new Banlist()); // Act var result = await _sut.Handle(banlistDataConsumer, CancellationToken.None); // Assert result.YugiohBanlist.Should().NotBeNull(); } [Test] public async Task Given_A_Valid_Message_BanlistExist_Method_Should_Invoke_Once() { // Arrange const int expected = 1; var banlistDataConsumer = new BanlistDataConsumer { Message = "{\"ArticleId\":642752,\"Title\":\"April 2000 Lists\",\"BanlistType\":\"Ocg\",\"StartDate\":\"2000-04-01T00:00:00\",\"Sections\":[{\"Title\":\"April 2000 Lists\",\"Content\":[]},{\"Title\":\"Full Lists\",\"Content\":[]},{\"Title\":\"Limited\",\"Content\":[\"Change of Heart\",\"Dark Hole\",\"Exodia the Forbidden One\",\"Last Will\",\"Left Arm of the Forbidden One\",\"Left Leg of the Forbidden One\",\"Mirror Force\",\"Pot of Greed\",\"Raigeki\",\"Right Arm of the Forbidden One\",\"Right Leg of the Forbidden One\"]},{\"Title\":\"Semi-Limited\",\"Content\":[\"Graceful Charity\",\"Harpie's Feather Duster\",\"Monster Reborn\"]}]}" }; _banlistService.Add(Arg.Any<YugiohBanlist>()).Returns(new Banlist()); // Act await _sut.Handle(banlistDataConsumer, CancellationToken.None); // Assert await _banlistService.Received(expected).BanlistExist(Arg.Any<int>()); } [Test] public async Task Given_A_Valid_Message_If_Banlist_Exists_Should_Invoke_Add_Method_Once() { // Arrange const int expected = 1; var banlistDataConsumer = new BanlistDataConsumer { Message = "{\"ArticleId\":642752,\"Title\":\"April 2000 Lists\",\"BanlistType\":\"Ocg\",\"StartDate\":\"2000-04-01T00:00:00\",\"Sections\":[{\"Title\":\"April 2000 Lists\",\"Content\":[]},{\"Title\":\"Full Lists\",\"Content\":[]},{\"Title\":\"Limited\",\"Content\":[\"Change of Heart\",\"Dark Hole\",\"Exodia the Forbidden One\",\"Last Will\",\"Left Arm of the Forbidden One\",\"Left Leg of the Forbidden One\",\"Mirror Force\",\"Pot of Greed\",\"Raigeki\",\"Right Arm of the Forbidden One\",\"Right Leg of the Forbidden One\"]},{\"Title\":\"Semi-Limited\",\"Content\":[\"Graceful Charity\",\"Harpie's Feather Duster\",\"Monster Reborn\"]}]}" }; _banlistService.BanlistExist(Arg.Any<int>()).Returns(false); _banlistService.Add(Arg.Any<YugiohBanlist>()).Returns(new Banlist()); // Act await _sut.Handle(banlistDataConsumer, CancellationToken.None); // Assert await _banlistService.Received(expected).Add(Arg.Any<YugiohBanlist>()); } [Test] public async Task Given_A_Valid_Message_If_Banlist_Does_Not_Exists_Should_Invoke_Update_Method_Once() { // Arrange const int expected = 1; var banlistDataConsumer = new BanlistDataConsumer { Message = "{\"ArticleId\":642752,\"Title\":\"April 2000 Lists\",\"BanlistType\":\"Ocg\",\"StartDate\":\"2000-04-01T00:00:00\",\"Sections\":[{\"Title\":\"April 2000 Lists\",\"Content\":[]},{\"Title\":\"Full Lists\",\"Content\":[]},{\"Title\":\"Limited\",\"Content\":[\"Change of Heart\",\"Dark Hole\",\"Exodia the Forbidden One\",\"Last Will\",\"Left Arm of the Forbidden One\",\"Left Leg of the Forbidden One\",\"Mirror Force\",\"Pot of Greed\",\"Raigeki\",\"Right Arm of the Forbidden One\",\"Right Leg of the Forbidden One\"]},{\"Title\":\"Semi-Limited\",\"Content\":[\"Graceful Charity\",\"Harpie's Feather Duster\",\"Monster Reborn\"]}]}" }; _banlistService.BanlistExist(Arg.Any<int>()).Returns(true); _banlistService.Update(Arg.Any<YugiohBanlist>()).Returns(new Banlist()); // Act await _sut.Handle(banlistDataConsumer, CancellationToken.None); // Assert await _banlistService.Received(expected).Update(Arg.Any<YugiohBanlist>()); } } } <file_sep>/src/wikia/processor/cardprocessor/src/Tests/Unit/cardprocessor.domain.unit.tests/StrategiesTests/SpellCardTypeStrategyTests/AddTests.cs using System.Threading.Tasks; using cardprocessor.core.Models; using cardprocessor.core.Models.Db; using cardprocessor.domain.Repository; using cardprocessor.domain.Strategies; using cardprocessor.tests.core; using NSubstitute; using NUnit.Framework; namespace cardprocessor.domain.unit.tests.StrategiesTests.SpellCardTypeStrategyTests { [TestFixture] [Category(TestType.Unit)] public class AddTests { private ICardRepository _cardRepository; private SpellCardTypeStrategy _sut; [SetUp] public void SetUp() { _cardRepository = Substitute.For<ICardRepository>(); _sut = new SpellCardTypeStrategy(_cardRepository); } [Test] public async Task Given_A_CardModel_Should_Execute_Add_Method_Once() { // Arrange const int expected = 1; var cardModel = new CardModel(); // Act await _sut.Add(cardModel); // Assert await _cardRepository.Received(expected).Add(Arg.Any<Card>()); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Tests/Unit/cardprocessor.domain.unit.tests/ServiceTests/CardServiceTests/CardByIdTests.cs using System.Collections.Generic; using System.Threading.Tasks; using cardprocessor.core.Models.Db; using cardprocessor.core.Strategies; using cardprocessor.domain.Repository; using cardprocessor.domain.Services; using cardprocessor.tests.core; using NSubstitute; using NUnit.Framework; namespace cardprocessor.domain.unit.tests.ServiceTests.CardServiceTests { [TestFixture] [Category(TestType.Unit)] public class CardByIdTests { private IEnumerable<ICardTypeStrategy> _cardTypeStrategies; private ICardRepository _cardRepository; private CardService _sut; [SetUp] public void SetUp() { _cardTypeStrategies = Substitute.For<IEnumerable<ICardTypeStrategy>>(); _cardRepository = Substitute.For<ICardRepository>(); _sut = new CardService(_cardTypeStrategies, _cardRepository); } [Test] public async Task Given_A_Card_Id_Should_Invoke_CardById_Method_Once() { // Arrange const long cardId = 4322; _cardRepository.CardById(Arg.Any<long>()).Returns(new Card()); // Act await _sut.CardById(cardId); // Assert await _cardRepository.Received(1).CardById(Arg.Is(cardId)); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Domain/cardprocessor.domain/Services/Messaging/Cards/CardImageQueueService.cs using System.Threading.Tasks; using cardprocessor.core.Models; using cardprocessor.core.Services.Messaging.Cards; using cardprocessor.domain.Queues.Cards; namespace cardprocessor.domain.Services.Messaging.Cards { public class CardImageQueueService : ICardImageQueueService { private readonly ICardImageQueue _cardImageQueue; public CardImageQueueService(ICardImageQueue cardImageQueue) { _cardImageQueue = cardImageQueue; } public Task<CardImageCompletion> Publish(DownloadImage downloadImage) { return _cardImageQueue.Publish(downloadImage); } } }<file_sep>/src/wikia/semanticsearch/src/Tests/Unit/semanticsearch.application.unit.tests/ScheduledTasksTests/CardSearchTests/SemanticSearchCardTaskHandlerTests.cs using FluentAssertions; using Microsoft.Extensions.Options; using NSubstitute; using NUnit.Framework; using semanticsearch.application.Configuration; using semanticsearch.application.ScheduledTasks.CardSearch; using semanticsearch.core.Search; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using semanticsearch.tests.core; namespace semanticsearch.application.unit.tests.ScheduledTasksTests.CardSearchTests { [TestFixture] [Category(TestType.Unit)] public class SemanticSearchCardTaskHandlerTests { private IOptions<AppSettings> _appSettingsOptions; private ISemanticSearchProcessor _semanticSearchProcessor; private SemanticSearchCardTaskHandler _sut; [SetUp] public void SetUp() { _appSettingsOptions = Substitute.For<IOptions<AppSettings>>(); _semanticSearchProcessor = Substitute.For<ISemanticSearchProcessor>(); _sut = new SemanticSearchCardTaskHandler ( Substitute.For<ILogger<SemanticSearchCardTaskHandler>>(), _appSettingsOptions, _semanticSearchProcessor ); } [Test] public async Task Given_A_SemanticSearchCardTask_Should_Process_It_Successfully() { // Arrange var semanticSearchCardTask = new SemanticSearchCardTask(); _appSettingsOptions.Value.Returns(new AppSettings { CardSearchUrls = new Dictionary<string, string> { ["normalmonsters"] = "https://www.youtube.com/" } }); // Act var result = await _sut.Handle(semanticSearchCardTask, CancellationToken.None); // Assert result.IsSuccessful.Should().BeTrue(); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Tests/Unit/cardprocessor.application.unit.tests/ValidatorsTests/CardsTests/MonsterCardValidatorTests.cs using System; using cardprocessor.application.Enums; using cardprocessor.application.Models.Cards.Input; using cardprocessor.application.Validations.Cards; using cardprocessor.tests.core; using FluentValidation.TestHelper; using NUnit.Framework; namespace cardprocessor.application.unit.tests.ValidatorsTests.CardsTests { [TestFixture] [Category(TestType.Unit)] public class MonsterCardValidatorTests { private MonsterCardValidator _sut; [SetUp] public void SetUp() { _sut = new MonsterCardValidator(); } [TestCase(null)] [TestCase("")] [TestCase(" ")] public void Given_An_Invalid_CardName_Validation_Should_Fail(string name) { // Arrange var inputModel = new CardInputModel{ CardType = YgoCardType.Monster, Name = name}; // Act Action act = () => _sut.ShouldHaveValidationErrorFor(c => c.Name, inputModel); // Assert act.Invoke(); } [TestCase(0)] [TestCase(-1)] [TestCase(21)] public void Given_An_Invalid_CardLevel_Validation_Should_Fail(int cardLevel) { // Arrange var inputModel = new CardInputModel{ CardType = YgoCardType.Monster, CardLevel = cardLevel}; // Act Action act = () => _sut.ShouldHaveValidationErrorFor(c => c.CardLevel, inputModel); // Assert act.Invoke(); } [TestCase(0)] [TestCase(-1)] [TestCase(21)] public void Given_An_Invalid_CardRank_Validation_Should_Fail(int cardRank) { // Arrange var inputModel = new CardInputModel{ CardType = YgoCardType.Monster, CardRank = cardRank}; // Act Action act = () => _sut.ShouldHaveValidationErrorFor(c => c.CardRank, inputModel); // Assert act.Invoke(); } [TestCase(-1)] [TestCase(21000)] public void Given_An_Invalid_Ark_Validation_Should_Fail(int atk) { // Arrange var inputModel = new CardInputModel { CardType = YgoCardType.Monster, Atk = atk}; // Act Action act = () => _sut.ShouldHaveValidationErrorFor(c => c.Atk, inputModel); // Assert act.Invoke(); } [TestCase(-1)] [TestCase(21000)] public void Given_An_Invalid_Def_Validation_Should_Fail(int def) { // Arrange var inputModel = new CardInputModel { CardType = YgoCardType.Monster, Def = def}; // Act Action act = () => _sut.ShouldHaveValidationErrorFor(c => c.Def, inputModel); // Assert act.Invoke(); } [TestCase(0)] [TestCase(-1)] public void Given_An_Invalid_Attribute_Validation_Should_Fail(int attribute) { // Arrange var inputModel = new CardInputModel { CardType = YgoCardType.Monster, AttributeId = attribute}; // Act Action act = () => _sut.ShouldHaveValidationErrorFor(c => c.AttributeId, inputModel); // Assert act.Invoke(); } [TestCase(0)] [TestCase(-1)] public void Given_An_Invalid_CardNumber_Validation_Should_Fail(int cardNumber) { // Arrange var inputModel = new CardInputModel { CardType = YgoCardType.Monster, CardNumber = cardNumber}; // Act Action act = () => _sut.ShouldHaveValidationErrorFor(c => c.CardNumber, inputModel); // Assert act.Invoke(); } [Test] public void Given_An_Invalid_SubCategoryIds_Validation_Should_Fail() { // Arrange var inputModel = new CardInputModel { CardType = YgoCardType.Monster}; // Act Action act = () => _sut.ShouldHaveValidationErrorFor(c => c.SubCategoryIds, inputModel); // Assert act.Invoke(); } } }<file_sep>/src/wikia/processor/banlistprocessor/src/Domain/banlistprocessor.domain/banlistprocessor.domain/Repository/IFormatRepository.cs using System.Threading.Tasks; using banlistprocessor.core.Models.Db; namespace banlistprocessor.domain.Repository { public interface IFormatRepository { Task<Format> FormatByAcronym(string acronym); } }<file_sep>/src/wikia/processor/cardprocessor/src/Infrastructure/cardprocessor.infrastructure/Repository/CardRepository.cs using System.Threading.Tasks; using cardprocessor.core.Models.Db; using cardprocessor.domain.Repository; using cardprocessor.infrastructure.Database; using Microsoft.EntityFrameworkCore; namespace cardprocessor.infrastructure.Repository { public class CardRepository : ICardRepository { private readonly YgoDbContext _context; public CardRepository(YgoDbContext context) { _context = context; } public Task<Card> CardByName(string name) { return _context .Card .Include(c => c.CardSubCategory) .ThenInclude(sc => sc.SubCategory) .Include(c => c.CardAttribute) .ThenInclude(ca => ca.Attribute) .Include(c => c.CardType) .ThenInclude(ct => ct.Type) .Include(c => c.CardLinkArrow) .ThenInclude(cla => cla.LinkArrow) .AsNoTracking() .SingleOrDefaultAsync(c => c.Name == name); } public async Task<Card> Add(Card newCard) { _context.Card.Add(newCard); await _context.SaveChangesAsync(); return newCard; } public Task<Card> CardById(long id) { return _context .Card .Include(c => c.CardSubCategory) .ThenInclude(sc => sc.SubCategory) .Include(c => c.CardAttribute) .ThenInclude(ca => ca.Attribute) .Include(c => c.CardType) .ThenInclude(ct => ct.Type) .Include(c => c.CardLinkArrow) .ThenInclude(cla => cla.LinkArrow) .AsNoTracking() .SingleOrDefaultAsync(s => s.Id == id); } public async Task<Card> Update(Card card) { _context.Card.Update(card); var result = await _context.SaveChangesAsync(); return card; } public Task<bool> CardExists(long id) { return _context.Card.AsNoTracking().AnyAsync(c => c.Id == id); } } }<file_sep>/src/wikia/semanticsearch/src/Tests/Unit/semanticsearch.domain.unit.tests/SemanticSearchProducerTests/ProducerTests.cs using FluentAssertions; using HtmlAgilityPack; using NSubstitute; using NUnit.Framework; using semanticsearch.core.Model; using semanticsearch.domain.Search.Producer; using semanticsearch.domain.WebPage; using semanticsearch.tests.core; using System; using System.Collections.Generic; using System.Linq; namespace semanticsearch.domain.unit.tests.SemanticSearchProducerTests { [TestFixture] [Category(TestType.Unit)] public class ProducerTests { private SemanticSearchProducer _sut; private ISemanticSearchResultsWebPage _semanticSearchResultsWebPage; private ISemanticCardSearchResultsWebPage _semanticCardSearchResultsWebPage; [SetUp] public void SetUp() { _semanticSearchResultsWebPage = Substitute.For<ISemanticSearchResultsWebPage>(); _semanticCardSearchResultsWebPage = Substitute.For<ISemanticCardSearchResultsWebPage>(); _sut = new SemanticSearchProducer(_semanticSearchResultsWebPage, _semanticCardSearchResultsWebPage); } [TestCase(null)] [TestCase("")] [TestCase(" ")] public void Given_An_Invalid_Url_Should_Throw_ArgumentException(string url) { // Arrange // Act Func<IEnumerable<SemanticCard>> act = () => _sut.Producer(url).ToArray(); // Assert act.Should().Throw<ArgumentException>(); } [Test] public void Given_A_Url_With_Only_One_Page_Should_Not_Invoke_NextPageLink() { // Arrange var tableRows = new HtmlNodeCollection(new HtmlNode(HtmlNodeType.Document, new HtmlDocument(), 0)) { new (HtmlNodeType.Element, new HtmlDocument(), 1) }; _semanticSearchResultsWebPage.Load(Arg.Any<string>()); _semanticSearchResultsWebPage.TableRows.Returns(tableRows); _semanticCardSearchResultsWebPage.Name(Arg.Any<HtmlNode>()).Returns("Card Name"); _semanticCardSearchResultsWebPage.Url(Arg.Any<HtmlNode>(), Arg.Any<Uri>()).Returns("https://www.youtube.com"); // Act _sut.Producer("https://www.youtube.com").ToArray(); // Assert _semanticSearchResultsWebPage.DidNotReceive().NextPageLink(); } [Test] public void Given_A_Url_With_2_Pages_Should_Invoke_Load_Twice() { // Arrange var tableRows = new HtmlNodeCollection(new HtmlNode(HtmlNodeType.Document, new HtmlDocument(), 0)) { new (HtmlNodeType.Element, new HtmlDocument(), 1) }; _semanticSearchResultsWebPage.Load(Arg.Any<string>()); _semanticSearchResultsWebPage.TableRows.Returns(tableRows); _semanticSearchResultsWebPage.HasNextPage.Returns(true, true, false); _semanticCardSearchResultsWebPage.Name(Arg.Any<HtmlNode>()).Returns("Card Name"); _semanticCardSearchResultsWebPage.Url(Arg.Any<HtmlNode>(), Arg.Any<Uri>()).Returns("https://www.youtube.com"); // Act _sut.Producer("https://www.youtube.com").ToArray(); // Assert _semanticSearchResultsWebPage.Received(2).Load(Arg.Any<string>()); } [Test] public void Given_A_Url_With_1_Page_Should_Invoke_Load_Once() { // Arrange var tableRows = new HtmlNodeCollection(new HtmlNode(HtmlNodeType.Document, new HtmlDocument(), 0)) { new (HtmlNodeType.Element, new HtmlDocument(), 1) }; _semanticSearchResultsWebPage.Load(Arg.Any<string>()); _semanticSearchResultsWebPage.TableRows.Returns(tableRows); _semanticSearchResultsWebPage.HasNextPage.Returns(false); _semanticCardSearchResultsWebPage.Name(Arg.Any<HtmlNode>()).Returns("Card Name"); _semanticCardSearchResultsWebPage.Url(Arg.Any<HtmlNode>(), Arg.Any<Uri>()).Returns("https://www.youtube.com"); // Act _sut.Producer("https://www.youtube.com").ToArray(); // Assert _semanticSearchResultsWebPage.Received(1).Load(Arg.Any<string>()); } [Test] public void Given_A_Url_With_Multiple_Pages_Should_Invoke_NextPageLink() { // Arrange var tableRows = new HtmlNodeCollection(new HtmlNode(HtmlNodeType.Document, new HtmlDocument(), 0)) { new (HtmlNodeType.Element, new HtmlDocument(), 1) }; _semanticSearchResultsWebPage.Load(Arg.Any<string>()); _semanticSearchResultsWebPage.TableRows.Returns(tableRows); _semanticSearchResultsWebPage.HasNextPage.Returns(true, false); _semanticCardSearchResultsWebPage.Name(Arg.Any<HtmlNode>()).Returns("Card Name"); _semanticCardSearchResultsWebPage.Url(Arg.Any<HtmlNode>(), Arg.Any<Uri>()).Returns("https://www.youtube.com"); // Act _sut.Producer("https://www.youtube.com").ToArray(); // Assert _semanticSearchResultsWebPage.Received(1).NextPageLink(); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Mappings/Mappers/CommandMapperHelper.cs using AutoMapper; using cardprocessor.application.Dto; using cardprocessor.application.Enums; using cardprocessor.core.Models.Db; using System; namespace cardprocessor.application.Mappings.Mappers { public static class CommandMapperHelper { public static object MapCardByCardType(IMapper mapper, YgoCardType cardCardType, Card cardUpdated) { switch (cardCardType) { case YgoCardType.Monster: return mapper.Map<MonsterCardDto>(cardUpdated); case YgoCardType.Spell: return mapper.Map<SpellCardDto>(cardUpdated); case YgoCardType.Trap: return mapper.Map<TrapCardDto>(cardUpdated); default: throw new ArgumentOutOfRangeException(nameof(cardCardType), cardCardType, null); } } } }<file_sep>/src/wikia/data/banlistdata/src/Infrastructure/banlistdata.infrastructure/Services/Messaging/BanlistDataQueue.cs using System; using System.Linq; using System.Threading.Tasks; using banlistdata.application.Configuration; using banlistdata.core.Models; using banlistdata.domain.Services.Messaging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using RabbitMQ.Client; namespace banlistdata.infrastructure.Services.Messaging { public class BanlistDataQueue : IBanlistDataQueue { private readonly IOptions<RabbitMqSettings> _rabbitMqConfig; public BanlistDataQueue(IOptions<RabbitMqSettings> rabbitMqConfig) { _rabbitMqConfig = rabbitMqConfig; } public Task<YugiohBanlistCompletion> Publish(ArticleProcessed articleProcessed) { var yugiohBanlistCompletion = new YugiohBanlistCompletion(); yugiohBanlistCompletion.Article = articleProcessed.Article; yugiohBanlistCompletion.Banlist = articleProcessed.Banlist; try { var messageBodyBytes = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(articleProcessed.Banlist)); var factory = new ConnectionFactory() { HostName = _rabbitMqConfig.Value.Host }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { var props = channel.CreateBasicProperties(); props.ContentType = _rabbitMqConfig.Value.ContentType; props.DeliveryMode = _rabbitMqConfig.Value.Exchanges[RabbitMqExchangeConstants.YugiohHeadersData].PersistentMode; props.Headers = _rabbitMqConfig.Value.Exchanges[RabbitMqExchangeConstants.YugiohHeadersData].Headers.ToDictionary(k => k.Key, k => (object)k.Value); channel.BasicPublish ( RabbitMqExchangeConstants.YugiohHeadersData, "", props, messageBodyBytes ); } yugiohBanlistCompletion.IsSuccessful = true; } catch (Exception ex) { Console.WriteLine(ex); throw; } return Task.FromResult(yugiohBanlistCompletion); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Mappings/Profiles/TypeProfile.cs using AutoMapper; using cardprocessor.application.Dto; using cardprocessor.core.Models.Db; namespace cardprocessor.application.Mappings.Profiles { public class TypeProfile : Profile { public TypeProfile() { CreateMap<Type, TypeDto>(); } } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Domain/archetypeprocessor.domain/Processor/ArchetypeProcessor.cs using System; using System.Threading.Tasks; using archetypeprocessor.core.Models; using archetypeprocessor.core.Models.Db; using archetypeprocessor.core.Processor; using archetypeprocessor.core.Services; using archetypeprocessor.domain.Messaging; namespace archetypeprocessor.domain.Processor { public class ArchetypeProcessor : IArchetypeProcessor { private readonly IArchetypeService _archetypeService; private readonly IArchetypeImageQueueService _archetypeImageQueueService; public ArchetypeProcessor(IArchetypeService archetypeService, IArchetypeImageQueueService archetypeImageQueueService) { _archetypeService = archetypeService; _archetypeImageQueueService = archetypeImageQueueService; } public async Task<ArchetypeDataTaskResult<ArchetypeMessage>> Process(ArchetypeMessage archetypeData) { var articleDataTaskResult = new ArchetypeDataTaskResult<ArchetypeMessage> { ArchetypeData = archetypeData }; var existingArchetype = await _archetypeService.ArchetypeById(archetypeData.Id); if (existingArchetype == null) { var newArchetype = new Archetype { Id = archetypeData.Id, Name = archetypeData.Name, Url = archetypeData.ProfileUrl, Created = DateTime.UtcNow, Updated = archetypeData.Revision }; await _archetypeService.Add(newArchetype); } else { existingArchetype.Name = archetypeData.Name; existingArchetype.Url = archetypeData.ProfileUrl; existingArchetype.Updated = archetypeData.Revision; await _archetypeService.Update(existingArchetype); } if (!string.IsNullOrWhiteSpace(archetypeData.ImageUrl)) { var downloadImage = new DownloadImage { RemoteImageUrl = new Uri(archetypeData.ImageUrl), ImageFileName = archetypeData.Id.ToString(), }; await _archetypeImageQueueService.Publish(downloadImage); } return articleDataTaskResult; } } }<file_sep>/src/services/Cards.API/src/Application/Cards.Application/Configuration/RabbitMqSettings.cs using System.Collections.Generic; namespace Cards.Application.Configuration { public record RabbitMqSettings { public string Host { get; init; } public int Port { get; init; } public string Username { get; init; } public string Password { get; init; } public string ContentType { get; init; } public Dictionary<string, ExchangeSetting> Exchanges { get; init; } public Dictionary<string, QueueSetting> Queues { get; init; } } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Mappings/Profiles/CardProfile.cs using System.IO; using AutoMapper; using cardprocessor.application.Dto; using cardprocessor.application.Models.Cards.Input; using cardprocessor.core.Models; using cardprocessor.core.Models.Db; namespace cardprocessor.application.Mappings.Profiles { public class CardProfile : Profile { public CardProfile() { CreateMap<CardInputModel, CardModel>(); CreateMap<Card, MonsterCardDto>() .ForMember(dest => dest.ImageUrl, opt => opt.MapFrom(src => $"/api/images/cards/{string.Concat(src.Name.Split(Path.GetInvalidFileNameChars()))}")); CreateMap<Card, SpellCardDto>() .ForMember(dest => dest.ImageUrl, opt => opt.MapFrom(src => $"/api/images/cards/{string.Concat(src.Name.Split(Path.GetInvalidFileNameChars()))}")); CreateMap<Card, TrapCardDto>() .ForMember(dest => dest.ImageUrl, opt => opt.MapFrom(src => $"/api/images/cards/{string.Concat(src.Name.Split(Path.GetInvalidFileNameChars()))}")); } } }<file_sep>/src/services/Cards.API/src/Presentation/Cards.API/Startup.cs using System; using System.IO; using Cards.API.Services; using Cards.Application; using Cards.Application.Configuration; using Cards.DatabaseMigration; using MediatR; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.OpenApi.Models; namespace Cards.API { public class Startup { public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { Configuration = configuration; } public void ConfigureServices(IServiceCollection services) { services.AddLogging(); services.Configure<RabbitMqSettings>(Configuration.GetSection(nameof(RabbitMqSettings))); services.AddControllers(); services.AddRouting(options => options.LowercaseUrls = true); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "CardsController API", Version = "v1" }); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{typeof(Startup).Assembly.GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); services.AddHostedService<CardProcessorHostedService>(); services.AddApplicationServices(); // Database Migrations services.AddDatabaseMigrationServices(Configuration.GetConnectionString("Db")); } public void Configure(IApplicationBuilder app) { // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Cards API V1"); c.RoutePrefix = string.Empty; }); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } } <file_sep>/src/wikia/processor/cardsectionprocessor/src/cardsectionprocessor.domain.unit.tests/StrategyTests/CardTipsProcessorStrategyTests/HandlesTests.cs using cardsectionprocessor.core.Constants; using cardsectionprocessor.core.Service; using cardsectionprocessor.domain.Strategy; using cardsectionprocessor.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace cardsectionprocessor.domain.unit.tests.StrategyTests.CardTipsProcessorStrategyTests { [TestFixture] [Category(TestType.Unit)] public class HandlesTests { private ICardTipService _cardTipService; private ICardService _cardService; private CardTipsProcessorStrategy _sut; [SetUp] public void SetUp() { _cardTipService = Substitute.For<ICardTipService>(); _cardService = Substitute.For<ICardService>(); _sut = new CardTipsProcessorStrategy(_cardService, _cardTipService); } [TestCase(ArticleCategory.CardTips)] public void Given_A_Valid_Category_Should_Return_True(string category) { // Arrange // Act var result = _sut.Handles(category); // Assert result.Should().BeTrue(); } [TestCase("category")] public void Given_A_Valid_Category_Should_Return_False(string category) { // Arrange // Act var result = _sut.Handles(category); // Assert result.Should().BeFalse(); } } }<file_sep>/src/wikia/semanticsearch/src/Domain/semanticsearch.domain/WebPage/IHtmlWebPage.cs using System; using HtmlAgilityPack; namespace semanticsearch.domain.WebPage { public interface IHtmlWebPage { HtmlDocument Load(string url); HtmlDocument Load(Uri url); } }<file_sep>/src/wikia/semanticsearch/src/Application/semanticsearch.application/ScheduledTasks/CardSearch/SemanticSearchCardTaskHandler.cs using MediatR; using Microsoft.Extensions.Options; using semanticsearch.application.Configuration; using semanticsearch.core.Search; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace semanticsearch.application.ScheduledTasks.CardSearch { public class SemanticSearchCardTaskHandler : IRequestHandler<SemanticSearchCardTask, SemanticSearchCardTaskResult> { private readonly ILogger<SemanticSearchCardTaskHandler> _logger; private readonly IOptions<AppSettings> _appSettingsOptions; private readonly ISemanticSearchProcessor _semanticSearchProcessor; public SemanticSearchCardTaskHandler ( ILogger<SemanticSearchCardTaskHandler> logger, IOptions<AppSettings> appSettingsOptions, ISemanticSearchProcessor semanticSearchProcessor ) { _logger = logger; _appSettingsOptions = appSettingsOptions; _semanticSearchProcessor = semanticSearchProcessor; } public async Task<SemanticSearchCardTaskResult> Handle(SemanticSearchCardTask request, CancellationToken cancellationToken) { var semanticSearchCardTaskResult = new SemanticSearchCardTaskResult(); foreach (var (category, url) in _appSettingsOptions.Value.CardSearchUrls) { _logger.LogInformation("Processing semantic category '{Category}'.", category); await _semanticSearchProcessor.ProcessUrl(url); _logger.LogInformation("Finished processing semantic category '{Category}'.", category); } semanticSearchCardTaskResult.IsSuccessful = true; return semanticSearchCardTaskResult; } } }<file_sep>/src/wikia/processor/cardprocessor/src/Tests/Unit/cardprocessor.domain.unit.tests/ServiceTests/CardServiceTests/CardExistsTests.cs using System.Collections.Generic; using System.Threading.Tasks; using cardprocessor.core.Strategies; using cardprocessor.domain.Repository; using cardprocessor.domain.Services; using cardprocessor.tests.core; using NSubstitute; using NUnit.Framework; namespace cardprocessor.domain.unit.tests.ServiceTests.CardServiceTests { [TestFixture] [Category(TestType.Unit)] public class CardExistsTests { private IEnumerable<ICardTypeStrategy> _cardTypeStrategies; private ICardRepository _cardRepository; private CardService _sut; [SetUp] public void SetUp() { _cardTypeStrategies = Substitute.For<IEnumerable<ICardTypeStrategy>>(); _cardRepository = Substitute.For<ICardRepository>(); _sut = new CardService(_cardTypeStrategies, _cardRepository); } [Test] public async Task Given_A_Card_Id_Should_Invoke_CardExists_Method_Once() { // Arrange const long cardId = 4322; _cardRepository.CardExists(Arg.Any<long>()).Returns(true); // Act await _sut.CardExists(cardId); // Assert await _cardRepository.Received(1).CardExists(Arg.Is(cardId)); } } }<file_sep>/src/wikia/article/src/Domain/article.domain/WebPages/Banlists/IBanlistWebPage.cs using System; using System.Collections.Generic; using article.core.Enums; using HtmlAgilityPack; namespace article.domain.WebPages.Banlists { public interface IBanlistWebPage { Dictionary<string, List<Uri>> GetBanlistUrlList(BanlistType banlistType, string banlistUrl); Dictionary<string, List<Uri>> GetBanlistUrlList(HtmlNode banlistUrlListNode); } }<file_sep>/src/wikia/data/banlistdata/src/Domain/banlistdata.domain/Processor/BanlistProcessor.cs using banlistdata.core.Models; using banlistdata.core.Processor; using banlistdata.domain.Helpers; using banlistdata.domain.Services.Messaging; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using wikia.Api; namespace banlistdata.domain.Processor { public class BanlistProcessor : IBanlistProcessor { private readonly IWikiArticle _wikiArticle; private readonly IBanlistDataQueue _banlistDataQueue; private readonly ILogger<BanlistProcessor> _logger; public BanlistProcessor(IWikiArticle wikiArticle, IBanlistDataQueue banlistDataQueue, ILogger<BanlistProcessor> logger) { _wikiArticle = wikiArticle; _banlistDataQueue = banlistDataQueue; _logger = logger; } public async Task<ArticleProcessed> Process(Article article) { var response = new ArticleProcessed { Article = article }; var articleDetailsList = await _wikiArticle.Details((int) article.Id); var (_, expandedArticle) = articleDetailsList.Items.First(); var banlistArticleSummary = BanlistHelpers.ExtractBanlistArticleDetails(expandedArticle.Id, expandedArticle.Abstract); if (banlistArticleSummary != null) { const char beginChar = '「'; const char endChar = '」'; var banlist = new YugiohBanlist { ArticleId = banlistArticleSummary.ArticleId, Title = expandedArticle.Title, BanlistType = banlistArticleSummary.BanlistType, StartDate = banlistArticleSummary.StartDate }; var banlistContentResult = await _wikiArticle.Simple(banlistArticleSummary.ArticleId); _logger.LogInformation($"{banlist.BanlistType.ToString()}, {banlist.Title}, {banlist.StartDate}"); foreach (var section in banlistContentResult.Sections) { // skip references section if (section.Title.ToLower() == "references") continue; // new section var ybls = new YugiohBanlistSection { Title = StringHelpers.RemoveBetween(section.Title, beginChar, endChar).Trim(), Content = ContentResultHelpers.GetSectionContentList(section).OrderBy(c => c).ToList() }; // remove invalid characters if (ybls.Content.Any()) ybls.Content = ybls.Content.Select(c => StringHelpers.RemoveBetween(c, beginChar, endChar)).ToList(); banlist.Sections.Add(ybls); } response.Banlist = banlist; var publishBanlistResult = await _banlistDataQueue.Publish(new ArticleProcessed{ Article = article, Banlist = banlist}); response.IsSuccessful = publishBanlistResult.IsSuccessful; } return response; } } }<file_sep>/src/wikia/article/src/Presentation/article.latestbanlists/QuartzConfiguration/BanlistInformationJob.cs using article.application.Configuration; using article.application.ScheduledTasks.LatestBanlist; using MediatR; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Quartz; using System.Threading.Tasks; using article.domain.Settings; namespace article.latestbanlists.QuartzConfiguration { public class BanlistInformationJob : IJob { private readonly IMediator _mediator; private readonly ILogger<BanlistInformationJob> _logger; private readonly IOptions<AppSettings> _options; public BanlistInformationJob(IMediator mediator, ILogger<BanlistInformationJob> logger, IOptions<AppSettings> options) { _mediator = mediator; _logger = logger; _options = options; } public async Task Execute(IJobExecutionContext context) { var result = await _mediator.Send(new BanlistInformationTask { Category = _options.Value.Category, PageSize = _options.Value.PageSize }); _logger.LogInformation("Finished processing '{Category}' category.", _options.Value.Category); if (!result.IsSuccessful) { _logger.LogInformation("Errors while processing '{Category}' category. Errors: {Errors}", _options.Value.Category, result.Errors); } } } }<file_sep>/src/wikia/processor/banlistprocessor/src/Presentation/banlistprocessor/Services/BanlistProcessorHostedService.cs using System; using System.Text; using System.Threading; using System.Threading.Tasks; using banlistprocessor.application.Configuration; using banlistprocessor.application.MessageConsumers.BanlistData; using MediatR; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using RabbitMQ.Client; using RabbitMQ.Client.Events; using Serilog; using Serilog.Events; using Serilog.Formatting.Json; namespace banlistprocessor.Services { public class BanlistProcessorHostedService : BackgroundService { private const string BanlistDataQueue = "banlist-data"; public IServiceProvider Services { get; } private readonly IOptions<RabbitMqSettings> _rabbitMqOptions; private readonly IOptions<AppSettings> _appSettingsOptions; private readonly IMediator _mediator; private ConnectionFactory _factory; private IConnection _connection; private IModel _channel; private EventingBasicConsumer _cardDataConsumer; public BanlistProcessorHostedService ( IServiceProvider services, IOptions<RabbitMqSettings> rabbitMqOptions, IOptions<AppSettings> appSettingsOptions, IMediator mediator ) { Services = services; _rabbitMqOptions = rabbitMqOptions; _appSettingsOptions = appSettingsOptions; _mediator = mediator; ConfigureSerilog(); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { await StartConsumer(); } public override void Dispose() { _connection.Close(); _channel.Close(); base.Dispose(); } private Task StartConsumer() { _factory = new ConnectionFactory() {HostName = _rabbitMqOptions.Value.Host}; _connection = _factory.CreateConnection(); _channel = _connection.CreateModel(); _channel.BasicQos(0, 1, false); _cardDataConsumer = new EventingBasicConsumer(_channel); _cardDataConsumer.Received += async (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); var result = await _mediator.Send(new BanlistDataConsumer { Message = message }); if(result.IsSuccessful) { _channel.BasicAck(ea.DeliveryTag, false); } else { _channel.BasicNack(ea.DeliveryTag, false, false); } }; _channel.BasicConsume ( queue: _rabbitMqOptions.Value.Queues[BanlistDataQueue].Name, autoAck: _rabbitMqOptions.Value.Queues[BanlistDataQueue].AutoAck, consumer: _cardDataConsumer ); return Task.CompletedTask; } private void ConfigureSerilog() { // Create the logger Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Console() .WriteTo.File(new JsonFormatter(renderMessage: true), (_appSettingsOptions.Value.LogFolder + $@"/banlistprocessor.{Environment.MachineName}.txt"), fileSizeLimitBytes: 100000000, rollOnFileSizeLimit: true, rollingInterval: RollingInterval.Day) .CreateLogger(); } } } <file_sep>/src/wikia/processor/cardsectionprocessor/src/cardsectionprocessor.application.unit.tests/CardInformationConsumerHandlerTests.cs using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using cardsectionprocessor.application.MessageConsumers.CardInformation; using cardsectionprocessor.core.Models; using cardsectionprocessor.core.Processor; using cardsectionprocessor.tests.core; using FluentAssertions; using FluentValidation; using Microsoft.Extensions.Logging; using NSubstitute; using NUnit.Framework; namespace cardsectionprocessor.application.unit.tests { [TestFixture] [Category(TestType.Unit)] public class CardInformationConsumerHandlerTests { private IValidator<CardInformationConsumer> _validator; private ICardSectionProcessor _cardSectionProcessor; private CardInformationConsumerHandler _sut; private ILogger<CardInformationConsumerHandler> _logger; [SetUp] public void SetUp() { _validator = Substitute.For<IValidator<CardInformationConsumer>>(); _cardSectionProcessor = Substitute.For<ICardSectionProcessor>(); _logger = Substitute.For<ILogger<CardInformationConsumerHandler>>(); _sut = new CardInformationConsumerHandler(_cardSectionProcessor, _validator, _logger); } [Test] public async Task Given_An_Invalid_CardInformationConsumer_IsSuccessful_Should_Be_False() { // Arrange var cardInformationConsumer = new CardInformationConsumer(); _validator.Validate(Arg.Any<CardInformationConsumer>()) .Returns(new CardInformationConsumerValidator().Validate(cardInformationConsumer)); // Act var result = await _sut.Handle(cardInformationConsumer, CancellationToken.None); // Assert result.IsSuccessful.Should().BeFalse(); } [Test] public async Task Given_An_Invalid_CardInformationConsumer_Errors_List_Should_Not_Be_Null_Or_Empty() { // Arrange var cardTipInformationConsumer = new CardInformationConsumer(); _validator.Validate(Arg.Any<CardInformationConsumer>()) .Returns(new CardInformationConsumerValidator().Validate(cardTipInformationConsumer)); // Act var result = await _sut.Handle(cardTipInformationConsumer, CancellationToken.None); // Assert result.Errors.Should().NotBeNullOrEmpty(); } [Test] public async Task Given_A_Valid_CardInformationConsumer_IsSuccessful_Should_Be_True() { // Arrange var cardInformationConsumer = new CardInformationConsumer { Category = "category", Message = "{\"Id\":703544,\"CorrelationId\":\"3e2bf3ca-d903-440c-8cd5-be61c95ae1fc\",\"Title\":\"Tenyi\",\"Url\":\"https://yugioh.fandom.com/wiki/Card_Tips:Tenyi\"}" }; _validator.Validate(Arg.Any<CardInformationConsumer>()) .Returns(new CardInformationConsumerValidator().Validate(cardInformationConsumer)); _cardSectionProcessor.Process(Arg.Any<string>(), Arg.Any<CardSectionMessage>()).Returns(new CardSectionDataTaskResult<CardSectionMessage>()); // Act var result = await _sut.Handle(cardInformationConsumer, CancellationToken.None); // Assert result.IsSuccessful.Should().BeTrue(); } [Test] public async Task Given_A_Valid_CardInformationConsumer_Should_Execute_Process_Method_Once() { // Arrange var cardInformationConsumer = new CardInformationConsumer { Category = "category", Message = "{\"Id\":703544,\"CorrelationId\":\"3e2bf3ca-d903-440c-8cd5-be61c95ae1fc\",\"Title\":\"Tenyi\",\"Url\":\"https://yugioh.fandom.com/wiki/Card_Tips:Tenyi\"}" }; _validator.Validate(Arg.Any<CardInformationConsumer>()) .Returns(new CardInformationConsumerValidator().Validate(cardInformationConsumer)); _cardSectionProcessor.Process(Arg.Any<string>(), Arg.Any<CardSectionMessage>()).Returns(new CardSectionDataTaskResult<CardSectionMessage>()); // Act await _sut.Handle(cardInformationConsumer, CancellationToken.None); // Assert await _cardSectionProcessor.Received(1).Process(Arg.Any<string>(), Arg.Any<CardSectionMessage>()); } [Test] public async Task Given_A_Valid_CardInformationConsumer_If_Not_Processed_Successfully_Errors_Should_Not_Be_Null_Or_Empty() { // Arrange var cardInformationConsumer = new CardInformationConsumer { Category = "category", Message = "{\"Id\":703544,\"CorrelationId\":\"3e2bf3ca-d903-440c-8cd5-be61c95ae1fc\",\"Title\":\"Tenyi\",\"Url\":\"https://yugioh.fandom.com/wiki/Card_Tips:Tenyi\"}" }; _validator.Validate(Arg.Any<CardInformationConsumer>()) .Returns(new CardInformationConsumerValidator().Validate(cardInformationConsumer)); _cardSectionProcessor.Process(Arg.Any<string>(), Arg.Any<CardSectionMessage>()).Returns(new CardSectionDataTaskResult<CardSectionMessage> { Errors = new List<string> { "Something went horribly wrong" } }); // Act var result = await _sut.Handle(cardInformationConsumer, CancellationToken.None); // Assert result.Errors.Should().NotBeNullOrEmpty(); } } }<file_sep>/src/services/Cards.API/src/Application/Cards.Application/Configuration/QueueSetting.cs namespace Cards.Application.Configuration { public record QueueSetting { public string Name { get; init; } public bool AutoAck { get; init; } } }<file_sep>/src/wikia/data/carddata/src/Core/carddata.core/Exceptions/YugiohCardException.cs using System; using carddata.core.Models; namespace carddata.core.Exceptions { public class YugiohCardException { public YugiohCard Card { get; set; } public Exception Exception { get; set; } } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Helpers/Cards/MonsterCardHelper.cs using cardprocessor.application.Models.Cards.Input; using cardprocessor.core.Models; using cardprocessor.core.Models.Db; using System; using System.Collections.Generic; using System.Linq; using Attribute = cardprocessor.core.Models.Db.Attribute; using Type = cardprocessor.core.Models.Db.Type; namespace cardprocessor.application.Helpers.Cards { public class MonsterCardHelper { public static List<int> MonsterLinkArrowIds(YugiohCard yugiohCard, ICollection<LinkArrow> linkArrows) { return linkArrows .Where(mla => yugiohCard.MonsterLinkArrows.Any(ymla => ymla.Equals(mla.Name, StringComparison.OrdinalIgnoreCase))) .Select(la => (int)la.Id) .ToList(); } public static List<int> MonsterTypeIds(YugiohCard yugiohCard, ICollection<Type> types) { return types .Where(mt => yugiohCard.MonsterSubCategoriesAndTypes.Any(yt => yt.Equals(mt.Name, StringComparison.OrdinalIgnoreCase))) .Select(smt => (int)smt.Id) .ToList(); } public static List<int> MonsterSubCategoryIds(YugiohCard yugiohCard, IEnumerable<SubCategory> monsterSubCategories) { return monsterSubCategories .Where(msb => yugiohCard.MonsterSubCategoriesAndTypes.Any(ysc => ysc.Equals(msb.Name, StringComparison.OrdinalIgnoreCase))) .Select(ssc => (int)ssc.Id) .ToList(); } public static int MonsterAttributeId(YugiohCard yugiohCard, ICollection<Attribute> attributes) { return (int) ( from a in attributes where a.Name.Equals(yugiohCard.Attribute, StringComparison.OrdinalIgnoreCase) select a.Id ) .Single(); } public static string Atk(YugiohCard yugiohCard) { return yugiohCard.AtkDef?.Split('/').First().Trim(); } public static string AtkLink(YugiohCard yugiohCard) { return yugiohCard.AtkLink?.Split('/').First().Trim(); } public static string DefOrLink(YugiohCard yugiohCard) { return yugiohCard.AtkDef?.Split('/').Last().Trim(); } public static CardInputModel MapMonsterCard(YugiohCard yugiohCard, CardInputModel cardInputModel, ICollection<Attribute> attributes, IEnumerable<SubCategory> monsterSubCategories, ICollection<Type> types, ICollection<LinkArrow> linkArrows) { cardInputModel.AttributeId = MonsterAttributeId(yugiohCard, attributes); cardInputModel.SubCategoryIds = MonsterSubCategoryIds(yugiohCard, monsterSubCategories); cardInputModel.TypeIds = MonsterTypeIds(yugiohCard, types); if (yugiohCard.LinkArrows != null) { cardInputModel.LinkArrowIds = MonsterLinkArrowIds(yugiohCard, linkArrows); } if (yugiohCard.Level.HasValue) cardInputModel.CardLevel = yugiohCard.Level; if (yugiohCard.Rank.HasValue) cardInputModel.CardRank = yugiohCard.Rank; if (!string.IsNullOrWhiteSpace(yugiohCard.AtkDef)) { var atk = Atk(yugiohCard); var def = DefOrLink(yugiohCard); int.TryParse(atk, out var cardAtk); int.TryParse(def, out var cardDef); cardInputModel.Atk = cardAtk; cardInputModel.Def = cardDef; } if (!string.IsNullOrWhiteSpace(yugiohCard.AtkLink)) { var atk = AtkLink(yugiohCard); int.TryParse(atk, out var cardAtk); cardInputModel.Atk = cardAtk; } return cardInputModel; } } }<file_sep>/src/wikia/data/carddata/src/Core/carddata.core/Models/YugiohCardCompletion.cs using carddata.core.Exceptions; namespace carddata.core.Models { public class YugiohCardCompletion { public bool IsSuccessful { get; set; } public Article Article { get; set; } public YugiohCard Card { get; set; } public YugiohCardException Exception { get; set; } } }<file_sep>/src/wikia/article/src/Tests/Unit/article.application.unit.tests/ScheduledTasksTests/ValidationTests/ArchetypeInformationTaskValidatorTests.cs using article.application.ScheduledTasks.Archetype; using article.tests.core; using FluentValidation.TestHelper; using NUnit.Framework; namespace article.application.unit.tests.ScheduledTasksTests.ValidationTests { [TestFixture] [Category(TestType.Unit)] public class ArchetypeInformationTaskValidatorTests { private ArchetypeInformationTaskValidator _sut; [SetUp] public void Setup() { _sut = new ArchetypeInformationTaskValidator(); } [TestCaseSource(nameof(InvalidCategories))] public void Given_Invalid_Categories_Validation_Should_Fail(string category) { // Arrange var inputModel = new ArchetypeInformationTask { Category = category }; var result = _sut.TestValidate(inputModel); // Act void Act() => result.ShouldHaveValidationErrorFor(ci => ci.Category); // Assert Act(); } [TestCase(0)] [TestCase(-1)] [TestCase(501)] public void Given_Invalid_PageSize_Validation_Should_Fail(int pageSize) { // Arrange var inputModel = new ArchetypeInformationTask { PageSize = pageSize }; var result = _sut.TestValidate(inputModel); // Act void Act() => result.ShouldHaveValidationErrorFor(ci => ci.PageSize); // Assert Act(); } #region private helpers private static readonly object[] InvalidCategories = { null, "", " " }; #endregion } }<file_sep>/src/wikia/processor/imageprocessor/src/Application/imageprocessor.application/MessageConsumers/YugiohImage/ImageConsumer.cs using MediatR; namespace imageprocessor.application.MessageConsumers.YugiohImage { public class ImageConsumer : IRequest<ImageConsumerResult> { public string Message { get; set; } } }<file_sep>/src/wikia/processor/banlistprocessor/src/Domain/banlistprocessor.domain/banlistprocessor.domain/Repository/IBanlistRepository.cs using System.Threading.Tasks; using banlistprocessor.core.Models.Db; namespace banlistprocessor.domain.Repository { public interface IBanlistRepository { Task<bool> BanlistExist(int id); Task<Banlist> Add(Banlist banlist); Task<Banlist> Update(Banlist banlist); Task<Banlist> GetBanlistById(int id); } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Domain/cardsectionprocessor.domain/Strategy/CardRulingsProcessorStrategy.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using cardsectionprocessor.core.Constants; using cardsectionprocessor.core.Models; using cardsectionprocessor.core.Models.Db; using cardsectionprocessor.core.Service; using cardsectionprocessor.core.Strategy; namespace cardsectionprocessor.domain.Strategy { public class CardRulingsProcessorStrategy : ICardSectionProcessorStrategy { private readonly ICardService _cardService; private readonly ICardRulingService _cardRulingService; public CardRulingsProcessorStrategy(ICardService cardService, ICardRulingService cardRulingService) { _cardService = cardService; _cardRulingService = cardRulingService; } public async Task<CardSectionDataTaskResult<CardSectionMessage>> Process(CardSectionMessage cardSectionData) { var cardSectionDataTaskResult = new CardSectionDataTaskResult<CardSectionMessage> { CardSectionData = cardSectionData }; var card = await _cardService.CardByName(cardSectionData.Name); if (card != null) { await _cardRulingService.DeleteByCardId(card.Id); var rulingSections = new List<RulingSection>(); foreach (var cardSection in cardSectionData.CardSections) { var rulingSection = new RulingSection { CardId = card.Id, Name = cardSection.Name, Created = DateTime.UtcNow, Updated = DateTime.UtcNow }; foreach (var ruling in cardSection.ContentList) { rulingSection.Ruling.Add(new Ruling { RulingSection = rulingSection, Text = ruling, Created = DateTime.UtcNow, Updated = DateTime.UtcNow }); } rulingSections.Add(rulingSection); } if (rulingSections.Any()) { await _cardRulingService.Update(rulingSections); } } else { cardSectionDataTaskResult.Errors.Add($"Card Rulings: card '{cardSectionData.Name}' not found."); } return cardSectionDataTaskResult; } public bool Handles(string category) { return category == ArticleCategory.CardRulings; } } }<file_sep>/src/wikia/article/src/Tests/Unit/article.infrastructure.unit.tests/ServicesTests/MessagingTests/BanlistArticleQueueTests/PublishTests.cs using System.Threading.Tasks; using article.core.Models; using article.domain.Services.Messaging; using article.infrastructure.Services.Messaging; using article.tests.core; using NSubstitute; using NUnit.Framework; using wikia.Models.Article.AlphabeticalList; namespace article.infrastructure.unit.tests.ServicesTests.MessagingTests.BanlistArticleQueueTests { [TestFixture] [Category(TestType.Unit)] public class PublishTests { private BanlistArticleQueue _sut; private IQueue<Article> _queue; [SetUp] public void SetUp() { _queue = Substitute.For<IQueue<Article>>(); _sut = new BanlistArticleQueue(_queue); } [Test] public async Task Given_An_UnexpandedArticle_Should_Invoke_Publish_Method_Once() { // Arrange const int expected = 1; var unexpandedArticle = new UnexpandedArticle(); // Act await _sut.Publish(unexpandedArticle); // Assert await _queue.Received(expected).Publish(Arg.Any<Article>()); } } }<file_sep>/src/wikia/article/src/Tests/Unit/article.domain.unit.tests/ArticleCategoryDataSourceTests.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using article.core.ArticleList.DataSource; using article.domain.ArticleList.DataSource; using article.tests.core; using AutoFixture; using FluentAssertions; using NSubstitute; using NUnit.Framework; using wikia.Api; using wikia.Models.Article; using wikia.Models.Article.AlphabeticalList; namespace article.domain.unit.tests { [TestFixture] [Category(TestType.Unit)] public class ArticleCategoryDataSourceTests { private IWikiArticleList _articleList; private IArticleCategoryDataSource _sut; [SetUp] public void Setup() { _articleList = Substitute.For<IWikiArticleList>(); _sut = new ArticleCategoryDataSource(_articleList); } [TestCase(null)] [TestCase("")] [TestCase(" ")] public void Given_A_Invalid_Category_Should_Throw_ArgumentException(string category) { // Arrange // Act Func<Task<List<UnexpandedArticle[]>>> act = () => _sut.Producer(category, 500).ToListAsync(); // Assert act.Should().ThrowAsync<ArgumentException>(); } [Test] public async Task Given_Batches_Of_UnexpandedArticles_Should_Process_All_Batches() { // Arrange const int expected = 5; const int pageSize = 100; var fixture = new Fixture(); var articleBatch1 = fixture.Build<UnexpandedListArticleResultSet>().With(x => x.Items, new Fixture { RepeatCount = pageSize }.Create<UnexpandedArticle[]>()).Create(); var articleBatch2 = fixture.Build<UnexpandedListArticleResultSet>().With(x => x.Items, new Fixture { RepeatCount = pageSize }.Create<UnexpandedArticle[]>()).Create(); var articleBatch3 = fixture.Build<UnexpandedListArticleResultSet>().With(x => x.Items, new Fixture { RepeatCount = pageSize }.Create<UnexpandedArticle[]>()).Create(); var articleBatch4 = fixture.Build<UnexpandedListArticleResultSet>().With(x => x.Items, new Fixture { RepeatCount = pageSize }.Create<UnexpandedArticle[]>()).Create(); var articleBatch5 = fixture.Build<UnexpandedListArticleResultSet>().With(x => x.Items, new Fixture { RepeatCount = pageSize }.Create<UnexpandedArticle[]>()).Create(); // Set Last page articleBatch5.Offset = null; _articleList .AlphabeticalList(Arg.Any<ArticleListRequestParameters>()) .ReturnsForAnyArgs ( articleBatch1, articleBatch2, articleBatch3, articleBatch4, articleBatch5 ); // Act var result = await _sut.Producer("category", 500).ToListAsync(); // Assert result.Count.Should().Be(expected); } } public static class AsyncEnumerableExtensions { public static async Task<List<T>> ToListAsync<T>(this IAsyncEnumerable<T> enumerable) { var list = new List<T>(); await foreach (var item in enumerable) { list.Add(item); } return list; } public static async Task<T[]> ToArrayAsync<T>(this IAsyncEnumerable<T> enumerable) { var result = await ToListAsync(enumerable); return result.ToArray(); } public static async Task<T> SingleOrDefault<T>(this IAsyncEnumerable<T> enumerable) { var result = await ToListAsync(enumerable); return result.SingleOrDefault(); } public static async IAsyncEnumerable<T> ToAsyncEnumerable<T>(this IEnumerable<T> enumerable) { foreach (var item in enumerable) { yield return await Task.FromResult(item); } } } } <file_sep>/src/wikia/article/src/Domain/article.domain/ArticleList/Item/BanlistItemProcessor.cs using article.core.ArticleList.Processor; using article.core.Constants; using article.core.Exceptions; using article.core.Models; using article.domain.Services.Messaging; using System; using System.Threading.Tasks; using wikia.Models.Article.AlphabeticalList; namespace article.domain.ArticleList.Item { public sealed class BanlistItemProcessor : IArticleItemProcessor { private readonly IBanlistArticleQueue _banlistArticleQueue; public BanlistItemProcessor(IBanlistArticleQueue banlistArticleQueue) { _banlistArticleQueue = banlistArticleQueue; } public async Task<ArticleTaskResult> ProcessItem(UnexpandedArticle item) { if (item == null) throw new ArgumentNullException(nameof(item)); var articleTaskResult = new ArticleTaskResult { Article = item }; try { await _banlistArticleQueue.Publish(item); articleTaskResult.IsSuccessfullyProcessed = true; } catch (Exception ex) { articleTaskResult.Failed = new ArticleException { Article = item, Exception = ex }; } return articleTaskResult; } public bool Handles(string category) { return category == ArticleCategory.ForbiddenAndLimited; } } }<file_sep>/src/wikia/data/archetypedata/src/Infrastructure/archetypedata.infrastructure/WebPages/ArchetypeWebPage.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using archetypedata.application.Configuration; using archetypedata.domain.WebPages; using HtmlAgilityPack; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Extensions.Options; using wikia.Models.Article.Details; namespace archetypedata.infrastructure.WebPages { public class ArchetypeWebPage : IArchetypeWebPage { private readonly IOptions<AppSettings> _appsettingsOptions; private readonly IHtmlWebPage _htmlWebPage; private readonly IArchetypeThumbnail _archetypeThumbnail; public ArchetypeWebPage(IOptions<AppSettings> appsettingsOptions, IHtmlWebPage htmlWebPage, IArchetypeThumbnail archetypeThumbnail) { _appsettingsOptions = appsettingsOptions; _htmlWebPage = htmlWebPage; _archetypeThumbnail = archetypeThumbnail; } public IEnumerable<string> Cards(Uri archetypeUrl) { var cardList = new HashSet<string>(); var archetypeWebPage = _htmlWebPage.Load(archetypeUrl); var tableCollection = archetypeWebPage.DocumentNode .SelectNodes("//table") .Where(t => t.Attributes["class"] != null && t.Attributes["class"].Value.Contains("card-list")) .ToList(); foreach (var tb in tableCollection) { var cardLinks = tb.SelectNodes("./tbody/tr/td[position() =1]/a"); cardList.UnionWith(cardLinks.Select(cn => cn.InnerText)); } var furtherResultsUrl = GetFurtherResultsUrl(archetypeWebPage); if (!string.IsNullOrEmpty(furtherResultsUrl)) { if (!furtherResultsUrl.Contains("http")) furtherResultsUrl = _appsettingsOptions.Value.WikiaDomainUrl + furtherResultsUrl; var cardsFromFurtherResultsUrl = CardsFromFurtherResultsUrl(furtherResultsUrl); cardList.UnionWith(cardsFromFurtherResultsUrl); } return cardList; } public List<string> CardsFromFurtherResultsUrl(string furtherResultsUrl) { var cardList = new HashSet<string>(); var uri = new Uri(furtherResultsUrl); var baseUri = uri.GetComponents(UriComponents.Scheme | UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.UriEscaped); var query = QueryHelpers.ParseQuery(uri.Query); var items = query.SelectMany(x => x.Value, (col, value) => new KeyValuePair<string, string>(col.Key, value)).ToDictionary(x => x.Key, x => x.Value); items["limit"] = "500"; items["offset"] = "0"; var qb = new QueryBuilder(items); var newUrl = baseUri + qb.ToQueryString(); var sematicSearchPage = _htmlWebPage.Load(newUrl); var cardNameList = sematicSearchPage.DocumentNode.SelectNodes("//*[@id='result']/table/tbody/tr/td[1]/a"); if (cardNameList != null) cardList.UnionWith(cardNameList.Select(cn => cn.InnerText)); return cardList.ToList(); } public string GetFurtherResultsUrl(HtmlDocument archetypeWebPage) { return archetypeWebPage.DocumentNode.SelectSingleNode("//span[@class='smw-table-furtherresults']/a")?.Attributes["href"].Value; } public async Task<string> ArchetypeThumbnail(long articleId, string archetypeWebPageUrl) { var thumbNail = await _archetypeThumbnail.FromArticleId((int)articleId); return ArchetypeThumbnail(thumbNail, archetypeWebPageUrl); } public string ArchetypeThumbnail(KeyValuePair<string, ExpandedArticle> articleDetails, string archetypeWebPageUrl) { var thumbNail = _archetypeThumbnail.FromArticleDetails(articleDetails); return ArchetypeThumbnail(thumbNail, archetypeWebPageUrl); } public string ArchetypeThumbnail(string thumbNailUrl, string archetypeWebPageUrl) { return string.IsNullOrWhiteSpace(thumbNailUrl) ? _archetypeThumbnail.FromWebPage(archetypeWebPageUrl) : thumbNailUrl; } } } <file_sep>/src/wikia/semanticsearch/src/Core/semanticsearch.core/Search/ISemanticSearchConsumer.cs using System.Threading.Tasks; using semanticsearch.core.Model; namespace semanticsearch.core.Search { public interface ISemanticSearchConsumer { Task<SemanticCardPublishResult> Process(SemanticCard semanticCard); } }<file_sep>/src/wikia/data/banlistdata/src/Infrastructure/banlistdata.infrastructure/InfrastructureInstaller.cs using banlistdata.domain.Services.Messaging; using banlistdata.infrastructure.Services.Messaging; using Microsoft.Extensions.DependencyInjection; namespace banlistdata.infrastructure { public static class InfrastructureInstaller { public static IServiceCollection AddInfrastructureServices(this IServiceCollection services) { services.AddMessagingServices(); return services; } public static IServiceCollection AddMessagingServices(this IServiceCollection services) { services.AddTransient<IBanlistDataQueue, BanlistDataQueue>(); return services; } } }<file_sep>/src/wikia/processor/banlistprocessor/src/Domain/banlistprocessor.domain/banlistprocessor.domain/Services/BanlistService.cs using System; using System.Threading.Tasks; using AutoMapper; using banlistprocessor.core.Models; using banlistprocessor.core.Models.Db; using banlistprocessor.core.Services; using banlistprocessor.domain.Repository; namespace banlistprocessor.domain.Services { public class BanlistService : IBanlistService { private readonly IBanlistCardService _banlistCardService; private readonly IBanlistRepository _banlistRepository; private readonly IFormatRepository _formatRepository; private readonly IMapper _mapper; public BanlistService ( IBanlistCardService banlistCardService, IBanlistRepository banlistRepository, IFormatRepository formatRepository, IMapper mapper ) { _banlistCardService = banlistCardService; _banlistRepository = banlistRepository; _formatRepository = formatRepository; _mapper = mapper; } public Task<bool> BanlistExist(int id) { return _banlistRepository.BanlistExist(id); } public async Task<Banlist> Add(YugiohBanlist yugiohBanlist) { var format = await _formatRepository.FormatByAcronym(yugiohBanlist.BanlistType.ToString()); if(format == null) throw new ArgumentException($"Format with acronym '{yugiohBanlist.BanlistType.ToString()}' not found."); var newBanlist = _mapper.Map<Banlist>(yugiohBanlist); newBanlist.FormatId = format.Id; newBanlist = await _banlistRepository.Add(newBanlist); newBanlist.BanlistCard = await _banlistCardService.Update(newBanlist.Id, yugiohBanlist.Sections); return newBanlist; } public async Task<Banlist> Update(YugiohBanlist yugiohBanlist) { var format = await _formatRepository.FormatByAcronym(yugiohBanlist.BanlistType.ToString()); if (format == null) throw new ArgumentException($"Format with acronym '{yugiohBanlist.BanlistType.ToString()}' not found."); var banlistToupdate = await _banlistRepository.GetBanlistById(yugiohBanlist.ArticleId); banlistToupdate.FormatId = format.Id; banlistToupdate.Name = yugiohBanlist.Title; banlistToupdate.ReleaseDate = yugiohBanlist.StartDate; banlistToupdate.Updated = DateTime.UtcNow; banlistToupdate = await _banlistRepository.Update(banlistToupdate); banlistToupdate.BanlistCard = await _banlistCardService.Update(banlistToupdate.Id, yugiohBanlist.Sections); return banlistToupdate; } } }<file_sep>/src/wikia/data/cardsectiondata/src/Application/cardsectiondata.application/MessageConsumers/CardRulingInformation/CardRulingInformationConsumerHandler.cs using cardsectiondata.application.MessageConsumers.CardInformation; using cardsectiondata.core.Constants; using MediatR; using System.Threading; using System.Threading.Tasks; namespace cardsectiondata.application.MessageConsumers.CardRulingInformation { public class CardRulingInformationConsumerHandler : IRequestHandler<CardRulingInformationConsumer, CardRulingInformationConsumerResult> { private readonly IMediator _mediator; public CardRulingInformationConsumerHandler(IMediator mediator) { _mediator = mediator; } public async Task<CardRulingInformationConsumerResult> Handle(CardRulingInformationConsumer request, CancellationToken cancellationToken) { var cardRulingInformationConsumerResult = new CardRulingInformationConsumerResult(); var cardInformation = new CardInformationConsumer { Category = ArticleCategory.CardRulings, Message = request.Message }; var result = await _mediator.Send(cardInformation, cancellationToken); if (!result.IsSuccessful) { cardRulingInformationConsumerResult.Errors = result.Errors; } return cardRulingInformationConsumerResult; } } }<file_sep>/src/wikia/data/cardsectiondata/src/Infrastructure/cardsectiondata.infrastructure/WebPages/TipRelatedCardList.cs using System.Collections.Generic; using System.Linq; using cardsectiondata.domain.WebPages; using HtmlAgilityPack; namespace cardsectiondata.infrastructure.WebPages { public class TipRelatedCardList : ITipRelatedCardList { public List<string> ExtractCardsFromTable(HtmlNode table) { var cardNameList = table.SelectNodes("//tr/td[position() = 1]/a"); return cardNameList.Select(cn => cn.InnerText).ToList(); } } }<file_sep>/src/wikia/article/src/Core/article.core/ArticleList/Processor/IArticleCategoryProcessor.cs using System.Collections.Generic; using System.Threading.Tasks; using article.core.Models; namespace article.core.ArticleList.Processor { public interface IArticleCategoryProcessor { Task<IEnumerable<ArticleBatchTaskResult>> Process(IEnumerable<string> categories, int pageSize); Task<ArticleBatchTaskResult> Process(string category, int pageSize); } }<file_sep>/src/services/Cards.API/src/Tests/Unit/Cards.Application.Unit.Tests/MessageConsumersTests/CardInformationConsumerHandlerTests.cs using System.Threading; using System.Threading.Tasks; using Cards.Application.MessageConsumers.CardData; using FluentAssertions; using NUnit.Framework; namespace Cards.Application.Unit.Tests.MessageConsumersTests { [TestFixture] [Category(TestType.Unit)] public class CardInformationConsumerHandlerTests { private CardInformationConsumerHandler _sut; [SetUp] public void SetUp() { _sut = new CardInformationConsumerHandler(); } [Test] public async Task Given_Card_Json_If_Json_Is_Processed_Successfully_Is_The_IsSuccessful_Should_Be_True() { // Arrange var cardInformationConsumer = new CardInformationConsumer ( "{\"Name\":\"<NAME>\",\"Types\":\"Warrior / Effect\",\"CardType\":\"Monster\",\"Attribute\":\"Earth\",\"Level\":4,\"Rank\":null,\"PendulumScale\":null,\"AtkDef\":\"1400 / 1000\",\"AtkLink\":null,\"CardNumber\":\"91869203\",\"Materials\":null,\"CardEffectTypes\":\"Ignition\",\"Property\":null,\"Description\":\"You can Tribute 2 monsters; inflict 1200 damage to your opponent.\",\"ImageUrl\":\"https://vignette.wikia.nocookie.net/yugioh/images/0/02/AmazonessArcher-LEDU-EN-C-1E.png\",\"LinkArrows\":null,\"MonsterSubCategoriesAndTypes\":[\"Warrior\",\"Effect\"],\"MonsterLinkArrows\":null}" ); // Act var result = await _sut.Handle(cardInformationConsumer, CancellationToken.None); // Assert result.IsSuccessful.Should().BeTrue(); } } }<file_sep>/src/wikia/processor/imageprocessor/README.md ![alt text](https://fablecode.visualstudio.com/Yugioh%20Insight/_apis/build/status/Build_ArticleData "Visual studio team services build status") # Image Processor Persists image data.<file_sep>/src/wikia/processor/cardprocessor/src/Core/cardprocessor.core/Strategies/ICardTypeStrategy.cs using System.Threading.Tasks; using cardprocessor.core.Enums; using cardprocessor.core.Models; using cardprocessor.core.Models.Db; namespace cardprocessor.core.Strategies { public interface ICardTypeStrategy { Task<Card> Add(CardModel cardModel); Task<Card> Update(CardModel cardModel); bool Handles(YugiohCardType yugiohCardType); } }<file_sep>/src/wikia/data/archetypedata/src/Domain/archetypedata.domain/Processor/ArchetypeCardProcessor.cs using System; using System.Threading.Tasks; using archetypedata.core.Models; using archetypedata.core.Processor; using archetypedata.domain.Helpers; using archetypedata.domain.Services.Messaging; using archetypedata.domain.WebPages; namespace archetypedata.domain.Processor { public class ArchetypeCardProcessor : IArchetypeCardProcessor { private readonly IArchetypeWebPage _archetypeWebPage; private readonly IQueue<ArchetypeCard> _queue; public ArchetypeCardProcessor(IArchetypeWebPage archetypeWebPage, IQueue<ArchetypeCard> queue) { _archetypeWebPage = archetypeWebPage; _queue = queue; } public async Task<ArticleTaskResult> Process(Article article) { var articleTaskResult = new ArticleTaskResult { Article = article }; var archetypeName = StringHelpers.ArchetypeNameFromListTitle(article.Title); var archetypeCards = new ArchetypeCard { ArchetypeName = archetypeName, Cards = _archetypeWebPage.Cards(new Uri(article.Url)) }; await _queue.Publish(archetypeCards); return articleTaskResult; } } }<file_sep>/src/wikia/article/src/Presentation/article.archetypes/QuartzConfiguration/ArchetypeInformationJobFactory.cs using System; using Microsoft.Extensions.DependencyInjection; using Quartz; using Quartz.Spi; namespace article.archetypes.QuartzConfiguration { public class ArchetypeInformationJobFactory : IJobFactory { private readonly IServiceProvider _serviceProvider; public ArchetypeInformationJobFactory(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler) { return _serviceProvider.GetRequiredService<IJob>(); } public void ReturnJob(IJob job) { } } }<file_sep>/src/wikia/article/src/Presentation/article.latestbanlists/Dockerfile FROM mcr.microsoft.com/dotnet/aspnet:5.0-alpine AS base WORKDIR /app FROM mcr.microsoft.com/dotnet/sdk:5.0-alpine AS build WORKDIR /src COPY . . RUN dotnet restore "article.sln" FROM build AS publish RUN dotnet publish "Presentation/article.latestbanlists/article.latestbanlists.csproj" -c Release -o /app/publish --no-restore FROM base AS final WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "article.latestbanlists.dll"]<file_sep>/src/wikia/article/src/Infrastructure/article.infrastructure/WebPages/Banlists/BanlistHtmlDocument.cs using article.core.Enums; using article.domain.WebPages; using article.domain.WebPages.Banlists; using HtmlAgilityPack; namespace article.infrastructure.WebPages.Banlists { public class BanlistHtmlDocument : IBanlistHtmlDocument { private readonly IHtmlWebPage _htmlWebPage; public BanlistHtmlDocument(IHtmlWebPage htmlWebPage) { _htmlWebPage = htmlWebPage; } public HtmlNode GetBanlistHtmlNode(BanlistType banlistType, string banlistUrl) { return GetBanlistHtmlNode(banlistType, _htmlWebPage.Load(banlistUrl)); } public HtmlNode GetBanlistHtmlNode(BanlistType banlistType, HtmlDocument document) { return document .DocumentNode .SelectSingleNode($"//*[contains(@class,'nowraplinks navbox-subgroup')]/tr/th/i[contains(text(), '{banlistType.ToString().ToUpper()}')]") .ParentNode .ParentNode .SelectSingleNode("./td/table/tr[1]/td[1]/div/ul"); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Domain/cardprocessor.domain/Repository/ISubCategoryRepository.cs using System.Collections.Generic; using System.Threading.Tasks; using cardprocessor.core.Models.Db; namespace cardprocessor.domain.Repository { public interface ISubCategoryRepository { Task<List<SubCategory>> AllSubCategories(); } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Domain/cardsectionprocessor.domain/Service/CardTriviaService.cs using System.Collections.Generic; using System.Threading.Tasks; using cardsectionprocessor.core.Models.Db; using cardsectionprocessor.core.Service; using cardsectionprocessor.domain.Repository; namespace cardsectionprocessor.domain.Service { public class CardTriviaService : ICardTriviaService { private readonly ICardTriviaRepository _cardTriviaRepository; public CardTriviaService(ICardTriviaRepository cardTriviaRepository) { _cardTriviaRepository = cardTriviaRepository; } public Task DeleteByCardId(long id) { return _cardTriviaRepository.DeleteByCardId(id); } public Task Update(List<TriviaSection> triviaSections) { return _cardTriviaRepository.Update(triviaSections); } } }<file_sep>/src/wikia/article/src/Domain/article.domain/Banlist/Processor/BanlistProcessor.cs using System.Threading.Tasks; using article.core.ArticleList.Processor; using article.core.Constants; using article.core.Enums; using article.core.Models; using article.domain.Banlist.DataSource; using Microsoft.Extensions.Logging; using wikia.Models.Article.AlphabeticalList; namespace article.domain.Banlist.Processor { public sealed class BanlistProcessor : IBanlistProcessor { private readonly IBanlistUrlDataSource _banlistUrlDataSource; private readonly IArticleProcessor _articleProcessor; private readonly ILogger<BanlistProcessor> _logger; public BanlistProcessor(IBanlistUrlDataSource banlistUrlDataSource, IArticleProcessor articleProcessor, ILogger<BanlistProcessor> logger) { _banlistUrlDataSource = banlistUrlDataSource; _articleProcessor = articleProcessor; _logger = logger; } public async Task<ArticleBatchTaskResult> Process(BanlistType banlistType) { var response = new ArticleBatchTaskResult(); const string baseBanlistUrl = "http://yugioh.fandom.com/wiki/July_1999_Lists"; var banListArticleIds = _banlistUrlDataSource.GetBanlists(banlistType, baseBanlistUrl); foreach (var (year, banlistIds) in banListArticleIds) { _logger.LogInformation("{@BanlistType} banlists for the year: {@Year}", banlistType.ToString().ToUpper(), year); foreach (var articleId in banlistIds) { _logger.LogInformation("{@BanlistType} banlist articleId: {@ArticleId}", banlistType.ToString().ToUpper(), articleId); var articleResult = await _articleProcessor.Process(ArticleCategory.ForbiddenAndLimited, new UnexpandedArticle {Id = articleId}); if (articleResult.IsSuccessfullyProcessed) response.Processed += 1; } } return response; } } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Core/archetypeprocessor.core/Models/ArchetypeMessage.cs using System; namespace archetypeprocessor.core.Models { public class ArchetypeMessage { public long Id { get; set; } public string Name { get; set; } public string ImageUrl { get; set; } public string ProfileUrl { get; set; } public DateTime Revision { get; set; } } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Application/archetypeprocessor.application/MessageConsumers/ArchetypeCardInformation/ArchetypeCardInformationConsumerHandler.cs using System.Linq; using System.Threading; using System.Threading.Tasks; using archetypeprocessor.core.Models; using archetypeprocessor.core.Processor; using FluentValidation; using MediatR; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace archetypeprocessor.application.MessageConsumers.ArchetypeCardInformation { public class ArchetypeCardInformationConsumerHandler : IRequestHandler<ArchetypeCardInformationConsumer, ArchetypeCardInformationConsumerResult> { private readonly IArchetypeCardProcessor _archetypeCardProcessor; private readonly IValidator<ArchetypeCardInformationConsumer> _validator; private readonly ILogger<ArchetypeCardInformationConsumerHandler> _logger; public ArchetypeCardInformationConsumerHandler(IArchetypeCardProcessor archetypeCardProcessor, IValidator<ArchetypeCardInformationConsumer> validator, ILogger<ArchetypeCardInformationConsumerHandler> logger) { _archetypeCardProcessor = archetypeCardProcessor; _validator = validator; _logger = logger; } public async Task<ArchetypeCardInformationConsumerResult> Handle(ArchetypeCardInformationConsumer request, CancellationToken cancellationToken) { var archetypeInformationConsumerResult = new ArchetypeCardInformationConsumerResult(); var validationResults = _validator.Validate(request); if (validationResults.IsValid) { var archetypeArticle = JsonConvert.DeserializeObject<ArchetypeCardMessage>(request.Message); _logger.LogInformation("Processing archetype '{@Title}' cards", archetypeArticle.ArchetypeName); var results = await _archetypeCardProcessor.Process(archetypeArticle); _logger.LogInformation("Finished processing archetype '{@Title}' cards", archetypeArticle.ArchetypeName); if (!results.IsSuccessful) { archetypeInformationConsumerResult.Errors.AddRange(results.Errors); } } else { archetypeInformationConsumerResult.Errors = validationResults.Errors.Select(err => err.ErrorMessage).ToList(); } return archetypeInformationConsumerResult; } } }<file_sep>/src/wikia/data/archetypedata/src/Tests/Unit/archetypedata.application.unit.tests/ArchetypeInformationConsumerHandlerTests.cs using System; using archetypedata.application.MessageConsumers.ArchetypeInformation; using archetypedata.core.Models; using archetypedata.core.Processor; using archetypedata.tests.core; using FluentAssertions; using FluentValidation; using Microsoft.Extensions.Logging; using NSubstitute; using NUnit.Framework; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using NSubstitute.ExceptionExtensions; namespace archetypedata.application.unit.tests { [TestFixture] [Category(TestType.Unit)] public class ArchetypeInformationConsumerHandlerTests { private IValidator<ArchetypeInformationConsumer> _validator; private IArchetypeProcessor _archetypeProcessor; private ArchetypeInformationConsumerHandler _sut; private ILogger<ArchetypeInformationConsumerHandler> _logger; [SetUp] public void SetUp() { _validator = Substitute.For<IValidator<ArchetypeInformationConsumer>>(); _archetypeProcessor = Substitute.For<IArchetypeProcessor>(); _logger = Substitute.For<ILogger<ArchetypeInformationConsumerHandler>>(); _sut = new ArchetypeInformationConsumerHandler(_archetypeProcessor, _validator, _logger); } [Test] public async Task Given_An_Invalid_ArchetypeInformationConsumer_IsSuccessful_Should_Be_False() { // Arrange var archetypeInformationConsumer = new ArchetypeInformationConsumer(); _validator.Validate(Arg.Any<ArchetypeInformationConsumer>()) .Returns(new ArchetypeInformationConsumerValidator().Validate(archetypeInformationConsumer)); // Act var result = await _sut.Handle(archetypeInformationConsumer, CancellationToken.None); // Assert result.IsSuccessful.Should().BeFalse(); } [Test] public async Task Given_An_Invalid_ArchetypeInformationConsumer_Errors_List_Should_Not_Be_Null_Or_Empty() { // Arrange var archetypeInformationConsumer = new ArchetypeInformationConsumer(); _validator.Validate(Arg.Any<ArchetypeInformationConsumer>()) .Returns(new ArchetypeInformationConsumerValidator().Validate(archetypeInformationConsumer)); // Act var result = await _sut.Handle(archetypeInformationConsumer, CancellationToken.None); // Assert result.Errors.Should().NotBeNullOrEmpty(); } [Test] public async Task Given_A_Valid_ArchetypeInformationConsumer_IsSuccessful_Should_Be_True() { // Arrange var archetypeInformationConsumer = new ArchetypeInformationConsumer { Message = "{\"Id\":703544,\"CorrelationId\":\"3e2bf3ca-d903-440c-8cd5-be61c95ae1fc\",\"Title\":\"Tenyi\",\"Url\":\"https://yugioh.fandom.com/wiki/Tenyi\"}" }; _validator.Validate(Arg.Any<ArchetypeInformationConsumer>()) .Returns(new ArchetypeInformationConsumerValidator().Validate(archetypeInformationConsumer)); _archetypeProcessor.Process(Arg.Any<Article>()).Returns(new ArticleTaskResult()); // Act var result = await _sut.Handle(archetypeInformationConsumer, CancellationToken.None); // Assert result.IsSuccessful.Should().BeTrue(); } [Test] public async Task Given_A_Valid_ArchetypeInformationConsumer_Should_Execute_Process_Method_Once() { // Arrange var archetypeInformationConsumer = new ArchetypeInformationConsumer { Message = "{\"Id\":703544,\"CorrelationId\":\"3e2bf3ca-d903-440c-8cd5-be61c95ae1fc\",\"Title\":\"Tenyi\",\"Url\":\"https://yugioh.fandom.com/wiki/Tenyi\"}" }; _validator.Validate(Arg.Any<ArchetypeInformationConsumer>()) .Returns(new ArchetypeInformationConsumerValidator().Validate(archetypeInformationConsumer)); _archetypeProcessor.Process(Arg.Any<Article>()).Returns(new ArticleTaskResult()); // Act await _sut.Handle(archetypeInformationConsumer, CancellationToken.None); // Assert await _archetypeProcessor.Received(1).Process(Arg.Any<Article>()); } [Test] public async Task Given_A_Valid_ArchetypeInformationConsumer_If_Not_Processed_Successfully_Errors_Should_Not_Be_Null_Or_Empty() { // Arrange var archetypeInformationConsumer = new ArchetypeInformationConsumer { Message = "{\"Id\":703544,\"CorrelationId\":\"3e2bf3ca-d903-440c-8cd5-be61c95ae1fc\",\"Title\":\"Tenyi\",\"Url\":\"https://yugioh.fandom.com/wiki/Tenyi\"}" }; _validator.Validate(Arg.Any<ArchetypeInformationConsumer>()) .Returns(new ArchetypeInformationConsumerValidator().Validate(archetypeInformationConsumer)); _archetypeProcessor.Process(Arg.Any<Article>()).Returns(new ArticleTaskResult{ Errors = new List<string>{ "Something went horribly wrong"}}); // Act var result = await _sut.Handle(archetypeInformationConsumer, CancellationToken.None); // Assert result.Errors.Should().NotBeNullOrEmpty(); } [Test] public async Task Given_A_Valid_ArchetypeInformationConsumer_If_Process_Method_Throws_Exception_Should_Invoke_LogError() { // Arrange const int expected = 1; var archetypeInformationConsumer = new ArchetypeInformationConsumer { Message = "{\"Id\":703544,\"CorrelationId\":\"3e2bf3ca-d903-440c-8cd5-be61c95ae1fc\",\"Title\":\"Tenyi\",\"Url\":\"https://yugioh.fandom.com/wiki/Tenyi\"}" }; _validator.Validate(Arg.Any<ArchetypeInformationConsumer>()) .Returns(new ArchetypeInformationConsumerValidator().Validate(archetypeInformationConsumer)); _archetypeProcessor.Process(Arg.Any<Article>()).Throws<ArgumentNullException>(); // Act await _sut.Handle(archetypeInformationConsumer, CancellationToken.None); // Assert _logger.Received(expected).Log(LogLevel.Error, Arg.Any<EventId>(), Arg.Any<object>(), Arg.Any<Exception>(), Arg.Any<Func<object, Exception, string>>()); } } } <file_sep>/src/wikia/article/src/Infrastructure/article.infrastructure/InfrastructureInstaller.cs using article.core.Models; using article.domain.Services.Messaging; using article.domain.Services.Messaging.Cards; using article.domain.WebPages; using article.domain.WebPages.Banlists; using article.infrastructure.Services.Messaging; using article.infrastructure.Services.Messaging.Cards; using article.infrastructure.WebPages.Banlists; using Microsoft.Extensions.DependencyInjection; namespace article.infrastructure { public static class InfrastructureInstaller { public static IServiceCollection AddInfrastructureServices(this IServiceCollection services) { services .AddMessagingServices() .AddHtmlServices(); return services; } public static IServiceCollection AddMessagingServices(this IServiceCollection services) { services.AddTransient<IQueue<Article>, ArticleQueue>(); services.AddTransient<IBanlistArticleQueue, BanlistArticleQueue>(); services.AddTransient<IArchetypeArticleQueue, ArchetypeArticleQueue>(); services.AddTransient<ICardArticleQueue, CardArticleQueue>(); services.AddTransient<ISemanticCardArticleQueue, SemanticCardArticleQueue>(); return services; } public static IServiceCollection AddHtmlServices(this IServiceCollection services) { services.AddTransient<IBanlistHtmlDocument, BanlistHtmlDocument>(); services.AddTransient<IBanlistWebPage, BanlistWebPage>(); services.AddTransient<IHtmlWebPage, HtmlWebPage>(); return services; } } }<file_sep>/src/wikia/data/banlistdata/src/Core/banlistdata.core/Exceptions/BanlistException.cs using System; using banlistdata.core.Models; namespace banlistdata.core.Exceptions { public class BanlistException { public YugiohBanlist Banlist { get; set; } public Exception Exception { get; set; } } }<file_sep>/src/wikia/processor/imageprocessor/src/Tests/Unit/imageprocessor.application.unit.tests/MessageConsumersTests/ImageConsumerHandlerTests.cs using System; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using imageprocessor.application.Commands; using imageprocessor.application.Commands.DownloadImage; using imageprocessor.application.MessageConsumers.YugiohImage; using imageprocessor.tests.core; using MediatR; using Microsoft.Extensions.Logging; using NSubstitute; using NSubstitute.ExceptionExtensions; using NUnit.Framework; namespace imageprocessor.application.unit.tests.MessageConsumersTests { [TestFixture] [Category(TestType.Unit)] public class ImageConsumerHandlerTests { private IMediator _mediator; private ImageConsumerHandler _sut; [SetUp] public void SetUp() { _mediator = Substitute.For<IMediator>(); var logger = Substitute.For<ILogger<ImageConsumerHandler>>(); _sut = new ImageConsumerHandler(_mediator, logger); } [Test] public async Task Given_A_CardImageConsumer_If_Exception_Is_Thrown_Exception_Variable_Should_Not_Be_Null() { // Arrange var cardImageConsumer = new ImageConsumer { Message = "{\"RemoteImageUrl\":\"https://vignette.wikia.nocookie.net/yugioh/images/f/f6/AdreusKeeperofArmageddon-BP01-EN-R-1E.png\",\"ImageFileName\":\"Adreus, Keeper of Armageddon\",\"ImageFolderPath\":\"D:\\\\Apps\\\\ygo-api\\\\Images\\\\Cards\"}\r" }; _mediator.Send(Arg.Any<DownloadImageCommand>()).Throws(new Exception()); // Act var result = await _sut.Handle(cardImageConsumer, CancellationToken.None); // Assert result.Exception.Should().NotBeNull(); } [Test] public async Task Given_A_CardImageConsumer_If_Exception_Is_Thrown_IsSuccessful_Should_False() { // Arrange var cardImageConsumer = new ImageConsumer { Message = "{\"RemoteImageUrl\":\"https://vignette.wikia.nocookie.net/yugioh/images/f/f6/AdreusKeeperofArmageddon-BP01-EN-R-1E.png\",\"ImageFileName\":\"Adreus, Keeper of Armageddon\",\"ImageFolderPath\":\"D:\\\\Apps\\\\ygo-api\\\\Images\\\\Cards\"}\r" }; _mediator.Send(Arg.Any<DownloadImageCommand>()).Throws(new Exception()); // Act var result = await _sut.Handle(cardImageConsumer, CancellationToken.None); // Assert result.IsSuccessful.Should().BeFalse(); } [Test] public async Task Given_A_CardImageConsumer_Should_Process_CardImage_Successfully() { // Arrange var cardImageConsumer = new ImageConsumer { Message = "{\"RemoteImageUrl\":\"https://vignette.wikia.nocookie.net/yugioh/images/f/f6/AdreusKeeperofArmageddon-BP01-EN-R-1E.png\",\"ImageFileName\":\"Adreus, Keeper of Armageddon\",\"ImageFolderPath\":\"D:\\\\Apps\\\\ygo-api\\\\Images\\\\Cards\"}\r" }; _mediator.Send(Arg.Any<DownloadImageCommand>()).Returns(new CommandResult {IsSuccessful = true}); // Act var result = await _sut.Handle(cardImageConsumer, CancellationToken.None); // Assert result.IsSuccessful.Should().BeTrue(); } } }<file_sep>/src/wikia/data/cardsectiondata/src/Presentation/cardsectiondata/Program.cs using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using cardsectiondata.application; using cardsectiondata.application.Configuration; using cardsectiondata.Extensions.WindowsService; using cardsectiondata.infrastructure; using cardsectiondata.Services; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Serilog; namespace cardsectiondata { internal class Program { static async Task Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper; var hostBuilder = CreateHostBuilder(args); var isService = !(Debugger.IsAttached || args.Contains("--console")); if (isService) { var pathToExe = Process.GetCurrentProcess().MainModule?.FileName; var pathToContentRoot = Path.GetDirectoryName(pathToExe); Directory.SetCurrentDirectory(pathToContentRoot); } if (isService) await hostBuilder.RunAsServiceAsync(); else await hostBuilder.RunConsoleAsync(); } private static IHostBuilder CreateHostBuilder(string[] args) { var hostBuilder = new HostBuilder() .ConfigureLogging((hostContext, config) => { config.AddConsole(); config.AddDebug(); }) .ConfigureHostConfiguration(config => { #if DEBUG config.AddEnvironmentVariables(prefix: "ASPNETCORE_"); #else config.AddEnvironmentVariables(); #endif }) .ConfigureAppConfiguration((hostContext, config) => { config.SetBasePath(Directory.GetCurrentDirectory()); config.AddJsonFile("appsettings.json", false, true); config.AddCommandLine(args); #if DEBUG config.AddUserSecrets<Program>(); #endif }) .ConfigureServices((hostContext, services) => { services.AddHttpClient(); services.AddLogging(); //configuration settings services.Configure<AppSettings>(hostContext.Configuration.GetSection(nameof(AppSettings))); services.Configure<RabbitMqSettings>(hostContext.Configuration.GetSection(nameof(RabbitMqSettings))); // hosted service services.AddHostedService<CardSectionDataHostedService>(); services.AddApplicationServices(); services.AddInfrastructureServices(); }) .UseConsoleLifetime() .UseSerilog(); return hostBuilder; } private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs ex) { Log.Logger.Error("Unhandled exception occurred. Exception: {@Exception}", ex); } } } <file_sep>/src/wikia/article/src/Presentation/article.cardinformation/QuartzConfiguration/CardInformationJobFactory.cs using System; using Microsoft.Extensions.DependencyInjection; using Quartz; using Quartz.Spi; namespace article.cardinformation.QuartzConfiguration { public class CardInformationJobFactory : IJobFactory { private readonly IServiceProvider _serviceProvider; public CardInformationJobFactory(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler) { return _serviceProvider.GetRequiredService<IJob>(); } public void ReturnJob(IJob job) { } } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Mappings/Profiles/SubCategoryProfile.cs using AutoMapper; using cardprocessor.application.Dto; using cardprocessor.core.Models.Db; namespace cardprocessor.application.Mappings.Profiles { public class SubCategoryProfile : Profile { public SubCategoryProfile() { CreateMap<SubCategory, SubCategoryDto>() .ForMember(dest => dest.CategoryId, opt => opt.MapFrom(src => src.Category.Id)); } } }<file_sep>/src/wikia/data/cardsectiondata/src/Tests/Unit/cardsectiondata.domain.unit.tests/ArticleListTests/CardSectionProcessorTests.cs using System.Threading.Tasks; using cardsectiondata.core.Models; using cardsectiondata.domain.ArticleList.Processor; using cardsectiondata.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; using wikia.Api; using wikia.Models.Article.Simple; namespace cardsectiondata.domain.unit.tests.ArticleListTests { [TestFixture] [Category(TestType.Unit)] public class CardSectionProcessorTests { private IWikiArticle _wikiArticle; private CardSectionProcessor _sut; [SetUp] public void SetUp() { _wikiArticle = Substitute.For<IWikiArticle>(); _sut = new CardSectionProcessor(_wikiArticle); } [Test] public async Task Given_A_Valid_Article_Should_Return_CardSectionMessage_With_Correct_Title() { // Arrange const string expected = "Call Of The Haunted"; var article = new Article{ Title = "Call Of The Haunted" }; _wikiArticle.Simple(Arg.Any<long>()).Returns(new ContentResult { Sections = new[] { new Section { Title = "Call of the Haunted", Level = 1, Content = new[] { new SectionContent { Type = "list", Elements = new[] { new ListElement { Text = "This card can be searched by \"A Cat of Ill Omen\" and \"The Despair Uranus\"." }, } }, } } } }); // Act var result = await _sut.ProcessItem(article); // Assert result.Name.Should().BeEquivalentTo(expected); } [Test] public async Task Given_A_Valid_Article_Should_Return_CardSectionMessage_ContentList_Containing_1_Item() { // Arrange const int expected = 1; var article = new Article{ Title = "Call Of The Haunted" }; _wikiArticle.Simple(Arg.Any<long>()).Returns(new ContentResult { Sections = new[] { new Section { Title = "Call of the Haunted", Level = 1, Content = new[] { new SectionContent { Type = "list", Elements = new[] { new ListElement { Text = "This card can be searched by \"A Cat of Ill Omen\" and \"The Despair Uranus\"." }, } }, } } } }); // Act var result = await _sut.ProcessItem(article); // Assert result.CardSections.Count.Should().Be(expected); } [Test] public async Task Given_A_Valid_Article_If_It_Contains_A_Section_With_The_Title_References_It_Should_Not_Be_Processed() { // Arrange const int expected = 1; var article = new Article{ Title = "Call Of The Haunted" }; _wikiArticle.Simple(Arg.Any<long>()).Returns(new ContentResult { Sections = new[] { new Section { Title = "Call of the Haunted", Level = 1, Content = new[] { new SectionContent { Type = "list", Elements = new[] { new ListElement { Text = "This card can be searched by \"A Cat of Ill Omen\" and \"The Despair Uranus\"." }, } }, } }, new Section { Title = "References" }, } }); // Act var result = await _sut.ProcessItem(article); // Assert result.CardSections.Count.Should().Be(expected); } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/cardsectionprocessor.domain.unit.tests/ServicesTests/CardTipServiceTests.cs using System.Collections.Generic; using System.Threading.Tasks; using cardsectionprocessor.core.Models.Db; using cardsectionprocessor.domain.Repository; using cardsectionprocessor.domain.Service; using cardsectionprocessor.tests.core; using NSubstitute; using NUnit.Framework; namespace cardsectionprocessor.domain.unit.tests.ServicesTests { [TestFixture] [Category(TestType.Unit)] public class CardTipServiceTests { private ICardTipRepository _cardTipRepository; private CardTipService _sut; [SetUp] public void SetUp() { _cardTipRepository = Substitute.For<ICardTipRepository>(); _sut = new CardTipService(_cardTipRepository); } [Test] public async Task Given_A_CardId_Should_Invoke_DeleteByCardId_Once() { // Arrange const int cardId = 2342; // Act await _sut.DeleteByCardId(cardId); // Assert await _cardTipRepository.Received(1).DeleteByCardId(Arg.Any<long>()); } [Test] public async Task Given_A_Collection_Of_Tips_Should_Invoke_Update_Once() { // Arrange var tipSections = new List<TipSection>(); // Act await _sut.Update(tipSections); // Assert await _cardTipRepository.Received(1).Update(Arg.Any<List<TipSection>>()); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Helpers/Cards/CardHelper.cs using System; using cardprocessor.application.Enums; using cardprocessor.application.Models.Cards.Input; using cardprocessor.core.Models; namespace cardprocessor.application.Helpers.Cards { public static class CardHelper { public static CardInputModel MapCardImageUrl(YugiohCard yugiohCard, CardInputModel cardInputModel) { if (yugiohCard.ImageUrl != null) cardInputModel.ImageUrl = new Uri(yugiohCard.ImageUrl); return cardInputModel; } public static CardInputModel MapBasicCardInformation(YugiohCard yugiohCard, CardInputModel cardInputModel) { cardInputModel.CardType = (YgoCardType?)(Enum.TryParse(typeof(YgoCardType), yugiohCard.CardType, true, out var cardType) ? cardType : null); cardInputModel.CardNumber = long.TryParse(yugiohCard.CardNumber, out var cardNumber) ? cardNumber : (long?)null; cardInputModel.Name = yugiohCard.Name; cardInputModel.Description = yugiohCard.Description; return cardInputModel; } } }<file_sep>/src/wikia/data/cardsectiondata/src/Core/cardsectiondata.core/Processor/IArticleItemProcessor.cs using System.Threading.Tasks; using cardsectiondata.core.Models; namespace cardsectiondata.core.Processor { public interface IArticleItemProcessor { Task<ArticleTaskResult> ProcessItem(Article article); bool Handles(string category); } }<file_sep>/src/wikia/data/banlistdata/src/Core/banlistdata.core/Models/ArticleConsumerResult.cs using banlistdata.core.Exceptions; namespace banlistdata.core.Models { public class ArticleConsumerResult { public bool IsSuccessfullyProcessed { get; set; } public string Article { get; set; } public ArticleException Failed { get; set; } } }<file_sep>/src/wikia/processor/banlistprocessor/src/Infrastructure/banlistprocessor.infrastructure/Repository/CardRepository.cs using System.Threading.Tasks; using banlistprocessor.core.Models.Db; using banlistprocessor.domain.Repository; using banlistprocessor.infrastructure.Database; using Microsoft.EntityFrameworkCore; namespace banlistprocessor.infrastructure.Repository { public class CardRepository : ICardRepository { private readonly YgoDbContext _context; public CardRepository(YgoDbContext context) { _context = context; } public Task<Card> CardByName(string cardName) { return _context .Card .Include(c => c.CardSubCategory) .ThenInclude(sc => sc.SubCategory) .Include(c => c.CardAttribute) .ThenInclude(ca => ca.Attribute) .Include(c => c.CardType) .ThenInclude(ct => ct.Type) .Include(c => c.CardLinkArrow) .ThenInclude(cla => cla.LinkArrow) .AsNoTracking() .SingleOrDefaultAsync(c => c.Name == cardName); } } }<file_sep>/src/wikia/processor/banlistprocessor/src/Infrastructure/banlistprocessor.infrastructure/Repository/BanlistCardRepository.cs using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using banlistprocessor.core.Models.Db; using banlistprocessor.domain.Repository; using banlistprocessor.infrastructure.Database; namespace banlistprocessor.infrastructure.Repository { public class BanlistCardRepository : IBanlistCardRepository { private readonly YgoDbContext _context; public BanlistCardRepository(YgoDbContext context) { _context = context; } public async Task<ICollection<BanlistCard>> Update(long banlistId, IList<BanlistCard> banlistCards) { var existingBanlistCards = _context.BanlistCard.Select(bl => bl).Where(bl => bl.BanlistId == banlistId).ToList(); if (existingBanlistCards.Any()) { _context.BanlistCard.RemoveRange(existingBanlistCards); await _context.SaveChangesAsync(); } await _context.BanlistCard.AddRangeAsync(banlistCards); await _context.SaveChangesAsync(); return banlistCards; } } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Tests/Unit/archetypeprocessor.domain.unit.tests/ProcessorTests/ArchetypeProcessorTests.cs using System.Threading.Tasks; using archetypeprocessor.core.Models; using archetypeprocessor.core.Models.Db; using archetypeprocessor.core.Services; using archetypeprocessor.domain.Messaging; using archetypeprocessor.domain.Processor; using archetypeprocessor.tests.core; using NSubstitute; using NUnit.Framework; namespace archetypeprocessor.domain.unit.tests.ProcessorTests { [TestFixture] [Category(TestType.Unit)] public class ArchetypeProcessorTests { private IArchetypeService _archetypeService; private IArchetypeImageQueueService _archetypeImageQueueService; private ArchetypeProcessor _sut; [SetUp] public void SetUp() { _archetypeService = Substitute.For<IArchetypeService>(); _archetypeImageQueueService = Substitute.For<IArchetypeImageQueueService>(); _sut = new ArchetypeProcessor(_archetypeService, _archetypeImageQueueService); } [Test] public async Task Given_An_ArchetypeMessage_If_Archetype_Is_Not_Found_Should_Invoke_Add_Method() { // Arrange var archetypeMessage = new ArchetypeMessage(); // Act await _sut.Process(archetypeMessage); // Assert await _archetypeService.Received(1).Add(Arg.Any<Archetype>()); } [Test] public async Task Given_An_ArchetypeMessage_If_Archetype_Is_Not_Found_Should_Not_Invoke_Update_Method() { // Arrange var archetypeMessage = new ArchetypeMessage(); // Act await _sut.Process(archetypeMessage); // Assert await _archetypeService.DidNotReceive().Update(Arg.Any<Archetype>()); } [Test] public async Task Given_An_ArchetypeMessage_If_Archetype_Is_Found_Should_Invoke_Update_Method() { // Arrange var archetypeMessage = new ArchetypeMessage(); _archetypeService.ArchetypeById(Arg.Any<long>()).Returns(new Archetype { Id = 42432, Name = "Blue-Eyes"}); // Act await _sut.Process(archetypeMessage); // Assert await _archetypeService.Received(1).Update(Arg.Any<Archetype>()); } [Test] public async Task Given_An_ArchetypeMessage_If_Archetype_Is_Found_Should_Not_Invoke_Add_Method() { // Arrange var archetypeMessage = new ArchetypeMessage(); _archetypeService.ArchetypeById(Arg.Any<long>()).Returns(new Archetype { Id = 42432, Name = "Blue-Eyes"}); // Act await _sut.Process(archetypeMessage); // Assert await _archetypeService.DidNotReceive().Add(Arg.Any<Archetype>()); } [Test] public async Task Given_An_ArchetypeMessage_With_An_ImageUrl_Should_Invoke_Publish_Method() { // Arrange var archetypeMessage = new ArchetypeMessage { ImageUrl = "https://vignette.wikia.nocookie.net/yugioh/images/3/3d/DMx001_Triple_Blue-Eyes.png/revision/latest/scale-to-width-down/350?cb=20140404164917" }; _archetypeService.ArchetypeById(Arg.Any<long>()).Returns(new Archetype { Id = 42432, Name = "Blue-Eyes"}); // Act await _sut.Process(archetypeMessage); // Assert await _archetypeImageQueueService.Received(1).Publish(Arg.Any<DownloadImage>()); } } } <file_sep>/src/wikia/processor/cardsectionprocessor/src/Application/cardsectionprocessor.application/MessageConsumers/CardTipInformation/CardTipInformationConsumer.cs using MediatR; namespace cardsectionprocessor.application.MessageConsumers.CardTipInformation { public class CardTipInformationConsumer : IRequest<CardTipInformationConsumerResult> { public string Message { get; set; } } }<file_sep>/src/wikia/processor/banlistprocessor/src/Core/banlistprocessor.core/Services/IBanlistCardService.cs using System.Collections.Generic; using System.Threading.Tasks; using banlistprocessor.core.Models; using banlistprocessor.core.Models.Db; namespace banlistprocessor.core.Services { public interface IBanlistCardService { Task<ICollection<BanlistCard>> Update(long banlistId, List<YugiohBanlistSection> yugiohBanlistSections); } }<file_sep>/src/wikia/semanticsearch/src/Application/semanticsearch.application/ScheduledTasks/CardSearch/SemanticSearchCardTaskResult.cs namespace semanticsearch.application.ScheduledTasks.CardSearch { public class SemanticSearchCardTaskResult { public bool IsSuccessful { get; set; } } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Validations/Cards/SpellCardValidator.cs using cardprocessor.application.Enums; using cardprocessor.application.Models.Cards.Input; using FluentValidation; namespace cardprocessor.application.Validations.Cards { public class SpellCardValidator : AbstractValidator<CardInputModel> { public SpellCardValidator() { When(c => c.CardType == YgoCardType.Spell, () => { RuleFor(c => c.Name) .Cascade(CascadeMode.StopOnFirstFailure) .CardNameValidator(); }); } } }<file_sep>/src/wikia/data/banlistdata/src/Tests/Unit/banlistdata.domain.unit.tests/BanlistProcessorTests.cs using banlistdata.core.Models; using banlistdata.domain.Processor; using banlistdata.domain.Services.Messaging; using banlistdata.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using wikia.Api; using wikia.Models.Article.Details; using wikia.Models.Article.Simple; namespace banlistdata.domain.unit.tests { [TestFixture] [Category(TestType.Unit)] public class BanlistProcessorTests { private IBanlistDataQueue _banlistDataQueue; private IWikiArticle _wikiArticle; private BanlistProcessor _sut; [SetUp] public void SetUp() { _wikiArticle = Substitute.For<IWikiArticle>(); _banlistDataQueue = Substitute.For<IBanlistDataQueue>(); _sut = new BanlistProcessor(_wikiArticle, _banlistDataQueue, Substitute.For<ILogger<BanlistProcessor>>()); } [Test] public async Task Given_An_Article_If_Not_Published_To_Queue_IsSuccessful_Should_Be_False() { // Arrange var article = new Article(); _wikiArticle.Details(Arg.Any<int>()).Returns(new ExpandedArticleResultSet{ Items = new Dictionary<string, ExpandedArticle> { ["key"] = new ExpandedArticle { Id = 24324, Abstract = "OCG in effect since September 1, 2007." } }}); _wikiArticle.Simple(Arg.Any<long>()).Returns(new ContentResult {Sections = new Section[0]}); _banlistDataQueue.Publish(Arg.Any<ArticleProcessed>()).Returns(new YugiohBanlistCompletion()); // Act var result = await _sut.Process(article); // Assert result.IsSuccessful.Should().BeFalse(); } [Test] public async Task Given_An_Article_If_Published_To_Queue_IsSuccessful_Should_Be_True() { // Arrange var article = new Article(); _wikiArticle.Details(Arg.Any<int>()).Returns(new ExpandedArticleResultSet{ Items = new Dictionary<string, ExpandedArticle> { ["key"] = new ExpandedArticle { Id = 24324, Abstract = "OCG in effect since September 1, 2007." } }}); _wikiArticle.Simple(Arg.Any<long>()).Returns(new ContentResult {Sections = new Section[0]}); _banlistDataQueue.Publish(Arg.Any<ArticleProcessed>()).Returns(new YugiohBanlistCompletion{ IsSuccessful = true}); // Act var result = await _sut.Process(article); // Assert result.IsSuccessful.Should().BeTrue(); } [Test] public async Task Given_An_Article_If_ContentResult_Only_Contains_Sections_With_Title_References_Items_Should_Be_Empty() { // Arrange var article = new Article(); _wikiArticle.Details(Arg.Any<int>()).Returns(new ExpandedArticleResultSet{ Items = new Dictionary<string, ExpandedArticle> { ["key"] = new ExpandedArticle { Id = 24324, Abstract = "OCG in effect since September 1, 2007." } }}); _wikiArticle.Simple(Arg.Any<long>()).Returns(new ContentResult { Sections = new [] { new Section{ Title = "references"}, new Section{ Title = "references"} } }); _banlistDataQueue.Publish(Arg.Any<ArticleProcessed>()).Returns(new YugiohBanlistCompletion{ IsSuccessful = true}); // Act var result = await _sut.Process(article); // Assert result.Banlist.Sections.Should().BeEmpty(); } [Test] public async Task Given_An_Article_Banlist_Sections_Should_not_Contain_Invalid_Characters() { // Arrange var expected = "Forbidden"; var article = new Article(); _wikiArticle.Details(Arg.Any<int>()).Returns(new ExpandedArticleResultSet{ Items = new Dictionary<string, ExpandedArticle> { ["key"] = new ExpandedArticle { Id = 24324, Abstract = "OCG in effect since September 1, 2007." } }}); _wikiArticle.Simple(Arg.Any<long>()).Returns(new ContentResult { Sections = new [] { new Section { Title = "Forbidden 「フィッシュボーグ-ガンナー」", Content = new [] { new SectionContent { Elements = new [] { new ListElement { Text = "Ancient Fairy Dragon" } } } }} } }); _banlistDataQueue.Publish(Arg.Any<ArticleProcessed>()).Returns(new YugiohBanlistCompletion{ IsSuccessful = true}); // Act var result = await _sut.Process(article); // Assert result.Banlist.Sections.First().Title.Should().BeEquivalentTo(expected); } [Test] public void Given_An_Invalid_Article_IsSuccessful_Should_Throw_InvalidOperationException() { // Arrange var article = new Article(); _wikiArticle.Details(Arg.Any<int>()).Returns(new ExpandedArticleResultSet{ Items = new Dictionary<string, ExpandedArticle>()}); // Act Func<Task<ArticleProcessed>> act = () => _sut.Process(article); // Assert act.Should().Throw<InvalidOperationException>(); } } }<file_sep>/src/wikia/data/carddata/src/Core/carddata.core/Models/ArticleConsumerResult.cs using carddata.core.Exceptions; namespace carddata.core.Models { public class ArticleConsumerResult { public bool IsSuccessfullyProcessed { get; set; } public Article Article { get; set; } public ArticleException Failed { get; set; } } }<file_sep>/src/services/Cards.API/src/Infrastructure/Cards.DatabaseMigration/DatabaseMigrationInstaller.cs using System; using System.Data.SqlClient; using System.Reflection; using Cards.DatabaseMigration.Exceptions; using DbUp; using DbUp.Engine; using Microsoft.Extensions.DependencyInjection; using Serilog; namespace Cards.DatabaseMigration { public static class DatabaseMigrationInstaller { public static IServiceCollection AddDatabaseMigrationServices(this IServiceCollection services, string connectionString) { Log.Logger.Information("Executing database migration at {@DatabaseMigrationStartTime}", DateTime.UtcNow); try { var upgradeEngine = DeployChanges.To .SqlDatabase(connectionString) // PreDeployment scripts .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly(), script => script.StartsWith("Cards.DatabaseMigration.Scripts.PreDeployment."), new SqlScriptOptions { RunGroupOrder = 1 }) // Migration scripts .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly(), script => script.StartsWith("Cards.DatabaseMigration.Scripts.Migrations."), new SqlScriptOptions { RunGroupOrder = 2 }) // PostDeployment scripts .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly(), script => script.StartsWith("Cards.DatabaseMigration.PostDeployment."), new SqlScriptOptions { RunGroupOrder = 3 }) .LogToAutodetectedLog() .Build(); EnsureDatabase.For.SqlDatabase(connectionString); var result = upgradeEngine.PerformUpgrade(); if (result.Successful) { Log.Logger.Information("Database migration successfully executed at {@DatabaseMigrationEndTime}!", DateTime.UtcNow); } else { Log.Logger.Fatal(result.Error.Message); throw new DatabaseMigrationException("Database migration failed. Stopping system! Please see the logs!"); } } catch (SqlException ex) { Log.Logger.Fatal("Database migration failed with exception: {@Exception}", ex); throw new DatabaseMigrationException("Database migration failed. Stopping system! Please see the logs!", ex); } return services; } } }<file_sep>/src/services/Cards.API/src/Application/Cards.Application/Configuration/ExchangeSetting.cs using System.Collections.Generic; namespace Cards.Application.Configuration { public record ExchangeSetting { public Dictionary<string, string> Headers { get; init; } public byte PersistentMode { get; init; } } }<file_sep>/src/wikia/processor/cardprocessor/src/Domain/cardprocessor.domain/Services/SubCategoryService.cs using System.Collections.Generic; using System.Threading.Tasks; using cardprocessor.core.Models.Db; using cardprocessor.core.Services; using cardprocessor.domain.Repository; namespace cardprocessor.domain.Services { public class SubCategoryService : ISubCategoryService { private readonly ISubCategoryRepository _subCategoryRepository; public SubCategoryService(ISubCategoryRepository subCategoryRepository) { _subCategoryRepository = subCategoryRepository; } public Task<List<SubCategory>> AllSubCategories() { return _subCategoryRepository.AllSubCategories(); } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Infrastructure/cardsectionprocessor.infrastructure/Repository/CardRepository.cs using System.Threading.Tasks; using cardsectionprocessor.core.Models.Db; using cardsectionprocessor.domain.Repository; using cardsectionprocessor.infrastructure.Database; using Microsoft.EntityFrameworkCore; namespace cardsectionprocessor.infrastructure.Repository { public class CardRepository : ICardRepository { private readonly YgoDbContext _context; public CardRepository(YgoDbContext context) { _context = context; } public Task<Card> CardByName(string name) { return _context .Card .Include(c => c.CardSubCategory) .ThenInclude(sc => sc.SubCategory) .Include(c => c.CardAttribute) .ThenInclude(ca => ca.Attribute) .Include(c => c.CardType) .ThenInclude(ct => ct.Type) .Include(c => c.CardLinkArrow) .ThenInclude(cla => cla.LinkArrow) .AsNoTracking() .SingleOrDefaultAsync(c => c.Name == name); } } }<file_sep>/src/wikia/semanticsearch/src/Tests/Integration/semanticsearch.infrastructure.integration.tests/WebPageTests/SemanticCardSearchResultsWebPageTests/NameTests.cs using System; using System.Linq; using FluentAssertions; using NUnit.Framework; using semanticsearch.infrastructure.WebPage; namespace semanticsearch.infrastructure.integration.tests.WebPageTests.SemanticCardSearchResultsWebPageTests { [TestFixture] public class NameTests { private SemanticCardSearchResultsWebPage _sut; [SetUp] public void SetUp() { _sut = new SemanticCardSearchResultsWebPage(); } [Test] public void Given_A_Html_Table_Row_Should_Extract_The_First_Card_Name_Which_Is_MegasonicEye() { // Arrange const string expected = "Megasonic Eye"; const string url = "https://yugioh.fandom.com/wiki/Special:Ask?limit=500&offset=500&q=%5B%5BClass+1%3A%3AOfficial%5D%5D+%5B%5BCard+type%3A%3ANormal+Monster%5D%5D&p=format%3Dbroadtable%2Flink%3Dall%2Fheaders%3Dshow%2Fsearchlabel%3D%E2%80%A6-20further-20results%2Fclass%3D-20sortable-20wikitable-20smwtable-20card-2Dlist&po=%3FJapanese+name%0A%3FRank%0A%3FLevel%0A%3FAttribute%0A%3FType%0A%3FMonster+type%0A%3FATK+string%3DATK%0A%3FDEF+string%3DDEF%0A&sort=&order=&eq=yes#search"; var semanticSearchResultsWebPage = new SemanticSearchResultsWebPage(new HtmlWebPage()); semanticSearchResultsWebPage.Load(url); // Act var result = _sut.Name(semanticSearchResultsWebPage.TableRows.First()); // Assert result.Should().Be(expected); } [Test] public void Given_A_Html_Table_Row_Should_Extract_The_First_Card_MegasonicEye_Profile_WebPage_Url() { // Arrange const string expected = "https://yugioh.fandom.com/wiki/Megasonic_Eye"; const string url = "https://yugioh.fandom.com/wiki/Special:Ask?limit=500&offset=500&q=%5B%5BClass+1%3A%3AOfficial%5D%5D+%5B%5BCard+type%3A%3ANormal+Monster%5D%5D&p=format%3Dbroadtable%2Flink%3Dall%2Fheaders%3Dshow%2Fsearchlabel%3D%E2%80%A6-20further-20results%2Fclass%3D-20sortable-20wikitable-20smwtable-20card-2Dlist&po=%3FJapanese+name%0A%3FRank%0A%3FLevel%0A%3FAttribute%0A%3FType%0A%3FMonster+type%0A%3FATK+string%3DATK%0A%3FDEF+string%3DDEF%0A&sort=&order=&eq=yes#search"; var semanticSearchResultsWebPage = new SemanticSearchResultsWebPage(new HtmlWebPage()); semanticSearchResultsWebPage.Load(url); // Act var result = _sut.Url(semanticSearchResultsWebPage.TableRows.First(), new Uri(url)); // Assert result.Should().Be(expected); } } }<file_sep>/src/wikia/data/carddata/src/Domain/carddata.domain/WebPages/Cards/ICardWebPage.cs using System; using carddata.core.Models; using HtmlAgilityPack; namespace carddata.domain.WebPages.Cards { public interface ICardWebPage { YugiohCard GetYugiohCard(string url); YugiohCard GetYugiohCard(Uri url); ArticleProcessed GetYugiohCard(Article article); YugiohCard GetYugiohCard(HtmlDocument htmlDocument); } }<file_sep>/src/wikia/data/cardsectiondata/src/Domain/cardsectiondata.domain/ArticleList/Item/CardTriviaItemProcessor.cs using cardsectiondata.core.Constants; using cardsectiondata.core.Models; using cardsectiondata.core.Processor; using cardsectiondata.domain.Services.Messaging; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace cardsectiondata.domain.ArticleList.Item { public class CardTriviaItemProcessor : IArticleItemProcessor { private readonly ICardSectionProcessor _cardSectionProcessor; private readonly IEnumerable<IQueue> _queues; public CardTriviaItemProcessor(ICardSectionProcessor cardSectionProcessor, IEnumerable<IQueue> queues) { _cardSectionProcessor = cardSectionProcessor; _queues = queues; } public async Task<ArticleTaskResult> ProcessItem(Article article) { var response = new ArticleTaskResult { Article = article }; var cardSectionMessage = await _cardSectionProcessor.ProcessItem(article); await _queues.Single(q => q.Handles(ArticleCategory.CardTrivia)).Publish(cardSectionMessage); return response; } public bool Handles(string category) { return category == ArticleCategory.CardTrivia; } } }<file_sep>/src/wikia/processor/cardprocessor/src/Domain/cardprocessor.domain/Services/CardService.cs using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using cardprocessor.core.Models; using cardprocessor.core.Models.Db; using cardprocessor.core.Services; using cardprocessor.core.Strategies; using cardprocessor.domain.Repository; namespace cardprocessor.domain.Services { public class CardService : ICardService { private readonly IEnumerable<ICardTypeStrategy> _cardTypeStrategies; private readonly ICardRepository _cardRepository; public CardService(IEnumerable<ICardTypeStrategy> cardTypeStrategies, ICardRepository cardRepository) { _cardTypeStrategies = cardTypeStrategies; _cardRepository = cardRepository; } public async Task<Card> Add(CardModel cardModel) { var handler = _cardTypeStrategies.Single(cts => cts.Handles(cardModel.CardType)); return await handler.Add(cardModel); } public async Task<Card> Update(CardModel cardModel) { var handler = _cardTypeStrategies.Single(cts => cts.Handles(cardModel.CardType)); return await handler.Update(cardModel); } public Task<Card> CardById(long cardId) { return _cardRepository.CardById(cardId); } public Task<Card> CardByName(string name) { return _cardRepository.CardByName(name); } public Task<bool> CardExists(long id) { return _cardRepository.CardExists(id); } } }<file_sep>/src/wikia/data/archetypedata/src/Tests/Unit/archetypedata.infrastructure.unit.tests/WebPagesTests/ArchetypeWebPageTests/ArchetypeThumbnailTests.cs using System.Collections.Generic; using System.Threading.Tasks; using archetypedata.application.Configuration; using archetypedata.domain.WebPages; using archetypedata.infrastructure.WebPages; using archetypedata.tests.core; using FluentAssertions; using Microsoft.Extensions.Options; using NSubstitute; using NUnit.Framework; using wikia.Models.Article.Details; namespace archetypedata.infrastructure.unit.tests.WebPagesTests.ArchetypeWebPageTests { [TestFixture] [Category(TestType.Unit)] public class ArchetypeThumbnailTests { private ArchetypeWebPage _sut; private IHtmlWebPage _htmlWebPage; private IArchetypeThumbnail _archetypeThumbnail; [SetUp] public void SetUp() { _htmlWebPage = Substitute.For<IHtmlWebPage>(); _archetypeThumbnail = Substitute.For<IArchetypeThumbnail>(); _sut = new ArchetypeWebPage(Substitute.For<IOptions<AppSettings>>(), _htmlWebPage, _archetypeThumbnail); } [Test] public void Given_A_Thumbnail_Url_And_A_Archetype_Web_Page_Url_If_Thumbnail_Url_Is_NullOrEmpty_Should_Invoke_ArchetypeThumbnailFromWebPage_Method_Once() { // Arrange const string articleUrl = "https://yugioh.fandom.com/wiki/Tentacluster"; // Act _sut.ArchetypeThumbnail(string.Empty, articleUrl); // Assert _archetypeThumbnail.Received(1).FromWebPage(Arg.Is(articleUrl)); } [Test] public void Given_A_Thumbnail_Url_And_A_Archetype_Web_Page_Url_If_Thumbnail_Url_Is_Not_NullOrEmpty_Should_Return_Thumbnail_Url() { // Arrange const string thumbnailUrl = "https://static.wikia.nocookie.net/yugioh/images/7/7c/Tentacluster.png"; const string articleUrl = "https://yugioh.fandom.com/wiki/Tentacluster"; // Act var result = _sut.ArchetypeThumbnail(thumbnailUrl, articleUrl); // Assert result.Should().BeEquivalentTo(thumbnailUrl); } [Test] public void Given_ArticleDetails_And_A_Archetype_Url_Should_Invoke_ArchetypeType_FromArticleDetails_Method_Once() { // Arrange var articleDetails = new KeyValuePair<string, ExpandedArticle>("666747", new ExpandedArticle { Thumbnail = "https://static.wikia.nocookie.net/yugioh/images/7/7c/Tentacluster.png/revision/latest/smart/width/200/height/200?cb=20170830132740" }); const string archetypeWebPageUrl = "https://yugioh.fandom.com/wiki/Tentacluster"; // Act _sut.ArchetypeThumbnail(articleDetails, archetypeWebPageUrl); // Assert _archetypeThumbnail.Received(1).FromArticleDetails(Arg.Is(articleDetails)); } [Test] public async Task Given_An_ArticleId_And_A_Archetype_Url_Should_Invoke_ArchetypeType_FromArticleId_Method_Once() { // Arrange const int articleId = 666747; const string archetypeWebPageUrl = "https://yugioh.fandom.com/wiki/Tentacluster"; // Act await _sut.ArchetypeThumbnail(articleId, archetypeWebPageUrl); // Assert await _archetypeThumbnail.Received(1).FromArticleId(Arg.Is(articleId)); } } }<file_sep>/src/wikia/processor/banlistprocessor/src/Core/banlistprocessor.core/Services/IBanlistService.cs using System.Threading.Tasks; using banlistprocessor.core.Models; using banlistprocessor.core.Models.Db; namespace banlistprocessor.core.Services { public interface IBanlistService { Task<bool> BanlistExist(int id); Task<Banlist> Add(YugiohBanlist yugiohBanlist); Task<Banlist> Update(YugiohBanlist yugiohBanlist); } }<file_sep>/src/wikia/processor/banlistprocessor/src/Application/banlistprocessor.application/ApplicationInstaller.cs using System.Reflection; using AutoMapper; using banlistprocessor.core.Services; using banlistprocessor.domain.Services; using MediatR; using Microsoft.Extensions.DependencyInjection; namespace banlistprocessor.application { public static class ApplicationInstaller { public static IServiceCollection AddApplicationServices(this IServiceCollection services) { services .AddCqrs() .AddDomainServices() .AddAutoMapper(); return services; } private static IServiceCollection AddCqrs(this IServiceCollection services) { services.AddMediatR(typeof(ApplicationInstaller).GetTypeInfo().Assembly); return services; } private static IServiceCollection AddDomainServices(this IServiceCollection services) { services.AddTransient<IBanlistService, BanlistService>(); services.AddTransient<IBanlistCardService, BanlistCardService>(); return services; } private static IServiceCollection AddValidation(this IServiceCollection services) { return services; } } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Infrastructure/archetypeprocessor.infrastructure/Messaging/ArchetypeImageQueueService.cs using System.Threading.Tasks; using archetypeprocessor.application.Configuration; using archetypeprocessor.core.Models; using archetypeprocessor.domain.Messaging; using Microsoft.Extensions.Options; namespace archetypeprocessor.infrastructure.Messaging { public class ArchetypeImageQueueService : IArchetypeImageQueueService { private readonly IOptions<AppSettings> _appSettingsOptions; private readonly IImageQueueService _imageQueueService; public ArchetypeImageQueueService(IOptions<AppSettings> appSettingsOptions, IImageQueueService imageQueueService) { _appSettingsOptions = appSettingsOptions; _imageQueueService = imageQueueService; } public async Task Publish(DownloadImage downloadImage) { downloadImage.ImageFolderPath = _appSettingsOptions.Value.ArchetypeImageFolderPath; await _imageQueueService.Publish(downloadImage); } } }<file_sep>/src/wikia/semanticsearch/src/Tests/Unit/semanticsearch.domain.unit.tests/SemanticSearchProcessorTests.cs using FluentAssertions; using NSubstitute; using NUnit.Framework; using semanticsearch.core.Exceptions; using semanticsearch.core.Model; using semanticsearch.core.Search; using semanticsearch.domain.Search; using semanticsearch.tests.core; using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace semanticsearch.domain.unit.tests { [TestFixture] [Category(TestType.Unit)] public class SemanticSearchProcessorTests { private ISemanticSearchProducer _semanticSearchProducer; private ISemanticSearchConsumer _semanticSearchConsumer; private SemanticSearchProcessor _sut; [SetUp] public void SetUp() { _semanticSearchProducer = Substitute.For<ISemanticSearchProducer>(); _semanticSearchConsumer = Substitute.For<ISemanticSearchConsumer>(); _sut = new SemanticSearchProcessor(Substitute.For<ILogger<SemanticSearchProcessor>>(), _semanticSearchProducer, _semanticSearchConsumer); } [Test] public async Task Given_A_Valid_Url_Producer_Method_Should_Be_Invoked_Once() { // Arrange const int expected = 1; const string url = "http://yugioh.fandom.com/index.php?title=Special%3AAsk&q=%5B%5BClass+1%3A%3AOfficial%5D%5D+%5B%5BCard+type%3A%3ANormal+Monster%5D%5D"; // Act var _ = await _sut.ProcessUrl(url); // Assert _semanticSearchProducer.Received(expected).Producer(Arg.Is(url)); } [Test] public async Task Given_A_Valid_Url_Process_Method_Should_Be_Invoked_3_Times() { // Arrange const int expected = 3; const string url = "http://yugioh.fandom.com/index.php?title=Special%3AAsk&q=%5B%5BClass+1%3A%3AOfficial%5D%5D+%5B%5BCard+type%3A%3ANormal+Monster%5D%5D"; _semanticSearchProducer.Producer(Arg.Is(url)) .GetEnumerator() .Returns ( new List<SemanticCard> { new(), new(), new() }.GetEnumerator() ); _semanticSearchConsumer.Process(Arg.Any<SemanticCard>()).Returns ( new SemanticCardPublishResult { Card = new SemanticCard(), IsSuccessful = true } ); // Act var _ = await _sut.ProcessUrl(url); // Assert await _semanticSearchConsumer.Received(expected).Process(Arg.Any<SemanticCard>()); } [Test] public async Task Given_A_Valid_Url_Number_Of_UnSuccessfully_Processed_Semantic_Cards_Should_Be_1() { // Arrange const int expected = 1; const string url = "http://yugioh.fandom.com/index.php?title=Special%3AAsk&q=%5B%5BClass+1%3A%3AOfficial%5D%5D+%5B%5BCard+type%3A%3ANormal+Monster%5D%5D"; _semanticSearchProducer.Producer(Arg.Is(url)) .GetEnumerator() .Returns ( new List<SemanticCard> { new(), new(), new() }.GetEnumerator() ); _semanticSearchConsumer.Process(Arg.Any<SemanticCard>()).Returns ( new SemanticCardPublishResult { Card = new SemanticCard(), IsSuccessful = true }, new SemanticCardPublishResult { Card = new SemanticCard(), IsSuccessful = true }, new SemanticCardPublishResult { Card = new SemanticCard(), Exception = new SemanticCardPublishException { Url = url, Exception = new ArgumentNullException(nameof(url), "fail")} } ); // Act var result = await _sut.ProcessUrl(url); // Assert result.Failed.Should().NotBeNullOrEmpty().And.HaveCount(expected); } [Test] public async Task Given_A_Valid_Url_Number_Of_Successfully_Processed_Semantic_Cards_Should_Be_2() { // Arrange const int expected = 2; const string url = "http://yugioh.fandom.com/index.php?title=Special%3AAsk&q=%5B%5BClass+1%3A%3AOfficial%5D%5D+%5B%5BCard+type%3A%3ANormal+Monster%5D%5D"; _semanticSearchProducer.Producer(Arg.Is(url)) .GetEnumerator() .Returns ( new List<SemanticCard> { new(), new(), new() }.GetEnumerator() ); _semanticSearchConsumer.Process(Arg.Any<SemanticCard>()).Returns ( new SemanticCardPublishResult { Card = new SemanticCard(), IsSuccessful = true }, new SemanticCardPublishResult { Card = new SemanticCard(), IsSuccessful = true }, new SemanticCardPublishResult { Card = new SemanticCard() } ); // Act var result = await _sut.ProcessUrl(url); // Assert result.Processed.Should().Be(expected); } [Test] public async Task Given_A_Url_IsSuccessful_Should_Be_True() { // Arrange const string url = "http://yugioh.fandom.com/index.php?title=Special%3AAsk&q=%5B%5BClass+1%3A%3AOfficial%5D%5D+%5B%5BCard+type%3A%3ANormal+Monster%5D%5D"; // Act var result = await _sut.ProcessUrl(url); // Assert result.IsSuccessful.Should().BeTrue(); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Infrastructure/cardprocessor.infrastructure/InfrastructureInstaller.cs using cardprocessor.domain.Queues.Cards; using cardprocessor.domain.Repository; using cardprocessor.infrastructure.Database; using cardprocessor.infrastructure.Repository; using cardprocessor.infrastructure.Services.Messaging.Cards; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; namespace cardprocessor.infrastructure { public static class InfrastructureInstaller { public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, string connectionString) { services.AddMessagingServices(); services.AddRepositories(); services.AddYgoDatabase(connectionString); return services; } public static IServiceCollection AddYgoDatabase(this IServiceCollection services, string connectionString) { //services.AddDbContextPool<YgoDbContext>(c => c.UseSqlServer(connectionString)); services.AddDbContext<YgoDbContext>(c => c.UseSqlServer(connectionString), ServiceLifetime.Transient); return services; } public static IServiceCollection AddMessagingServices(this IServiceCollection services) { services.AddTransient<ICardImageQueue, CardImageQueue>(); return services; } public static IServiceCollection AddRepositories(this IServiceCollection services) { services.AddTransient<ICategoryRepository, CategoryRepository>(); services.AddTransient<ICardRepository, CardRepository>(); services.AddTransient<ISubCategoryRepository, SubCategoryRepository>(); services.AddTransient<ITypeRepository, TypeRepository>(); services.AddTransient<ILinkArrowRepository, LinkArrowRepository>(); services.AddTransient<IAttributeRepository, AttributeRepository>(); services.AddTransient<ILimitRepository, LimitRepository>(); return services; } } }<file_sep>/src/wikia/article/src/Domain/article.domain/Banlist/DataSource/IBanlistUrlDataSource.cs using System.Collections.Generic; using article.core.Enums; namespace article.domain.Banlist.DataSource { public interface IBanlistUrlDataSource { IDictionary<int, List<int>> GetBanlists(BanlistType banlistType, string banlistUrl); } }<file_sep>/src/wikia/processor/imageprocessor/src/Application/imageprocessor.application/MessageConsumers/YugiohImage/ImageConsumerResult.cs using System; namespace imageprocessor.application.MessageConsumers.YugiohImage { public class ImageConsumerResult { public bool IsSuccessful { get; set; } public string Errors { get; set; } public Exception Exception { get; set; } } }<file_sep>/src/wikia/data/banlistdata/src/Core/banlistdata.core/Exceptions/ArticleException.cs using System; namespace banlistdata.core.Exceptions { public class ArticleException { public string Article { get; set; } public Exception Exception { get; set; } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/cardsectionprocessor.application.unit.tests/CardRulingInformationConsumerHandlerTests.cs using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using cardsectionprocessor.application.MessageConsumers.CardInformation; using cardsectionprocessor.application.MessageConsumers.CardRulingInformation; using cardsectionprocessor.tests.core; using FluentAssertions; using MediatR; using NSubstitute; using NUnit.Framework; namespace cardsectionprocessor.application.unit.tests { [TestFixture] [Category(TestType.Unit)] public class CardRulingInformationConsumerHandlerTests { private IMediator _mediator; private CardRulingInformationConsumerHandler _sut; [SetUp] public void SetUp() { _mediator = Substitute.For<IMediator>(); _sut = new CardRulingInformationConsumerHandler(_mediator); } [Test] public async Task Given_An_Invalid_CardRulingInformationConsumer_IsSuccessful_Should_Be_False() { // Arrange var cardRulingInformationConsumer = new CardRulingInformationConsumer(); _mediator.Send(Arg.Any<CardInformationConsumer>(), Arg.Any<CancellationToken>()).Returns(new CardInformationConsumerResult { Errors = new List<string> { "Something went horriblely wrong." }}); // Act var result = await _sut.Handle(cardRulingInformationConsumer, CancellationToken.None); // Assert result.IsSuccessful.Should().BeFalse(); } [Test] public async Task Given_An_Invalid_CardRulingInformationConsumer_Errors_List_Should_Not_Be_Null_Or_Empty() { // Arrange var cardRulingInformationConsumer = new CardRulingInformationConsumer(); _mediator.Send(Arg.Any<CardInformationConsumer>(), Arg.Any<CancellationToken>()).Returns(new CardInformationConsumerResult { Errors = new List<string> { "Something went horriblely wrong." } }); // Act var result = await _sut.Handle(cardRulingInformationConsumer, CancellationToken.None); // Assert result.Errors.Should().NotBeNullOrEmpty(); } [Test] public async Task Given_A_Valid_CardRulingInformationConsumer_IsSuccessful_Should_Be_True() { // Arrange var cardRulingInformationConsumer = new CardRulingInformationConsumer { Message = "{\"Id\":703544,\"CorrelationId\":\"3e2bf3ca-d903-440c-8cd5-be61c95ae1fc\",\"Title\":\"Tenyi\",\"Url\":\"https://yugioh.fandom.com/wiki/Card_Ruling:Tenyi\"}" }; _mediator.Send(Arg.Any<CardInformationConsumer>(), Arg.Any<CancellationToken>()).Returns( new CardInformationConsumerResult()); // Act var result = await _sut.Handle(cardRulingInformationConsumer, CancellationToken.None); // Assert result.IsSuccessful.Should().BeTrue(); } [Test] public async Task Given_A_Valid_CardRulingInformationConsumer_Should_Execute_Send_Method_Once() { // Arrange var cardRulingInformationConsumer = new CardRulingInformationConsumer { Message = "{\"Id\":703544,\"CorrelationId\":\"3e2bf3ca-d903-440c-8cd5-be61c95ae1fc\",\"Title\":\"Tenyi\",\"Url\":\"https://yugioh.fandom.com/wiki/Card_Ruling:Tenyi\"}" }; _mediator.Send(Arg.Any<CardInformationConsumer>(), Arg.Any<CancellationToken>()).Returns(new CardInformationConsumerResult()); // Act await _sut.Handle(cardRulingInformationConsumer, CancellationToken.None); // Assert await _mediator.Received(1).Send(Arg.Any<CardInformationConsumer>(), Arg.Any<CancellationToken>()); } [Test] public async Task Given_A_Valid_CardRulingInformationConsumer_If_Not_Processed_Successfully_Errors_Should_Not_Be_Null_Or_Empty() { // Arrange var cardInformationConsumer = new CardRulingInformationConsumer { Message = "{\"Id\":703544,\"CorrelationId\":\"3e2bf3ca-d903-440c-8cd5-be61c95ae1fc\",\"Title\":\"Tenyi\",\"Url\":\"https://yugioh.fandom.com/wiki/Card_Trivia:Tenyi\"}" }; _mediator.Send(Arg.Any<CardInformationConsumer>(), Arg.Any<CancellationToken>()).Returns(new CardInformationConsumerResult {Errors = new List<string> {"Something went horribly wrong"}}); // Act var result = await _sut.Handle(cardInformationConsumer, CancellationToken.None); // Assert result.Errors.Should().NotBeNullOrEmpty(); } } } <file_sep>/src/wikia/processor/cardsectionprocessor/src/Application/cardsectionprocessor.application/Configuration/QueueSetting.cs using System.Collections.Generic; namespace cardsectionprocessor.application.Configuration { public class QueueSetting { public Dictionary<string, string> Headers { get; set; } } }<file_sep>/src/wikia/semanticsearch/src/Application/semanticsearch.application/Configuration/AppSettings.cs using System.Collections.Generic; namespace semanticsearch.application.Configuration { public class AppSettings { public Dictionary<string, string> CardSearchUrls { get; set; } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Domain/cardsectionprocessor.domain/Repository/ICardTriviaRepository.cs using System.Collections.Generic; using System.Threading.Tasks; using cardsectionprocessor.core.Models.Db; namespace cardsectionprocessor.domain.Repository { public interface ICardTriviaRepository { Task DeleteByCardId(long id); Task Update(List<TriviaSection> triviaSections); } }<file_sep>/src/wikia/semanticsearch/src/Tests/Integration/semanticsearch.infrastructure.integration.tests/WebPageTests/HtmlWebPageTests/LoadTests.cs using FluentAssertions; using NUnit.Framework; using semanticsearch.infrastructure.WebPage; using semanticsearch.tests.core; namespace semanticsearch.infrastructure.integration.tests.WebPageTests.HtmlWebPageTests { [TestFixture] [Category(TestType.Integration)] public class LoadTests { private HtmlWebPage _sut; [SetUp] public void SetUp() { _sut = new HtmlWebPage(); } [Test] public void Given_A_WebPage_Url_Should_Load_WebPage_To_HtmlDocument() { // Arrange const string url = "https://www.google.com/"; // Act var result = _sut.Load(url); // Assert result.Should().NotBeNull(); } } }<file_sep>/src/wikia/article/src/Tests/Unit/article.infrastructure.unit.tests/ServicesTests/MessagingTests/CardsTests/CardArticleQueueTests/PublishTests.cs using article.core.Models; using article.domain.Services.Messaging; using article.domain.Settings; using article.infrastructure.Services.Messaging.Cards; using article.tests.core; using Microsoft.Extensions.Options; using NSubstitute; using NUnit.Framework; using System.Threading.Tasks; using wikia.Models.Article.AlphabeticalList; namespace article.infrastructure.unit.tests.ServicesTests.MessagingTests.CardsTests.CardArticleQueueTests { [TestFixture] [Category(TestType.Unit)] public class PublishTests { private CardArticleQueue _sut; private IQueue<Article> _queue; [SetUp] public void SetUp() { _queue = Substitute.For<IQueue<Article>>(); _sut = new CardArticleQueue(Substitute.For<IOptions<AppSettings>>(), _queue); } [Test] public async Task Given_An_UnexpandedArticle_Should_Invoke_Publish_Method_Once() { // Arrange const int expected = 1; var unexpandedArticle = new UnexpandedArticle(); // Act await _sut.Publish(unexpandedArticle); // Assert await _queue.Received(expected).Publish(Arg.Is(unexpandedArticle)); } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/cardsectionprocessor.domain.unit.tests/ServicesTests/CardTriviaServiceTests.cs using System.Collections.Generic; using System.Threading.Tasks; using cardsectionprocessor.core.Models.Db; using cardsectionprocessor.domain.Repository; using cardsectionprocessor.domain.Service; using cardsectionprocessor.tests.core; using NSubstitute; using NUnit.Framework; namespace cardsectionprocessor.domain.unit.tests.ServicesTests { [TestFixture] [Category(TestType.Unit)] public class CardTriviaServiceTests { private ICardTriviaRepository _cardTriviaRepository; private CardTriviaService _sut; [SetUp] public void SetUp() { _cardTriviaRepository = Substitute.For<ICardTriviaRepository>(); _sut = new CardTriviaService(_cardTriviaRepository); } [Test] public async Task Given_A_CardId_Should_Invoke_DeleteByCardId_Once() { // Arrange const int cardId = 2342; // Act await _sut.DeleteByCardId(cardId); // Assert await _cardTriviaRepository.Received(1).DeleteByCardId(Arg.Any<long>()); } [Test] public async Task Given_A_Collection_Of_Rulings_Should_Invoke_Update_Once() { // Arrange var triviaSections = new List<TriviaSection>(); // Act await _sut.Update(triviaSections); // Assert await _cardTriviaRepository.Received(1).Update(Arg.Any<List<TriviaSection>>()); } } }<file_sep>/src/wikia/processor/banlistprocessor/src/Presentation/banlistprocessor/DbConstants.cs namespace banlistprocessor { internal static class DbConstants { public const string YgoDatabase = "ygo"; } }<file_sep>/src/wikia/article/src/Tests/Unit/article.domain.unit.tests/BanlistProcessorTests.cs using System.Collections.Generic; using System.Threading.Tasks; using article.core.ArticleList.Processor; using article.core.Enums; using article.core.Models; using article.domain.Banlist.DataSource; using article.domain.Banlist.Processor; using article.tests.core; using FluentAssertions; using Microsoft.Extensions.Logging; using NSubstitute; using NUnit.Framework; using wikia.Models.Article.AlphabeticalList; namespace article.domain.unit.tests { [TestFixture] [Category(TestType.Unit)] public class BanlistProcessorTests { private IBanlistUrlDataSource _banlistUrlDataSource; private IArticleProcessor _articleProcessor; private ILogger<BanlistProcessor> _logger; private BanlistProcessor _sut; [SetUp] public void SetUp() { _banlistUrlDataSource = Substitute.For<IBanlistUrlDataSource>(); _articleProcessor = Substitute.For<IArticleProcessor>(); _logger = Substitute.For<ILogger<BanlistProcessor>>(); _sut = new BanlistProcessor ( _banlistUrlDataSource, _articleProcessor, _logger ); } [Test] public async Task Given_A_banlistType_Should_Invoke_Process_Method_Twice() { // Arrange const int expected = 2; _banlistUrlDataSource .GetBanlists(Arg.Any<BanlistType>(), Arg.Any<string>()) .Returns ( new Dictionary<int, List<int>> { [2017] = new List<int> {1, 2} } ); _articleProcessor .Process(Arg.Any<string>(), Arg.Any<UnexpandedArticle>()) .Returns(new ArticleTaskResult {IsSuccessfullyProcessed = true}); // Act await _sut.Process(BanlistType.Tcg); // Assert await _articleProcessor.Received(expected).Process(Arg.Any<string>(), Arg.Any<UnexpandedArticle>()); } [Test] public async Task Given_A_banlistType_Should_Invoke_GetBanlists_Method_Once() { // Arrange const int expected = 1; _banlistUrlDataSource .GetBanlists(Arg.Any<BanlistType>(), Arg.Any<string>()) .Returns ( new Dictionary<int, List<int>> { [2017] = new List<int> {1, 2} } ); _articleProcessor .Process(Arg.Any<string>(), Arg.Any<UnexpandedArticle>()) .Returns(new ArticleTaskResult {IsSuccessfullyProcessed = true}); // Act await _sut.Process(BanlistType.Tcg); // Assert _banlistUrlDataSource.Received(expected).GetBanlists(Arg.Any<BanlistType>(), Arg.Any<string>()); } [Test] public async Task Given_A_banlistType_Should_Return_All_Banlists() { // Arrange const int expected = 2; _banlistUrlDataSource .GetBanlists(Arg.Any<BanlistType>(), Arg.Any<string>()) .Returns ( new Dictionary<int, List<int>> { [2017] = new List<int> {1, 2} } ); _articleProcessor .Process(Arg.Any<string>(), Arg.Any<UnexpandedArticle>()) .Returns(new ArticleTaskResult {IsSuccessfullyProcessed = true}); // Act var result = await _sut.Process(BanlistType.Tcg); // Assert result.Processed.Should().Be(expected); } } }<file_sep>/src/wikia/data/banlistdata/README.md ![alt text](https://fablecode.visualstudio.com/Yugioh%20Insight/_apis/build/status/Build-BanlistData "Visual studio team services build status") # Banlist Data Amalgamates latest banlist information from different sources. <file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Mappings/Profiles/LinkArrowProfile.cs using AutoMapper; using cardprocessor.application.Dto; using cardprocessor.core.Models.Db; namespace cardprocessor.application.Mappings.Profiles { public class LinkArrowProfile : Profile { public LinkArrowProfile() { CreateMap<LinkArrow, LinkArrowDto>(); } } }<file_sep>/src/wikia/data/carddata/src/Core/carddata.core/Processor/IArticleDataFlow.cs using System.Threading.Tasks; using carddata.core.Models; namespace carddata.core.Processor { public interface IArticleDataFlow { Task<ArticleCompletion> ProcessDataFlow(Article article); } }<file_sep>/src/wikia/processor/cardprocessor/src/Core/cardprocessor.core/Models/CardImageCompletion.cs using System; using System.Collections.Generic; namespace cardprocessor.core.Models { public class CardImageCompletion { public bool IsSuccessful { get; set; } public List<string> Errors { get; set; } public Exception Exception { get; set; } } }<file_sep>/src/wikia/data/carddata/src/Tests/Unit/carddata.domain.unit.tests/ArticleProcessorTests.cs using carddata.core.Models; using carddata.core.Processor; using carddata.domain.Exceptions; using carddata.domain.Processor; using carddata.tests.core; using FluentAssertions; using Microsoft.Extensions.Logging; using NSubstitute; using NSubstitute.ExceptionExtensions; using NUnit.Framework; using System.Threading.Tasks; namespace carddata.domain.unit.tests { [TestFixture] [Category(TestType.Unit)] public class ArticleProcessorTests { private IArticleDataFlow _articleDataFlow; private ArticleProcessor _sut; [SetUp] public void SetUp() { _articleDataFlow = Substitute.For<IArticleDataFlow>(); _sut = new ArticleProcessor(_articleDataFlow, Substitute.For<ILogger<ArticleProcessed>>()); } [Test] public async Task Given_An_Article_If_Processed_And_Errors_Do_Not_Occur_IsSuccessfullyProcessed_Should_Be_True() { // Arrange var article = new Article(); _articleDataFlow.ProcessDataFlow(article).Returns(new ArticleCompletion { IsSuccessful = true}); // Act var result = await _sut.Process(article); // Assert result.IsSuccessfullyProcessed.Should().BeTrue(); } [Test] public async Task Given_An_Article_If_Processed_And_Errors_Occur_IsSuccessfullyProcessed_Should_Be_False() { // Arrange var article = new Article(); _articleDataFlow.ProcessDataFlow(article).Returns(new ArticleCompletion( )); // Act var result = await _sut.Process(article); // Assert result.IsSuccessfullyProcessed.Should().BeFalse(); } [Test] public async Task Given_An_Article_If_Processed_And_An_ArticleCompletionException_Occur_IsSuccessfullyProcessed_Should_Be_False() { // Arrange var article = new Article(); _articleDataFlow.ProcessDataFlow(article).Throws(new ArticleCompletionException("Article not processed.")); // Act var result = await _sut.Process(article); // Assert result.IsSuccessfullyProcessed.Should().BeFalse(); } } } <file_sep>/src/wikia/processor/archetypeprocessor/src/Core/archetypeprocessor.core/Models/ArchetypeCardMessage.cs using System.Collections.Generic; namespace archetypeprocessor.core.Models { public class ArchetypeCardMessage { public string ArchetypeName { get; set; } public IEnumerable<string> Cards { get; set; } = new List<string>(); } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Domain/cardsectionprocessor.domain/Strategy/CardTipsProcessorStrategy.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using cardsectionprocessor.core.Constants; using cardsectionprocessor.core.Models; using cardsectionprocessor.core.Models.Db; using cardsectionprocessor.core.Service; using cardsectionprocessor.core.Strategy; namespace cardsectionprocessor.domain.Strategy { public class CardTipsProcessorStrategy : ICardSectionProcessorStrategy { private readonly ICardService _cardService; private readonly ICardTipService _cardTipService; public CardTipsProcessorStrategy(ICardService cardService, ICardTipService cardTipService) { _cardService = cardService; _cardTipService = cardTipService; } public async Task<CardSectionDataTaskResult<CardSectionMessage>> Process(CardSectionMessage cardSectionData) { var cardSectionDataTaskResult = new CardSectionDataTaskResult<CardSectionMessage> { CardSectionData = cardSectionData }; var card = await _cardService.CardByName(cardSectionData.Name); if (card != null) { await _cardTipService.DeleteByCardId(card.Id); var newTipSectionList = new List<TipSection>(); foreach (var cardSection in cardSectionData.CardSections) { var newTipSection = new TipSection { CardId = card.Id, Name = cardSection.Name, Created = DateTime.UtcNow, Updated = DateTime.UtcNow }; foreach (var tip in cardSection.ContentList) { newTipSection.Tip.Add(new Tip { TipSection = newTipSection, Text = tip, Created = DateTime.UtcNow, Updated = DateTime.UtcNow }); } newTipSectionList.Add(newTipSection); } if (newTipSectionList.Any()) { await _cardTipService.Update(newTipSectionList); } } else { cardSectionDataTaskResult.Errors.Add($"Card Tips: card '{cardSectionData.Name}' not found."); } return cardSectionDataTaskResult; } public bool Handles(string category) { return category == ArticleCategory.CardTips; } } }<file_sep>/src/wikia/data/carddata/src/Domain/carddata.domain/Processor/ArticleProcessor.cs using carddata.core.Exceptions; using carddata.core.Models; using carddata.core.Processor; using carddata.domain.Exceptions; using Microsoft.Extensions.Logging; using System.Threading.Tasks; namespace carddata.domain.Processor { public class ArticleProcessor : IArticleProcessor { private readonly IArticleDataFlow _articleDataFlow; private readonly ILogger<ArticleProcessed> _logger; public ArticleProcessor(IArticleDataFlow articleDataFlow, ILogger<ArticleProcessed> logger) { _articleDataFlow = articleDataFlow; _logger = logger; } public async Task<ArticleConsumerResult> Process(Article article) { var response = new ArticleConsumerResult {Article = article}; try { _logger.LogInformation($"{article.Title} processing... "); var result = await _articleDataFlow.ProcessDataFlow(article); if (result.IsSuccessful) { _logger.LogInformation($"{article.Title} processed successfully. "); response.IsSuccessfullyProcessed = true; } else { _logger.LogInformation($"{article.Title} processing failed. "); } } catch (ArticleCompletionException ex ) { _logger.LogError(" {ArticleTitle} error. Exception: {@Exception}, Article: {Article}", article.Title, ex, article); response.Failed = new ArticleException { Article = article, Exception = ex }; } return response; } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Core/cardsectionprocessor.core/Models/CardSectionMessage.cs using System.Collections.Generic; namespace cardsectionprocessor.core.Models { public class CardSectionMessage { public string Name { get; set; } public List<CardSection> CardSections { get; set; } = new List<CardSection>(); } }<file_sep>/src/wikia/processor/cardprocessor/src/Tests/Unit/cardprocessor.application.unit.tests/HelperTests/CardTests/TrapCardHelperTests.cs using System.Collections.Generic; using cardprocessor.application.Helpers.Cards; using cardprocessor.application.Models.Cards.Input; using cardprocessor.core.Models; using cardprocessor.tests.core; using FluentAssertions; using NUnit.Framework; namespace cardprocessor.application.unit.tests.HelperTests.CardTests { [TestFixture] [Category(TestType.Unit)] public class TrapCardHelperTests { [Test] public void Given_A_Valid_Trap_YugiohCard_With_Types_Should_Map_To_SubCategoryIds_Property() { // Arrange var expected = new List<int> { 22 }; var yugiohCard = new YugiohCard { Name = "<NAME>", Description = "Amazing card!", CardNumber = "97077563", Property = "Continuous", CardType = "Trap", ImageUrl = "https://vignette.wikia.nocookie.net/yugioh/images/4/47/CalloftheHaunted-YS18-EN-C-1E.png/revision/latest/scale-to-width-down/300?cb=20180712163539" }; var cardInputModel = new CardInputModel(); // Act var result = TrapCardHelper.MapSubCategoryIds(yugiohCard, cardInputModel, TestData.AllCategories(), TestData.AllSubCategories()); // Assert result.SubCategoryIds.Should().BeEquivalentTo(expected); } } }<file_sep>/src/wikia/data/archetypedata/src/Infrastructure/archetypedata.infrastructure/Services/Messaging/ArchetypeCardQueue.cs using System; using System.Linq; using System.Threading.Tasks; using archetypedata.application.Configuration; using archetypedata.core.Models; using archetypedata.domain.Services.Messaging; using archetypedata.infrastructure.Services.Messaging.Constants; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using RabbitMQ.Client; namespace archetypedata.infrastructure.Services.Messaging { public class ArchetypeCardQueue : IQueue<ArchetypeCard> { private readonly ILogger<ArchetypeQueue> _logger; private readonly IOptions<RabbitMqSettings> _rabbitMqConfig; public ArchetypeCardQueue(ILogger<ArchetypeQueue> logger, IOptions<RabbitMqSettings> rabbitMqConfig) { _logger = logger; _rabbitMqConfig = rabbitMqConfig; } public Task Publish(ArchetypeCard message) { try { var messageBodyBytes = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)); var factory = new ConnectionFactory() { HostName = _rabbitMqConfig.Value.Host }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { var props = channel.CreateBasicProperties(); props.ContentType = _rabbitMqConfig.Value.ContentType; props.DeliveryMode = _rabbitMqConfig.Value.Exchanges[RabbitMqExchangeConstants.YugiohHeadersData].PersistentMode; props.Headers = _rabbitMqConfig.Value .Exchanges[RabbitMqExchangeConstants.YugiohHeadersData] .Queues[RabbitMqQueueConstants.ArchetypeCardData] .Headers.ToDictionary(k => k.Key, k => (object)k.Value); channel.BasicPublish ( RabbitMqExchangeConstants.YugiohHeadersData, "", props, messageBodyBytes ); } } catch (Exception ex) { _logger.LogError("Unable to send Archetype Card message to queue '{ArchetypeCardMessage}'. Exception: {Exception}", message, ex); throw; } return Task.CompletedTask; } } }<file_sep>/src/wikia/data/banlistdata/src/Application/banlistdata.application/MessageConsumers/BanlistInformation/BanlistInformationConsumerValidator.cs using FluentValidation; namespace banlistdata.application.MessageConsumers.BanlistInformation { public class BanlistInformationConsumerValidator : AbstractValidator<BanlistInformationConsumer> { public BanlistInformationConsumerValidator() { RuleFor(ci => ci.Message) .NotNull() .NotEmpty(); } } }<file_sep>/src/wikia/article/src/Core/article.core/ArticleList/DataSource/IArticleCategoryDataSource.cs using System.Collections.Generic; using wikia.Models.Article.AlphabeticalList; namespace article.core.ArticleList.DataSource { public interface IArticleCategoryDataSource { IAsyncEnumerable<UnexpandedArticle[]> Producer(string category, int pageSize); } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Presentation/archetypeprocessor/Services/ArchetypeProcessorHostedService.cs using System; using System.Text; using System.Threading; using System.Threading.Tasks; using archetypeprocessor.application.Configuration; using archetypeprocessor.application.MessageConsumers.ArchetypeCardInformation; using archetypeprocessor.application.MessageConsumers.ArchetypeInformation; using MediatR; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using RabbitMQ.Client; using RabbitMQ.Client.Events; using Serilog; using Serilog.Events; using Serilog.Formatting.Json; namespace archetypeprocessor.Services { public class ArchetypeProcessorHostedService : BackgroundService { private const string ArchetypeDataQueue = "archetype-data"; private const string ArchetypeCardDataQueue = "archetype-cards-data"; public IServiceProvider Services { get; } private readonly IOptions<RabbitMqSettings> _rabbitMqOptions; private readonly IOptions<AppSettings> _appSettingsOptions; private readonly IMediator _mediator; private ConnectionFactory _factory; private IModel _archetypeDataChannel; private IModel _archetypeCardDataChannel; private IConnection _archetypeConnection; private IConnection _archetypeCardConnection; private EventingBasicConsumer _archetypeArticleConsumer; private EventingBasicConsumer _archetypeCardArticleConsumer; public ArchetypeProcessorHostedService ( IServiceProvider services, IOptions<RabbitMqSettings> rabbitMqOptions, IOptions<AppSettings> appSettingsOptions, IMediator mediator ) { Services = services; _rabbitMqOptions = rabbitMqOptions; _appSettingsOptions = appSettingsOptions; _mediator = mediator; ConfigureSerilog(); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { await StartConsumer(); } public override void Dispose() { _archetypeConnection.Close(); _archetypeCardConnection.Close(); _archetypeDataChannel.Close(); _archetypeCardDataChannel.Close(); base.Dispose(); } private Task StartConsumer() { _factory = new ConnectionFactory() { HostName = _rabbitMqOptions.Value.Host }; _archetypeConnection = _factory.CreateConnection(); _archetypeCardConnection = _factory.CreateConnection(); _archetypeArticleConsumer = CreateArchetypeDataConsumer(_archetypeConnection); _archetypeCardArticleConsumer = CreateArchetypeCardDataConsumer(_archetypeCardConnection); return Task.CompletedTask; } private EventingBasicConsumer CreateArchetypeDataConsumer(IConnection connection) { _archetypeDataChannel = connection.CreateModel(); _archetypeDataChannel.BasicQos(0, 1, false); var consumer = new EventingBasicConsumer(_archetypeDataChannel); consumer.Received += async (model, ea) => { try { var body = ea.Body; var message = Encoding.UTF8.GetString(body); var result = await _mediator.Send(new ArchetypeInformationConsumer { Message = message }); if (result.IsSuccessful) { _archetypeDataChannel.BasicAck(ea.DeliveryTag, false); } else { _archetypeDataChannel.BasicNack(ea.DeliveryTag, false, false); } } catch (Exception ex) { Log.Logger.Error("RabbitMq Consumer: " + ArchetypeDataQueue + " exception. Exception: {@Exception}", ex); } }; consumer.Shutdown += OnArchetypeDataConsumerShutdown; consumer.Registered += OnArchetypeDataConsumerRegistered; consumer.Unregistered += OnArchetypeDataConsumerUnregistered; consumer.ConsumerCancelled += OnArchetypeDataConsumerCancelled; _archetypeDataChannel.BasicConsume ( queue: ArchetypeDataQueue, autoAck: false, consumer: consumer ); return consumer; } private EventingBasicConsumer CreateArchetypeCardDataConsumer(IConnection connection) { _archetypeCardDataChannel = connection.CreateModel(); _archetypeCardDataChannel.BasicQos(0, 1, false); var consumer = new EventingBasicConsumer(_archetypeCardDataChannel); consumer.Received += async (model, ea) => { try { var body = ea.Body; var message = Encoding.UTF8.GetString(body); var result = await _mediator.Send(new ArchetypeCardInformationConsumer { Message = message }); if (result.IsSuccessful) { _archetypeCardDataChannel.BasicAck(ea.DeliveryTag, false); } else { _archetypeCardDataChannel.BasicNack(ea.DeliveryTag, false, false); } } catch (Exception ex) { Log.Logger.Error("RabbitMq Consumer: " + ArchetypeCardDataQueue + " exception. Exception: {@Exception}", ex); } }; consumer.Shutdown += OnArchetypeCardArticleConsumerShutdown; consumer.Registered += OnArchetypeCardArticleConsumerRegistered; consumer.Unregistered += OnArchetypeCardArticleConsumerUnregistered; consumer.ConsumerCancelled += OnArchetypeCardArticleConsumerCancelled; _archetypeCardDataChannel.BasicConsume ( queue: ArchetypeCardDataQueue, autoAck: false, consumer: consumer ); return consumer; } private void ConfigureSerilog() { // Create the logger Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Console() .WriteTo.File(new JsonFormatter(renderMessage: true), (_appSettingsOptions.Value.LogFolder + $@"/archetypeprocessor.{Environment.MachineName}.txt"), fileSizeLimitBytes: 100000000, rollOnFileSizeLimit: true, rollingInterval: RollingInterval.Day) .CreateLogger(); } private static void OnArchetypeDataConsumerCancelled(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{ArchetypeDataQueue}' Cancelled"); } private static void OnArchetypeDataConsumerUnregistered(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{ArchetypeDataQueue}' Unregistered"); } private static void OnArchetypeDataConsumerRegistered(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{ArchetypeDataQueue}' Registered"); } private static void OnArchetypeDataConsumerShutdown(object sender, ShutdownEventArgs e) { Log.Logger.Information($"Consumer '{ArchetypeDataQueue}' Shutdown"); } private static void OnArchetypeCardArticleConsumerCancelled(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{ArchetypeCardDataQueue}' Cancelled"); } private static void OnArchetypeCardArticleConsumerUnregistered(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{ArchetypeCardDataQueue}' Unregistered"); } private static void OnArchetypeCardArticleConsumerRegistered(object sender, ConsumerEventArgs e) { Log.Logger.Information($"Consumer '{ArchetypeCardDataQueue}' Registered"); } private static void OnArchetypeCardArticleConsumerShutdown(object sender, ShutdownEventArgs e) { Log.Logger.Information($"Consumer '{ArchetypeCardDataQueue}' Shutdown"); } } } <file_sep>/src/wikia/article/src/Domain/article.domain/Services/Messaging/IQueue.cs using System.Threading.Tasks; using wikia.Models.Article.AlphabeticalList; namespace article.domain.Services.Messaging { public interface IQueue<in T> { Task Publish(T message); Task Publish(UnexpandedArticle message); } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Infrastructure/cardsectionprocessor.infrastructure/Repository/CardTipRepository.cs using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using cardsectionprocessor.core.Models.Db; using cardsectionprocessor.domain.Repository; using cardsectionprocessor.infrastructure.Database; using Microsoft.EntityFrameworkCore; namespace cardsectionprocessor.infrastructure.Repository { public class CardTipRepository : ICardTipRepository { private readonly YgoDbContext _context; public CardTipRepository(YgoDbContext context) { _context = context; } public async Task DeleteByCardId(long cardId) { var tipSections = await _context .TipSection .Include(t => t.Card) .Include(t => t.Tip) .Where(ts => ts.CardId == cardId) .ToListAsync(); if (tipSections.Any()) { _context.Tip.RemoveRange(tipSections.SelectMany(t => t.Tip)); _context.TipSection.RemoveRange(tipSections); await _context.SaveChangesAsync(); } } public async Task Update(List<TipSection> tipSections) { _context.TipSection.UpdateRange(tipSections); await _context.SaveChangesAsync(); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Domain/cardprocessor.domain/Services/LinkArrowService.cs using System.Collections.Generic; using System.Threading.Tasks; using cardprocessor.core.Models.Db; using cardprocessor.core.Services; using cardprocessor.domain.Repository; namespace cardprocessor.domain.Services { public class LinkArrowService : ILinkArrowService { private readonly ILinkArrowRepository _linkArrowRepository; public LinkArrowService(ILinkArrowRepository linkArrowRepository) { _linkArrowRepository = linkArrowRepository; } public Task<List<LinkArrow>> AllLinkArrows() { return _linkArrowRepository.AllLinkArrows(); } } }<file_sep>/src/wikia/data/cardsectiondata/src/Tests/Unit/cardsectiondata.domain.unit.tests/ArticleListTests/ItemTests/CardTipItemProcessorTests/ProcessItemTests.cs using System.Collections.Generic; using System.Threading.Tasks; using cardsectiondata.core.Models; using cardsectiondata.domain.ArticleList.Item; using cardsectiondata.domain.Services.Messaging; using cardsectiondata.domain.WebPages; using cardsectiondata.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; using wikia.Api; using wikia.Models.Article.Simple; namespace cardsectiondata.domain.unit.tests.ArticleListTests.ItemTests.CardTipItemProcessorTests { [TestFixture] [Category(TestType.Unit)] public class ProcessItemTests { private IWikiArticle _wikiArticle; private ITipRelatedWebPage _tipRelatedWebPage; private IEnumerable<IQueue> _queues; private CardTipItemProcessor _sut; [SetUp] public void SetUp() { _wikiArticle = Substitute.For<IWikiArticle>(); _tipRelatedWebPage = Substitute.For<ITipRelatedWebPage>(); _queues = Substitute.For<IEnumerable<IQueue>>(); _sut = new CardTipItemProcessor(_wikiArticle, _tipRelatedWebPage, _queues); } [Test] public async Task Given_A_Valid_Article_Should_Process_Article_Successfully() { // Arrange var article = new Article{ Title = "Call of the Haunted" }; _wikiArticle.Simple(Arg.Any<long>()).Returns(new ContentResult { Sections = new[] { new Section { Title = "Call of the Haunted", Level = 1, Content = new[] { new SectionContent { Type = "list", Elements = new[] { new ListElement { Text = "This card can be searched by \"A Cat of Ill Omen\" and \"The Despair Uranus\".", Elements = new ListElement[0] }, } }, } }, new Section { Title = "References", Content = new SectionContent[0] }, new Section { Title = "List", Content = new [] { new SectionContent { Elements = new[] { new ListElement { Text = "Ancient Fairy Dragon" }, new ListElement { Text = "Blaster, Dragon Ruler of Infernos" }, new ListElement { Text = "Cyber Jar" } } } } }, } }); var handler = Substitute.For<IQueue>(); handler.Handles(Arg.Any<string>()).Returns(true); handler.Publish(Arg.Any<CardSectionMessage>()).Returns(Task.CompletedTask); _queues.GetEnumerator().Returns(new List<IQueue> {handler}.GetEnumerator()); // Act var result = await _sut.ProcessItem(article); // Assert result.Article.Should().Be(article); } [Test] public async Task Given_A_Valid_Article_Should_Invoke_Simple_Method_Once() { // Arrange const int expected = 1; var article = new Article{ Title = "Call of the Haunted" }; _wikiArticle.Simple(Arg.Any<long>()).Returns(new ContentResult { Sections = new[] { new Section { Title = "Call of the Haunted", Level = 1, Content = new[] { new SectionContent { Type = "list", Elements = new[] { new ListElement { Text = "This card can be searched by \"A Cat of Ill Omen\" and \"The Despair Uranus\".", Elements = new ListElement[0] }, } }, } }, new Section { Title = "References", Content = new SectionContent[0] }, new Section { Title = "List", Content = new [] { new SectionContent { Elements = new[] { new ListElement { Text = "Ancient Fairy Dragon" }, new ListElement { Text = "Blaster, Dragon Ruler of Infernos" }, new ListElement { Text = "Cyber Jar" } } } } }, } }); var handler = Substitute.For<IQueue>(); handler.Handles(Arg.Any<string>()).Returns(true); handler.Publish(Arg.Any<CardSectionMessage>()).Returns(Task.CompletedTask); _queues.GetEnumerator().Returns(new List<IQueue> {handler}.GetEnumerator()); // Act await _sut.ProcessItem(article); // Assert await _wikiArticle.Received(expected).Simple(Arg.Any<long>()); } [Test] public async Task Given_A_Valid_Article_Should_Invoke_GetTipRelatedCards_Method_Once() { // Arrange const int expected = 1; var article = new Article{ Title = "Call of the Haunted" }; _wikiArticle.Simple(Arg.Any<long>()).Returns(new ContentResult { Sections = new[] { new Section { Title = "Call of the Haunted", Level = 1, Content = new[] { new SectionContent { Type = "list", Elements = new[] { new ListElement { Text = "This card can be searched by \"A Cat of Ill Omen\" and \"The Despair Uranus\".", Elements = new ListElement[0] }, } }, } }, new Section { Title = "References", Content = new SectionContent[0] }, new Section { Title = "List", Content = new [] { new SectionContent { Elements = new[] { new ListElement { Text = "Ancient Fairy Dragon" }, new ListElement { Text = "Blaster, Dragon Ruler of Infernos" }, new ListElement { Text = "Cyber Jar" } } } } }, } }); var handler = Substitute.For<IQueue>(); handler.Handles(Arg.Any<string>()).Returns(true); handler.Publish(Arg.Any<CardSectionMessage>()).Returns(Task.CompletedTask); _queues.GetEnumerator().Returns(new List<IQueue> {handler}.GetEnumerator()); // Act await _sut.ProcessItem(article); // Assert _tipRelatedWebPage.Received(expected).GetTipRelatedCards(Arg.Any<CardSection>(), Arg.Any<Article>()); } [Test] public async Task Given_A_Valid_Article_Should_Invoke_Publish_Method_Once() { // Arrange const int expected = 1; var article = new Article{ Title = "Call of the Haunted" }; _wikiArticle.Simple(Arg.Any<long>()).Returns(new ContentResult { Sections = new[] { new Section { Title = "Call of the Haunted", Level = 1, Content = new[] { new SectionContent { Type = "list", Elements = new[] { new ListElement { Text = "This card can be searched by \"A Cat of Ill Omen\" and \"The Despair Uranus\".", Elements = new ListElement[0] }, } }, } }, new Section { Title = "References", Content = new SectionContent[0] }, new Section { Title = "List", Content = new [] { new SectionContent { Elements = new[] { new ListElement { Text = "Ancient Fairy Dragon" }, new ListElement { Text = "Blaster, Dragon Ruler of Infernos" }, new ListElement { Text = "Cyber Jar" } } } } }, } }); var handler = Substitute.For<IQueue>(); handler.Handles(Arg.Any<string>()).Returns(true); handler.Publish(Arg.Any<CardSectionMessage>()).Returns(Task.CompletedTask); _queues.GetEnumerator().Returns(new List<IQueue> {handler}.GetEnumerator()); // Act await _sut.ProcessItem(article); // Assert await handler.Received(expected).Publish(Arg.Any<CardSectionMessage>()); } } }<file_sep>/src/wikia/article/src/Application/article.application/ScheduledTasks/Archetype/ArchetypeInformationTaskValidator.cs using FluentValidation; namespace article.application.ScheduledTasks.Archetype { public class ArchetypeInformationTaskValidator : AbstractValidator<ArchetypeInformationTask> { private const int MaxPageSize = 500; public ArchetypeInformationTaskValidator() { RuleFor(ci => ci.Category) .Cascade(CascadeMode.Stop) .NotNull() .NotEmpty(); RuleFor(ci => ci.PageSize) .GreaterThan(0) .LessThanOrEqualTo(MaxPageSize); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Tests/Unit/cardprocessor.application.unit.tests/HelperTests/CardTests/SpellCardHelperTests.cs using System.Collections.Generic; using cardprocessor.application.Helpers.Cards; using cardprocessor.application.Models.Cards.Input; using cardprocessor.core.Models; using cardprocessor.tests.core; using FluentAssertions; using NUnit.Framework; namespace cardprocessor.application.unit.tests.HelperTests.CardTests { [TestFixture] [Category(TestType.Unit)] public class SpellCardHelperTests { [Test] public void Given_A_Valid_Spell_YugiohCard_With_Types_Should_Map_To_SubCategoryIds_Property() { // Arrange var expected = new List<int> { 18 }; var yugiohCard = new YugiohCard { Name = "<NAME>", Description = "Amazing card!", CardNumber = "41426869", Property = "Ritual", CardType = "Spell", ImageUrl = "https://vignette.wikia.nocookie.net/yugioh/images/8/82/BlackIllusionRitual-LED2-EN-C-1E.png/revision/latest/scale-to-width-down/300?cb=20180223153750" }; var cardInputModel = new CardInputModel(); // Act var result = SpellCardHelper.MapSubCategoryIds(yugiohCard, cardInputModel, TestData.AllCategories(), TestData.AllSubCategories()); // Assert result.SubCategoryIds.Should().BeEquivalentTo(expected); } } }<file_sep>/src/wikia/semanticsearch/src/Application/semanticsearch.application/ApplicationInstaller.cs using MediatR; using Microsoft.Extensions.DependencyInjection; using semanticsearch.core.Search; using semanticsearch.domain.Search.Consumer; using semanticsearch.domain.Search.Producer; using System.Reflection; using semanticsearch.domain.Search; namespace semanticsearch.application { public static class ApplicationInstaller { public static IServiceCollection AddApplicationServices(this IServiceCollection services) { services .AddCqrs() .AddDomainServices(); return services; } private static IServiceCollection AddCqrs(this IServiceCollection services) { services.AddMediatR(typeof(ApplicationInstaller).GetTypeInfo().Assembly); return services; } private static IServiceCollection AddDomainServices(this IServiceCollection services) { services.AddTransient<ISemanticSearchProducer, SemanticSearchProducer>(); services.AddTransient<ISemanticSearchConsumer, SemanticSearchConsumer>(); services.AddTransient<ISemanticSearchProcessor, SemanticSearchProcessor>(); return services; } } }<file_sep>/src/wikia/semanticsearch/src/Core/semanticsearch.core/Exceptions/SemanticCardPublishException.cs using System; namespace semanticsearch.core.Exceptions { public class SemanticCardPublishException { public string Url { get; set; } public Exception Exception { get; set; } } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Infrastructure/archetypeprocessor.infrastructure/Repository/ArchetypeRepository.cs using archetypeprocessor.core.Models.Db; using archetypeprocessor.domain.Repository; using archetypeprocessor.infrastructure.Database; using Microsoft.EntityFrameworkCore; using System.Threading.Tasks; namespace archetypeprocessor.infrastructure.Repository { public class ArchetypeRepository : IArchetypeRepository { private readonly YgoDbContext _dbContext; public ArchetypeRepository(YgoDbContext dbContext) { _dbContext = dbContext; } public Task<Archetype> ArchetypeByName(string name) { return _dbContext .Archetype .SingleOrDefaultAsync(a => a.Name == name); } public Task<Archetype> ArchetypeById(long id) { return _dbContext .Archetype .SingleOrDefaultAsync(a => a.Id == id); } public async Task<Archetype> Add(Archetype archetype) { await _dbContext.Archetype.AddAsync(archetype); await _dbContext.SaveChangesAsync(); return archetype; } public async Task<Archetype> Update(Archetype archetype) { _dbContext.Archetype.Update(archetype); await _dbContext.SaveChangesAsync(); return archetype; } } }<file_sep>/src/wikia/data/carddata/src/Tests/Unit/carddata.domain.unit.tests/ArticleDataFlowTests.cs using System; using System.Threading.Tasks; using carddata.core.Models; using carddata.domain.Processor; using carddata.domain.Services.Messaging; using carddata.domain.WebPages.Cards; using carddata.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace carddata.domain.unit.tests { [TestFixture] [Category(TestType.Unit)] public class ArticleDataFlowTests { private IYugiohCardQueue _yugiohCardQueue; private ICardWebPage _cardWebPage; private ArticleDataFlow _sut; [SetUp] public void SetUp() { _yugiohCardQueue = Substitute.For<IYugiohCardQueue>(); _cardWebPage = Substitute.For<ICardWebPage>(); _sut = new ArticleDataFlow(_cardWebPage, _yugiohCardQueue); } [Test] public async Task Given_An_Article_Should_Invoke_GetYugiohCard_Once() { // Arrange var article = new Article{Id = 3242423}; _yugiohCardQueue.Publish(Arg.Any<ArticleProcessed>()).Returns(new YugiohCardCompletion {Article = article, IsSuccessful = true}); // Act await _sut.ProcessDataFlow(article); // Assert _cardWebPage.Received(1).GetYugiohCard(Arg.Is(article)); } [Test] public async Task Given_An_Article_Should_Invoke_Publish_Once() { // Arrange var article = new Article{Id = 3242423}; _yugiohCardQueue.Publish(Arg.Any<ArticleProcessed>()).Returns(new YugiohCardCompletion {Article = article, IsSuccessful = true}); // Act await _sut.ProcessDataFlow(article); // Assert await _yugiohCardQueue.Received(1).Publish(Arg.Any<ArticleProcessed>()); } [Test] public void Given_An_Article_If_Not_Successfully_Processed_Should_Exception() { // Arrange var article = new Article{Id = 3242423}; _yugiohCardQueue.Publish(Arg.Any<ArticleProcessed>()).Returns(new YugiohCardCompletion {Article = article}); // Act Func<Task<ArticleCompletion>> act = () => _sut.ProcessDataFlow(article); // Assert act.Should().Throw<Exception>(); } } }<file_sep>/src/wikia/data/cardsectiondata/src/Tests/Unit/cardsectiondata.domain.unit.tests/ArticleListTests/ItemTests/CardTriviaItemProcessorTests/ProcessItemTests.cs using System.Collections.Generic; using System.Threading.Tasks; using cardsectiondata.core.Models; using cardsectiondata.core.Processor; using cardsectiondata.domain.ArticleList.Item; using cardsectiondata.domain.Services.Messaging; using cardsectiondata.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace cardsectiondata.domain.unit.tests.ArticleListTests.ItemTests.CardTriviaItemProcessorTests { [TestFixture] [Category(TestType.Unit)] public class ProcessItemTests { private IEnumerable<IQueue> _queues; private CardTriviaItemProcessor _sut; private ICardSectionProcessor _cardSectionProcessor; [SetUp] public void SetUp() { _queues = Substitute.For<IEnumerable<IQueue>>(); _cardSectionProcessor = Substitute.For<ICardSectionProcessor>(); _sut = new CardTriviaItemProcessor(_cardSectionProcessor, _queues); } [Test] public async Task Given_A_Valid_Article_Should_Process_Article_Successfully() { // Arrange var article = new Article{ Title = "Call of the Haunted" }; _cardSectionProcessor.ProcessItem(Arg.Any<Article>()).Returns(new CardSectionMessage()); var handler = Substitute.For<IQueue>(); handler.Handles(Arg.Any<string>()).Returns(true); handler.Publish(Arg.Any<CardSectionMessage>()).Returns(Task.CompletedTask); _queues.GetEnumerator().Returns(new List<IQueue> {handler}.GetEnumerator()); // Act var result = await _sut.ProcessItem(article); // Assert result.Article.Should().Be(article); } [Test] public async Task Given_A_Valid_Article_Should_Invoke_ProcessItem_Method_Once() { // Arrange const int expected = 1; var article = new Article{ Title = "Call of the Haunted" }; _cardSectionProcessor.ProcessItem(Arg.Any<Article>()).Returns(new CardSectionMessage()); var handler = Substitute.For<IQueue>(); handler.Handles(Arg.Any<string>()).Returns(true); handler.Publish(Arg.Any<CardSectionMessage>()).Returns(Task.CompletedTask); _queues.GetEnumerator().Returns(new List<IQueue> {handler}.GetEnumerator()); // Act await _sut.ProcessItem(article); // Assert await _cardSectionProcessor.Received(expected).ProcessItem(Arg.Any<Article>()); } [Test] public async Task Given_A_Valid_Article_Should_Invoke_Publish_Method_Once() { // Arrange const int expected = 1; var article = new Article{ Title = "Call of the Haunted" }; _cardSectionProcessor.ProcessItem(Arg.Any<Article>()).Returns(new CardSectionMessage()); var handler = Substitute.For<IQueue>(); handler.Handles(Arg.Any<string>()).Returns(true); handler.Publish(Arg.Any<CardSectionMessage>()).Returns(Task.CompletedTask); _queues.GetEnumerator().Returns(new List<IQueue> {handler}.GetEnumerator()); // Act await _sut.ProcessItem(article); // Assert await handler.Received(expected).Publish(Arg.Any<CardSectionMessage>()); } } }<file_sep>/src/wikia/data/banlistdata/src/Core/banlistdata.core/Processor/IArticleDataFlow.cs using System.Threading.Tasks; using banlistdata.core.Models; namespace banlistdata.core.Processor { public interface IArticleDataFlow { Task<ArticleCompletion> ProcessDataFlow(Article article); } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/cardsectionprocessor.domain.unit.tests/StrategyTests/CardTipsProcessorStrategyTests/ProcessTests.cs using System.Collections.Generic; using System.Threading.Tasks; using cardsectionprocessor.core.Models; using cardsectionprocessor.core.Models.Db; using cardsectionprocessor.core.Service; using cardsectionprocessor.domain.Strategy; using cardsectionprocessor.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace cardsectionprocessor.domain.unit.tests.StrategyTests.CardTipsProcessorStrategyTests { [TestFixture] [Category(TestType.Unit)] public class ProcessTests { private ICardTipService _cardTipService; private ICardService _cardService; private CardTipsProcessorStrategy _sut; [SetUp] public void SetUp() { _cardTipService = Substitute.For<ICardTipService>(); _cardService = Substitute.For<ICardService>(); _sut = new CardTipsProcessorStrategy(_cardService, _cardTipService); } [Test] public async Task Given_A_CardSectionMessage_If_Card_Is_Not_Found_IsSuccessful_Should_be_False() { // Arrange var cardSectionMessage = new CardSectionMessage(); // Act var result = await _sut.Process(cardSectionMessage); // Assert result.IsSuccessful.Should().BeFalse(); } [Test] public async Task Given_A_CardSectionMessage_If_Card_Is_Not_Found_Should_Return_Errors() { // Arrange var cardSectionMessage = new CardSectionMessage(); // Act var result = await _sut.Process(cardSectionMessage); // Assert result.Errors.Should().NotBeNullOrEmpty(); } [Test] public async Task Given_A_CardSectionMessage_Should_Invoke_CardByName_Method_Once() { // Arrange const int expected = 1; var cardSectionMessage = new CardSectionMessage(); // Act await _sut.Process(cardSectionMessage); // Assert await _cardService.Received(expected).CardByName(Arg.Any<string>()); } [Test] public async Task Given_A_CardSectionMessage_Should_Invoke_DeleteByCardId_Method_Once() { // Arrange const int expected = 1; var cardSectionMessage = new CardSectionMessage(); _cardService.CardByName(Arg.Any<string>()).Returns(new Card()); // Act await _sut.Process(cardSectionMessage); // Assert await _cardTipService.Received(expected).DeleteByCardId(Arg.Any<long>()); } [Test] public async Task Given_A_CardSectionMessage_Should_Invoke_Update_Method_Once() { // Arrange const int expected = 1; var cardSectionMessage = new CardSectionMessage { CardSections = new List<CardSection> { new CardSection { Name = "<NAME>", ContentList = new List<string> { "It's a trap!" } } } }; _cardService.CardByName(Arg.Any<string>()).Returns(new Card()); // Act await _sut.Process(cardSectionMessage); // Assert await _cardTipService.Received(expected).Update(Arg.Any<List<TipSection>>()); } } } <file_sep>/src/wikia/semanticsearch/src/Domain/semanticsearch.domain/WebPage/ISemanticCardSearchResultsWebPage.cs using System; using HtmlAgilityPack; namespace semanticsearch.domain.WebPage { public interface ISemanticCardSearchResultsWebPage { string Name(HtmlNode tableRow); string Url(HtmlNode tableRow, Uri uri); } }<file_sep>/src/wikia/data/carddata/src/Domain/carddata.domain/Exceptions/ArticleCompletionException.cs using System; namespace carddata.domain.Exceptions { public class ArticleCompletionException : Exception { public ArticleCompletionException(string exceptionMessage) : base (exceptionMessage) { } } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Domain/archetypeprocessor.domain/Messaging/IArchetypeImageQueueService.cs using System.Threading.Tasks; using archetypeprocessor.core.Models; namespace archetypeprocessor.domain.Messaging { public interface IArchetypeImageQueueService { Task Publish(DownloadImage downloadImage); } }<file_sep>/src/wikia/article/src/Domain/article.domain/ArticleList/Item/CardItemProcessor.cs using System; using System.Threading.Tasks; using article.core.ArticleList.Processor; using article.core.Constants; using article.core.Exceptions; using article.core.Models; using article.domain.Services.Messaging.Cards; using wikia.Models.Article.AlphabeticalList; namespace article.domain.ArticleList.Item { public sealed class CardItemProcessor : IArticleItemProcessor { private readonly ICardArticleQueue _cardArticleQueue; public CardItemProcessor(ICardArticleQueue cardArticleQueue) { _cardArticleQueue = cardArticleQueue; } public async Task<ArticleTaskResult> ProcessItem(UnexpandedArticle item) { if (item == null) throw new ArgumentNullException(nameof(item)); var articleTaskResult = new ArticleTaskResult { Article = item }; try { await _cardArticleQueue.Publish(item); articleTaskResult.IsSuccessfullyProcessed = true; } catch (Exception ex) { articleTaskResult.Failed = new ArticleException{ Article = item, Exception = ex}; } return articleTaskResult; } public bool Handles(string category) { return category == ArticleCategory.TcgCards || category == ArticleCategory.OcgCards; } } }<file_sep>/src/wikia/data/banlistdata/src/Tests/Unit/banlistdata.application.unit.tests/BanlistInformationConsumerHandlerTests.cs using System; using System.Threading; using System.Threading.Tasks; using banlistdata.application.MessageConsumers.BanlistInformation; using banlistdata.core.Exceptions; using banlistdata.core.Models; using banlistdata.core.Processor; using banlistdata.tests.core; using FluentAssertions; using FluentValidation; using NSubstitute; using NUnit.Framework; namespace banlistdata.application.unit.tests { [TestFixture] [Category(TestType.Unit)] public class BanlistInformationConsumerHandlerTests { private IArticleProcessor _articleProcessor; private IValidator<BanlistInformationConsumer> _validator; private BanlistInformationConsumerHandler _sut; [SetUp] public void SetUp() { _articleProcessor = Substitute.For<IArticleProcessor>(); _validator = Substitute.For<IValidator<BanlistInformationConsumer>>(); _sut = new BanlistInformationConsumerHandler(_articleProcessor, _validator); } [Test] public async Task Given_An_Invalid_BanlistInformationConsumer_BanlistInformationConsumerResult_Should_Be_Null() { // Arrange var banlistInformationConsumer = new BanlistInformationConsumer(); _validator .Validate(Arg.Is(banlistInformationConsumer)) .Returns(new BanlistInformationConsumerValidator().Validate(banlistInformationConsumer)); // Act var result = await _sut.Handle(banlistInformationConsumer, CancellationToken.None); // Assert result.Message.Should().BeNull(); } [Test] public async Task Given_An_Valid_BanlistInformationConsumer_IsSuccessful_Should_BeTrue() { // Arrange var banlistInformationConsumer = new BanlistInformationConsumer { Message = $"{{\"Id\":16022,\"CorrelationId\":\"0606a974-ea5f-436b-a263-ee638762e019\",\"Title\":\"Historic Forbidden/Limited Chart\",\"Url\":null}}" }; _validator .Validate(Arg.Is(banlistInformationConsumer)) .Returns(new BanlistInformationConsumerValidator().Validate(banlistInformationConsumer)); _articleProcessor.Process(Arg.Any<Article>()) .Returns(new ArticleConsumerResult { IsSuccessfullyProcessed = true }); // Act var result = await _sut.Handle(banlistInformationConsumer, CancellationToken.None); // Assert result.IsSuccessful.Should().BeTrue(); } [Test] public async Task Given_An_Valid_BanlistInformationConsumer_Should_Invoke_ArticleProcessor_Process_Once() { // Arrange var banlistInformationConsumer = new BanlistInformationConsumer { Message = $"{{\"Id\":16022,\"CorrelationId\":\"0606a974-ea5f-436b-a263-ee638762e019\",\"Title\":\"Historic Forbidden/Limited Chart\",\"Url\":null}}" }; _validator .Validate(Arg.Is(banlistInformationConsumer)) .Returns(new BanlistInformationConsumerValidator().Validate(banlistInformationConsumer)); _articleProcessor.Process(Arg.Any<Article>()) .Returns(new ArticleConsumerResult { IsSuccessfullyProcessed = true }); // Act await _sut.Handle(banlistInformationConsumer, CancellationToken.None); // Assert await _articleProcessor.Received(1).Process(Arg.Any<Article>()); } [Test] public async Task Given_An_Valid_BanlistInformationConsumer_If_Processing_Failed_IsSuccessful_Should_Be_False() { // Arrange var banlistInformationConsumer = new BanlistInformationConsumer { Message = $"{{\"Id\":16022,\"CorrelationId\":\"0606a974-ea5f-436b-a263-ee638762e019\",\"Title\":\"Historic Forbidden/Limited Chart\",\"Url\":null}}" }; _validator .Validate(Arg.Is(banlistInformationConsumer)) .Returns(new BanlistInformationConsumerValidator().Validate(banlistInformationConsumer)); _articleProcessor.Process(Arg.Any<Article>()) .Returns(new ArticleConsumerResult { IsSuccessfullyProcessed = false, Failed = new ArticleException { Exception = new Exception("Error message") } }); // Act var result = await _sut.Handle(banlistInformationConsumer, CancellationToken.None); // Assert result.IsSuccessful.Should().BeFalse(); } } } <file_sep>/src/wikia/processor/archetypeprocessor/src/Core/archetypeprocessor.core/Processor/IArchetypeCardProcessor.cs using System.Threading.Tasks; using archetypeprocessor.core.Models; namespace archetypeprocessor.core.Processor { public interface IArchetypeCardProcessor { Task<ArchetypeDataTaskResult<ArchetypeCardMessage>> Process(ArchetypeCardMessage archetypeData); } }<file_sep>/src/wikia/processor/banlistprocessor/src/Domain/banlistprocessor.domain/banlistprocessor.domain/Services/BanlistCardService.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using banlistprocessor.core.Models; using banlistprocessor.core.Models.Db; using banlistprocessor.core.Services; using banlistprocessor.domain.Repository; namespace banlistprocessor.domain.Services { public class BanlistCardService : IBanlistCardService { private readonly ILimitRepository _limitRepository; private readonly ICardRepository _cardRepository; private readonly IBanlistCardRepository _banlistCardRepository; public BanlistCardService(ILimitRepository limitRepository, ICardRepository cardRepository, IBanlistCardRepository banlistCardRepository) { _limitRepository = limitRepository; _cardRepository = cardRepository; _banlistCardRepository = banlistCardRepository; } public async Task<ICollection<BanlistCard>> Update(long banlistId, List<YugiohBanlistSection> yugiohBanlistSections) { var banlistCards = await MapToBanlistCards(banlistId, yugiohBanlistSections); return await _banlistCardRepository.Update(banlistId, banlistCards); } #region private helpers private async Task<IList<BanlistCard>> MapToBanlistCards(long banlistId, IList<YugiohBanlistSection> yugiohBanlistSections) { var banlistCards = new List<BanlistCard>(); var cardlimits = await _limitRepository.GetAll(); const string forbidden = "forbidden"; const string limited = "limited"; const string semiLimited = "semi-limited"; const string unlimited = "unlimited"; var forbiddenBanSection = yugiohBanlistSections.FirstOrDefault(bs => bs.Title.Equals(forbidden, StringComparison.OrdinalIgnoreCase)); var limitedBanSection = yugiohBanlistSections.FirstOrDefault(bs => bs.Title.Equals(limited, StringComparison.OrdinalIgnoreCase)); var semiLimitedBanSection = yugiohBanlistSections.FirstOrDefault(bs => bs.Title.Equals(semiLimited, StringComparison.OrdinalIgnoreCase)); var unlimitedBanSection = yugiohBanlistSections.FirstOrDefault(bs => bs.Title.Equals(unlimited, StringComparison.OrdinalIgnoreCase)); if (forbiddenBanSection != null && forbiddenBanSection.Content.Any()) await AddCardsToBanlist(banlistCards, forbiddenBanSection, banlistId, cardlimits, forbidden); if (limitedBanSection != null && limitedBanSection.Content.Any()) await AddCardsToBanlist(banlistCards, limitedBanSection, banlistId, cardlimits, limited); if (semiLimitedBanSection != null && semiLimitedBanSection.Content.Any()) await AddCardsToBanlist(banlistCards, semiLimitedBanSection, banlistId, cardlimits, semiLimited); if (unlimitedBanSection != null && unlimitedBanSection.Content.Any()) await AddCardsToBanlist(banlistCards, unlimitedBanSection, banlistId, cardlimits, unlimited); return banlistCards; } private async Task AddCardsToBanlist(List<BanlistCard> banlistCards, YugiohBanlistSection forbiddenBanSection, long banlistId, IEnumerable<Limit> cardlimits, string limit) { var selectedLimit = cardlimits.Single(l => l.Name.Equals(limit, StringComparison.OrdinalIgnoreCase)); if (selectedLimit != null) { foreach (var cardName in forbiddenBanSection.Content) { var card = await _cardRepository.CardByName(cardName); if (card != null && !banlistCards.Any(blc => blc.BanlistId == banlistId && blc.CardId == card.Id)) banlistCards.Add(new BanlistCard { BanlistId = banlistId, CardId = card.Id, LimitId = selectedLimit.Id }); } } } #endregion } } <file_sep>/src/wikia/article/src/Core/article.core/Exceptions/ArticleException.cs using System; using wikia.Models.Article.AlphabeticalList; namespace article.core.Exceptions { public class ArticleException { public UnexpandedArticle Article { get; set; } public Exception Exception { get; set; } } }<file_sep>/src/wikia/data/cardsectiondata/src/Domain/cardsectiondata.domain/ArticleList/Item/CardTipItemProcessor.cs using cardsectiondata.core.Constants; using cardsectiondata.core.Models; using cardsectiondata.core.Processor; using cardsectiondata.domain.Helpers; using cardsectiondata.domain.WebPages; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using cardsectiondata.domain.Services.Messaging; using wikia.Api; namespace cardsectiondata.domain.ArticleList.Item { public class CardTipItemProcessor : IArticleItemProcessor { private readonly IWikiArticle _wikiArticle; private readonly ITipRelatedWebPage _tipRelatedWebPage; private readonly IEnumerable<IQueue> _queues; public CardTipItemProcessor ( IWikiArticle wikiArticle, ITipRelatedWebPage tipRelatedWebPage, IEnumerable<IQueue> queues ) { _wikiArticle = wikiArticle; _tipRelatedWebPage = tipRelatedWebPage; _queues = queues; } public async Task<ArticleTaskResult> ProcessItem(Article article) { var response = new ArticleTaskResult { Article = article }; var tipSections = new List<CardSection>(); var articleCardTips = await _wikiArticle.Simple(article.Id); foreach (var cardTipSection in articleCardTips.Sections) { var tipSection = new CardSection { Name = cardTipSection.Title, ContentList = SectionHelper.GetSectionContentList(cardTipSection) }; if (cardTipSection.Title.Equals("List", StringComparison.OrdinalIgnoreCase) || cardTipSection.Title.Equals("Lists", StringComparison.OrdinalIgnoreCase)) { tipSection.Name = tipSection.ContentList.First(); tipSection.ContentList.Clear(); _tipRelatedWebPage.GetTipRelatedCards(tipSection, article); } tipSections.Add(tipSection); } var cardSectionMessage = new CardSectionMessage { Name = article.Title, CardSections = tipSections }; await _queues.Single(q => q.Handles(ArticleCategory.CardTips)).Publish(cardSectionMessage); return response; } public bool Handles(string category) { return category == ArticleCategory.CardTips; } } }<file_sep>/src/wikia/processor/banlistprocessor/src/Application/banlistprocessor.application/MessageConsumers/BanlistData/BanlistDataConsumerResult.cs using System; using System.Collections.Generic; using System.Linq; using banlistprocessor.core.Models; namespace banlistprocessor.application.MessageConsumers.BanlistData { public class BanlistDataConsumerResult { public bool IsSuccessful => !Errors.Any(); public YugiohBanlist YugiohBanlist { get; set; } public List<string> Errors { get; set; } = new List<string>(); public Exception Exception { get; set; } public long BanlistId { get; set; } } } <file_sep>/src/wikia/data/banlistdata/src/Core/banlistdata.core/Processor/IBanlistProcessor.cs using System.Threading.Tasks; using banlistdata.core.Models; namespace banlistdata.core.Processor { public interface IBanlistProcessor { Task<ArticleProcessed> Process(Article article); } }<file_sep>/src/wikia/data/banlistdata/src/Domain/banlistdata.domain/Processor/ArticleProcessor.cs using System; using System.Threading.Tasks; using banlistdata.core.Exceptions; using banlistdata.core.Models; using banlistdata.core.Processor; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace banlistdata.domain.Processor { public class ArticleProcessor : IArticleProcessor { private readonly IArticleDataFlow _articleDataFlow; private readonly ILogger<ArticleProcessed> _logger; public ArticleProcessor(IArticleDataFlow articleDataFlow, ILogger<ArticleProcessed> logger) { _articleDataFlow = articleDataFlow; _logger = logger; } public async Task<ArticleConsumerResult> Process(Article article) { var articleJson = JsonConvert.SerializeObject(article); var response = new ArticleConsumerResult(); response.Article = articleJson; try { _logger.LogInformation($"{article.Title} processing... "); var result = await _articleDataFlow.ProcessDataFlow(article); if (result.IsSuccessful) { _logger.LogInformation($"{article.Title} processed successfully. "); response.IsSuccessfullyProcessed = true; } else { _logger.LogInformation($"{article.Title} processing failed. "); } } catch (Exception ex ) { _logger.LogError(article.Title + " error. Exception: {@Exception}", ex); response.Failed = new ArticleException { Article = articleJson, Exception = ex }; } return response; } } }<file_sep>/src/wikia/data/carddata/src/Core/carddata.core/Exceptions/ArticleException.cs using System; using carddata.core.Models; namespace carddata.core.Exceptions { public class ArticleException { public Article Article { get; set; } public Exception Exception { get; set; } } }<file_sep>/src/wikia/processor/cardprocessor/src/Domain/cardprocessor.domain/Services/AttributeService.cs using System.Collections.Generic; using System.Threading.Tasks; using cardprocessor.core.Models.Db; using cardprocessor.core.Services; using cardprocessor.domain.Repository; namespace cardprocessor.domain.Services { public class AttributeService : IAttributeService { private readonly IAttributeRepository _attributeRepository; public AttributeService(IAttributeRepository attributeRepository) { _attributeRepository = attributeRepository; } public Task<List<Attribute>> AllAttributes() { return _attributeRepository.AllAttributes(); } } }<file_sep>/src/wikia/data/cardsectiondata/src/Infrastructure/cardsectiondata.infrastructure/Services/Messaging/CardRulingQueue.cs using System; using System.Linq; using System.Threading.Tasks; using cardsectiondata.application.Configuration; using cardsectiondata.core.Constants; using cardsectiondata.core.Models; using cardsectiondata.domain.Services.Messaging; using cardsectiondata.infrastructure.Services.Messaging.Constants; using Microsoft.Extensions.Options; using Newtonsoft.Json; using RabbitMQ.Client; namespace cardsectiondata.infrastructure.Services.Messaging { public class CardRulingQueue : IQueue { private readonly IOptions<RabbitMqSettings> _rabbitMqConfig; public CardRulingQueue(IOptions<RabbitMqSettings> rabbitMqConfig) { _rabbitMqConfig = rabbitMqConfig; } public Task Publish(CardSectionMessage message) { try { var messageBodyBytes = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)); var factory = new ConnectionFactory() { HostName = _rabbitMqConfig.Value.Host }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { var props = channel.CreateBasicProperties(); props.ContentType = _rabbitMqConfig.Value.ContentType; props.DeliveryMode = _rabbitMqConfig.Value.Exchanges[RabbitMqExchangeConstants.YugiohHeadersData].PersistentMode; props.Headers = _rabbitMqConfig.Value .Exchanges[RabbitMqExchangeConstants.YugiohHeadersData] .Queues[RabbitMqQueueConstants.CardRulingsData] .Headers.ToDictionary(k => k.Key, k => (object)k.Value); channel.BasicPublish ( RabbitMqExchangeConstants.YugiohHeadersData, "", props, messageBodyBytes ); } } catch (Exception ex) { Console.WriteLine(ex); throw; } return Task.CompletedTask; } public bool Handles(string category) { return category == ArticleCategory.CardRulings; } } }<file_sep>/src/wikia/semanticsearch/src/Presentation/semanticsearch.card/Dockerfile FROM mcr.microsoft.com/dotnet/aspnet:5.0-alpine AS base WORKDIR /app FROM mcr.microsoft.com/dotnet/sdk:5.0-alpine AS build WORKDIR /src COPY . . RUN dotnet restore "semanticsearch.sln" FROM build AS publish RUN dotnet publish "Presentation/semanticsearch.card/semanticsearch.card.csproj" -c Release -o /app/publish --no-restore FROM base AS final WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "semanticsearch.card.dll"]<file_sep>/src/wikia/semanticsearch/src/Infrastructure/semanticsearch.infrastructure/WebPage/SemanticCardSearchResultsWebPage.cs using System; using HtmlAgilityPack; using semanticsearch.domain.WebPage; namespace semanticsearch.infrastructure.WebPage { public class SemanticCardSearchResultsWebPage : ISemanticCardSearchResultsWebPage { public string Name(HtmlNode tableRow) { return tableRow.SelectSingleNode("td[position() = 1]")?.InnerText.Trim(); } public string Url(HtmlNode tableRow, Uri uri) { var cardUrl = tableRow.SelectSingleNode("td[position() = 1]/a")?.Attributes["href"]?.Value; return !string.IsNullOrWhiteSpace(cardUrl) ? $"{uri.GetLeftPart(UriPartial.Authority)}{cardUrl}" : null; } } }<file_sep>/src/wikia/article/src/Application/article.application/ScheduledTasks/Articles/ArticleInformationTaskHandler.cs using System.Linq; using System.Threading; using System.Threading.Tasks; using article.core.ArticleList.Processor; using FluentValidation; using MediatR; namespace article.application.ScheduledTasks.Articles { public class ArticleInformationTaskHandler : IRequestHandler<ArticleInformationTask, ArticleInformationTaskResult> { private readonly IArticleCategoryProcessor _articleCategoryProcessor; private readonly IValidator<ArticleInformationTask> _validator; public ArticleInformationTaskHandler ( IArticleCategoryProcessor articleCategoryProcessor, IValidator<ArticleInformationTask> validator ) { _articleCategoryProcessor = articleCategoryProcessor; _validator = validator; } public async Task<ArticleInformationTaskResult> Handle(ArticleInformationTask request, CancellationToken cancellationToken) { var response = new ArticleInformationTaskResult(); var validationResults = _validator.Validate(request); if (validationResults.IsValid) { var categoryResult = await _articleCategoryProcessor.Process(request.Category, request.PageSize); response.ArticleTaskResults = categoryResult; response.IsSuccessful = true; } else { response.Errors = validationResults.Errors.Select(err => err.ErrorMessage).ToList(); } return response; } } }<file_sep>/src/services/Cards.API/src/Domain/Cards.Domain/Models/Card.cs using Cards.Domain.Enums; namespace Cards.Domain.Models { public class Card { public string Name { get; } protected Card(string name) { Name = name; } } }<file_sep>/src/services/Cards.API/src/Presentation/Cards.API/Controllers/CardsController.cs using Microsoft.AspNetCore.Mvc; namespace Cards.API.Controllers { [Route("api/[controller]")] [ApiController] public class CardsController : ControllerBase { /// <summary> /// Get card by name /// </summary> /// <returns></returns> [HttpGet] public IActionResult Get([FromQuery] string name) { return Ok($"It's working. I found the card {name} in the database"); } } }<file_sep>/src/wikia/data/cardsectiondata/src/Tests/Unit/cardsectiondata.domain.unit.tests/HelpersTests/SectionHelperTests/GetContentListTests.cs using cardsectiondata.domain.Helpers; using cardsectiondata.tests.core; using FluentAssertions; using NUnit.Framework; using wikia.Models.Article.Simple; namespace cardsectiondata.domain.unit.tests.HelpersTests.SectionHelperTests { [TestFixture] [Category(TestType.Unit)] public class GetContentListTests { [TestCaseSource(nameof(_getContentListCases))] public void Given_A_Section_With_ContentList_Should_Use_Recursion_To_Traverse_Data(Section section, string[] expected) { // Assert // Act var result = SectionHelper.GetSectionContentList(section); // Assert result.Should().BeEquivalentTo(expected); } static object[] _getContentListCases = { new object[] {new Section { Content = new[] { new SectionContent { Elements = new[] { new ListElement { Text = "Ancient Fairy Dragon" }, new ListElement { Text = "Blaster, Dragon Ruler of Infernos", Elements = new[] { new ListElement { Text = "Master Peace, the True Dracoslaying King", Elements = new[] { new ListElement { Text = "Mind Master" } } } } }, new ListElement { Text = "Cyber Jar" } } } } }, new [] {"Cyber Jar", "Ancient Fairy Dragon", "Blaster, Dragon Ruler of Infernos", "Master Peace, the True Dracoslaying King", "Mind Master"}} }; } }<file_sep>/src/wikia/data/archetypedata/src/Tests/Unit/archetypedata.domain.unit.tests/ArchetypeProcessorTests/ProcessTests.cs using System; using System.Collections.Generic; using System.Threading.Tasks; using archetypedata.core.Models; using archetypedata.domain.Processor; using archetypedata.domain.Services.Messaging; using archetypedata.domain.WebPages; using archetypedata.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; using wikia.Api; using wikia.Models.Article; using wikia.Models.Article.Details; namespace archetypedata.domain.unit.tests.ArchetypeProcessorTests { [TestFixture] [Category(TestType.Unit)] public class ProcessTests { private IArchetypeWebPage _archetypeWebPage; private IQueue<Archetype> _queue; private ArchetypeProcessor _sut; private IWikiArticle _wikiArticle; [SetUp] public void SetUp() { _archetypeWebPage = Substitute.For<IArchetypeWebPage>(); _queue = Substitute.For<IQueue<Archetype>>(); _wikiArticle = Substitute.For<IWikiArticle>(); _sut = new ArchetypeProcessor(_archetypeWebPage, _queue, _wikiArticle); } [Test] public async Task Given_A_Valid_Article_If_The_Title_Equals_Archetype_IsSuccessful_Should_Be_True() { // Arrange var article = new Article { CorrelationId = Guid.NewGuid(), Id = 909890, Title = "Archetype", Url = "http://yugioh.wikia.com/wiki/Blue-Eyes" }; // Act var result = await _sut.Process(article); // Assert result.IsSuccessful.Should().BeTrue(); } [Test] public async Task Given_A_Valid_Article_If_The_Title_Equals_Archetype_Should_Not_Invoke_WikiaArticle_Details_Method() { // Arrange var article = new Article { CorrelationId = Guid.NewGuid(), Id = 909890, Title = "Archetype", Url = "http://yugioh.wikia.com/wiki/Blue-Eyes" }; // Act await _sut.Process(article); // Assert await _wikiArticle.DidNotReceive().Details(Arg.Any<int>()); } [Test] public async Task Given_A_Valid_Article_If_The_Title_Equals_Archetype_Should_Not_Invoke_ArchetypeThumbnail_Method() { // Arrange var article = new Article { CorrelationId = Guid.NewGuid(), Id = 909890, Title = "Archetype", Url = "http://yugioh.wikia.com/wiki/Blue-Eyes" }; // Act await _sut.Process(article); // Assert await _archetypeWebPage.DidNotReceive().ArchetypeThumbnail(Arg.Any<long>(), Arg.Any<string>()); } [Test] public async Task Given_A_Valid_Article_If_The_Title_Equals_Archetype_Should_Not_Invoke_Publish_Method() { // Arrange var article = new Article { CorrelationId = Guid.NewGuid(), Id = 909890, Title = "Archetype", Url = "http://yugioh.wikia.com/wiki/Blue-Eyes" }; // Act await _sut.Process(article); // Assert await _queue.DidNotReceive().Publish(Arg.Any<Archetype>()); } [Test] public async Task Given_A_Valid_Article_If_Processed_Successfully_IsSuccessful_Should_Be_True() { // Arrange var article = new Article { CorrelationId = Guid.NewGuid(), Id = 909890, Title = "Blue-Eyes", Url = "http://yugioh.wikia.com/wiki/Blue-Eyes" }; _wikiArticle.Details(Arg.Any<int>()).Returns(new ExpandedArticleResultSet { Items = new Dictionary<string, ExpandedArticle> { ["690148"] = new() { Revision = new Revision {Timestamp = 1563318260} } } }); // Act var result = await _sut.Process(article); // Assert result.IsSuccessful.Should().BeTrue(); } [Test] public async Task Given_A_Valid_Article_Should_Invoke_WikiaArticle_Details_Once() { // Arrange var article = new Article { CorrelationId = Guid.NewGuid(), Id = 909890, Title = "Blue-Eyes", Url = "http://yugioh.wikia.com/wiki/Blue-Eyes" }; _wikiArticle.Details(Arg.Any<int>()).Returns(new ExpandedArticleResultSet { Items = new Dictionary<string, ExpandedArticle> { ["690148"] = new() { Revision = new Revision { Timestamp = 1563318260 } } } }); // Act await _sut.Process(article); // Assert await _wikiArticle.Received(1).Details(Arg.Any<int>()); } [Test] public async Task Given_A_Valid_Article_Should_Invoke_ArchetypeThumbnail_Once() { // Arrange var article = new Article { CorrelationId = Guid.NewGuid(), Id = 909890, Title = "Blue-Eyes", Url = "http://yugioh.wikia.com/wiki/Blue-Eyes" }; _wikiArticle.Details(Arg.Any<int>()).Returns(new ExpandedArticleResultSet { Items = new Dictionary<string, ExpandedArticle> { ["690148"] = new() { Revision = new Revision { Timestamp = 1563318260 } } } }); // Act await _sut.Process(article); // Assert _archetypeWebPage.Received(1).ArchetypeThumbnail(Arg.Any<KeyValuePair<string, ExpandedArticle>>(), Arg.Any<string>()); } [Test] public async Task Given_A_Valid_Article_Should_Invoke_Publish_Once() { // Arrange var article = new Article { CorrelationId = Guid.NewGuid(), Id = 909890, Title = "Blue-Eyes", Url = "http://yugioh.wikia.com/wiki/Blue-Eyes" }; _wikiArticle.Details(Arg.Any<int>()).Returns(new ExpandedArticleResultSet { Items = new Dictionary<string, ExpandedArticle> { ["690148"] = new ExpandedArticle { Revision = new Revision { Timestamp = 1563318260 } } } }); // Act await _sut.Process(article); // Assert await _queue.Received(1).Publish(Arg.Any<Archetype>()); } } } <file_sep>/src/wikia/processor/banlistprocessor/src/Application/banlistprocessor.application/MessageConsumers/BanlistData/BanlistDataConsumerHandler.cs using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using banlistprocessor.core.Models; using banlistprocessor.core.Services; using MediatR; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace banlistprocessor.application.MessageConsumers.BanlistData { public class BanlistDataConsumerHandler : IRequestHandler<BanlistDataConsumer, BanlistDataConsumerResult> { private readonly IBanlistService _banlistService; private readonly ILogger<BanlistDataConsumerHandler> _logger; public BanlistDataConsumerHandler(IBanlistService banlistService, ILogger<BanlistDataConsumerHandler> logger) { _banlistService = banlistService; _logger = logger; } public async Task<BanlistDataConsumerResult> Handle(BanlistDataConsumer request, CancellationToken cancellationToken) { var banlistDataConsumerResult = new BanlistDataConsumerResult(); try { var yugiohBanlist = JsonConvert.DeserializeObject<YugiohBanlist>(request.Message); if (yugiohBanlist != null && yugiohBanlist.Sections.Any()) { banlistDataConsumerResult.YugiohBanlist = yugiohBanlist; _logger.LogInformation( $"{yugiohBanlist.BanlistType.ToString()}, {yugiohBanlist.Title}, {yugiohBanlist.StartDate}"); var banlistExists = await _banlistService.BanlistExist(yugiohBanlist.ArticleId); var result = banlistExists ? await _banlistService.Update(yugiohBanlist) : await _banlistService.Add(yugiohBanlist); banlistDataConsumerResult.BanlistId = result.Id; } else { _logger.LogInformation("Banlist not processed, {@Title}, {@StartDate}", yugiohBanlist.Title, yugiohBanlist.StartDate); } } catch (ArgumentNullException ex) { _logger.LogError("Argument {@Param} was null. Message: {@Message}: ", ex.ParamName, request.Message); } catch (NullReferenceException ex) { _logger.LogError("Null reference exception {@Message}. Exception: {@Exception}: ", request.Message, ex); } catch (Exception ex) { _logger.LogError("Unexpected error occured {@Exception}: ", ex); } return banlistDataConsumerResult; } } }<file_sep>/src/wikia/article/src/Tests/Unit/article.application.unit.tests/ScheduledTasksTests/BanlistInformationTaskHandlerTests.cs using article.application.ScheduledTasks.LatestBanlist; using article.core.ArticleList.Processor; using article.core.Enums; using article.domain.Banlist.Processor; using article.tests.core; using FluentAssertions; using FluentValidation; using FluentValidation.Results; using NSubstitute; using NUnit.Framework; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace article.application.unit.tests.ScheduledTasksTests { [TestFixture] [Category(TestType.Unit)] public class BanlistInformationTaskHandlerTests { private IArticleCategoryProcessor _articleCategoryProcessor; private IValidator<BanlistInformationTask> _validator; private IBanlistProcessor _banlistProcessor; private BanlistInformationTaskHandler _sut; [SetUp] public void SetUp() { _articleCategoryProcessor = Substitute.For<IArticleCategoryProcessor>(); _validator = Substitute.For<IValidator<BanlistInformationTask>>(); _banlistProcessor = Substitute.For<IBanlistProcessor>(); _sut = new BanlistInformationTaskHandler ( _articleCategoryProcessor, _validator, _banlistProcessor ); } [Test] public async Task Given_A_BanlistInformationTask_If_Validation_Fails_Should_Return_Errors() { // Arrange _validator.Validate(Arg.Any<BanlistInformationTask>()).Returns(new ValidationResult(new List<ValidationFailure> { new ValidationFailure("propertyName", "failed") })); // Act var result = await _sut.Handle(new BanlistInformationTask(), CancellationToken.None); // Assert result.Errors.Should().NotBeNullOrEmpty(); } [Test] public async Task Given_A_BanlistInformationTask_If_Validation_Fails_Should_Not_Invoke_ArticleCategoryProcessor_Process_Method() { // Arrange _validator.Validate(Arg.Any<BanlistInformationTask>()).Returns(new ValidationResult(new List<ValidationFailure> { new ValidationFailure("propertyName", "failed") })); // Act await _sut.Handle(new BanlistInformationTask(), CancellationToken.None); // Assert await _articleCategoryProcessor.DidNotReceive().Process(Arg.Any<string>(), Arg.Any<int>()); } [Test] public async Task Given_A_BanlistInformationTask_If_Validation_Fails_Should_Not_Invoke_BanlistProcessor_Process_Method() { // Arrange _validator.Validate(Arg.Any<BanlistInformationTask>()).Returns(new ValidationResult(new List<ValidationFailure> { new ValidationFailure("propertyName", "failed") })); // Act await _sut.Handle(new BanlistInformationTask(), CancellationToken.None); // Assert await _banlistProcessor.DidNotReceive().Process(Arg.Any<BanlistType>()); } [Test] public async Task Given_A_BanlistInformationTask_If_Validation_Is_Succesful_Should_Be_true() { // Arrange var banlistInformationTask = new BanlistInformationTask{ Category = "banlist", PageSize = 8}; _validator.Validate(Arg.Any<BanlistInformationTask>()).Returns(new BanlistInformationTaskValidator().Validate(banlistInformationTask)); // Act var result = await _sut.Handle(banlistInformationTask, CancellationToken.None); // Assert result.IsSuccessful.Should().BeTrue(); } [Test] public async Task Given_A_BanlistInformationTask_If_Validation_Is_Succesful_Should_Invoke_BanlistProcessor_Process_Method_Twice() { // Arrange const int expected = 2; var banlistInformationTask = new BanlistInformationTask { Category = "banlist", PageSize = 8 }; _validator.Validate(Arg.Any<BanlistInformationTask>()).Returns(new BanlistInformationTaskValidator().Validate(banlistInformationTask)); // Act await _sut.Handle(banlistInformationTask, CancellationToken.None); // Assert await _banlistProcessor.Received(expected).Process(Arg.Any<BanlistType>()); } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Core/cardsectionprocessor.core/Constants/ArticleCategory.cs namespace cardsectionprocessor.core.Constants { public static class ArticleCategory { public const string CardTips = "Card Tips"; public const string CardRulings = "Card Rulings"; public const string CardTrivia = "Card Trivia"; } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Application/archetypeprocessor.application/MessageConsumers/ArchetypeInformation/ArchetypeInformationConsumerValidator.cs using FluentValidation; namespace archetypeprocessor.application.MessageConsumers.ArchetypeInformation { public class ArchetypeInformationConsumerValidator : AbstractValidator<ArchetypeInformationConsumer> { public ArchetypeInformationConsumerValidator() { RuleFor(ci => ci.Message) .NotNull() .NotEmpty(); } } }<file_sep>/src/wikia/article/src/Application/article.application/ScheduledTasks/Articles/ArticleInformationTaskResult.cs using article.core.Models; using System.Collections.Generic; namespace article.application.ScheduledTasks.Articles { public class ArticleInformationTaskResult { public ArticleBatchTaskResult ArticleTaskResults { get; set; } public List<string> Errors { get; set; } public bool IsSuccessful { get; set; } } }<file_sep>/src/wikia/data/banlistdata/src/Application/banlistdata.application/MessageConsumers/BanlistInformation/BanlistInformationConsumer.cs using MediatR; namespace banlistdata.application.MessageConsumers.BanlistInformation { public class BanlistInformationConsumer : IRequest<BanlistInformationConsumerResult> { public string Message { get; set; } } }<file_sep>/src/wikia/data/archetypedata/src/Tests/Unit/archetypedata.infrastructure.unit.tests/WebPagesTests/ArchetypeThumbnailTests/FromArticleDetailsTests.cs using System.Collections.Generic; using System.Threading.Tasks; using archetypedata.application.Configuration; using archetypedata.domain.WebPages; using archetypedata.infrastructure.WebPages; using archetypedata.tests.core; using FluentAssertions; using Microsoft.Extensions.Options; using NSubstitute; using NUnit.Framework; using wikia.Api; using wikia.Models.Article.Details; namespace archetypedata.infrastructure.unit.tests.WebPagesTests.ArchetypeThumbnailTests { [TestFixture] [Category(TestType.Unit)] public class FromArticleDetailsTests { private ArchetypeThumbnail _sut; private IWikiArticle _wikiArticle; [SetUp] public void SetUp() { _wikiArticle = Substitute.For<IWikiArticle>(); _sut = new ArchetypeThumbnail(_wikiArticle, Substitute.For<IHtmlWebPage>(), Substitute.For<IOptions<AppSettings>>()); } [Test] public void Given_ArticleDetails_Should_Extract_Article_Thumbnail() { // Arrange const string expected = "https://static.wikia.nocookie.net/yugioh/images/7/7c/Tentacluster.png"; var articleDetails = new KeyValuePair<string, ExpandedArticle>("666747", new ExpandedArticle { Thumbnail = "https://static.wikia.nocookie.net/yugioh/images/7/7c/Tentacluster.png/revision/latest/smart/width/200/height/200?cb=20170830132740" }); // Act var result = _sut.FromArticleDetails(articleDetails); // Assert result.Should().BeEquivalentTo(expected); } [Test] public async Task Given_An_Article_Id_Should_Invoke_Wikia_Details_Method_Once() { // Arrange const int expected = 1; const int articleId = 666747; _wikiArticle.Details(Arg.Any<int>()).Returns(new ExpandedArticleResultSet { Items = new Dictionary<string, ExpandedArticle> { ["666747"] = new() { Thumbnail = "https://static.wikia.nocookie.net/yugioh/images/7/7c/Tentacluster.png/revision/latest/smart/width/200/height/200?cb=20170830132740" } } }); // Act await _sut.FromArticleId(articleId); // Assert await _wikiArticle.Received(expected).Details(Arg.Is(articleId)); } } }<file_sep>/src/services/Cards.API/src/Presentation/Cards.API/Services/CardProcessorHostedService.cs using System; using System.Text; using System.Threading; using System.Threading.Tasks; using Cards.Application.Configuration; using Cards.Application.MessageConsumers.CardData; using MediatR; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using RabbitMQ.Client; using RabbitMQ.Client.Events; using RabbitMQ.Client.Exceptions; namespace Cards.API.Services { public sealed class CardProcessorHostedService : BackgroundService { private const string CardDataQueue = "card-data"; private readonly ILogger<CardProcessorHostedService> _logger; private readonly IOptions<RabbitMqSettings> _rabbitMqOptions; private readonly IMediator _mediator; private ConnectionFactory _factory; private IConnection _connection; private IModel _channel; public CardProcessorHostedService ( ILogger<CardProcessorHostedService> logger, IOptions<RabbitMqSettings> rabbitMqOptions, IMediator mediator ) { _logger = logger; _rabbitMqOptions = rabbitMqOptions; _mediator = mediator; } protected override Task ExecuteAsync(CancellationToken stoppingToken) { stoppingToken.ThrowIfCancellationRequested(); _factory = new ConnectionFactory { HostName = _rabbitMqOptions.Value.Host, Port = _rabbitMqOptions.Value.Port, UserName = _rabbitMqOptions.Value.Username, Password = _rabbitMqOptions.Value.Password, DispatchConsumersAsync = true }; _connection = _factory.CreateConnection(); _channel = _connection.CreateModel(); _channel.BasicQos(0, 1, false); var consumer = new AsyncEventingBasicConsumer(_channel); consumer.Received += async (_, ea) => { try { var body = ea.Body.ToArray(); var message = Encoding.UTF8.GetString(body); var result = await _mediator.Send(new CardInformationConsumer(message), stoppingToken); if (result.IsSuccessful) { _channel.BasicAck(ea.DeliveryTag, false); } else { _channel.BasicNack(ea.DeliveryTag, false, false); } await Task.Yield(); } catch (RabbitMQClientException ex) { _logger.LogError("RabbitMq Consumer: '{CardArticleQueue}' exception. Exception: {@Exception}", _rabbitMqOptions.Value.Queues[CardDataQueue], ex); } catch (Exception ex) { _logger.LogError("Unexpected exception occurred for RabbitMq Consumer: '{CardArticleQueue}'. Exception: {@Exception}", _rabbitMqOptions.Value.Queues[CardDataQueue], ex); } }; _channel.BasicConsume(_rabbitMqOptions.Value.Queues[CardDataQueue].Name, _rabbitMqOptions.Value.Queues[CardDataQueue].AutoAck, consumer); return Task.CompletedTask; } public override void Dispose() { _channel.Close(); _connection.Close(); base.Dispose(); } } }<file_sep>/src/wikia/processor/banlistprocessor/README.md ![alt text](https://fablecode.visualstudio.com/Yugioh%20Insight/_apis/build/status/Build_ArticleData "Visual studio team services build status") # Banlist Processor Persists banlist related data.<file_sep>/src/wikia/processor/banlistprocessor/src/Core/banlistprocessor.core/Models/YugiohBanlistSection.cs using System.Collections.Generic; namespace banlistprocessor.core.Models { public class YugiohBanlistSection { public string Title { get; set; } public List<string> Content { get; set; } } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/Configuration/QueueSetting.cs namespace cardprocessor.application.Configuration { public class QueueSetting { public string Name { get; set; } public bool AutoAck { get; set; } } }<file_sep>/src/wikia/processor/cardprocessor/src/Tests/Unit/cardprocessor.application.unit.tests/MappingsTests/MapperTests/CardCommandMapperTests/MapToUpdateCommandTests.cs using cardprocessor.application.Mappings.Mappers; using cardprocessor.core.Models; using cardprocessor.core.Models.Db; using cardprocessor.core.Services; using cardprocessor.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; namespace cardprocessor.application.unit.tests.MappingsTests.MapperTests.CardCommandMapperTests { [TestFixture] [Category(TestType.Unit)] public class MapToUpdateCommandTests { private ICategoryService _categoryService; private ISubCategoryService _subCategoryService; private ITypeService _typeService; private IAttributeService _attributeService; private ILinkArrowService _linkArrowService; private CardCommandMapper _sut; [SetUp] public void SetUp() { _categoryService = Substitute.For<ICategoryService>(); _subCategoryService = Substitute.For<ISubCategoryService>(); _typeService = Substitute.For<ITypeService>(); _attributeService = Substitute.For<IAttributeService>(); _linkArrowService = Substitute.For<ILinkArrowService>(); _categoryService.AllCategories().Returns(TestData.AllCategories()); _subCategoryService.AllSubCategories().Returns(TestData.AllSubCategories()); _typeService.AllTypes().Returns(TestData.AllTypes()); _attributeService.AllAttributes().Returns(TestData.AllAttributes()); _linkArrowService.AllLinkArrows().Returns(TestData.AllLinkArrows()); _sut = new CardCommandMapper ( _categoryService, _subCategoryService, _typeService, _attributeService, _linkArrowService ); } [Test] public void Given_A_Valid_Spell_Type_YugiohCard_Should_Return_AddCommand() { // Arrange var yugiohCard = new YugiohCard { Name = "Black Illusion Ritual", Description = "Amazing card!", CardNumber = "41426869", Property = "Ritual", CardType = "Spell", ImageUrl = "https://vignette.wikia.nocookie.net/yugioh/images/8/82/BlackIllusionRitual-LED2-EN-C-1E.png/revision/latest/scale-to-width-down/300?cb=20180223153750" }; var cardToUpdate = new Card{ Id = 23424}; // Act var result = _sut.MapToUpdateCommand(yugiohCard, cardToUpdate); // Assert result.Should().NotBeNull(); } [Test] public void Given_A_Valid_Trap_Type_YugiohCard_Should_Return_AddCommand() { // Arrange var yugiohCard = new YugiohCard { Name = "<NAME>", Description = "Amazing card!", CardNumber = "97077563", Property = "Continuous", CardType = "Trap", ImageUrl = "https://vignette.wikia.nocookie.net/yugioh/images/4/47/CalloftheHaunted-YS18-EN-C-1E.png/revision/latest/scale-to-width-down/300?cb=20180712163539" }; var cardToUpdate = new Card { Id = 23424 }; // Act var result = _sut.MapToUpdateCommand(yugiohCard, cardToUpdate); // Assert result.Should().NotBeNull(); } [Test] public void Given_A_Valid_Monster_Type_YugiohCard_Should_Return_AddCommand() { // Arrange var yugiohCard = new YugiohCard { Name = "<NAME>", Description = "Amazing card!", CardNumber = "543534", Attribute = "Dark", Types = "Effect/Ritual/Dragon", CardType = "Monster", Rank = 3, AtkLink = "2300 / 3", ImageUrl = "https://vignette.wikia.nocookie.net/yugioh/images/b/b4/BlueEyesWhiteDragon-LED3-EN-C-1E.png/revision/latest/scale-to-width-down/300?cb=20180928161125" }; var cardToUpdate = new Card { Id = 23424 }; // Act var result = _sut.MapToUpdateCommand(yugiohCard, cardToUpdate); // Assert result.Should().NotBeNull(); } } }<file_sep>/src/wikia/data/carddata/src/Core/carddata.core/Processor/IArticleProcessor.cs using System.Threading.Tasks; using carddata.core.Models; namespace carddata.core.Processor { public interface IArticleProcessor { Task<ArticleConsumerResult> Process(Article article); } }<file_sep>/src/wikia/data/archetypedata/src/Domain/archetypedata.domain/WebPages/IArchetypeThumbnail.cs using System.Collections.Generic; using System.Threading.Tasks; using wikia.Models.Article.Details; namespace archetypedata.domain.WebPages { public interface IArchetypeThumbnail { Task<string> FromArticleId(int articleId); string FromArticleDetails(KeyValuePair<string, ExpandedArticle> articleDetails); string FromWebPage(string url); } }<file_sep>/src/wikia/processor/cardprocessor/src/Tests/Unit/cardprocessor.application.unit.tests/Commands/DownloadImageCommandHandlerTests.cs using cardprocessor.application.Commands.DownloadImage; using cardprocessor.core.Models; using cardprocessor.core.Services.Messaging.Cards; using cardprocessor.tests.core; using FluentAssertions; using FluentValidation; using FluentValidation.Results; using NSubstitute; using NUnit.Framework; using System; using System.Threading; using System.Threading.Tasks; namespace cardprocessor.application.unit.tests.Commands { [TestFixture] [Category(TestType.Unit)] public class DownloadImageCommandHandlerTests { private ICardImageQueueService _cardImageQueueService; private IValidator<DownloadImageCommand> _validator; private DownloadImageCommandHandler _sut; [SetUp] public void SetUp() { _cardImageQueueService = Substitute.For<ICardImageQueueService>(); _validator = Substitute.For<IValidator<DownloadImageCommand>>(); _sut = new DownloadImageCommandHandler(_cardImageQueueService, _validator); } [Test] public async Task Given_An_Invalid_DownloadImageCommand_Should_Return_Errors() { // Arrange var downloadImageCommand = new DownloadImageCommand(); _validator.Validate(Arg.Any<DownloadImageCommand>()).Returns(new ValidationResult { Errors = { new ValidationFailure("Validation property", "Validation failed")} }); // Act var result = await _sut.Handle(downloadImageCommand, CancellationToken.None); // Assert result.Errors.Should().NotBeNullOrEmpty(); } [Test] public async Task Given_An_Valid_DownloadImageCommand_Should_Execute_Publish_Method_Once() { // Arrange var downloadImageCommand = new DownloadImageCommand { ImageFolderPath = @"c:\windows", ImageFileName = "Call Of The Haunted", RemoteImageUrl = new Uri("http://filesomewhere/callofthehaunted.png") }; _validator.Validate(Arg.Any<DownloadImageCommand>()).Returns(new DownloadImageCommandValidator().Validate(downloadImageCommand)); _cardImageQueueService.Publish(Arg.Any<DownloadImage>()).Returns(new CardImageCompletion()); // Act await _sut.Handle(downloadImageCommand, CancellationToken.None); // Assert await _cardImageQueueService.Received(1).Publish(Arg.Any<DownloadImage>()); } [Test] public async Task Given_An_Valid_DownloadImageCommand_If_Publish_Fails_IsSuccessful_Should_Be_False() { // Arrange var downloadImageCommand = new DownloadImageCommand { ImageFolderPath = @"c:\windows", ImageFileName = "Call Of The Haunted", RemoteImageUrl = new Uri("http://filesomewhere/callofthehaunted.png") }; _validator.Validate(Arg.Any<DownloadImageCommand>()).Returns(new DownloadImageCommandValidator().Validate(downloadImageCommand)); _cardImageQueueService.Publish(Arg.Any<DownloadImage>()).Returns(new CardImageCompletion()); // Act var result = await _sut.Handle(downloadImageCommand, CancellationToken.None); // Assert result.IsSuccessful.Should().BeFalse(); } [Test] public async Task Given_An_Valid_DownloadImageCommand_If_Publish_Succeeds_IsSuccessful_Should_Be_True() { // Arrange var downloadImageCommand = new DownloadImageCommand { ImageFolderPath = @"c:\windows", ImageFileName = "Call Of The Haunted", RemoteImageUrl = new Uri("http://filesomewhere/callofthehaunted.png") }; _validator.Validate(Arg.Any<DownloadImageCommand>()).Returns(new DownloadImageCommandValidator().Validate(downloadImageCommand)); _cardImageQueueService.Publish(Arg.Any<DownloadImage>()).Returns(new CardImageCompletion{ IsSuccessful = true }); // Act var result = await _sut.Handle(downloadImageCommand, CancellationToken.None); // Assert result.IsSuccessful.Should().BeTrue(); } } }<file_sep>/src/wikia/processor/banlistprocessor/src/Application/banlistprocessor.application/MessageConsumers/BanlistData/BanlistDataConsumer.cs using MediatR; namespace banlistprocessor.application.MessageConsumers.BanlistData { public class BanlistDataConsumer : IRequest<BanlistDataConsumerResult> { public string Message { get; set; } } }<file_sep>/src/wikia/data/carddata/src/Application/carddata.application/MessageConsumers/CardInformation/CardInformationConsumer.cs using MediatR; namespace carddata.application.MessageConsumers.CardInformation { public class CardInformationConsumer : IRequest<CardInformationConsumerResult> { public string Message { get; set; } } }<file_sep>/src/wikia/article/src/Application/article.application/ScheduledTasks/Archetype/ArchetypeInformationTask.cs using MediatR; namespace article.application.ScheduledTasks.Archetype { public class ArchetypeInformationTask : IRequest<ArchetypeInformationTaskResult> { public string Category { get; set; } public int PageSize { get; set; } } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Application/archetypeprocessor.application/MessageConsumers/ArchetypeInformation/ArchetypeInformationConsumer.cs using MediatR; namespace archetypeprocessor.application.MessageConsumers.ArchetypeInformation { public class ArchetypeInformationConsumer : IRequest<ArchetypeInformationConsumerResult> { public string Message { get; set; } } }<file_sep>/src/wikia/article/src/Application/article.application/ApplicationInstaller.cs using article.application.Decorators.Loggers; using article.application.ScheduledTasks.Archetype; using article.application.ScheduledTasks.Articles; using article.application.ScheduledTasks.LatestBanlist; using article.core.ArticleList.DataSource; using article.core.ArticleList.Processor; using article.domain.ArticleList.DataSource; using article.domain.ArticleList.Item; using article.domain.ArticleList.Processor; using article.domain.Banlist.DataSource; using article.domain.Banlist.Processor; using FluentValidation; using MediatR; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using System.Reflection; using article.domain.Settings; using wikia.Api; namespace article.application { public static class ApplicationInstaller { public static IServiceCollection AddApplicationServices(this IServiceCollection services) { services .AddCqrs() .AddValidation() .AddDomainServices() .AddDecorators(); return services; } private static IServiceCollection AddCqrs(this IServiceCollection services) { services.AddMediatR(typeof(ApplicationInstaller).GetTypeInfo().Assembly); return services; } private static IServiceCollection AddDomainServices(this IServiceCollection services) { services.AddTransient<IArticleCategoryDataSource, ArticleCategoryDataSource>(); services.AddTransient<IArticleBatchProcessor, ArticleBatchProcessor>(); services.AddTransient<IArticleCategoryProcessor, ArticleCategoryProcessor>(); services.AddTransient<IArticleProcessor, ArticleProcessor>(); services.AddTransient<IBanlistProcessor, BanlistProcessor>(); services.AddTransient<IBanlistUrlDataSource, BanlistUrlDataSource>(); services.AddTransient<IArticleItemProcessor, CardItemProcessor>(); services.AddTransient<IArticleItemProcessor, BanlistItemProcessor>(); services.AddTransient<IArticleItemProcessor, ArchetypeItemProcessor>(); services.AddTransient<IArticleItemProcessor, ArticleItemProcessor>(); var appSettings = services.BuildServiceProvider().GetService<IOptions<AppSettings>>(); services.AddSingleton<IWikiArticleList>(new WikiArticleList(appSettings.Value.WikiaDomainUrl)); return services; } private static IServiceCollection AddValidation(this IServiceCollection services) { services.AddTransient<IValidator<BanlistInformationTask>, BanlistInformationTaskValidator>(); services.AddTransient<IValidator<ArchetypeInformationTask>, ArchetypeInformationTaskValidator>(); services.AddTransient<IValidator<ArticleInformationTask>, ArticleInformationTaskValidator>(); return services; } private static IServiceCollection AddDecorators(this IServiceCollection services) { services.Decorate<IArticleProcessor, ArticleProcessorLoggerDecorator>(); return services; } } }<file_sep>/src/wikia/processor/archetypeprocessor/README.md ![alt text](https://fablecode.visualstudio.com/Yugioh%20Insight/_apis/build/status/Build-ArchetypeProcessor "Visual studio team services build status") # Archetype Processor Persists archetype related data.<file_sep>/src/wikia/semanticsearch/src/Core/semanticsearch.core/Model/SemanticCard.cs using System; namespace semanticsearch.core.Model { public class SemanticCard { public Guid CorrelationId { get; set; } public string Title { get; set; } public string Url { get; set; } } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Tests/Unit/archetypeprocessor.domain.unit.tests/ServicesTests/ArchetypeServiceTests/ArchetypeByNameTests.cs using System.Threading.Tasks; using archetypeprocessor.domain.Repository; using archetypeprocessor.domain.Services; using archetypeprocessor.tests.core; using NSubstitute; using NUnit.Framework; namespace archetypeprocessor.domain.unit.tests.ServicesTests.ArchetypeServiceTests { [TestFixture] [Category(TestType.Unit)] public class ArchetypeByNameTests { private IArchetypeRepository _archetypeRepository; private ArchetypeService _sut; [SetUp] public void SetUp() { _archetypeRepository = Substitute.For<IArchetypeRepository>(); _sut = new ArchetypeService(_archetypeRepository); } [Test] public async Task Given_An_Archetype_Name_Should_Invoke_ArchetypeByName_Method_Once() { // Arrange const string archetypeName = "Blue-Eyes"; // Act await _sut.ArchetypeByName(archetypeName); // Assert await _archetypeRepository.Received(1).ArchetypeByName(Arg.Is(archetypeName)); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/MessageConsumers/CardData/CardDataConsumerResult.cs using System; namespace cardprocessor.application.MessageConsumers.CardData { public class CardDataConsumerResult { public bool IsSuccessful { get; set; } public string Errors { get; set; } public Exception Exception { get; set; } } }<file_sep>/src/wikia/processor/cardprocessor/src/Core/cardprocessor.core/Services/ITypeService.cs using System.Collections.Generic; using System.Threading.Tasks; using cardprocessor.core.Models.Db; namespace cardprocessor.core.Services { public interface ITypeService { Task<List<Type>> AllTypes(); } }<file_sep>/src/wikia/data/archetypedata/src/Domain/archetypedata.domain/Processor/ArchetypeProcessor.cs using archetypedata.core.Models; using archetypedata.core.Processor; using archetypedata.domain.Services.Messaging; using archetypedata.domain.WebPages; using System; using System.Linq; using System.Threading.Tasks; using wikia.Api; namespace archetypedata.domain.Processor { public class ArchetypeProcessor : IArchetypeProcessor { private readonly IArchetypeWebPage _archetypeWebPage; private readonly IQueue<Archetype> _queue; private readonly IWikiArticle _wikiArticle; public ArchetypeProcessor(IArchetypeWebPage archetypeWebPage, IQueue<Archetype> queue, IWikiArticle wikiArticle) { _archetypeWebPage = archetypeWebPage; _queue = queue; _wikiArticle = wikiArticle; } public async Task<ArticleTaskResult> Process(Article article) { var articleTaskResult = new ArticleTaskResult { Article = article }; if (!article.Title.Equals("Archetype", StringComparison.OrdinalIgnoreCase)) { var articleDetailsList = await _wikiArticle.Details((int)article.Id); var articleDetails = articleDetailsList.Items.First(); var epoch = articleDetails.Value.Revision.Timestamp; var thumbNailUrl = _archetypeWebPage.ArchetypeThumbnail(articleDetails, article.Url); var archetype = new Archetype { Id = article.Id, Name = article.Title, Revision = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(epoch), ImageUrl = thumbNailUrl, ProfileUrl = article.Url }; await _queue.Publish(archetype); } return articleTaskResult; } } } <file_sep>/src/wikia/article/src/Domain/article.domain/Banlist/DataSource/BanlistUrlDataSource.cs using System.Collections.Generic; using System.Text.RegularExpressions; using article.core.Enums; using article.domain.WebPages; using article.domain.WebPages.Banlists; namespace article.domain.Banlist.DataSource { public sealed class BanlistUrlDataSource : IBanlistUrlDataSource { private readonly IBanlistWebPage _banlistWebPage; private readonly IHtmlWebPage _htmlWebPage; public BanlistUrlDataSource(IBanlistWebPage banlistWebPage, IHtmlWebPage htmlWebPage) { _banlistWebPage = banlistWebPage; _htmlWebPage = htmlWebPage; } public IDictionary<int, List<int>> GetBanlists(BanlistType banlistType, string banlistUrl) { var articleIdsList = new Dictionary<int, List<int>>(); var articleIdRegex = new Regex("wgArticleId=([^,]*),"); var banlistUrlsByYear = _banlistWebPage.GetBanlistUrlList(banlistType, banlistUrl); foreach (var (year, banlistUrls) in banlistUrlsByYear) { var banlistYear = int.Parse(year); var articleIds = new List<int>(); foreach (var url in banlistUrls) { var banlistPageHtml = _htmlWebPage.Load(url).DocumentNode.InnerHtml; var match = articleIdRegex.Match(banlistPageHtml); var wgArticleId = int.Parse(match.Groups[1].Value); articleIds.Add(wgArticleId); } articleIdsList.Add(banlistYear, articleIds); } return articleIdsList; } } }<file_sep>/src/wikia/data/archetypedata/src/Presentation/archetypedata/Services/ArchetypeSupportCardDataHostedService.cs using archetypedata.application.Configuration; using archetypedata.application.MessageConsumers.ArchetypeCardInformation; using MediatR; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Text; using System.Threading; using System.Threading.Tasks; namespace archetypedata.Services { public sealed class ArchetypeSupportCardDataHostedService : BackgroundService { private const string ArchetypeSupportCardArticleQueue = "archetype-support-cards-article"; private readonly ILogger<ArchetypeCardDataHostedService> _logger; private readonly IOptions<RabbitMqSettings> _rabbitMqOptions; private readonly IOptions<AppSettings> _appSettingsOptions; private readonly IMediator _mediator; private ConnectionFactory _factory; private IConnection _connection; private IModel _channel; public ArchetypeSupportCardDataHostedService ( ILogger<ArchetypeCardDataHostedService> logger, IOptions<RabbitMqSettings> rabbitMqOptions, IOptions<AppSettings> appSettingsOptions, IMediator mediator ) { _logger = logger; _rabbitMqOptions = rabbitMqOptions; _appSettingsOptions = appSettingsOptions; _mediator = mediator; } protected override Task ExecuteAsync(CancellationToken stoppingToken) { stoppingToken.ThrowIfCancellationRequested(); _factory = new ConnectionFactory() { HostName = _rabbitMqOptions.Value.Host, UserName = _rabbitMqOptions.Value.Username, Password = _<PASSWORD> }; _connection = _factory.CreateConnection(); _channel = _connection.CreateModel(); var consumer = new EventingBasicConsumer(_channel); consumer.Received += async (_, ea) => { try { var body = ea.Body.ToArray(); var message = Encoding.UTF8.GetString(body); var result = await _mediator.Send(new ArchetypeCardInformationConsumer { Message = message }, stoppingToken); if (result.IsSuccessful) { _channel.BasicAck(ea.DeliveryTag, false); } else { _channel.BasicNack(ea.DeliveryTag, false, false); } } catch (Exception ex) { _logger.LogError("RabbitMq Consumer: '{ArchetypeSupportCardArticleQueue}' exception. Exception: {Exception}", ArchetypeSupportCardArticleQueue, ex); } }; consumer.Shutdown += OnArchetypeSupportCardArticleConsumerShutdown; consumer.Registered += OnArchetypeSupportCardArticleConsumerRegistered; consumer.Unregistered += OnArchetypeSupportCardArticleConsumerUnregistered; consumer.ConsumerCancelled += OnArchetypeSupportCardArticleConsumerCancelled; _channel.BasicConsume(ArchetypeSupportCardArticleQueue, false, consumer); return Task.CompletedTask; } #region private helper private void OnArchetypeSupportCardArticleConsumerCancelled(object sender, ConsumerEventArgs e) { _logger.LogInformation("Consumer '{ArchetypeSupportCardArticleQueue}' Cancelled", ArchetypeSupportCardArticleQueue); } private void OnArchetypeSupportCardArticleConsumerUnregistered(object sender, ConsumerEventArgs e) { _logger.LogInformation("Consumer '{ArchetypeSupportCardArticleQueue}' Unregistered", ArchetypeSupportCardArticleQueue); } private void OnArchetypeSupportCardArticleConsumerRegistered(object sender, ConsumerEventArgs e) { _logger.LogInformation("Consumer '{ArchetypeSupportCardArticleQueue}' Registered", ArchetypeSupportCardArticleQueue); } private void OnArchetypeSupportCardArticleConsumerShutdown(object sender, ShutdownEventArgs e) { _logger.LogInformation("Consumer '{ArchetypeSupportCardArticleQueue}' Shutdown", ArchetypeSupportCardArticleQueue); } #endregion public override void Dispose() { _channel.Close(); _connection.Close(); base.Dispose(); } } }<file_sep>/src/wikia/data/cardsectiondata/src/Tests/Unit/cardsectiondata.domain.unit.tests/ArticleListTests/ItemTests/CardRulingItemProcessorTests/HandlesTests.cs using cardsectiondata.core.Constants; using cardsectiondata.core.Processor; using cardsectiondata.domain.ArticleList.Item; using cardsectiondata.domain.Services.Messaging; using cardsectiondata.tests.core; using FluentAssertions; using NSubstitute; using NUnit.Framework; using System.Collections.Generic; namespace cardsectiondata.domain.unit.tests.ArticleListTests.ItemTests.CardRulingItemProcessorTests { [TestFixture] [Category(TestType.Unit)] public class HandlesTests { private IEnumerable<IQueue> _queues; private CardRulingItemProcessor _sut; [SetUp] public void SetUp() { _queues = Substitute.For<IEnumerable<IQueue>>(); _sut = new CardRulingItemProcessor(Substitute.For<ICardSectionProcessor>(), _queues); } [TestCase(ArticleCategory.CardRulings)] public void Given_A_Valid_Category_Should_Return_True(string category) { // Arrange // Act var result = _sut.Handles(category); // Assert result.Should().BeTrue(); } [TestCase("category")] public void Given_A_Valid_Category_Should_Return_False(string category) { // Arrange // Act var result = _sut.Handles(category); // Assert result.Should().BeFalse(); } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Domain/cardsectionprocessor.domain/Processor/CardSectionProcessor.cs using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using cardsectionprocessor.core.Models; using cardsectionprocessor.core.Processor; using cardsectionprocessor.core.Strategy; namespace cardsectionprocessor.domain.Processor { public class CardSectionProcessor : ICardSectionProcessor { private readonly IEnumerable<ICardSectionProcessorStrategy> _cardSectionProcessorStrategies; public CardSectionProcessor(IEnumerable<ICardSectionProcessorStrategy> cardSectionProcessorStrategies) { _cardSectionProcessorStrategies = cardSectionProcessorStrategies; } public async Task<CardSectionDataTaskResult<CardSectionMessage>> Process(string category, CardSectionMessage cardSectionData) { var handler = _cardSectionProcessorStrategies.Single(h => h.Handles(category)); var cardSectionDataTaskResult = await handler.Process(cardSectionData); return cardSectionDataTaskResult; } } }<file_sep>/src/wikia/data/cardsectiondata/src/Infrastructure/cardsectiondata.infrastructure/Services/Messaging/Constants/RabbitMqQueueConstants.cs namespace cardsectiondata.infrastructure.Services.Messaging.Constants { public static class RabbitMqQueueConstants { public const string CardTipsData = "card-tips-data"; public const string CardRulingsData = "card-rulings-data"; public const string CardTriviaData = "card-trivia-data"; } }<file_sep>/src/wikia/semanticsearch/src/Infrastructure/semanticsearch.infrastructure/InfrastructureInstaller.cs using Microsoft.Extensions.DependencyInjection; using semanticsearch.domain.Messaging.Exchanges; using semanticsearch.domain.WebPage; using semanticsearch.infrastructure.Messaging.Exchanges; using semanticsearch.infrastructure.WebPage; namespace semanticsearch.infrastructure { public static class InfrastructureInstaller { public static IServiceCollection AddInfrastructureServices(this IServiceCollection services) { services .AddHtmlAgility() .AddMessagingServices(); return services; } public static IServiceCollection AddHtmlAgility(this IServiceCollection services) { services.AddTransient<IHtmlWebPage, HtmlWebPage>(); return services; } public static IServiceCollection AddMessagingServices(this IServiceCollection services) { services.AddTransient<IArticleHeaderExchange, ArticleHeaderExchange>(); services.AddTransient<ISemanticSearchResultsWebPage, SemanticSearchResultsWebPage>(); services.AddTransient<ISemanticCardSearchResultsWebPage, SemanticCardSearchResultsWebPage>(); return services; } } } <file_sep>/src/wikia/processor/cardprocessor/src/Application/cardprocessor.application/MessageConsumers/CardData/CardDataConsumer.cs using MediatR; namespace cardprocessor.application.MessageConsumers.CardData { public class CardDataConsumer : IRequest<CardDataConsumerResult> { public string Message { get; set; } } }<file_sep>/src/wikia/data/carddata/src/Tests/Integration/carddata.infrastructure.integration.tests/WebPagesTests/CardsTests/CardHtmlDocumentTests/ImageUrlTests.cs using carddata.infrastructure.WebPages; using carddata.infrastructure.WebPages.Cards; using carddata.tests.core; using FluentAssertions; using NUnit.Framework; namespace carddata.infrastructure.integration.tests.WebPagesTests.CardsTests.CardHtmlDocumentTests { [TestFixture] [Category(TestType.Integration)] public class ImageUrlTests { private CardHtmlDocument _sut; [SetUp] public void SetUp() { _sut = new CardHtmlDocument(new CardHtmlTable()); } [TestCase("https://yugioh.fandom.com/wiki/4-Starred_Ladybug_of_Doom", "https://static.wikia.nocookie.net/yugioh/images/a/a1/4StarredLadybugofDoom-YSYR-EN-C-1E.png")] public void Given_A_Card_Profile_WebPage_Url_Should_Extract_Card_Image(string url, string expected) { // Arrange var htmlWebPage = new HtmlWebPage(); var htmlDocument = htmlWebPage.Load(url); // Act var result = _sut.ImageUrl(htmlDocument); // Assert result.Should().BeEquivalentTo(expected); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Tests/Unit/cardprocessor.application.unit.tests/MessageConsumersTests/CardDataTests/CardDataConsumerHandlerTests.cs using System; using System.Threading; using System.Threading.Tasks; using cardprocessor.application.Commands; using cardprocessor.application.Commands.AddCard; using cardprocessor.application.Commands.UpdateCard; using cardprocessor.application.MessageConsumers.CardData; using cardprocessor.core.Models; using cardprocessor.core.Models.Db; using cardprocessor.core.Services; using cardprocessor.tests.core; using FluentAssertions; using MediatR; using Microsoft.Extensions.Logging; using NSubstitute; using NSubstitute.ExceptionExtensions; using NUnit.Framework; namespace cardprocessor.application.unit.tests.MessageConsumersTests.CardDataTests { [TestFixture] [Category(TestType.Unit)] public class CardDataConsumerHandlerTests { private ICardService _cardService; private IMediator _mediator; private ICardCommandMapper _cardCommandMapper; private CardDataConsumerHandler _sut; [SetUp] public void SetUp() { _cardService = Substitute.For<ICardService>(); _mediator = Substitute.For<IMediator>(); _cardCommandMapper = Substitute.For<ICardCommandMapper>(); _sut = new CardDataConsumerHandler ( _cardService, _mediator, _cardCommandMapper, Substitute.For<ILogger<CardDataConsumerHandler>>() ); } [Test] public async Task Given_CardData_Should_Execute_CardByName_Method_Once() { // Arrange const int expected = 1; var cardDataConsumer = new CardDataConsumer { Message = "{\"Name\":\"<NAME>\",\"Types\":\"Warrior / Effect\",\"CardType\":\"Monster\",\"Attribute\":\"Earth\",\"Level\":4,\"Rank\":null,\"PendulumScale\":null,\"AtkDef\":\"1400 / 1000\",\"AtkLink\":null,\"CardNumber\":\"91869203\",\"Materials\":null,\"CardEffectTypes\":\"Ignition\",\"Property\":null,\"Description\":\"You can Tribute 2 monsters; inflict 1200 damage to your opponent.\",\"ImageUrl\":\"https://vignette.wikia.nocookie.net/yugioh/images/0/02/AmazonessArcher-LEDU-EN-C-1E.png\",\"LinkArrows\":null,\"MonsterSubCategoriesAndTypes\":[\"Warrior\",\"Effect\"],\"MonsterLinkArrows\":null}" }; _cardCommandMapper.MapToAddCommand(Arg.Any<YugiohCard>()).Returns(new AddCardCommand()); _mediator.Send(Arg.Any<AddCardCommand>()).Returns(new CommandResult {IsSuccessful = true}); // Act var result = await _sut.Handle(cardDataConsumer, CancellationToken.None); // Assert await _cardService.Received(expected).CardByName(Arg.Any<string>()); result.IsSuccessful.Should().BeTrue(); } [Test] public async Task Given_CardData_If_Exception_Occurrs_The_Response_Exception_Property_Should_Not_Be_Null() { // Arrange var cardDataConsumer = new CardDataConsumer { Message = "{\"Name\":\"<NAME>\",\"Types\":\"Warrior / Effect\",\"CardType\":\"Monster\",\"Attribute\":\"Earth\",\"Level\":4,\"Rank\":null,\"PendulumScale\":null,\"AtkDef\":\"1400 / 1000\",\"AtkLink\":null,\"CardNumber\":\"91869203\",\"Materials\":null,\"CardEffectTypes\":\"Ignition\",\"Property\":null,\"Description\":\"You can Tribute 2 monsters; inflict 1200 damage to your opponent.\",\"ImageUrl\":\"https://vignette.wikia.nocookie.net/yugioh/images/0/02/AmazonessArcher-LEDU-EN-C-1E.png\",\"LinkArrows\":null,\"MonsterSubCategoriesAndTypes\":[\"Warrior\",\"Effect\"],\"MonsterLinkArrows\":null}" }; _cardService.CardByName(Arg.Any<string>()).Throws(new Exception()); // Act var result = await _sut.Handle(cardDataConsumer, CancellationToken.None); // Assert result.Exception.Should().NotBeNull(); } [Test] public async Task Given_CardData_Should_Execute_MapToAddCommand_Method_Once() { // Arrange const int expected = 1; var cardDataConsumer = new CardDataConsumer { Message = "{\"Name\":\"<NAME>\",\"Types\":\"Warrior / Effect\",\"CardType\":\"Monster\",\"Attribute\":\"Earth\",\"Level\":4,\"Rank\":null,\"PendulumScale\":null,\"AtkDef\":\"1400 / 1000\",\"AtkLink\":null,\"CardNumber\":\"91869203\",\"Materials\":null,\"CardEffectTypes\":\"Ignition\",\"Property\":null,\"Description\":\"You can Tribute 2 monsters; inflict 1200 damage to your opponent.\",\"ImageUrl\":\"https://vignette.wikia.nocookie.net/yugioh/images/0/02/AmazonessArcher-LEDU-EN-C-1E.png\",\"LinkArrows\":null,\"MonsterSubCategoriesAndTypes\":[\"Warrior\",\"Effect\"],\"MonsterLinkArrows\":null}" }; _cardCommandMapper.MapToAddCommand(Arg.Any<YugiohCard>()).Returns(new AddCardCommand()); _mediator.Send(Arg.Any<AddCardCommand>()).Returns(new CommandResult { IsSuccessful = true }); // Act var result = await _sut.Handle(cardDataConsumer, CancellationToken.None); // Assert await _cardCommandMapper.Received(expected).MapToAddCommand(Arg.Any<YugiohCard>()); result.IsSuccessful.Should().BeTrue(); } [Test] public async Task Given_CardData_Should_Execute_MapToUpdateCommand_Method_Once() { // Arrange const int expected = 1; var cardDataConsumer = new CardDataConsumer { Message = "{\"Name\":\"<NAME>\",\"Types\":\"Warrior / Effect\",\"CardType\":\"Monster\",\"Attribute\":\"Earth\",\"Level\":4,\"Rank\":null,\"PendulumScale\":null,\"AtkDef\":\"1400 / 1000\",\"AtkLink\":null,\"CardNumber\":\"91869203\",\"Materials\":null,\"CardEffectTypes\":\"Ignition\",\"Property\":null,\"Description\":\"You can Tribute 2 monsters; inflict 1200 damage to your opponent.\",\"ImageUrl\":\"https://vignette.wikia.nocookie.net/yugioh/images/0/02/AmazonessArcher-LEDU-EN-C-1E.png\",\"LinkArrows\":null,\"MonsterSubCategoriesAndTypes\":[\"Warrior\",\"Effect\"],\"MonsterLinkArrows\":null}" }; _cardService.CardByName(Arg.Any<string>()).Returns(new Card()); _cardCommandMapper.MapToUpdateCommand(Arg.Any<YugiohCard>(), Arg.Any<Card>()).Returns(new UpdateCardCommand()); _mediator.Send(Arg.Any<UpdateCardCommand>()).Returns(new CommandResult { IsSuccessful = true }); // Act var result = await _sut.Handle(cardDataConsumer, CancellationToken.None); // Assert await _cardCommandMapper.Received(expected).MapToUpdateCommand(Arg.Any<YugiohCard>(), Arg.Any<Card>()); result.IsSuccessful.Should().BeTrue(); } } }<file_sep>/src/wikia/data/cardsectiondata/src/Domain/cardsectiondata.domain/ArticleList/Processor/ArticleProcessor.cs using cardsectiondata.core.Models; using cardsectiondata.core.Processor; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace cardsectiondata.domain.ArticleList.Processor { public class ArticleProcessor : IArticleProcessor { private readonly IEnumerable<IArticleItemProcessor> _articleItemProcessors; public ArticleProcessor(IEnumerable<IArticleItemProcessor> articleItemProcessors) { _articleItemProcessors = articleItemProcessors; } public Task<ArticleTaskResult> Process(string category, Article article) { var handler = _articleItemProcessors.Single(h => h.Handles(category)); return handler.ProcessItem(article); } } } <file_sep>/src/wikia/processor/imageprocessor/src/Presentation/imageprocessor/Services/ImageProcessorHostedService.cs using System; using System.Text; using System.Threading; using System.Threading.Tasks; using imageprocessor.application.Configuration; using imageprocessor.application.MessageConsumers.YugiohImage; using MediatR; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using RabbitMQ.Client; using RabbitMQ.Client.Events; using Serilog; using Serilog.Events; using Serilog.Formatting.Json; namespace imageprocessor.Services { public class ImageProcessorHostedService : BackgroundService { private const string CardImageQueue = "card-image"; private const string ArchetypeImageQueue = "archetype-image"; public IServiceProvider Services { get; } private readonly IOptions<RabbitMqSettings> _rabbitMqOptions; private readonly IOptions<AppSettings> _appSettingsOptions; private readonly IMediator _mediator; private ConnectionFactory _factory; private IConnection _connection; private IModel _channel; private EventingBasicConsumer _imageConsumer; public ImageProcessorHostedService ( IServiceProvider services, IOptions<RabbitMqSettings> rabbitMqOptions, IOptions<AppSettings> appSettingsOptions, IMediator mediator ) { Services = services; _rabbitMqOptions = rabbitMqOptions; _appSettingsOptions = appSettingsOptions; _mediator = mediator; ConfigureSerilog(); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { await StartConsumer(); } private Task StartConsumer() { _factory = new ConnectionFactory() {HostName = _rabbitMqOptions.Value.Host}; _connection = _factory.CreateConnection(); _channel = _connection.CreateModel(); _channel.BasicQos(0, 20, false); _imageConsumer = new EventingBasicConsumer(_channel); _imageConsumer.Received += async (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); var result = await _mediator.Send(new ImageConsumer { Message = message }); if(result.IsSuccessful) { _channel.BasicAck(ea.DeliveryTag, false); } else { _channel.BasicNack(ea.DeliveryTag, false, false); } }; _channel.BasicConsume ( queue: _rabbitMqOptions.Value.Queues[CardImageQueue].Name, autoAck: _rabbitMqOptions.Value.Queues[CardImageQueue].AutoAck, consumer: _imageConsumer ); _channel.BasicConsume ( queue: _rabbitMqOptions.Value.Queues[ArchetypeImageQueue].Name, autoAck: _rabbitMqOptions.Value.Queues[ArchetypeImageQueue].AutoAck, consumer: _imageConsumer ); return Task.CompletedTask; } public override void Dispose() { _connection.Close(); _channel.Close(); base.Dispose(); } private void ConfigureSerilog() { // Create the logger Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Console() .WriteTo.File(new JsonFormatter(renderMessage: true), (_appSettingsOptions.Value.LogFolder + $@"/imageprocessor.{Environment.MachineName}.txt"), fileSizeLimitBytes: 100000000, rollOnFileSizeLimit: true, rollingInterval: RollingInterval.Day) .CreateLogger(); } } } <file_sep>/src/wikia/data/cardsectiondata/src/Infrastructure/cardsectiondata.infrastructure/WebPages/TipRelatedWebPage.cs using cardsectiondata.application.Configuration; using cardsectiondata.core.Models; using cardsectiondata.domain.WebPages; using HtmlAgilityPack; using Microsoft.Extensions.Options; using System; using System.Linq; namespace cardsectiondata.infrastructure.WebPages { public class TipRelatedWebPage : ITipRelatedWebPage { private readonly IOptions<AppSettings> _appsettingsOptions; private readonly ITipRelatedCardList _tipRelatedCardList; private readonly ITipRelatedHtmlDocument _tipRelatedHtmlDocument; private readonly ISemanticSearch _semanticSearch; public TipRelatedWebPage ( IOptions<AppSettings> appsettingsOptions, ITipRelatedCardList tipRelatedCardList, ITipRelatedHtmlDocument tipRelatedHtmlDocument, ISemanticSearch semanticSearch ) { _appsettingsOptions = appsettingsOptions; _tipRelatedCardList = tipRelatedCardList; _tipRelatedHtmlDocument = tipRelatedHtmlDocument; _semanticSearch = semanticSearch; } public void GetTipRelatedCards(CardSection section, Article item) { if (section == null) throw new ArgumentNullException(nameof(section)); if (item == null) throw new ArgumentNullException(nameof(item)); var tipWebPage = new HtmlWeb().Load(item.Url); //Get tip related card list url var cardListUrl = _tipRelatedHtmlDocument.GetUrl(tipWebPage); //get tips related card list table var cardListTable = _tipRelatedHtmlDocument.GetTable(tipWebPage); GetTipRelatedCards(section, cardListUrl, cardListTable); } public void GetTipRelatedCards(CardSection section, string tipRelatedCardListUrl, HtmlNode tipRelatedCardListTable) { if(section == null) throw new ArgumentNullException(nameof(section)); if (!string.IsNullOrEmpty(tipRelatedCardListUrl)) { var cardsFromUrl = _semanticSearch.CardsByUrl(tipRelatedCardListUrl); section.ContentList.AddRange(cardsFromUrl.Select(c => c.Name)); } else if (tipRelatedCardListTable != null) { var cardsFromTable = _tipRelatedCardList.ExtractCardsFromTable(tipRelatedCardListTable); section.ContentList.AddRange(cardsFromTable); } } } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Application/archetypeprocessor.application/MessageConsumers/ArchetypeCardInformation/ArchetypeCardInformation.cs using MediatR; namespace archetypeprocessor.application.MessageConsumers.ArchetypeCardInformation { public class ArchetypeCardInformationConsumer : IRequest<ArchetypeCardInformationConsumerResult> { public string Message { get; set; } } }<file_sep>/src/services/Cards.API/src/Domain/Cards.Domain/Models/Monsters/PendulumMonster.cs namespace Cards.Domain.Models.Monsters { public sealed class PendulumMonster { public int Scale { get; set; } public string Effect { get; set; } } }<file_sep>/src/wikia/processor/banlistprocessor/src/Domain/banlistprocessor.domain/banlistprocessor.domain/Repository/ILimitRepository.cs using System.Collections.Generic; using System.Threading.Tasks; using banlistprocessor.core.Models.Db; namespace banlistprocessor.domain.Repository { public interface ILimitRepository { Task<List<Limit>> GetAll(); } }<file_sep>/src/services/Cards.API/src/Infrastructure/Cards.DatabaseMigration/Exceptions/DatabaseMigrationException.cs using System; using System.Runtime.Serialization; namespace Cards.DatabaseMigration.Exceptions { public sealed class DatabaseMigrationException : Exception { public DatabaseMigrationException() { } public DatabaseMigrationException(SerializationInfo info, StreamingContext context) : base(info, context) { } public DatabaseMigrationException(string? message) : base(message) { } public DatabaseMigrationException(string? message, Exception? innerException) : base(message, innerException) { } } }<file_sep>/src/wikia/semanticsearch/src/Domain/semanticsearch.domain/Search/Consumer/SemanticSearchConsumer.cs using semanticsearch.core.Model; using semanticsearch.core.Search; using semanticsearch.domain.Messaging.Exchanges; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace semanticsearch.domain.Search.Consumer { public class SemanticSearchConsumer : ISemanticSearchConsumer { private readonly ILogger<SemanticSearchConsumer> _logger; private readonly IArticleHeaderExchange _articleHeaderExchange; public SemanticSearchConsumer(ILogger<SemanticSearchConsumer> logger, IArticleHeaderExchange articleHeaderExchange) { _logger = logger; _articleHeaderExchange = articleHeaderExchange; } public async Task<SemanticCardPublishResult> Process(SemanticCard semanticCard) { var response = new SemanticCardPublishResult { Card = semanticCard }; _logger.LogInformation("Publishing semantic card '{CardName}' to queue", semanticCard.Title); await _articleHeaderExchange.Publish(semanticCard); response.IsSuccessful = true; return response; } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Domain/cardsectionprocessor.domain/Repository/ICardRepository.cs using System.Threading.Tasks; using cardsectionprocessor.core.Models.Db; namespace cardsectionprocessor.domain.Repository { public interface ICardRepository { Task<Card> CardByName(string name); } }<file_sep>/src/wikia/data/banlistdata/src/Application/banlistdata.application/MessageConsumers/BanlistInformation/BanlistInformationConsumerHandler.cs using System.Threading; using System.Threading.Tasks; using banlistdata.core.Models; using banlistdata.core.Processor; using FluentValidation; using MediatR; using Newtonsoft.Json; namespace banlistdata.application.MessageConsumers.BanlistInformation { public class BanlistInformationConsumerHandler : IRequestHandler<BanlistInformationConsumer, BanlistInformationConsumerResult> { private readonly IArticleProcessor _articleProcessor; private readonly IValidator<BanlistInformationConsumer> _validator; public BanlistInformationConsumerHandler(IArticleProcessor articleProcessor, IValidator<BanlistInformationConsumer> validator) { _articleProcessor = articleProcessor; _validator = validator; } public async Task<BanlistInformationConsumerResult> Handle(BanlistInformationConsumer request, CancellationToken cancellationToken) { var response = new BanlistInformationConsumerResult(); var validationResults = _validator.Validate(request); if (validationResults.IsValid) { var banlistArticle = JsonConvert.DeserializeObject<Article>(request.Message); var results = await _articleProcessor.Process(banlistArticle); if(!results.IsSuccessfullyProcessed) response.Errors.Add(results.Failed.Exception.Message); response.Message = request.Message; } return response; } } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Domain/archetypeprocessor.domain/Messaging/IImageQueueService.cs using System.Threading.Tasks; using archetypeprocessor.core.Models; namespace archetypeprocessor.domain.Messaging { public interface IImageQueueService { Task Publish(DownloadImage downloadImage); } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Domain/cardsectionprocessor.domain/Service/CardRulingService.cs using System.Collections.Generic; using System.Threading.Tasks; using cardsectionprocessor.core.Models.Db; using cardsectionprocessor.core.Service; using cardsectionprocessor.domain.Repository; namespace cardsectionprocessor.domain.Service { public class CardRulingService : ICardRulingService { private readonly ICardRulingRepository _cardRulingRepository; public CardRulingService(ICardRulingRepository cardRulingRepository) { _cardRulingRepository = cardRulingRepository; } public Task DeleteByCardId(long id) { return _cardRulingRepository.DeleteByCardId(id); } public Task Update(List<RulingSection> tipSections) { return _cardRulingRepository.Update(tipSections); } } }<file_sep>/src/wikia/data/cardsectiondata/src/Domain/cardsectiondata.domain/WebPages/ISemanticSearch.cs using System.Collections.Generic; using cardsectiondata.core.Models; namespace cardsectiondata.domain.WebPages { public interface ISemanticSearch { List<SemanticCard> CardsByUrl(string url); } }<file_sep>/src/services/Cards.API/src/Domain/Cards.Domain/Enums/MonsterCardSubType.cs namespace Cards.Domain.Enums { public enum MonsterCardAttribute { Earth, Water, Fire, Wind, Light, Dark, Divine } public enum MonsterCardType { Warrior, Spellcaster, Fairy, Fiend, Zombie, Machine, Aqua, Pyro, Rock, WingedBeast, Plant, Insect, Thunder, Dragon, Beast, BeastWarrior, Dinosaur, Fish, SeaSerpent, Reptile, Psychic, DivineBeast, CreatorGod, Wyrm, Cyberse } public enum MonsterCardSubType { Normal, Effect, Fusion, Ritual, Synchro, Xyz, Pendulum, Link, Tuner, Gemini, Union, Spirit, Flip, Toon } public enum MonsterType { Warrior, Spellcaster, Fairy, Fiend, Zombie, Machine, Aqua, Pyro, Rock, WingedBeast, Plant, Insect, Thunder, Dragon, Beast, BeastWarrior, Dinosaur, Fish, SeaSerpent, Reptile, Psychic, DivineBeast, CreatorGod, Wyrm, Cyberse } }<file_sep>/src/wikia/article/src/Core/article.core/Models/ArticleBatchTaskResult.cs using article.core.Exceptions; using System.Collections.Generic; namespace article.core.Models { public class ArticleBatchTaskResult { public string Category { get; set; } public int Processed { get; set; } public List<ArticleException> Failed { get; set; } = new List<ArticleException>(); } }<file_sep>/src/wikia/processor/cardprocessor/src/Tests/Unit/cardprocessor.application.unit.tests/HelperTests/CardTests/MonsterCardHelperTests/MapMonsterCardTests.cs using System; using System.Collections.Generic; using System.Linq; using cardprocessor.application.Enums; using cardprocessor.application.Helpers.Cards; using cardprocessor.application.Models.Cards.Input; using cardprocessor.core.Models; using cardprocessor.tests.core; using FluentAssertions; using NUnit.Framework; namespace cardprocessor.application.unit.tests.HelperTests.CardTests.MonsterCardHelperTests { [TestFixture] [Category(TestType.Unit)] public class MapMonsterCardTests { [Test] public void Given_A_Valid_A_Monster_YugiohCard_Should_Map_To_CardInputModel() { // Arrange var yugiohCard = new YugiohCard { Name = "<NAME>", Description = "Amazing card!", CardNumber = "01861629", Attribute = "Dark", Types = "Cyberse / Link / Effect", CardType = "Monster", LinkArrows = " Bottom-Left, Top, Bottom-Right", AtkDef = "2300 / 3", ImageUrl = "https://vignette.wikia.nocookie.net/yugioh/images/5/5d/DecodeTalker-YS18-EN-C-1E.png/revision/latest/scale-to-width-down/300?cb=20180712163921" }; var cardInputModel = new CardInputModel(); var monsterCategory = TestData.AllCategories().Single(c => c.Name.Equals(YgoCardType.Monster.ToString(), StringComparison.OrdinalIgnoreCase)); var monsterSubCategories = TestData.AllSubCategories().Select(sc => sc).Where(sc => sc.CategoryId == monsterCategory.Id); // Act var result = MonsterCardHelper.MapMonsterCard(yugiohCard, cardInputModel, TestData.AllAttributes(), monsterSubCategories, TestData.AllTypes(), TestData.AllLinkArrows()); // Assert result.Should().NotBeNull(); } [Test] public void Given_A_Valid_YugiohCard_With_Types_Should_Map_To_TypeIds_Property() { // Arrange var expected = new List<int> { 8 }; var yugiohCard = new YugiohCard { Name = "<NAME>", Description = "Amazing card!", CardNumber = "543534", Attribute = "Dark", Types = "Effect/Ritual/Dragon", CardType = "Monster", ImageUrl = "https://vignette.wikia.nocookie.net/yugioh/images/b/b4/BlueEyesWhiteDragon-LED3-EN-C-1E.png/revision/latest/scale-to-width-down/300?cb=20180928161125" }; var cardInputModel = new CardInputModel(); var monsterCategory = TestData.AllCategories().Single(c => c.Name.Equals(YgoCardType.Monster.ToString(), StringComparison.OrdinalIgnoreCase)); var monsterSubCategories = TestData.AllSubCategories().Select(sc => sc).Where(sc => sc.CategoryId == monsterCategory.Id); // Act var result = MonsterCardHelper.MapMonsterCard(yugiohCard, cardInputModel, TestData.AllAttributes(), monsterSubCategories, TestData.AllTypes(), TestData.AllLinkArrows()); // Assert result.TypeIds.Should().BeEquivalentTo(expected); } [Test] public void Given_A_Valid_YugiohCard_With_A_Level_Should_Map_To_CardLevel_Property() { // Arrange const int expected = 8; var yugiohCard = new YugiohCard { Name = "<NAME>", Description = "Amazing card!", CardNumber = "543534", Attribute = "Dark", Types = "Effect/Ritual/Dragon", CardType = "Monster", Level = 8, ImageUrl = "https://vignette.wikia.nocookie.net/yugioh/images/b/b4/BlueEyesWhiteDragon-LED3-EN-C-1E.png/revision/latest/scale-to-width-down/300?cb=20180928161125" }; var cardInputModel = new CardInputModel(); var monsterCategory = TestData.AllCategories().Single(c => c.Name.Equals(YgoCardType.Monster.ToString(), StringComparison.OrdinalIgnoreCase)); var monsterSubCategories = TestData.AllSubCategories().Select(sc => sc).Where(sc => sc.CategoryId == monsterCategory.Id); // Act var result = MonsterCardHelper.MapMonsterCard(yugiohCard, cardInputModel, TestData.AllAttributes(), monsterSubCategories, TestData.AllTypes(), TestData.AllLinkArrows()); // Assert result.CardLevel.Should().Be(expected); } [Test] public void Given_A_Valid_YugiohCard_With_A_Rank_Should_Map_To_CardRank_Property() { // Arrange const int expected = 3; var yugiohCard = new YugiohCard { Name = "<NAME>", Description = "Amazing card!", CardNumber = "543534", Attribute = "Dark", Types = "Effect/Ritual/Dragon", CardType = "Monster", Rank = 3, ImageUrl = "https://vignette.wikia.nocookie.net/yugioh/images/b/b4/BlueEyesWhiteDragon-LED3-EN-C-1E.png/revision/latest/scale-to-width-down/300?cb=20180928161125" }; var cardInputModel = new CardInputModel(); var monsterCategory = TestData.AllCategories().Single(c => c.Name.Equals(YgoCardType.Monster.ToString(), StringComparison.OrdinalIgnoreCase)); var monsterSubCategories = TestData.AllSubCategories().Select(sc => sc).Where(sc => sc.CategoryId == monsterCategory.Id); // Act var result = MonsterCardHelper.MapMonsterCard(yugiohCard, cardInputModel, TestData.AllAttributes(), monsterSubCategories, TestData.AllTypes(), TestData.AllLinkArrows()); // Assert result.CardRank.Should().Be(expected); } [Test] public void Given_A_Valid_YugiohCard_With_An_Atk_Should_Map_To_Atk_Property() { // Arrange const int expected = 3000; var yugiohCard = new YugiohCard { Name = "<NAME>", Description = "Amazing card!", CardNumber = "543534", Attribute = "Dark", Types = "Effect/Ritual/Dragon", CardType = "Monster", Level = 8, AtkDef = "3000 / 2500", ImageUrl = "https://vignette.wikia.nocookie.net/yugioh/images/b/b4/BlueEyesWhiteDragon-LED3-EN-C-1E.png/revision/latest/scale-to-width-down/300?cb=20180928161125" }; var cardInputModel = new CardInputModel(); var monsterCategory = TestData.AllCategories().Single(c => c.Name.Equals(YgoCardType.Monster.ToString(), StringComparison.OrdinalIgnoreCase)); var monsterSubCategories = TestData.AllSubCategories().Select(sc => sc).Where(sc => sc.CategoryId == monsterCategory.Id); // Act var result = MonsterCardHelper.MapMonsterCard(yugiohCard, cardInputModel, TestData.AllAttributes(), monsterSubCategories, TestData.AllTypes(), TestData.AllLinkArrows()); // Assert result.Atk.Should().Be(expected); } [Test] public void Given_A_Valid_Link_Monster_YugiohCard_With_An_Atk_Should_Map_To_Atk_Property() { // Arrange const int expected = 2300; var yugiohCard = new YugiohCard { Name = "<NAME>", Description = "Amazing card!", CardNumber = "543534", Attribute = "Dark", Types = "Effect/Ritual/Dragon", CardType = "Monster", Rank = 3, AtkLink = "2300 / 3", ImageUrl = "https://vignette.wikia.nocookie.net/yugioh/images/b/b4/BlueEyesWhiteDragon-LED3-EN-C-1E.png/revision/latest/scale-to-width-down/300?cb=20180928161125" }; var cardInputModel = new CardInputModel(); var monsterCategory = TestData.AllCategories().Single(c => c.Name.Equals(YgoCardType.Monster.ToString(), StringComparison.OrdinalIgnoreCase)); var monsterSubCategories = TestData.AllSubCategories().Select(sc => sc).Where(sc => sc.CategoryId == monsterCategory.Id); // Act var result = MonsterCardHelper.MapMonsterCard(yugiohCard, cardInputModel, TestData.AllAttributes(), monsterSubCategories, TestData.AllTypes(), TestData.AllLinkArrows()); // Assert result.Atk.Should().Be(expected); } [Test] public void Given_A_Valid_YugiohCard_With_An_Def_Should_Map_To_Def_Property() { // Arrange const int expected = 2500; var yugiohCard = new YugiohCard { Name = "<NAME>", Description = "Amazing card!", CardNumber = "543534", Attribute = "Dark", Types = "Effect/Ritual/Dragon", CardType = "Monster", Level = 8, AtkDef = "3000 / 2500", ImageUrl = "https://vignette.wikia.nocookie.net/yugioh/images/b/b4/BlueEyesWhiteDragon-LED3-EN-C-1E.png/revision/latest/scale-to-width-down/300?cb=20180928161125" }; var cardInputModel = new CardInputModel(); var monsterCategory = TestData.AllCategories().Single(c => c.Name.Equals(YgoCardType.Monster.ToString(), StringComparison.OrdinalIgnoreCase)); var monsterSubCategories = TestData.AllSubCategories().Select(sc => sc).Where(sc => sc.CategoryId == monsterCategory.Id); // Act var result = MonsterCardHelper.MapMonsterCard(yugiohCard, cardInputModel, TestData.AllAttributes(), monsterSubCategories, TestData.AllTypes(), TestData.AllLinkArrows()); // Assert result.Def.Should().Be(expected); } } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Domain/cardsectionprocessor.domain/Service/CardTipService.cs using System.Collections.Generic; using System.Threading.Tasks; using cardsectionprocessor.core.Models.Db; using cardsectionprocessor.core.Service; using cardsectionprocessor.domain.Repository; namespace cardsectionprocessor.domain.Service { public class CardTipService : ICardTipService { private readonly ICardTipRepository _cardTipRepository; public CardTipService(ICardTipRepository cardTipRepository) { _cardTipRepository = cardTipRepository; } public Task DeleteByCardId(long id) { return _cardTipRepository.DeleteByCardId(id); } public Task Update(List<TipSection> tips) { return _cardTipRepository.Update(tips); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Core/cardprocessor.core/Services/IAttributeService.cs using System.Collections.Generic; using System.Threading.Tasks; using cardprocessor.core.Models.Db; namespace cardprocessor.core.Services { public interface IAttributeService { Task<List<Attribute>> AllAttributes(); } }<file_sep>/src/wikia/processor/banlistprocessor/src/Domain/banlistprocessor.domain/banlistprocessor.domain/Repository/IBanlistCardRepository.cs using System.Collections.Generic; using System.Threading.Tasks; using banlistprocessor.core.Models.Db; namespace banlistprocessor.domain.Repository { public interface IBanlistCardRepository { Task<ICollection<BanlistCard>> Update(long banlistId, IList<BanlistCard> banlistCards); } }<file_sep>/src/wikia/processor/cardsectionprocessor/src/Core/cardsectionprocessor.core/Strategy/ICardSectionProcessorStrategy.cs using System.Threading.Tasks; using cardsectionprocessor.core.Models; namespace cardsectionprocessor.core.Strategy { public interface ICardSectionProcessorStrategy { Task<CardSectionDataTaskResult<CardSectionMessage>> Process(CardSectionMessage cardSectionData); bool Handles(string category); } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Domain/archetypeprocessor.domain/Repository/IArchetypeCardsRepository.cs using System.Collections.Generic; using System.Threading.Tasks; using archetypeprocessor.core.Models.Db; namespace archetypeprocessor.domain.Repository { public interface IArchetypeCardsRepository { Task<IEnumerable<ArchetypeCard>> Update(long archetypeId, IEnumerable<string> cards); } }<file_sep>/src/wikia/data/cardsectiondata/src/Infrastructure/cardsectiondata.infrastructure/InfrastructureInstaller.cs using cardsectiondata.domain.Services.Messaging; using cardsectiondata.domain.WebPages; using cardsectiondata.infrastructure.Services.Messaging; using cardsectiondata.infrastructure.WebPages; using Microsoft.Extensions.DependencyInjection; namespace cardsectiondata.infrastructure { public static class InfrastructureInstaller { public static IServiceCollection AddInfrastructureServices(this IServiceCollection services) { services.AddMessagingServices(); return services; } public static IServiceCollection AddMessagingServices(this IServiceCollection services) { services.AddTransient<IQueue, CardTipsQueue>(); services.AddTransient<IQueue, CardRulingQueue>(); services.AddTransient<IQueue, CardTriviaQueue>(); services.AddTransient<IHtmlWebPage, HtmlWebPage>(); services.AddTransient<ISemanticSearch, SemanticSearch>(); services.AddTransient<ITipRelatedCardList, TipRelatedCardList>(); services.AddTransient<ITipRelatedHtmlDocument, TipRelatedHtmlDocument>(); services.AddTransient<ITipRelatedWebPage, TipRelatedWebPage>(); return services; } } }<file_sep>/src/wikia/data/archetypedata/src/Infrastructure/archetypedata.infrastructure/Services/Messaging/Constants/RabbitMqQueueConstants.cs namespace archetypedata.infrastructure.Services.Messaging.Constants { public static class RabbitMqQueueConstants { public const string ArchetypeData = "archetype-data"; public const string ArchetypeCardData = "archetype-card-data"; } }<file_sep>/src/wikia/processor/archetypeprocessor/src/Tests/Unit/archetypeprocessor.domain.unit.tests/ServicesTests/ArchetypeServiceTests/ArchetypeByIdTests.cs using System.Threading.Tasks; using archetypeprocessor.domain.Repository; using archetypeprocessor.domain.Services; using archetypeprocessor.tests.core; using NSubstitute; using NUnit.Framework; namespace archetypeprocessor.domain.unit.tests.ServicesTests.ArchetypeServiceTests { [TestFixture] [Category(TestType.Unit)] public class ArchetypeByIdTests { private IArchetypeRepository _archetypeRepository; private ArchetypeService _sut; [SetUp] public void SetUp() { _archetypeRepository = Substitute.For<IArchetypeRepository>(); _sut = new ArchetypeService(_archetypeRepository); } [Test] public async Task Given_An_Archetype_Id_Should_Invoke_ArchetypeById_Method_Once() { // Arrange const long archetypeId = 23424; // Act await _sut.ArchetypeById(archetypeId); // Assert await _archetypeRepository.Received(1).ArchetypeById(Arg.Is(archetypeId)); } } }<file_sep>/src/wikia/processor/cardprocessor/src/Core/cardprocessor.core/Services/ILinkArrowService.cs using System.Collections.Generic; using System.Threading.Tasks; using cardprocessor.core.Models.Db; namespace cardprocessor.core.Services { public interface ILinkArrowService { Task<List<LinkArrow>> AllLinkArrows(); } }<file_sep>/src/wikia/data/carddata/src/Infrastructure/carddata.infrastructure/WebPages/Cards/CardWebPage.cs using System; using carddata.core.Models; using carddata.domain.WebPages; using carddata.domain.WebPages.Cards; using HtmlAgilityPack; namespace carddata.infrastructure.WebPages.Cards { public class CardWebPage : ICardWebPage { private readonly ICardHtmlDocument _cardHtmlDocument; private readonly IHtmlWebPage _htmlWebPage; public CardWebPage(ICardHtmlDocument cardHtmlDocument, IHtmlWebPage htmlWebPage) { _cardHtmlDocument = cardHtmlDocument; _htmlWebPage = htmlWebPage; } public ArticleProcessed GetYugiohCard(Article article) { var card = GetYugiohCard(article.Url); return new ArticleProcessed {Article = article, Card = card}; } public YugiohCard GetYugiohCard(string url) { return GetYugiohCard(new Uri(url)); } public YugiohCard GetYugiohCard(Uri url) { var htmlDocument = _htmlWebPage.Load(url); return GetYugiohCard(htmlDocument); } public YugiohCard GetYugiohCard(HtmlDocument htmlDocument) { var yugiohCard = new YugiohCard { ImageUrl = _cardHtmlDocument.ImageUrl(htmlDocument), Name = _cardHtmlDocument.Name(htmlDocument), Description = _cardHtmlDocument.Description(htmlDocument), CardNumber = _cardHtmlDocument.CardNumber(htmlDocument), CardType = _cardHtmlDocument.CardType(htmlDocument), Property = _cardHtmlDocument.Property(htmlDocument), Attribute = _cardHtmlDocument.Attribute(htmlDocument), Level = _cardHtmlDocument.Level(htmlDocument), Rank = _cardHtmlDocument.Rank(htmlDocument), AtkDef = _cardHtmlDocument.AtkDef(htmlDocument), AtkLink = _cardHtmlDocument.AtkLink(htmlDocument), Types = _cardHtmlDocument.Types(htmlDocument), Materials = _cardHtmlDocument.Materials(htmlDocument), CardEffectTypes = _cardHtmlDocument.CardEffectTypes(htmlDocument), PendulumScale = _cardHtmlDocument.PendulumScale(htmlDocument) }; return yugiohCard; } } } <file_sep>/src/wikia/semanticsearch/src/Domain/semanticsearch.domain/Search/Producer/SemanticSearchProducer.cs using semanticsearch.core.Model; using semanticsearch.core.Search; using semanticsearch.domain.WebPage; using System; using System.Collections.Generic; namespace semanticsearch.domain.Search.Producer { public class SemanticSearchProducer : ISemanticSearchProducer { private readonly ISemanticSearchResultsWebPage _semanticSearchResults; private readonly ISemanticCardSearchResultsWebPage _semanticCardSearchResults; public SemanticSearchProducer(ISemanticSearchResultsWebPage semanticSearchResults, ISemanticCardSearchResultsWebPage semanticCardSearchResults) { _semanticSearchResults = semanticSearchResults; _semanticCardSearchResults = semanticCardSearchResults; } public IEnumerable<SemanticCard> Producer(string url) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentException(nameof(url)); var nextPageUrl = url; do { _semanticSearchResults.Load(nextPageUrl); foreach (var row in _semanticSearchResults.TableRows) { var semanticCard = new SemanticCard { Title = _semanticCardSearchResults.Name(row), CorrelationId = Guid.NewGuid(), Url = _semanticCardSearchResults.Url(row, _semanticSearchResults.CurrentWebPageUri) }; if (!string.IsNullOrWhiteSpace(semanticCard.Title) && !string.IsNullOrWhiteSpace(semanticCard.Url)) { yield return semanticCard; } } if (_semanticSearchResults.HasNextPage) { nextPageUrl = _semanticSearchResults.NextPageLink(); } } while (_semanticSearchResults.HasNextPage); } } }<file_sep>/src/wikia/data/carddata/src/Tests/Unit/carddata.infrastructure.unit.tests/WebPagesTests/CardsTests/CardWebPageTests/GetYugiohCardTests.cs using carddata.core.Models; using carddata.domain.WebPages; using carddata.domain.WebPages.Cards; using carddata.infrastructure.WebPages.Cards; using carddata.tests.core; using FluentAssertions; using HtmlAgilityPack; using NSubstitute; using NUnit.Framework; using System; namespace carddata.infrastructure.unit.tests.WebPagesTests.CardsTests.CardWebPageTests { [TestFixture] [Category(TestType.Integration)] public class GetYugiohCardTests { private CardWebPage _sut; private ICardHtmlDocument _cardHtmlDocument; [SetUp] public void SetUp() { _cardHtmlDocument = Substitute.For<ICardHtmlDocument>(); _sut = new CardWebPage(_cardHtmlDocument, Substitute.For<IHtmlWebPage>()); } [Test] public void Given_An_Card_Article_Should_Extract_Card_Image() { // Arrange const string expected = "https://static.wikia.nocookie.net/yugioh/images/a/a1/4StarredLadybugofDoom-YSYR-EN-C-1E.png"; var article = new Article { CorrelationId = Guid.NewGuid(), Title = "4-Starred Ladybug of Doom", Url = "https://yugioh.fandom.com/wiki/4-Starred_Ladybug_of_Doom" }; _cardHtmlDocument.ImageUrl(Arg.Any<HtmlDocument>()).Returns("https://static.wikia.nocookie.net/yugioh/images/a/a1/4StarredLadybugofDoom-YSYR-EN-C-1E.png"); // Act var result = _sut.GetYugiohCard(article); // Assert result.Card.ImageUrl.Should().BeEquivalentTo(expected); } [Test] public void Given_An_Card_Article_Should_Extract_Card_Name() { // Arrange const string expected = "4-Starred Ladybug of Doom"; var article = new Article { CorrelationId = Guid.NewGuid(), Title = "4-Starred Ladybug of Doom", Url = "https://yugioh.fandom.com/wiki/4-Starred_Ladybug_of_Doom" }; _cardHtmlDocument.Name(Arg.Any<HtmlDocument>()).Returns("4-Starred Ladybug of Doom"); // Act var result = _sut.GetYugiohCard(article); // Assert result.Card.Name.Should().BeEquivalentTo(expected); } [Test] public void Given_An_Card_Article_Should_Extract_Card_Description() { // Arrange const string expected = "FLIP: Destroy all Level 4 monsters your opponent controls."; var article = new Article { CorrelationId = Guid.NewGuid(), Title = "4-Starred Ladybug of Doom", Url = "https://yugioh.fandom.com/wiki/4-Starred_Ladybug_of_Doom" }; _cardHtmlDocument.Description(Arg.Any<HtmlDocument>()).Returns("FLIP: Destroy all Level 4 monsters your opponent controls."); // Act var result = _sut.GetYugiohCard(article); // Assert result.Card.Description.Should().BeEquivalentTo(expected); } [Test] public void Given_An_Card_Article_Should_Extract_Card_Number() { // Arrange const string expected = "83994646"; var article = new Article { CorrelationId = Guid.NewGuid(), Title = "4-Starred Ladybug of Doom", Url = "https://yugioh.fandom.com/wiki/4-Starred_Ladybug_of_Doom" }; _cardHtmlDocument.CardNumber(Arg.Any<HtmlDocument>()).Returns("83994646"); // Act var result = _sut.GetYugiohCard(article); // Assert result.Card.CardNumber.Should().BeEquivalentTo(expected); } [Test] public void Given_An_Card_Article_Should_Extract_Card_Type() { // Arrange const string expected = "Monster"; var article = new Article { CorrelationId = Guid.NewGuid(), Title = "4-Starred Ladybug of Doom", Url = "https://yugioh.fandom.com/wiki/4-Starred_Ladybug_of_Doom" }; _cardHtmlDocument.CardType(Arg.Any<HtmlDocument>()).Returns("Monster"); // Act var result = _sut.GetYugiohCard(article); // Assert result.Card.CardType.Should().BeEquivalentTo(expected); } [Test] public void Given_An_Card_Article_Should_Extract_Card_Attribute() { // Arrange const string expected = "Wind"; var article = new Article { CorrelationId = Guid.NewGuid(), Title = "4-Starred Ladybug of Doom", Url = "https://yugioh.fandom.com/wiki/4-Starred_Ladybug_of_Doom" }; _cardHtmlDocument.Attribute(Arg.Any<HtmlDocument>()).Returns("Wind"); // Act var result = _sut.GetYugiohCard(article); // Assert result.Card.Attribute.Should().BeEquivalentTo(expected); } [Test] public void Given_An_Card_Article_Should_Extract_Card_Rank() { // Arrange const int expected = 4; var article = new Article { CorrelationId = Guid.NewGuid(), Title = "Bagooska the Terribly Tired Tapir", Url = "https://yugioh.fandom.com/wiki/Number_41:_Bagooska_the_Terribly_Tired_Tapir" }; _cardHtmlDocument.Rank(Arg.Any<HtmlDocument>()).Returns(4); // Act var result = _sut.GetYugiohCard(article); // Assert result.Card.Rank.Should().Be(expected); } [Test] public void Given_An_Card_Article_Should_Extract_Card_AtkDef() { // Arrange const string expected = "2100 / 2000"; var article = new Article { CorrelationId = Guid.NewGuid(), Title = "Bagooska the Terribly Tired Tapir", Url = "https://yugioh.fandom.com/wiki/Number_41:_Bagooska_the_Terribly_Tired_Tapir" }; _cardHtmlDocument.AtkDef(Arg.Any<HtmlDocument>()).Returns("2100 / 2000"); // Act var result = _sut.GetYugiohCard(article); // Assert result.Card.AtkDef.Should().Be(expected); } [Test] public void Given_An_Card_Article_Should_Extract_Card_AtkLink() { // Arrange const string expected = "2500 / 4"; var article = new Article { CorrelationId = Guid.NewGuid(), Title = "Firewall Dragon", Url = "https://yugioh.fandom.com/wiki/Firewall_Dragon" }; _cardHtmlDocument.AtkLink(Arg.Any<HtmlDocument>()).Returns("2500 / 4"); // Act var result = _sut.GetYugiohCard(article); // Assert result.Card.AtkLink.Should().Be(expected); } [Test] public void Given_An_Card_Article_Should_Extract_Card_Types() { // Arrange const string expected = "Cyberse / Link / Effect"; var article = new Article { CorrelationId = Guid.NewGuid(), Title = "Firewall Dragon", Url = "https://yugioh.fandom.com/wiki/Firewall_Dragon" }; _cardHtmlDocument.Types(Arg.Any<HtmlDocument>()).Returns("Cyberse / Link / Effect"); // Act var result = _sut.GetYugiohCard(article); // Assert result.Card.Types.Should().Be(expected); } [Test] public void Given_An_Card_Article_Should_Extract_Card_Materials() { // Arrange const string expected = "2+ monsters"; var article = new Article { CorrelationId = Guid.NewGuid(), Title = "Firewall Dragon", Url = "https://yugioh.fandom.com/wiki/Firewall_Dragon" }; _cardHtmlDocument.Materials(Arg.Any<HtmlDocument>()).Returns("2+ monsters"); // Act var result = _sut.GetYugiohCard(article); // Assert result.Card.Materials.Should().Be(expected); } [Test] public void Given_An_Card_Article_Should_Extract_Card_CardEffectTypes() { // Arrange const string expected = "Quick,Trigger"; var article = new Article { CorrelationId = Guid.NewGuid(), Title = "Firewall Dragon", Url = "https://yugioh.fandom.com/wiki/Firewall_Dragon" }; _cardHtmlDocument.CardEffectTypes(Arg.Any<HtmlDocument>()).Returns("Quick,Trigger"); // Act var result = _sut.GetYugiohCard(article); // Assert result.Card.CardEffectTypes.Should().Be(expected); } [Test] public void Given_An_Card_Article_Should_Extract_Card_PendulumScale() { // Arrange const int expected =7; var article = new Article { CorrelationId = Guid.NewGuid(), Title = "Archfiend Eccentrick", Url = "https://yugioh.fandom.com/wiki/Archfiend_Eccentrick" }; _cardHtmlDocument.PendulumScale(Arg.Any<HtmlDocument>()).Returns(7); // Act var result = _sut.GetYugiohCard(article); // Assert result.Card.PendulumScale.Should().Be(expected); } [Test] public void Given_An_Card_Article_Should_Extract_Card_Level() { // Arrange const int expected = 4; var article = new Article { CorrelationId = Guid.NewGuid(), Title = "4-Starred Ladybug of Doom", Url = "https://yugioh.fandom.com/wiki/4-Starred_Ladybug_of_Doom" }; _cardHtmlDocument.Level(Arg.Any<HtmlDocument>()).Returns(4); // Act var result = _sut.GetYugiohCard(article); // Assert result.Card.Level.Should().Be(expected); } [Test] public void Given_An_Card_Article_Should_Extract_Card_Property() { // Arrange const string expected = "Normal"; var article = new Article { CorrelationId = Guid.NewGuid(), Title = "Monster Reborn", Url = "https://yugioh.fandom.com/wiki/Monster_Reborn" }; _cardHtmlDocument.Property(Arg.Any<HtmlDocument>()).Returns("Normal"); // Act var result = _sut.GetYugiohCard(article); // Assert result.Card.Property.Should().BeEquivalentTo(expected); } } }<file_sep>/src/wikia/article/src/Domain/article.domain/WebPages/Banlists/IBanlistHtmlDocument.cs using article.core.Enums; using HtmlAgilityPack; namespace article.domain.WebPages.Banlists { public interface IBanlistHtmlDocument { HtmlNode GetBanlistHtmlNode(BanlistType banlistType, string banlistUrl); HtmlNode GetBanlistHtmlNode(BanlistType banlistType, HtmlDocument document); } }<file_sep>/src/wikia/data/archetypedata/src/Domain/archetypedata.domain/Helpers/StringHelpers.cs using System.Text.RegularExpressions; namespace archetypedata.domain.Helpers { public static class StringHelpers { public static string ArchetypeNameFromListTitle(string text) { var regex = new Regex("\"([^\"]*?)\""); var match = regex.Match(text); return match.Success ? match.Value.Trim('"') : null; } } }
25a6ec7e2d7b6e527fdda8825829c70064b71e63
[ "Markdown", "C#", "YAML", "Dockerfile" ]
448
C#
fablecode/yugioh-insight
16e7fadc2d5f97ded64d9149975d76b46a55b6cd
77753640c6ff36fbf1ad1fee98c95d45a81cf8d0
refs/heads/main
<file_sep><?php function pass($a){ echo $a+= 1; } $x = 10; pass($x); ?>
0906b3e99c3b12e2284bf6873b5db69a8da46f7b
[ "PHP" ]
1
PHP
hyurai/training8
db3ccc601906bd90dde273cc6cb48567871af5db
e05d906aee00f13390fbecfe662d15d637b7102c
refs/heads/master
<repo_name>kylethorpe/csc-360<file_sep>/p3/diskinfo.c #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "disk.h" void diskinfo(char * filename); void storeOSName(char * p); void storeDiskLabel(char * p); unsigned int getNumFATCopies(char * p); unsigned int getSectorsPerFAT(char * p); int getNumFiles(char * p); int countFiles(char * p, int offset, unsigned long size); struct diskinfo { char osname[9]; char labeldisk[12]; int totalsizedisk; int freesizedisk; int numfiles; int numFATcopies; int secperFAT; }info; int main(int argc, char* argv[]) { if(argc == 2) { char *filename = malloc(strlen(argv[1])*sizeof(char)); if(filename == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } strcpy(filename, argv[1]); diskinfo(filename); } else { printf("Incorrect Usage. Try %s <filename>\n",argv[0]); } } /** Gets disk info and prints it out Parameters: char * filename - Name of disk image Returns: void **/ void diskinfo(char * filename) { int fd; fd = open(filename, O_RDONLY); if(fd < 0){ fprintf(stderr, "Error: failed to open file.\n"); return; } //printf("Reading disk image file: %s\n",filename); struct stat sf; fstat(fd, &sf); char *p; p = mmap(NULL, sf.st_size, PROT_READ, MAP_SHARED, fd, 0); storeOSName(p); storeDiskLabel(p); info.totalsizedisk = getTotalSizeDisk(p); info.freesizedisk = getFreeSizeDisk(p); info.numfiles = getNumFiles(p); info.numFATcopies = getNumFATCopies(p); info.secperFAT = getSectorsPerFAT(p); // fclose(fp); printf("OS Name: %s\n",info.osname); printf("Label of the disk: %s\n",info.labeldisk); printf("Total size of the disk: %d\n",info.totalsizedisk); printf("Free size of the disk: %d\n",info.freesizedisk); printf("\n==============\n"); printf("The number of files in the disk (including all files in the root directory and files in all subdirectories): %d\n",info.numfiles); printf("\n==============\n"); printf("Number of FAT copies: %d\n",info.numFATcopies); printf("Sectors per FAT: %d\n\n\n",info.secperFAT); // printf("Get location for 230th FAT: %d\n",getLocation(230)); return; } /** Gets OS name and stores it in the info struct Parameters: char * p - Pointer to disk image Returns: void **/ void storeOSName(char *p) { unsigned char *os = (unsigned char *)p + 3; int i; for(i = 0; i < 8; i++){ info.osname[i] = *os; os++; } info.osname[8] = '\0'; } /** Gets disk label and stores it in the info struct Parameters: char * p - Pointer to disk image Returns: void **/ void storeDiskLabel(char *p) { int root_offset = 512 * 19; int i; for (i = 0; i < 224; i++){ int flag = p[root_offset + 0x0b + i*32]; if(flag == 0x08) { char *offset = p+root_offset+(i*32); for(i = 0; i < 11; i++){ info.labeldisk[i] = *offset; offset++; } info.labeldisk[11] = '\0'; break; } } if(!strcmp(info.labeldisk, "")){ strncpy(info.labeldisk, p+43, 11); info.labeldisk[11] = '\0'; } } /** Gets the number of FAT copies in the disk image Parameters: char * p - Pointer to disk image Returns: unsigned int - Number of FAT copies in the disk image **/ unsigned int getNumFATCopies(char * p){ unsigned int numfats = (unsigned int)(*(p + 16)); return numfats; } /** Gets the amount of Sectors per FAT Parameters: char * p - Pointer to disk image Returns: unsigned int - Number of sectors per FAT **/ unsigned int getSectorsPerFAT(char * p){ char *spf_c = p+22; unsigned char spfbuf[2]; spfbuf[0] = *spf_c; // 22 spf_c++; spfbuf[1] = *spf_c; // 23 unsigned int spf = (spfbuf[0]) | (spfbuf[1]<<8); return spf; } /** Gets the amount of files in the disk image Parameters: char * p - Pointer to disk image Returns: int - Number of files in the disk image **/ int getNumFiles(char * p){ // starting from the root directory, traverse the directory tree. // # of files = # of directory entries in each directory // However, skip a directory if: // the values of it's attribute field is 0x0F // the 4th bit of it's attribute field is 1 // the Volume Label bit of it's attribute field is 1 // the directory_entry is free int offset = 512 * 19; int numFiles = 0; numFiles = numFiles + countFiles(p, offset, 224); return numFiles; } /** Helper function that recursively calls itsself to count all files in the disk image Parameters: char * p - Pointer to disk image int offset - Physical location of directory to search through unsigned long size - Maximum amount of directory entries in the directory (224 for root, 16 otherwise) Returns: int - The amount of files in the current directory + amount of files in recursed directory **/ int countFiles(char * p, int offset, unsigned long size) { int numFiles = 0; int i = 0; for(i = 0; i < size; i ++){ char *file = p+offset+(i*32); unsigned short ffb = *file; int attr = p[offset + 0x0b + i*32]; char filename[9]; strncpy(filename, file, 8); filename[8] = '\0'; char *flc_c = file+26; unsigned char flcbuf[2]; flcbuf[0] = *flc_c; // 26 flc_c++; flcbuf[1] = *flc_c; // 27 unsigned int flc = (flcbuf[0]) | (flcbuf[1]<<8); char *size_c = file+28; unsigned char sizebuf[4]; int j; for(j = 0; j < 4; j++){ sizebuf[j] = *size_c; size_c++; } //unsigned int size = (sizebuf[0]) | (sizebuf[1]<<8) | (sizebuf[2]<<16) | (sizebuf[3]<<24); if(flc == 0 || flc == 1) continue; if((ffb&0xFF) != 0xE5 && (ffb&0xFF) != 0x00){ // not free if(attr != 0x0F){ // not part of long file name if((attr&0x08) == 0x00 && (attr&0x02) == 0x00){ // not a volume label if((attr&0x10) == 0x00){// not a subdirectory numFiles = numFiles + 1; //printf("Found file %s at %d of size %d\n",filename,flc,size); }else{ if(strncmp(filename,". ",2) == 0 || strncmp(filename,".. ",3) == 0) continue; unsigned int logicalID = flc; unsigned int physicalID = 33 + logicalID - 2; unsigned int physicalLocation = physicalID * 512; numFiles = numFiles + countFiles(p, physicalLocation, 16); } } } } } int current_cluster = (offset/512)-33+2; unsigned int nextPossibleSector = getSectorLocation(current_cluster,p); unsigned int next_location = getPhysicalLocation(nextPossibleSector); if(nextPossibleSector < 0xFF8 && size == 16){ return numFiles + countFiles(p,next_location,16); } return numFiles; }<file_sep>/p1/PMan.c #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <readline/readline.h> #include <readline/history.h> #include <signal.h> #include <pthread.h> //Define a linkedlist data structure and its head node. struct node{ int pid; char *path; struct node *next; }; struct node *head = NULL; // Thread functions void *backgroundStatusThread(void *param); // Linkedlist functions int addNode(int pid, char *path); void removeNode(int pid); // Processing functions int getInput(char **args); void process_commands(char **args, int amt_args); void checkProcesses(); // Command functions void bg(char * args[]); void bglist(); void bgkill(int pid); void bgstop(int pid); void bgstart(int pid); void pstat(int pid); #define MAX_ARGS 50 // Maximum number of characters in one argument #define MAX_INPUT 256 // total max input in one command #define MULTITHREADED 1 // To disable multithreaded funcitonality, set this to 0 void checkProcesses(){ int status; int pid; while(1){ pid = waitpid(-1, &status, WNOHANG); if(pid <= 0){ return; } printf("Process was terminated: %d\n",pid); removeNode(pid); } return; } // prompts the user for input, splits the arguments (tokenizes), and returns the amount of args. int getInput(char **args){ char *prompt = "PMan : > "; char *input = readline(prompt); //input[strcspn(input, "\n")] = 0; // remove the trailing \n if(strcmp(input, "") == 0){ return 0; } char *inp; inp = strtok(input, " "); int ind = 0; while(inp != NULL){ args[ind] = inp; inp = strtok(NULL, " "); ind++; } return ind; // Number of arguments } void process_commands(char **args, int amt_args){ char *command = args[0]; if(strncmp(command,"bg",MAX_ARGS)==0){ if(amt_args >= 2){ char* newArgs[MAX_INPUT]; int i; for(i=0; i<amt_args; i++){ newArgs[i] = args[i+1]; } newArgs[amt_args-1] = NULL; // since argv which is passed into execvp() needs to be null terminated bg(newArgs); return; } else{ printf("[Error] bg command requires at least 1 arguments (eg. bg [process name]])\n"); return; } } else if(strncmp(command,"bglist",MAX_ARGS)==0){ bglist(); return; } else if(strncmp(command,"bgkill",MAX_ARGS)==0){ if(amt_args != 2){ printf("[Error] bgkill command requires 1 argument exactly (eg. bgkill [pid])\n"); } int pid = 0; if(sscanf(args[1], "%d", &pid) ==1){ bgkill(pid); } else{ printf("[Error] pid must be in the form of an integer\n"); } return; } else if(strncmp(command,"bgstop",MAX_ARGS)==0){ if(amt_args != 2){ printf("[Error] bgstop command requires 1 argument exactly (eg. bgstop [pid])\n"); } int pid = 0; if(sscanf(args[1], "%d", &pid) ==1){ bgstop(pid); } else{ printf("[Error] pid must be in the form of an integer\n"); } return; } else if(strncmp(command,"bgstart",MAX_ARGS)==0){ if(amt_args != 2){ printf("[Error] bgstart command requires 1 argument exactly (eg. bgstart [pid])\n"); } int pid = 0; if(sscanf(args[1], "%d", &pid) ==1){ bgstart(pid); } else{ printf("[Error] pid must be in the form of an integer\n"); } return; } else if(strncmp(command,"pstat",MAX_ARGS)==0){ if(amt_args != 2){ printf("[Error] pstat command requires 1 argument exactly (eg. pstat [pid])\n"); } int pid = 0; if(sscanf(args[1], "%d", &pid) ==1){ pstat(pid); } else{ printf("[Error] pid must be in the form of an integer\n"); } return; } else{ printf("PMan: > Command not found: %s\n",command); return; } } void *backgroundStatusThread(void *param){ while(1){ checkProcesses(); sleep(1); } } int main(){ //Create and run a thread to constantly (approx. every 1 second) check on background processes. if(MULTITHREADED){ pthread_t backgroundThread_id; pthread_create(&backgroundThread_id, NULL, backgroundStatusThread, NULL); } char *args[MAX_ARGS]; int amt_args; while(1){ amt_args = 0; *args = ""; // Clear the argument pointer. if(!MULTITHREADED){checkProcesses();} amt_args = getInput(args); if(MULTITHREADED){checkProcesses();} if(amt_args == 0){continue;} process_commands(args, amt_args); } } void bg(char * args[]){ int pid = fork(); if (pid == 0){ //child process printf("Starting background process : %s\n",args[0]); if(execvp(args[0],args) < 0){ printf("[Error] Invalid command.\n"); } // If the code reaches here, it failed to replace the current program. printf("[Error] Could not start background process %s\n",args[0]); exit(1); } else if(pid > 0){ // parent process char actualpath [1024]; char *ptr; ptr = realpath(args[0],actualpath); // get the absolute path of the executable and add it to the node with the pid addNode(pid,actualpath); // sleep to prevent the program from prompting before the child process is executed. sleep(1); } else { // error printf("[Error] Fork failed.\n"); } } void bglist(){ // traverse the linkedlist and print out all of the pid's int count = 0; if(head == NULL){ printf("There are currently no background processes.\n"); return; } struct node *temp = head; while(temp != NULL){ printf("%d: %s\n",temp->pid,temp->path); count++; temp = temp->next; } printf("Total background jobs: %d\n",count); } void bgkill(int pid){ int wstatus = 0; waitpid(pid, &wstatus, WNOHANG | WUNTRACED | WCONTINUED); if(WIFSTOPPED(wstatus) != 0){ //returns a nonzero value if the process is stopped kill(pid, SIGCONT); // if the process is stopped, we need to continue it before we kill it. } if(kill(pid,SIGTERM)==0){ //uses the TERM signal to terminate printf("Terminated process %d\n", pid); removeNode(pid); return; } else{ printf("[Error] Cannot find process with pid %d\n",pid); return; } } void bgstop(int pid){ if(kill(pid,SIGSTOP) == 0){ printf("Stopped process %d\n",pid); return; } else{ printf("[Error] Cannot find process with pid %d\n",pid); return; } } void bgstart(int pid){ if(kill(pid,SIGCONT) == 0){ printf("Started process %d\n",pid); return; } else{ printf("[Error] Cannot find process with pid %d\n",pid); return; } } void pstat(int pid){ // Create the directory for proc/[pid]/stat and proc/[pid]/status char direcStat[256]; char direcStatus[256]; sprintf(direcStat, "/proc/%d/stat",pid); sprintf(direcStatus, "/proc/%d/status",pid); if(access(direcStat, R_OK) < 0){ printf("[Error] Stat file for process %d could not be accessed.\n",pid); return; } FILE *stat; FILE *status; char statFile[1024]; char statusFile[1024]; stat = fopen(direcStat, "r"); if(stat){ fgets(statFile, 1024, stat); } char *stat_contents[MAX_ARGS]; char *temp; temp = strtok(statFile, " "); int ind = 0; while(temp != NULL){ stat_contents[ind] = temp; temp = strtok(NULL, " "); ind++; } char status_contents[MAX_INPUT][MAX_ARGS]; status = fopen(direcStatus, "r"); if(status){ int j = 0; while(fgets(status_contents[j], MAX_INPUT, status) != NULL){ j++; } } char *utime_c = stat_contents[13]; char *stime_c = stat_contents[14]; printf("Process %d:\n",pid); printf("comm:\n%s\n",stat_contents[1]); // (2) The filename of the executable, in parentheses. printf("state:\n%s\n",stat_contents[2]); // (3) One character from the string "RSDZTW" where R is running, S is sleeping in an interruptible wait, D is waiting in uninterruptible disk sleep, Z is zombie, T is traced or stopped (on a signal), and W is paging. printf("utime:\n%.6f\n",atof(utime_c)); // (14) Amount of time that this process has been scheduled in user mode, measured in clock ticks printf("stime:\n%.6f\n",atof(stime_c)); // (15) Amount of time that this process has been scheduled in kernel mode, measured in clock ticks printf("rss:\n%s\n",stat_contents[23]); // (24) Resident Set Size: number of pages the process has in real memory. printf("%s",status_contents[46]); // voluntary_context_switches printf("%s",status_contents[47]); // nonvoluntary_context_switches } int addNode(int pid, char *path){ struct node *p = malloc(sizeof(struct node)); p->path = path; p->pid = pid; p->next = NULL; // if the current head is null, we have an empty linked list. Set the head to this node if(head == NULL){ head = p; } else{ // traverse the linked list and attach the new node to the end struct node *temp = head; while(temp->next != NULL){ temp = temp->next; } temp->next = p; } } void removeNode(int pid){ struct node *temp = head; //case: 0 nodes if(head == NULL){ return; } //case: head of list is target else if(temp->pid == pid){ head = head->next; free(temp); return; } else{ // traverse the linked list until the pid is found, then remove the node. struct node *prev = NULL; while(temp != NULL){ if(temp->pid == pid){ //found it prev->next = temp->next; free(temp); return; } else{ prev = temp; temp = temp->next; } } // if finished traversing and cannot find the pid if (temp == NULL){ printf("[Error] Cannot find process: %d\n",pid); return; } } }<file_sep>/p3/disk.h #ifndef DISK_H_ /* Include guard */ #define DISK_H_ int getFreeSizeDisk(char *p); int getTotalSizeDisk(char *p); unsigned int getPhysicalLocation(unsigned int cluster); int getSectorCount(char *p); unsigned int getFileSize(char * file); char * getFilename(char * file); char * getExtension(char * file); unsigned int getFirstLogicalCluster(char * file); unsigned int getSectorLocation(int f,char * p); #endif // DISK_H_<file_sep>/p3/diskput.c #include <stdio.h> #include <time.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <math.h> #include <libgen.h> #include "queue.h" #include "disk.h" void diskput(char * p, struct Queue * q, char * filename); int traverseDirec(char * p, struct Queue * q, FILE * fp, char * filename, time_t last_modified, long offset, int size); void copyFile(char * p, FILE * fp, char * filename, time_t last_modified, unsigned int directory_cluster); unsigned int getNextAvailableFAT(char * p, int j); int getNextAvailableEntry(char * p, int offset, int entries); void setFATValue(char * p, int i, int value); int main(int argc, char* argv[]) { if(argc == 3) { char *imagename = malloc(strlen(argv[1])*sizeof(char)); char *path = malloc(strlen(argv[2])*sizeof(char)); if(imagename == NULL || path == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } strcpy(imagename, argv[1]); strcpy(path, argv[2]); int fd; fd = open(imagename, O_RDWR); if(fd < 0){ printf("Error reading image %s\n",imagename); return 0; } //printf("Reading disk image: %s\n",imagename); struct stat sf; fstat(fd, &sf); char *p; p = mmap(NULL, sf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); char * filename = basename(path); char * direc = dirname(path); char * limiter = "/"; struct Queue * q = createQueue(10); char * root = "."; if(strncmp(direc,root,1) == 0){ q = enqueue(q,direc); diskput(p,q,filename); return 1; } char * token = strtok(direc, limiter); while(token != NULL){ q = enqueue(q,token); token = strtok(0, limiter); } diskput(p,q,filename); return 1; } else { printf("Incorrect Usage. Try %s <image> <pathtofile>\n",argv[0]); return 0; } } /** Function to put file within disk image at a specified directory Parameters: char * p - pointer to disk image in main memory struct Queue * q - pointer to Queue struct char * filename - name of file Returns: void **/ void diskput(char * p, struct Queue * q, char * filename) { FILE * fp = fopen(filename, "r"); if(fp == NULL){ printf("File not found: %s\n",filename); return; } struct stat buf; stat(filename,&buf); time_t last_modified = buf.st_mtime; fseek(fp, 0L, SEEK_END); int file_size; file_size = ftell(fp); rewind(fp); //printf("Size of file: %d\n",file_size); int free_space; free_space = getFreeSizeDisk(p); if(file_size > free_space){ printf("Not enough free space in the disk image.\n"); return; } long offset = 512 * 19; // if(isEmpty(q)){ // //copyFile(p,fp,19); // printf("TODO: Copy to root.\n"); // } int found; found = traverseDirec(p, q, fp, filename, last_modified, offset, 224); fclose(fp); if(found == 0){ printf("The directory was not found.\n"); return; } return; } /** Function which recursively calls itsself to search for the directory location Parameters: char * p - pointer to disk image in main memory struct Queue * q - pointer to Queue struct FILE * fp - pointer to file to put into the disk image char * filename - name of file long offset - physical location of the current directory int size - Maximum number of directory entries in the current directory Returns: int - 1 if found the directory, 0 if not found **/ int traverseDirec(char * p, struct Queue * q, FILE * fp, char * filename, time_t last_modified, long offset, int size) { int found = 0; char * toTraverse; if(!isEmpty(q)){ toTraverse = dequeue(q); }else{ return found; } int toTraverse_len = strlen(toTraverse); int current_cluster = (offset/512)-33+2; //derive the cluster number from the offset. //check if we're in the root and if we're looking for the root. if(strncmp(toTraverse,".",1) == 0 && current_cluster == -12){ copyFile(p,fp,filename,last_modified,-12); return 1; } int i = 0; for(i = 0; i < size; i ++){ char *file = p+offset+(i*32); unsigned short ffb = *file; // First byte of file int attr = p[offset + 0x0b + i*32]; unsigned int flc = getFirstLogicalCluster(file); if(flc == 0 || flc == 1 || flc == current_cluster){ continue; } if((ffb&0xFF) != 0xE5 && (ffb&0xFF) != 0x00){ // not free if(attr != 0x0F){ // not part of long file name if((attr&0x08) == 0x00 ){ // not a volume label char * filename_found = getFilename(file); if((attr&0x10) != 0x00){// subdirectory if(strncmp(filename_found,". ",2) == 0 || strncmp(filename_found,".. ",3) == 0 || strcmp(filename_found,"") == 0) continue; //printf("Found subdirectory %s at %d of size %d\n",filename_found,flc,size); //unsigned int fatIndex = getSectorLocation(flc,p); unsigned int logicalID = flc; unsigned int physicalID = 33 + logicalID - 2; unsigned int physicalLocation = physicalID * 512; if(strncmp(filename_found,toTraverse,toTraverse_len)==0){ //printf("Found directory!"); copyFile(p,fp,filename,last_modified,flc); return 1; } found += traverseDirec(p,q,fp,filename,last_modified,physicalLocation,16); } free(filename_found); } } } } return found; } /** Function to copy the file into the disk image Parameters: char * p - pointer to disk image in main memory FILE * fp - pointer to file to put into the disk image char * filename - name of file unsigned int directory_cluster - cluster of directory to put the image into Returns: void **/ void copyFile(char * p, FILE * fp, char * filename, time_t last_modified, unsigned int directory_cluster){ unsigned int directory_location = getPhysicalLocation(directory_cluster); int file_size; fseek(fp, 0l, SEEK_END); file_size = ftell(fp); rewind(fp); int fat = getNextAvailableFAT(p,0); unsigned int entry_offset = getNextAvailableEntry(p,directory_location,16); // Seperate filename and extension char * token = strtok(filename, "."); char * title = malloc(9); if(token == NULL || title == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } memset(title,'\0',9); strcpy(title,token); token = strtok(0, "."); char * extension = malloc(4); if(extension == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } memset(extension,'\0',4); if(token != NULL){ strcpy(extension,token); } strncpy(p+entry_offset,title,8); strncpy(p+entry_offset+8,extension,3); // Write current date and time to directory entry struct tm * timeinfo; timeinfo = localtime(&last_modified); int year = timeinfo->tm_year-80; // tm_year is the amount of years since 1900 // we need the amount of years since 1980 so subtract 80. int month = timeinfo->tm_mon+1; int day = timeinfo->tm_mday; int hour = timeinfo->tm_hour; int minute = timeinfo->tm_min; // Y Y Y Y Y Y Y M M M M D D D D D Reality (1,0) // M M M D D D D D Y Y Y Y Y Y Y M Storage (0,1) unsigned int date_int[2]; date_int[0] = ((month << 5)&0xE0) | (day&0x1F); date_int[1] = ((year << 1)&0xFE) | ((month >> 3)&0x01); // H H H H H M M M M M M 0 0 0 0 0 Reality (1,0) // M M M 0 0 0 0 0 H H H H H M M M Storage (0,1) unsigned int time_int[2]; time_int[0] = ((minute << 5)&0xE0); time_int[1] = ((hour << 3)&0xF8) | ((minute >> 3)&0x07); p[entry_offset+14] = time_int[0]; p[entry_offset+14+1] = time_int[1]; p[entry_offset+16] = date_int[0]; p[entry_offset+16+1] = date_int[1]; // Write first logical cluster into directory entry int flc[2]; flc[0] = fat&0xFF; flc[1] = (fat >> 8)&0xFF; p[entry_offset+26] = flc[0]; p[entry_offset+26+1] = flc[1]; // Write size into directory entry int f_size[4]; f_size[0] = file_size&0xFF; f_size[1] = (file_size >> 8)&0xFF; f_size[2] = (file_size >> 16)&0xFF; f_size[3] = (file_size >> 24)&0xFF; p[entry_offset+28+0] = f_size[0]; p[entry_offset+28+1] = f_size[1]; p[entry_offset+28+2] = f_size[2]; p[entry_offset+28+3] = f_size[3]; // Write to data sector unsigned int curr_fat = fat; unsigned int next_fat = 0; unsigned int physical_location = 0; unsigned char buffer[512]; int bytes_left = file_size; size_t bytes_read = 0; while(bytes_read < file_size){ int bytes_read_this = fread(buffer, sizeof(unsigned char), 512, fp); bytes_read += bytes_read_this; bytes_left -= bytes_read_this; physical_location = getPhysicalLocation(curr_fat); memcpy(p+physical_location,buffer,bytes_read_this); if(bytes_left > 0){ next_fat = getNextAvailableFAT(p,curr_fat); setFATValue(p,curr_fat,next_fat); } curr_fat = getSectorLocation(curr_fat,p); } setFATValue(p,curr_fat,0xFFF); return; } /** Function to get the next available FAT entry Parameters: char * p - pointer to disk image in main memory int j - Entry to ignore Returns: unsigned int - available FAT entry **/ unsigned int getNextAvailableFAT(char * p, int j){ int i; int sectorsAmount = getTotalSizeDisk(p)/512; for(i = 2; i < sectorsAmount; i++){ if(getSectorLocation(i,p) == 0x00 && i != j){ return i; } } printf("Error: No available FAT entries\n"); return 0; } /** Function to get the next available directory entry for a specified directory Parameters: char * p - pointer to disk image in main memory int offset - Physical location of first logical cluster of directory int entries - Maximum amount of directory entries in a specific directory sector Returns: int - Next available entry physical address **/ int getNextAvailableEntry(char * p, int offset, int entries){ int current_cluster = (offset/512)-33+2; //derive the cluster number from the offset. int i = 0; while(1){ for(i = 0; i < entries; i++){ char *direc = p+offset+(i*32); unsigned int attr = p[offset+0x0b + i*32]; if(!strcmp(direc,"") && attr == 0x00){ return offset+(i*32); } } current_cluster = getSectorLocation(current_cluster,p); offset = getPhysicalLocation(current_cluster); } } /** Function to set the sector value in the FAT table Parameters: char * p - pointer to disk image in main memory int i - the specified FAT entry (i.e. sector number) int value - value to write into the FAT Returns: void **/ void setFATValue(char * p, int i, int value){ int offset = 0x200; int buf[2]; if(i%2 == 0){ // even // low four bits buf[0] = value&0xFF; // 8 bits buf[1] = ((value>>8) & 0x0F); // retain existing high four bits buf[1] |= (p[offset+ 1 + ((3*i)/2)] & 0xF0); p[offset + ((3*i)/2)] = buf[0]; p[offset + 1 + ((3*i)/2)] = buf[1]; } else{ // odd // high four bits buf[0] = (value<<4)&0xF0; // 8 bits buf[1] = ((value>>4) & 0xFF); // retain existing low four bits buf[0] |= (p[offset + ((3*i)/2)] & 0x0F); p[offset + ((3*i)/2)] = buf[0]; p[offset + 1 + ((3*i)/2)] = buf[1]; } }<file_sep>/README.md # csc-360 Assignments for CSC 360 <file_sep>/p2/queue.h #include <stdio.h> #include <stdlib.h> #include <limits.h> struct Queue { int front, rear, size; unsigned capacity; int* array; int status;// 0 is IDLE, 1 is BUSY }; struct Queue* createQueue(unsigned capacity); int isFull(struct Queue* queue); int isEmpty(struct Queue* queue); int enqueue(struct Queue* queue, int item); int dequeue(struct Queue* queue); int front(struct Queue* queue); int rear(struct Queue* queue); //int getStatus(struct Queue* queue); //void setStatus(struct Queue* queue, int status); struct Queue* createQueue(unsigned capacity) { struct Queue* queue = (struct Queue*) malloc(sizeof(struct Queue)); queue->status = 0; queue->capacity = capacity; queue->front = queue->size = 0; queue->rear = capacity-1; queue->array = (int*)malloc(queue->capacity * sizeof(int)); return queue; } int isFull(struct Queue* queue) {return (queue->size == queue->capacity);} int isEmpty(struct Queue* queue) {return (queue->size == 0);} int enqueue(struct Queue* queue, int item) { if(isFull(queue)) return INT_MIN; queue->rear = (queue->rear+1)%queue->capacity; queue->array[queue->rear] = item; queue->size = queue->size+1; return 1; } int dequeue(struct Queue* queue){ if (isEmpty(queue)) return INT_MIN; int item = queue->array[queue->front]; queue->front = (queue->front + 1)%queue->capacity; queue->size = queue->size-1; return item; } int front(struct Queue* queue) { if(isEmpty(queue)) return INT_MIN; return queue->array[queue->front]; } int rear(struct Queue* queue) { if(isEmpty(queue)) return INT_MIN; return queue->array[queue->rear]; } // int getStatus(struct Queue* queue) // { // return queue->status; // } // void setStatus(struct Queue* queue, int status) // { // queue->status = status; // } <file_sep>/p3/disk.c #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <math.h> #include <libgen.h> #include "disk.h" /** Function to get the free size of a specified disk image Parameters: char * p - pointer to disk image in main memory Returns: int - free size of disk **/ int getFreeSizeDisk(char *p) { int freeSectors = 0; int sectorCount = 2848; int i; unsigned int sv; for(i = 2; i <= sectorCount; i ++){ sv = getSectorLocation(i,p); if(sv == 0x00){ freeSectors++; } } return freeSectors*512; } /** Function to get the total size of the disk image Parameters: char * p - pointer to disk image in main memory Returns: int - total size of the disk **/ int getTotalSizeDisk(char *p) { int sc = getSectorCount(p); return sc * 512; } /** Function to get the physical location of a cluster/sector Parameters: unsigned int cluster - cluster/sector number Returns: unsigned int - physical location of cluster/sector number **/ unsigned int getPhysicalLocation(unsigned int cluster){ unsigned int physicalLocation; physicalLocation = (33 + cluster - 2) * 512; return physicalLocation; } /** Function to get the total amount of sectors (from the boot sector in the disk image) Parameters: char * p - pointer to disk image in main memory Returns: int - sector count **/ int getSectorCount(char *p) { unsigned int sectorCount[2]; sectorCount[0] = p[19]; sectorCount[1] = p[20]; return (sectorCount[0] & 0xFF) | ((sectorCount[1] & 0xFF) << 8); } /** Function to get size of a file from a directory entry within a disk image Parameters: char * file - pointer to directory entry Returns: unsigned int - size of file **/ unsigned int getFileSize(char * file) { char *size_p = file+28; unsigned char sizebuf[4]; int j; for(j = 0; j < 4; j++){ sizebuf[j] = *size_p; size_p++; } unsigned int size_int = (sizebuf[0]) | (sizebuf[1]<<8) | (sizebuf[2]<<16) | (sizebuf[3]<<24); return size_int; } /** Function to get name of file from a directory entry within a disk image Parameters: char * file - pointer to directory entry Returns: char * - name of file **/ char * getFilename(char * file) { char * filename; filename = (char*)malloc(sizeof(char)*21); if(filename == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } memset(filename, '\0', 20); strncpy(filename, file, 8); //filename[20] = '\0'; return filename; } /** Function to get extension of file from a directory entry within a disk image Parameters: char * file - pointer to directory entry Returns: char * - extension of file **/ char * getExtension(char * file) { file = file+8; char * extension; extension = (char*)malloc(sizeof(char)*4); if(extension == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } memset(extension, '\0', 4); strncpy(extension, file, 3); return extension; } /** Function to get the first logical cluster from a directory entry within a disk image Parameters: char * file - pointer to directory entry Returns: unsigned int - first logical cluster **/ unsigned int getFirstLogicalCluster(char * file) { char *flc_p = file+26; unsigned char flcbuf[2]; flcbuf[0] = *flc_p; // 26 flc_p++; flcbuf[1] = *flc_p; // 27 unsigned int flc = (flcbuf[0]) | (flcbuf[1]<<8); return flc; } /** Function to get next sector location of a FAT entry within a disk image Parameters: int f - FAT entry char * p - pointer to disk image Returns: unsigned int - logical sector number of next sector **/ unsigned int getSectorLocation(int f,char * p){ //FAT = 33 + FAT - 2; // Convert logical to physical sector number int offset = 0x200; int buffer[2]; unsigned int location = 0; int sl; if(f%2 == 0){ // low 4 bits buffer[0] = p[offset + 1 +((3*f)/2)]& 0x0F; // full 8 bits buffer[1] = p[offset + ((3*f)/2)]& 0xFF; sl = (buffer[0] << 8) | (buffer[1]); } else { // high 4 bits buffer[0] = p[offset + ((3*f)/2)]& 0xF0; // full 8 bits buffer[1] = p[offset + 1 + ((3*f)/2)]& 0xFF; sl = (buffer[0] >> 4) | (buffer[1] << 4); } return sl; }<file_sep>/p2/README.md # csc-360 A2 - <NAME> Assignment 2 for CSC 360 - October 2018 # Included files: README.txt - A usage manual for ACS Makefile - A Makefile to compile ACS.c (Requires make, use %sudo apt install make) ACS.c - Airline Check-in System queue.h - Queue data structure implementation customers.txt - Customer data file # Usage 1. If ACS has not been compiled yet, run the command "%make" in terminal 2. Once ACS has been compiled, run the command "%./ACS customers.txt" in terminal <file_sep>/p3/queue.c #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <string.h> #include "queue.h" /** Function to create a Queue of size capacity Parameters: unsigned int capacity - maximum capacity of Queue Returns: struct Queue* - pointer to created Queue **/ struct Queue* createQueue(unsigned int capacity) { struct Queue* queue = (struct Queue*) malloc(sizeof(struct Queue)); if(queue == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } queue->capacity = capacity; queue->front = queue->size = 0; queue->rear = capacity-1; queue->array = (char*)malloc(queue->capacity * sizeof(char) * MAX_STR); if(queue->array == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } memset(queue->array, '\0', queue->capacity * sizeof(char) * MAX_STR); return queue; } /** Function to expand and copy Queue Parameters: struct Queue *queue - pointer to Queue Returns: struct Queue* - pointer to expanded Queue **/ struct Queue* resizeQueue(struct Queue *queue) { struct Queue* newqueue = (struct Queue*) malloc(sizeof(struct Queue)); if(newqueue == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } newqueue->capacity = ((queue)->capacity)*2; newqueue->front = newqueue->size = 0; newqueue->rear = newqueue->capacity-1; newqueue->array = (char*)malloc(newqueue->capacity * sizeof(char) * MAX_STR); if(newqueue->array == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } memset(newqueue->array, '\0', newqueue->capacity * sizeof(char) * MAX_STR); int i; char * item; while(!isEmpty(queue)){ item = dequeue(queue); enqueue(newqueue, item); } free(queue); return newqueue; } /** Function to check if a Queue is full Parameters: struct Queue *queue - pointer to Queue Returns: int - 1 if full, 0 if not full **/ int isFull(struct Queue* queue) { return (queue->size == queue->capacity); } /** Function to check if a Queue is empty Parameters: struct Queue *queue - pointer to Queue Returns: int - 1 if empty, 0 if not empty **/ int isEmpty(struct Queue* queue) { return (queue->size == 0); } /** Function to enqueue an item onto an existing Queue Parameters: struct Queue *queue - pointer to Queue char * item - pointer to item Returns: struct Queue* - pointer to Queue with new item **/ struct Queue* enqueue(struct Queue* queue, char * item) { if(isFull(queue)) queue = resizeQueue(queue); (queue)->rear = ((queue)->rear+1)%(queue)->capacity; char * p = (queue)->array+((queue->rear)*MAX_STR); memset(p,'\0',MAX_STR); strcpy(p,item); (queue)->size = (queue)->size+1; return queue; } /** Helper function to append every item from one Queue onto another Queue Parameters: struct Queue *queue - pointer to Queue struct Queue *toAdd - pointer to Queue to add onto *queue Returns: struct Queue* - pointer to Queue with new items **/ struct Queue * appendQueue(struct Queue* queue, struct Queue* toAdd) { int i; while(!isEmpty(toAdd)){ char * item = dequeue(toAdd); enqueue(queue,item); } free(toAdd); return queue; } /** Function to dequeue an item from an existing Queue Parameters: struct Queue *queue - pointer to Queue Returns: char * - item that was dequeued **/ char * dequeue(struct Queue* queue){ if (isEmpty(queue)) return ""; char * item; item = malloc(sizeof(char)*MAX_STR); if(item == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } char * p = (queue)->array+((queue->front)*MAX_STR); memset(item, '\0', MAX_STR); strcpy(item,p); (queue)->front = ((queue)->front + 1)%(queue)->capacity; (queue)->size = (queue)->size-1; return item; } /** Function to check the item at the front on an existing Queue Parameters: struct Queue *queue - pointer to Queue Returns: char * - item at the front **/ char * front(struct Queue* queue) { if(isEmpty(queue)) return ""; char * item; item = malloc(sizeof(char)*MAX_STR); if(item == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } char * p = queue->array+((queue->front)*MAX_STR); memset(item,'\0',MAX_STR); strcpy(item,p); return item; } /** Function to check the item at the rear on an existing Queue Parameters: struct Queue *queue - pointer to Queue Returns: char * - item at the rear **/ char * rear(struct Queue* queue) { if(isEmpty(queue)) return ""; char * item; item = malloc(sizeof(char)*MAX_STR); if(item == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } char * p = queue->array+((queue->rear)*MAX_STR); memset(item,'\0',MAX_STR); strcpy(item,p); return item; } <file_sep>/p3/TODO.md # TODO: CSC 360 Assignment 3 ### <NAME> 2018 - [ ] For diskget.c, do not read in 1 byte at a time. - This might be the only way to do this? - [ ] Check return values of all system calls - [ ] Use official error handling prodedures - [ ] Documenation - [X] Document functions - [ ] Comment code within functions - [ ] Create README.txt - [ ] All files: - [ ] Fix . and .. problem (Make a test image with multiple layers) - [ ] Turn loading image code into function in disk.h - [X] **Check FAT for long directories** - diskput.c - [X] Handle case where there is no path (root directory) - [ ] Rewrite getNextAvailableFAT() and getNextAvailableEntry() - [ ] Fix possible infinite loop in getNextAvailableEntry() - [ ] Rewrite setFATValue() in a different way - [ ] Properly setup disk.h and queue.h (Should I be defining the function within the header files?) - [ ] Ignore capitals for diskput and diskget CLI arguments<file_sep>/p2/ACS.c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <sys/types.h> #include <string.h> #include <time.h> #include <unistd.h> #include "queue.h" struct customer { int id; int class; int arrival_time; int service_time; }; void *customer_thread_function(void *param); void *clerk_thread_function(void *param); long getCurrentTimeMicro(); long convertTenthToMicro(long tenth); long convertMicroToTenth(long micro); int getTotalWaitingTimes(int class); pthread_mutex_t B_CUSTOMER_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t B_CLERK_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t B_CUSTOMER_cv = PTHREAD_COND_INITIALIZER; pthread_cond_t B_CLERK_cv = PTHREAD_COND_INITIALIZER; pthread_mutex_t E_CUSTOMER_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t E_CLERK_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t E_CUSTOMER_cv = PTHREAD_COND_INITIALIZER; pthread_cond_t E_CLERK_cv = PTHREAD_COND_INITIALIZER; pthread_mutex_t clerk1_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t clerk2_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t clerk3_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t clerk4_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t clerk1_cv = PTHREAD_COND_INITIALIZER; pthread_cond_t clerk2_cv = PTHREAD_COND_INITIALIZER; pthread_cond_t clerk3_cv = PTHREAD_COND_INITIALIZER; pthread_cond_t clerk4_cv = PTHREAD_COND_INITIALIZER; struct Queue* q_e; struct Queue* q_b; int queue_e_status = -1; int queue_b_status = -1; int amount_customers; int finished; long startUpTime = 0; int *waitingTimesB = NULL; int *waitingTimesE = NULL; int waitingTimesBind = 0; int waitingTimesEind = 0; int main(int argc, char* argv[]) { if (argc == 2){ finished = 0; amount_customers = 0; // Read the customers.txt data file and create the customer strucs FILE *fp = fopen(argv[1], "r"); if(fp == NULL){ printf("Error reading file %s\n",argv[1]); return 0; } char line[100]; // Read the first line of the file, which is the amount of customers fgets(line, sizeof(line), fp); amount_customers = atoi(line); printf("Amount of customers: %d\n",amount_customers); pthread_t threads[amount_customers]; struct customer customers[amount_customers]; int count_B = 0; int count_E = 0; int i = 0; while(fgets(line, sizeof(line), fp)){ char* token = strtok(line, ":"); int id = atoi(token); token = strtok(0, ","); int class = atoi(token); token = strtok(0, ","); int arrival_time = atoi(token); token = strtok(0, ","); int service_time = atoi(token); //printf("id: %d class: %d arrival_time: %d service_time: %d\n",id,class,arrival_time,service_time); customers[i].id = id; customers[i].class = class; customers[i].arrival_time = arrival_time; customers[i].service_time = service_time; i = i + 1; if(class == 0) count_E = count_E + 1; if(class == 1) count_B = count_B + 1; } fclose(fp); waitingTimesB = (int *) malloc(sizeof(int) * count_B); waitingTimesE = (int *) malloc(sizeof(int) * count_E); pthread_t clerk1_thread; pthread_t clerk2_thread; pthread_t clerk3_thread; pthread_t clerk4_thread; int clerk1 = 1, clerk2 = 2, clerk3 = 3, clerk4 = 4; q_e = createQueue(count_E); q_b = createQueue(count_B); if(pthread_create(&clerk1_thread, NULL, clerk_thread_function, &clerk1) != 0) fprintf(stderr, "error: Cannot create clerk thread.\n"); if(pthread_create(&clerk2_thread, NULL, clerk_thread_function, &clerk2) != 0) fprintf(stderr, "error: Cannot create clerk thread.\n"); if(pthread_create(&clerk3_thread, NULL, clerk_thread_function, &clerk3) != 0) fprintf(stderr, "error: Cannot create clerk thread.\n"); if(pthread_create(&clerk4_thread, NULL, clerk_thread_function, &clerk4) != 0) fprintf(stderr, "error: Cannot create clerk thread.\n"); for(i = 0; i < amount_customers; i++){ struct customer *c = &customers[i]; if(pthread_create(&threads[i], NULL, customer_thread_function, c) != 0){ fprintf(stderr, "error: Cannot create thread # %d\n", i); return 0; } } startUpTime = getCurrentTimeMicro(); if(threads){ int b; for(b = 0; b < amount_customers; b = b + 1){ pthread_join(threads[b],NULL); } // Once all customer threads return, we are done. finished = 1; pthread_mutex_destroy(&E_CUSTOMER_mutex); pthread_mutex_destroy(&E_CLERK_mutex); pthread_mutex_destroy(&B_CUSTOMER_mutex); pthread_mutex_destroy(&B_CLERK_mutex); pthread_cond_destroy(&E_CUSTOMER_cv); pthread_cond_destroy(&E_CLERK_cv); pthread_cond_destroy(&B_CUSTOMER_cv); pthread_cond_destroy(&B_CLERK_cv); pthread_mutex_destroy(&clerk1_mutex); pthread_mutex_destroy(&clerk2_mutex); pthread_mutex_destroy(&clerk3_mutex); pthread_mutex_destroy(&clerk4_mutex); pthread_cond_destroy(&clerk1_cv); pthread_cond_destroy(&clerk2_cv); pthread_cond_destroy(&clerk3_cv); pthread_cond_destroy(&clerk4_cv); printf("Finished serving all customers.\n"); double finishTime = (double)getCurrentTimeMicro(); finishTime = finishTime - startUpTime; finishTime = (double)convertMicroToTenth(finishTime); finishTime = finishTime / 10; double totalE = (double)getTotalWaitingTimes(0); double totalB = (double)getTotalWaitingTimes(1); double total = totalE+totalB; double totalAvg = (total/amount_customers) / 10; double eAvg = (totalE / count_E) / 10; double bAvg = (totalB / count_B) / 10; printf("The average waiting time for all customers in the system is: %.2f seconds.\n",totalAvg); printf("The average waiting time for all business-class customers is: %.2f seconds.\n",bAvg); printf("The average waiting time for all economy-class customers is: %.2f seconds.\n",eAvg); printf("Finished in %.2f seconds.\n",finishTime); free(waitingTimesB); free(waitingTimesE); }else{ printf("Error with thread array pointer.\n"); } } else { printf("Invalid command. Usage: %s <filename>.txt\n",argv[0]); } } /** * customer_thread_function, for use by each customer thread. * Parameter is the customer struct which contains the customer data * */ void* customer_thread_function(void *param){ int clerk_id; struct customer *c = param; long arrival_time = c->arrival_time; arrival_time = convertTenthToMicro(arrival_time); long service_time = c->service_time; service_time = convertTenthToMicro(service_time); long seconds = arrival_time/1000000; int id = c->id; int class = c->class; printf("Customer %d arriving in %ld seconds\n",id, seconds); usleep(arrival_time); // Wait for arrival_time microseconds printf("A customer arrives: %d\n",id); long arrivalTime = convertMicroToTenth(getCurrentTimeMicro() - startUpTime); long ts; struct Queue* q; void *mutex_customer, *mutex_clerk, *cond_customer, *cond_clerk; int queue_id; int *status; int *waitingTimes; int *waitingTimesind; // Define which mutexes and condition variables to use based on the class. if(class == 0){ q = q_e; mutex_customer = &E_CUSTOMER_mutex; mutex_clerk = &E_CLERK_mutex; cond_customer = &E_CUSTOMER_cv; cond_clerk = &E_CLERK_cv; queue_id = 1; status = &queue_e_status; waitingTimes = waitingTimesE; waitingTimesind = &waitingTimesEind; } else if(class == 1){ q = q_b; mutex_customer = &B_CUSTOMER_mutex; mutex_clerk = &B_CLERK_mutex; cond_customer = &B_CUSTOMER_cv; cond_clerk = &B_CLERK_cv; queue_id = 0; status = &queue_b_status; waitingTimes = waitingTimesB; waitingTimesind = &waitingTimesBind; }else{ printf("[Error] Class of customer %d is neither 1 or 0: %d\n",id,class); return (void *)0; } if(!isFull(q)){ pthread_mutex_lock(mutex_customer); enqueue(q,id); printf("Customer %d enters queue %d of length %d\n",id,queue_id,q->size); pthread_cond_wait(cond_customer, mutex_customer); //relase mutex lock while(front(q) != id || *status == -1){ pthread_cond_wait(cond_customer, mutex_customer); } ts = getCurrentTimeMicro(); ts = ts - startUpTime; ts = convertMicroToTenth(ts); clerk_id = *status; // Retrieve the clerk id dequeue(q); *status = -1; pthread_mutex_unlock(mutex_customer); // Unlock the mutex for another customer to join the queue / get serviced by a clerk printf("A clerk starts serving a customer: Start time: %ld, Customer ID: %d, Clerk ID %d.\n",ts,id,clerk_id); usleep(service_time); // Get serviced for service_time microseconds // Signal the clerk that was serving us to show that we are done if(clerk_id == 1) pthread_cond_signal(&clerk1_cv); if(clerk_id == 2) pthread_cond_signal(&clerk2_cv); if(clerk_id == 3) pthread_cond_signal(&clerk3_cv); if(clerk_id == 4) pthread_cond_signal(&clerk4_cv); if(clerk_id == -1) printf("[ERROR] Customer %d served by -1\n",id); }else{ printf("[Error] Queue %d full.\n",class); return (void *)0; } long waitingTime = ts - arrivalTime; waitingTimes[*waitingTimesind] = waitingTime; // Store the waiting time for this customer in the proper waiting time array *waitingTimesind = *waitingTimesind + 1; long te = getCurrentTimeMicro(); te = te - startUpTime; te = convertMicroToTenth(te); printf("A clerk finishes serving a customer: End time: %ld, Customer ID: %d, Clerk ID %d.\n",te,id,clerk_id); return (void *) 1; } /** * clerk_thread_function, for use by each clerk thread. * Parameter is the id of the clerk * */ void* clerk_thread_function(void *param){ int id = *((int *)param); printf("Clerk %d idle.\n",id); int printed = 1; while(finished == 0){ if(isEmpty(q_b) && isEmpty(q_e)){ if(!printed){ printed = 1; printf("Clerk %d idle.\n",id); } usleep(100000); continue; } struct Queue* q; void *cond_customer, *cond_clerk, *mutex_customer, *mutex_clerk; int* status; if(!isEmpty(q_b)){ // If the business queue is not empty, we must serve those customers first q = q_b; cond_customer = &B_CUSTOMER_cv; cond_clerk = &B_CLERK_cv; mutex_customer = &B_CUSTOMER_mutex; mutex_clerk = &B_CLERK_mutex; status = &queue_b_status; } else if(isEmpty(q_b) && !isEmpty(q_e)){ q = q_e; cond_customer = &E_CUSTOMER_cv; cond_clerk = &E_CLERK_cv; mutex_customer = &E_CUSTOMER_mutex; mutex_clerk = &E_CLERK_mutex; status = &queue_e_status; } if(*status != -1){ usleep(10000); continue; } if(isEmpty(q)) continue; int ret = pthread_mutex_trylock(mutex_clerk); // Check to see if this queue is being used by another clerk. if(ret != 0) continue; // A clerk is already using that queue, try a different queue *status = id; // Set the queue status to the clerk id for the customer to retrieve int customer = front(q); pthread_cond_broadcast(cond_customer); // Broadcast to all customers in the queue while(front(q) == customer){ // Wait for the customer at the front to store the clerk id and dequeue themselves usleep(1000); } pthread_mutex_unlock(mutex_clerk); // Unlock the clerk mutex for the queue so another clerk may choose the next customer // Wait on the correct condition variable. When the customer is done getting serviced they will signal this variable void *clerk_ID_mutex; void *clerk_ID_cv; if(id == 1){ clerk_ID_mutex = &clerk1_mutex; clerk_ID_cv = &clerk1_cv; } if(id == 2){ clerk_ID_mutex = &clerk2_mutex; clerk_ID_cv = &clerk2_cv; } else if(id == 3){ clerk_ID_mutex = &clerk3_mutex; clerk_ID_cv = &clerk3_cv; } else if(id == 4){ clerk_ID_mutex = &clerk4_mutex; clerk_ID_cv = &clerk4_cv; } pthread_cond_wait(clerk_ID_cv, clerk_ID_mutex); pthread_mutex_unlock(clerk_ID_mutex); printed = 0; // We have finished serving a customer, reset the debug boolean for when we go back to the idle state. } return (void *) 1; } // Get current system time in microseconds long getCurrentTimeMicro(){ struct timespec spec; clock_gettime(CLOCK_MONOTONIC, &spec); long delta_us = (spec.tv_sec * 1000000) + (spec.tv_nsec / 1000); return delta_us; } // Convert microseconds to tenth of a seconds long convertMicroToTenth(long micro){ return (micro/1e+6)*10; } // Convert tenth of a seconds to microseconds long convertTenthToMicro(long tenth){ return (tenth/10)*1e+6; } // Get total waiting times for a particular class int getTotalWaitingTimes(int class){ int *waitingTimes; int max_ind = 0; if(class == 0){ waitingTimes = waitingTimesE; max_ind = waitingTimesEind; } if(class == 1){ waitingTimes = waitingTimesB; max_ind = waitingTimesBind; } int j; int total = 0; for(j = 0; j < max_ind; j++){ total = total + waitingTimes[j]; } return total; }<file_sep>/p3/README.md # CSC 360: Operating Systems (Fall 2018) ## Assignment 3: A Simple File System (SFS) ### <NAME> # Included files: README.txt - A usage manual for SFS Makefile - A Makefile to compile the .c files (Requires make, use %sudo apt install make) diskinfo.c - Disk info tool disklist.c - Disk file explorer tool diskget.c - Disk retrieval tool diskput.c - Disk injection tool queue.c - Queue data structure implementation queue.h - Header file for queue.c disk.c - Disk helper functions implementation disk.h - Header file for disk.c # Usage 1. If the .c files have not been compiled yet, run the command "%make" in terminal 2. Once the files have been compiled, use each of the tools like so: 1. diskinfo.c - `%./diskinfo [imagename]` 1. disklist.c - `%./disklist [imagename]` 2. diskget.c - `%./diskget [imagename] [filename]` 3. diskput.c - `%./diskput [imagename] [path/to/file.extension]`<file_sep>/p3/diskget.c #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <math.h> #include "disk.h" void diskget(char * imagename, char * filename); int traverseDirec(char * p, char * filename, char * extension, long offset, int size); void copyFile(char * p,char * filename, char * extension, int flc, int size); int main(int argc, char* argv[]) { if(argc == 3) { char *imagename = malloc(strlen(argv[1])*sizeof(char)); char *filename = malloc(strlen(argv[2])*sizeof(char)); if(imagename == NULL || filename == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } strcpy(imagename, argv[1]); strcpy(filename, argv[2]); diskget(imagename,filename); } else { printf("Incorrect Usage. Try %s <image> <filename>\n",argv[0]); } } /** Function to get a file from a specified disk image and copy it into the current linux directory Parameters: char * imagename - name of image file char * filename - name of file Returns: void **/ void diskget(char * imagename, char * filename) { int fd; fd = open(imagename, O_RDONLY); if(fd < 0){ printf("Error reading image %s\n",imagename); return; } //printf("Reading disk image: %s\n",imagename); struct stat sf; fstat(fd, &sf); char *p; p = mmap(NULL, sf.st_size, PROT_READ, MAP_SHARED, fd, 0); char * token = strtok(filename, "."); char * title = token; token = strtok(0, "."); if(token == NULL){ printf("Error. No extension specified.\n"); return; } char * extension = token; long offset = 512 * 19; int found; found = traverseDirec(p, filename, extension, offset, 224); if(found == 0){ printf("File not found.\n"); return; } printf("File %s.%s found. Copied to current directory.\n",filename,extension); return; } /** Function which recursively calls itsself to search for the file Parameters: char * p - pointer to disk image in main memory char * filename - name of file char * extension - extension of file long offset - physical location of the current directory int size - Maximum number of directory entries in the current directory Returns: int - 1 if found the directory, 0 if not found **/ int traverseDirec(char * p, char * filename, char * extension, long offset, int size) { int found = 0; int name_len = strlen(filename); int extension_len = strlen(extension); int current_cluster = (offset/512)-33+2; //derive the cluster number from the offset. int i = 0; for(i = 0; i < size; i ++){ char *file = p+offset+(i*32); unsigned short ffb = *file; // First byte of file int attr = p[offset + 0x0b + i*32]; unsigned int flc = getFirstLogicalCluster(file); if(flc == 0 || flc == 1 || flc == current_cluster){ continue; } if((ffb&0xFF) != 0xE5 && (ffb&0xFF) != 0x00){ // not free if(attr != 0x0F){ // not part of long file name if((attr&0x08) == 0x00 ){ // not a volume label char * filename_found = getFilename(file); char * extension_found = getExtension(file); int size_file = (int)getFileSize(file); if((attr&0x10) == 0x00){// not a subdirectory if(strncmp(filename_found,filename,name_len) == 0){ if(strncmp(extension_found,extension,extension_len) == 0){ found += 1; copyFile(p,filename,extension,flc,size_file); return found; } } }else{ if(strncmp(filename_found,". ",2) == 0 || strncmp(filename_found,".. ",3) == 0) continue; unsigned int logicalID = flc; unsigned int physicalID = 33 + logicalID - 2; unsigned int physicalLocation = physicalID * 512; found += traverseDirec(p,filename,extension,physicalLocation,16); } free(filename_found); free(extension_found); } } } } return found; } /** Function to copy the file from the disk image into the current linux directory Parameters: char * p - pointer to disk image in main memory char * filename - name of file char * extension - extension of file int flc - Logical cluster of file in disk image int size - size of file Returns: void **/ void copyFile(char * p,char * filename, char * extension, int flc, int size){ unsigned int next_cluster = flc; unsigned int next_location = getPhysicalLocation(next_cluster); int size_sofar = 0; int length_full_file = strlen(filename) +1+ strlen(extension) + 1; char * full_file = malloc(length_full_file); if(full_file == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } memset(full_file,'\0',length_full_file); strcat(full_file,filename); strcat(full_file,(const char *)"."); strcat(full_file,extension); FILE *fp = fopen(full_file,"w+"); free(full_file); while(next_cluster < 0xFF8 && size_sofar < size){ int i; for(i = 0;i<512;i++){ if(size_sofar < size){ fprintf(fp,"%c",p[next_location+i]); size_sofar+=1; } else{ break; } } next_cluster = getSectorLocation(next_cluster,p); next_location = getPhysicalLocation(next_cluster); } fclose(fp); }<file_sep>/p3/disklist.c #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <math.h> #include "queue.h" #include "disk.h" void disklist(char * filename); char * createCol(char type, char * size, char * filename, char * creationdatetime); char * stringAppend(char * str, char * append); void traverseDirec(char * p, char * directory_name, long offset, int size, int first); char * get_date_time(char * directory_entry_startPos); char * getFileSizeS(char * file); unsigned int getFirstLogicalCluster(char * file); int main(int argc, char* argv[]) { if(argc == 2) { char *filename = malloc(strlen(argv[1])*sizeof(char)); if(filename == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } strcpy(filename, argv[1]); disklist(filename); } else { printf("Incorrect Usage. Try %s <filename>\n",argv[0]); } } /** Function to load disk image into main memory and calls traverseDirec() Parameters: char * filename - Name of disk image Returns: void **/ void disklist(char * filename) { int fd; fd = open(filename, O_RDONLY); if(fd < 0){ printf("Error reading file %s\n",filename); return; } //printf("Reading disk image file: %s\n",filename); struct stat sf; fstat(fd, &sf); char *p; p = mmap(NULL, sf.st_size, PROT_READ, MAP_SHARED, fd, 0); long offset = 512 * 19; char * fn; fn = malloc(sizeof(char)*9); if(fn == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } memset(fn,'\0',9); strcpy(fn,"ROOT DIR"); traverseDirec(p, fn, offset, 224, 1); return; } /** Recursive function to find all files in disk image Parameters: char * p - Pointer to disk image in memory char * directory_name - Name of directory to search through long offset - Physical location of directory int size - Amount of maximum possible directory entries in directory. (224 for root, 16 for data section) int first - Boolean value. 1 if first logical cluster, 0 if not Returns: void **/ void traverseDirec(char * p, char * directory_name, long offset, int size, int first) { struct Queue *q = createQueue(10); if(first == 1){ q = enqueue(q,directory_name); q = enqueue(q,"=================="); } struct Queue *toTraverseLoc = createQueue(10); struct Queue *toTraverseName = createQueue(10); int current_cluster = (offset/512)-33+2; //derive the cluster number from the offset. int i = 0; for(i = 0; i < size; i ++){ char *file = p+offset+(i*32); unsigned short ffb = *file; // First byte of file int attr = p[offset + 0x0b + i*32]; unsigned int flc = getFirstLogicalCluster(file); if(flc == 0 || flc == 1 || flc == current_cluster){ continue; } if((ffb&0xFF) != 0xE5 && (ffb&0xFF) != 0x00){ // not free if(attr != 0x0F){ // not part of long file name if((attr&0x08) == 0x00 ){ // not a volume label char * creationdatetime_s = get_date_time(file); char * size_s = getFileSizeS(file); char * filename = getFilename(file); char * extension = getExtension(file); char * filename_with_extension = malloc(strlen(filename) + 4); if(filename_with_extension == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } memset(filename_with_extension,'\0',strlen(filename)+5); strncpy(filename_with_extension,filename,strlen(filename)); filename_with_extension[strlen(filename)] = '.'; strncat(filename_with_extension,extension,strlen(extension)); if((attr&0x10) == 0x00){// not a subdirectory char * toAppend = createCol('F',size_s,filename_with_extension,creationdatetime_s); q = enqueue(q,toAppend); free(filename); }else{ if(strncmp(filename,". ",2) == 0 || strncmp(filename,".. ",3) == 0) continue; unsigned int logicalID = flc; unsigned int physicalID = 33 + logicalID - 2; unsigned int physicalLocation = physicalID * 512; char * toAppend = createCol('D',size_s,filename,creationdatetime_s); q = enqueue(q,toAppend); char * physicalLocation_s; physicalLocation_s = malloc(((int)log10(physicalLocation)+1)+1); if(physicalLocation_s == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } sprintf(physicalLocation_s,"%u",physicalLocation); toTraverseLoc = enqueue(toTraverseLoc,physicalLocation_s); toTraverseName = enqueue(toTraverseName,filename); free(filename); } } } } } while(!isEmpty(q)){ char * line = dequeue(q); printf("%s\n",line); free(line); } free(q); while(!isEmpty(toTraverseLoc)){ if(isEmpty(toTraverseName)) printf("FATAL ERROR!\n"); char * loc; char * name; loc = dequeue(toTraverseLoc); long physicalLocation; physicalLocation = strtol(loc,NULL,10); free(loc); name = dequeue(toTraverseName); traverseDirec(p,name,physicalLocation,16,1); } free(toTraverseLoc); free(toTraverseName); unsigned int nextPossibleSector = getSectorLocation(current_cluster,p); unsigned int next_location = getPhysicalLocation(nextPossibleSector); if(nextPossibleSector < 0xFF8 && size == 16){ traverseDirec(p, directory_name, next_location, 16, 0); } return; } /** Function to concatenate all file information Parameters: char type - type of file (F or D for file or subdirectory) char * size - size of file char * filename - name of file char * creationdatetime - creation date and time Returns: char * - All parameters appended togethers and formatted properly **/ char * createCol(char type, char * size, char * filename, char * creationdatetime) { char * toAppend; char * new_filename; new_filename = (char*)malloc(sizeof(char)*21); if(new_filename == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } memset(new_filename, ' ', 20); strncpy(new_filename, filename, strlen(filename)); size_t length = 1+1+strlen(size)+1+strlen(new_filename)+1+strlen(creationdatetime)+1; if((toAppend = malloc(length)) != NULL){ memset(toAppend, '\0', length); toAppend[0] = type; strcat(toAppend," "); strcat(toAppend,size); strcat(toAppend," "); strncat(toAppend,new_filename,strlen(new_filename)); strcat(toAppend," "); strcat(toAppend,creationdatetime); }else{ printf("Malloc failed!\n"); return ""; } free(size); //free(filename); free(new_filename); free(creationdatetime); return toAppend; } /** Function to get the creation date and time of a file Parameters: char * directory_entry_startPos - physical location of the directory entry Returns: char * - time and date formatted into a char * pointer *Code taken from tutorial resource on Connex* Written by <NAME>, November 16, 2018 **/ char * get_date_time(char * directory_entry_startPos){ int timeOffset = 14; int dateOffset = 16; int time,date; int hours, minutes, day, month, year; time = *(unsigned short *)(directory_entry_startPos + timeOffset); date = *(unsigned short *)(directory_entry_startPos + dateOffset); // the year is stored as a value since 1980 // the year is stored in the high seven bits year = ((date & 0xFE00) >> 9) + 1980; // the month is stored in the middle four bits month = (date & 0x1E0) >> 5; // the day is stored in the low five bits day = (date & 0x1F); size_t length_date = 4+1+2+1+2+1; size_t length_time = 2+1+2+1; char * final_str = (char *)malloc(length_date+length_time); char * date_s = (char *)malloc(length_date); char * time_s = (char *)malloc(length_time); if(final_str == NULL || date_s == NULL || time_s == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } memset(final_str, '\0', length_date+length_time); sprintf(date_s,"%d-%02d-%02d ", year, month, day); strcat(final_str,date_s); // the hours are stored in the high five bits hours = (time & 0xF800) >> 11; // the minutes are stored in the middle 6 bits minutes = (time & 0x7E0) >> 5; sprintf(time_s,"%02d:%02d",hours,minutes); strcat(final_str,time_s); free(time_s); free(date_s); return final_str; } /** Function to get the file size as a char * Parameters: char * file - pointer to the directory file entry Returns: char * - size of file **/ char * getFileSizeS(char * file) { char *size_p = file+28; unsigned char sizebuf[4]; int j; for(j = 0; j < 4; j++){ sizebuf[j] = *size_p; size_p++; } unsigned int size_int = (sizebuf[0]) | (sizebuf[1]<<8) | (sizebuf[2]<<16) | (sizebuf[3]<<24); char * size_s; size_s = (char*)malloc(sizeof(char)*10+1); if(size_s == NULL){ fprintf(stderr, "Fatal: failed to allocate memory.\n"); abort(); } memset(size_s, ' ', 10); sprintf(size_s,"%u",size_int); size_s[10] = '\0'; return size_s; } <file_sep>/p1/README.md # csc-360 A1 - <NAME> Assignment 1 for CSC 360 - September 2018 #// A note on the multithreaded functionality // This implementation of PMan uses Pthread to check roughly every 1 second for jobs that have been killed that were originally executed by PMan. If you would prefer to disable this functionality, change the MULTITHREADED variable in PMan.c to 0. In other words, the code should read like so on line 45 of PMan.c \#define MULTITHREADED 0 # Included files: README.txt - A usage manual for PMan Makefile - A Makefile to compile PMan.c (Requires make, use %sudo apt install make) PMan.c - Process manager C program # Usage 1. If PMan has not been compiled yet, run the command "%make" in terminal 2. Once PMan has been compiled, run the command "%./PMan" in terminal 1. To start a background process, use >bg [Process name] [arg0] [arg1] [...] 2. To list all background processes currently running that were started by PMan, use >bglist 3. To kill a process, use >bgkill [PID] 4. To stop a process, use >bgstop [PID] 5. To start a previously stopped process, use >bgstart [PID] 6. To get the stats of a process, use >pstat [PID]
f3d10e0bf77e06131806739405c58b3a360eabb1
[ "Markdown", "C" ]
15
C
kylethorpe/csc-360
b7143b6c3080787235b42684b76c390cc10ffda7
dbb191e5e4b3253bcd2447cd49c9cd0d76b4b27e
refs/heads/master
<repo_name>San-Diego-Web-Design/clementia<file_sep>/application/config/tests.php <?php return array( 'types' => array( 'text' => 'Test for the presence of a text string', 'element' => 'Test for the existence of HTML elements', ), 'tags' => array( '' => 'Any', 'div' => 'div', 'h1' => 'h1', 'h2' => 'h2', 'h3' => 'h3', 'h4' => 'h4', 'h5' => 'h5', 'h6' => 'h6', ), 'default_max_tests' => 5, 'allowed_attributes' => array( 'class', ), );<file_sep>/application/views/home/index.php <?php Section::start('content'); ?> <div class="row"> <div class="span6"> <h2>Lorem Ipsum</h2> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus vitae risus vitae lorem iaculis placerat. Aliquam sit amet felis. Etiam congue. Donec risus risus, pretium ac, tincidunt eu, tempor eu, quam. Morbi blandit mollis magna. Suspendisse eu tortor. Donec vitae felis nec ligula blandit rhoncus. Ut a pede ac neque mattis facilisis. Nulla nunc ipsum, sodales vitae, hendrerit non, imperdiet ac, ante. Morbi sit amet mi. Ut magna. Curabitur id est. Nulla velit. Sed consectetuer sodales justo. Aliquam dictum gravida libero. Sed eu turpis. Nunc id lorem. Aenean consequat tempor mi. Phasellus in neque. Nunc fermentum convallis ligula. </div> <div class="span6"> <?php echo render('user.signup'); ?> </div> </div> <?php Section::stop(); ?><file_sep>/application/views/user/account.php <?php Section::start('content'); ?> <div class="row"> <div class="span4 offset4 login-form"> <h1>Account</h1> <?php echo Form::open('user/index', 'PUT'); ?> <?php echo Form::token(); ?> <div class="control-group"> <?php echo Form::label('email', 'Email Address', array('class' => 'control-label')); ?> <div class="controls"> <?php echo Form::text('email', Input::old('email', Auth::user()->email), array('class' => 'span4')); ?> </div> </div> <div class="control-group"> <?php echo Form::label('password', '<PASSWORD>', array('class' => 'control-label')); ?> <div class="controls"> <?php echo Form::password('<PASSWORD>', array('class' => 'span4')); ?> </div> </div> <div class="control-group"> <?php echo Form::label('password_confirmation', 'Confirm Password', array('class' => 'control-label')); ?> <div class="controls"> <?php echo Form::password('<PASSWORD>', array('class' => 'span4')); ?> </div> <span class="help-block">Leave the password fields blank to keep your current password.</span> </div> <button type="submit" class="btn btn-primary">Log In</button> <?php echo Form::close(); ?> </div> </div> <?php Section::stop(); ?><file_sep>/application/views/test/form.php <div class="row"> <div class="span6"> <?php echo Form::label('description', 'Description'); ?> <?php echo Form::text('description', Input::old('description', $test->description), array('class' => 'span6')); ?> </div> <div class="span6"> <?php echo Form::label('url', 'URL'); ?> <?php echo Form::text('url', Input::old('url', $test->url), array('class' => 'span6')); ?> </div> </div> <div class="row"> <div class="span6"> <?php echo Form::label('type', 'Test Type'); ?> <?php $types = Config::get('tests.types'); if (count($types) > 1) { $types = array('' => 'Select a test type...') + $types; echo Form::select('type', $types, Input::old('type', $test->type), array('class' => 'span6')); } else { $key = key($types); $type = array_shift($types); echo Form::hidden('type', $key); printf('<em>%s</em>', $type); } ?> <?php ?> </div> </div> <div id="test-type-text" class="test-type" style="display:none;"> <div class="row"> <div class="span6"> <?php echo Form::label('options[text]', 'Text to Search For'); ?> <?php echo Form::text('options[text]', $test->option('text'), array('class' => 'span6')); ?> <label class="checkbox"> <?php echo Form::checkbox('options[case_sensitive]', TRUE, $test->option('case_sensitive')); ?> Case Sensitive </label> </div> </div> </div> <div id="test-type-element" class="test-type" style="display:none;"> <div class="row"> <div class="span6"> <h4>Find the Elements</h4> <span class="help-block"> Choose how to select the element(s). You must select an HTML tag, enter an ID, or both. Once the elements are selected they will be filtered according to the other criteria you select. </span> </div> <div class="span6"> <h4>Filter the Elements</h4> <span class="help-block"> Choose how to filter the element(s). After the elements are found using the HTML tag or ID you entered, they will be checked for the CSS class or inner text that you specify below. You can leave either or both of these blank, if you'd like. </span> </div> </div> <div class="row"> <div class="span3"> <?php echo Form::label('options[tag]', 'HTML Tag'); ?> <?php echo Form::select('options[tag]', Config::get('tests.tags'), $test->option('tag')); ?> </div> <div class="span3"> <?php echo Form::label('options[id]', 'ID'); ?> <?php echo Form::text('options[id]', $test->option('id')); ?> </div> <div class="span3"> <?php echo Form::label('options[attributes][class]', 'CSS Class'); ?> <?php echo Form::text('options[attributes][class]', $test->option('attributes')['class']); ?> </div> <div class="span3"> <?php echo Form::label('options[inner_text]', 'Element Inner Text'); ?> <?php echo Form::text('options[inner_text]', $test->option('inner_text')); ?> </div> </div> </div> <?php Section::start('additional_footer_content'); ?> <script>require(['clementia/test-types']);</script> <?php Section::stop(); ?><file_sep>/application/models/user.php <?php class User extends Aware { public static $timestamps = true; public static $rules = array( 'email' => 'required|email|unique:users', 'password' => '<PASSWORD>', ); public function onSave() { // if there's a new password, hash it if($this->changed('password')) { $this->password = Hash::make($this->password); } return true; } public function tests() { return $this->has_many('Test'); } public function has_reached_his_test_limit() { $max_tests = Config::get('tests.default_max_tests'); $existing_tests = count($this->tests); if ($existing_tests >= $max_tests) { return TRUE; } else { return FALSE; } } }<file_sep>/readme.md # Codename "Clementia" A web app based on the Laravel MVC framework, to enable easy creation and running of web acceptance tests. Still in very early stages.<file_sep>/application/views/user/form.php <div class="control-group"> <?php echo Form::label('email', 'Email Address', array('class' => 'control-label')); ?> <div class="controls"> <?php echo Form::text('email', Input::old('email'), array('class' => 'span4')); ?> </div> </div> <div class="control-group"> <?php echo Form::label('password', '<PASSWORD>', array('class' => 'control-label')); ?> <div class="controls"> <?php echo Form::password('<PASSWORD>', array('class' => 'span4')); ?> </div> </div><file_sep>/application/views/user/signup.php <h2>Sign Up</h2> <?php if ($signup_errors = Session::get('signup_errors')): ?> <div class="alert alert-error"> <button type="button" class="close" data-dismiss="alert">×</button> <ul class="unstyled"> <?php foreach ($signup_errors as $error): ?> <li><?php echo $error; ?></li> <?php endforeach; ?> </ul> </div> <?php endif; ?> <?php echo Form::open('user/create', 'POST', array('class' => 'form-horizontal')); ?> <?php echo Form::token(); ?> <div class="control-group"> <?php echo Form::label('email', 'Email Address', array('class' => 'control-label')); ?> <div class="controls"> <?php echo Form::text('email', Input::old('email'), array('class' => 'span4')); ?> </div> </div> <div class="control-group"> <?php echo Form::label('password', '<PASSWORD>', array('class' => 'control-label')); ?> <div class="controls"> <?php echo Form::password('<PASSWORD>', array('class' => 'span4')); ?> </div> </div> <div class="control-group"> <div class="controls"> <button type="submit" class="btn btn-primary">Sign Up</button> </div> </div> <?php echo Form::close(); ?><file_sep>/application/views/test/list.php <?php Section::start('content'); ?> <?php if ($user_can_create_more_tests): ?> <p> <a class="btn btn-primary" href="<?php echo URL::to('test/create'); ?>"> <i class="icon-plus icon-white"></i> New Test </a> </p> <?php else: ?> <div class="alert alert-warning"> You have reached the maximum amount of tests you are allowed. If you'd like to add more, you will need to delete some of the ones below. </div> <?php endif; ?> <table class="table table-striped"> <tbody> <?php foreach ($tests as $test): ?> <tr> <td> <?php echo HTML::link_to_route('test_detail', $test->description, array($test->id)); ?> </td> <td> <a href="<?php echo $test->url; ?>" target="_blank"><?php echo $test->url; ?></a> <i class="icon-share"></i> </td> <td> <a href="<?php echo URL::to_route('test_detail', array($test->id)); ?>"><i class="icon-zoom-in"></i></a> <a data-method="DELETE" href="<?php echo URL::to_route('test_delete', array($test->id)); ?>"><i class="icon-remove"></i></a> </td> </tr> <?php endforeach; ?> </tbody> </table> <?php Section::stop(); ?><file_sep>/application/views/session/login.php <?php Section::start('content'); ?> <div class="row"> <div class="span4 offset4 login-form"> <?php echo Form::open('session/create', 'PUT'); ?> <?php echo Form::token(); ?> <div class="control-group"> <?php echo Form::label('email', 'Email Address', array('class' => 'control-label')); ?> <div class="controls"> <?php echo Form::text('email', Input::old('email'), array('class' => 'span4')); ?> </div> </div> <div class="control-group"> <?php echo Form::label('password', 'Password', array('class' => 'control-label')); ?> <div class="controls"> <?php echo Form::password('<PASSWORD>', array('class' => 'span4')); ?> </div> </div> <button type="submit" class="btn btn-primary">Log In</button> <?php echo Form::close(); ?> </div> </div> <?php Section::stop(); ?><file_sep>/application/libraries/clementiarequest.php <?php class ClementiaRequest { public function __construct() { } public function get($url) { return Requests::get($url); } }<file_sep>/application/controllers/user.php <?php class User_Controller extends Base_Controller { public $restful = TRUE; public function get_index() { $user = Auth::user(); if (!$user) { return Response::error('404'); } else { $this->layout->nest('content', 'user.account', array( 'user' => $user, )); } } // update the user public function put_index() { $user = Auth::user(); $rules = array( 'email' => 'required|email|unique:users,email,' . $user->id, // force email to be unique, but do not fail on this user's email ); $update_password = FALSE; if (Input::get('password') != '') { $rules['password'] = '<PASSWORD>'; $update_password = TRUE; } $validation = Validator::make(Input::all(), $rules); if ($validation->fails()) { return Redirect::to_route('user_account')->with('error', $validation->errors->all()); } else { $user->email = Input::get('email'); if ($update_password) $user->password = Input::get('<PASSWORD>'); if ($user->save()) { return Redirect::to_route('user_account')->with('success', 'Account updated'); } else { return Redirect::to_route('user_account')->with('error', $user->errors->all()); } } } public function post_create() { $user = new User; $user->email = Input::get('email'); $user->password = Input::get('password'); if ($user->save()) { Auth::login($user->id); return Redirect::to_route('user_account'); } else { return Redirect::to_route('home') ->with('signup_errors', $user->errors->all()) ->with_input('only', array('email')); } } }<file_sep>/application/tests/clementarequest.test.php <?php class TestClementiaRequest extends PHPUnit_Framework_TestCase { public function testThatLibraryExists() { $this->assertTrue(class_exists('ClementiaRequest')); } }<file_sep>/application/controllers/test.php <?php class Test_Controller extends Base_Controller { public $restful = TRUE; public function get_list() { $tests = Auth::user()->tests; $user_can_create_more_tests = !Auth::user()->has_reached_his_test_limit(); $this->layout->nest('content', 'test.list', array( 'tests' => $tests, 'user_can_create_more_tests' => $user_can_create_more_tests, )); } public function get_detail($id) { $test = Test::find($id); if (!$test) { return Response::error('404'); } else { $logs = $test->logs()->order_by('created_at', 'desc')->get(); $description = $test->generate_description_for_output(); $this->layout->nest('content', 'test.detail', array( 'test' => $test, 'logs' => $logs, 'description' => $description, )); } } public function post_run($id) { $test = Test::find($id); if (!$test) { return Response::error('404'); } else { $test->run(); return Redirect::to_route('test_detail', array($id))->with('success', 'Sweet! The test was run.'); } } public function get_create() { $test = new Test; $this->layout->nest('content', 'test.create', array( 'test' => $test, )); } public function post_create() { $test = new Test; $test->description = Input::get('description'); $test->url = Input::get('url'); $test->type = Input::get('type'); $test->user_id = Auth::user()->id; $test->options = Input::get('options'); try { if ($test->save()) { return Redirect::to_route('test_detail', array($test->id)); } else { return Redirect::to('test/create') ->with('error', $test->errors->all()) ->with_input(); } } catch (Max_Tests_Exceeded_Exception $e) { return Redirect::to_route('test_list')->with('error', 'Sorry! You have reached the maximum amount of tests you are allowed.'); } } public function get_edit($id) { $test = Test::find($id); if (!$test) { return Response::error('404'); } else { $this->layout->nest('content', 'test.edit', array( 'test' => $test, )); } } public function put_edit($id) { $test = Test::find($id); if (!$test) { return Response::error('404'); } else { $test->description = Input::get('description'); $test->url = Input::get('url'); $test->type = Input::get('type'); $test->options = Input::get('options'); if ($test->save()) { return Redirect::to_route('test_detail', array($test->id)); } else { return Redirect::to('test/edit/'.$id) ->with('error', $test->errors->all()) ->with_input(); } } } public function delete_destroy($id) { $test = Test::find($id); if (!$test) { return Response::error('404'); } else { if ($test->destroy_if_user_can(Auth::user()->id)) { return Redirect::to_route('test_list')->with('success', 'Test deleted.'); } else { return Response::error('403'); } } } }<file_sep>/application/models/test.php <?php class Test extends Aware { public static $timestamps = true; public static $rules = array( 'url' => 'required|url', 'type' => 'required', ); public function set_options($options) { $options = array_map_deep('trim', $options); // traverse options and remove any blank ones foreach ($options as $key => $val) { if (empty($val)) { unset($options[$key]); } else { if (is_array($val)) { foreach ($val as $val_key => $val_val) { if (empty($val_val)) { unset($options[$key]); } } } } } $this->set_attribute('options', json_encode($options)); } public function get_options() { return json_decode($this->get_attribute('options'), TRUE); } public function option($key) { if (!$this->options) $this->options = array(); return array_key_exists($key, $this->options) ? $this->options[$key] : NULL; } /** * Get some nice descriptive text about the test. */ public function generate_description_for_output() { $description = 'Unknown Test'; $details = array(); switch ($this->type) { case 'element': $description = sprintf('Test for presence of tag <code>%s</code>', $this->option('tag')); if ($this->option('id') != '') { $details[] = sprintf('With ID <code>%s</code>', $this->option('id')); } if ($this->option('attributes') != '') { foreach ($this->option('attributes') as $attr => $val) { $details[] = sprintf('With attribute <code>%s</code> equal to <code>%s</code>', $attr, $val); } } if ($this->option('inner_text') != '') { $details[] = sprintf('With text <code>%s</code>', $this->option('inner_text')); } break; case 'text': $description = sprintf('Test for presence of text <code>%s</code>', $this->option('text')); if ($this->option('case_sensitive') != '' && (bool)$this->option('case_sensitive') == TRUE) { $details[] = 'Case sensitive'; } else { $details[] = 'Case insensitive'; } break; } return array('description' => $description, 'details' => $details); } /** * Run the test and create a TestLog. */ public function run() { $tester = IoC::resolve('tester'); $passed = $tester->test($this->type, $this->url, $this->options); $message = $passed ? 'Test Passed' : 'Test Failed'; #todo: more descriptive messages Test\Log::create(array( 'test_id' => $this->id, 'message' => $message, 'passed' => $passed, )); } /** * Destroy the record if the user is able to. */ public function destroy_if_user_can($user_id) { if ($user_id === $this->user_id) { $this->delete(); return TRUE; } else { return FALSE; } } public function onSave() { return $this->check_for_max_tests(); } private function check_for_max_tests() { if (!$this->exists && Auth::user()->has_reached_his_test_limit()) { throw new Max_Tests_Exceeded_Exception; } else { return TRUE; } } /** * Relationships. */ public function user() { return $this->belongs_to('User'); } public function logs() { return $this->has_many('Test\Log'); } } class Max_Tests_Exceeded_Exception extends Exception {}
2ad6803b705a67147d915b2c317f30b2a81a1398
[ "Markdown", "PHP" ]
15
PHP
San-Diego-Web-Design/clementia
265c6582ce9edb5aea9cf8f8f4321631b88c0d80
6f2f88c16ce833766bf79291bbc42e215a9913b8
refs/heads/master
<file_sep>package com.smtm.mvvm.data.remote.request /** */ data class GithubUserRequest( val keyword: String, val pageNumber: Int, val requiredSize: Int, val isFirstRequest: Boolean )<file_sep>package com.smtm.mvvm.data.db.transformer.error import androidx.room.EmptyResultSetException import com.smtm.mvvm.data.repository.error.RepositoryException /** **/ object RoomExceptionConverter { fun toRepositoryException(throwable: Throwable): RepositoryException { val errorMessage: String = throwable.message ?: "" return when(throwable) { is EmptyResultSetException -> { RepositoryException.NotFoundException(errorMessage + "no result error") } else -> { RepositoryException.DatabaseUnknownException(errorMessage + "database unknown error") } } } }<file_sep>package com.smtm.mvvm.data.repository.user.model /** */ data class UserResponse( val githubDocuments: List<UserDocument> )<file_sep>package com.smtm.mvvm.data.remote.response import com.google.gson.annotations.SerializedName /** */ data class GithubDocument( @SerializedName("id") val id: Long, @SerializedName("login") val login: String?, @SerializedName("avatar_url") val avatar_url: String? )<file_sep>package com.smtm.mvvm.data.db.transformer.error import io.reactivex.* class SingleExceptionTransformer<T> : SingleTransformer<T, T> { override fun apply(upstream: Single<T>): SingleSource<T> { return upstream.onErrorResumeNext { throwable -> Single.error(RoomExceptionConverter.toRepositoryException(throwable)) } } } <file_sep>package com.smtm.mvvm.presentation.webview import android.app.Application import android.content.res.AssetManager import android.os.Environment import android.text.format.DateFormat import android.util.Log import androidx.core.content.ContextCompat import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.smtm.mvvm.R import com.smtm.mvvm.data.remote.request.ConnectRequest import com.smtm.mvvm.data.remote.request.Template import com.smtm.mvvm.data.remote.request.TokenRequest import com.smtm.mvvm.data.remote.request.UserData import com.smtm.mvvm.data.remote.response.ConnectResponse import com.smtm.mvvm.data.remote.response.TokenResponse import com.smtm.mvvm.data.repository.error.RepositoryException import com.smtm.mvvm.data.repository.user.UserRepository import com.smtm.mvvm.data.repository.user.model.UserDocument import com.smtm.mvvm.presentation.base.BaseViewModel import com.smtm.mvvm.presentation.search.SearchState import io.reactivex.android.schedulers.AndroidSchedulers import java.io.* /** */ class WebViewModel( application: Application, private val userRepository: UserRepository ) : BaseViewModel(application) { private val _userDocuments = MutableLiveData<TokenResponse>() val userDocuments: LiveData<TokenResponse> = _userDocuments private val _apiState = MutableLiveData<SearchState>(SearchState.NONE) val searchState: LiveData<SearchState> = _apiState private var query: String = "" init { // requestImagesToRepository() } private var mUserDocument: UserDocument? = null // private fun observeChangingFavoriteImage() { // userRepository.observeChangingFavoriteImage() // .observeOn(AndroidSchedulers.mainThread()) // .subscribe({ changedUserDocument -> // _userDocuments.replace(changedUserDocument) { // it.id == changedUserDocument.id } // }, { throwable -> // Log.d("gg", throwable.message) // }) // .disposeByOnCleared() // } fun doSearch() { Log.e("gg", "doSearch()") requestToken() } fun jsSave(js: String) { Log.e("gg", "jsSave()") query = js } private fun requestToken() { _apiState.value = SearchState.NONE val request = TokenRequest("pca-<PASSWORD>", "abef<PASSWORD>c1") userRepository.getToken(request) .observeOn(AndroidSchedulers.mainThread()) .doOnSuccess { _apiState.value = SearchState.SUCCESS } .doOnError { _apiState.value = SearchState.FAIL } .subscribe({ response -> requestConnection(response) }, { throwable -> handlingImageSearchError(throwable) }) .disposeByOnCleared() } private fun requestConnection(tokenInfo: TokenResponse) { _apiState.value = SearchState.NONE // var data: ArrayList<String> = ArrayList() // data.add("http://www.gravatar.com/avatar/68f912364117ca0d704a9d20f343b2b2?d=identicon&s=40") var userData: UserData = UserData("student", "teacher", query) var template: Template = Template("mobile-student") val request = ConnectRequest("abe16", "class-room-090", userData, template, "delta-canvas-demo") userRepository.getConnect("Bearer " + tokenInfo.token, request) .observeOn(AndroidSchedulers.mainThread()) .doOnSuccess { _apiState.value = SearchState.SUCCESS } .doOnError { _apiState.value = SearchState.FAIL } .subscribe({ response -> updateDocuments(response) }, { throwable -> handlingImageSearchError(throwable) }) .disposeByOnCleared() } private fun updateDocuments( receivedImageDocuments: ConnectResponse ) { _userDocuments.apply { saveHtmlFile(receivedImageDocuments.html) }.also { // if (it.isEmpty()) { // updateShowMessage(R.string.success_image_search_no_result) // } } } private fun saveHtmlFile(html: String) { val path: String = Environment.getExternalStorageDirectory().getPath() var fileName: String = DateFormat.format("dd_MM_yyyy_hh_mm_ss", System.currentTimeMillis()).toString() fileName = "fileName15.html" val file = File(path, fileName) // val html = "<html><head><title>Title</title></head><body>This is random text.</body></html>" try { val out = FileOutputStream(file) val data = html.toByteArray() out.write(data) out.close() Log.e("gg", "File Save : " + file.getPath()) } catch (e: IOException) { e.printStackTrace() } } private fun handlingImageSearchError(throwable: Throwable) { when (throwable) { is RepositoryException.NetworkNotConnectingException -> { updateShowMessage(R.string.network_not_connecting_error) } else -> { updateShowMessage(R.string.unknown_error) } } } } <file_sep>package com.smtm.mvvm.data.db.transformer.error import io.reactivex.Completable import io.reactivex.CompletableSource import io.reactivex.CompletableTransformer class CompletableExceptionTransformer : CompletableTransformer { override fun apply(upstream: Completable): CompletableSource { return upstream.onErrorResumeNext { throwable -> Completable.error(RoomExceptionConverter.toRepositoryException(throwable)) } } }<file_sep>package com.smtm.mvvm.presentation.search /** */ enum class SearchState { SUCCESS, FAIL, NONE }<file_sep>package com.smtm.mvvm.data.db.entity.mapper import com.smtm.mvvm.data.db.entity.BookmarkEntity import com.smtm.mvvm.data.repository.user.model.UserDocument /** * **/ object UserDocumentEntityMapper { fun toEntity(imageDocument: UserDocument): BookmarkEntity { return imageDocument.run { BookmarkEntity( id, book_id, login, avatar_url, isFavorite ) } } fun fromEntityList(imageDocumentEntityList: List<BookmarkEntity>): List<UserDocument> { return imageDocumentEntityList.map { fromEntity(it) } } fun fromEntity(imageDocumentEntity: BookmarkEntity): UserDocument { return imageDocumentEntity.run { UserDocument( id, book_id, login, avatar_url, isFavorite ) } } }<file_sep>package com.smtm.mvvm.presentation.common.pageload import ccom.leopold.mvvm.common.pageload.PageLoadApproveLog import com.smtm.mvvm.extension.safeLet /** */ class PageLoadHelper<T>(private val config: PageLoadConfiguration) { private val previousApproveLog = PageLoadApproveLog<T>() var onPageLoadApproveCallback: ((key: T, pageNumber: Int, dataSize: Int, isFirstPage: Boolean) -> Unit)? = null fun requestFirstLoad(key: T) { approveFirstImageSearch(key) } fun requestPreloadIfPossible( currentPosition: Int, dataTotalSize: Int, countOfItemInLine: Int = 1 ) { previousApproveLog.run { safeLet(key, pageNumber) { previousKey, previousPageNumber -> if (isPreloadPossible(currentPosition, dataTotalSize, countOfItemInLine)) { approveImageSearch(previousKey, previousPageNumber+1, dataTotalSize) } } } } fun requestRetryAsPreviousValue() { previousApproveLog.run { safeLet(key, pageNumber, dataTotalSize) { currentKey, previousPageNumber, previousDataTotalSize -> approveImageSearch(currentKey, previousPageNumber, previousDataTotalSize) } } } fun getCurrentKey(): T? = previousApproveLog.key private fun approveFirstImageSearch(key: T) { initApproveRequestLog() approveImageSearch(key, config.startPageNumber, 0) } private fun initApproveRequestLog() { previousApproveLog.apply { key = null dataTotalSize = null pageNumber = config.startPageNumber-1 } } private fun isPreloadPossible( displayPosition: Int, dataTotalSize: Int, countOfItemInLine: Int ): Boolean { return isNotMaxPage() && isAllowPreloadRange(displayPosition, dataTotalSize, countOfItemInLine) } private fun isNotMaxPage(): Boolean { return previousApproveLog.pageNumber?.let { previousPageNumber -> previousPageNumber < config.maxPageNumber } ?: false } private fun isAllowPreloadRange( displayPosition: Int, dataTotalSize: Int, countOfItemInLine: Int ): Boolean { return previousApproveLog.dataTotalSize?.let { previousDataTotalSize -> val preloadAllowLimit = dataTotalSize - (countOfItemInLine * config.preloadAllowLineMultiple) (dataTotalSize > previousDataTotalSize) && (displayPosition > preloadAllowLimit) } ?: false } private fun approveImageSearch(key: T, pageNumber: Int, dataTotalSize: Int) { recordApproveRequest(key, dataTotalSize, pageNumber) onPageLoadApproveCallback?.invoke(key, pageNumber, config.requiredDataSize, pageNumber == config.startPageNumber) } private fun recordApproveRequest(key: T, dataTotalSize: Int, pageNumber: Int) { previousApproveLog.apply { this.key = key this.dataTotalSize = dataTotalSize this.pageNumber = pageNumber } } }<file_sep>package com.smtm.mvvm.presentation.common.pageload import org.junit.Assert.assertEquals import org.junit.Test /** **/ class PageLoadHelperTest { private lateinit var pageLoadHelper: PageLoadHelper<String> @Test fun `최초 페이지 로드 요청시 승인을 하는지 테스트`() { // given val config = PageLoadConfiguration(1, 3, 10, 1) pageLoadHelper = PageLoadHelper(config) // when var actualKey: String? = null var actualPageNumber: Int? = null var actualDataSize: Int? = null var actualIsFirstPage: Boolean? = null pageLoadHelper.onPageLoadApproveCallback = { key, pageNumber, dataSize, isFirstPage -> actualKey = key actualPageNumber = pageNumber actualDataSize = dataSize actualIsFirstPage = isFirstPage } pageLoadHelper.requestFirstLoad("테스트") // then assertEquals("테스트", actualKey) assertEquals(1, actualPageNumber) assertEquals(10, actualDataSize) assertEquals(true, actualIsFirstPage) } @Test fun `추가 페이지 로드 요청 시 승인을 하는지 테스트`() { // given val config = PageLoadConfiguration(1, 3, 10, 2) pageLoadHelper = PageLoadHelper(config) // when var actualKey: String? = null var actualPageNumber: Int? = null var actualDataSize: Int? = null var actualIsFirstPage: Boolean? = null pageLoadHelper.onPageLoadApproveCallback = { key, pageNumber, dataSize, isFirstPage -> actualKey = key actualPageNumber = pageNumber actualDataSize = dataSize actualIsFirstPage = isFirstPage } pageLoadHelper.requestFirstLoad("테스트") pageLoadHelper.requestPreloadIfPossible(9, 10, 1) assertEquals("테스트", actualKey) assertEquals(2, actualPageNumber) assertEquals(10, actualDataSize) assertEquals(false, actualIsFirstPage) } @Test fun `추가 페이지 로드 요청 시, 현재 포지션이 프리로드 허용 범위안에 속하지 못한다면 승인을 안하는지 테스트`() { // given val config = PageLoadConfiguration(1, 3, 10, 2) pageLoadHelper = PageLoadHelper(config) // when var actualKey: String? = null var actualPageNumber: Int? = null var actualDataSize: Int? = null var actualIsFirstPage: Boolean? = null pageLoadHelper.onPageLoadApproveCallback = { key, pageNumber, dataSize, isFirstPage -> actualKey = key actualPageNumber = pageNumber actualDataSize = dataSize actualIsFirstPage = isFirstPage } pageLoadHelper.requestFirstLoad("테스트") pageLoadHelper.requestPreloadIfPossible(1, 10, 1) assertEquals("테스트", actualKey) assertEquals(1, actualPageNumber) assertEquals(10, actualDataSize) assertEquals(true, actualIsFirstPage) } @Test fun `추가 페이지 로드 요청 시, 마지막 페이지라면 승인을 안하는지 테스트`() { // given val config = PageLoadConfiguration(1, 1, 10, 2) pageLoadHelper = PageLoadHelper(config) // when var approveCount = 0 pageLoadHelper.onPageLoadApproveCallback = { _, _, _, _ -> approveCount++ } pageLoadHelper.requestFirstLoad("테스트") pageLoadHelper.requestPreloadIfPossible(9, 10, 1) assertEquals(1, approveCount) } @Test fun `직전 값과 동일한 값 재시도 요청 시 동일한 값으로 승인하는지 테스트`() { // given val config = PageLoadConfiguration(1, 3, 10, 2) pageLoadHelper = PageLoadHelper(config) // when var baseKey: String? = null var basePageNumber: Int? = null var baseDataSize: Int? = null var baseIsFirstPage: Boolean? = null pageLoadHelper.onPageLoadApproveCallback = { key, pageNumber, dataSize, isFirstPage -> baseKey = key basePageNumber = pageNumber baseDataSize = dataSize baseIsFirstPage = isFirstPage } pageLoadHelper.requestFirstLoad("테스트") pageLoadHelper.requestPreloadIfPossible(10, 10, 1) pageLoadHelper.requestPreloadIfPossible(20, 10, 1) var targetKey: String? = null var targetPageNumber: Int? = null var targetDataSize: Int? = null var targetIsFirstPage: Boolean? = null pageLoadHelper.onPageLoadApproveCallback = { key, pageNumber, dataSize, isFirstPage -> targetKey = key targetPageNumber = pageNumber targetDataSize = dataSize targetIsFirstPage = isFirstPage } pageLoadHelper.requestRetryAsPreviousValue() // then assertEquals(baseKey, targetKey) assertEquals(basePageNumber, targetPageNumber) assertEquals(baseDataSize, targetDataSize) assertEquals(baseIsFirstPage, targetIsFirstPage) } }<file_sep>((w, d) => { const button = document.createElement("button"); button.style["z-index"] = "1000"; button.innerText = "button"; button.style.position = "fixed"; button.style.top = "80px"; button.onclick = () => alert("clicked"); d.body.appendChild(button) })(window, document) <file_sep>package com.smtm.mvvm.data.remote.request import com.google.gson.annotations.SerializedName /** */ data class UserData( @SerializedName("type") var type: String, @SerializedName("listenType") var listenType: String, @SerializedName("script") var script: String )<file_sep>package com.smtm.mvvm.data.repository.user import com.smtm.mvvm.data.remote.request.ConnectRequest import com.smtm.mvvm.data.remote.request.GithubUserRequest import com.smtm.mvvm.data.remote.request.TokenRequest import com.smtm.mvvm.data.remote.response.ConnectResponse import com.smtm.mvvm.data.remote.response.TokenResponse import com.smtm.mvvm.data.repository.user.model.UserResponse import io.reactivex.Single /** **/ interface UserRemoteDataSource { fun getUsers(userSearchRequest: GithubUserRequest): Single<UserResponse> fun getToken(tokenRequest: TokenRequest): Single<TokenResponse> fun getConnect(authorization: String, connectRequest: ConnectRequest): Single<ConnectResponse> }<file_sep>package com.smtm.mvvm.presentation.bookmark import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.smtm.mvvm.data.repository.user.model.UserDocument import com.smtm.mvvm.databinding.ItemBookmarkBinding import com.smtm.mvvm.extension.cancelImageLoad import io.reactivex.Observable import io.reactivex.subjects.PublishSubject /** */ class BookmarkAdapter : ListAdapter<UserDocument, BookmarkAdapter.BookmarkViewHolder>(DiffCallback()) { private val _itemClicks = PublishSubject.create<UserDocument>() val itemClicks: Observable<UserDocument> = _itemClicks override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BookmarkViewHolder { val inflater = LayoutInflater.from(parent.context) return BookmarkViewHolder(ItemBookmarkBinding.inflate(inflater, parent, false)).apply { binding.bookmarkItemDel.setOnClickListener { _itemClicks.onNext(getItem(adapterPosition)) } } } override fun onBindViewHolder(holder: BookmarkViewHolder, position: Int) { holder.setItem(getItem(position)) } override fun onViewRecycled(holder: BookmarkViewHolder) { holder.clear() super.onViewRecycled(holder) } class BookmarkViewHolder( val binding: ItemBookmarkBinding ) : RecyclerView.ViewHolder(binding.root) { fun setItem(imageDocument: UserDocument) { // binding.userDocument = imageDocument // binding.executePendingBindings() } fun clear() { binding.bookmarkItemAvatarUrl.cancelImageLoad() } } class DiffCallback : DiffUtil.ItemCallback<UserDocument>() { override fun areItemsTheSame(oldItem: UserDocument, newItem: UserDocument): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: UserDocument, newItem: UserDocument): Boolean { return oldItem == newItem } } } <file_sep>package com.smtm.mvvm.extension import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import java.util.concurrent.TimeUnit /** */ fun <T> Observable<T>.throttleFirstWithHalfSecond(): Observable<T> { return throttleFirst(500, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread()) } <file_sep>package com.ch.yoon.imagesearch.presentation.common.databinding import android.view.View import androidx.databinding.BindingAdapter /** */ @BindingAdapter("isSelected") fun isSelected(view: View, isSelected: Boolean) { view.isSelected = isSelected }<file_sep>package com.smtm.mvvm.presentation.bookmark import android.os.Bundle import android.util.Log import com.smtm.mvvm.R import com.smtm.mvvm.presentation.base.RxBaseFragment import com.smtm.mvvm.databinding.FragmentBookmarkBinding import com.smtm.mvvm.extension.throttleFirstWithHalfSecond import org.koin.androidx.viewmodel.ext.android.viewModel /** */ class BookmarkFragment : RxBaseFragment<FragmentBookmarkBinding>() { private val bookmarkViewModel: BookmarkViewModel by viewModel() override fun getLayoutId(): Int { return R.layout.fragment_bookmark } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) // binding.bookmarkListViewModel = bookmarkViewModel // binding.setLifecycleOwner(this) // TODO: Use the ViewModel Log.e("gg","BookmarkFragment onActivityCreated()") initFavoriteListViewModel() initFavoriteRecyclerView() binding.bookmarkListViewModel = bookmarkViewModel } private fun initFavoriteListViewModel() { with(bookmarkViewModel) { bookmarkViewModel.loadFavoriteImageList() } } private fun initFavoriteRecyclerView() { binding.bookmarkRecyclerView.apply { adapter = BookmarkAdapter().apply { itemClicks.throttleFirstWithHalfSecond() .subscribe { userDocument -> bookmarkViewModel.onClickDel(userDocument) } .disposeByOnDestroy() } } } } <file_sep>package com.smtm.mvvm.data.remote.response import com.google.gson.annotations.SerializedName /** */ data class GithubUserResponse( @SerializedName("total_count") val totalCount: Int, @SerializedName("incomplete_results") val incompleteResults: Boolean, @SerializedName("items") val githubDocuments: ArrayList<GithubDocument> )<file_sep>package com.smtm.mvvm.data.remote.response import com.google.gson.annotations.SerializedName import com.smtm.mvvm.data.remote.request.UserData /** */ data class ConnectResponse( @SerializedName("html") val html: String, @SerializedName("roomId") val roomId: String, @SerializedName("busy") val publicRoomId: Boolean )<file_sep>package com.smtm.mvvm.presentation.common.databinding import android.widget.ImageView import android.widget.ProgressBar import androidx.databinding.BindingAdapter import com.smtm.mvvm.extension.loadImageWithCenterCrop import com.smtm.mvvm.extension.loadImageWithCenterInside /** */ @BindingAdapter(value = ["loadImageWithCenterInside", "roundedCorners", "loadingProgressBar"], requireAll = false) fun loadImageWithCenterInside( imageView: ImageView, imageUrl: String?, roundedCorners: Int = 0, progressBar: ProgressBar? = null ) { imageView.loadImageWithCenterInside(imageUrl, roundedCorners, progressBar) } @BindingAdapter(value = ["loadImageWithCenterCrop", "roundedCorners", "loadingProgressBar"], requireAll = false) fun loadImageWithCenterCrop( imageView: ImageView, imageUrl: String?, roundedCorners: Int = 0, progressBar: ProgressBar? = null ) { imageView.loadImageWithCenterCrop(imageUrl, roundedCorners, progressBar) } @BindingAdapter("srcAlpha") fun setSrcAlpha(imageView: ImageView, alpha: Int) { imageView.drawable?.alpha = alpha }<file_sep>package com.smtm.mvvm.extension import android.content.Context import android.view.View import android.view.inputmethod.InputMethodManager /** */ internal fun View.visible() { visibility = View.VISIBLE } internal fun View.gone() { visibility = View.GONE } internal fun View.showKeyboard() { val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputMethodManager.showSoftInput(this, 0) } internal fun View.hideKeyboard() { val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputMethodManager.hideSoftInputFromWindow(windowToken, 0) }<file_sep>package com.smtm.mvvm.presentation.base import android.app.Application import androidx.annotation.StringRes import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import com.smtm.mvvm.presentation.common.livedata.SingleLiveEvent import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable /** */ open class BaseViewModel(application: Application) : AndroidViewModel(application){ private val compositeDisposable = CompositeDisposable() private val _showMessageEvent = SingleLiveEvent<String>() val showMessageEvent: LiveData<String> = _showMessageEvent override fun onCleared() { compositeDisposable.clear() super.onCleared() } protected fun Disposable.disposeByOnCleared() { compositeDisposable.add(this) } protected fun updateShowMessage(@StringRes stringResId: Int) { _showMessageEvent.value = getApplication<Application>().getString(stringResId) } }<file_sep>package com.smtm.mvvm.presentation.base import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.annotation.LayoutRes import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.fragment.app.Fragment /** */ abstract class BaseFragment<B : ViewDataBinding> : Fragment() { protected lateinit var binding: B private set override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return DataBindingUtil.inflate<B>(inflater, getLayoutId(), container, false).apply { binding = this // lifecycleOwner = this@BaseFragment }.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { binding.lifecycleOwner = viewLifecycleOwner } protected fun showToast(message: String?) { message?.let { Toast.makeText(activity?.applicationContext, it, Toast.LENGTH_SHORT).show() } } @LayoutRes protected abstract fun getLayoutId(): Int }<file_sep>package com.smtm.mvvm.presentation.main import android.Manifest import android.content.pm.PackageManager import android.os.Bundle import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.smtm.mvvm.R import com.smtm.mvvm.presentation.base.RxBaseActivity import com.smtm.mvvm.databinding.ActivityMainBinding import com.smtm.mvvm.util.Strings import org.koin.androidx.viewmodel.ext.android.viewModel /** */ class MainActivity : RxBaseActivity<ActivityMainBinding>() { private val mainViewModel: MainViewModel by viewModel() private val PERMISSION = 111; override fun getLayoutId(): Int { return R.layout.activity_main } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) checkPermission() binding.viewPager.apply { adapter = MainAdapter(this@MainActivity, supportFragmentManager).apply { } } binding.tabs.apply { setupWithViewPager(binding.viewPager) } binding.vm = mainViewModel } private fun checkPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.MODIFY_AUDIO_SETTINGS) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ) { if ((ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.MODIFY_AUDIO_SETTINGS)) || (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA))|| (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE))|| (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) ) { } } else { ActivityCompat.requestPermissions(this, Strings.checkList, PERMISSION) } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == PERMISSION) { if (grantResults.isNotEmpty()) { for (i in 0..grantResults.size - 1) { if (grantResults[i] == PackageManager.PERMISSION_DENIED) { return } } } } } } <file_sep>package com.smtm.mvvm.presentation.search import androidx.databinding.BindingAdapter import androidx.recyclerview.widget.RecyclerView /** **/ @BindingAdapter("imageSearchState") fun setImageSearchState(recyclerView: RecyclerView, searchState: SearchState) { (recyclerView.adapter as? SearchResultsAdapter)?.let { adapter -> with(adapter) { when (searchState) { SearchState.NONE, SearchState.SUCCESS -> { changeFooterViewVisibility(false) } SearchState.FAIL -> { changeFooterViewVisibility(true) } } } } }<file_sep>package com.smtm.mvvm.presentation.search import android.util.Log import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.smtm.mvvm.data.repository.user.model.UserDocument import com.smtm.mvvm.databinding.ItemRepositoryBinding import com.smtm.mvvm.databinding.ItemRetryFooterBinding import com.smtm.mvvm.extension.cancelImageLoad import io.reactivex.Observable import io.reactivex.subjects.PublishSubject /** */ class SearchResultsAdapter : ListAdapter<UserDocument, RecyclerView.ViewHolder>(DiffCallback()) { companion object { private const val TYPE_ITEM = 1 private const val TYPE_FOOTER = 2 } private var retryFooterViewVisibility = false private val _footerClicks = PublishSubject.create<Unit>() val footerClicks: Observable<Unit> = _footerClicks var onBindPosition: ((position: Int) -> Unit)? = null private val _itemClicks = PublishSubject.create<UserDocument>() val itemClicks: Observable<UserDocument> = _itemClicks override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val inflater = LayoutInflater.from(parent.context) return if (viewType == TYPE_ITEM) { SearchResultsViewHolder(ItemRepositoryBinding.inflate(inflater, parent, false)).apply { binding.repositoryItemRemove.setOnClickListener { _itemClicks.onNext(getItem(adapterPosition)) } } } else { RetryFooterViewHolder(ItemRetryFooterBinding.inflate(inflater, parent, false)).apply { binding.retryButton.setOnClickListener { _footerClicks.onNext(Unit) } } } // // // return SearchResultsViewHolder( // ItemRepositoryBinding.inflate(inflater, parent, false)).apply { // binding.repositoryItemRemove.setOnClickListener { // ) // _itemClicks.onNext(getItem(adapterPosition)) // } // } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when(holder) { is SearchResultsViewHolder -> { Log.e("gg","onBindViewHolder") holder.setItem(getItem(position)) onBindPosition?.invoke(position) } is RetryFooterViewHolder -> { holder.setRetryVisibility(retryFooterViewVisibility) } } } override fun getItemViewType(position: Int): Int { return if (isFooterViewPosition(position)) { TYPE_FOOTER } else { TYPE_ITEM } } /** * recyclerview adapter는 row가 재활용이 되기 위해 내부데이터를 지우기 바로 전에 onViewRecycled를 호출하는데요 출처: https://trend21c.tistory.com/2021 [나를 찾는 아이] 샘플 코드 https://github.com/spotlight21c/viewpagerinrecyclerview */ override fun onViewRecycled(holder: RecyclerView.ViewHolder) { when(holder) { is SearchResultsViewHolder -> { holder.clear() } } super.onViewRecycled(holder) } override fun getItemCount(): Int { val itemCount = super.getItemCount() return if (itemCount == 0) { itemCount } else { itemCount + 1 } } fun isFooterViewPosition(position: Int): Boolean { return position == super.getItemCount() } fun changeFooterViewVisibility(visibility: Boolean) { retryFooterViewVisibility = visibility notifyItemChanged(super.getItemCount()) } class SearchResultsViewHolder(val binding: ItemRepositoryBinding) : RecyclerView.ViewHolder(binding.root) { fun setItem(userDocument: UserDocument) { binding.userDocument = userDocument binding.executePendingBindings() } fun clear() { binding.repositoryItemAvatarUrl.cancelImageLoad() } } class RetryFooterViewHolder( val binding: ItemRetryFooterBinding ) : RecyclerView.ViewHolder(binding.root) { fun setRetryVisibility(visible: Boolean) { binding.retryButtonVisibility = visible binding.executePendingBindings() } } class DiffCallback : DiffUtil.ItemCallback<UserDocument>() { override fun areItemsTheSame(oldItem: UserDocument, newItem: UserDocument): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: UserDocument, newItem: UserDocument): Boolean { return oldItem == newItem } } }<file_sep>package com.smtm.mvvm.data.remote.api import com.smtm.mvvm.data.remote.request.ConnectRequest import com.smtm.mvvm.data.remote.response.ConnectResponse import com.smtm.mvvm.data.remote.response.GithubUserResponse import com.smtm.mvvm.data.remote.response.TokenResponse import io.reactivex.Single import retrofit2.http.* /** */ interface SearchAPI { @GET("/search/users") fun search( @Query("q") query: String, @Query("page") page: Int, @Query("per_page") per_page: Int ): Single<GithubUserResponse> // 토큰 발금 @FormUrlEncoded @POST("/authentication/token") fun token( @Field("apiKey") apiKey: String, @Field("apiSecret") apiSecret: String ): Single<TokenResponse> // @FormUrlEncoded // @POST("/connection/in") // fun connect( // @Header("Authorization") token: String?, // @Field("userId") userId: String?, // @Field("publicRoomId") publicRoomId: String?, // @Field("userData") userData: com.smtm.mvvm.data.remote.request.UserData // ): Single<ConnectResponse> @POST("/connection/in") fun connect( @Header("Authorization") token: String?, @Body connectRequest: ConnectRequest ): Single<ConnectResponse> }<file_sep>package com.smtm.mvvm.data.repository.user import com.smtm.mvvm.data.remote.request.ConnectRequest import com.smtm.mvvm.data.remote.request.GithubUserRequest import com.smtm.mvvm.data.remote.request.TokenRequest import com.smtm.mvvm.data.remote.response.ConnectResponse import com.smtm.mvvm.data.remote.response.TokenResponse import com.smtm.mvvm.data.repository.user.model.UserDocument import com.smtm.mvvm.data.repository.user.model.UserResponse import io.reactivex.Completable import io.reactivex.Observable import io.reactivex.Single /** **/ interface UserRepository { fun getImages(userSearchRequest: GithubUserRequest): Single<UserResponse> fun getAllFavoriteImages(): Single<List<UserDocument>> fun saveFavoriteImage(imageDocument: UserDocument): Completable fun deleteFavoriteImage(imageDocument: UserDocument): Completable fun observeChangingFavoriteImage(): Observable<UserDocument> fun getToken(tokenRequest: TokenRequest): Single<TokenResponse> fun getConnect(token: String,tokenRequest: ConnectRequest): Single<ConnectResponse> }<file_sep>package com.smtm.mvvm.presentation.common.pageload data class PageLoadConfiguration( val startPageNumber: Int, val maxPageNumber: Int, val requiredDataSize: Int, val preloadAllowLineMultiple: Int = 1 )<file_sep>package com.smtm.mvvm.extension /** */ fun <T1, T2, R> safeLet(t1: T1?, t2: T2?, block: (T1, T2) -> R?): R? { return if(t1 != null && t2 != null) { block(t1, t2) } else { null } } fun <T1, T2, T3, R> safeLet(t1: T1?, t2: T2?, t3: T3?, block: (T1, T2, T3) -> R?): R? { return if(t1 != null && t2 != null && t3 != null) { block(t1, t2, t3) } else { null } }<file_sep>package com.smtm.mvvm.presentation.main import android.app.Application import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import com.smtm.mvvm.presentation.base.BaseViewModel /** */ class MainViewModel(application: Application) : BaseViewModel(application) { private val _index = MutableLiveData<Int>() val text: LiveData<String> = Transformations.map(_index) { "Hello world from section: $it" } fun setIndex(index: Int) { _index.value = index } }<file_sep>package com.smtm.mvvm.presentation.base import android.os.Bundle import android.os.PersistableBundle import android.widget.Toast import androidx.annotation.LayoutRes import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding /** */ abstract class BaseActivity<B : ViewDataBinding> : AppCompatActivity() { companion object { private const val ARGUMENT_ACTIVITY_IS_CREATED = "ARGUMENT_ACTIVITY_IS_CREATED" } protected lateinit var binding: B private set protected var isActivityFirstCreate: Boolean = true private set override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initBinding() checkActivityFirstCreate(savedInstanceState) } private fun initBinding() { binding = DataBindingUtil.setContentView<B>(this, getLayoutId()).apply { lifecycleOwner = this@BaseActivity } } private fun checkActivityFirstCreate(savedInstanceState: Bundle?) { isActivityFirstCreate = savedInstanceState?.getBoolean(ARGUMENT_ACTIVITY_IS_CREATED)?.not() ?: true } override fun onSaveInstanceState(outState: Bundle?, outPersistentState: PersistableBundle?) { super.onSaveInstanceState(outState, outPersistentState) outState?.putBoolean(ARGUMENT_ACTIVITY_IS_CREATED, true) } protected fun showToast(message: String?) { message?.let { Toast.makeText(applicationContext, it, Toast.LENGTH_SHORT).show() } } @LayoutRes protected abstract fun getLayoutId(): Int }<file_sep>package com.smtm.mvvm.data.remote.request import com.google.gson.annotations.SerializedName /** */ data class Template( @SerializedName("preset") var preset: String )<file_sep>package ccom.leopold.mvvm.common.pageload data class PageLoadApproveLog<T>( var key: T? = null, var dataTotalSize: Int? = null, var pageNumber: Int? = null )<file_sep>apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-kapt' android { compileSdkVersion AndroidSdk.compileSdk defaultConfig { applicationId "com.smtm.mvvm" minSdkVersion AndroidSdk.minSdk targetSdkVersion AndroidSdk.targetSdk versionCode AndroidSdk.versionCode versionName AndroidSdk.versionName testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } dataBinding { enabled = true } packagingOptions { exclude 'LICENSE.txt' exclude 'LICENSE' exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/NOTICE' exclude 'META-INF/NOTICE.txt' exclude 'META-INF/rxjava.properties' } compileOptions { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } buildTypes { debug { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } release { minifyEnabled false proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" } } } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') // Support Libraries implementation Support.app_compat implementation Support.v4 implementation Support.design implementation Support.recyclerview implementation Support.constraint_layout // Architecture components kapt Lifecycle.compiler implementation Lifecycle.runtime implementation Lifecycle.extensions // implementation Libraries.paging_ktx // room implementation Room.runtime kapt Room.compiler implementation Room.rxjava2 // RxJava implementation Rx.rx_android implementation Rx.rxjava2 // Kotlin implementation Kotlin.stdlib // Koin implementation Koin.core implementation Koin.android implementation Koin.architecture //glide implementation Glide.runtime kapt Glide.compiler // Retrofit implementation Retrofit.runtime implementation Retrofit.rx_adapter implementation Retrofit.gson // OkHttp implementation Libraries.okhttp_logging_interceptor // testImplementation Kotlin.stdlib // testImplementation Kotlin.test // testImplementation Koin.test, { exclude group: 'org.mockito' } // testing // Dependencies for local unit tests testImplementation TestLibraries.junit testImplementation Lifecycle.arch_core testImplementation TestLibraries.mockk // Core library androidTestImplementation TestLibraries.test_core // Assertions androidTestImplementation TestLibraries.ext_junit androidTestImplementation TestLibraries.ext_truth androidTestImplementation TestLibraries.google_truth // AndroidJUnitRunner and JUnit Rules androidTestImplementation TestLibraries.axt_runner androidTestImplementation TestLibraries.axt_rules // Espresso dependencies androidTestImplementation TestLibraries.espresso_core // Resolve conflicts between main and test APK: // androidTestImplementation Support.annotations // androidTestImplementation Support.v4 // androidTestImplementation Support.app_compat // androidTestImplementation Support.design } <file_sep>package com.smtm.mvvm.data.remote.request import com.google.gson.annotations.SerializedName /** */ data class ConnectRequest( val userId: String, val publicRoomId: String, var userData: UserData, var template: Template, var appName: String ) <file_sep>package com.smtm.mvvm.data.repository.user import com.smtm.mvvm.data.repository.user.model.UserDocument import io.reactivex.Completable import io.reactivex.Single /** */ interface UserLocalDataSource { fun saveFavoriteUserDocument(imageDocument: UserDocument): Completable fun deleteFavoriteUserDocument(imageDocument: UserDocument): Completable fun getAllFavoriteUsers(): Single<List<UserDocument>> }<file_sep>package com.smtm.mvvm.data.remote.response import com.google.gson.annotations.SerializedName /** */ data class TokenResponse( @SerializedName("token") val token: String, @SerializedName("exp") val exp: String )<file_sep>package com.smtm.mvvm.di import com.smtm.mvvm.presentation.bookmark.BookmarkViewModel import com.smtm.mvvm.presentation.main.MainViewModel import com.smtm.mvvm.presentation.search.SearchViewModel import com.smtm.mvvm.presentation.webview.WebViewModel import org.koin.androidx.viewmodel.ext.koin.viewModel import org.koin.dsl.module.module /** */ val viewModelModule = module { viewModel { MainViewModel(get()) } viewModel { SearchViewModel(get(), get(), get()) } viewModel { BookmarkViewModel(get(), get()) } viewModel { WebViewModel(get(), get()) } }<file_sep>package com.smtm.mvvm.data.db.entity import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.TypeConverters import com.smtm.mvvm.data.db.converter.DateConverter /** */ @Entity(tableName = "Bookmark") @TypeConverters(DateConverter::class) data class BookmarkEntity( @PrimaryKey val id: String, @ColumnInfo(name = "book_id") val book_id: Long, @ColumnInfo(name = "login") val login: String, @ColumnInfo(name = "avatar_url") val avatar_url: String, @ColumnInfo(name = "isFavorite") val isFavorite: Boolean )<file_sep>package com.smtm.mvvm.di import com.smtm.mvvm.presentation.common.pageload.PageLoadConfiguration import com.smtm.mvvm.presentation.common.pageload.PageLoadHelper import org.koin.dsl.module.module /** **/ val helperModule = module { factory { PageLoadHelper<String>(get()) } factory { PageLoadConfiguration(1, 50, 50, 5) } }<file_sep>package com.smtm.mvvm.data.repository.user import com.smtm.mvvm.data.remote.request.ConnectRequest import com.smtm.mvvm.data.remote.request.GithubUserRequest import com.smtm.mvvm.data.remote.request.TokenRequest import com.smtm.mvvm.data.remote.response.ConnectResponse import com.smtm.mvvm.data.remote.response.TokenResponse import com.smtm.mvvm.data.repository.user.model.UserDocument import com.smtm.mvvm.data.repository.user.model.UserResponse import io.reactivex.Completable import io.reactivex.Observable import io.reactivex.Single import io.reactivex.functions.BiFunction import io.reactivex.schedulers.Schedulers import io.reactivex.subjects.PublishSubject /** **/ class UserRepositoryImpl( private val userLocalDataSource: UserLocalDataSource, private val userRemoteDataSource: UserRemoteDataSource ) : UserRepository { private val favoriteChangePublishSubject = PublishSubject.create<UserDocument>() override fun getImages(userSearchRequest: GithubUserRequest): Single<UserResponse> { return Single.zip( userRemoteDataSource.getUsers(userSearchRequest) .subscribeOn(Schedulers.io()), userLocalDataSource.getAllFavoriteUsers() .map { favoriteList -> favoriteList.associateBy({ it.id }, {it}) } .subscribeOn(Schedulers.io()), BiFunction { response: UserResponse, favoriteMap: Map<String, UserDocument> -> val newList = response.githubDocuments.map { favoriteMap[it.id] ?: it } UserResponse(newList) } ).subscribeOn(Schedulers.io()) } override fun getAllFavoriteImages(): Single<List<UserDocument>> { return userLocalDataSource.getAllFavoriteUsers() .subscribeOn(Schedulers.io()) } override fun saveFavoriteImage(imageDocument: UserDocument): Completable { return userLocalDataSource.saveFavoriteUserDocument(imageDocument) .doOnComplete { favoriteChangePublishSubject.onNext(imageDocument) } .subscribeOn(Schedulers.io()) } override fun deleteFavoriteImage(imageDocument: UserDocument): Completable { return userLocalDataSource.deleteFavoriteUserDocument(imageDocument) .doOnComplete { favoriteChangePublishSubject.onNext(imageDocument) } .subscribeOn(Schedulers.io()) } override fun observeChangingFavoriteImage(): Observable<UserDocument> { return favoriteChangePublishSubject.subscribeOn(Schedulers.io()) } override fun getToken(tokenRequest: TokenRequest): Single<TokenResponse> { return userRemoteDataSource.getToken(tokenRequest) .subscribeOn(Schedulers.io()) } override fun getConnect(token: String, connectRequest: ConnectRequest): Single<ConnectResponse> { return userRemoteDataSource.getConnect(token,connectRequest) .subscribeOn(Schedulers.io()) } }<file_sep>package com.smtm.mvvm.presentation.base import androidx.databinding.ViewDataBinding import androidx.lifecycle.Lifecycle import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable /** */ abstract class RxBaseFragment<B : ViewDataBinding> : BaseFragment<B>() { private val compositeDisposableMap = HashMap<Lifecycle.Event, CompositeDisposable>().apply { put(Lifecycle.Event.ON_PAUSE, CompositeDisposable()) put(Lifecycle.Event.ON_STOP, CompositeDisposable()) put(Lifecycle.Event.ON_DESTROY, CompositeDisposable()) } override fun onPause() { compositeDisposableMap[Lifecycle.Event.ON_PAUSE]?.clear() super.onPause() } override fun onStop() { compositeDisposableMap[Lifecycle.Event.ON_STOP]?.clear() super.onStop() } override fun onDestroy() { compositeDisposableMap[Lifecycle.Event.ON_DESTROY]?.clear() super.onDestroy() } protected fun Disposable.disposeByOnPause() { compositeDisposableMap[Lifecycle.Event.ON_PAUSE]?.add(this) } protected fun Disposable.disposeByOnStop() { compositeDisposableMap[Lifecycle.Event.ON_STOP]?.add(this) } protected fun Disposable.disposeByOnDestroy() { compositeDisposableMap[Lifecycle.Event.ON_DESTROY]?.add(this) } } <file_sep>package com.smtm.mvvm.di import com.smtm.mvvm.data.db.AppDatabase import com.smtm.mvvm.data.db.UserLocalDataSourceImpl import com.smtm.mvvm.data.repository.user.UserLocalDataSource import org.koin.android.ext.koin.androidApplication import org.koin.dsl.module.module /** */ val roomModule = module { single { AppDatabase.getInstance(androidApplication()) } single<UserLocalDataSource> { UserLocalDataSourceImpl(get()) } single { get<AppDatabase>().getBookmarkDao() } }<file_sep>package com.smtm.mvvm.data.repository.error import java.lang.Exception /** **/ sealed class RepositoryException(errorMessage: String) : Exception(errorMessage) { // 찾을 수 없는 오류 class NotFoundException(errorMessage: String): RepositoryException(errorMessage) // 잘못된 요청 오류(잘못된 파라미터) class WrongRequestException(errorMessage: String) : RepositoryException(errorMessage) // 사용자 인증 오류 class AuthenticationException(errorMessage: String): RepositoryException(errorMessage) // 권한/퍼미션 오류 class PermissionException(errorMessage: String): RepositoryException(errorMessage) // 서버 시스템 오류 class ServerSystemException(errorMessage: String): RepositoryException(errorMessage) // 네트워크 미 연결 오류 class NetworkNotConnectingException(errorMessage: String): RepositoryException(errorMessage) // 네트워크 알 수 없는 오류 class NetworkUnknownException(errorMessage: String): RepositoryException(errorMessage) // 데이터베이스 알 수 없는 오류 class DatabaseUnknownException(errorMessage: String): RepositoryException(errorMessage) // 알 수 없는 오류 class UnknownException(errorMessage: String): RepositoryException(errorMessage) }<file_sep>package com.smtm.mvvm.presentation.common.databinding import androidx.databinding.BindingAdapter import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView /** */ @Suppress("UNCHECKED_CAST") @BindingAdapter("itemsWithListAdapter") fun <T, VH : RecyclerView.ViewHolder> setItemsWithListAdapter(recyclerView: RecyclerView, items: List<T>?) { (recyclerView.adapter as? ListAdapter<T, VH>)?.let { adapter -> val newList = if(items == null || items.isEmpty()) null else ArrayList(items) adapter.submitList(newList) if(newList == null) { adapter.notifyDataSetChanged() } } } @BindingAdapter("spanCount") fun setSpanCount(recyclerView: RecyclerView, spanCount: Int) { (recyclerView.layoutManager as? GridLayoutManager)?.spanCount = spanCount }<file_sep>package com.smtm.mvvm.extension import android.graphics.drawable.Drawable import android.view.View import android.widget.ImageView import android.widget.ProgressBar import com.bumptech.glide.Glide import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.load.resource.bitmap.RoundedCorners import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.RequestOptions import com.bumptech.glide.request.target.Target import com.smtm.mvvm.R /** */ private const val THUMBNAIL_VALUE = 0.1f private val centerCropRequestOptionsMap = mutableMapOf<Int, RequestOptions>() private val centerInsideRequestOptionsMap = mutableMapOf<Int, RequestOptions>() private fun getCenterCropRequestOptions(roundedCornersRadius: Int): RequestOptions { val radius = if(roundedCornersRadius < 0) 0 else roundedCornersRadius val requestOptions = centerCropRequestOptionsMap[radius] ?: run { createDefaultRequestOptions().centerCrop().apply { if (0 < roundedCornersRadius) { transform(RoundedCorners(roundedCornersRadius)) } } } centerCropRequestOptionsMap[radius] = requestOptions return requestOptions } private fun getCenterInsideRequestOptions(roundedCornersRadius: Int): RequestOptions { val radius = if(roundedCornersRadius < 0) 0 else roundedCornersRadius val requestOptions = centerInsideRequestOptionsMap[radius] ?: run { createDefaultRequestOptions().centerInside().apply { if (0 < roundedCornersRadius) { transform(RoundedCorners(roundedCornersRadius)) } } } centerCropRequestOptionsMap[radius] = requestOptions return requestOptions } private fun createDefaultRequestOptions(): RequestOptions { return RequestOptions() .diskCacheStrategy(DiskCacheStrategy.NONE) .error(R.drawable.image_load_fail) } fun ImageView.cancelImageLoad() { Glide.with(context).clear(this) } fun ImageView.loadImageWithCenterCrop( imageUrl: String?, roundedCornersRadius: Int = 0, progressBar: ProgressBar? = null ) { val requestOptions = getCenterCropRequestOptions(roundedCornersRadius) loadImage(imageUrl, requestOptions, progressBar) } fun ImageView.loadImageWithCenterInside( imageUrl: String?, roundedCornersRadius: Int = 0, progressBar: ProgressBar? = null ) { val requestOptions = getCenterInsideRequestOptions(roundedCornersRadius) loadImage(imageUrl, requestOptions, progressBar) } private fun ImageView.loadImage( imageUrl: String?, requestOptions: RequestOptions, progressBar: ProgressBar? ) { progressBar?.visibility = View.VISIBLE Glide.with(context) .load(imageUrl ?: "") .thumbnail(THUMBNAIL_VALUE) .transition(DrawableTransitionOptions.withCrossFade()) .apply(requestOptions) .listener(object : RequestListener<Drawable> { override fun onLoadFailed( e: GlideException?, model: Any, target: Target<Drawable>, isFirstResource: Boolean ): Boolean { progressBar?.visibility = View.GONE return false } override fun onResourceReady( resource: Drawable, model: Any, target: Target<Drawable>, dataSource: DataSource, isFirstResource: Boolean ): Boolean { progressBar?.visibility = View.GONE return false } }) .into(this) }<file_sep>package com.smtm.mvvm.presentation.search import android.os.Bundle import android.util.Log import androidx.lifecycle.Observer import com.smtm.mvvm.R import com.smtm.mvvm.presentation.base.RxBaseFragment import com.smtm.mvvm.databinding.FragmentSearchBinding import com.smtm.mvvm.extension.throttleFirstWithHalfSecond import org.koin.androidx.viewmodel.ext.android.viewModel /** */ class SearchFragment : RxBaseFragment<FragmentSearchBinding>() { private val searchViewModel: SearchViewModel by viewModel() override fun getLayoutId(): Int { return R.layout.fragment_search } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) Log.e("gg","SearchFragment onActivityCreated()!!") initImageRecyclerView() initImageListViewModel() // binding.searchListViewModel = searchViewModel // binding.setLifecycleOwner(this) // TODO: Use the ViewModel } private fun initImageRecyclerView() { binding.searchRecyclerView.apply { adapter = SearchResultsAdapter().apply { onBindPosition = { position -> searchViewModel.loadMoreImagesIfPossible(position) } itemClicks.throttleFirstWithHalfSecond() .subscribe { document -> searchViewModel.onClickFavorite(document) } .disposeByOnDestroy() footerClicks.throttleFirstWithHalfSecond() .subscribe { searchViewModel.retryLoadMoreImageList() } .disposeByOnDestroy() } } } private fun initImageListViewModel() { val owner = this with(searchViewModel) { showMessageEvent.observe(owner, Observer { message -> showToast(message) }) } binding.searchListViewModel = searchViewModel } }<file_sep>package com.smtm.mvvm.data.remote.api import com.smtm.mvvm.data.remote.request.ConnectRequest import com.smtm.mvvm.data.remote.request.GithubUserRequest import com.smtm.mvvm.data.remote.request.TokenRequest import com.smtm.mvvm.data.remote.response.ConnectResponse import com.smtm.mvvm.data.remote.response.TokenResponse import com.smtm.mvvm.data.remote.response.mapper.GithubUserSearchEntityMapper import com.smtm.mvvm.data.repository.user.UserRemoteDataSource import com.smtm.mvvm.data.repository.user.model.UserResponse import io.reactivex.Single /** **/ class UserRemoteDataSourceImpl( private val githubSearchApi: SearchAPI ) : UserRemoteDataSource { override fun getUsers(userSearchRequest: GithubUserRequest): Single<UserResponse> { return userSearchRequest.run { githubSearchApi.search(keyword, pageNumber, requiredSize) .map { GithubUserSearchEntityMapper.fromEntity(it) } } } override fun getToken(tokenRequest: TokenRequest): Single<TokenResponse> { return tokenRequest.run { githubSearchApi.token(apiKey, apiSecret) } } override fun getConnect(authorization: String, connectRequest: ConnectRequest): Single<ConnectResponse> { return connectRequest.run { githubSearchApi.connect(authorization, connectRequest) } } }<file_sep>const val kotlinVersion = "1.3.50" object BuildPlugins { object Versions { const val buildToolsVersion = "3.5.3" } const val androidGradlePlugin = "com.android.tools.build:gradle:${Versions.buildToolsVersion}" const val kotlinGradlePlugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" } object AndroidSdk { const val compileSdk = 28 const val minSdk = 21 const val targetSdk = compileSdk const val versionCode = 1 const val versionName = "1.0.0" } object Kotlin { const val stdlib = "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlinVersion" const val test = "org.jetbrains.kotlin:kotlin-test-junit:$kotlinVersion" const val plugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" const val allopen = "org.jetbrains.kotlin:kotlin-allopen:$kotlinVersion" } object Support { private object Versions { const val compat = "1.1.0" const val material = "1.0.0" const val constraintLayout = "1.1.2" const val ktx = "1.1.0-alpha05" } const val annotations = "androidx.annotation:annotation:${Versions.compat}" const val app_compat = "androidx.appcompat:appcompat:${Versions.compat}" const val recyclerview = "androidx.recyclerview:recyclerview:${Versions.compat}" const val design = "com.google.android.material:material:${Versions.material}" const val v4 = "androidx.legacy:legacy-support-v4:${Versions.material}" const val core_utils = "androidx.legacy:legacy-support-core-utils:${Versions.compat}" const val constraint_layout = "androidx.constraintlayout:constraintlayout:${Versions.constraintLayout}" const val ktx_core = "androidx.core:core-ktx:${Versions.ktx}" } object Libraries { private object Versions { const val okhttp_logging_interceptor = "3.9.0" const val paging = "2.1.0" } const val okhttp_logging_interceptor = "com.squareup.okhttp3:logging-interceptor:${Versions.okhttp_logging_interceptor}" const val paging_ktx = "androidx.paging:paging-runtime-ktx:${Versions.paging}" } object Koin { private object Versions { const val koin = "1.0.2" } const val core = "org.koin:koin-core:${Versions.koin}" const val android = "org.koin:koin-android:${Versions.koin}" const val architecture = "org.koin:koin-androidx-viewmodel:${Versions.koin}" const val test = "org.koin:koin-test:${Versions.koin}" } object Room { private object Versions { const val room = "2.2.2" } const val runtime = "androidx.room:room-runtime:${Versions.room}" const val compiler = "androidx.room:room-compiler:${Versions.room}" const val rxjava2 = "androidx.room:room-rxjava2:${Versions.room}" const val testing = "androidx.room:room-testing:${Versions.room}" } object Lifecycle { private object Versions { const val lifecycle = "2.1.0" } const val runtime = "androidx.lifecycle:lifecycle-runtime:${Versions.lifecycle}" const val extensions = "androidx.lifecycle:lifecycle-extensions:${Versions.lifecycle}" const val java8 = "androidx.lifecycle:lifecycle-common-java8:${Versions.lifecycle}" const val compiler = "androidx.lifecycle:lifecycle-compiler:${Versions.lifecycle}" // optional - Test helpers for LiveData const val arch_core = "androidx.arch.core:core-testing:${Versions.lifecycle}" } object Retrofit { private object Versions { const val retrofit = "2.3.0" } const val runtime = "com.squareup.retrofit2:retrofit:${Versions.retrofit}" const val rx_adapter = "com.squareup.retrofit2:adapter-rxjava2:${Versions.retrofit}" const val gson = "com.squareup.retrofit2:converter-gson:${Versions.retrofit}" } object Rx { private object Versions { const val rxjava2 = "2.1.3" const val rx_android = "2.0.1" } const val rxjava2 = "io.reactivex.rxjava2:rxjava:${Versions.rxjava2}" const val rx_android = "io.reactivex.rxjava2:rxandroid:${Versions.rx_android}" } object Glide { private object Versions { const val glide = "4.11.0" } const val runtime = "com.github.bumptech.glide:glide:${Versions.glide}" const val compiler = "com.github.bumptech.glide:compiler:${Versions.glide}" } object TestLibraries { private object Versions { const val junit4 = "4.12" const val test_core = "1.2.0" const val ext_junit = "1.1.1" const val ext_truth = "1.2.0" const val google_truth = "0.42" const val axt_runner = "1.2.0" const val axt_rules = "1.2.0" const val espresso = "3.2.0" const val mockk_version = "1.9.3" } const val junit = "junit:junit:${Versions.junit4}" const val test_core = "androidx.test:core:${Versions.test_core}" const val ext_junit = "androidx.test.ext:junit:${Versions.ext_junit}" const val ext_truth = "androidx.test.ext:truth:${Versions.ext_truth}" const val google_truth = "com.google.truth:truth:${Versions.google_truth}" const val axt_runner = "androidx.test:runner:${Versions.axt_runner}" const val axt_rules = "androidx.test:rules:${Versions.axt_rules}" const val espresso = "androidx.test.espresso:espresso-core:${Versions.espresso}" const val espresso_core = "androidx.test.espresso:espresso-core:${Versions.espresso}" const val espresso_contrib = "androidx.test.espresso:espresso-contrib:${Versions.espresso}" const val espresso_intents = "androidx.test.espresso:espresso-intents:${Versions.espresso}" const val mockk = "io.mockk:mockk:${Versions.mockk_version}" }<file_sep>package com.smtm.mvvm import android.app.Application import com.smtm.mvvm.di.* import org.koin.android.ext.android.startKoin /** */ @Suppress("Unused") class MVVMApp : Application() { override fun onCreate() { super.onCreate() startKoin(this, listOf( networkModule, apiModule, repositoryModule, roomModule, viewModelModule, helperModule )) } }<file_sep>package com.smtm.mvvm.di import com.smtm.mvvm.data.remote.api.SearchAPI import com.smtm.mvvm.data.remote.api.UserRemoteDataSourceImpl import com.smtm.mvvm.data.repository.user.UserRemoteDataSource import org.koin.dsl.module.module import retrofit2.Retrofit /** */ val apiModule = module { single<UserRemoteDataSource> { UserRemoteDataSourceImpl(get()) } single(createOnStart = false) { get<Retrofit>().create(SearchAPI::class.java) } }<file_sep>package com.smtm.mvvm.presentation.webview import android.text.TextUtils import android.webkit.WebChromeClient import android.webkit.WebResourceRequest import androidx.databinding.BindingAdapter import android.webkit.WebView import android.webkit.WebViewClient @BindingAdapter("setWebViewClient") fun setWebViewClient(webView: WebView, client: WebViewClient) { webView.webViewClient = client WebView.setWebContentsDebuggingEnabled(false) webView.settings.javaScriptEnabled = true webView.settings.loadsImagesAutomatically = true webView.settings.useWideViewPort = true webView.settings.domStorageEnabled = true } @BindingAdapter("webViewUrl") fun loadUrl(webView: WebView, url: String) { if (TextUtils.isEmpty(url)) { return; } webView.loadUrl(url); } @BindingAdapter("htmlString") fun loadHTML(view: WebView, htmlString: String) { if (htmlString.isEmpty()) { return } try { view.webChromeClient = WebChromeClient() view.webViewClient = object : WebViewClient() { override fun onPageFinished(view: WebView, url: String) { super.onPageFinished(view, url) } override fun shouldOverrideUrlLoading( view: WebView, request: WebResourceRequest ): Boolean { return false } } view.loadData(htmlString, "text/html", "UTF-8") } catch (ex: Exception) { } } <file_sep>package com.smtm.mvvm.extension /** */ inline fun <T> MutableList<T>.removeFirstIf(predicate: (T) -> Boolean): MutableList<T> { for(i in 0 until size) { if(predicate(this[i])) { removeAt(i) break } } return this } inline fun <T> MutableList<T>.replace(replaceValue: T, predicate: (T) -> Boolean) { for(i in 0 until size) { if(predicate(this[i])) { this[i] = replaceValue break } } } fun <T> MutableList<T>.addFirst(value: T): MutableList<T> { add(0, value) return this }<file_sep>package com.smtm.mvvm.data.repository.user.model import android.os.Parcel import android.os.Parcelable /** **/ data class UserDocument( val id: String, val book_id: Long, val login: String, val avatar_url: String, var isFavorite: Boolean ) : Parcelable { constructor(source: Parcel) : this( source.readString() ?: "", source.readLong(), source.readString() ?: "", source.readString() ?: "", source.readInt() == 1 ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) { writeString(id) writeLong(book_id) writeString(login) writeString(avatar_url) writeInt((if (isFavorite) 1 else 0)) } companion object { @JvmField val CREATOR: Parcelable.Creator<UserDocument> = object : Parcelable.Creator<UserDocument> { override fun createFromParcel(source: Parcel): UserDocument = UserDocument(source) override fun newArray(size: Int): Array<UserDocument?> = arrayOfNulls(size) } } }<file_sep>package com.smtm.mvvm.data.remote.response.mapper import com.smtm.mvvm.data.remote.response.GithubUserResponse import com.smtm.mvvm.data.repository.user.model.UserDocument import com.smtm.mvvm.data.repository.user.model.UserResponse /** */ object GithubUserSearchEntityMapper { fun fromEntity(remoteEntity: GithubUserResponse): UserResponse { return remoteEntity.run { val userDocumentList = githubDocuments.map { UserDocument( "${it.avatar_url}", it.id, it.login?:"", it.avatar_url?:"", false ) } UserResponse(userDocumentList) } } }<file_sep>package com.smtm.mvvm.di import com.smtm.mvvm.data.repository.user.UserRepository import com.smtm.mvvm.data.repository.user.UserRepositoryImpl import org.koin.dsl.module.module /** **/ val repositoryModule = module { single<UserRepository> { UserRepositoryImpl(get(), get()) } }<file_sep>package com.smtm.mvvm.extension import androidx.lifecycle.MutableLiveData /** **/ inline fun <T> MutableLiveData<MutableList<T>>.removeFirstAndAddFirst(insertValue: T, predicate: (T) -> Boolean) { value?.let { list -> list.removeFirstIf(predicate) list.add(0, insertValue) value = list } } inline fun <T> MutableLiveData<MutableList<T>>.removeFirst(predicate: (T) -> Boolean) { value?.let { list -> list.removeFirstIf(predicate) value = list } } inline fun <T> MutableLiveData<MutableList<T>>.replace(replaceValue: T, predicate: (T) -> Boolean) { value?.let { list -> list.replace(replaceValue, predicate) value = list } } inline fun <T> MutableLiveData<MutableList<T>>.find(predicate: (T) -> Boolean): T? { return value?.let { list -> list.find { predicate(it) } } } fun <T> MutableLiveData<MutableList<T>>.clear() { value?.let { list -> list.clear() value = list } } fun <T> MutableLiveData<MutableList<T>>.isNotEmpty(): Boolean { return isEmpty().not() } fun <T> MutableLiveData<MutableList<T>>.isEmpty(): Boolean { return value?.isEmpty() ?: true } fun <T> MutableLiveData<MutableList<T>>.addAll(list: List<T>) { val newList = value ?: mutableListOf() newList.addAll(list) value = newList } fun <T> MutableLiveData<MutableList<T>>.add(t: T) { val newList = value ?: mutableListOf() newList.add(t) value = newList } fun <T> MutableLiveData<MutableList<T>>.size(): Int { return value?.size ?: 0 }<file_sep>package com.smtm.mvvm.data.db.dao import androidx.room.* import com.smtm.mvvm.data.db.entity.BookmarkEntity import io.reactivex.Completable import io.reactivex.Single /** */ @Dao interface BookmarkDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertOrUpdateImageDocument(imageDocumentEntity: BookmarkEntity): Completable @Query("DELETE FROM Bookmark WHERE id = :id") fun deleteImageDocument(id: String): Completable @Query("SELECT * FROM Bookmark") fun selectAllImageDocument(): Single<List<BookmarkEntity>> }<file_sep>package com.smtm.mvvm.presentation.search import android.app.Application import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import com.smtm.mvvm.R import com.smtm.mvvm.presentation.common.pageload.PageLoadHelper import com.smtm.mvvm.presentation.base.BaseViewModel import com.smtm.mvvm.data.remote.request.GithubUserRequest import com.smtm.mvvm.data.repository.error.RepositoryException import com.smtm.mvvm.data.repository.user.UserRepository import com.smtm.mvvm.data.repository.user.model.UserDocument import com.smtm.mvvm.extension.* import io.reactivex.android.schedulers.AndroidSchedulers /** */ class SearchViewModel( application: Application, private val userRepository: UserRepository, private val pageLoadHelper: PageLoadHelper<String> ) : BaseViewModel(application) { private val _userDocuments = MutableLiveData<MutableList<UserDocument>>() val userDocuments: LiveData<List<UserDocument>> = Transformations.map(_userDocuments) { it?.toList() } private val _imageSearchState = MutableLiveData<SearchState>(SearchState.NONE) val searchState: LiveData<SearchState> = _imageSearchState private var query: String = "" init { observeChangingFavoriteImage() observePageLoadInspector() } private var mUserDocument: UserDocument? = null private fun observeChangingFavoriteImage() { userRepository.observeChangingFavoriteImage() .observeOn(AndroidSchedulers.mainThread()) .subscribe({ changedUserDocument -> _userDocuments.replace(changedUserDocument) { it.id == changedUserDocument.id } }, { throwable -> Log.d("gg", throwable.message) }) .disposeByOnCleared() } fun onQueryChange(query: CharSequence) { this.query = query.toString() } fun doSearch() { _userDocuments.clear() pageLoadHelper.requestFirstLoad(query) } fun loadMoreImagesIfPossible(position: Int) { pageLoadHelper.requestPreloadIfPossible(position, _userDocuments.size()) } fun retryLoadMoreImageList() { pageLoadHelper.requestRetryAsPreviousValue() } private fun observePageLoadInspector() { pageLoadHelper.onPageLoadApproveCallback = { key, pageNumber, dataSize, isFirstPage -> val request = GithubUserRequest(key, pageNumber, dataSize, isFirstPage) requestImagesToRepository(request) } } private fun requestImagesToRepository(request: GithubUserRequest) { _imageSearchState.value = SearchState.NONE userRepository.getImages(request) .observeOn(AndroidSchedulers.mainThread()) .doOnSuccess { _imageSearchState.value = SearchState.SUCCESS } .doOnError { _imageSearchState.value = SearchState.FAIL } .subscribe({ response -> updateDocuments(response.githubDocuments) }, { throwable -> handlingImageSearchError(throwable) }) .disposeByOnCleared() } private fun updateDocuments( receivedImageDocuments: List<UserDocument> ) { _userDocuments.apply { addAll(receivedImageDocuments) }.also { if (it.isEmpty()) { updateShowMessage(R.string.success_image_search_no_result) } } } private fun handlingImageSearchError(throwable: Throwable) { when (throwable) { is RepositoryException.NetworkNotConnectingException -> { updateShowMessage(R.string.network_not_connecting_error) } else -> { updateShowMessage(R.string.unknown_error) } } } fun onClickFavorite(userDocument: UserDocument) { mUserDocument = userDocument.copy() mUserDocument?.let { document -> document.isFavorite = document.isFavorite.not() if (document.isFavorite) { saveFavoriteToRepository(document) } else { deleteFavoriteFromRepository(document) } } } private fun saveFavoriteToRepository(target: UserDocument) { userRepository.saveFavoriteImage(target) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ updateShowMessage(R.string.success_favorite_save) }, { throwable -> Log.d("gg", throwable.message) }) .disposeByOnCleared() } private fun deleteFavoriteFromRepository(target: UserDocument) { userRepository.deleteFavoriteImage(target) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ updateShowMessage(R.string.success_favorite_delete) }, { throwable -> handlingImageSearchError(throwable) }) .disposeByOnCleared() } } <file_sep>package com.smtm.mvvm.presentation.common.livedata import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer /** */ class NonNullMutableLiveData<T>(private val defaultValue: T): MutableLiveData<T>(defaultValue) { override fun setValue(value: T) { super.setValue(value) } override fun postValue(value: T) { super.postValue(value) } override fun getValue(): T { return super.getValue() ?: defaultValue } override fun observe(owner: LifecycleOwner, observer: Observer<in T>) { super.observe(owner, Observer<T> { value -> observer.onChanged(value ?: defaultValue) }) } }<file_sep>package com.smtm.mvvm.data.remote.request /** */ data class TokenRequest( val apiKey: String, val apiSecret: String )<file_sep>package com.smtm.mvvm.presentation.bookmark import android.app.Application import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import com.smtm.mvvm.R import com.smtm.mvvm.presentation.common.livedata.SingleLiveEvent import com.smtm.mvvm.presentation.base.BaseViewModel import com.smtm.mvvm.data.repository.user.UserRepository import com.smtm.mvvm.data.repository.user.model.UserDocument import com.smtm.mvvm.extension.add import com.smtm.mvvm.extension.removeFirst import io.reactivex.android.schedulers.AndroidSchedulers /** */ class BookmarkViewModel(application: Application, private val userRepository: UserRepository): BaseViewModel(application) { // val items: LiveData<PagedList<BookmarkEntity>> = LivePagedListBuilder(dao.findAll(), /* page size */ 10).build() // // fun delete(bookmarkEntity: BookmarkEntity) = ioThread { dao.delete(bookmarkEntity) } private val _favoriteImages = MutableLiveData<MutableList<UserDocument>>() val favoriteImages: LiveData<List<UserDocument>> = Transformations.map(_favoriteImages) { it?.toList() } private val _moveToDetailScreenEvent = SingleLiveEvent<UserDocument>() val moveToDetailScreenEvent: LiveData<UserDocument> = _moveToDetailScreenEvent init { // observeChangingFavoriteImage() } fun loadFavoriteImageList() { userRepository.getAllFavoriteImages() .observeOn(AndroidSchedulers.mainThread()) .subscribe({ receivedFavoriteImages -> _favoriteImages.value = receivedFavoriteImages.toMutableList() }, { throwable -> Log.d("", throwable.message) }) .disposeByOnCleared() } fun onClickDel(userDocument: UserDocument) { deleteFavoriteFromRepository(userDocument) // _moveToDetailScreenEvent.value = userDocument } private fun observeChangingFavoriteImage() { userRepository.observeChangingFavoriteImage() .observeOn(AndroidSchedulers.mainThread()) .subscribe({ changedImageDocument -> with(changedImageDocument) { _favoriteImages.removeFirst { it.id == id } if(isFavorite) { _favoriteImages.add(this) } } }, { Log.d("", it.message) }) .disposeByOnCleared() } private fun deleteFavoriteFromRepository(target: UserDocument) { userRepository.deleteFavoriteImage(target) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ updateImageDocument(target) updateShowMessage(R.string.success_favorite_delete) }, { throwable -> Log.d("", throwable.message) }) .disposeByOnCleared() } private fun updateImageDocument(target: UserDocument) { // userDocument = target // _isFavorite.value = target.isFavorite observeChangingFavoriteImage() } } <file_sep>package com.smtm.mvvm.util import android.Manifest object Strings { val checkList = arrayOf(Manifest.permission.MODIFY_AUDIO_SETTINGS, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO) }<file_sep>package com.smtm.mvvm.data.db import com.smtm.mvvm.data.db.dao.BookmarkDao import com.smtm.mvvm.data.db.entity.mapper.UserDocumentEntityMapper import com.smtm.mvvm.data.db.transformer.error.CompletableExceptionTransformer import com.smtm.mvvm.data.db.transformer.error.SingleExceptionTransformer import com.smtm.mvvm.data.repository.user.UserLocalDataSource import com.smtm.mvvm.data.repository.user.model.UserDocument import io.reactivex.Completable import io.reactivex.Single /** */ class UserLocalDataSourceImpl( private val bookDAO: BookmarkDao ) : UserLocalDataSource { override fun saveFavoriteUserDocument(userDocument: UserDocument): Completable { val imageDocumentEntity = UserDocumentEntityMapper.toEntity(userDocument) return bookDAO.insertOrUpdateImageDocument(imageDocumentEntity) .compose(CompletableExceptionTransformer()) } override fun deleteFavoriteUserDocument(userDocument: UserDocument): Completable { return bookDAO.deleteImageDocument(userDocument.id) .compose(CompletableExceptionTransformer()) } override fun getAllFavoriteUsers(): Single<List<UserDocument>> { return bookDAO.selectAllImageDocument() .map { UserDocumentEntityMapper.fromEntityList(it) } .compose(SingleExceptionTransformer()) } }<file_sep>package com.smtm.mvvm.presentation.main import android.content.Context import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentStatePagerAdapter import com.smtm.mvvm.R import com.smtm.mvvm.presentation.bookmark.BookmarkFragment import com.smtm.mvvm.presentation.search.SearchFragment import com.smtm.mvvm.presentation.webview.WebFragment class MainAdapter(private val context: Context, fm: FragmentManager) : FragmentStatePagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) { private val TAB_TITLES = arrayOf( R.string.tab_text_1, R.string.tab_text_2 ) // fragNum : 몇개의 Fragment를 생성할 것인지를 인자로 받는다. // fm : FragmentManager로 FragmentStatePagerAdapter의 생성자 매개변수 val firstFrag : Fragment = SearchFragment() // val firstFrag: Fragment = WebFragment() val secondFrag: Fragment = BookmarkFragment() // position 별로 어느 Fragment로 이동할지 결정 override fun getItem(position: Int): Fragment { return when (position) { 0 -> firstFrag 1 -> secondFrag else -> firstFrag } } override fun getPageTitle(position: Int): CharSequence? { return context.resources.getString(TAB_TITLES[position]) } // 몇 개의 Fragment인지 결정 override fun getCount(): Int = 2 }
5f7461a6d0d36c79b4fb2bd39a89825501b7c0b6
[ "JavaScript", "Kotlin", "Gradle" ]
67
Kotlin
asus4862/MVVMArchitecture
c535bd319d7a77fb9d5df8524313026d1b3ce2da
f03312176116884246d649299f04f5cbb0d1a965
refs/heads/master
<repo_name>icelandcheng/test<file_sep>/break_time.py import time import webbrowser num=1 while(num<3): time.sleep(10) webbrowser.open("https://www.youtube.com/watch?v=DDWKuo3gXMQ") num=num+1 <file_sep>/circle_square.py import turtle def draw_circle(): window = turtle.Screen() window.bgcolor("red") cir = turtle.Turtle() cir.shape("classic") cir.color("yellow") for i in range(0,36): num=1 while(num<5): cir.forward(100) cir.right(90) num=num+1 cir.right(10) window.exitonclick() draw_circle() <file_sep>/README.md # test 測試上傳 j
285db85ea6290bcf41adde639ec746d2077b2663
[ "Markdown", "Python" ]
3
Python
icelandcheng/test
9eb4b68c71d15a2d09668aa9bcc48a5c07427515
03822e78e5a6007ae89aa9d40d05ea4d2182ce48
refs/heads/master
<repo_name>oahmadseecs/Advanced-Programming-Labs<file_sep>/lab9_src/FormComponents/UserForm/userform.js import React from 'react'; import './userform.css'; class UserForm extends React.Component{ constructor(){ super(); } render(){ return ( <form> <input type="text" name="Name" placeholder="Name" /> <br /> <input type="text" name="Username" placeholder="Username" /> <br /> <input type="<PASSWORD>" name="Password" placeholder="<PASSWORD>" /> <br /> <select name="type"> <option value="Seller">Seller</option> <option value="Buyer">Buyer</option> </select> <br /> <button type="submit" className="btn btn-submit">Submit</button> </form> ); } } export default UserForm;<file_sep>/lab9_src/FormComponents/CategoryForm/form.js import React from 'react'; import './form.css'; class CategoryForm extends React.Component{ constructor(){ super(); } render(){ return ( <form> <input type="checkbox" name="category1" /> <p>Technology</p> <br /> <input type="checkbox" name="category1" /> <p>Clothing</p> <br /> <input type="checkbox" name="category1" /> <p>Cosmetics</p> <br /> <input type="checkbox" name="category1" /> <p>Vehicles</p> <br /> </form> ); } } export default CategoryForm;<file_sep>/lab9_src/Components/Product/product.js import React, {Component} from 'react'; import './product.css'; import img from '../../assets/placeholder.png'; class Product extends Component { constructor(props){ super(props); this.state = { name : this.props.name, imgUrl : this.props.image, summary : this.props.summary, price : this.props.price } this.sendData = this.sendData.bind(this); } product = { name : this.props.name, imgUrl : this.props.image, summary : this.props.summary, price : this.props.price } sendData(){ this.props.recvData(this.product); } render(){ return ( <div className="product"> <div className="imageContainer"> <img className="thumbnail" src={this.state.imgUrl}></img> </div> <h1 className="productName">{this.state.name}</h1> <p className="summar">{this.state.summary}</p> <p className="price">${this.state.price}</p> <button className="btn button-cart" onClick={this.sendData}>Add to Cart</button> </div> ) } } export default Product;<file_sep>/lab9_src/Components/ProductArea/productArea.js import React ,{Component} from 'react'; import './productArea.css'; import Cart from '../Cart/cart'; import Product from '../Product/product'; import { EventEmitter } from 'events'; class ProductArea extends Component { constructor(){ super(); this.state = { products : [], incrementCart : false }; this.addtoCart = this.addtoCart.bind(this); this.getResponse = this.getResponse.bind(this); this.sendStates = this.sendStates.bind(this); } sendStates(data){ this.props.sendStates(data); } addtoCart(data){ this.setState({ incrementCart : true, Data : data }) } getResponse() { this.setState({ incrementCart : false }) } componentDidMount(){ var data = require('../../codebeautify.json'); this.setState({ products : data.arrayOfProducts }) } render(){ const data = this.state.products; return ( <div className="main"> <div className="border-bottom"> <h2>Products</h2> <button class="cart-container" onClick={this.props.changeView}> { this.state.incrementCart ? <Cart sendStates={this.sendStates} data={this.state.Data} response={this.getResponse} increment={true} smallerView = {true} /> : <Cart sendStates={this.sendStates} smallerView = {true} data={this.state.Data} response={this.getResponse} increment={false} /> } </button> </div> <div className="productContainer"> { this.state.products.map(function(product){ return ( <Product image = {product.imgUrl} name = {product.name} summary = {product.summary} price = {product.price} recvData = {this.addtoCart} /> ); }, this) } </div> </div> ) } } export default ProductArea; <file_sep>/lab9_src/Components/Admin/admin.js import React, {Component} from 'react'; import './admin.css'; import { tsConstructorType } from '@babel/types'; import Popup from '../Popup/popup'; class Admin extends Component { constructor(){ super(); this.state = { text : "Edit Form", showPopupEdit : false, showPopupAdd : false } this.togglePopupEdit = this.togglePopupEdit.bind(this); this.togglePopupAdd = this.togglePopupAdd.bind(this); } togglePopupEdit(){ this.setState({ showPopupEdit : !this.state.showPopupEdit }); console.log(this.state.showPopupEdit); } togglePopupAdd(){ this.setState({ showPopupAdd : !this.state.showPopupAdd }); } render(){ return ( <div className="admin-container"> <h1 id="pageHeading">Users</h1> <table> <tr> <th>Name</th> <th>Username</th> <th>Password</th> <th>Type</th> <th>Actions</th> </tr> <tr> <td><NAME></td> <td>owi4014</td> <td>1234</td> <td>Seller</td> <td className="btn-con"> <button className="btn btn-edit" onClick={this.togglePopupEdit}>Edit</button> <button className="btn btn-delete">Delete</button> </td> </tr> <tr> <td colSpan="5"><button className="btn btn-add" onClick={this.togglePopupAdd}>Add Users</button></td> </tr> </table> {this.state.showPopupEdit ? <Popup text="Edit Form" closePopup = {this.togglePopupEdit} /> : null } { this.state.showPopupAdd ? <Popup text="Add User" closePopup = {this.togglePopupAdd} /> : null } </div> ); } } export default Admin;<file_sep>/lab9_src/Components/Cart/cart.js import React, {Component} from 'react'; import './cart.css'; class Cart extends Component { constructor(props){ super(props); this.state = { count : 0, products : [] } } products = []; componentDidUpdate(prevProps){ if(this.props.increment == true){ this.setState({ count : this.state.count + 1 }) this.products = this.state.products; this.products.push(this.props.data); this.setState({ products : this.products }); this.sendResponse(); } } componentWillUnmount() { var data = this.state; this.props.sendStates(data); } sendResponse(){ this.props.response(); } render() { console.log(this.props) if(this.props.smallerView){ return ( <div className="box"> <i className="fa fa-shopping-cart fa-2x"></i> <div className="count">{this.state.count}</div> </div> ) } else { return ( <div className="full-view"> <h1>Total Items: {this.props.updateState.count}</h1> <table> <tr> <th>Name</th> <th>Price</th> </tr> { this.props.updateState.products? this.props.updateState.products.map((product) => { return ( <tr> <td>{product.name}</td> <td>{product.price}</td> </tr> ) }) : null } </table> </div> ) } } } export default Cart;<file_sep>/lab9_src/App.js import React from 'react'; import './App.css'; import Header from './Components/Header/header'; import Shop from './Components/Shop/shop'; import Admin from './Components/Admin/admin'; import Cart from './Components/Cart/cart'; let state = {}; class App extends React.Component { constructor(){ super(); this.state = { cartOnly : false, save : [] } this.data = null; this.cartOnly = this.cartOnly.bind(this); this.saveStates = this.saveStates.bind(this); } saveStates(data){ this.setState({ save : data }) } componentDidUpdate(){ console.log(this.state); } cartOnly(){ this.setState({ cartOnly : true }) } render(){ if(!this.state.cartOnly){ return ( <div> <Header /> <Shop changeView={this.cartOnly} sendStates = {this.saveStates}/> </div> ); } else { return ( <div> <Header /> <Cart smallView={true} updateState={this.state.save} /> </div> ) } } } export default App;
c7e4743ea2dae9624a055c75fad6f9f7ed0218da
[ "JavaScript" ]
7
JavaScript
oahmadseecs/Advanced-Programming-Labs
f32a8b8458d0c87b5707b2a2f4e52e1c2bf7f83a
0758f508225fb3dd6456428f8314e59aa13aec81
refs/heads/master
<file_sep>print "new" print "HI"
be052f9b2e9f701838d42c30efb7d2bb9842a13d
[ "Python" ]
1
Python
Flap-Py/branchcheck
40c98aef875cd63881d306da4b9a7c277a2cb244
2a10fa82667c322a03693595c9c7c2dbd6d69928
refs/heads/master
<repo_name>tchoblond59/MSRollerShutter<file_sep>/Shutter.cpp #include "Shutter.h" #include <EEPROM.h> #include <core/MySensorsCore.h> Shutter::Shutter() { } Shutter::~Shutter() { } void Shutter::init() { // Set relay pins in output mode // Make sure relays are off when starting up digitalWrite(SHUTTER_POWER_PIN, RELAY_OFF); pinMode(SHUTTER_POWER_PIN, OUTPUT); digitalWrite(SHUTTER_UPDOWN_PIN, RELAY_OFF); pinMode(SHUTTER_UPDOWN_PIN, OUTPUT); pinMode(DEBUG_LED, OUTPUT); digitalWrite(DEBUG_LED, LOW); m_oneWire = new OneWire(DS18B20_PIN); m_ds18b20.setOneWire(m_oneWire); m_current_position = readEeprom(EEPROM_POSITION); m_last_position = m_current_position; m_travel_time_up = readEeprom(EEPROM_TRAVELUP); m_travel_time_down = readEeprom(EEPROM_TRAVELDOWN); m_state = RollerState::STOPPED; m_calibration = false; m_last_move = millis(); last_update_temperature = m_last_move; m_last_send = m_last_move; m_last_refresh_position = m_last_send; m_hilinkTemperature = 0; m_percent_target = -1; m_analog_read = 0; debug(); sendSketchInfo(NODE_NAME, RELEASE); present(CHILD_ID_ROLLERSHUTTER, S_DIMMER ); } void Shutter::open() { //stop(); delay(25); m_state = RollerState::ACTIVE_UP; touchLastMove(); // 0=RELAY_UP, 1= RELAY_DOWN digitalWrite(SHUTTER_UPDOWN_PIN, RELAY_UP); // Power ON motor digitalWrite(SHUTTER_POWER_PIN, RELAY_ON); digitalWrite(DEBUG_LED, HIGH); } void Shutter::close() { //stop(); delay(25); m_state = RollerState::ACTIVE_DOWN; touchLastMove(); // 0=RELAY_UP, 1= RELAY_DOWN digitalWrite(SHUTTER_UPDOWN_PIN, RELAY_DOWN); // Power ON motor digitalWrite(SHUTTER_POWER_PIN, RELAY_ON); digitalWrite(DEBUG_LED, HIGH); } void Shutter::stop() { // Power OFF motor digitalWrite(SHUTTER_POWER_PIN, RELAY_OFF); // Power OFF UPDOWN relay so we dont consume current digitalWrite(SHUTTER_UPDOWN_PIN, RELAY_OFF); digitalWrite(DEBUG_LED, LOW); m_state = RollerState::STOPPED; Serial.println("Motor Stopped"); m_last_position = m_current_position; writeEeprom(EEPROM_POSITION, m_last_position); MyMessage msgShutterPosition(CHILD_ID_ROLLERSHUTTER, V_PERCENTAGE); // Message for % shutter msgShutterPosition.set(m_current_position); send(msgShutterPosition); } void Shutter::update() { if (m_calibration)//Calibration in progress shutter is opening { if (isTimeout()) { m_calibration = false; stop(); } if (m_state == RollerState::UP)//Wait for shutter to be completely open { m_travel_time_up = millis() - m_last_move; close(); } else if (m_state == RollerState::DOWN)//Wait for close { m_travel_time_down = millis() - m_last_move; stop(); m_calibration = false; storeTravelTime(); } } else if(m_state == RollerState::ACTIVE_DOWN || m_state == RollerState::ACTIVE_UP) { mesureCurrent(); Serial.print("Analog read: "); Serial.println(m_analog_read); calculatePercent(); checkPosition(); if (millis() - m_last_send >= REFRESH_POSITION_TIMEOUT) { m_last_send = millis(); sendShutterPosition(); } } if(millis() - m_last_refresh_position > AUTO_REFRESH) { m_last_refresh_position = millis(); sendShutterPosition(); } refreshTemperature(); } void Shutter::endStop() { if (m_state == RollerState::ACTIVE_DOWN) { m_state = RollerState::DOWN; m_current_position = 100; //100% is completely down } else if (m_state == RollerState::ACTIVE_UP) { m_state = RollerState::UP; m_current_position = 0; //0% is completely closed } } void Shutter::calibration() { m_calibration = true; open(); } void Shutter::setTravelTimeDown(unsigned long time) { m_travel_time_down = time; } void Shutter::setTravelTimeUp(unsigned long time) { m_travel_time_up = time; } void Shutter::setPercent(int percent) { m_percent_target = percent; if (m_percent_target < m_current_position) { open(); } else if(m_percent_target > m_current_position) { close(); } } int Shutter::getState() { return m_state; } int Shutter::getPosition() { return m_current_position; } void Shutter::debug() { Serial.println(F("========= Node EEprom loading ==========")); Serial.print("Current Position : "); Serial.println(m_current_position); Serial.print("Up Traveltime Ref : "); Serial.println(m_travel_time_up); Serial.print("Down Traveltime Ref : "); Serial.println(m_travel_time_down); Serial.print("Timeout Traveltime Ref : "); Serial.println(CALIBRATION_TIMEOUT); Serial.print("Traveltime now "); Serial.println(getCurrentTravelTime()); Serial.print("Traveltime up % "); Serial.println(getCurrentTravelTime() * 100 / m_travel_time_up); Serial.print("Traveltime down % "); Serial.println(getCurrentTravelTime() * 100 / m_travel_time_up); Serial.print("Last position"); Serial.println(m_last_position); Serial.println(F("========================================")); } void Shutter::writeEeprom(uint16_t pos, uint16_t value) { // function for saving the values to the internal EEPROM // value = the value to be stored (as int) // pos = the first byte position to store the value in // only two bytes can be stored with this function (max 32.767) EEPROM.update(pos, ((uint16_t)value >> 8)); pos++; EEPROM.update(pos, (value & 0xff)); } uint16_t Shutter::readEeprom(uint16_t pos) { // function for reading the values from the internal EEPROM // pos = the first byte position to read the value from uint16_t hiByte; uint16_t loByte; hiByte = EEPROM.read(pos) << 8; pos++; loByte = EEPROM.read(pos); return (hiByte | loByte); } void Shutter::refreshTemperature() { if (millis() - last_update_temperature > 30000) { last_update_temperature = millis(); float oldTemp = m_hilinkTemperature; m_ds18b20.requestTemperatures(); m_hilinkTemperature = m_ds18b20.getTempCByIndex(0); // Check if reading was successful if (m_hilinkTemperature != DEVICE_DISCONNECTED_C) { Serial.println("READ TEMPERATURE"); if (abs(m_hilinkTemperature - oldTemp) >= TEMP_TRANSMIT_THRESHOLD) { sendTemperature(); } } else { Serial.println("Error: Could not read temperature data"); } } } void Shutter::sendTemperature() { MyMessage msgTemperature(CHILD_ID_TEMPERATURE, V_TEMP); // Message for onboard hilink temperature msgTemperature.set(m_hilinkTemperature, 2); send(msgTemperature); } void Shutter::touchLastMove() { m_last_move = millis(); } void Shutter::storeTravelTime() { writeEeprom(EEPROM_TRAVELDOWN, m_travel_time_down); writeEeprom(EEPROM_TRAVELUP, m_travel_time_up); } unsigned long Shutter::getCurrentTravelTime() { return millis() - m_last_move; } uint16_t Shutter::calculatePercent() { if (m_state == RollerState::ACTIVE_UP) { m_current_position = m_last_position - getCurrentTravelTime() * 100 / m_travel_time_up; //Serial.println("CALCUL OUVERTURE EN COURS"); //Serial.println(m_current_position); } else if (m_state == RollerState::ACTIVE_DOWN) { m_current_position = m_last_position + getCurrentTravelTime() * 100 / m_travel_time_down; //Serial.println("CALCUL FERMETURE EN COURS"); //Serial.println(m_current_position); } return m_current_position; } void Shutter::checkPosition() { if (m_current_position <= 0 && m_state == RollerState::ACTIVE_UP) { Serial.println("POSITION OUVERTE ATTEINTE"); stop(); m_state == RollerState::UP; m_current_position = 0; m_last_position = m_current_position; } else if(m_current_position >= 100 && m_state == RollerState::ACTIVE_DOWN) { Serial.println("POSITION FERMEE ATTEINTE"); stop(); m_state == RollerState::DOWN; m_current_position = 100; m_last_position = m_current_position; } else if (m_percent_target != -1)//User wants precise position { if (m_state == RollerState::ACTIVE_UP && m_current_position <= m_percent_target) { stop(); m_state == RollerState::STOPPED; m_last_position = m_current_position; m_percent_target = -1; } else if (m_state == RollerState::ACTIVE_DOWN && m_current_position >= m_percent_target) { stop(); m_state == RollerState::STOPPED; m_last_position = m_current_position; m_percent_target = -1; } } } bool Shutter::isTimeout() { if (getCurrentTravelTime() > CALIBRATION_TIMEOUT) return true; else return false; } void Shutter::mesureCurrent() { m_analog_read = analogRead(ACS712_SENSOR); } void Shutter::sendShutterPosition() { MyMessage msgShutterPosition(CHILD_ID_ROLLERSHUTTER, V_PERCENTAGE); // Message for % shutter msgShutterPosition.set(getPosition()); send(msgShutterPosition); } <file_sep>/README.md # MSRollerShutter This is based on [scalz](https://github.com/scalz/MySensors-HW/tree/development/RollerShutterNode) work. This is the software of the hardware node. You can find the front end code for [LaraHome](https://github.com/tchoblond59/LaraHome) -> [here](https://github.com/tchoblond59/SSRollerShutter) For the moment you have to calibrate your node by manually trigger the end stop. It will store the travel time down and up. Then you can set the position in percent. Your shutter has to be closed when you launch calibration <file_sep>/Shutter.h #ifndef Shutter_h #define Shutter_h #include <Arduino.h> #include "MyNodeDefinition.h" //#include <C:\Users\julie\OneDrive\Documents\Arduino\libraries\MySensors\core\MySensorsCore.h> //If someone can explain me why i have to do this shit... #include <OneWire.h> #include <DallasTemperature.h> //#include <timer.h> // ********************* PIN/RELAYS DEFINES ******************************************* #define SHUTTER_UPDOWN_PIN A1 // Default pin for relay SPDT, you can change it with : initShutter(SHUTTER_POWER_PIN, SHUTTER_UPDOWN_PIN) #define SHUTTER_POWER_PIN A2 // Default pin for relay SPST : Normally open, power off rollershutter motor #define RELAY_ON 1 // ON state for power relay #define RELAY_OFF 0 #define RELAY_UP 0 // UP state for UPDOWN relay #define RELAY_DOWN 1 // UP state for UPDOWN relay // ********************* EEPROM DEFINES ********************************************** #define EEPROM_OFFSET_SKETCH 512 // Address start where we store our data (before is mysensors stuff) #define EEPROM_POSITION EEPROM_OFFSET_SKETCH // Address of shutter last position #define EEPROM_TRAVELUP EEPROM_POSITION+2 // Address of travel time for Up. 16bit value #define EEPROM_TRAVELDOWN EEPROM_POSITION+4 // Address of travel time for Down. 16bit value // ********************* CALIBRATION DEFINES ***************************************** #define START_POSITION 0 // Shutter start position in % if no parameter in memory #define TRAVELTIME_UP 40000 // in ms, time measured between 0-100% for Up. it's initialization value. if autocalibration used, these will be overriden #define TRAVELTIME_DOWN 40000 // in ms, time measured between 0-100% for Down #define TRAVELTIME_ERRORMS 1000 // in ms, max ms of error during travel, before reporting it as an error #define CALIBRATION_SAMPLES 1 // nb of round during calibration, then average #define CALIBRATION_TIMEOUT 55000 // in ms, timeout between 0 to 100% or vice versa, during calibration #define REFRESH_POSITION_TIMEOUT 2000 // in ms time between each send of position when moving #define AUTO_REFRESH 1800000 //in ms time between each send of position when its not moving keep high value. enum RollerState { STOPPED, UP, DOWN, ACTIVE_UP, ACTIVE_DOWN }; class Shutter { public: Shutter(); ~Shutter(); void init(); void open(); void close(); void stop(); void update(); void endStop(); void calibration(); void setTravelTimeDown(unsigned long time); void setTravelTimeUp(unsigned long time); void setPercent(int percent); int getState(); int getPosition(); void debug(); void writeEeprom(uint16_t pos, uint16_t value); uint16_t readEeprom(uint16_t pos); void refreshTemperature(); void sendTemperature(); void sendShutterPosition(); private: uint8_t m_state; uint16_t m_travel_time_up; uint16_t m_travel_time_down; int m_current_position; int m_last_position; bool m_calibration; unsigned long m_last_move;//Store last time shutter move in ms unsigned long m_last_send;//Store last time shutter move in ms unsigned long m_last_refresh_position;//Store last time we send the shutter position DallasTemperature m_ds18b20; OneWire *m_oneWire; float m_hilinkTemperature; unsigned long last_update_temperature; int m_percent_target; int m_analog_read; void touchLastMove(); void storeTravelTime(); unsigned long getCurrentTravelTime(); uint16_t calculatePercent(); void checkPosition(); bool isTimeout(); void mesureCurrent(); }; #endif <file_sep>/RollerShutter.ino #include "Shutter.h" #include "MyNodeDefinition.h" #include <SPI.h> #include <MySensors.h> Shutter rollerShutter; // the setup function runs once when you press reset or power the board void setup() { rollerShutter.init(); rollerShutter.sendShutterPosition(); } // the loop function runs over and over again until power down or reset void loop() { rollerShutter.update(); } /* ====================================================================== Function: receive Purpose : Mysensors incomming message Comments: ====================================================================== */ void receive(const MyMessage &message) { if (message.isAck()) {} else { // Message received : Open shutters if (message.type == V_UP && message.sensor == CHILD_ID_ROLLERSHUTTER) { Serial.println("V_UP"); rollerShutter.open(); } // Message received : Close shutters if (message.type == V_DOWN && message.sensor == CHILD_ID_ROLLERSHUTTER) { Serial.println("V_DOWN"); rollerShutter.close(); } // Message received : Stop shutters motor if (message.type == V_STOP && message.sensor == CHILD_ID_ROLLERSHUTTER) { Serial.println("V_STOP"); rollerShutter.stop(); } // Message received : Set position of Rollershutter if (message.type == V_PERCENTAGE && message.sensor == CHILD_ID_ROLLERSHUTTER) { Serial.print("SET PERCENT: "); Serial.println(message.getInt()); rollerShutter.setPercent(message.getInt()); } // Message received : Set position of Rollershutter if (message.type == V_DIMMER && message.sensor == CHILD_ID_PERCENT) { } // Message received : Calibration requested if (message.type == V_STATUS && message.sensor == CHILD_ID_AUTOCALIBRATION) { Serial.println("CALIBRATION"); rollerShutter.calibration(); } // Message received : Endstop command received if (message.type == V_STATUS && message.sensor == CHILD_ID_ENDSTOP) { Serial.println("ENDSTOP"); rollerShutter.endStop(); } // Message received : temperature command received if (message.type == V_TEMP && message.sensor == CHILD_ID_TEMPERATURE) { //Send Temperature } } }
e19dafb0eb4f282dab5a0644a02356a6cc2db15e
[ "Markdown", "C++" ]
4
C++
tchoblond59/MSRollerShutter
9d5047f65d3ef97e4285f4bffa1394a42c84638f
58d5d93505bfba5809c659bdf7ba775f69b8f706
refs/heads/master
<file_sep>#!/usr/bin/env node const chalk = require('chalk'); const semver = require('semver'); const nodeVersion = require('../package.json').engines.node; function checkNodeVersion (wanted, id) { if (!semver.satisfies(process.version, wanted)) { console.log(chalk.red( 'You are using Node ' + process.version + ', but this version of ' + id + ' requires Node ' + wanted + '.\nPlease upgrade your Node version.' )); process.exit(1); } } checkNodeVersion(nodeVersion, 'yty-cli'); const program = require('commander'); program .version(require('../package').version, '-v, --version') .usage('[options]') .option('-i, --init', '初始化项目文件夹') program.on('--help', function () { console.log(' Examples:') console.log() console.log(chalk.gray(' # create a new project with an official template')) console.log(' $ yty-cli --init') console.log(' $ yty-cli -i') console.log() }) program.parse(process.argv) if (program.init) { require('../src/init')() } <file_sep>const { logWithSpinner, stopSpinner } = require('../src/util/spinner') const { error, clearConsole, log } = require('../src/util/logger') const { fetchRemoteTemplate, copyTemplate } = require('../src/util/loadFile') const path = require('path') const inquirer = require('inquirer') const validateProjectName = require('validate-npm-package-name') const fs = require('fs') const fse = require('fs-extra') const child_process = require('child_process') const chalk = require('chalk') async function init () { const { project } = await inquirer.prompt([ { name: 'project', message: 'please enter the project name', default: 'my-project' } ]) const { tpl } = await inquirer.prompt([ { name: 'tpl', type: 'list', message: 'please select a project template', choices: [ { name: 'gulp-simple', value: 'gulp-simple' }, { name: 'vue-webpack', value: 'vue-webpack' }, { name: 'react-webpack', value: 'react-webpack' } ] } ]) const cwd = process.cwd() const targetDir = path.resolve(cwd, project) const result = validateProjectName(project) if (!result.validForNewPackages) { console.error(chalk.red(`Invalid project name: "${project}"`)) result.errors && result.errors.forEach(err => { console.error(chalk.red(err)) }) process.exit(1) } if (fs.existsSync(targetDir)) { const { ok } = await inquirer.prompt([ { name: 'ok', type: 'confirm', message: `${project} already exists. Are you sure to cover it?` } ]) if (!ok) { return } else { logWithSpinner('delete the old project dir') await fse.remove(targetDir) stopSpinner() } } // await clearConsole() logWithSpinner('create the new project dir') await fse.mkdir(targetDir) stopSpinner() logWithSpinner('download remote templete') await fetchRemoteTemplate() stopSpinner() logWithSpinner('create project file') await copyTemplate(tpl, targetDir) stopSpinner() // await child_process.execSync('cd ' + project) log(chalk.green('✔') + ' the project initialization is complete.') process.exit(1) } module.exports = () => { return init().catch(err => { stopSpinner(false) error(err) process.exit(1) }) } <file_sep># my-cli custom fe staging ### 目的 学习本地命令行对远程项目的控制,目前只是简单的脚手架,只有单纯的初始化、拷贝模板功能。 ### 参考文档 - [我想写一个前端开发工具](https://www.cnblogs.com/webARM/p/6505683.html) - [vue-cli](https://github.com/vuejs/vue-cli) ### 分析流程 - 命令行参数获取 在命令行中能获取的首要信息就是 process.argv, 所以要根据参数的不同进行相应的操作,那么就用到了 [commander](https://www.npmjs.com/package/commander) 的命令行接口,其中的option 接口可以捕获到命令行的参数,来进行相应的操作。 eg: ``` const program = require('commander'); program .version(require('../package').version, '-v, --version') .usage('[options]') .option('-i, --init', '初始化项目文件夹') .parse(process.argv) // 如果是init则进行初始化的操作 if (program.init) { require('../src/init')() } ``` - 自动化配置 如果把所有参数都放在一行命令上,那么就太麻烦了,参数只是用作入口,具体一点的当然还是希望自己控制,那么就要支持输入、选择等可操作的功能,然后就是[inquirer](https://www.npmjs.com/package/inquirer)登场,它的作用就是提醒使用者一步一步的配置项目,比如最基础的我想给项目起一个名字,eg: ``` const { project } = await inquirer.prompt([ { name: 'project', message: 'please enter the project name', default: 'my-project' } ]) console.log(project) // my-project ``` 可以自己输入,也会有默认的项目名称。随着前端框架、编译工具的不断增加,可选择的越来越多,这种自动化配置显得越来越重要。 - 拉取模板 配置完成之后,要根据配置生成对应的模板,前提是会有一个基础的模板,在基础的模板上进行工具的选择,配置文件可以生成到本地保存,下来,配置项目的时候在进行读取,我这里只介绍把远程模板拉取到本地,以后或许会增加配置的node文件,由于我的模板是放在git仓库中的,所以可以使用[download-git-repo](https://www.npmjs.com/package/download-git-repo)把远程的模板拉取到本地,eg: ``` const path = require('path') const os = require('os') const download = require('download-git-repo') const tmpdir = path.join(os.tmpdir(), 'my-cli') //获取系统临时文件存放地址,并且加上我们自己的文件名称,用于管理 download('git项目', tmpdir, err => { if (err) return reject(err) resolve() }) ``` 这里只是拉取到临时文件夹下,可以再对文件进行相应的操作,然后拷贝到自己的项目下,就完成了本地项目的构建。 ### 总结 - 比较困难的就两个吧,第一个就是通过命令行获取配置文件,就是上面的步骤,第二个就是把配置文件应用到你的基础模板上,这也是暂时没有做到的,以后会慢慢实现。
9e3cb97ef9bb7a58312a4bcc9b37b82687ceb5d7
[ "JavaScript", "Markdown" ]
3
JavaScript
huochezaodian/my-cli
1a3b5e6e40c61e068e5412ccba3197fd94fad0d6
7ec936e10aa84ef8898c2f53184a8c4b9b8f1afd
refs/heads/main
<repo_name>vtamara/rails7a2_importmap<file_sep>/test/system/publicaciones_test.rb require "application_system_test_case" class PublicacionesTest < ApplicationSystemTestCase setup do @publicacion = publicaciones(:one) end test "visiting the index" do visit publicaciones_url assert_selector "h1", text: "Publicaciones" end test "should create Publicacion" do visit publicaciones_url click_on "New Publicacion" fill_in "Contenido", with: @publicacion.contenido fill_in "Titulo", with: @publicacion.titulo click_on "Create Publicacion" assert_text "Publicacion was successfully created" click_on "Back" end test "should update Publicacion" do visit publicaciones_url click_on "Edit", match: :first fill_in "Contenido", with: @publicacion.contenido fill_in "Titulo", with: @publicacion.titulo click_on "Update Publicacion" assert_text "Publicacion was successfully updated" click_on "Back" end test "should destroy Publicacion" do visit publicaciones_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Publicacion was successfully destroyed" end end <file_sep>/test/controllers/publicaciones_controller_test.rb require "test_helper" class PublicacionesControllerTest < ActionDispatch::IntegrationTest setup do @publicacion = publicaciones(:one) end test "should get index" do get publicaciones_url assert_response :success end test "should get new" do get new_publicacion_url assert_response :success end test "should create publicacion" do assert_difference("Publicacion.count") do post publicaciones_url, params: { publicacion: { contenido: @publicacion.contenido, titulo: @publicacion.titulo } } end assert_redirected_to publicacion_url(Publicacion.last) end test "should show publicacion" do get publicacion_url(@publicacion) assert_response :success end test "should get edit" do get edit_publicacion_url(@publicacion) assert_response :success end test "should update publicacion" do patch publicacion_url(@publicacion), params: { publicacion: { contenido: @publicacion.contenido, titulo: @publicacion.titulo } } assert_redirected_to publicacion_url(@publicacion) end test "should destroy publicacion" do assert_difference("Publicacion.count", -1) do delete publicacion_url(@publicacion) end assert_redirected_to publicaciones_url end end <file_sep>/app/views/publicaciones/index.json.jbuilder json.array! @publicaciones, partial: "publicaciones/publicacion", as: :publicacion <file_sep>/app/controllers/publicaciones_controller.rb class PublicacionesController < ApplicationController before_action :set_publicacion, only: %i[ show edit update destroy ] # GET /publicaciones or /publicaciones.json def index @publicaciones = Publicacion.all end # GET /publicaciones/1 or /publicaciones/1.json def show end # GET /publicaciones/new def new @publicacion = Publicacion.new end # GET /publicaciones/1/edit def edit end # POST /publicaciones or /publicaciones.json def create @publicacion = Publicacion.new(publicacion_params) respond_to do |format| if @publicacion.save format.html { redirect_to @publicacion, notice: "Publicacion was successfully created." } format.json { render :show, status: :created, location: @publicacion } else format.html { render :new, status: :unprocessable_entity } format.json { render json: @publicacion.errors, status: :unprocessable_entity } end end end # PATCH/PUT /publicaciones/1 or /publicaciones/1.json def update respond_to do |format| if @publicacion.update(publicacion_params) format.html { redirect_to @publicacion, notice: "Publicacion was successfully updated." } format.json { render :show, status: :ok, location: @publicacion } else format.html { render :edit, status: :unprocessable_entity } format.json { render json: @publicacion.errors, status: :unprocessable_entity } end end end # DELETE /publicaciones/1 or /publicaciones/1.json def destroy @publicacion.destroy respond_to do |format| format.html { redirect_to publicaciones_url, notice: "Publicacion was successfully destroyed." } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_publicacion @publicacion = Publicacion.find(params[:id]) end # Only allow a list of trusted parameters through. def publicacion_params params.require(:publicacion).permit(:titulo, :contenido) end end <file_sep>/app/javascript/componentes/componente_vue.js import Vue from "vue" new Vue ({ el: '#ap-4', data: { porhacer: [ { text: 'Aprende Javascript'}, { text: 'Aprende Vue'}, { text: 'Crea algo fenomenal'} ] } }) new Vue ({ el: '#ap-5', data: { mensaje: 'Hola Vue.js!', }, methods: { invertirMensaje: function () { this.mensaje = this.mensaje.split('').reverse().join('') } } }) <file_sep>/config/importmap.rb # Pin npm packages by running ./bin/importmap pin "application", preload: true pin "@hotwired/turbo-rails", to: "turbo.js" pin "@hotwired/stimulus", to: "stimulus.js" pin "@hotwired/stimulus-loading", to: "stimulus-loading.js" pin_all_from "app/javascript/controllers", under: "controllers" pin "trix" pin "@rails/actiontext", to: "actiontext.js" pin 'md5', to: 'https://cdn.skypack.dev/md5' pin 'vue', to: 'https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.esm.browser.js' pin_all_from 'app/javascript/componentes', under: 'componentes' pin 'd3', to: 'https://esm.sh/d3?bundle' pin "react", to: "https://ga.jspm.io/npm:react@17.0.2/index.js" pin "object-assign", to: "https://ga.jspm.io/npm:object-assign@4.1.1/index.js" pin "react-dom", to: "https://ga.jspm.io/npm:react-dom@17.0.2/index.js" pin "scheduler", to: "https://ga.jspm.io/npm:scheduler@0.20.2/index.js" <file_sep>/app/models/publicacion.rb class Publicacion < ApplicationRecord has_rich_text :contenido end <file_sep>/app/views/publicaciones/_publicacion.json.jbuilder json.extract! publicacion, :id, :titulo, :contenido, :created_at, :updated_at json.url publicacion_url(publicacion, format: :json) <file_sep>/app/views/publicaciones/show.json.jbuilder json.partial! "publicaciones/publicacion", publicacion: @publicacion <file_sep>/app/javascript/componentes/componente_d3.js import {select,zoom} from "d3" const datos = { vertices: [ {id: 1, x: 100, y: 50}, {id: 2, x: 50, y: 100}, {id: 3, x: 150, y: 100} ], arcos: [ {fuente: 1, destino: 2}, {fuente: 1, destino: 3} ] }; var svg = select('svg'); var g = svg.append('g') const manejaAcercamiento = function (e) { g.attr('transform', e.transform); } const acercamiento = zoom().on('zoom', manejaAcercamiento); select('svg').call(acercamiento); const arcos = datos.arcos.map(l=> { const fuente = datos.vertices.find(n => n.id === l.fuente); const destino = datos.vertices.find(n => n.id === l.destino); return {fuente, destino}; }) g.selectAll('line.link') .data(arcos, d => `${d.fuente.id}-${d.destino.id}`) .enter() .append('line') .classed('link', true) .attr('x1', d => d.fuente.x) .attr('x2', d => d.destino.x) .attr('y1', d => d.fuente.y) .attr('y2', d => d.destino.y) .style('stroke', 'black'); const vertices = g.selectAll('g.node') .data(datos.vertices, d => d.id) .enter() .append('g') .classed('node', true) .attr('transform', d => `translate(${d.x}, ${d.y})`); vertices.append('circle') .attr('r', 10) .style('fill', 'blue'); <file_sep>/README.md #!/bin/sh # Ejemplo de uso de importmap en rails 7.0.0.alpha con base en https://www.youtube.com/watch?v=PtxZvFnL2i0 # Este archivo es también script para el interprete de ordenes en adJ # 1. Instalación y configuración inicial de publicaciones rails -v #Rails 7.0.0.alpha2 rm -rf rails7a2_importmap rails new rails7a2_importmap cd rails7a2_importmap cat >> config/initializers/inflections.rb <<FDA ActiveSupport::Inflector.inflections do |i| i.irregular "publicacion", "publicaciones" end FDA bin/rails g scaffold publicacion titulo:string contenido:text bin/rails db:migrate ed app/views/publicaciones/_form.html.erb <<FDA ,s/prohibited this publicacion from being saved:/no permite(n) guardar esta publicación/g w q FDA ed app/views/publicaciones/_publicacion.html.erb <<FDA ,s/Show this publicacion/Resumen de esta publicación/g w q FDA ed app/views/publicaciones/edit.html.erb <<FDA ,s/Editing/Edición de/g ,s/Show this publicacion/Resumen de esta publicación/g ,s/Back to publicaciones/Regresar al listado de publicaciones/g w q FDA ed app/views/publicaciones/index.html.erb <<FDA ,s/New publicacion/Nueva publicación/g ,s/Publicacion/Publicación/g w q FDA ed app/views/publicaciones/new.html.erb <<FDA ,s/New publicacion/Nueva publicación/g ,s/Back to publicaciones/Regresar al listado de publicaciones/g w q FDA ed app/views/publicaciones/show.html.erb <<FDA ,s/Edit this publicacion/Editar esta publicación/g ,s/Back to publicaciones/Regresar al listado de publicaciones/g ,s/Destroy this publicacion/Eliminar esta publicación/g w q FDA ed config/application.rb <<FDA /end i config.hosts << "rbd.nocheyniebla.org" . w q FDA #bin/rails s -p3500 -b 192.168.177.45 # 2. Enriquecer contenido de una publicación bin/rails action_text:install bin/rails db:migrate cat >> config/importmap.rb <<FDA pin "trix" pin "@rails/actiontext", to: "actiontext.js" FDA ed app/models/publicacion.rb <<FDA /end i has_rich_text :contenido . w q FDA ed app/views/publicaciones/_form.html.erb <<FDA ,s/form.text_area :contenido/form.rich_text_area :contenido/g w q FDA cat >> app/javascript/application.js <<FDA import 'trix' import '@rails/actiontext' FDA doas ln -s /usr/local/lib/libglib-2.0.so.4201.5 /usr/local/lib/libglib-2.0.so.0 doas ln -s /usr/local/lib/libgobject-2.0.so.4200.12 /usr/local/lib/libgobject-2.0.so.0 doas pkg_add libvips doas ln -s /usr/local/lib/libvips.so.0.0 /usr/local/lib/libvips.so.42 #bin/rails s -p3500 -b 192.168.177.45 # 3. Usando un paquete javascript simple: md5 echo "pin 'md5', to: 'https://cdn.skypack.dev/md5'" >> config/importmap.rb mkdir app/javascript/controllers/utilidades cat > app/javascript/controllers/utilidades/md5_controller.js <<FDA import { Controller } from "@hotwired/stimulus" import md5 from 'md5' export default class extends Controller { convert(event) { event.preventDefault() event.target.textContent = md5(event.target.textContent) } } FDA cat >> app/views/publicaciones/index.html.erb <<FDA <div data-controller="utilidades--md5"> <%= link_to "Hash this!", "#", "data-action": "utilidades--md5#convertir" %> </div> FDA #bin/rails s -p3500 -b 192.168.177.45 # 4. Incrustar un componente vue echo "pin 'vue', to: 'https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.esm.browser.js'" >> config/importmap.rb mkdir app/javascript/componentes echo "pin_all_from 'app/javascript/componentes', under: 'componentes'" >> config/importmap.rb cat > app/javascript/componentes/componente_vue.js <<FDA import Vue from "vue" new Vue ({ el: '#ap-4', data: { porhacer: [ { text: 'Aprende Javascript'}, { text: 'Aprende Vue'}, { text: 'Crea algo fenomenal'} ] } }) new Vue ({ el: '#ap-5', data: { mensaje: 'Hola Vue.js!', }, methods: { invierteMensaje: function () { this.mensaje = this.mensaje.split('').reverse().join('') } } }) FDA echo "import \"componentes/componente_vue\"" >> app/javascript/application.js cat >> app/views/publicaciones/index.html.erb <<FDA <div id="ap-4"> <ol> <li v-for="hacer in porhacer"> {{ hacer.text }} </li> </ol> </div> <div id="ap-5"> <p>{{ mensaje }}</p> <button v-on:click="invertirMensaje">Invertir Mensaje</button> </div> FDA #bin/rails s -p3500 -b 192.168.177.45 # 5. Incrustar un componente d3 echo "pin 'd3', to: 'https://esm.sh/d3?bundle'" >> config/importmap.rb cat > app/javascript/componentes/componente_d3.js <<FDA import {select,zoom} from "d3" const datos = { vertices: [ {id: 1, x: 100, y: 50}, {id: 2, x: 50, y: 100}, {id: 3, x: 150, y: 100} ], arcos: [ {fuente: 1, destino: 2}, {fuente: 1, destino: 3} ] }; var svg = select('svg'); var g = svg.append('g') const manejaAcercamiento = function (e) { g.attr('transform', e.transform); } const acercamiento = zoom().on('zoom', manejaAcercamiento); select('svg').call(acercamiento); const arcos = datos.arcos.map(l=> { const fuente = datos.vertices.find(n => n.id === l.fuente); const destino = datos.vertices.find(n => n.id === l.destino); return {fuente, destino}; }) g.selectAll('line.link') .data(arcos, d => \`\${d.fuente.id}-\${d.destino.id}\`) .enter() .append('line') .classed('link', true) .attr('x1', d => d.fuente.x) .attr('x2', d => d.destino.x) .attr('y1', d => d.fuente.y) .attr('y2', d => d.destino.y) .style('stroke', 'black'); const vertices = g.selectAll('g.node') .data(datos.vertices, d => d.id) .enter() .append('g') .classed('node', true) .attr('transform', d => \`translate(\${d.x}, \${d.y})\`); vertices.append('circle') .attr('r', 10) .style('fill', 'blue'); FDA echo "import \"componentes/componente_d3\"" >> app/javascript/application.js cat >> app/views/publicaciones/index.html.erb <<FDA <svg width='300' height='200'></svg> FDA #bin/rails s -p3500 -b 192.168.177.45 # 6. Incrustar un componente react sin JSX bin/importmap pin react react-dom cat > app/javascript/componentes/componente_react.js <<FDA import React from "react" import ReactDom from "react-dom" const e = React.createElement class Hola extends React.Component { render() { return e('div', null, \`Hola \${this.props.aQue}\`); } } ReactDom.render( e(Hola, { aQue: 'Mundo' }, null), document.getElementById('react') ) FDA bin/rails s -p3500 -b 192.168.177.45 echo "import \"componentes/componente_react\"" >> app/javascript/application.js cat >> app/views/publicaciones/index.html.erb <<FDA <div id="react"> </div> FDA
1ef1acc863488de24911df0167c7031fdcc51567
[ "JavaScript", "Ruby", "Shell" ]
11
Ruby
vtamara/rails7a2_importmap
f0d0f55f91369f631ec001d28912633d51a1a5b2
2529e9128dd0d74d7ad20a17b75766c85f6bb203
refs/heads/main
<file_sep>#include <stdio.h> #include <stdbool.h> void print_array(char * pre, int array[], int length) { printf("%s[ ", pre); for (int i = 0; i < length; i++) { if (i != length - 1) { printf("%d,", array[i]); } else { printf("%d ]\n", array[i]); } } } int main() { int length; printf("Length: "); scanf("%d", &length); int array[length]; for (int i = 0; i < length; i++) { printf("Item %d: ", i); scanf("%d", &array[i]); } print_array("Source array: ", array, length); bool loop = true; while (loop) { loop = false; for (int i = 0; i < length - 1; i++) { if (array[i] > array[i + 1]) { loop = true; int tmp = array[i]; array[i] = array[i + 1]; array[i + 1] = tmp; } } } print_array("Sorted array: ", array, length); return 0; }<file_sep> function equalDeepPartial(expectation, actual) { if (typeof expectation !== typeof actual) return false if (typeof expectation !== 'object') { if (typeof expectation === 'number' && expectation !== expectation) return actual !== actual return expectation === actual } if (typeof expectation !== 'object') return actual === actual if (!expectation || !actual) return expectation === actual if (Array.isArray(expectation) || Array.isArray(actual)) { if (Array.isArray(expectation) && Array.isArray(actual)) { const expectationCopy = [...expectation] const actualCopy = [...actual] for (let ie = 0; ie < expectationCopy.length; ie++) { let found = false for (let ia = 0; ia < actualCopy.length; ia++) { if (equalDeepPartial(expectationCopy[ie], actualCopy[ia])) { found = true actualCopy.splice(ia, 1) break } } if (!found) return false expectationCopy.splice(ie, 1) ie-- } return true } else { return false } } const expectationKeys = Object.keys(expectation) for (let i = 0; i < expectationKeys.length; i++) { const curKey = expectationKeys[i] if (!Object.prototype.hasOwnProperty.call(actual, curKey)) return false if (!equalDeepPartial(expectation[curKey], actual[curKey])) return false } return true } module.exports = equalDeepPartial<file_sep> def main(): length = int(input('Length: ')) array = [None] * length for i in range(length): array[i] = int(input('Item {}: '.format(i))) print('Source array: ', array) left = 0 right = length - 1 while left < right: for i in range(left, right, 1): if array[i] > array[i + 1]: array[i], array[i + 1] = array[i + 1], array[i] right -= 1 for i in range(right, left, -1): if (array[i] < array[i - 1]): array[i], array[i - 1] = array[i - 1], array[i] left += 1 print('Sorted array: ', array) if __name__ == "__main__": main()<file_sep> function equalDeep(obj1, obj2) { if (typeof obj1 !== typeof obj2) return false if (typeof obj1 === 'number' && obj1 !== obj1)//NaN return obj2 !== obj2 if (typeof obj1 !== 'object') return obj1 === obj2 if (Array.isArray(obj1) || Array.isArray(obj2)) { if (Array.isArray(obj1) && Array.isArray(obj2)) { if (obj1.length !== obj2.length) return false for (let i = 0; i < obj1.length; i++) if (!equalDeep(obj1[i], obj2[i])) return false return true } else { return false } } if (!obj1 || !obj2)//null return obj1 === obj2 const ent1 = Object.entries(obj1) const ent2 = Object.entries(obj2) if (ent1.length !== ent2.length) return false for (let i1 = 0; i1 < ent1.length; i1++) { let found = false for (let i2 = 0; i2 < ent2.length; i2++) { if (ent1[i1][0] !== ent2[i2][0]) continue found = true if (!equalDeep(ent1[i1][1], ent2[i2][1])) return false ent2.splice(i2, 1) break } if (!found) return false } return true } module.exports = equalDeep<file_sep>#include <stdio.h> void print_array(char * pre, int array[], int length) { printf("%s[ ", pre); for (int i = 0; i < length; i++) { if (i != length - 1) { printf("%d,", array[i]); } else { printf("%d ]\n", array[i]); } } } int main() { int length; printf("Length: "); scanf("%d", &length); int array[length]; for (int i = 0; i < length; i++) { printf("Item %d: ", i); scanf("%d", &array[i]); } print_array("Source array: ", array, length); for (int i = 0; i < length; i++) { int key = array[i]; int j = i - 1; while (j >= 0 && array[j] > key) { array[j + 1] = array[j]; j = j - 1; } array[j + 1] = key; } print_array("Sorted array: ", array, length); return 0; }<file_sep> function inDotNotation(targetObject, propertyName = '') { let object = {...targetObject} if (propertyName) propertyName += '.' const entries = Object.entries(object) for (let i = 0; i < entries.length; i++) { if (entries[i][1] && typeof entries[i][1] === 'object' && !Array.isArray(entries[i][1])) { object = {...object, ...inDotNotation(entries[i][1], propertyName + entries[i][0])} delete object[entries[i][0]] } else if (propertyName) { object[propertyName + entries[i][0]] = entries[i][1] delete object[entries[i][0]] } } return object } <file_sep>import java.util.Arrays; import java.util.Scanner; class Shake { public static void main(String [] args) { Scanner in = new Scanner(System.in); System.out.print("Length: "); int length = in.nextInt(); int[] array = new int[length]; for (int i = 0; i < length; i++) { System.out.printf("Item %d: ", i); array[i] = in.nextInt(); } System.out.println("Source array " + Arrays.toString(array)); int left = 0; int right = length -1; do { for (int i = left; i < right; i++) { if (array[i] > array[i + 1]) { int tmp = array[i]; array[i] = array[i + 1]; array[i + 1] = tmp; } } right--; for (int i = right; left < i; i++) { if (array[i] < array[i -1]) { int tmp = array[i]; array[i] = array[i - 1]; array[i - 1] = tmp; } } left++; } while (left < right); System.out.println("Sorted array " + Arrays.toString(array)); in.close(); } }<file_sep> function copyPropertiesDeep(source, target) { for (const [key, value] of Object.entries(source)) { if (typeof value === 'object' && !Array.isArray(value)) { if (key in target) { if (typeof target[key] === 'object' && !Array.isArray(target[key])) { replaceDeep(source[key], target[key]) } else { target[key] = source[key] } } } else { target[key] = value } } return target } module.exports = copyPropertiesDeep<file_sep> def main(): length = int(input('Length: ')) array = [None] * length for i in range(length): array[i] = int(input('Item {}: '.format(i))) print('Source array: ', array) loop = True while loop: loop = False for i in range(length - 1): if (array[i] > array[i + 1]): loop = True array[i], array[i + 1] = array[i + 1], array[i] print('Sorted array: ', array) if __name__ == "__main__": main()<file_sep>import java.util.Arrays; import java.util.Scanner; class Bubble { public static void main(String [] args) { Scanner in = new Scanner(System.in); System.out.print("Length: "); int length = in.nextInt(); int[] array = new int[length]; for (int i = 0; i < length; i++) { System.out.printf("Item %d: ", i); array[i] = in.nextInt(); } System.out.println("Source array " + Arrays.toString(array)); boolean loop = true; while (loop) { loop = false; for (int i = 0; i < length - 1; i++) { if (array[i] > array[i + 1]) { loop = true; int tmp = array[i]; array[i] = array[i + 1]; array[i + 1] = tmp; } } } System.out.println("Sorted array " + Arrays.toString(array)); in.close(); } }<file_sep>#include <stdio.h> void print_array(char * pre, int array[], int length) { printf("%s[ ", pre); for (int i = 0; i < length; i++) { if (i != length - 1) { printf("%d,", array[i]); } else { printf("%d ]\n", array[i]); } } } int main() { int length; printf("Length: "); scanf("%d", &length); int array[length]; for (int i = 0; i < length; i++) { printf("Item %d: ", i); scanf("%d", &array[i]); } print_array("Source array: ", array, length); int left = 0; int right = length - 1; do { for (int i = left; i < right; i++) { if (array[i] > array[i + 1]) { int tmp = array[i]; array[i] = array[i + 1]; array[i + 1] = tmp; } } right--; for (int i = right; left < i; i--) { if (array[i] < array[i - 1]) { int tmp = array[i]; array[i] = array[i - 1]; array[i - 1] = tmp; } } left++; } while (left < right); print_array("Sorted array: ", array, length); return 0; }<file_sep> def main(): lenght = int(input('Lenght: ')) array = [None] * lenght for i in range(lenght): array[i] = int(input('Item {}: '.format(i))) print('Source array: ', array) for i in range(lenght): key = array[i] j = i - 1 while j >= 0 and array[j] > key: array[j + 1] = array[j] j = j - 1 array[j + 1] = key print('Sorted array: ', array) if __name__ == "__main__": main()
94b88c7c1f162e7f2c58cfe4c3ee97a75ceedb1d
[ "JavaScript", "C", "Python", "Java" ]
12
C
QuisEgoSum/different
8c9bf452b32f427db302100c6118a3b14a0c0657
a7dd60b29449f64e35f04e63c97a669ae9256170
refs/heads/main
<file_sep>const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN}); const helpers = require('../../../../../helpers/shared.js'); let nextTrack = await helpers.dequeueTrack(context.params.event); if (nextTrack) { await helpers.play(context.params.event, nextTrack.youtube_link, false) } <file_sep>const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN}); const helpers = require('../../../../helpers/shared.js') if (context.params.event.content.split(' ')[0] === `${process.env.PREFIX}play`) { let searchString = context.params.event.content.split(' ').slice(1).join(' ').trim(); if (searchString) { let newTrack = await helpers.play(context.params.event, searchString, true); await helpers.sendPlayerUpdate(context.params.event, newTrack); } else { let currentTrack = await lib.discord.voice['@0.0.1'].tracks.retrieve({ guild_id: `${context.params.event.guild_id}` }); if (!currentTrack?.paused) { await helpers.sendPlayerUpdate(context.params.event, currentTrack); } else if (currentTrack?.media_url) { let resumedTrackData = await lib.discord.voice['@0.0.1'].tracks.resume({ guild_id: `${context.params.event.guild_id}` }); await helpers.sendPlayerUpdate(context.params.event, resumedTrackData); } else { let nextTrack = await helpers.dequeueTrack(context.params.event); if (nextTrack) { await helpers.play(context.params.event, nextTrack.youtube_link, true); } else { return lib.discord.channels['@0.2.0'].messages.create({ channel_id: `${context.params.event.channel_id}`, content: ` `, embeds: [{ "type": "rich", "description": `No items in the current queue. Please provide a YouTube link to play a track.`, "color": 0xaa0000 }] }); } } } } else if (context.params.event.content === `${process.env.PREFIX}pause`) { let trackData = await lib.discord.voice['@0.0.1'].tracks.pause({ guild_id: `${context.params.event.guild_id}` }); await helpers.sendPlayerUpdate(context.params.event, trackData); } else if (context.params.event.content === `${process.env.PREFIX}disconnect`) { let response = await lib.discord.voice['@0.0.1'].channels.disconnect({ guild_id: `${context.params.event.guild_id}` }); await lib.discord.channels['@0.2.0'].messages.create({ channel_id: `${context.params.event.channel_id}`, content: ` `, embeds: [{ "type": "rich", "description": `Disconnected from <#${process.env.RADIO_VOICE_CHANNEL}>!`, "color": 0xaa0000 }] }); } else if (context.params.event.content === `${process.env.PREFIX}help`){ await lib.discord.channels['@0.2.0'].messages.create({ channel_id: `${context.params.event.channel_id}`, content: ` `, embeds: [{ "type": "rich", "title": "Available commands", "description": [ `\`${process.env.PREFIX}play <query>\`: Play or search for a track`, `\`${process.env.PREFIX}play\` Resume a paused track or play the latest track from the queue if the player is disconnected`, `\`${process.env.PREFIX}pause\`: Pause the currently playing track`, `\`${process.env.PREFIX}disconnect\`: Disconnect the bot from the voice channel`, `\`${process.env.PREFIX}nowplaying\`: Retrieve the current track and queued tracks`, `\`${process.env.PREFIX}queue\`: Same as ${process.env.PREFIX}nowplaying`, `\`${process.env.PREFIX}enqueue <query>\`: Add a track to the queue`, `\`${process.env.PREFIX}skip\`: Skip currently playing track and play the next track in the queue`, `\`${process.env.PREFIX}clearqueue\`: Clear the current queue`, `\`${process.env.PREFIX}help\`: Bring up this help menu` ].join('\n'), "color": 0x00aaaa }] }); }<file_sep>// authenticates you with the API standard library // type `await lib.` to display API autocomplete const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN}); await lib.discord.channels['@0.2.0'].messages.create({ channel_name: `#general`, content: ` `, embeds: [{ "type": "rich", "title": "Available commands", "description": [ `\`${process.env.PREFIX}play <query>\`: Play or search for a track`, `\`${process.env.PREFIX}play\` Resume a paused track or play the latest track from the queue if the player is disconnected`, `\`${process.env.PREFIX}pause\`: Pause the currently playing track`, `\`${process.env.PREFIX}disconnect\`: Disconnect the bot from the voice channel`, `\`${process.env.PREFIX}nowplaying\`: Retrieve the current track and queued tracks`, `\`${process.env.PREFIX}queue\`: Same as ${process.env.PREFIX}nowplaying`, `\`${process.env.PREFIX}enqueue <query>\`: Add a track to the queue`, `\`${process.env.PREFIX}skip\`: Skip currently playing track and play the next track in the queue`, `\`${process.env.PREFIX}clearqueue\`: Clear the current queue`, `\`${process.env.PREFIX}help\`: Bring up this help menu` ].join('\n'), "color": 0x00aaaa }] });<file_sep>const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN}); const ytdl = require('ytdl-core'); const yts = require('yt-search') module.exports = { play: async (event, searchString, sendErrorToChannel) => { try { let youtubeLink; if (!searchString) { throw new Error('No search string provided.'); } if (!searchString.includes('youtube.com')) { let results = await yts(searchString); if (!results?.all?.length) { throw new Error('No results found for your search string. Please try a different one.'); } youtubeLink = results.all[0].url; } else { youtubeLink = searchString; } let downloadInfo = await ytdl.getInfo(youtubeLink); return lib.discord.voice['@0.0.1'].tracks.play({ channel_id: `${process.env.RADIO_VOICE_CHANNEL}`, guild_id: `${event.guild_id}`, download_info: downloadInfo }); } catch (e) { console.log(e); if (sendErrorToChannel) { if (e.message.includes('410')) { e.message = `Failed to download track from YouTube. Please try again later.` } await lib.discord.channels['@0.2.0'].messages.create({ channel_id: `${event.channel_id}`, content: ` `, embeds: [{ "type": "rich", "title": `Failed to play track!`, "description": e.message, "color": 0xaa0000 }] }); } } }, sendPlayerUpdate: async (event, currentTrack, currentQueue) => { let embeds = []; if (currentTrack) { embeds.push({ "type": "rich", "description": [ `${currentTrack.paused ? 'Paused' : 'Playing'} in <#${process.env.RADIO_VOICE_CHANNEL}>:`, '', `**${currentTrack.media_display_name || 'Nothing playing'}**` ].join('\n'), "color": currentTrack.paused ? 0xaa0000 : 0x00aa00 }); } if (currentQueue) { let queueMessage = [ 'Playing next:', '' ]; if (currentQueue.length) { queueMessage = queueMessage.concat(currentQueue.map((track) => { return `**• ${track.media_display_name}**`; }).slice(0, 10)); } else { queueMessage = queueMessage.concat([ `**No tracks in queue. Add one with \`${process.env.PREFIX}enqueue <link>\`!**` ]); } embeds.push({ type: 'rich', description: queueMessage.join('\n'), color: 0x0000aa }); } await lib.discord.channels['@0.2.0'].messages.create({ channel_id: `${event.channel_id}`, content: ` `, embeds: embeds }); }, enqueueTrack: async (event, searchString) => { let queueKey = `${event.guild_id}:musicQueue`; let currentQueue = await lib.utils.kv['@0.1.16'].get({ key: queueKey, defaultValue: [] }); try { let video; if (searchString.includes('youtube.com')) { let url = new URL(searchString); video = await yts({ videoId: url.searchParams.get('v') }); } else { let results = await yts(searchString); if (!results?.all?.length) { throw new Error('No results found for your search string. Please try a different one.'); } video = results.all[0]; } currentQueue.push({ youtube_link: video.url, media_display_name: video.title }); await lib.utils.kv['@0.1.16'].set({ key: queueKey, value: currentQueue }); } catch (e) { console.log(e); if (e.message.includes('410')) { e.message = `Failed to download track from YouTube. Please try again later.` } await lib.discord.channels['@0.2.0'].messages.create({ channel_id: `${event.channel_id}`, content: ` `, embeds: [{ "type": "rich", "title": `Failed to queue track!`, "description": e.message, "color": 0xaa0000 }] }); throw e; } return currentQueue; }, dequeueTrack: async (event) => { let queueKey = `${event.guild_id}:musicQueue`; let currentQueue = await lib.utils.kv['@0.1.16'].get({ key: queueKey, defaultValue: [] }); if (currentQueue.length) { await lib.utils.kv['@0.1.16'].set({ key: queueKey, value: currentQueue.slice(1) }); } return currentQueue[0]; }, clearQueue: async (event) => { let queueKey = `${event.guild_id}:musicQueue`; await lib.utils.kv['@0.1.16'].clear({ key: queueKey }); }, retrieveQueue: async (event) => { let queueKey = `${event.guild_id}:musicQueue`; return lib.utils.kv['@0.1.16'].get({ key: queueKey, defaultValue: [] }); } }
78d533599dbb7ce8ce4e4ea732b825a17d10d4b5
[ "JavaScript" ]
4
JavaScript
Zakaria-ElGhoul/Discord-Bot
81e9db1b8a8b5562b191a895c4e73f711b9cd2b8
6af6abac7995beb795caad95bc6b94661b79ac89
refs/heads/master
<repo_name>varTommy/Web-server<file_sep>/WebServer.go package main import ( "database/sql" "encoding/json" "fmt" "log" "net/http" _ "github.com/go-sql-driver/mysql" ) func checkErr(err error) { if err != nil { panic(err.Error()) } } //登录 func Login(w http.ResponseWriter, r *http.Request) { db, err := sql.Open("mysql", "root:123456@tcp(localhost:3306)/appdb?charset=utf8") checkErr(err) r.ParseForm() //解析参数,默认是不会解析的 uname := r.Form.Get("name") upassword := r.Form.Get("password") sql := "select id from `user` where username=? and password=?" defer db.Close() userinfo := make(map[string]interface{}) stmtOut, err := db.Prepare(sql) rows, err := stmtOut.Query(uname, upassword) for rows.Next() { var uid int err = rows.Scan(&uid) checkErr(err) userinfo["id"] = uid b, err := json.Marshal(userinfo) checkErr(err) fmt.Fprintf(w, string(b)) } } // 预定 func reserved(w http.ResponseWriter, r *http.Request) { r.ParseForm() //解析参数,默认是不会解析的 db, err := sql.Open("mysql", "root:123456@tcp(localhost:3306)/appdb?charset=utf8") checkErr(err) uname := r.Form.Get("name") seatid := r.Form.Get("seatid") adtime := r.Form.Get("adTime") var sql, seatsql string if adtime == "1" { sql = "update `user` set seatid=? , adTime=? ,state = 1 where username=?" seatsql = "update `seatinfo` set used = 1 ,Time1=1 where id=?" } else if adtime == "2" { sql = "update `user` set seatid=? , adTime=? ,state = 1 where username=?" seatsql = "update `seatinfo` set used = 1 ,Time2=1 where id=?" } else if adtime == "3" { sql = "update `user` set seatid=? , adTime=? ,state = 1 where username=?" seatsql = "update `seatinfo` set used = 1 ,Time3=1 where id=?" } defer db.Close() stmtOut, err := db.Prepare(sql) rows, err := stmtOut.Exec(seatid, adtime, uname) affect, err := rows.RowsAffected() checkErr(err) fmt.Println(affect) stmt, err := db.Prepare(seatsql) row, err := stmt.Exec(seatid) affects, err := row.RowsAffected() checkErr(err) fmt.Println(affects) } //个人Info func userinfo(w http.ResponseWriter, r *http.Request) { r.ParseForm() //解析参数,默认是不会解析的 db, err := sql.Open("mysql", "root:123456@tcp(localhost:3306)/appdb?charset=utf8") checkErr(err) uname := r.Form.Get("name") sql := "select * from `user` where username=?" defer db.Close() userinfo := make(map[string]interface{}) stmtOut, err := db.Prepare(sql) rows, err := stmtOut.Query(uname) for rows.Next() { var username, upassword, uid, seatid, state string var adtime string err = rows.Scan(&uid, &username, &upassword, &seatid, &adtime, &state) checkErr(err) userinfo["id"] = uid userinfo["name"] = username userinfo["password"] = upassword userinfo["seatid"] = seatid userinfo["adtime"] = adtime userinfo["state"] = state b, err := json.Marshal(userinfo) checkErr(err) fmt.Fprintf(w, string(b)) } } //签到 func SignSeat(w http.ResponseWriter, r *http.Request) { r.ParseForm() //解析参数,默认是不会解析的 db, err := sql.Open("mysql", "root:123456@tcp(localhost:3306)/appdb?charset=utf8") checkErr(err) uname := r.Form.Get("name") seatid := r.Form.Get("seatid") sql := "update `user` set state = 2 where username=?" defer db.Close() stmtOut, err := db.Prepare(sql) rows, err := stmtOut.Exec(uname) affect, err := rows.RowsAffected() fmt.Println(affect) checkErr(err) seatsql := "update `seatinfo` set used = 2 where id=?" stmt, err := db.Prepare(seatsql) row, err := stmt.Exec(seatid) affects, err := row.RowsAffected() fmt.Println(affects) checkErr(err) } //座位状态 func seatinfo(w http.ResponseWriter, r *http.Request) { r.ParseForm() //解析参数,默认是不会解析的 db, err := sql.Open("mysql", "root:123456@tcp(localhost:3306)/appdb?charset=utf8") checkErr(err) time := r.Form.Get("time") number := r.Form.Get("number") var sql string if number == "1" { sql = "select * from `seatinfo` where Time1=?" } else if number == "2" { sql = "select * from `seatinfo` where Time2=?" } else if number == "3" { sql = "select * from `seatinfo` where Time3=?" } defer db.Close() seatinfo := make(map[string]interface{}) stmtOut, err := db.Prepare(sql) rows, err := stmtOut.Query(time) jsonString := "[" for rows.Next() { var id, used, time1, time2, time3 string err = rows.Scan(&id, &used, &time1, &time2, &time3) checkErr(err) seatinfo["id"] = id seatinfo["used"] = used seatinfo["time"] = time b, err := json.Marshal(seatinfo) checkErr(err) jsonString = jsonString + string(b) + "," //fmt.Fprintf(w, string(b)) } jsonString = jsonString + "{}]" fmt.Fprintf(w, string(jsonString)) } //离开座位 func leave(w http.ResponseWriter, r *http.Request) { r.ParseForm() //解析参数,默认是不会解析的 db, err := sql.Open("mysql", "root:123456@tcp(localhost:3306)/appdb?charset=utf8") checkErr(err) uname := r.Form.Get("name") id := r.Form.Get("seatid") seatime := r.Form.Get("time") sql := "update `user` set seatid=0 ,adTime=0 ,state=0 where username=?" stmtOut, err := db.Prepare(sql) rows, err := stmtOut.Exec(uname) affects, err := rows.RowsAffected() checkErr(err) fmt.Println(affects) var seatsql string if seatime == "1" { seatsql = "update `seatinfo` set used = 0 ,Time1 = 0 where id=?" } else if seatime == "2" { seatsql = "update `seatinfo` set used = 0 ,Time2 = 0 where id=?" } else if seatime == "3" { seatsql = "update `seatinfo` set used = 0 ,Time3 = 0 where id=?" } stmt, err := db.Prepare(seatsql) row, err := stmt.Exec(id) affect, err := row.RowsAffected() checkErr(err) fmt.Println(affect) defer db.Close() } //检查座位 func checkseat(w http.ResponseWriter, r *http.Request) { r.ParseForm() //解析参数,默认是不会解析的 db, err := sql.Open("mysql", "root:123456@tcp(localhost:3306)/appdb?charset=utf8") checkErr(err) id := r.Form.Get("id") time := r.Form.Get("time") var sql string if time == "1" { sql = "select id from `seatinfo` where Time1 = 1 and id = ?" } else if time == "2" { sql = "select id from `seatinfo` where Time2 = 1 and id = ?" } else if time == "3" { sql = "select id from `seatinfo` where Time3 = 1 and id = ?" } defer db.Close() seatinfo := make(map[string]interface{}) stmtOut, err := db.Prepare(sql) rows, err := stmtOut.Query(id) for rows.Next() { var id string err = rows.Scan(&id) checkErr(err) seatinfo["id"] = id b, err := json.Marshal(seatinfo) checkErr(err) fmt.Fprintf(w, string(b)) } } func main() { http.HandleFunc("/Login", Login) http.HandleFunc("/leave", leave) http.HandleFunc("/SignSeat", SignSeat) http.HandleFunc("/userinfo", userinfo) http.HandleFunc("/reserved", reserved) http.HandleFunc("/seatinfo", seatinfo) http.HandleFunc("/checkseat", checkseat) err := http.ListenAndServe(":9090", nil) //设置监听的端口 if err != nil { log.Fatal("ListenAndServe: ", err) } }
2c307a563febb1efdc95794cef16b874c6cad5a0
[ "Go" ]
1
Go
varTommy/Web-server
63ae6a6c30eb202512358f9ee566364de2ae2e11
66d2cb6b5157f15092d3c8f0bf37131d6ccbcd10
refs/heads/master
<repo_name>lin-shaojie/vuex_case<file_sep>/README.md # vuex_case Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。 ## 介绍 这是一个基于Vuex的一个小案例。案例中包含了Vuex中所有核心概念,全部在案例在体现了出来。 ## 案例技术栈主要包括: `Vue-CLi`,`Axios`,`Vuex`,`Ant Design of Vue` <file_sep>/src/store/index.js import Vue from 'vue' import Vuex from 'vuex' import axios from 'axios' Vue.use(Vuex) export default new Vuex.Store({ state: { list: [], inputValue: '', nextId: 5, viewKey: 'all' }, mutations: { initList(state, step) { state.list = step }, inputValeChange(state, step) { state.inputValue = step }, // 添加item项 addItem(state) { const obj = { id: state.nextId, info: state.inputValue, done: false } state.list.push(obj) state.nextId++ state.inputValue = '' }, //根据id删除对应的任务item removeItem(state, id) { // 根据id查找对应的索引值 const index = state.list.findIndex(item => { return item.id == id }) // 根据索引删除数组中的某一项 state.list.splice(index, 1) }, // 修改 复选框选中项 的状态 changeStatus(state, params) { const index = state.list.findIndex(x => x.id == params.id) if (index != -1) { state.list[index].done = params.status } }, // 清除已完成的任务 cleanDone(state) { state.list = state.list.filter(x => x.done === false) }, // 修改 视图关键字 viewKeyChange(state, key) { state.viewKey = key } }, actions: { async getList(context) { const { data: res } = await axios.get('list.json') context.commit('initList', res) } }, getters: { // 统计为完成任务的条数 unDoneLength(state) { return state.list.filter(x => x.done === false).length }, // 筛选 数据 infoList(state) { if (state.viewKey === 'all') { return state.list } if (state.viewKey === 'unDone') { return state.list.filter(x=>x.done === false) } if (state.viewKey === 'done') { return state.list.filter(x=>x.done === true) } return state.list } }, modules: {} })
0714ba868b722bae5642e54b9c466d7083c01d27
[ "Markdown", "JavaScript" ]
2
Markdown
lin-shaojie/vuex_case
2f28637087bf5118b2a4a8cdbc64e3c5479fa224
423d7dcf579ab21ed8daff171b7ea343f58ed48b
refs/heads/master
<repo_name>xiaoxin-vue/xinxinmall<file_sep>/routes/api/profiles.js const express = require('express') const router = express.Router() const passport = require('passport') const Profile = require('../../models/Profile') // $route GET api/profiles/test // @desc 返回请求的json数据 // @access public router.get('/test', (req, res) =>{ res.json({msg: "profile works"}) }) // $route GET api/profiles/add // @desc 创建信息接口 // @access private router.post('/add', passport.authenticate('jwt', {session: false}), (req, res) => { const profileFields = {} if(req.body.type) {profileFields.type = req.body.type} if(req.body.describe) {profileFields.describe = req.body.describe} if(req.body.income) {profileFields.income = req.body.income} if(req.body.expend) {profileFields.expend = req.body.expend} if(req.body.cash) {profileFields.cash = req.body.cash} if(req.body.remark) {profileFields.remark = req.body.remark} // 添加数据保存到User01数据库中的profile集合中 new Profile(profileFields).save() .then(profile => { res.json(profile) }) }) // $route GET api/profiles // @desc 获取所有信息 // @access private router.get('/', passport.authenticate('jwt', {session: false}), (req, res) => { Profile.find() .then(profile => { if(!profile) { res.status(404).json('没有任何内容') } res.json(profile) }) .catch(err => console.log(err)) }) // $route GET api/profiles:id url中 : 必加 // @desc 获取单个信息 // @access private router.get('/:id', passport.authenticate('jwt', {session: false}), (req, res) => { Profile.findOne({_id: req.params.id}) .then(profile => { if(!profile) { res.status(404).json('没有任何内容') } res.json(profile) }) .catch(err => console.log(err)) }) // $route GET api/profiles/edit:id // @desc 编辑信息接口 // @access private router.post('/edit/:id', passport.authenticate('jwt', {session: false}), (req, res) => { const profileFields = {} if(req.body.type) {profileFields.type = req.body.type} if(req.body.describe) {profileFields.describe = req.body.describe} if(req.body.income) {profileFields.income = req.body.income} if(req.body.expend) {profileFields.expend = req.body.expend} if(req.body.cash) {profileFields.cash = req.body.cash} if(req.body.remark) {profileFields.remark = req.body.remark} // 新获取到的信息保存到带有这个_id标志的User01数据库中的profile集合中 // Model.findOneAndUpdate() moogose对数据库实现查询并且更新的方法 Profile.findOneAndUpdate( {_id: req.params.id}, {$set: profileFields}, {new: true} ).then(profile => res.json(profile)) }) // $route delete api/profiles/delete // @desc 编辑信息接口 // @access private router.delete('/delete/:id', passport.authenticate('jwt', {session: false}), (req, res) => { Profile.findOneAndRemove({_id: req.params.id}) .then(profile => { if(profile) { res.json(profile) } else { res.json('已删除') } }) .catch(err => res.status(404).json('删除失败')) }) module.exports = router<file_sep>/models/Multidata.js const mongoose = require('mongoose') const Schema = mongoose.Schema // Create Schema const MultidataSchema = new Schema({ goods: Object }) module.exports = Multidata = mongoose.model('Multidatas', MultidataSchema)<file_sep>/routes/api/orders.js const express = require('express') const router = express.Router() const passport = require('passport') const Order = require('../../models/Order') // $route GET api/profiles/test // @desc 返回请求的json数据 // @access public router.get('/test', (req, res) =>{ res.json({msg: "order works"}) }) // $route GET api/order/add // @desc 创建信息接口 // @access private router.post('/add', passport.authenticate('jwt', {session: false}), (req, res) => { console.log('niah') console.log(req.query) console.log(req.body) const orderFields = {} if(req.body.name) {orderFields.name = req.body.name} if(req.body.goods) {orderFields.goods = req.body.goods} Order.findOne({name: orderFields.name}) .then(o => { console.log('kkkks') console.log(o) if (o) { console.log('推进的订单'); Order.findOneAndUpdate({name: orderFields.name}, {$push: {"goods": orderFields.goods}}) .then(order => { res.json(order) }) } else { console.log('新的订单'); new Order(orderFields).save() .then(order => { if(!order) { res.status(404).json('没有任何内容') } res.json(order) }) .catch(err => console.log(err)) } }) // .then(() => { // Order.findOneAndUpdate({name: orderFields.name}, {$push: {"goods": orderFields.goods}}) // .then(order => { // console.log(order) // res.json(order) // }) // }) // .catch(() => { // console.log('dfafasfafas') // new Order(orderFields).save() // .then(order => { // if(!order) { // res.status(404).json('没有任何内容') // } // return res.json(order) // }) // .catch(err => console.log(err)) // }) }) // $route GET api/order/currentUserOrder 根据?name=test01 返回相对应的订单商品 params => req.query // @desc 创建信息接口 // @access private router.get('/currentUserOrder', passport.authenticate('jwt', {session: false}), (req, res) => { // console.log(req.query.name, 'sadf') Order.find({name: req.query.name}) .then((orders) => { res.send(orders) }) .catch(err => { res.send('订单为空') }) }) // $route GET api/order/delete/orderGood 删除当前用户单个商品订单 // @desc 创建信息接口 // @access private router.delete('/delete/orderGood', passport.authenticate('jwt', {session: false}), (req, res) => { console.log(req.query.iid) console.log(req.query.name) Order.findOneAndUpdate({name: req.query.name}, {$pull: {"goods": {iid: req.query.iid}}}) .then(orders => { if(!orders) { res.status(404).json('没有任何内容') } res.json(orders) }) .catch(err => console.log(err)) }) // $route GET api/order/delete/allOrderGood 删除当前用户所有商品订单 // @desc 创建信息接口 // @access private router.delete('/delete/allOrderGood', passport.authenticate('jwt', {session: false}), (req, res) => { console.log(req.query.name) Order.findOneAndUpdate({name: req.query.name}, {$set: {"goods": []}}) .then(() => { console.log('sda') res.send('删除成功') }) .catch(err => console.log(err)) }) // $route GET api/order/allOrders 获取所有商品信息 // @desc 创建信息接口 // @access private router.get('/allOrders', passport.authenticate('jwt', {session: false}), (req, res) => { Order.find() .then((orders) => { res.json(orders) }) }) module.exports = router<file_sep>/routes/api/detail.js const express = require('express') const router = express.Router() const passport = require('passport') const Detail = require('../../models/Detail') // $route GET api/profiles/test // @desc 返回请求的json数据 // @access public router.get('/test', (req, res) =>{ res.json({msg: "Detail works"}) }) router.get('/', passport.authenticate('jwt', {session: false}), (req, res) =>{ console.log(req.query) Detail.findOne({iid: req.query.iid}) .then((msg) => { res.json(msg) }) }) module.exports = router<file_sep>/xinxinmall-client/src/network/http.js import axios from 'axios' import { Message, Loading } from 'element-ui' import router from '../router' //定义loading变量 let loading function startLoading() { loading = Loading.service({ lock: true, text: '拼命加载中...', background: 'rgba(0, 0, 0, 0.7)' }) } function endLoading() { loading.close() } // 请求拦截 axios.interceptors.request.use( config => { // 加载动画 startLoading() // 设置统一的请求头 // console.log(localStorage.eleToken) if(localStorage.eleToken) config.headers.Authorization = localStorage.eleToken return config }, error => { return Promise.reject(error) }) // 响应拦截 axios.interceptors.response.use( res => { // 结束加载动画 endLoading() // 返回数据 console.log(res) return res }, error => { // 结束加载动画 endLoading() console.log(error.response.data.msg) Message({ message: error.response.data.msg, type: 'error', offset: 1, duration: 2000 }) const { status } = err.response // 获取错误状态码 if(status === 401) { Message.error('token值无效,请重新登录!') // 清除token localStorage.removeItem('eleToken') // 页面跳转 router.push('/login') } // 处理错误响应并结束 return Promise.reject(error) }) export default axios<file_sep>/xinxinmall-client/src/store/mutations.js import { ADD_COUNTER, ADD_TO_CART, INCREASE, DECREASE, CHECKED_ALL, CHANGE_CHECKED, SET_IS_AUTNENTICATED, SET_USER} from './mutation-types' const mutations = { // muutations的唯一目的就是修改state中的状态,其中的每一个方法尽可能完成的事情比较单一 [ADD_COUNTER](state, oldProduct) { oldProduct.count += 1; }, [ADD_TO_CART](state, product) { state.cartList.push(product); }, [INCREASE](state, iid) { // for(let k in state.cartList) { // if(state.cartList[k].iid === iid) { // state.cartList[k].count++ // } // } let itemIid = state.cartList.find(item => item.iid === iid); itemIid.count++; }, [DECREASE](state, iid) { // for(let k in state.cartList) { // if(state.cartList[k].iid === iid) { // if(state.cartList[k].count > 1) { // state.cartList[k].count-- // } // } // } let itemIid = state.cartList.find(item => item.iid === iid); if(itemIid.count > 1) { itemIid.count--; } }, [CHANGE_CHECKED](state, iid) { let itemIid = state.cartList.find(item => item.iid === iid); itemIid.checked = !itemIid.checked; }, [CHECKED_ALL](state, isSelectAll) { if(isSelectAll === true) { state.cartList.forEach(item => { item.checked = false; }); } else { state.cartList.forEach(item => { item.checked = true; }); } }, [SET_IS_AUTNENTICATED](state, isAutnenticated) { if(isAutnenticated) { state.isAutnenticated = isAutnenticated } else { state.isAutnenticated = false } }, [SET_USER](state, user) { if(user) { state.user = user } else { state.user = {} } } } export default mutations<file_sep>/README.md # xinxinmall 模仿coderwhy老师的移动端商城,进行了部分页面优化,并且结合node.js、mongodb数据库,完成后端开发,在原有的基础上进行了部分扩展,比如注册登录、订单管理、支付中心功能。 <file_sep>/models/Order.js const mongoose = require('mongoose') const Schema = mongoose.Schema // Create Schema const OrderSchema = new Schema({ name: String, goods: Array }) module.exports = Order = mongoose.model('orders', OrderSchema)<file_sep>/routes/api/home.js const express = require('express') const router = express.Router() const passport = require('passport') const Home = require('../../models/Home') // $route GET api/profiles/test // @desc 返回请求的json数据 // @access public router.get('/test', (req, res) =>{ res.json({msg: "Home works"}) }) router.get('/data', passport.authenticate('jwt', {session: false}), (req, res) =>{ console.log(req.query) Home.find({type: req.query.type}) .then((msg) => { res.json(msg) }) }) module.exports = router<file_sep>/routes/api/category.js const express = require('express') const router = express.Router() const passport = require('passport') const Category = require('../../models/Category') // $route GET api/profiles/test // @desc 返回请求的json数据 // @access public router.get('/test', (req, res) =>{ res.json({msg: "Category works"}) }) router.get('/', passport.authenticate('jwt', {session: false}), (req, res) =>{ Category.find() .then((msg) => { res.json(msg) }) }) module.exports = router<file_sep>/models/Recommend.js const mongoose = require('mongoose') const Schema = mongoose.Schema // Create Schema const RecommendSchema = new Schema({ RecommendGoods: Object }) module.exports = Recommend = mongoose.model('Recommends', RecommendSchema)<file_sep>/models/Detail.js const mongoose = require('mongoose') const Schema = mongoose.Schema // Create Schema const DetailSchema = new Schema({ iid: String, result: Object }) module.exports = Detail = mongoose.model('Details', DetailSchema)
1f6512e60562ef01b01d48d5570fd31406277507
[ "JavaScript", "Markdown" ]
12
JavaScript
xiaoxin-vue/xinxinmall
24542cfc9c48d859b8abfca2fbfe0e76c6defa46
744402318b3389172d22694a7bb69383d4f03a27
refs/heads/master
<repo_name>jewel-agi/SpotifyFellowshipChallenge<file_sep>/models/person.js "use strict"; module.exports = function(sequelize, DataTypes) { var Person= sequelize.define("Person", { name: DataTypes.STRING, favoriteCity: DataTypes.STRING }); return Person; }; <file_sep>/app/singlePerson.jsx import React from 'react'; import $ from 'jquery'; import {Link , browserHistory} from 'react-router'; const SinglePerson = React.createClass({ getInitialState(){ return({singles: [], editing: false, favoriteCity: ''}) }, componentDidMount(){ let ID = this.props.params.id; $.ajax({ url: '/api/people/' + ID, type: 'GET', success:((data)=>{ this.setState({singles: data}) }) }) }, deletePerson(e){ browserHistory.push('/community'); let ID = this.props.params.id; $.ajax({ url: '/api/people/' + ID, type: 'DELETE', success: ((data)=>{ console.log('Successful Deletion!') }) }) }, editCity(e){ this.setState({editing: true, favoriteCity: e.target.value}) }, updateCity(e){ let ID = this.props.params.id $.ajax({ url: '/api/people/' + ID, type: 'PUT', data: this.state.favoriteCity, success:((data)=>{ console.log('updated was made') }) }) }, render(){ console.log('CITIES', this.state.favoriteCity); if(this.state.editing){ return( <div> <input type="text" value={this.state.favoriteCity} onChange={this.editCity} placeholder="Enter Here"></input> <button type="button" className="btn btn-default" onClick={this.updateCity}>Save</button> </div> ) } else{ return( <div className="single"> <h1>{this.state.singles.favoriteCity}</h1> <h3>{this.state.singles.name}'s Playlist</h3> <ol> <li>24k Magic Bruno Mars</li> <li>Side Ariana Grande Ft <NAME></li> <li>One Dance Drake </li> <li>Zero <NAME> </li> <li>Last Friday Night <NAME></li> </ol> <div className="recommend"> <h3>Recommend A Song:</h3> Artist<input className="artist" placeholder="enter here"></input>Song<input className="song"placeholder="enter here"></input> <button type="button" className="btn btn-default">Submit</button> </div> <button type="button" className="btn btn-default edit" onClick={this.editCity}>Edit</button> <button className="btn btn-danger" onClick={this.deletePerson}>Delete</button> </div> ) } } }) export default SinglePerson;<file_sep>/app/entry.jsx import ReactDOM from 'react-dom'; import React from 'react'; import {browserHistory, IndexRoute, Router, Route} from 'react-router'; //Components import PersonForm from './personForm.jsx'; import People from './people.jsx'; import SinglePerson from './singlePerson.jsx'; //CSS import css from './css/app.css'; import profileCss from './css/people.css'; import singleCss from './css/single.css'; const App = React.createClass({ render(){ return( <div> {this.props.children} </div> ) } }) ReactDOM.render( <Router history={browserHistory}> <Route path="/" component={App}> <IndexRoute component={PersonForm}/> <Route path="intro" component={PersonForm}/> <Route path="community" component={People}/> <Route path="people/:id" component={SinglePerson}/> </Route> </Router>, document.getElementById('root') )<file_sep>/app/personForm.jsx import React from 'react'; import $ from 'jquery'; import {browserHistory} from 'react-router'; const PersonForm = React.createClass({ getInitialState(){ return({name: '', favoriteCity: ''}) }, nameChange(e){ this.setState({name: e.target.value}) }, cityChange(e){ this.setState({favoriteCity: e.target.value}) }, personSubmit(e){ browserHistory.push('/community'); e.preventDefault(); $.ajax({ url:'/api/people/', type:'POST', data: this.state }) console.log('New Person Added!') }, render(){ return( <div> <center> <div className="container"> <h3 className="headingOne">Join Your Music Community</h3> <form onSubmit={this.personSubmit}> <input type="text" className="form-control"value={this.name} onChange={this.nameChange}placeholder="Name"></input><br/> <input type="text" className="form-control"value={this.favoriteCity}onChange={this.cityChange}placeholder="Favorite City"></input><br/> <input type="submit" className="btn btn-success" value="Next"/> </form> </div> </center> </div> ) } }) export default PersonForm;<file_sep>/routes/index.js const router = require('express').Router(); router.use('/people', require('./person-router')); module.exports = router;<file_sep>/app/people.jsx import React from 'react'; import $ from 'jquery'; import {Link} from 'react-router'; import PersonForm from './personForm.jsx'; //CSS import css from './css/people.css'; const People = React.createClass({ getInitialState(){ return({people: [], clicked: false}) }, componentDidMount(){ $.ajax({ url: '/api/people', type: 'GET', success: ((data)=>{ data ? this.setState({people: data}) : console.log('Error with people object') }) }) }, newestCity(e){ this.setState({clicked: true}) }, render(){ console.log('PROPS', this.props) let displayPeople = this.state.people.map((val,indx)=>{ return( <div className="cities"key={indx}><Link className="ppl" to={"/people/" + val.id}><p id="city">{val.favoriteCity}</p><p id="name">{val.name}</p></Link></div> ) }) if(!this.state.people){ return(<div> Still Waiting.....</div>) } if(this.state.clicked){ return( <div> <PersonForm/> <p id="refresh">Refresh Page</p> </div> ) } else{ return( <div> <center> <h3 className="community">Community</h3> {displayPeople} <button className="add btn btn-default" onClick={this.newestCity}>+</button> </center> </div> ) } } }) export default People;<file_sep>/routes/person-router.js const personRouter = require('express').Router(); const person = require('../models').Person; //TO CHECK ROUTES : http://localhost:8888/api/people/ //GET REQUEST - FINDING ALL THE PEOPLE AND ONE SINGLE PERSON const allPeople = (req,res)=>{ person.findAll() .then((data)=>{ res.send(data) }) .catch((error)=>{ res.sendStatus(500); }) } const singlePerson = (req,res)=>{ person.findById(req.params.id) .then((data)=>{ res.send(data) }) .catch((error)=>{ res.sendStatus(500); }) } //POST REQUEST - CREATING A NEW PERSON const newPerson = (req,res)=>{ person.create({favoriteCity:req.body.favoriteCity,name: req.body.name}) .then((data)=>{ res.send(data) }) .catch((error)=>{ res.sendStatus(500); }) } //PUT REQUEST - UPDATING THE PERSON'S CITY const updateCity = (req,res)=>{ person.findById(req.params.id) .then((person)=>{ person.update({favoriteCity: req.body.city}) }) .catch((error)=>{ res.sendStatus(500); }) } //DELETE REQUEST - DELETING ONE PERSON const deletePerson = (req,res)=>{ person.destroy({where:{id:req.params.id}}) .then((data)=>{ res.sendStatus(200) }) } personRouter.route('/') .get(allPeople) .post(newPerson) personRouter.route('/:id') .get(singlePerson) .put(updateCity) .delete(deletePerson) module.exports = personRouter;
cbc213e599aaae290da99c78910ad0923fadff22
[ "JavaScript" ]
7
JavaScript
jewel-agi/SpotifyFellowshipChallenge
1e10c199cc1cb83995ceaa80e97e9d0ca94de70e
e00c47edfceb9f7a6406a0158bd9c1471682029e
refs/heads/master
<file_sep>// // Router+App.swift // YiLuTong // // Created by SeanXu on 2018/11/19. // Copyright © 2018 SeanXu. All rights reserved. // import UIKit // sourcery: router="main" class RouterMainViewController: UIViewController, CustomRoutable { // sourcery: parameter // home、message、user var tab: String? } // sourcery: router="external" class RouterExternalViewController: UIViewController, CustomRoutable { // sourcery: parameter var url: String? } <file_sep>// Generated using Sourcery 0.16.1 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT // // Router.stencil.swift // AnnotationNavigator // // Created by SeanXu on 27/03/2018. // Copyright © 2018 SeanXu. All rights reserved. // import UIKit #if canImport(ObjectMapper) import ObjectMapper #endif // swiftlint:disable all public enum RouterType: String { /// RouterType: Custom Page case custom = "/custom" /// RouterType: Detail Page case detail = "/detail" /// RouterType: Home Page case home = "/home" /// RouterType: Message Center case message = "/message" /// RouterType: case external = "/external" /// RouterType: case main = "/main" /// RouterType: User Center case user = "/user" /// RouterType: Web Page case web = "/web" var name: String { switch self { case .custom: return "Custom Page" case .detail: return "Detail Page" case .home: return "Home Page" case .message: return "Message Center" case .external: return "" case .main: return "" case .user: return "User Center" case .web: return "Web Page" } } } extension CustomViewController: RouterControllerType { var routerType: RouterType { return .custom } } extension DetailViewController: RouterControllerType { var routerType: RouterType { return .detail } } extension HomeViewController: RouterControllerType { var routerType: RouterType { return .home } } extension MessageViewController: RouterControllerType { var routerType: RouterType { return .message } } extension RouterExternalViewController: RouterControllerType { var routerType: RouterType { return .external } } extension RouterMainViewController: RouterControllerType { var routerType: RouterType { return .main } } extension UserViewController: RouterControllerType { var routerType: RouterType { return .user } } extension WebViewController: RouterControllerType { var routerType: RouterType { return .web } } // swiftlint:disable all public enum RouterParameter { case custom(pageTitle: String?, url: String, param: [String: Any]?) case detail(name: String?, uuid: String?) case home case message case external(url: String?) case main(tab: String?) case user case web(url: String) init?(urlScheme: String) { guard let url = URL(string: urlScheme) else { return nil } var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) urlComponents?.query = nil guard let path = urlComponents?.path else { return nil } guard let type = RouterType(rawValue: path) else { return nil } guard let parameter = RouterParameter(type: type, parameter: url.queryParameters) else { return nil } self = parameter } init?(type: RouterType, parameter: [String: Any] = [:]) { do { switch type { case .custom: let pageTitle: String? = try parameter.get("title") let url: String = try parameter.get("url") var param: [String: Any]? let paramTemp: String? = try parameter.get("param") if let paramTemp = paramTemp { param = RouterParser.parseJSONStringIntoDictionary(JSONString: paramTemp) } else { param = nil } self = .custom(pageTitle: pageTitle, url: url, param: param) case .detail: let name: String? = try parameter.get("name") let uuid: String? = try parameter.get("uuid") self = .detail(name: name, uuid: uuid) case .home: self = .home case .message: self = .message case .external: let url: String? = try parameter.get("url") self = .external(url: url) case .main: let tab: String? = try parameter.get("tab") self = .main(tab: tab) case .user: self = .user case .web: let url: String = try parameter.get("url") self = .web(url: url) } } catch { return nil } } var type: RouterType { switch self { case .custom: return .custom case .detail: return .detail case .home: return .home case .message: return .message case .external: return .external case .main: return .main case .user: return .user case .web: return .web } } var parameters: [String: Any] { switch self { case let .custom(pageTitle, url, param): var parameter: [String: Any] = [:] parameter["title"] = pageTitle parameter["url"] = url parameter["param"] = param return parameter case let .detail(name, uuid): var parameter: [String: Any] = [:] parameter["name"] = name parameter["uuid"] = uuid return parameter case .home: return [:] case .message: return [:] case let .external(url): var parameter: [String: Any] = [:] parameter["url"] = url return parameter case let .main(tab): var parameter: [String: Any] = [:] parameter["tab"] = tab return parameter case .user: return [:] case let .web(url): var parameter: [String: Any] = [:] parameter["url"] = url return parameter } } } extension RouterType { // Full URL var url: String { return NavigatorMap.scheme + "://" + NavigatorMap.host + rawValue } } public enum RouterError: Error { case typeNotMatch } <file_sep>// Generated using Sourcery 0.16.1 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT // // Router.stencil.swift // AnnotationNavigator // // Created by SeanXu on 27/03/2018. // Copyright © 2018 SeanXu. All rights reserved. // import URLNavigator // swiftlint:disable all extension NavigatorMap { func registerGenerated(navigator: NavigatorType) { navigator.register(.detail) { _, _, context in guard let router = context as? Router, case let .detail(name, uuid) = router.parameter else { return nil } let viewController = DetailViewController() if name != nil { viewController.name = name } if uuid != nil { viewController.uuid = uuid } viewController.hidesBottomBarWhenPushed = true return viewController } navigator.register(.home) { _, _, context in let viewController = HomeViewController() viewController.hidesBottomBarWhenPushed = true return viewController } navigator.register(.message) { _, _, context in let viewController = MessageViewController() viewController.hidesBottomBarWhenPushed = true return viewController } navigator.register(.user) { _, _, context in let viewController = UserViewController() viewController.hidesBottomBarWhenPushed = true return viewController } navigator.register(.web) { _, _, context in guard let router = context as? Router, case let .web(url) = router.parameter else { return nil } let viewController = WebViewController(url: url) viewController.hidesBottomBarWhenPushed = true return viewController } } } <file_sep>platform :ios, '9.0' use_frameworks! target 'NavigatorDemo' do pod 'Sourcery' pod 'URLNavigator' end project 'NavigatorDemo.xcodeproj' <file_sep>// // TabBarController.swift // NavigatorDemo // // Created by SeanXu on 2018/8/13. // import UIKit protocol TabBarControllerType { var isRootController: Bool { get } } class TabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let appDelegate = UIApplication.shared.delegate as? AppDelegate appDelegate?.tabRouters = [.home, .message, .user] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>// // WebViewController.swift // NavigatorDemo // // Created by SeanXu on 2018/8/13. // import UIKit // sourcery: router="web", name="Web Page" class WebViewController: BaseViewController, InitRoutable { // sourcery: parameter var url: String init(url: String) { self.url = url super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. view.backgroundColor = UIColor.red title = "Web" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep># AnnotationNavigator (自动化Router) ![Swift](https://img.shields.io/badge/Swift-4.1-orange.svg) > 基于sourcery自动生成router定义和注册的代码。工程里已经加了script,添加标注以后,编译一下,就会自动生成router相关的代码 ## Router类型定义 ``` // sourcery: router="sign" // 签单第二步 class SignedBillViewController: ViewController { } ``` ## Router参数定义 - 单个参数的场合 ``` // sourcery: parameter public var url: String ``` - 多个参数的场合 ``` // sourcery:begin: parameter var buildingId: Int? var companyId: Int? var companyName: String? var companyAlias: String? var kpId: Int? var endOrder: Int? var companyPhotos: [PhotoModel]? var stationPhotos: [PhotoModel]? // sourcery:end ``` - 参数别名 URL中的参数可能是关键字,或者super已声明字段,可以通过alias来起一个别名(别名对应URL中的参数名字) ``` // sourcery: parameter, alias="title" public var pageTitle: String? ``` ## Router页面跳转 - 直接通过带Associated Values的Enum进行跳转 ``` navigator.push(.weex(pageTitle: "修改密码", url: "change_password", param: nil)) ``` - 构造Router进行跳转 ``` Router("xxx://xxx.cn/web?url=xxxx") ``` ## Controller初始化 Controller默认通过无参数的初始化方法初始化。 如果自定义了带参数的初始化方法,需要按如下步骤实现: - Controller需要实现InitRoutable的协议 - init方法的参数需要按照参数列表,从上到下,依次书写,一定要保证顺序和名字一致 ``` // sourcery: router="weex" class WeexViewController: UIViewController, InitRoutable { // sourcery: parameter, alias="title" public var pageTitle: String? // sourcery: parameter public var url: String // sourcery: parameter init(pageTitle: String?, url: String, param: [String: Any]?) { self.pageTitle = pageTitle self.url = url self.param = param super.init(nibName: nil, bundle: nil) } ... } ``` ## 特殊情况处理 如果有不能通过sourcery生成router的情况,比如Pods的页面,特殊参数类型等。 - 在Router.swift里面写一个假的Controller来写标注,并实现CustomRoutable协议 - 在URLNavigationMap.swift里面自己写register ``` // sourcery: router="photoView", path="photo_view" class RouterPhotoViewController: UIViewController, CustomRoutable {} // 照片浏览 navigator.register(RouterType.photoView) { _, _, context in guard let router = context as? Router else { return nil } if let urls = router.context["urls"] as? [String], let currentIndex = router.context["currentIndex"] as? Int { let photoBrowser = SKPhotoBrowser(photos: urls.map { SKPhoto.photoWithImageURL($0) }) photoBrowser.currentPageIndex = currentIndex photoBrowser.hidesBottomBarWhenPushed = true return photoBrowser } return nil } ``` <file_sep>// // NavigatorType.swift // AnnotationNavigator // // Created by SeanXu on 16/12/2017. // Copyright © 2017 SeanXu. All rights reserved. // import Foundation import URLNavigator extension NavigatorType { /// register a view controller factory to the router /// /// - Parameters: /// - router: RouterType /// - factory: factory func register(_ router: RouterType, _ factory: @escaping URLNavigator.ViewControllerFactory) { register(router.url, factory) } /// register a handler factory to the router /// /// - Parameters: /// - router: RouterType /// - factory: factory func handle(_ router: RouterType, _ factory: @escaping URLOpenHandlerFactory) { handle(router.url, factory) } /// get the handler for router /// /// - Parameters: /// - router: RouterType /// - context: parameter /// - Returns: handler func handler(for router: RouterType, context: Any?) -> URLOpenHandler? { return handler(for: router.url, context: context) } /// register a custom handler factory to the router /// /// - Parameters: /// - router: RouterType /// - factory: handler factory func customHandle(_ router: RouterType, _ factory: @escaping URLOpenHandlerFactory) { // customHandle(router.url, factory) } /// get the custom handler for router /// /// - Parameters: /// - router: RouterType /// - factory: custom handler func customHandler(for router: RouterType, context: Any?) -> URLOpenHandler? { // return customHandler(for: router.url, context: context) return nil } /// push to router page /// /// - Parameter router: router /// - Returns: controller @discardableResult public func push(_ router: Router) -> UIViewController? { return self.pushURL(router.type.url, context: router) } /// navigate to url (push/present/handler/openURL) /// /// - Parameter url: router url /// - Returns: controller @discardableResult public func open(_ url: URL) -> UIViewController? { if let scheme = url.scheme, scheme == NavigatorMap.scheme { guard let router = Router(url.absoluteString) else { return nil } if navigator.handler(for: router.type, context: router) != nil { navigator.openURL(router.type.url, context: router) return nil } else { if router.isPresent() { return navigator.present(router, wrap: UINavigationController.self) } else { return navigator.push(router) } } } else { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.openURL(url) } return nil } } /// navigate to url (push/present/handler/openURL) /// /// - Parameters: /// - url: router url /// - useCustomHandler: wether using the custom handler /// - Returns: controller @discardableResult public func open(_ url: URL, useCustomHandler: Bool) -> UIViewController? { if let scheme = url.scheme, scheme == NavigatorMap.scheme { guard let router = Router(url.absoluteString) else { return nil } if navigator.handler(for: router.type.url) != nil { navigator.openURL(router.type.url, context: router) return nil } else { if useCustomHandler, executeCustomHandler(router: router) { return nil } else { if router.isPresent() { return navigator.present(router, wrap: UINavigationController.self) } else { return navigator.push(router) } } } } else { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.openURL(url) } } return nil } /// execute custom handler /// /// - Parameter router: RouterType /// - Returns: result private func executeCustomHandler(router: Router) -> Bool { guard let action = customHandler(for: router.type, context: router) else { return false } return action() } /// push to url page /// /// - Parameter url: router url /// - Returns: controller @discardableResult public func push(_ url: URL) -> UIViewController? { if let scheme = url.scheme, scheme == NavigatorMap.scheme { guard let router = Router(url.absoluteString) else { return nil } return navigator.push(router) } else { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.openURL(url) } return nil } } /// push to url page /// /// - Parameters: /// - url: router url /// - useCustomHandler: wether using the custom handler /// - Returns: controller @discardableResult public func push(_ url: URL, useCustomHandler: Bool) -> UIViewController? { if let scheme = url.scheme, scheme == NavigatorMap.scheme { guard let router = Router(url.absoluteString) else { return nil } if useCustomHandler && executeCustomHandler(router: router) { return nil } else { return navigator.push(router) } } else { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.openURL(url) } } return nil } /// check handler exist or push to url page /// /// - Parameters: /// - url: router url /// - useCustomHandler: wether using the custom handler /// - Returns: controller @discardableResult public func pushOrHandle(_ url: URL, useCustomHandler: Bool) -> UIViewController? { if navigator.handler(for: url) != nil { return navigator.open(url) } else { return navigator.push(url, useCustomHandler: useCustomHandler) } } /// present to url /// /// - Parameters: /// - url: router url /// - wrap: wrap in UINavigationController /// - Returns: controller @discardableResult public func present(_ url: URL, wrap: UINavigationController.Type? = nil) -> UIViewController? { if let scheme = url.scheme, scheme == NavigatorMap.scheme, let router = Router(url.absoluteString) { return navigator.present(router, wrap: wrap) } else { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.openURL(url) } return nil } } /// present to router /// /// - Parameters: /// - router: router /// - wrap: wrap in UINavigationController /// - Returns: controller @discardableResult public func present(_ router: Router, wrap: UINavigationController.Type? = nil) -> UIViewController? { return self.presentURL(router.type.url, context: router, wrap: wrap) } /// push to router parameters /// /// - Parameters: /// - parameter: router parameter /// - from: from /// - animated: animated /// - Returns: controller @discardableResult public func push(_ parameter: RouterParameter, from: UINavigationControllerType? = nil, animated: Bool = true) -> UIViewController? { let router = Router(parameter) return self.pushURL(router.type.url, context: router, from: from, animated: animated) } /// present to router parameter /// /// - Parameters: /// - parameter: router parameter /// - context: context /// - wrap: wrap /// - from: from /// - animated: animated /// - completion: completion /// - Returns: controller for router @discardableResult public func present(_ parameter: RouterParameter, context: Any? = nil, wrap: UINavigationController.Type? = nil, from: UIViewControllerType? = nil, animated: Bool = true, completion: (() -> Void)? = nil) -> UIViewController? { let router = Router(parameter) return self.presentURL(router.type.url, context: router, wrap: wrap, from: from, animated: animated, completion: completion) } /// open router with parameter /// /// - Parameters: /// - parameter: router parameter /// - context: context /// - Returns: open result @discardableResult public func open(_ parameter: RouterParameter, context: Any? = nil) -> Bool { let router = Router(parameter) return self.openURL(router.type.url, context: router) } /// new controller for router parameter /// /// - Parameter parameter: router parameter /// - Returns: controller for router public func viewController(_ parameter: RouterParameter) -> UIViewController? { let router = Router(parameter) return viewController(for: router.type.url, context: router) } } <file_sep>// // NavigatorType+Application.swift // JuYouFan // // Created by SeanXu on 2018/8/13. // Copyright © 2018 SeanXu. All rights reserved. // import Foundation import URLNavigator extension NavigatorType { /// navigate to url page /// /// - Parameter urlString: router url string func handleOpenURL(_ urlString: String) { guard let url = URL(string: urlString) else { return } handleOpenURL(url) } /// navigate to url page /// /// - Parameter url: router url func handleOpenURL(_ url: URL) { if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let viewController = appDelegate.window?.rootViewController, viewController.isViewLoaded, viewController.view.window != nil { navigator.open(url, useCustomHandler: true) } else { // save open url } } /// router跳转时优先检查是否需要自定义跳转处理,比如直接切换tabBar func addCustomHandler() { let appDelegate = UIApplication.shared.delegate as? AppDelegate guard let tabRouters = appDelegate?.tabRouters else { return } let tabBarItemHandler: URLOpenHandlerFactory = { url, values, context in guard let topViewController = UIViewController.topMost, let tabBarControllerType = topViewController as? TabBarControllerType, tabBarControllerType.isRootController else { return false } guard let tabBarController = topViewController.tabBarController, let router = context as? Router else { return false } // 切换选中tab if let index = tabRouters.firstIndex(of: router.type) { tabBarController.selectedIndex = index } return true } tabRouters.forEach { type in navigator.customHandle(type, tabBarItemHandler) } } /// switch to tab /// /// - Parameter selectedIndex: tabBar index func openMainTab(_ selectedIndex: Int) { let topViewController = UIViewController.topMost if let navigationController = topViewController?.navigationController, let tabBarController = topViewController?.tabBarController { if navigationController.viewControllers.count > 1 { navigationController.popToRootViewController(animated: false) } if selectedIndex != tabBarController.selectedIndex { tabBarController.selectedIndex = selectedIndex } } } } <file_sep>// // DetailViewController.swift // NavigatorDemo // // Created by SeanXu on 2018/8/13. // import UIKit // sourcery: router="detail", name="Detail Page" class DetailViewController: BaseViewController { // sourcery:begin: parameter var name: String? var uuid: String? // sourcery:end override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. view.backgroundColor = UIColor.yellow title = "Detail" if isPresented { let closeItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(close)) navigationItem.leftBarButtonItem = closeItem } } @objc func close() { dismiss(animated: true, completion: nil) } } <file_sep>// // URLNavigationMap.swift // AnnotationNavigator // // Created by SeanXu on 16/12/2017. // Copyright © 2017 SeanXu. All rights reserved. // import UIKit import URLNavigator // Global Router let navigator = Navigator() struct NavigatorMap { static var scheme = "" static var host = "" init() { guard let urlTypes = Bundle.main.object(forInfoDictionaryKey: "CFBundleURLTypes") as? [[String: Any]], !urlTypes.isEmpty else { fatalError("You need config url scheme in project setting") } for type in urlTypes { if let isNavigator = type["Navigator"] as? Bool, isNavigator { if let host = type["CFBundleURLName"] as? String, !host.isEmpty { NavigatorMap.host = host } else { fatalError("You need config url scheme in project setting") } if let schemes = type["CFBundleURLSchemes"] as? [String], let scheme = schemes.first, !scheme.isEmpty { NavigatorMap.scheme = scheme } else { fatalError("You need config url scheme in project setting") } } } } func initialize() { registerGenerated(navigator: navigator) registerCustom(navigator: navigator) } // Class Controller factory private func classViewControllerFactory<T: UIViewController>(_: T.Type) -> URLNavigator.ViewControllerFactory { return { (url: URLConvertible, values: [String: Any], context: Any?) -> T? in guard url.urlValue != nil else { return nil } let viewController = T() #if os(iOS) viewController.hidesBottomBarWhenPushed = true #endif return viewController } } // Nib controller factory private func nibViewControllerFactory<T: UIViewController>(_: T.Type) -> URLNavigator.ViewControllerFactory { return { (url: URLConvertible, values: [String: Any], context: Any?) -> T? in guard url.urlValue != nil else { return nil } let className = NSStringFromClass(T.self).components(separatedBy: ".").last! let viewController = T(nibName: className, bundle: nil) #if os(iOS) viewController.hidesBottomBarWhenPushed = true #endif return viewController } } } <file_sep>// // RouterParser.swift // JuYouFan // // Created by SeanXu on 2018/9/11. // Copyright © 2018 SeanXu. All rights reserved. // import Foundation public struct RouterParser { /// Convert a JSON String into a Dictionary<String, Any> using NSJSONSerialization public static func parseJSONStringIntoDictionary(JSONString: String) -> [String: Any]? { let parsedJSON: Any? = RouterParser.parseJSONString(JSONString: JSONString) return parsedJSON as? [String: Any] } /// Convert a JSON String into an Object using NSJSONSerialization public static func parseJSONString(JSONString: String) -> Any? { let data = JSONString.data(using: String.Encoding.utf8, allowLossyConversion: true) if let data = data { let parsedJSON: Any? do { parsedJSON = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) } catch let error { print(error) parsedJSON = nil } return parsedJSON } return nil } } <file_sep>// // String+Mapper.swift // JuYouFan // // Created by SeanXu on 2018/11/9. // Copyright © 2018 SeanXu. All rights reserved. // import Foundation extension String { public func map<D: Decodable>(_ type: D.Type) -> D? { let decoder = JSONDecoder() guard let jsonData = data(using: .utf8), !jsonData.isEmpty else { return nil } do { return try decoder.decode(D.self, from: jsonData) } catch { return nil } } } <file_sep>// // UserViewController.swift // NavigatorDemo // // Created by SeanXu on 2018/8/13. // import UIKit // sourcery: router="user", name="User Center" class UserViewController: BaseViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. title = "User" } } extension UserViewController: TabBarControllerType { var isRootController: Bool { return true } } <file_sep>// // NavigatorMap+App.swift // YiLuTong // // Created by SeanXu on 2018/11/19. // Copyright © 2018 SeanXu. All rights reserved. // import UIKit import URLNavigator extension NavigatorMap { func registerCustom(navigator: NavigatorType) { addRegister() addHandler() } private func addRegister() { } private func addHandler() { // 强制切回一级页面,选中tab navigator.handle(.main) { _, _, context in let appDelegate = UIApplication.shared.delegate as? AppDelegate guard let router = context as? Router, case let .main(tab) = router.parameter, let toTab = tab, let routerType = RouterType(rawValue: "/" + toTab), let index = appDelegate?.tabRouters.firstIndex(of: routerType) else { return false } let topViewController = UIViewController.topMost // 当前controller是否是present if let navigationController = topViewController?.navigationController, navigationController.presentingViewController != nil, let delegate = UIApplication.shared.delegate as? AppDelegate, let rootViewController = delegate.window?.rootViewController { // dismiss all controller rootViewController.dismiss(animated: false, completion: { navigator.openMainTab(index) }) } else { navigator.openMainTab(index) } return true } // 外部打开 navigator.handle(.external) { _, _, context in guard let router = context as? Router, case let .external(url) = router.parameter, let urlString = url, let openURL = URL(string: urlString) else { return false } if UIApplication.shared.canOpenURL(openURL) { UIApplication.shared.openURL(openURL) } return true } } } <file_sep>// // MessageViewController.swift // NavigatorDemo // // Created by SeanXu on 2018/8/13. // import UIKit // sourcery: router="message", name="Message Center" class MessageViewController: BaseViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. title = "Message" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension MessageViewController: TabBarControllerType { var isRootController: Bool { return true } } <file_sep>// // Dictionary+Extension.swift // AnnotationNavigator // // Created by SeanXu on 27/03/2018. // Copyright © 2018 SeanXu. All rights reserved. // import Foundation public enum DictionaryError: Error { case notFound case typeNotMatch } protocol OptionalProtocol {} extension Optional: OptionalProtocol {} extension Dictionary where Key == String { public func get<T>(_ key: String) throws -> T { guard let value = self[key] else { throw DictionaryError.notFound } if let transformedValue = transform(value: value, toType: T.self) as? T { return transformedValue } else { throw DictionaryError.typeNotMatch } } public func get<T: ExpressibleByNilLiteral>(_ key: String) throws -> T { guard let value = self[key] else { if T.self is OptionalProtocol.Type { return nil } else { throw DictionaryError.notFound } } if let transformedValue = transform(value: value, toType: T.self) as? T { return transformedValue } else { if T.self is OptionalProtocol.Type { return nil } else { throw DictionaryError.typeNotMatch } } } public func transform<T>(value: Value, toType: T.Type) -> Any? { if value is NSNull { return nil } else if let array = value as? [Any] { if toType is [Any].Type || toType is Optional<[Any]>.Type { return array } else if toType is [[String: Any]].Type || toType is Optional<[[String: Any]]>.Type { return array } else { return nil } } else if let dictionary = value as? [String: Any] { if toType is [String: Any].Type || toType is Optional<[String: Any]>.Type { return dictionary } else { return nil } } else { // convert string to generic type if toType is String.Type || toType is Optional<String>.Type { if let stringValue = value as? String { return stringValue } else if let numberValue = value as? NSNumber { // convert number to string return numberValue.stringValue } } else if toType is Int.Type || toType is Optional<Int>.Type { if let intValue = value as? Int { return intValue } else if let stringValue = value as? String { // convert string to int return Int(stringValue) } } else if toType is Double.Type || toType is Optional<Double>.Type { if let doubleValue = value as? Double { return doubleValue } else if let stringValue = value as? String { // convert string to double return Double(stringValue) } } else if toType is Bool.Type || toType is Optional<Bool>.Type { if let boolValue = value as? Bool { return boolValue } else if let stringValue = value as? String { // convert string to bool return Bool(stringValue) } } } return nil } } <file_sep>// // RouterParameter.swift // JuYouFan // // Created by SeanXu on 2019/2/20. // Copyright © 2019 SeanXu. All rights reserved. // import Foundation extension RouterParameter { var urlScheme: String { return urlScheme(transition: nil) } func urlScheme(transition: String?) -> String { let url = URL(string: type.url) var queries = parameters if let transition = transition { queries["transition"] = transition } guard !queries.isEmpty else { return url?.absoluteString ?? "" } let fullURL = url?.added(queries) return fullURL?.absoluteString ?? "" } } <file_sep>// // CRMWeexViewController.swift // AnnotationNavigator // // Created by SeanXu on 15/01/2018. // Copyright © 2018 SeanXu. All rights reserved. // import UIKit // sourcery: router="custom", name="Custom Page" class CustomViewController: UIViewController, CustomRoutable { // sourcery: parameter, alias="title" public var pageTitle: String? // sourcery: parameter public var url: String // sourcery: parameter public var param: [String: Any]? init(pageTitle: String?, url: String, param: [String: Any]?) { self.pageTitle = pageTitle self.url = url self.param = param super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>// // BaseViewController.swift // NavigatorDemo // // Created by SeanXu on 2018/4/27. // import UIKit class BaseViewController: UIViewController, Routable { var isPresented: Bool { return navigationController?.viewControllers.count == 1 && navigationController?.presentingViewController != nil } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. view.backgroundColor = UIColor.white } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>// // HomeViewController.swift // NavigatorDemo // // Created by SeanXu on 2018/8/13. // import UIKit // sourcery: router="home", name="Home Page" class HomeViewController: BaseViewController { @IBOutlet var tableView: UITableView! var urls: [[String: String]] = [ ["title": "detail", "url": "navidemo://demo-navigator.com/detail"], ["title": "detail with parameter", "url": "navidemo://demo-navigator.com/detail?name=A&uuid=111"], ["title": "detail(present)", "url": "navidemo://demo-navigator.com/detail?name=A&uuid=111&transition=present"], ["title": "web", "url": "navidemo://demo-navigator.com/web?url=xxx"], ] var schemes: [[String: Any]] = [ // ["title": "detail scheme", "scheme": RouterParameter.detail(name: "AAA", uuid: "123")], // ["title": "web scheme", "scheme": RouterParameter.web(url: "https://www.google.com")] ] override func viewDidLoad() { super.viewDidLoad() title = "Home" } } extension HomeViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return urls.count } else { return schemes.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "CellIdentifier") else { fatalError() } if indexPath.section == 0 { cell.textLabel?.text = urls[indexPath.row]["title"] cell.detailTextLabel?.text = urls[indexPath.row]["url"] } else { cell.textLabel?.text = schemes[indexPath.row]["title"] as? String if let parameter = schemes[indexPath.row]["scheme"] as? RouterParameter { cell.detailTextLabel?.text = ".\(parameter)" } } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.section == 0 { if let urlString = urls[indexPath.row]["url"], let url = URL(string: urlString) { navigator.open(url) } } else { if let scheme = schemes[indexPath.row]["scheme"] as? RouterParameter { navigator.push(scheme) } } } } extension HomeViewController: TabBarControllerType { var isRootController: Bool { return true } } <file_sep>// // Routable.swift // NavigatorDemo // // Created by SeanXu on 2018/9/13. // import UIKit // Router跳转 protocol Routable {} // 通过Init方法初始化Controller protocol InitRoutable: Routable {} // 自定义Router跳转 protocol CustomRoutable: Routable {} // Flutter Router跳转 protocol FlutterRoutable: Routable {} protocol RouterControllerType { var routerType: RouterType { get } } enum RouterTransitionType: String { case present case push } <file_sep>// // Router.swift // AnnotationNavigator // // Created by SeanXu on 18/12/2017. // Copyright © 2017 SeanXu. All rights reserved. // import UIKit // Router public struct Router { var type: RouterType var parameter: RouterParameter var context: [String: Any] = [:] /// 初始化 /// /// - Parameter parameter: router参数类型 init(_ parameter: RouterParameter) { self.type = parameter.type self.parameter = parameter } /// App URL Scheme方式初始化 /// /// - Parameters: /// - urlScheme: url /// - context: 附加参数 init?(_ urlScheme: String, context: [String: Any]? = nil) { guard let url = URL(string: urlScheme) else { return nil } var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) urlComponents?.query = nil guard let path = urlComponents?.path else { return nil } guard let type = RouterType(rawValue: path) else { return nil } self.context = urlScheme.queryParameters if let extraContext = context { self.context.merge(extraContext) { (_, new) in new } } guard let parameter = RouterParameter(type: type, parameter: self.context) else { return nil } self.type = type self.parameter = parameter } /// Router类型方式初始化 /// /// - Parameters: /// - type: 页面p类型 /// - context: 参数 init(_ type: RouterType, context: [String: Any] = [:]) { self.type = type guard let parameter = RouterParameter(type: type, parameter: context) else { fatalError("router parameter interval error") } self.parameter = parameter self.context = context } /// transition类型 /// /// - Returns: 是否使用present transition func isPresent() -> Bool { if let transition = context["transition"] as? String, transition == RouterTransitionType.present.rawValue { return true } return false } }
cea27522cfd66efc98aa99282a8cc4a6a2ebb003
[ "Swift", "Ruby", "Markdown" ]
23
Swift
seanxux/AnnotationNavigator
5b85777b90d01b8a7c1b52dd0d622da6708ac047
7ed52ae8827c83d14812d147699bbd5294eb34c6
refs/heads/master
<repo_name>AndreiViasat/ReactHolaMundo<file_sep>/docs/precache-manifest.42895a5a00cdc7c752c4fe6b00750fd4.js self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "10fbf7024888a6afdf0bb9be5afca7a2", "url": "/index.html" }, { "revision": "a87bb1260d602abfd6ef", "url": "/static/css/main.b53daf71.chunk.css" }, { "revision": "450c009cbe237af53050", "url": "/static/js/2.224915d0.chunk.js" }, { "revision": "e88a3e95b5364d46e95b35ae8c0dc27d", "url": "/static/js/2.224915d0.chunk.js.LICENSE.txt" }, { "revision": "a87bb1260d602abfd6ef", "url": "/static/js/main.27d33368.chunk.js" }, { "revision": "abccdcd76010c2c1074c", "url": "/static/js/runtime-main.9897510a.js" } ]);<file_sep>/src/CounterApp.js import React, { useState } from 'react' import PropTypes from 'prop-types' const CounterApp = ({ value }) => { const [counter, setCounter] = useState(0); //Devuelve un arreglo con dos campos //handleAdd const handleAdd = (e) => { setCounter(counter + 1); } return ( <> <h1>Valor del componente:</h1> <p>{counter}</p> <button onClick={handleAdd}>sumar +1</button> </> ); } CounterApp.prototypes = { value: PropTypes.number.isRequired, //Obliga a recibir esta propiedad } export default CounterApp;<file_sep>/src/PrimerComponente.js import React from 'react' import PropTypes from 'prop-types' const PrimerComponente = ({ saludo, valor01 = 'soy un valor por defecto' }) => { return ( <> <h1>{saludo}</h1> <p>{valor01}</p> <p>Soy un espacio</p> </> ); } PrimerComponente.prototypes = { saludo: PropTypes.string.isRequired, //Obliga a recibir esta propiedad } // Metodo para valores por defecto PrimerComponente.defaultProps = { valor01: 'Valor por defecto' } export default PrimerComponente;<file_sep>/src/index.js import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import * as serviceWorker from "./serviceWorker"; import PrimerComponente from "./PrimerComponente"; import CounterApp from "./CounterApp"; //const saludo = <h1> <NAME></h1> const divApp = document.querySelector('#app') ReactDOM.render(<CounterApp value={123} />, divApp) //ReactDOM.render(<GifExpertApp />, document.getElementById("app")); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister(); <file_sep>/src/GifExpertApp.js import React from 'react' export const GifExpertApp = () => { const nombre = 'Andres' return ( <div> <h2>Hola mundo</h2> {nombre} </div>) }
76143684a96ad6c756c55e675e1099203d0952ec
[ "JavaScript" ]
5
JavaScript
AndreiViasat/ReactHolaMundo
9f307bd766918d10304186db4531431ccebada85
01752dea7badd3e8f2d05d6e2b870eaf68100623
refs/heads/main
<repo_name>KhalilGhanem/My-Project<file_sep>/index.html <!DOCTYPE html> <head> <title>Football Around The World</title> <link rel="shortcut icon" href="Images/flaming-football.png" type="image/x-icon"> <link rel="stylesheet" href="Css/style.css"> </head> <body> <header> <h1 >Football Around The World</h1> <nav> <ul> <li ><a href="https://www.uefa.com/uefachampionsleague/" target="_blank" >Uefa champions league</a></li> <li ><a href="https://www.premierleague.com/" target="_blank" >Premier league</a></li> <li ><a href="https://www.laliga.com/en-GB" target="_blank">La Liga</a></li> </ul> </nav> </header> <script src="JavaScript /Script1.js"> </script> <main> <aside style="float: right;"> <table border="1" > <caption>champions league all-time top scorers</caption> <thead> <tr> <th>Player</th> <th>Goals</th> <th>Pos</th> </tr> </thead> <tbody> <tr> <td><NAME></td> <td>134</td> <td>1</td> </tr> <tr> <td><NAME></td> <td>119</td> <td>2</td> </tr> <tr> <td><NAME></td> <td>73</td> <td>3</td> </tr> <tr> <td>Raul</td> <td>71</td> <td>4</td> </tr> </tbody> </table> </aside> <h3>Atalanta vs Real Madrid Champions League preview:</h3> <img src="https://1.bp.blogspot.com/-pk08aJxoSgc/YDZjwxWbhcI/AAAAAAAAESo/sEIAJqtOyN4gk1NCKyOiIeX4y5Zq5HZNACLcBGAsYHQ/s16000/Untitled%2Bdesign%2B%252837%2529-compressed.jpg" alt="Rmimage"> <p> The UEFA Champions League's most established name takes on the young pretenders. These sides have racked up 53 campaigns in Europe's elite competition between them: Atalanta two, Madrid 51. Yet the Spanish side have struggled for consistency and have bowed out in the last 16 in the two seasons since claiming their 13th title, while vibrant Atalanta have never failed to reach the quarter-finals (from a sample of one)! </p> <hr> <h3>Juventus 3-2 Porto: Juventus beaten by Porto on away goals in Champions League:</h3> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSjjhAMpbICyRrex9puIKbuF4JCapN32box0g&usqp=CAU" alt="juvimage"> <p> <NAME> scored twice as 10-man Porto dumped Juventus out of the Champions League with a scintillating away goals victory after a 3-2 second-leg defeat in Turin. Juventus' task of overturning a 2-1 deficit from the first leg was compounded when Oliveira's penalty gave Porto a the lead after 19 minutes, but <NAME> netted twice in 14 second-half minutes - either side of a red card shown to Porto striker Mehdi Taremi - to take the round-of-16 tie into extra-time. </p> <hr> </main> <footer> &COPY;All Right Reserved 2021 </footer> </body> </html><file_sep>/JavaScript /Script1.js function greating(){ var userName = prompt('What is Your name?'); alert ('Welcom to my site '+userName ); } greating(); function pickteam(){ var yourTeam = prompt('which team do you support ?!!' ,'Real Madrid , Barcelona , Bayern Munich'); while (yourTeam !=='Real Madrid' && yourTeam !=='Bayern Munich' && yourTeam !=='Barcelona'){ yourTeam= prompt('please enter a team from the list' ,'Real Madrid , Barcelona , Bayern Munich'); } if (yourTeam==='Real Madrid'){ document.write('<img src="Images/RM.jpg" height="200px" width="200px"/>'); }else if (yourTeam==='Bayern Munich'){ document.write('<img src="Images/BAYERN.jpg" height="200px" width="200px"/>'); }else if (yourTeam==='Barcelona'){ document.write('<img src="Images/Barca.jpg" height="200px" width="200px"/>'); } var image ='' var titles =0; titles= prompt('how many champions league titles your team have !!'); for(var i=0;i<titles;i++ ){ image+='<img src="Images/trophy.jpg" height="200px" width="200px"/>'; } console.log(image); document.write(image); } pickteam(); // else { // document.write('<h3>Good Team</h3>'); // }
9528a74f85499a771ceec212aa859526abd3c3cc
[ "JavaScript", "HTML" ]
2
HTML
KhalilGhanem/My-Project
a0e62479ce6576c953267e3bdf9982b85e7e9405
3a814d95d08a016e28db418773eebf414bf984b4
refs/heads/master
<file_sep>#include <iostream> #include <stdio> #include <stack> using namespace std; asdasdasdasdasd class stos { private int top; //szczyt stosu private int elementy[]; //przechowuje elementy stosu private int element; //pojedynczy element stosu public stos() //domyslny konstruktor - tworzy stos 10 elementowy { this(10); } public stos(int rozmiar) { elementy=new int[rozmiar]; //dynamiczna alokacja pamięci stosu dla wprowadzonego działania top=0; } public push(int element); { elementy[++top]=element; //odkłada element na stosie, przesuwa top na kolejne miejsce przed wrzuceniem elementu } public pop(); { return element[top--]; //zwraca element z góry stosu i przesuwa "wskaźnik" na poprzedni element } public top() { return element[top]; //zwraca element z wierzcholka } public isempty() { if(top==0) return 1; //jeżeli stos jest pusty zwraca 1, inaczej 0 else return 0; } public size() { for(int i=0; element[i]!='\0'; i++) //szuka pierwszej pustej komórki na stosie, zlicza elementy return i; } }; class kalklator { private x; private y; public char in[50]; public wejscie() { cin >> in; // wczytywanie } public liczby() { } public oper_aryt() { for(i=0; in[i]!='\0'; i++) { if(in[i+1]=='+') //dodawanie if(in[i+1]=='-') //odejmowanie if(in[i+1]=='*') //mnozenie if(in[i+1]=='/') //dzielenie } } public ster() { } };
af7ea7fa61ae4b0c9ed6009758e74e7257821add
[ "C++" ]
1
C++
BKozlovvski/repo_1
a1e744759ba0537020ebdcb346734493670d081e
f251c9c32a3008be8ec7262db17d7bf0209030f6
refs/heads/master
<file_sep># coding_test_go 코딩테스트 with Golang - 배열과 인덱스가 인자로 주어질때, 해당 배열에서 인덱스를 삭제한 배열을 리턴하라 - - [1,2,3], 2 => [1,2]<file_sep>package main import ( "testing" "github.com/stretchr/testify/assert" ) func TestMain(t *testing.T) { assert := assert.New(t) tc := []int{1, 2, 3, 4, 5, 6, 10, 100, 200, 300} // 음수값 삭제 result, err := calc(tc, -3) assert.Error(err) // 길이보다 큰 값 삭제 result, err = calc(tc, len(tc)+2) assert.Error(err) //0 삭제 result, err = calc(tc, 0) assert.NoError(err) assert.Equal([]int{2, 3, 4, 5, 6, 10, 100, 200, 300}, result) //2 삭제 result, err = calc(tc, 2) assert.NoError(err) assert.Equal([]int{1, 2, 4, 5, 6, 10, 100, 200, 300}, result) //마지막 앞 삭제 result, err = calc(tc, len(tc)-2) assert.NoError(err) assert.Equal([]int{1, 2, 3, 4, 5, 6, 10, 100, 300}, result) //마지막 삭제 result, err = calc(tc, len(tc)-1) assert.NoError(err) assert.Equal([]int{1, 2, 3, 4, 5, 6, 10, 100, 200}, result) } <file_sep>package main import "fmt" func calc(arr []int, index int) ([]int, error) { result := []int{} if index < 0 { return result, fmt.Errorf("index는 0보다 작을 수 없습니다.: %d", index) } if index >= len(arr) { return result, fmt.Errorf("index는 배열의 lenth보다 작아야합니다.: %d", index) } if index == 0 { result = arr[1:] return result, nil } if index == len(arr) { result = arr[0 : len(arr)-1] return result, nil } result = append(result, arr[0:index]...) result = append(result, arr[index+1:len(arr)]...) return result, nil } func main() { }
828ea3fb2cf12fcd8c8aaf2c1967100d9eec6ad2
[ "Markdown", "Go" ]
3
Markdown
mytkdals93/coding_test_go
441f486c9ca1830ce2595c4769c54fc183770a33
4fe46d8a7e685ef2789709c9216ba4439ac94d19
refs/heads/master
<repo_name>andreasviglakis/borderlands<file_sep>/sql/querygenerator.sh #!/bin/bash set -eu names=( 'Lower Colorado' 'Pacific Northwest' 'South Atlantic Gulf' 'Great Lakes' 'Tennessee' 'Arkansas-White-Red' 'Upper Mississippi' 'California' 'Missouri' 'Texas-Gulf' 'Ohio' 'New England' 'Upper Colorado' 'Rio Grande' 'Lower Mississippi' 'Mid Atlantic' 'Souris-Red-Rainy' 'Great Basin' ) for name in "${names[@]}"; do echo "UPDATE map_cities SET basin = (CASE WHEN ST_Within(geom,(SELECT ST_Union(ST_Makevalid(geom)) FROM map_basin WHERE name = '$name')) THEN '$name' ELSE basin END);" done for name in "${names[@]}"; do echo "UPDATE map_basin SET basin_z = (SELECT box2d(st_collect(geom))::text FROM map_basin WHERE name = '$name') WHERE name = '$name';" done names=( 'Mississippian aquifers' 'Southern Nevada volcanic-rock aquifers' 'Rio Grande aquifer system' 'Mississippi River Valley alluvial aquifer' 'New York and New England carbonate-rock aquifers' 'Pecos River Basin alluvial aquifer' 'Upper carbonate aquifer' 'Denver Basin aquifer system' 'Upper Tertiary aquifers' 'Other rocks' 'Willamette Lowland basin-fill aquifers' 'Marshall aquifer' 'Columbia Plateau basin-fill aquifers' 'Columbia Plateau basaltic-rock aquifers' 'Early Mesozoic basin aquifers' 'Ada-Vamoosa aquifer' 'California Coastal Basin aquifers' 'Rush Springs aquifer' 'Lower Cretaceous aquifers' 'Surficial aquifer system' 'Seymour aquifer' 'Ozark Plateaus aquifer system' 'Edwards-Trinity aquifer system' 'Upper Cretaceous aquifers' 'Valley and Ridge carbonate-rock aquifers' 'Valley and Ridge aquifers' 'Piedmont and Blue Ridge crystalline-rock aquifers' 'Puget Sound aquifer system' 'Colorado Plateaus aquifers' 'Snake River Plain basin-fill aquifers' 'Floridan aquifer system' 'Piedmont and Blue Ridge carbonate-rock aquifers' 'Central Oklahoma aquifer' 'Ordovician aquifers' 'Northern Atlantic Coastal Plain aquifer system' 'Biscayne aquifer' 'Blaine aquifer' 'Jacobsville aquifer' 'Roswell Basin aquifer system' 'Arbuckle-Simpson aquifer' 'Mississippi embayment aquifer system' 'Coastal lowlands aquifer system' 'Texas coastal uplands aquifer system' 'Basin and Range carbonate-rock aquifers' 'Central Valley aquifer system' 'Northern Rocky Mountains Intermontane Basins aquifer system' 'Southeastern Coastal Plain aquifer system' 'Castle Hayne aquifer' 'Basin and Range basin-fill aquifers' 'Snake River Plain basaltic-rock aquifers' 'Cambrian-Ordovician aquifer system' 'Lower Tertiary aquifers' 'Paleozoic aquifers' 'Pacific Northwest basaltic-rock aquifers' 'High Plains aquifer' 'New York sandstone aquifers' 'Pacific Northwest basin-fill aquifers' 'Silurian-Devonian aquifers' 'Pennsylvanian aquifers' ) for name in "${names[@]}"; do echo "UPDATE map_cities SET aquifer = (CASE WHEN ST_Within(geom,(SELECT ST_Union(ST_Makevalid(geom)) FROM map_aquifer WHERE name = '$name')) THEN '$name' ELSE aquifer END);" done for name in "${names[@]}"; do echo "UPDATE map_aquifer SET aquifer_z = (SELECT box2d(st_collect(geom))::text FROM map_aquifer WHERE name = '$name') WHERE name = '$name';" done for name in "${names[@]}"; do echo "case '$name': infoString = ''; break;" done names=( 'Alabama' 'Arizona' 'Arkansas' 'California' 'Colorado' 'Connecticut' 'Delaware' 'District of Columbia' 'Florida' 'Georgia' 'Idaho' 'Illinois' 'Indiana' 'Iowa' 'Kansas' 'Kentucky' 'Louisiana' 'Maine' 'Maryland' 'Massachusetts' 'Michigan' 'Minnesota' 'Mississippi' 'Missouri' 'Montana' 'Nebraska' 'Nevada' 'New Hampshire' 'New Jersey' 'New Mexico' 'New York' 'North Carolina' 'North Dakota' 'Ohio' 'Oklahoma' 'Oregon' 'Pennsylvania' 'Rhode Island' 'South Carolina' 'South Dakota' 'Tennessee' 'Texas' 'Utah' 'Vermont' 'Virginia' 'Washington' 'West Virginia' 'Wisconsin' 'Wyoming' ) for name in "${names[@]}"; do echo "UPDATE map_state SET state_z = (SELECT box2d(st_collect(geom))::text FROM map_state WHERE name = '$name') WHERE name = '$name';" done<file_sep>/README.md # border control --- Project to help users discover and compare state, aquifer, and watershed extents for cities in the contiguous United States. ##### `site` - index.html (contains JS) - css/style.css ##### `bordercontrol.tm2source` ###### Custom data vector tile source created Mapbox Studio Classic. ##### `sql` ###### functions and queries called/used by import.sh, process.sh, and process_cities.sh - bbox_query.sql - pre-process.sql - process.sql - process_cities.sql - querygenerator.sh --- #### Data Sources ##### USGS: - [Aquifers](http://water.usgs.gov/ogw/aquifer/map.html) - [Watersheds](https://water.usgs.gov/GIS/huc.html) <file_sep>/import.sh #!/bin/bash set -eu pushd "$(dirname $0)" SCRIPT_DIR="$(pwd)" popd ## Dependencies ## ----------------- req_cmds=( shp2pgsql psql parallel ) for cmd in "${req_cmds[@]}"; do if [[ -z "$(which $cmd)" ]]; then echo "ERROR: $cmd not found" exit 1 fi done ## Default Settings ## ----------------- data=$(dirname $BASH_SOURCE)/../../gisdata user=${user:-postgres} host=${host:-localhost} port=${port:-5432} db=${db:-bordercontrol} ## Build Database ## ----------------- psql="psql -U $user -h $host -p $port" psqld="psql -U $user -h $host -p $port -d $db" $psql -c "create database $db;" \ || read -r -p "Drop database \"$db\" & recreate it? [Y/n] " response case ${response:-NULL} in [yY][eE][sS]|[yY]) $psql -qc "drop database $db;" $psql -qc "create database $db;" ;; NULL) true # continue ;; *) echo "Aborting import!" exit 1 ;; esac $psqld -qc 'create extension if not exists postgis;' export pg_use_copy=YES ## Raw Data Import ## ----------------- function load_usgs () { local file_name=$1 local folder_name=$2 ogr2ogr \ -f PostgreSQL -append -t_srs EPSG:4326 -nlt geometry \ PG:"user="$user" host="$host" port="$port" dbname="$db"" \ -nln data_$file_name \ "$data"/national/usa/usgs/$folder_name/$file_name.shp } echo "aquifers" load_usgs us_aquifers us_aquifers echo "watersheds" load_usgs HUC2 huc250k_shp function load_ne () { local file_name=$1 ogr2ogr \ -f PostgreSQL -append -t_srs EPSG:4326 -nlt geometry \ PG:"user="$user" host="$host" port="$port" dbname="$db"" \ -s_srs EPSG:4326 -nln data_$file_name \ "$data"/global/ne/$file_name/$file_name.shp } echo "states" load_ne ne_10m_admin_1_states_provinces ne_10m_admin_1_states_provinces echo "cities" load_ne ne_10m_populated_places ne_10m_populated_places echo "rivers" load_ne ne_10m_rivers_lake_centerlines_scale_rank ne_10m_rivers_lake_centerlines_scale_rank echo "urban areas" load_ne ne_10m_urban_areas ne_10m_urban_areas # echo "countries" # load_ne ne_10m_admin_0_countries ne_10m_admin_0_countries function load_outline () { local file_name=$1 ogr2ogr \ -f PostgreSQL -append -t_srs EPSG:4326 -nlt geometry \ PG:"user="$user" host="$host" port="$port" dbname="$db"" \ -s_srs EPSG:4326 -nln data_$file_name \ "$data"/national/usa/outlines/$file_name.shp } echo "aquifer outline" load_outline lower48aquiferoutline echo "basin outline" load_outline lower48basinoutline echo "state outline" ogr2ogr \ -f PostgreSQL -append -t_srs EPSG:4326 -nlt geometry \ PG:"user="$user" host="$host" port="$port" dbname="$db"" \ -s_srs EPSG:4326 -nln data_lower48stateoutline_mask \ "$data"/national/usa/outlines/lower48stateoutline_mask.shp <file_sep>/sql/bbox_query.sql select (select box2d(st_collect(geom)) from map_state where name = 'Idaho') AS state_bbox, (select box2d(st_collect(geom)) from map_aquifer where name = 'Snake River Plain basin-fill aquifers') AS aquifer_bbox, (select box2d(st_collect(geom)) from map_basin where name = 'Strait of Georgia') AS basin_bbox;<file_sep>/process.sh #!/bin/bash set -eu pushd "$(dirname $0)" SCRIPT_DIR="$(pwd)" popd user=${user:-postgres} host=${host:-localhost} port=${port:-5432} db=${db:-bordercontrol} pre_process=$(cat sql/pre-process.sql) process=$(cat sql/process.sql) process_cities=$(cat sql/process_cities.sql) psqld="psql -U $user -h $host -p $port -d $db" $psqld -q <<SQL $pre_process $process $process_cities commit; SQL<file_sep>/sql/process.sql ----------------------------------------------------------------------------------- -- OUTLINE ----------------------------------------------------------------------------------- INSERT INTO polygon_outline (geom) ( SELECT ST_PolygonFromText('POLYGON((-163.5 66.9, -42.9 66.9, -42.9 3.0, -163.5 3.0, -163.5 66.9))',4326) AS geom ); ----------------------------------------------------------------------------------- -- RIVERS ----------------------------------------------------------------------------------- INSERT INTO map_rivers (id,name,rank,geom) ( SELECT ogc_fid AS id, name, scalerank AS rank, wkb_geometry AS geom FROM data_ne_10m_rivers_lake_centerlines_scale_rank WHERE ST_Within(wkb_geometry, ST_PolygonFromText('POLYGON((-128.1 52.5, -64.7 52.5, -64.7 22.4, -128.1 22.4, -128.1 52.5))',4326)) ); ----------------------------------------------------------------------------------- -- AQUIFER ----------------------------------------------------------------------------------- INSERT INTO map_aquifer (name,code,geom) ( SELECT aq_name AS name, aq_code AS code, wkb_geometry AS geom FROM data_us_aquifers WHERE ST_Within(wkb_geometry, ST_PolygonFromText('POLYGON((-128.1 52.5, -64.7 52.5, -64.7 22.4, -128.1 22.4, -128.1 52.5))',4326)) ); INSERT INTO map_aquifer (name,code,geom_line) ( SELECT aq_name AS name, aq_code AS code, ST_Boundary(wkb_geometry) AS geom_line FROM data_us_aquifers WHERE ST_Within(wkb_geometry, ST_PolygonFromText('POLYGON((-128.1 52.5, -64.7 52.5, -64.7 22.4, -128.1 22.4, -128.1 52.5))',4326)) ); INSERT INTO map_aquifer (name,code,geom_point) ( SELECT aq_name AS name, aq_code AS code, ST_PointOnSurface(ST_Collect(wkb_geometry)) AS geom_point FROM data_us_aquifers WHERE ST_Within(wkb_geometry, ST_PolygonFromText('POLYGON((-128.1 52.5, -64.7 52.5, -64.7 22.4, -128.1 22.4, -128.1 52.5))',4326)) GROUP BY aq_code,aq_name ); INSERT INTO map_aquifer (geom_mask) ( SELECT ST_Difference(( SELECT geom FROM polygon_outline),( SELECT wkb_geometry FROM data_lower48aquiferoutline)) AS geom_mask ); ----------------------------------------------------------------------------------- -- BASIN ----------------------------------------------------------------------------------- INSERT INTO map_basin (name,geom) ( SELECT huc_name AS name, wkb_geometry AS geom FROM data_huc2 WHERE ST_Within(wkb_geometry, ST_PolygonFromText('POLYGON((-128.1 52.5, -64.7 52.5, -64.7 22.4, -128.1 22.4, -128.1 52.5))',4326)) ); INSERT INTO map_basin (name,geom_line) ( SELECT huc_name AS name, ST_Boundary(wkb_geometry) AS geom_line FROM data_huc2 WHERE ST_Within(wkb_geometry, ST_PolygonFromText('POLYGON((-128.1 52.5, -64.7 52.5, -64.7 22.4, -128.1 22.4, -128.1 52.5))',4326)) ); INSERT INTO map_basin (name,geom_point) ( SELECT huc_name AS name, ST_PointOnSurface(ST_Collect(wkb_geometry)) AS geom_point FROM data_huc2 WHERE ST_Within(wkb_geometry, ST_PolygonFromText('POLYGON((-128.1 52.5, -64.7 52.5, -64.7 22.4, -128.1 22.4, -128.1 52.5))',4326)) GROUP BY huc_name ); INSERT INTO map_basin (geom_mask) ( SELECT ST_Difference(( SELECT geom FROM polygon_outline),( SELECT wkb_geometry FROM data_lower48basinoutline)) AS geom_mask ); UPDATE map_basin SET name = ( CASE WHEN name = 'White' THEN 'Lower Colorado' WHEN name = 'Strait of Georgia' THEN 'Pacific Northwest' WHEN name = 'Blackwater' THEN 'South Atlantic Gulf' WHEN name = 'Lake Superior' THEN 'Great Lakes' WHEN name = 'Upper Clinch' THEN 'Tennessee' WHEN name = 'Arkansas Headwaters' THEN 'Arkansas-White-Red' WHEN name = 'Mississippi Headwaters' THEN 'Upper Mississippi' WHEN name = 'Williamson' THEN 'California' WHEN name = 'Belly' THEN 'Missouri' WHEN name = 'Running Water Draw' THEN 'Texas-Gulf' WHEN name = 'Upper Allegheny' THEN 'Ohio' WHEN name = 'Upper St. John' THEN 'New England' WHEN name = 'Upper Green' THEN 'Upper Colorado' WHEN name = 'San Luis' THEN 'Rio Grande' WHEN name = 'Upper St. Francis' THEN 'Lower Mississippi' WHEN name = 'Missisquoi' THEN 'Mid Atlantic' WHEN name = 'Lake of the Woods' THEN 'Souris-Red-Rainy' WHEN name = 'Thousand-Virgin' THEN 'Great Basin' ELSE name END ); ----------------------------------------------------------------------------------- -- STATE ----------------------------------------------------------------------------------- INSERT INTO map_state (name,geom) ( SELECT name, wkb_geometry AS geom FROM data_ne_10m_admin_1_states_provinces WHERE iso_a2 = 'US' AND ST_Within(wkb_geometry, ST_PolygonFromText('POLYGON((-128.1 52.5, -64.7 52.5, -64.7 22.4, -128.1 22.4, -128.1 52.5))',4326)) ); INSERT INTO map_state (name,geom_line) ( SELECT name, ST_Boundary(wkb_geometry) AS geom_line FROM data_ne_10m_admin_1_states_provinces WHERE iso_a2 = 'US' AND ST_Within(wkb_geometry, ST_PolygonFromText('POLYGON((-128.1 52.5, -64.7 52.5, -64.7 22.4, -128.1 22.4, -128.1 52.5))',4326)) ); INSERT INTO map_state (name,geom_point) ( SELECT name, ST_PointOnSurface(ST_Collect(wkb_geometry)) AS geom_point FROM data_ne_10m_admin_1_states_provinces WHERE iso_a2 = 'US' AND ST_Within(wkb_geometry, ST_PolygonFromText('POLYGON((-128.1 52.5, -64.7 52.5, -64.7 22.4, -128.1 22.4, -128.1 52.5))',4326)) GROUP BY name ); INSERT INTO map_state (geom_mask) ( SELECT wkb_geometry AS geom_mask FROM data_lower48stateoutline_mask ); ----------------------------------------------------------------------------------- -- URBAN AREAS ----------------------------------------------------------------------------------- INSERT INTO map_urban (geom) ( SELECT wkb_geometry AS geom FROM data_ne_10m_urban_areas WHERE ST_Within(wkb_geometry, ST_PolygonFromText('POLYGON((-128.1 52.5, -64.7 52.5, -64.7 22.4, -128.1 22.4, -128.1 52.5))',4326)) );<file_sep>/sql/pre-process.sql ----------------------- -- AQUIFER ----------------------- DROP TABLE IF EXISTS map_aquifer; CREATE TABLE map_aquifer ( name text, code int, aquifer_z text, geom geometry, geom_mask geometry, geom_line geometry, geom_point geometry ); ----------------------- -- BASIN ----------------------- DROP TABLE IF EXISTS map_basin; CREATE TABLE map_basin ( name text, basin_z text, geom geometry, geom_mask geometry, geom_line geometry, geom_point geometry ); ----------------------- -- STATE ----------------------- DROP TABLE IF EXISTS map_state; CREATE TABLE map_state ( name text, state_z text, geom geometry, geom_mask geometry, geom_line geometry, geom_point geometry ); ----------------------- -- CITIES ----------------------- DROP TABLE IF EXISTS map_cities; CREATE TABLE map_cities ( id integer, name text, basin text, aquifer text, scalerank int, natscale int, labelrank int, geom geometry ); ----------------------- -- URBAN AREAS ----------------------- DROP TABLE IF EXISTS map_urban; CREATE TABLE map_urban ( geom geometry ); ----------------------- -- RIVERS ----------------------- DROP TABLE IF EXISTS map_rivers; CREATE TABLE map_rivers ( id integer, name text, rank int, geom geometry ); ----------------------- -- OUTLINE ----------------------- DROP TABLE IF EXISTS polygon_outline; CREATE TABLE polygon_outline ( geom geometry );
751fcdada193d4074fc1e89e4bc298dea4d9ae27
[ "Markdown", "SQL", "Shell" ]
7
Shell
andreasviglakis/borderlands
89872f840f7d32d447ab1bf9072ec71bfca55105
c0d788dc616c997e3eca39634aac51a6098c7288
refs/heads/master
<repo_name>decathect/Deflect<file_sep>/src/client/Render.java package client; import org.lwjgl.util.vector.Vector3f; import static org.lwjgl.opengl.GL11.*; /** * Collection of static methods to create and render display lists. */ public class Render { /** * Display list assigned to the Mote entity. */ public static final int MOTE_LIST = 1; /** * Display list assigned to the Player entity. */ public static final int PLAYER_LIST = 2; /** * Display list assigned to the wing polygon used in constructing the Player model. */ public static final int WING_LIST = 3; /** * Renders the specified display list with the specified position, size, rotation, and color. * * @param position position of object * @param scale size of object * @param rotation rotation of object * @param color color of object * @param list display list to be rendered */ public static void render(Vector3f position, float scale, int rotation, Vector3f color, int list) { glPushMatrix(); glTranslatef(position.x, position.y, position.z); glRotatef(rotation, 0, 0, 1); glScalef(scale, scale, 1); glColor3f(color.x, color.y, color.z); glCallList(list); glPopMatrix(); } /** * Creates a display list representing a circle. * * @param id display list id to be assigned to the generated circle * @param detail number of triangles to be used to approximate the circle */ public static void makeCircle(int id, int detail) { glNewList(id, GL_COMPILE); double degree; glPushMatrix(); glBegin(GL_TRIANGLE_FAN); for (int i = 0; i < detail; i++) { degree = (i / (float) detail) * (Math.PI * 2); glVertex3f((float) Math.cos(degree), (float) Math.sin(degree), 0); } glEnd(); glPopMatrix(); glEndList(); } /** * Initializes display lists for Mote and Player objects. */ public static void makeLists() { makeCircle(MOTE_LIST, 12); glNewList(WING_LIST, GL_COMPILE); glBegin(GL_QUADS); glVertex3f(-8, 4, 0); glVertex3f(-24, -12, 0); glVertex3f(-24, -16, 0); glVertex3f(-8, -16, 0); glEnd(); glEndList(); glNewList(PLAYER_LIST, GL_COMPILE); glRotatef(-90, 0, 0, 1); glScalef(.25f, .5f, 1); glBegin(GL_POLYGON); glVertex3f(-8, 4, 0); glVertex3f(0, 24, 0); glVertex3f(8, 4, 0); glVertex3f(8, -16, 0); glVertex3f(5, -19, 0); glVertex3f(-5, -19, 0); glVertex3f(-8, -16, 0); glEnd(); glCallList(WING_LIST); glScalef(-1, 1, 1); glCallList(WING_LIST); glEndList(); } } <file_sep>/src/simulation/entities/EntityManager.java package simulation.entities; import client.Render; import org.lwjgl.util.vector.Vector3f; import simulation.Util; import simulation.physics.PhysicsModel; import java.io.Serializable; import java.util.ArrayList; public class EntityManager implements Serializable { private ArrayList<Entity> entityList = new ArrayList<Entity>(); public synchronized void add(Entity e) { entityList.add(e); } public synchronized int addPlayer(Vector3f color) { Player p = new Player(Render.PLAYER_LIST); p.setColor(color); entityList.add(p); return entityList.indexOf(p); } public void updatePlayer(int index, int forward, int turn) { if (entityList.size() > index) { Player p = (Player) entityList.get(index); p.updatePlayer(forward, turn); } } public void update(int delta) { calculatePhysics(); for (Entity e : entityList) { e.update(delta); } } public void render() { for (Entity e : entityList) { e.render(); } } /** * Calculates the force of gravity and the impulse imparted by collisions and applies them to the relevant entities. * <p/> * (Note: gravity and collision are calculated at the same time. this is probably why clusters collapse.) */ public void calculatePhysics() { PhysicsModel e1; PhysicsModel e2; float relativeVelocity; float collisionDistance; float overlap; float gravity; Vector3f distance = new Vector3f(); Vector3f normal = new Vector3f(); Vector3f temp = new Vector3f(); for (int i = 0; i < entityList.size() - 1; i++) { e1 = entityList.get(i).getPhysics(); for (int j = i + 1; j < entityList.size(); j++) { e2 = entityList.get(j).getPhysics(); Vector3f.sub(e1.getPosition(), e2.getPosition(), distance); if (distance.length() > 0) distance.normalise(normal); // relative velocity Vector3f.sub(e1.getVelocity(), e2.getVelocity(), temp); // relative velocity projected onto the normalized distance vector // positive if the entities are approaching each other, negative otherwise relativeVelocity = Vector3f.dot(temp, normal); collisionDistance = entityList.get(i).getSize() + entityList.get(j).getSize(); overlap = distance.length() / collisionDistance; // gravity is capped at the distance at impact // otherwise as the distance approaches zero, the force of gravity goes to infinity // (it's a neat effect) gravity = Util.gravity(e1.getMass(), e2.getMass(), Math.max(distance.lengthSquared(), collisionDistance * collisionDistance)); // calculate and add gravitational force to both entities temp.set(normal); temp.scale(gravity); e2.addForce(temp); temp.negate(); e1.addForce(temp); // if the entities are touching or overlapping and moving towards each other // calculate and add collision impulses to both entities if (overlap <= 1 && relativeVelocity <= 0) { temp.set(normal); temp.scale(Util.impulse(e1.getMass(), e2.getMass(), relativeVelocity)); e1.addImpulse(temp); temp.negate(); e2.addImpulse(temp); } } } } }<file_sep>/src/simulation/Util.java package simulation; import org.lwjgl.Sys; import org.lwjgl.util.vector.Vector3f; public class Util { private static final float g = .0001f; // gravitational constant private static final float e = .8f; // coefficient of restitution private static long now, then = 0; private static int delta; public static int getDelta() { now = Sys.getTime() * 1000 / Sys.getTimerResolution(); delta = (int) (now - then); then = now; return delta; } /** * Calculates the force of gravity. * * @param mass1 mass of first object * @param mass2 mass of second object * @param rSquared distance between objects squared * @return force of gravity */ public static float gravity(float mass1, float mass2, float rSquared) { if (rSquared > 0) return g * mass1 * mass2 / rSquared; else return 0; } /** * Calculates impulse. * (from http://chrishecker.com/images/e/e7/Gdmphys3.pdf) * * @param mass1 mass of first object * @param mass2 mass of second object * @param relativeVelocity relative velocity of the objects * @return impulse from collision */ public static float impulse(float mass1, float mass2, float relativeVelocity) { return (-(1 + e) * relativeVelocity) / (1 / mass1 + 1 / mass2); } public static Vector3f toVector(float rotation) { double r = Math.toRadians(rotation); Vector3f v = new Vector3f(); v.setX((float) Math.cos(r)); v.setY((float) Math.sin(r)); return v; } }<file_sep>/src/network/Network.java package network; import simulation.entities.EntityManager; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.nio.ByteBuffer; public abstract class Network implements Runnable { public static final byte CONNECT = 1; public static final byte DISCONNECT = 2; public static final byte UPDATE = 3; public static final byte SERVER_FULL = 4; public static final byte SERVER_SHUTDOWN = 5; static final int SERVER_PORT = 5000; static final int MAX_PACKET_SIZE = 32 * 1024; DatagramSocket socket; EntityManager state; DatagramPacket statePacket; byte[] stateArray; ByteBuffer stateBuffer; ByteBuffer signalBuffer; private boolean running; public Network() { stateArray = new byte[MAX_PACKET_SIZE]; statePacket = new DatagramPacket(stateArray, stateArray.length); stateBuffer = ByteBuffer.wrap(stateArray); signalBuffer = ByteBuffer.allocate(4 * 4); } public void run() { running = true; try { while (running) { receive(); process(); } } catch (Exception e) { e.printStackTrace(); } socket.close(); } abstract void process(); void receive() { try { socket.receive(statePacket); } catch (IOException e) { e.printStackTrace(); } } public void send(InetSocketAddress address, DatagramPacket p) { p.setSocketAddress(address); try { socket.send(p); } catch (IOException e) { e.printStackTrace(); } } public void send(InetSocketAddress address, byte[] array) { send(address, new DatagramPacket(array, array.length)); } public void send(InetSocketAddress address, byte c) { send(address, new byte[]{c}); } public void send(InetSocketAddress address, byte c, int i) { signalBuffer.clear(); signalBuffer.put(c); signalBuffer.putInt(i); send(address, signalBuffer.array()); } public void exit() { running = false; } } <file_sep>/src/simulation/physics/RungeKutta.java package simulation.physics; import org.lwjgl.util.vector.Vector3f; public class RungeKutta extends AbstractModel { public void step(int delta) { Vector3f[] k2 = evaluate(delta * .5f, new Vector3f(), new Vector3f()); Vector3f[] k3 = evaluate(delta * .5f, k2[0], k2[1]); Vector3f[] k4 = evaluate((float) delta, k3[0], k3[1]); Vector3f temp = new Vector3f(); Vector3f.add(k2[0], k3[0], temp); temp.scale(2); Vector3f.add(temp, k4[0], temp); Vector3f.add(position, temp, position); Vector3f.add(k2[1], k3[1], temp); temp.scale(2); Vector3f.add(temp, k4[1], temp); Vector3f.add(velocity, temp, velocity); force = new Vector3f(); } private Vector3f[] evaluate(float delta, Vector3f dx, Vector3f dv) { Vector3f x = new Vector3f(position); Vector3f v = new Vector3f(velocity); dx.scale(delta); dv.scale(delta); Vector3f.add(x, dx, x); Vector3f.add(v, dv, v); dx.set(v); dv.set(force); dv.scale(1 / mass); Vector3f[] out = {dx, dv}; return out; } }<file_sep>/src/client/Deflect.java package client; import network.ClientSock; import org.lwjgl.LWJGLException; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode; import simulation.Simulation; import simulation.entities.EntityManager; import static org.lwjgl.opengl.GL11.*; public class Deflect implements Runnable { public static final int DISPLAY_WIDTH = 1440; public static final int DISPLAY_HEIGHT = 900; private int[] input = {0, 0}; private int index; private int tempDelta; static String serverAddress; Simulation sim; ClientSock net; public static void main(String[] args) { serverAddress = args[0]; new Deflect(); } public Deflect() { System.err.println("starting threads"); net = new ClientSock(this, serverAddress); while ((index = net.connect()) == 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } new Thread(this).start(); } public void run() { try { Display.setTitle("Deflect"); Display.setDisplayMode(new DisplayMode(DISPLAY_WIDTH, DISPLAY_HEIGHT)); Display.setFullscreen(false); Display.create(); } catch (LWJGLException e) { e.printStackTrace(); } glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, 1000, 0, DISPLAY_HEIGHT * 1000 / DISPLAY_WIDTH, 1, -1); glMatrixMode(GL_MODELVIEW); System.err.println("view initialized"); Render.makeLists(); sim = new Simulation(); new Thread(net).start(); while (!Display.isCloseRequested()) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); Display.sync(60); getInput(); sim.update(); sim.render(); Display.update(); } Display.destroy(); exit(); } public void exit() { net.exit(); System.err.println("exiting Deflect"); System.exit(0); } public void send(int[] input) { net.sendUpdate(input); } public void putState(EntityManager em) { send(input); input[0] = 0; input[1] = 0; sim.putState(em); } private void getInput() { int turn = 0; tempDelta = sim.getDelta(); if (Keyboard.isKeyDown(Keyboard.KEY_UP)) { input[0] += tempDelta; } if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)) { input[1] += tempDelta; turn += tempDelta; } else if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) { input[1] -= tempDelta; turn -= tempDelta; } sim.updatePlayer(index, 0, turn); } } <file_sep>/src/simulation/physics/PhysicsModel.java package simulation.physics; import org.lwjgl.util.vector.Vector3f; public interface PhysicsModel { void addForce(Vector3f f); void addImpulse(Vector3f i); void step(int delta); Vector3f getPosition(); void setPosition(Vector3f p); Vector3f getVelocity(); float getMass(); void setMass(float mass); }
98d91e3e83549feefc772c9e6a9b8cbcb88dd236
[ "Java" ]
7
Java
decathect/Deflect
aca10caf77beadcb37c3d51f96722cf0edf35df4
b381b55f5ee2dca6492d3666354734ccc30a73d4
refs/heads/master
<file_sep>Snake ===== [Live Demo](http://robhdawson.github.io/snake/) Classic snake game, built using jQuery. Features replay logic and local high-score keeping. Particular problems included allowing for different sized boards, and switching between the several different render states, all accomplished through manipulating CSS and DOM element classes with jQuery.<file_sep>(function (root) { var Game = root.Game = (root.Game || {}); var intervalID; var SnakeUI = Game.SnakeUI = function(size, root){ this.size = size; this.$root = root; this.cellSize = Math.floor(500 / size); this.board = new Game.Board(size); this.highscores = [["RHD", 100]] this.initialDraw(); this.waiting = false; } SnakeUI.prototype.reset = function() { this.board = new Game.Board(this.size); this.count = 0; this.score = 0; this.pressed = false; } SnakeUI.prototype.startScreen = function() { this.reset(); this.clearKeys(); this.render(); this.startScreenDraw(); this.bindScreenKeys(); } SnakeUI.prototype.play = function() { $('.game-wrapper').addClass('grayed'); var that = this; this.playDraw(); this.render(); intervalID = null; this.clearKeys(); var newApple = this.board.addApple(); $('#' + newApple[0] + "_" + newApple[1]).addClass('apple'); window.setTimeout(function() { that.bindPlayKeys(); $('.game-wrapper').removeClass('grayed'); that.startStep(); }, 1000); } SnakeUI.prototype.bindScreenKeys = function() { var that = this; $(document).keydown(function(e) { if(e.which === 32) { e.preventDefault(); that.play(); } }); } SnakeUI.prototype.clearKeys = function() { $(document).off('keydown'); } SnakeUI.prototype.bindPlayKeys = function() { var that = this; $(document).keydown(function(e) { if (e.which === 32) { e.preventDefault(); if (intervalID === null) { that.startStep(); } else { clearInterval(intervalID); intervalID = null; that.render(); } } if (!that.pressed) { switch(e.which) { case 37: e.preventDefault(); if(that.board.snake.dir != "E") { that.board.snake.turn("W"); } break; case 38: e.preventDefault(); if(that.board.snake.dir != "S") { that.board.snake.turn("N"); } break; case 39: e.preventDefault(); if(that.board.snake.dir != "W") { that.board.snake.turn("E"); } break; case 40: e.preventDefault(); if(that.board.snake.dir != "N") { that.board.snake.turn("S"); } break; } that.pressed = true; } }); } SnakeUI.prototype.startStep = function() { var that = this; intervalID = window.setInterval(function() { that.step(); }, 40); } SnakeUI.prototype.step = function() { this.pressed = false this.count += 1 this.board.snake.move(); var apple = this.board.appleCollision() if (apple !== "none") { $('#' + apple[0] + "_" + apple[1]).removeClass('apple'); var newApple = this.board.addApple(); $('#' + newApple[0] + "_" + newApple[1]).addClass('apple'); this.score += 10 } else { this.board.snake.shrink(); } if(this.board.hasLost()){ clearInterval(intervalID); this.endGame(); return; } else if (this.board.getOpenCells().length === 0) { clearInterval(intervalID); alert("u win!"); } else { this.render(); } } SnakeUI.prototype.endGame = function() { $('.game-wrapper').addClass('grayed'); var that = this; window.setTimeout(function() { if(that.shouldAddScore(that.score)){ that.clearKeys(); that.swapScoreEntry(); that.waiting = true; that.setNameKey(); that.getName(); } else { $('.game-wrapper').removeClass('grayed'); that.startScreen(); } }, 1000) } SnakeUI.prototype.shouldAddScore = function(score) { if(score === 0) { return false; } else if(this.highscores.length < 10) { return true; } else { if (this.score > this.highscores[9]) { return true; } else { return false; } } } SnakeUI.prototype.addScore = function(score, name) { this.swapScoreEntry(); $('#name-entry').val(''); if(this.highscores.length < 10){ this.highscores.push([name, score]); this.highscores.sort(function(a,b) {return b[1] - a[1];}); } else { this.highscores[9] = [name, score]; this.highscores.sort(function(a,b) {return b[1] - a[1];}); } this.renderHighscores(); $('.game-wrapper').removeClass('grayed'); this.startScreen(); } SnakeUI.prototype.setNameKey = function() { var that = this; $('#name-entry').find('input').focus(); $(document).keydown(function(e) { if(e.which === 13) { e.preventDefault(); that.waiting = false; } }); } SnakeUI.prototype.getName = function() { if(this.waiting) { window.setTimeout(this.getName.bind(this), 33); } else { this.addScore(this.score, $('#name-entry').find('input').val()); } } SnakeUI.prototype.swapScoreEntry = function() { $('#name-entry').toggleClass('invisible'); $('#highscores').toggleClass('invisible'); } SnakeUI.prototype.render = function() { this.clearSnakeUI() this.board.snake.segments.forEach(function(segment) { $('#' + segment[0] + "_" + segment[1]).addClass('snake') }); $('#score').html(this.score) if (intervalID === null) { $('#paused').css("display", "block") } else { $('#paused').css("display", "none") } } SnakeUI.prototype.clearSnakeUI = function() { $('.snake').removeClass('snake'); } SnakeUI.prototype.initialDraw = function () { this.$root.html($('<div class="game-wrapper" id="wrapper"></div>')); var $highscores = $('<div class="highscores"><h1>high scores</h1></div>') $highscores.append($('<ol id="highscores"></ol>')) $highscores.append($('<div id="name-entry">initials: <input type="text" maxlength="3" placeholder="AAA"></div>')) this.$root.append($highscores); $('#name-entry').toggleClass('invisible'); this.renderHighscores(); this.$root.append($('<p class="status">score: <span id="score">0</span></p>')) } SnakeUI.prototype.startScreenDraw = function () { var $gameWrapper = $('#wrapper'); $gameWrapper.addClass('screen'); $gameWrapper.text('press space to begin'); } SnakeUI.prototype.renderHighscores = function() { var $list = $('#highscores') $list.empty(); this.highscores.forEach(function(score) { $list.append('<li>' + score[0] + ": " + score[1] + '</li>') }); } SnakeUI.prototype.playDraw = function() { var $gameWrapper = $('#wrapper') $gameWrapper.empty(); $gameWrapper.removeClass('screen') $gameWrapper.removeAttr("style") for(var r = 0; r < this.size; r++) { for(var c = 0; c < this.size; c++) { var $cell = $('<div class="cell"></div>'); $cell.attr('id', r.toString() + "_" + c.toString()); $cell.css('width', this.cellSize); $cell.css('height', this.cellSize); $gameWrapper.append($cell); } } var $paused = $('<div class="pause" id="paused">((paused))</div>'); $gameWrapper.append($paused); } })(this);
f1cad00153b9bc3b3c16944e34c152db941c6a2d
[ "Markdown", "JavaScript" ]
2
Markdown
robhdawson/snake
90c0f158c9a61623954673492008dc7c42a234e9
8ff48c82a87dfa96d682d72a0682d2c3582231a2
refs/heads/master
<repo_name>avanslaars/shmajax<file_sep>/index.js console.log('coming soon-ish') <file_sep>/README.md # shmajax Placeholder for the shmajax http client
f43d9dde5ae1e1f7d091650443d714f9dff9fea8
[ "JavaScript", "Markdown" ]
2
JavaScript
avanslaars/shmajax
c60efe986eb7ef9f4b701f8de5b4cc41eabcfa98
f6a91192aedf0e3c058b26a28bb899d5d4e1e756
refs/heads/main
<file_sep>package com.company; public class Main { public static void main(String[] args) { Vehicle BlueOrigin = new Vehicle("Blue Origin", "ship", 0 ); Car ModelY = new Car("ModelY",4,"blue"); ModelS MyCar = new ModelS("Red", true); System.out.println("ModelS is a part of "+ModelS.company); MyCar.charge(100); MyCar.changeGear(5); MyCar.changeSpeed(100); MyCar.move(); MyCar.steer("Left"); } } <file_sep>package com.company; public class Main { public static void main(String[] args) { // int val = 1; // // if(val == 1){ // System.out.println("Value is 1"); // }else if(val == 2){ // System.out.println("Value is 2"); // }else{ // System.out.println("Not 1 or 2"); // } int switchVal = 2; switch (switchVal){ case 1: System.out.println("Value is 1"); break; case 2: System.out.println("Value is 2"); break; default: System.out.println("Not 1 or 2"); break; } } } <file_sep>package com.company; public class Main { public static void main(String[] args) { // Bank athhb = new Bank("8412886725", 100.48, "athhb", "1112233", "<EMAIL>"); Bank athhb = new Bank(); // athhb.setCustomerName("athhb"); // athhb.setAccountNo("112233"); // athhb.setEmail("<EMAIL>"); // athhb.setPhone("8412886725"); System.out.println(athhb.getCustomerName()); System.out.println(athhb.getAccountNo()); System.out.println(athhb.getEmail()); System.out.println(athhb.getPhone()); System.out.println("isDeposited : "+athhb.deposit(100)); System.out.println("Balance : "+athhb.getBalance()); System.out.println("isWithdraw : "+athhb.withdraw(50)); System.out.println("Balance : "+athhb.getBalance()); System.out.println("isDeposited : "+athhb.deposit(-50)); System.out.println("isWithdraw : "+athhb.withdraw(-50)); System.out.println("isWithdraw : "+athhb.withdraw(1000)); System.out.println("Balance : "+athhb.getBalance()); } } <file_sep>package com.company; public class HealthyBurger extends BaseBurger { private boolean isHealthyOil; private boolean isLowFatSauce; static double healthyOilPrice = 10; static double lowFatSaucePrice = 8; public HealthyBurger( String meat ) { super("HealthyBurger", "Brown Rye Bread", meat, 10); this.isHealthyOil = false; this.isLowFatSauce = false; } public void addHealthyOil() { // Healthy Oil costs 10 isHealthyOil = true; super.addPrice(HealthyBurger.healthyOilPrice); } public void addLowFatSauce() { // Healthy Oil costs 8 isLowFatSauce = true; super.addPrice(HealthyBurger.lowFatSaucePrice); } public boolean isHealthyOil() { return isHealthyOil; } public boolean isLowFatSauce() { return isLowFatSauce; } @Override public void displayInvoice() { super.displayInvoice(); if(this.isHealthyOil) System.out.println("Healthy Oil : $ "+HealthyBurger.healthyOilPrice); if(this.isLowFatSauce) System.out.println("Low Fat Sauce : $ "+HealthyBurger.lowFatSaucePrice); } } <file_sep>package com.company; public class Main { public static void main(String[] args) { int result = 7; result ++; System.out.println(result); result--; System.out.println(result); result += 2; System.out.println(result); boolean isAlien = false; if(isAlien == false) { System.out.println("It is not an alien!"); System.out.println("And I am sacred of aliens!"); } int topScore = 100; if(topScore <= 100){ System.out.println("You got the high score!"); } } } <file_sep>package com.company; public class Main { public static void main(String[] args) { int myValue = 10000; int myMinIntValue = Integer.MIN_VALUE; int myMaxIntValue = Integer.MAX_VALUE ; System.out.println("Integer Minimum Value = "+myMinIntValue); System.out.println("Integer Maximum Value = "+myMaxIntValue); System.out.println("Busted Max value = " + (myMaxIntValue +1)); System.out.println("Busted Min value = " + (myMinIntValue -1)); int maxIntTest = 2_147_483_647; byte myMinByteValue = Byte.MIN_VALUE; byte myMaxByteValue = Byte.MAX_VALUE; System.out.println("Byte Minimum Value = "+myMinByteValue); System.out.println("Byte Maximum Value = "+myMaxByteValue); short myMinShortValue = Short.MIN_VALUE; short myMaxShortValue = Short.MAX_VALUE; System.out.println("Short Minimum Value = "+myMinShortValue); System.out.println("Short Maximum Value = "+myMaxShortValue); long myLongValue = 100L; long myMinLongValue = Long.MIN_VALUE; long myMaxLongValue = Long.MAX_VALUE; System.out.println("Long Minimum Value = "+myMinLongValue); System.out.println("Long Maximum Value = "+myMaxLongValue); byte first = 121; short second = 11; int third = 12222; long total = 50000L + (10L * (first + second + third)); System.out.println(total); short shortTotal = (short) (1000 + 10 * (first + second + third)); } } <file_sep>package com.company; public class BaseBurger { private int basePrice; private double price; private String breadRoll; private String meat; private String name; private boolean isLettuce; private boolean isTomato; private boolean isCarrot; private boolean isOnion; static double lettucePrice = 3; static double tomatoPrice = 5; static double carrotPrice = 9; static double onionPrice = 8; public BaseBurger(String name,String breadRoll, String meat, int basePrice ) { this.price = this.basePrice = basePrice; // Base Price for a burger this.breadRoll = breadRoll; this.meat = meat; this.isLettuce = false; this.isTomato = false; this.isCarrot = false; this.isOnion = false; this.name = name; } public void addLettuce() { // Price to add lettuce is 3 isLettuce = true; this.price += BaseBurger.lettucePrice; } public void addTomato() { // Price to add tomato is 5 isTomato = true; this.price += BaseBurger.tomatoPrice; } public void addCarrot() { // Price to add carrot is 9 isCarrot = true; this.price += BaseBurger.carrotPrice; } public void addOnion() { // Price to add onion is 8 isOnion = true; this.price += BaseBurger.onionPrice; } public double getPrice() { return price; } public String getBreadRoll() { return breadRoll; } public String getMeat() { return meat; } public String getName() { return name; } public boolean isLettuce() { return isLettuce; } public boolean isTomato() { return isTomato; } public boolean isCarrot() { return isCarrot; } public boolean isOnion() { return isOnion; } public int getBasePrice() { return basePrice; } protected void addPrice(double price) { this.price += price; } public void displayInvoice (){ System.out.println("Burger Name : "+this.name); System.out.println("-------------------------------"); System.out.println("Base Price : $ "+this.basePrice); if(this.isCarrot) System.out.println("Carrot : $ "+BaseBurger.carrotPrice); if(this.isLettuce) System.out.println("Lettuce : $ "+BaseBurger.lettucePrice); if(this.isOnion) System.out.println("Onion : $ "+BaseBurger.onionPrice); if(this.isTomato) System.out.println("Tomato : $ "+BaseBurger.tomatoPrice); } public void displayTotal(){ System.out.println("Total : $ "+this.price); } public void displayBill(){ displayInvoice(); System.out.println("-------------------------------"); displayTotal(); } } <file_sep>package com.company; public class Main { public static void main(String[] args) { String stringNumber = "2018"; System.out.println(stringNumber); int number = Integer.parseInt(stringNumber); System.out.println("number = "+number); } } <file_sep>package com.company; public class ModelS extends Car { public static String company = "Tesla"; private boolean isSelfDriving; private int charging; public boolean isSelfDriving() { return isSelfDriving; } public int getCharging() { return charging; } public ModelS( String colour, boolean isSelfDriving) { super("ModelS", 4, colour); this.isSelfDriving = isSelfDriving; this.charging = 0; } public void charge(int newCharge){ System.out.println("Charging increased from "+this.charging+" to "+newCharge); this.charging += newCharge; } } <file_sep>package com.company; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int counter = 1; int sum = 0; while(counter <= 10){ System.out.println("Enter number #"+counter+": "); boolean isNextInt = scanner.hasNextInt(); if(isNextInt){ int input = scanner.nextInt(); sum += input; counter ++; }else{ System.out.println("Input value should be an Int!"); } scanner.nextLine(); } System.out.println("Sum is "+sum); } }
20bdddd02cc11847bdbc6c252c333dcab858f589
[ "Java" ]
10
Java
atharva-bhange/java-practice
6cb9c60cbd0ed08fe8b8aa6261b3ca729c2986cc
6415d17a49333131b9942d6627d91c97458d3bb5
refs/heads/master
<file_sep>import React from 'react'; import moment from 'moment'; import Dropdown from './Dropdown'; import { useDispatch } from 'react-redux'; import { deletePost, likePost } from '../../../redux/actions/posts'; export default function Post({ post, setcurrentid }) { const changeCurrentid = () => { setcurrentid(post._id); } var content = null; if(post.content.length >= 25){ content = post.content.substring(0,25) + "...Read More"; } else { content = post.content; } const dispatch = useDispatch(); // if(post.selectedFile === " "){ // document.querySelector(".creator").style.color = "black"; // } return ( <> {/* <div className="card" style={{width: "18rem"}}> <img src={post.selectedFile} className="card-img-top" alt="..."/> <Dropdown changeCurrentid={changeCurrentid}/> <h4 className="card-title creator">By {post.creator}</h4> <small className="createdOn">Created on {moment(post.createdAt).format('D/MM/YYYY, h:mm:ss a')}</small> {/* { (post.selectedFile === " ") ? document.querySelector(".creator").style.color = "black": null } */} {/* <div className="card-body"> {/* initially it was all 16px */} {/* <div> <h5 className="card-title">{post.name}</h5> <div> {(post.tags).map(tag => ( <small>{tag}</small> ))} </div> </div> <small className="card-text">{content}</small> <div> {/* <a href="#" class="btn btn-primary">Go somewhere</a> */} {/* <div className="card-buttons"> <button className="btn btn-outline-secondary btn-sm" style={{marginRight: '1rem'}} onClick={() => dispatch(likePost(post._id, post))}><i class="far fa-thumbs-up"></i>Like <small>{post.likes}</small></button> <button className="btn btn-danger btn-sm" onClick={() => dispatch(deletePost(post._id))}>Delete</button> </div> </div> */} {/* </div> */} {/* </div> */} <div className="card" style={{width: '18rem'}}> <div style={{height: 150, overflow: "hidden"}}> <img src={post.selectedFile} className="card-img-top" alt="..."/> <Dropdown changeCurrentid={changeCurrentid}/> <h4 className="card-title creator">By {post.creatorName}</h4> <small className="createdOn">Created on {moment(post.createdAt).format('D/MM/YYYY, h:mm:ss a')}</small> </div> <div className="card-body"> <div className="title-tags"> <h5 className="card-title">{post.name}</h5> <div> {(post.tags).map(tag => ( <small>{tag}</small> ))} </div> </div> <p className="card-text">{content}</p> <div className="buttons"> <button className="btn btn-outline-secondary btn-sm" style={{marginRight: '1rem'}} onClick={() => dispatch(likePost(post._id, post))}><i class="far fa-thumbs-up"></i>Like <small>{post.likes}</small></button> <button className="btn btn-danger btn-sm" onClick={() => dispatch(deletePost(post._id))}>Delete</button> </div> </div> </div> </> ) } <file_sep>import React, { useState, useEffect } from 'react' import { makeStyles } from '@material-ui/core' import { Paper } from '@material-ui/core'; import { Button } from '@material-ui/core'; import { GoogleLogin } from "react-google-login" import { useDispatch } from "react-redux"; import { useHistory } from "react-router-dom"; import { login } from "../../redux/actions/auth" import { yupResolver } from '@hookform/resolvers/yup'; import { useForm } from 'react-hook-form'; import { schema1 } from "../../Validation/Auth"; import { useSelector } from "react-redux"; import './Auth.css'; const useStyles = makeStyles((theme) => ({ root: { padding: "30px 0px", width: '30%', margin: 'auto', position: "relative", top: 60, [theme.breakpoints.down("sm")]: { width: 400, } }, button: { backgroundColor: "#DD4D3F", color: "white" }, btn2: { color: "blue" }, signupButton: { display: 'block', backgroundColor: '#FFCA2C', margin: 'auto', marginTop: 20, } })) export default function Login() { const classes = useStyles(); const dispatch = useDispatch(); const history = useHistory(); const [formData, setFormData] = useState({email: " ", password: <PASSWORD>}) const [viewPassword, setViewPassword] = useState(false); // const authwarning = useSelector(state => state.state?.authdata) const { register, handleSubmit, formState:{ errors } } = useForm({ resolver: yupResolver(schema1), mode: 'onTouched' }); // useEffect(() => { // if(authwarning){ // alert(authwarning) // } // }, [authwarning]) const toggleSignup = () => { history.push("/signup") setFormData({firstName: " ", lastName: " ", email: " ", password: <PASSWORD>}); } const onSubmit = (data) => { if(data) { const { email, password } = data setFormData({ email, password }) } } useEffect(() => { if(formData.firstName !== " ") { console.log(formData); dispatch(login(formData, history)) } }, [formData]) const googleSuccess = async (res) => { const token = res?.tokenId; const result = res?.profileObj; try { dispatch({type: "AUTH", payload: {token, result}}); history.push("/posts"); } catch (error) { console.log(error); } } const googleFailure = (res) => { console.log(res); } return ( <div className="authbackground_dark"> <Paper elevation={3} className={classes.root}> <h3 className="signup">Login</h3> <form style={{width: "70%", margin: "auto"}} onSubmit={handleSubmit(onSubmit)}> {/* email field */} <label className="form-label Label">Email</label> <input type="email" {...register("email")} className={`form-control ${errors?.email && "is-invalid"}`} /> {errors.email?.type === "email" && <label id="passwordHelp" class="text-danger">{errors.email?.message}</label>} {errors.email?.type === "required" && <label id="passwordHelp" class="text-danger">{errors.email?.message}</label>} <label className="form-label Label">Password</label> <div class="input-group"> <input type={viewPassword ? "text" : "password"} {...register("password")} className={`form-control ${errors?.password && "is-invalid"}`} /> <button class="btn btn-secondary" type="button" id="button-addon2" onClick={() => setViewPassword((viewPassword) => !viewPassword)}>{viewPassword ? <i class="fas fa-eye"></i> : <i class="fas fa-eye-slash"></i>}</button> </div> {errors.password?.type === "required" && <label id="passwordHelp" class="text-danger">{errors.password?.message}</label>} {/* submit button */} <Button type="submit" variant="contained" className={classes.signupButton}>Login</Button> </form> <br /> <p className="signup">OR</p> <div className="buttons"> <GoogleLogin clientId="316313260853-bsfl2laem9ma945ses2g9144t0cvmr51.apps.googleusercontent.com" render={renderProps => ( <Button variant="contained" className={classes.button} onClick={renderProps.onClick} disabled={renderProps.disabled}> <span><i class="fab fa-google"></i>&nbsp;Google</span> </Button> )} onSuccess={googleSuccess} onFailure={googleFailure} cookiePolicy="single_host_origin" /> <Button variant="contained" color="primary"> <span className={classes.btn1}><i class="fab fa-facebook"></i>&nbsp;Facebook</span> </Button> <Button className={classes.btn2} onClick={toggleSignup}>Don't have an account? Create Account</Button> </div> </Paper> </div> ) } <file_sep>const postsDetails = (posts = [], action) => { switch (action.type) { case "FETCH_ALL": return action.payload; case "CREATE": return [...posts, action.payload]; case "DELETE": return posts.filter((p) => {return p._id !== action.payload._id}) //what filter does is it finds the element as per the condition and deletes the rest case "UPDATE": return posts.map((post) => (post._id === action.payload._id ? action.payload : post)); // what does this statement do? case "LIKE": return posts.map((post) => (post._id === action.payload._id ? action.payload : post)); default: return posts; } } export default postsDetails;<file_sep>const express = require("express"); const cors = require("cors"); const createErrors = require("http-errors"); const PORT = 5000; const postRoutes = require("./routes/posts.js"); // dont forget to add the .js extention as it is important in node const userRoutes = require("./routes/user.js"); const app = express(); app.use(cors()); app.use(express.json({limit: '30mb', extended: "true"})); // extended: true allows jsonifying nested objects app.use(express.urlencoded({limit: '30mb', extended: "true"})); app.use("/posts", postRoutes); // always define routes after cors middleware app.use("/auth", userRoutes); app.use(async (req, res, next) => { next(createErrors.NotFound("Page not found")) }) app.use((err, req, res, next) => { res.status(err.status || 500) // 500 is a generic error so if nothing, then 500 res.send({ status: err.status || 500, message: err.message }) }) require("./db/connection.js"); app.listen(5000, (req, res) => { console.log("server running at port 5000"); });<file_sep>const mongoose = require("mongoose"); const postContentSchema = mongoose.Schema({ name: String, content: String, creator: String, creatorName: String, // new tags: [String], selectedFile: String, likes: { type: Number, default: 0 }, createdAt: { type: Number, default: new Date() }, }); var postInfo = mongoose.model('postinfo', postContentSchema); module.exports = postInfo; <file_sep>import React, { useState, useEffect } from 'react' import { makeStyles } from '@material-ui/core' import { Paper } from '@material-ui/core'; import { Button } from '@material-ui/core'; import { NameInput } from './Input'; import { ConfirmPassword } from './Input'; import { GoogleLogin } from "react-google-login" import { useDispatch } from "react-redux"; import { useHistory } from "react-router-dom"; import { signup } from "../../redux/actions/auth" import { yupResolver } from '@hookform/resolvers/yup'; import { useForm } from 'react-hook-form'; import { schema } from "../../Validation/Auth"; import { useSelector } from "react-redux"; import './Auth.css'; const useStyles = makeStyles((theme) => ({ root: { padding: "30px 0px", width: '30%', margin: 'auto', position: "relative", top: 60, [theme.breakpoints.down("sm")]: { width: 400, } }, root1: { padding: "30px 0px", width: '30%', margin: 'auto', position: "relative", top: 30, [theme.breakpoints.down("sm")]: { width: 400, } }, button: { backgroundColor: "#DD4D3F", color: "white" }, btn2: { color: "blue" }, signupButton: { display: 'block', backgroundColor: '#FFCA2C', margin: 'auto', marginTop: 20, } })) export default function SignUp() { const classes = useStyles(); const dispatch = useDispatch(); const history = useHistory(); const [formData, setFormData] = useState({firstName: " ", lastName: " ", email: " ", password: null}) // const authwarning = useSelector(state => state.state?.authdata) const { register, handleSubmit, formState:{ errors } } = useForm({ resolver: yupResolver(schema), mode: 'onTouched' }); // useEffect(() => { // if(authwarning){ // alert(authwarning) // } // }, [authwarning]) const toggleSignup = () => { history.push("/login") setFormData({firstName: " ", lastName: " ", email: " ", password: null}); } const onSubmit = (data) => { if(data) { const { firstName, lastName, email, password } = data setFormData({firstName, lastName, email, password}) } } useEffect(() => { if(formData.firstName !== " ") { console.log(formData); dispatch(signup(formData, history)) } }, [formData]) const googleSuccess = async (res) => { const token = res?.tokenId; const result = res?.profileObj; try { dispatch({type: "AUTH", payload: {token, result}}); history.push("/posts"); } catch (error) { console.log(error); } } const googleFailure = (res) => { console.log(res); } return ( <div className="authbackground_dark"> <Paper elevation={3} className={classes.root1}> <h3 className="signup">{"SignUp"}</h3> <form style={{width: "70%", margin: "auto"}} onSubmit={handleSubmit(onSubmit)}> {/* name fields */} <NameInput formData={formData} register={register} errors={errors} /> {/* email field */} <label className="form-label Label">Email</label> <input type="email" {...register("email")} className={`form-control ${errors?.email && "is-invalid"}`} /> {errors.email?.type === "email" && <label id="passwordHelp" class="text-danger">{errors.email?.message}</label>} {errors.email?.type === "required" && <label id="passwordHelp" class="text-danger">{errors.email?.message}</label>} {/* password field */} <ConfirmPassword formData={formData} register={register} errors={errors} /> {/* submit button */} <Button type="submit" variant="contained" className={classes.signupButton}>{"SignUp"}</Button> </form> <br /> <p className="signup">OR</p> <div className="buttons"> <GoogleLogin clientId="316313260853-bsfl2laem9ma945ses2g9144t0cvmr51.apps.googleusercontent.com" render={renderProps => ( <Button variant="contained" className={classes.button} onClick={renderProps.onClick} disabled={renderProps.disabled}> <span><i class="fab fa-google"></i>&nbsp;Google</span> </Button> )} onSuccess={googleSuccess} onFailure={googleFailure} cookiePolicy="single_host_origin" /> <Button variant="contained" color="primary"> <span className={classes.btn1}><i class="fab fa-facebook"></i>&nbsp;Facebook</span> </Button> <Button className={classes.btn2} onClick={toggleSignup}>Already have an account? Login from here</Button> </div> </Paper> </div> ) } <file_sep>import React from 'react'; import "./Desc.css"; export default function Desc() { return ( <section className="descsection"> <div class="px-4 py-5 text-center desccontent"> <h1 class="display-5 fw-bold">Centered hero</h1> <div class="col-lg-6 mx-auto"> <p class="lead mb-4">Quickly design and customize responsive mobile-first sites with Bootstrap, the world’s most popular front-end open source toolkit, featuring Sass variables and mixins, responsive grid system, extensive prebuilt components, and powerful JavaScript plugins.</p> <div class="d-grid gap-2 d-sm-flex justify-content-sm-center"> </div> </div> </div> </section> ) } <file_sep>import { Route, Redirect } from "react-router-dom"; import { useState } from "react"; const PrivateRoute = ({component: Component , ...rest}) => { const [User, setUser] = useState(JSON.parse(localStorage.getItem('profile'))); return ( <Route {...rest} render = {props => { return User ? <Component {...props} /> : <Redirect to="/login" /> }} /> ) } export default PrivateRoute;<file_sep>import * as yup from "yup"; const schema = yup.object().shape({ email: yup.string().email("Enter a valid email").required("Email is required"), password: yup.string().min(6, "Atleast 6 Characters").max(20, "Must be less than 20 characters").required(), // loginpassword: yup.string().required("<PASSWORD>"), firstName: yup.string().required("Firstname is required"), lastName: yup.string(), confirmpassword: yup.string().required("This field is required").oneOf([yup.ref("password"), null], "Passwords don't match") //yup.ref returns an array containing the input value }) const schema1 = yup.object().shape({ email: yup.string().email("Enter a valid email").required("Email is required"), password: yup.string().required("Password <PASSWORD>") }) export {schema, schema1}; <file_sep>const express = require("express"); const userInfo = require('../models/user.js'); const mongoose = require("mongoose"); const { route } = require("./posts.js"); const bcrypt = require("bcrypt"); const jwt = require("jsonwebtoken"); const createError = require("http-errors"); const { generateAccessToken, generateRefreshToken } = require("../util/_jwt-helper"); const secret = process.env.ACCESS_TOKEN_SECRET; const router = express.Router(); router.post("/login", async (req, res) => { const { email, password } = req.body; try { const user = await userInfo.findOne({ email: email }) if(!user) return res.json({ message: "user is not registered"}); const correctPassword = await bcrypt.compare(password, user.password); // bcrypt will automatically encrypt entered password while comparing the password (already encrypted) in database if(!correctPassword) return res.json("entered password is wrong"); const Accesstoken = generateAccessToken(user); const RefreshToken = generateRefreshToken(user); if(!Accesstoken || !RefreshToken) return res.json({result: user, Accesstoken, RefreshToken}) } catch (error) { console.log(error); } }); router.post("/signup", async (req, res) => { const { firstName, lastName, email, password } = req.body; try { //check if user already exists const user = await userInfo.findOne({ email }) if(user) return res.json({ message: "user is already registered"}); //hashing the password const hashedPassword = await bcrypt.hash(password, 12); // here 12 is brcypt salt...know more about this //store the user to the database const result = await userInfo.create({email: email, password: hashedPassword, name: `${firstName} ${lastName}`}); //create the token const Accesstoken = generateAccessToken(user); const RefreshToken = generateRefreshToken(user); if(!Accesstoken || !RefreshToken) return //response sent res.json({result, Accesstoken, RefreshToken}); } catch (error) { console.log(error); } }); module.exports = router;<file_sep>const mongoose = require("mongoose"); const userInfoSchema = mongoose.Schema({ email: { type: String, required: true }, name: { type: String, required: true }, password: { type: String, required: true }, }); var userInfo = mongoose.model('userinfo', userInfoSchema); module.exports = userInfo; <file_sep>import createError from "http-errors"; import jwt from "jsonwebtoken" const generateAccessToken = (user) => { try { const AccessToken = jwt.sign({ email: user.email, id: user._id }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: "1h", issuer: "memories.com", audience: user._id }); return AccessToken; } catch (error) { next(createError.InternalServerError()) } } const generateRefreshToken = (user) => { try { const RefreshToken = jwt.sign({ id: user._id }, process.env.REFRESH_TOKEN_SECRET, { expiresIn: "1y", issuer: "memories.com", audience: user._id }); return RefreshToken; } catch (error) { next(createError.InternalServerError()) } } module.exports = { generateAccessToken, generateRefreshToken }<file_sep>import React from 'react' export const NameInput = ({ formData, handleChange, register, errors }) => { return ( <> <div className="row"> <div className="col-sm-6"> <label className="form-label">First Name</label> <input {... register("firstName")} type="text" className={`form-control ${errors?.firstName && "is-invalid"}`} name="firstName" /> {errors.firstName?.type === "required" && <label id="passwordHelp" class="text-danger">{errors.firstName?.message}</label>} </div> <div className="col-sm-6"> <label className="form-label">Last Name</label> <input {...register("lastName")} type="text" name="lastName" className="form-control" /> </div> </div> </> ) } export const ConfirmPassword = ({ formData, handleChange, register, errors, isSignedUp }) => { const InvalidPassword = (err) => { return ( <> <label className="form-label Label">Confirm Password</label> <input {...register("confirmpassword")} type="password" class="form-control is-invalid" id="inputPassword" /> {err.type === "required" && <label id="passwordHelp" class="text-danger">{err.message}</label>} {err.type === "oneOf" && <label id="passwordHelp" class="text-danger">{err.message}</label>} </> ) } const ValidPassword = () => { return( <> <label className="form-label Label">Confirm Password</label> <input {...register("confirmpassword")} type="password" name="confirmpassword" className="form-control" /> </> ) } return ( <> <div className="row"> <div className="col-sm-6 spassword"> <label className="form-label Label">Password</label> <input {...register("password")} id="signuppassword" type="password" name="password" className={`form-control ${errors?.password && "is-invalid"}`} /> {errors.password?.type === "required" && <label id="passwordHelp" class="text-danger">{errors.password?.message}</label>} {errors.password?.type === "min" && <label id="passwordHelp" class="text-danger">{errors.password?.message}</label>} {errors.password?.type === "max" && <label id="passwordHelp" class="text-danger">{errors.password?.message}</label>} </div> <div className="col-sm-6"> {/* {confirmPassword !== null ? (confirmPassword === formData.password ? ValidPassword() : InvalidPassword()) : ValidPassword() } */} {errors ? (errors?.confirmpassword ? InvalidPassword(errors?.confirmpassword) : ValidPassword()): ValidPassword() } </div> </div> </> ) } // client ci run<file_sep>import React from 'react'; import { useSelector } from "react-redux"; import Post from './Post/Post'; import { CircularProgress } from '@material-ui/core'; export default function Posts({ setcurrentid }) { const posts = useSelector(state => state.posts); console.log(posts); return ( <> <div className="col-md-9"> <div className="row"> {posts.map((post) => ( <div className="col-sm-4"> <Post post={post} setcurrentid={setcurrentid}/> </div> ))} </div> </div> </> ) } <file_sep>const axios = require("axios"); // const url = 'http://localhost:5000/posts'; const API = axios.create({ baseURL : "http://localhost:5000"}); API.interceptors.request.use((req) => { if (localStorage.getItem('profile')) { req.headers.Authorization = `Bearer ${JSON.parse(localStorage.getItem('profile')).Accesstoken}`; } return req; }) export const fetchPosts = () => API.get("/posts").then(console.log("successfull request")).catch(console.error()); export const createPost = (newPost) => API.post("/posts", newPost).then(console.log("successfull request")).catch(console.error()); export const updatePost = (id, updatedPost) => API.patch(`/posts/${id}`, updatedPost).then(console.log("successfull request")).catch(console.error()); export const deletePost = (id) => API.delete(`/posts/${id}`).then(console.log("successfull request")).catch(console.error()); export const likePost = (id, updatedPost) => API.patch(`/posts/${id}/updatelikes`, updatedPost).then(console.log("successfull request")).catch(console.error()); export const signup = (formData) => API.post("/auth/signup", formData).then(console.log("signup successfull request")).catch(console.error()); export const login = (formData) => API.post("/auth/login", formData).then(console.log("login successfull request")).catch(console.error());<file_sep>import { combineReducers } from "redux"; import postsDetails from "./posts"; import authProvider from "./auth" export default combineReducers({ posts: postsDetails, authProvider })<file_sep>import React, { useState, useEffect } from 'react' import { useDispatch } from 'react-redux'; import { NavLink, useLocation, useHistory } from 'react-router-dom' export default function Navbar() { const [user, setUser] = useState(JSON.parse(localStorage.getItem('profile'))); const history = useHistory(); const location = useLocation(); const dispatch = useDispatch(); const logout = () => { dispatch({type: "LOGOUT"}); history.push("/login"); setUser(null); } useEffect(() => { setUser(JSON.parse(localStorage.getItem('profile'))); }, [location]) return ( <div> <header className="p-3 bg-dark text-white"> <div className="container"> <div className="brandLink d-flex flex-wrap align-items-center justify-content-center justify-content-lg-start"> <NavLink className="brandName" to="/posts"><h2 className="navbar-brand">Memories</h2></NavLink> <ul className="nav col-12 col-lg-auto me-lg-auto mb-2 justify-content-center mb-md-0"> <li><a href="#" className="nav-link px-2 text-white">Your Posts</a></li> <li><a href="#" className="nav-link px-2 text-white">Profile</a></li> </ul> <form className="col-12 col-lg-auto mb-3 mb-lg-0 me-lg-3"> <input type="search" className="form-control form-control-dark" placeholder="Search..." aria-label="Search" /> </form> { user?.result ? <div class="dropdown text-end"> { (user?.result.imageUrl) ? <a class="d-block link-dark text-decoration-none dropdown-toggle" id="dropdownUser1" data-bs-toggle="dropdown" aria-expanded="false"> <img src={user?.result.imageUrl} alt="mdo" width="32" height="32" class="rounded-circle" /> </a> : <a class="d-block text-decoration-none" id="dropdownUser1" data-bs-toggle="dropdown" aria-expanded="false"> <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" fill="currentColor" class="bi bi-person-circle" viewBox="0 0 16 16"> <path d="M11 6a3 3 0 1 1-6 0 3 3 0 0 1 6 0z"/> <path fill-rule="evenodd" d="M0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8zm8-7a7 7 0 0 0-5.468 11.37C3.242 11.226 4.805 10 8 10s4.757 1.225 5.468 2.37A7 7 0 0 0 8 1z"/> </svg> </a> } <ul class="dropdown-menu text-small" aria-labelledby="dropdownUser1"> <li><a class="dropdown-item" href="#">Settings</a></li> <li><a class="dropdown-item" href="#">Profile</a></li> <li><hr class="dropdown-divider" /></li> <li><button class="dropdown-item" href="#" onClick={logout}>Sign out</button></li> </ul> </div> : <div className="text-end"> <NavLink to="/login"><button type="button" className="btn btn-outline-light me-2">Login</button></NavLink> <NavLink to="/signup"><button type="button" className="btn btn-warning">Sign-up</button></NavLink> </div> } <div class="dropdown"> <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </div> </div> </div> </header> </div> ) } <file_sep>import React from 'react' import "./Footer.css" export default function Footer() { return ( <section> <footer class="footer mt-auto py-3 footersection"> <div class="container"> <span class="text-white">Place sticky footer content here.</span> </div> </footer> </section> ) } <file_sep>import {makeStyles} from "@material-ui/core/styles"; export const useStyles = makeStyles((theme) => ({ root: { display: 'flex', flexWrap: 'wrap', justifyContent: "center", padding: "20px 20px 20px 20px", position: "fixed", [theme.breakpoints.down("md")]: { position: "static", }, // '& > *': { // margin: theme.spacing(1), // width: theme.spacing(16), // height: theme.spacing(16), // }, }, }));<file_sep>import React from 'react' import Hero from "./Hero/Hero" import Desc from "./Description/Desc" import Footer from "./Footer/Footer" export default function Landing() { return ( <> <Hero /> <Desc /> <Footer /> </> ) } <file_sep>const jwt = require("jsonwebtoken"); const createErrors = require("http-errors"); const secret = process.env.ACCESS_TOKEN_SECRET; const auth = async (req, res, next) => { try { // if(!req.headers.authorization) return const Accesstoken = req.headers.authorization.split(" ")[1]; const isCustomAuth = token.length < 500; // if length is less than 500 then token is custom let decodedData; if (token && isCustomAuth) { // if the token is custom token jwt.verify(Accesstoken, secret, (err, payload) => { if(err) { const errormsg = (err.name === "JsonWebTokenError") ? "Unauthorized User" : err.message; next(createErrors.Unauthorized(errormsg)) // if token would have expired } req.userId = payload.id; next(); }) } else { // if the token is oauth token jwt.decode(Accesstoken, (err, payload) => { if(err) { const errormsg = (err.name === "JsonWebTokenError") ? "Unauthorized User" : err.message; next(createErrors.Unauthorized(errormsg)); } req.userId = payload.sub; next(); }) } } catch (error) { console.log(error); } }; module.exports = auth;
82376769fc8d19f6a7f0c9ee6626573b17cbc151
[ "JavaScript" ]
21
JavaScript
swayam-coder/memories-project
e984f8aad7c8b2d490d357215e430f702d60685c
ccd3272160187cc7b4aaf2f2ae9a08ac919e4c8f
refs/heads/master
<repo_name>rcmgleite/labSoft2_Estoque<file_sep>/models/order.go package models import ( "encoding/json" "fmt" "io/ioutil" "github.com/rcmgleite/labSoft2_Estoque/database" "github.com/rcmgleite/labSoft2_Estoque/requestHelper" ) // OrderToSend ... type OrderToSend struct { Products []ProductToSend `json:"produtos"` } //Order is the struct that defines the purchase order type Order struct { BaseModel `sql:"-" json:",omitempty"` // Ignore this field ID int Products []Product `gorm:"many2many:order_products;"` Valor int `json:"valor" sql:"-"` Approved bool } // GetByID ... func (order *Order) GetByID(id int) error { db := database.GetDatabase() order.ID = id products := []Product{} err := db.Model(order).Related(&products, "Products").Error order.Products = products fmt.Println(order) return err } //Save .. func (order *Order) Save() error { db := database.GetDatabase() return db.Create(order).Error } // Update ... func (order *Order) Update() error { db := database.GetDatabase() err := db.Save(order).Error if err != nil { return err } return order.send(comprasIP, "/order") } // Delete ... func (order *Order) Delete() error { db := database.GetDatabase() err := db.Delete(order).Error return err } //GetOpenOrder ... func GetOpenOrder(order *Order) error { db := database.GetDatabase() err := db.Where("approved = ?", false).First(order).Error if err != nil { return err } products := []Product{} err = db.Model(order).Related(&products, "Products").Error order.Products = products return err } // OpenOrderHasProduct ... func OpenOrderHasProduct(product Product) (bool, error) { db := database.GetDatabase() order := Order{} err := GetOpenOrder(&order) if err != nil { return false, err } err = db.Model(order).Association("Products").Find(&product).Error if err != nil { if err.Error() == "record not found" { return false, nil } return false, err } return true, nil } // RemoveProductFromOpenOrder from the existing opened order func RemoveProductFromOpenOrder(product Product) error { db := database.GetDatabase() order := Order{} err := GetOpenOrder(&order) if err != nil { return err } return db.Model(order).Association("Products").Delete([]Product{product}).Error } // AddProductToOpenOrder to the existing opened order or creates a new order if needed func AddProductToOpenOrder(product Product) error { var order Order err := GetOpenOrder(&order) if err != nil { if err.Error() == "record not found" { return order.createOrderAndAddProduct(product) } return err } return order.addProduct(product) } func (order *Order) createOrderAndAddProduct(product Product) error { db := database.GetDatabase() err := db.Create(order).Error if err != nil { return err } err = db.Model(order).Association("Products").Append([]Product{product}).Error if err != nil { return err } return nil } func (order *Order) addProduct(product Product) error { db := database.GetDatabase() return db.Model(order).Association("Products").Append([]Product{product}).Error } // FIXME - MOVE THIS FUNCTION TO A PROPER HELPER func getJSON(object interface{}) ([]byte, error) { if object != nil { return json.Marshal(object) } return nil, nil } //send = Function that sends the new order to compras module func (order *Order) send(dstIP string, dstPath string) error { err := order.GetByID(order.ID) if err == nil { headers := make(map[string]string) headers["Content-Type"] = "application/json" pToSend := make([]ProductToSend, len(order.Products)) for index, value := range order.Products { pToSend[index].ProductID = value.ID pToSend[index].Quantidade = value.MinQuantity - value.CurrQuantity pToSend[index].Valor = 10 } orderToSend := &OrderToSend{Products: pToSend} bJSON, err := getJSON(orderToSend) if err == nil { resp, err := requestHelper.MakeRequest("POST", dstIP+dstPath, bJSON, headers) if resp != nil && err == nil { body, _ := ioutil.ReadAll(resp.Body) fmt.Println("Response", string(body)) } else { fmt.Println(err) } } } return err } <file_sep>/test/README.txt To run the tests, do: 1) delete estoque_test.db on /bin folder if exists 2) execute ./install.sh -test on labSoft2_Estoque 3) enter test/ folder and execute "go test" When running it multiple times, you will need to delete the old database every time (FIXME) <file_sep>/models/modelsBase.go package models import "strings" //FIXME - USE PROC ENV VARIABLE TO HOLD THIS VALUE var comprasIP = "http://192.168.1.132:8080" //BaseModel struct for all models type BaseModel struct { QueryParams map[string]string `sql:"-" json:",omitempty"` } //Identifiers for query //The ideia is to use JSONS like: // { // last_modified_gt: 423424354 // min_quantity_lte: 10 // curr_quantity_eq: "min_quantity" // . // . // . // } var queryIdentifiers = map[string]string{"_gte": ">=", "_gt": ">", "_lte": "<=", "_lt": "<", "_eq": "="} //Aux functions func buildQuery(queryMap map[string]string) string { var query string for k, value := range queryMap { for keyIdentifier, vIdentifier := range queryIdentifiers { if strings.Contains(k, keyIdentifier) { if query != "" { query += " and " } columnName := k[0 : len(k)-len(keyIdentifier)] query += columnName + vIdentifier + value break } } } return query } <file_sep>/requestHelper/requestHelper.go package requestHelper import ( "bytes" "net/http" ) //MakeRequest ... func MakeRequest(httpMethod string, url string, requestObj []byte, headers map[string]string) (*http.Response, error) { req, err := http.NewRequest(httpMethod, url, bytes.NewBuffer(requestObj)) addHeaders(req, headers) client := &http.Client{} resp, err := client.Do(req) if err != nil { return nil, err } return resp, nil } func addHeaders(req *http.Request, headers map[string]string) { for k, v := range headers { req.Header.Set(k, v) } } <file_sep>/productController.go package main import ( "net/http" "github.com/rcmgleite/labSoft2_Estoque/decoder" "github.com/rcmgleite/labSoft2_Estoque/models" ) //POSTQueryProductHandler ... func POSTQueryProductHandler(w http.ResponseWriter, r *http.Request) { var p models.Product decoder := decoder.NewDecoder() err := decoder.DecodeReqBody(&p, r.Body) if err != nil { rj := NewResponseJSON(nil, err) writeBack(w, r, rj) return } products, err := p.Retreive() rj := NewResponseJSON(products, err) writeBack(w, r, rj) } //POSTConsumeProductHandler ... func POSTConsumeProductHandler(w http.ResponseWriter, r *http.Request) { var toConsume models.ProductToConsume decoder := decoder.NewDecoder() err := decoder.DecodeReqBody(&toConsume, r.Body) if err != nil { rj := NewResponseJSON(nil, err) writeBack(w, r, rj) return } product := &models.Product{ID: toConsume.ID} err = product.Consume(toConsume.Quantity) rj := NewResponseJSON("Product Consumed successfully", err) writeBack(w, r, rj) } // GETProductHandler ... func GETProductHandler(w http.ResponseWriter, r *http.Request) { queryString := r.URL.Query() var p models.Product decoder := decoder.NewDecoder() err := decoder.DecodeURLValues(&p, queryString) if err != nil { rj := NewResponseJSON(nil, err) writeBack(w, r, rj) return } products, err := p.Retreive() rj := NewResponseJSON(products, err) writeBack(w, r, rj) } // POSTProductHandler ... func POSTProductHandler(w http.ResponseWriter, r *http.Request) { var p models.Product decoder := decoder.NewDecoder() err := decoder.DecodeReqBody(&p, r.Body) if err != nil { rj := NewResponseJSON(nil, err) writeBack(w, r, rj) return } err = p.Save() if err != nil { rj := NewResponseJSON(nil, err) writeBack(w, r, rj) return } rj := NewResponseJSON("Product successfully saved", err) writeBack(w, r, rj) } // PUTProductHandler ... func PUTProductHandler(w http.ResponseWriter, r *http.Request) { var p models.Product decoder := decoder.NewDecoder() err := decoder.DecodeReqBody(&p, r.Body) if err != nil { rj := NewResponseJSON(nil, err) writeBack(w, r, rj) return } err = p.Update() if err != nil { rj := NewResponseJSON(nil, err) writeBack(w, r, rj) return } rj := NewResponseJSON("Product updated successfully", err) writeBack(w, r, rj) } // DELETEProductHandler ... func DELETEProductHandler(w http.ResponseWriter, r *http.Request) { var p models.Product decoder := decoder.NewDecoder() err := decoder.DecodeReqBody(&p, r.Body) if err != nil { rj := NewResponseJSON(nil, err) writeBack(w, r, rj) return } err = p.Delete() rj := NewResponseJSON("Product deleted successully", err) writeBack(w, r, rj) } <file_sep>/README.md # labEngSoft2_Estoque ## Dependencias Para usar o projeto, uma das dependencias adicionada foi: 1. go-sqlite3. 2. gorm ## Instalação - para instalar as dependências e criar as tabelas necessárias, execute - ```$ chmod a+x install.sh``` - ```$ ./install.sh``` <file_sep>/test/server_test.go package server_test import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "strings" "testing" "github.com/rcmgleite/labSoft2_Estoque/models" "github.com/rcmgleite/labSoft2_Estoque/requestHelper" ) //responseJSON type responseJSON struct { ResponseBody interface{} Error string } func getJSON(object interface{}) ([]byte, error) { if object != nil { return json.Marshal(object) } return nil, nil } func parseJSON(encodedJSON io.ReadCloser, object interface{}) { decoder := json.NewDecoder(encodedJSON) decoder.Decode(object) } // 1) Request to add product to db func TestCase1(t *testing.T) { var p models.Product p.Name = "test_product" p.Description = "test_descr" p.CurrQuantity = 100 p.MinQuantity = 200 p.Type = 2 headers := make(map[string]string) headers["Content-Type"] = "application/json" bJSON, err := getJSON(p) if err != nil { t.Error(err) } else { resp, err := requestHelper.MakeRequest("POST", "http://127.0.0.1:8080/product", bJSON, headers) if err != nil { t.Error(err) } body, _ := ioutil.ReadAll(resp.Body) if !strings.Contains(string(body), "Product successfully saved") { t.Error(string(body)) } } } // 2) Query for the product saved func TestCase2(t *testing.T) { headers := make(map[string]string) headers["Content-Type"] = "application/json" resp, err := requestHelper.MakeRequest("GET", "http://127.0.0.1:8080/product", nil, headers) if err != nil { t.Error(err) } var rj responseJSON parseJSON(resp.Body, &rj) bJSON, err := getJSON(rj.ResponseBody) var products []models.Product reader := bytes.NewReader(bJSON) decoder := json.NewDecoder(reader) decoder.Decode(&products) if len(products) != 1 { t.Error("Wrong number of products inserted on database") } if products[0].Name != "test_product" { t.Error("Wrong product.Name") } } // 3) Verify if order was created func TestCase3(t *testing.T) { headers := make(map[string]string) headers["Content-Type"] = "application/json" resp, err := requestHelper.MakeRequest("GET", "http://127.0.0.1:8080/order", nil, headers) if err != nil { t.Error(err) } var rj responseJSON parseJSON(resp.Body, &rj) bJSON, err := getJSON(rj.ResponseBody) var order models.Order reader := bytes.NewReader(bJSON) decoder := json.NewDecoder(reader) decoder.Decode(&order) if len(order.Products) != 1 { t.Error("Wrong number of products on order") } if order.Products[0].Name != "test_product" { t.Error("Wrong product.Name") } } // 4) Simple Query func TestCase4(t *testing.T) { // I) Creating more entries var p models.Product p.Name = "test_product2" p.Description = "test_descr2" p.CurrQuantity = 100 p.MinQuantity = 200 p.Type = 3 headers := make(map[string]string) headers["Content-Type"] = "application/json" bJSON, _ := getJSON(p) requestHelper.MakeRequest("POST", "http://127.0.0.1:8080/product", bJSON, headers) p.Name = "test_product3" p.Description = "test_descr3" p.CurrQuantity = 300 p.MinQuantity = 200 p.Type = 4 bJSON, _ = getJSON(p) requestHelper.MakeRequest("POST", "http://127.0.0.1:8080/product", bJSON, headers) p.Name = "test_product4" p.Description = "test_descr4" p.CurrQuantity = 100 p.MinQuantity = 200 p.Type = 5 bJSON, _ = getJSON(p) requestHelper.MakeRequest("POST", "http://127.0.0.1:8080/product", bJSON, headers) // Query for this new objects added resp, err := requestHelper.MakeRequest("GET", "http://127.0.0.1:8080/product", nil, headers) if err != nil { t.Error(err) } var rj responseJSON parseJSON(resp.Body, &rj) bJSON, err = getJSON(rj.ResponseBody) var products []models.Product reader := bytes.NewReader(bJSON) decoder := json.NewDecoder(reader) decoder.Decode(&products) if len(products) != 4 { t.Error("Wrong number of products inserted on database") } if products[0].Name != "test_product" { t.Error("Wrong product.Name") } if products[1].Name != "test_product2" { t.Error("Wrong product.Name") } if products[2].Name != "test_product3" { t.Error("Wrong product.Name") } if products[3].Name != "test_product4" { t.Error("Wrong product.Name") } } // 5) Update func TestCase5(t *testing.T) { // I) Update the item with id = 1 headers := make(map[string]string) headers["Content-Type"] = "application/json" var toUpdate models.Product toUpdate.ID = 1 toUpdate.Name = "test_product_updated" //Original was test_product toUpdate.Description = "test_descr_updated" //Original was test_descr toUpdate.Type = 3 //Original was 2 toUpdate.CurrQuantity = 150 //Original was 100 toUpdate.MinQuantity = 250 //Original was 200 bJSON, err := getJSON(toUpdate) if err == nil { _, err := requestHelper.MakeRequest("PUT", "http://127.0.0.1:8080/product", bJSON, headers) if err != nil { fmt.Println(err) } } // Query the item with id = 1 and verify if the update worked resp, err := requestHelper.MakeRequest("GET", "http://127.0.0.1:8080/product?ID=1", nil, headers) if err != nil { t.Error(err) } var rj responseJSON parseJSON(resp.Body, &rj) bJSON, err = getJSON(rj.ResponseBody) var products []models.Product reader := bytes.NewReader(bJSON) decoder := json.NewDecoder(reader) decoder.Decode(&products) if len(products) != 1 { t.Error("Wrong length for products") } p := products[0] if p.Name != "test_product_updated" || p.Description != "test_descr_updated" || p.Type != 3 || p.CurrQuantity != 150 || p.MinQuantity != 250 { t.Error("Update didn't worked") } } <file_sep>/models/product.go package models import ( "errors" "github.com/rcmgleite/labSoft2_Estoque/database" ) const ( //FOOD ... FOOD = 1 << iota //CLEANING ... CLEANING //ROOMITENS ... ROOMITENS // towels, bed sheets ) // ProductToSend ... type ProductToSend struct { ProductID int `json:"produto_id"` Valor float64 `json:"valor"` Quantidade int `json:"quantidade"` } // ProductToConsume ... type ProductToConsume struct { ID int Quantity int } //Product struct that defines a product type Product struct { BaseModel `sql:"-" json:",omitempty"` // Ignore this field ID int Name string `sql:"size:255"` Type int Description string `sql:"size:255"` CurrQuantity int MinQuantity int } //Save .. func (p *Product) Save() error { db := database.GetDatabase() err := db.Create(p).Error if err != nil { return err } if p.NeedRefill() { AddProductToOpenOrder(*p) } return err } // Update ... func (p *Product) Update() error { db := database.GetDatabase() err := db.Save(p).Error if err != nil { return err } if p.NeedRefill() { AddProductToOpenOrder(*p) } else if has, err := OpenOrderHasProduct(*p); has && err == nil { RemoveProductFromOpenOrder(*p) } return err } // Delete ... func (p *Product) Delete() error { db := database.GetDatabase() return db.Delete(p).Error } //Retreive ... it uses the object and a plain query to execute sql cmds func (p *Product) Retreive() ([]Product, error) { db := database.GetDatabase() var query string if p.QueryParams != nil { query = buildQuery(p.QueryParams) } orderBy := p.QueryParams["order_by"] var products []Product var err error //Remove queryParams p.QueryParams = nil if orderBy != "" { err = db.Order(orderBy).Where(*p).Find(&products, query).Error } else { err = db.Where(*p).Find(&products, query).Error } return products, err } // Consume ... func (p *Product) Consume(quantity int) error { db := database.GetDatabase() var pp Product err := db.Where(*p).First(&pp).Error if err != nil { return err } if pp.CurrQuantity-quantity < 0 { return errors.New("Requested quantity exceeds the available amount") } pp.CurrQuantity = pp.CurrQuantity - quantity err = pp.Update() if err != nil { return err } return nil } //NeedRefill verify if product need refill func (p *Product) NeedRefill() bool { if p.CurrQuantity < p.MinQuantity { return true } return false } <file_sep>/orderController.go package main import ( "net/http" "github.com/rcmgleite/labSoft2_Estoque/decoder" "github.com/rcmgleite/labSoft2_Estoque/models" ) // GETOrderHandler ... func GETOrderHandler(w http.ResponseWriter, r *http.Request) { var o models.Order models.GetOpenOrder(&o) rj := NewResponseJSON(o, nil) writeBack(w, r, rj) } // PUTOrderHandler ... func PUTOrderHandler(w http.ResponseWriter, r *http.Request) { var order models.Order decoder := decoder.NewDecoder() err := decoder.DecodeReqBody(&order, r.Body) if err != nil { rj := NewResponseJSON(nil, err) writeBack(w, r, rj) return } err = order.Update() if err != nil { rj := NewResponseJSON(nil, err) writeBack(w, r, rj) return } rj := NewResponseJSON("Order updated successfully", err) writeBack(w, r, rj) } // DELETEOrderHandler ... func DELETEOrderHandler(w http.ResponseWriter, r *http.Request) { var order models.Order decoder := decoder.NewDecoder() err := decoder.DecodeReqBody(&order, r.Body) if err != nil { rj := NewResponseJSON(nil, err) writeBack(w, r, rj) return } err = order.Delete() rj := NewResponseJSON("Order deleted successfully", err) writeBack(w, r, rj) } <file_sep>/server.go package main import ( "fmt" "net/http" "github.com/rcmgleite/router" ) func main() { r := router.NewRouter() // /product r.AddRoute("/product", router.GET, GETProductHandler) r.AddRoute("/product", router.POST, POSTProductHandler) r.AddRoute("/product", router.PUT, PUTProductHandler) r.AddRoute("/product", router.DELETE, DELETEProductHandler) r.AddRoute("/product/query", router.POST, POSTQueryProductHandler) r.AddRoute("/product/consume", router.POST, POSTConsumeProductHandler) // /order r.AddRoute("/order", router.GET, GETOrderHandler) r.AddRoute("/order", router.PUT, PUTOrderHandler) r.AddRoute("/order", router.DELETE, DELETEOrderHandler) fmt.Println("Server running on port: 8080") http.ListenAndServe(":8080", r) } <file_sep>/database/database.go package database import ( "os" "strconv" "github.com/jinzhu/gorm" //Blank import needed to call init from go-sqlite3() _ "github.com/mattn/go-sqlite3" ) const ( databaseType = "sqlite3" databaseFile = "./estoque.db" databaseTestFile = "./estoque_test.db" ) //GetDatabase ... func GetDatabase() *gorm.DB { testing, _ := strconv.ParseBool(os.Getenv("TEST")) var dbPath string if testing { dbPath = databaseTestFile } else { dbPath = databaseFile } db, err := gorm.Open(databaseType, dbPath) if err != nil { panic(err) } return &db } <file_sep>/createDatabase.sql CREATE TABLE "products" ( "id" integer, "name" varchar(255), "type" integer, "description" varchar(255), "curr_quantity" integer, "min_quantity" integer , PRIMARY KEY (id) ); CREATE TABLE "order_products" ( "order_id" integer, "product_id" integer ); CREATE TABLE "orders" ( "id" integer, "approved" bool , PRIMARY KEY (id) ); <file_sep>/install.sh clear # 1) clean up previous installation echo '> Cleaning up previous installation...' initialDir=$(pwd) echo '> Entering $GOPATH/bin dir at: '$GOPATH cd $GOPATH/bin rm -rf views/ labSoft2_Estoque cd $initialDir echo '>> Done!' # 2) Execute go install echo '> Preparing to execute "go install"...' go install echo '>> Done!' echo '>> Installation Complete!' # 3) creating database if one is not already created if [[ $1 = "-test" ]] then dbName=estoque_test.db export TEST=true else export TEST=false dbName=estoque.db fi cd $GOPATH/bin if [[ -f $dbName ]] then echo '> Skipping Database creation...' cd $initialDir else cd $initialDir sqlite3 $dbName < createDatabase.sql # create database estoque.db cd $GOPATH/bin # cd to $GOPATH/bin rm -rf $dbName # remove old db cd $initialDir # return to initialDir mv $dbName $GOPATH/bin # move new db to $GOPATH/bin echo '>> Done creating db!' fi echo 'Executing server...' cd $GOPATH/bin ./labSoft2_Estoque
7837114c19ef92b0a8dfe83425815e6e562e1ca8
[ "SQL", "Markdown", "Text", "Go", "Shell" ]
13
Go
rcmgleite/labSoft2_Estoque
d23844973896f93f4ccba7dfcfca74589301eae5
9119bde26f6287c44213645dd94957fe3b46586c
refs/heads/master
<file_sep>interface NodeModule { // Inserted by React hot loader hot: any; // TODO: Make this tighter } <file_sep>import { FSA } from 'types/redux'; export default async function runThunk( action: FSA | Function, dispatch: Function, getState: Function = () => {}, ) { if (typeof action === 'function') { const p = action( (nextAction: FSA | Function) => runThunk(nextAction, dispatch, getState), getState, ); if (p instanceof Promise) { await p; } } else { dispatch(action); } } <file_sep>import { FETCH_VENUE_LIST } from 'actions/venueBank'; import { SUCCESS, VenueBank } from 'types/reducers'; import { FSA } from 'types/redux'; const defaultModuleBankState: VenueBank = { venueList: [], // List of venue strings }; function venueBank(state: VenueBank = defaultModuleBankState, action: FSA): VenueBank { switch (action.type) { case FETCH_VENUE_LIST + SUCCESS: return { ...state, venueList: action.payload, }; default: return state; } } export default venueBank; export const persistConfig = { throttle: 1000, }; <file_sep>// Recursively retry fn until success, retries has been reached, or shouldRetry returns false. // Based on https://stackoverflow.com/a/30471209/5281021 // TODO: Remove eslint-disable-line comment when other functions have been added to this file export function retry<T>( // eslint-disable-line import/prefer-default-export retries: number, fn: () => Promise<T>, shouldRetry: (error: Error) => boolean = () => true, ): Promise<T> { return fn().catch((err) => { if (retries <= 0 || !shouldRetry(err)) { throw err; } return retry(retries - 1, fn, shouldRetry); }); } <file_sep>/** moduleBank constants * */ export const FETCH_MODULE = 'FETCH_MODULE'; // Action to fetch modules export const FETCH_MODULE_LIST = 'FETCH_MODULE_LIST'; export const UPDATE_MODULE_TIMESTAMP = 'UPDATE_MODULE_TIMESTAMP'; export const REMOVE_LRU_MODULE = 'REMOVE_LRU_MODULE'; export const FETCH_ARCHIVE_MODULE = 'FETCH_ARCHIVE_MODULE'; // Action to fetch module from previous years /** undoHistory constants * */ export const UNDO = 'UNDO'; export const REDO = 'REDO'; /** export constant(s) * */ export const SET_EXPORTED_DATA = 'SET_EXPORTED_DATA'; <file_sep>/** * Small utility functions that don't need to be part of the main API class */ import { Semester } from '../types/modules'; import { Cache } from '../types/persist'; import rootLogger, { Logger } from '../services/logger'; /** * Construct the 4 number term code from the academic year and semester */ export function getTermCode(semester: number | string, academicYear: string) { const year = /\d\d(\d\d)/.exec(academicYear); if (!year) throw new RangeError('academicYear should be in the format of YYYY/YYYY or YYYY-YY'); return `${year[1]}${semester}0`; } /** * Extract the academic year and semester from a term code */ export function fromTermCode(term: string): [string, Semester] { const year = parseInt(term.slice(0, 2), 10); const semester = parseInt(term.charAt(2), 10); return [`20${year}/20${year + 1}`, semester]; } /** * Cache and return download if it succeeds, otherwise return cached data if * it has not expired yet */ export async function cacheDownload<T>( name: string, download: () => Promise<T>, cache: Cache<T>, logger: Logger = rootLogger, ): Promise<T> { try { // Try to download the data, and if successful cache it const data = await download(); try { await cache.write(data); } catch (err) { logger.warn({ err, path: cache.path }, 'Failed to cache data'); } return data; } catch (downloadError) { // If the file is not available we try to load it from cache instead logger.warn(downloadError, `Cannot load ${name} from API, attempting to read from cache`); try { // Deliberately awaiting on cache.read() to catch read errors return await cache.read(); } catch (cacheError) { // Rethrow the download error if the cache is not available since an ENOTFOUND or // CacheExpiredError is usually not helpful throw downloadError; } } } /** * Retries the given promise */ export async function retry<T>( promiseFactory: () => Promise<T>, maxRetries: number, retryIf: (error: Error) => boolean = () => true, ): Promise<T> { try { return await promiseFactory(); } catch (e) { // If we run out of tries, or if the given condition is not fulfilled, we // don't retry if (maxRetries <= 1 || !retryIf(e)) throw e; return retry(promiseFactory, maxRetries - 1, retryIf); } } <file_sep>import academicCalendarJSON from './academic-calendar.json'; // Force TS to accept our typing instead of inferring from the JSON type DateTuple = [number, number, number]; const academicCalendar: { [year: string]: { [semester: string]: { start: DateTuple }; }; } = academicCalendarJSON as any; // eslint-disable-line @typescript-eslint/no-explicit-any export default academicCalendar; <file_sep>import { Reducer } from 'redux'; import { PersistConfig, Persistor } from 'redux-persist/lib/types'; import { persistReducer as basePersistReducer } from 'redux-persist'; import storage from 'redux-persist/lib/storage'; // Re-export type for easier consumption in other parts of the project export { PersistConfig, Persistor }; /** * Wrapper function around persistReducer from Redux Persist. */ export default function persistReducer( key: string, reducer: Reducer<any, any>, options: Pick< PersistConfig, Exclude<keyof PersistConfig, keyof { key: string; storage: Record<string, any> }> > = {}, ) { return basePersistReducer<any, any>( { key, storage, debug: process.env.NODE_ENV !== 'production', ...options, }, reducer, ); } <file_sep>/** * Various utility types and type utilities for making working with TypeScript * easier */ /* eslint-disable @typescript-eslint/no-explicit-any */ export type Omit<T, K> = Pick<T, Exclude<keyof T, K>>; export const EMPTY_ARRAY: readonly any[] = []; export const notFalsy = (Boolean as any) as <T>(x: T | false) => x is T; export const notNull = <T>(x: T | null | undefined): x is T => x != null; export const parseFloat = (float: number | string): number => typeof float === 'string' ? window.parseFloat(float) : float; <file_sep>import { requestAction } from 'actions/requests'; import NUSModsApi from 'apis/nusmods'; import config from 'config'; import { flatMap, get, size, sortBy, zip } from 'lodash'; import { ModulesMap } from 'types/reducers'; import { AcadYear, Module, ModuleCode } from 'types/modules'; import { GetState } from 'types/redux'; import { TimetableConfig } from 'types/timetables'; import { FETCH_ARCHIVE_MODULE, FETCH_MODULE, FETCH_MODULE_LIST, REMOVE_LRU_MODULE, UPDATE_MODULE_TIMESTAMP, } from './constants'; const MAX_MODULE_LIMIT = 100; export function fetchModuleList() { return requestAction(FETCH_MODULE_LIST, FETCH_MODULE_LIST, { url: NUSModsApi.moduleListUrl(), }); } export function fetchModuleRequest(moduleCode: ModuleCode) { return `${FETCH_MODULE}/${moduleCode}`; } export function getRequestModuleCode(key: string): ModuleCode | null { const parts = key.split('/'); if (parts.length === 2 && parts[0] === FETCH_MODULE) return parts[1]; return null; } export function updateModuleTimestamp(moduleCode: ModuleCode) { return { type: UPDATE_MODULE_TIMESTAMP, payload: moduleCode, }; } export function removeLRUModule(moduleCodes: ModuleCode[]) { return { type: REMOVE_LRU_MODULE, payload: moduleCodes, }; } // Export for testing export function getLRUModules( modules: ModulesMap, lessons: TimetableConfig, currentModule: string, toRemove: number = 1, ): ModuleCode[] { // Pull all the modules in all the timetables const timetableModules = new Set(flatMap(lessons, (semester) => Object.keys(semester))); // Remove the module which is least recently used and which is not in timetable // and not the currently loaded one const canRemove: ModuleCode[] = Object.keys(modules).filter( (moduleCode) => moduleCode !== currentModule && !timetableModules.has(moduleCode), ); // Sort them based on the timestamp alone const sortedModules = sortBy<ModuleCode>(canRemove, (moduleCode) => get(modules[moduleCode], ['timestamp'], 0), ); return sortedModules.slice(0, toRemove); } export function fetchModule(moduleCode: ModuleCode) { return (dispatch: Function, getState: GetState) => { const onFinally = () => { // Update the timestamp of the accessed module if it is in the store. if (getState().moduleBank.modules[moduleCode]) { dispatch(updateModuleTimestamp(moduleCode)); } // Remove the LRU module if the size exceeds the maximum and if anything // can be removed const overLimitCount = size(getState().moduleBank.modules) - MAX_MODULE_LIMIT; if (overLimitCount > 0) { const { moduleBank, timetables } = getState(); const LRUModule = getLRUModules( moduleBank.modules, timetables.lessons, moduleCode, overLimitCount, ); if (LRUModule) { dispatch(removeLRUModule(LRUModule)); } } }; const key = fetchModuleRequest(moduleCode); return dispatch( requestAction(key, FETCH_MODULE, { url: NUSModsApi.moduleDetailsUrl(moduleCode), }), ).then( (result: any) => { onFinally(); return result; }, (error: any) => { onFinally(); throw error; }, ); }; } export function fetchArchiveRequest(moduleCode: ModuleCode, year: string) { return `${FETCH_ARCHIVE_MODULE}_${moduleCode}_${year}`; } export function fetchModuleArchive(moduleCode: ModuleCode, year: string) { const key = fetchArchiveRequest(moduleCode, year); const action = requestAction(key, FETCH_ARCHIVE_MODULE, { url: NUSModsApi.moduleDetailsUrl(moduleCode, year), }); action.meta.academicYear = year; return action; } export function fetchAllModuleArchive(moduleCode: ModuleCode) { // Returns: Promise<[AcadYear, Module?][]> return (dispatch: Function) => Promise.all( config.archiveYears.map((year) => dispatch(fetchModuleArchive(moduleCode, year)).catch(() => null), ), ).then((modules) => zip<AcadYear, Module[]>(config.archiveYears, modules)); } <file_sep>import { FSA } from 'types/redux'; import { Requests, FAILURE, REQUEST, SUCCESS } from 'types/reducers'; import { API_REQUEST } from 'actions/requests'; export default function requests(state: Requests = {}, action: FSA): Requests { const { meta } = action; // requestStatus is a field specially designed and owned by api request actions if (!meta || !meta.requestStatus || !meta[API_REQUEST]) { return state; } const key = meta[API_REQUEST]; switch (meta.requestStatus) { case REQUEST: return { ...state, [key]: { status: REQUEST, }, }; case SUCCESS: return { ...state, [key]: { status: SUCCESS, }, }; case FAILURE: return { ...state, [key]: { status: FAILURE, error: action.payload, }, }; default: return state; } } <file_sep>import { REHYDRATE } from 'redux-persist'; import { FSA } from 'types/redux'; export function initAction(): FSA { return { type: 'INIT', payload: null, }; } export function rehydrateAction(): FSA { return { type: REHYDRATE, payload: null, }; } <file_sep>import { FSA } from 'types/redux'; export const SELECT_THEME = 'SELECT_THEME'; export function selectTheme(theme: string): FSA { return { type: SELECT_THEME, payload: theme, }; } export const CYCLE_THEME = 'CYCLE_THEME'; export function cycleTheme(offset: number): FSA { return { type: CYCLE_THEME, payload: offset, }; } export const TOGGLE_TIMETABLE_ORIENTATION = 'TOGGLE_TIMETABLE_ORIENTATION'; export function toggleTimetableOrientation(): FSA { return { type: TOGGLE_TIMETABLE_ORIENTATION, payload: null, }; } export const TOGGLE_TITLE_DISPLAY = 'TOGGLE_TITLE_DISPLAY'; export function toggleTitleDisplay(): FSA { return { type: TOGGLE_TITLE_DISPLAY, payload: null, }; } <file_sep>// TypeScript black magic to extract keys of ModuleInformation which are strings export type StringProperties<T> = Exclude< { [K in keyof T]: T[K] extends string | undefined ? K : never }[keyof T], undefined >; export interface ElasticSearchResult<T> { _id: string; _score: number; _type: string; _index: string; _source: T; highlight?: Partial<Record<StringProperties<T>, string[]>>; } <file_sep>import { ModuleCode, Semester } from 'types/modules'; import { FSA } from 'types/redux'; import { CustomModule } from 'types/planner'; export const SET_PLANNER_MIN_YEAR = 'SET_PLANNER_MIN_YEAR'; export function setPlannerMinYear(year: string) { return { type: SET_PLANNER_MIN_YEAR, payload: year, }; } export const SET_PLANNER_MAX_YEAR = 'SET_PLANNER_MAX_YEAR'; export function setPlannerMaxYear(year: string) { return { type: SET_PLANNER_MAX_YEAR, payload: year, }; } export const SET_PLANNER_IBLOCS = 'SET_PLANNER_IBLOCS'; export function setPlannerIBLOCs(iblocs: boolean) { return { type: SET_PLANNER_IBLOCS, payload: iblocs, }; } export const ADD_PLANNER_MODULE = 'ADD_PLANNER_MODULE'; export function addPlannerModule( moduleCode: ModuleCode, year: string, semester: Semester, index: number | null = null, ): FSA { return { type: ADD_PLANNER_MODULE, payload: { year, semester, moduleCode, index, }, }; } export const MOVE_PLANNER_MODULE = 'MOVE_PLANNER_MODULE'; export function movePlannerModule( moduleCode: ModuleCode, year: string, semester: Semester, index: number | null = null, ): FSA { return { type: MOVE_PLANNER_MODULE, payload: { year, semester, moduleCode, index, }, }; } export const REMOVE_PLANNER_MODULE = 'REMOVE_PLANNER_MODULE'; export function removePlannerModule(moduleCode: ModuleCode): FSA { return { type: REMOVE_PLANNER_MODULE, payload: { moduleCode, }, }; } export const ADD_CUSTOM_PLANNER_DATA = 'ADD_CUSTOM_PLANNER_DATA'; export function addCustomModule(moduleCode: ModuleCode, data: CustomModule): FSA { return { type: ADD_CUSTOM_PLANNER_DATA, payload: { moduleCode, data }, }; } <file_sep>import { ModuleCode } from 'types/modules'; import config from 'config'; import { isOngoing, isSuccess } from 'selectors/requests'; import { fetchArchiveRequest } from 'actions/moduleBank'; import { State } from 'types/state'; export function isArchiveLoading(state: State, moduleCode: ModuleCode) { return config.archiveYears.some((year) => isOngoing(state, fetchArchiveRequest(moduleCode, year)), ); } export function availableArchive(state: State, moduleCode: ModuleCode): string[] { return config.archiveYears.filter((year) => isSuccess(state, fetchArchiveRequest(moduleCode, year)), ); } <file_sep>import { State } from './state'; // Flux Standard Action: https://github.com/acdlite/flux-standard-action export type FSA = { type: string; payload: any; meta?: any; error?: boolean; }; export type GetState = () => State; <file_sep>/* eslint-disable import/prefer-default-export */ export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>; // Remove types from T that are assignable to U <file_sep>import { FSA } from 'types/redux'; import { REDO, UNDO } from './constants'; export function undo(): FSA { return { type: UNDO, payload: null }; } export function redo(): FSA { return { type: REDO, payload: null }; } <file_sep>#!/usr/bin/env bash # Starts a production instance of NUSMods. # Usage: start-prod.sh <port to expose NUSMods on> # Exit when any command fails set -e # Echo commands set -x # Port where NUSMods will be bound to export EXPOSED_PORT=$1 if [ -z "$EXPOSED_PORT" ]; then echo "No port number provided!" exit 1 fi # Navigate to project root pushd ../.. # Start docker-compose export GIT_COMMIT_HASH=$(git rev-parse HEAD) docker-compose -f docker-compose.prod.yml build --no-cache docker-compose -f docker-compose.prod.yml up docker-compose -f docker-compose.prod.yml down --remove-orphans <file_sep>import { Module } from 'types/modules'; import ACC2002_JSON from './ACC2002.json'; import BFS1001_JSON from './BFS1001.json'; import CS1010S_JSON from './CS1010S.json'; import CS3216_JSON from './CS3216.json'; import CS4243_JSON from './CS4243.json'; import GES1021_JSON from './GES1021.json'; import PC1222_JSON from './PC1222.json'; // Have to cast these as Module explicitly, otherwise TS will try to // incorrectly infer the shape from the JSON - specifically Weeks will // not be cast correctly export const CS1010S: Module = CS1010S_JSON; export const ACC2002: Module = ACC2002_JSON; export const BFS1001: Module = BFS1001_JSON; export const CS3216: Module = CS3216_JSON; export const GES1021: Module = GES1021_JSON; export const PC1222: Module = PC1222_JSON; export const CS4243: Module = CS4243_JSON; const modules: Module[] = [ACC2002, BFS1001, CS1010S, CS3216, GES1021, PC1222]; export default modules; <file_sep>import { requestAction } from 'actions/requests'; import NUSModsApi from 'apis/nusmods'; import config from 'config'; export const FETCH_VENUE_LIST = 'FETCH_VENUE_LIST'; export function fetchVenueList() { return requestAction(FETCH_VENUE_LIST, { url: NUSModsApi.venueListUrl(config.semester), }); } <file_sep>import { addWeeks, startOfWeek, isBefore, getYear } from 'date-fns'; /* eslint-disable no-fallthrough, no-console */ /** * Returns a Date object of the first weekday of Week 0 of that academic year. * Assumes Week 0 begins on the first Monday of August. * @param acadYear the academic year. E.g. "18/19" * @return {Date} Start date of the academic year */ export function getAcadYearStartDate(acadYear) { const shortYear = acadYear.split('/')[0]; const targetYear = 2000 + parseInt(shortYear, 10); const firstDateOfMonth = new Date(targetYear, 7, 1, 0, 0, 0); const nearestMonday = startOfWeek(firstDateOfMonth, { weekStartsOn: 1 }); if (isBefore(nearestMonday, firstDateOfMonth)) { const firstMonday = addWeeks(nearestMonday, 1); return firstMonday; } // 1st Aug is already a Monday return nearestMonday; } // Constant variables. const oneWeekDuration = 1000 * 60 * 60 * 24 * 7; const sem1 = 'Semester 1'; const sem2 = 'Semester 2'; const special1 = 'Special Term I'; const special2 = 'Special Term II'; /** * Takes in a Date and returns an object of acad year and start date for that year. * @param {Date} date * @return {Object} acadYearObject - { year: "15/16", startDate: Date } */ export function getAcadYear(date) { const shortYear = getYear(date) % 100; // A date like 8th August 2015 can either be in AY15/16 or AY16/17. We check // the date against the start of AY15/16 and return the correct one. const potentialAcadYear = `${shortYear}/${shortYear + 1}`; const potentialStartDate = getAcadYearStartDate(potentialAcadYear); const year = isBefore(date, potentialStartDate) ? `${shortYear - 1}/${shortYear}` : potentialAcadYear; return { year, startDate: getAcadYearStartDate(year), }; } /** * Computes the current academic semester. * Expects a week number of a year. * @param {number} acadWeekNumber * @return {string} semester - "Semester 1" * @example acadWeekNumber(3) */ export function getAcadSem(acadWeekNumber) { const earliestSupportedWeek = 1; const lastWeekOfSem1 = 23; const lastWeekOfSem2 = 40; const lastWeekOfSpecialSem1 = 46; const lastWeekOfSpecialSem2 = 52; if (acadWeekNumber < earliestSupportedWeek) { console.warn(`[nusmoderator] Unsupported acadWeekNumber: ${acadWeekNumber}`); return null; } if (acadWeekNumber <= lastWeekOfSem1) return sem1; if (acadWeekNumber <= lastWeekOfSem2) return sem2; if (acadWeekNumber <= lastWeekOfSpecialSem1) return special1; if (acadWeekNumber <= lastWeekOfSpecialSem2) return special2; console.warn(`[nusmoderator] Unsupported acadWeekNumber: ${acadWeekNumber}`); return null; } /** * Computes the current academic week of the semester * Expects a week number of a semester. * @param {number} acadWeekNumber * @return {string} semester - "Recess" | "Reading" | "Examination" * @example acadWeekNumber(3) */ export function getAcadWeekName(acadWeekNumber) { switch (acadWeekNumber) { case 7: return { weekType: 'Recess', weekNumber: null, }; case 15: return { weekType: 'Reading', weekNumber: null, }; case 16: case 17: return { weekType: 'Examination', weekNumber: acadWeekNumber - 15, }; default: { let weekNumber = acadWeekNumber; if (weekNumber >= 8) { // For weeks after recess week weekNumber -= 1; } if (acadWeekNumber < 1 || acadWeekNumber > 17) { console.warn(`[nusmoderator] Unsupported acadWeekNumber as parameter: ${acadWeekNumber}`); return null; } return { weekType: 'Instructional', weekNumber, }; } } } /** * Computes the current academic week and return in an object of acad date components * @param {Date} date * @return {Object} * { * year: "15/16", * sem: 'Semester 1'|'Semester 2'|'Special Sem 1'|'Special Sem 2', * type: 'Instructional'|'Reading'|'Examination'|'Recess'|'Vacation'|'Orientation', * num: <weekNum> * } */ export function getAcadWeekInfo(date) { const currentAcad = getAcadYear(date); const acadYear = currentAcad.year; const acadYearStartDate = getAcadYearStartDate(acadYear); let acadWeekNumber = Math.ceil( (date.getTime() - acadYearStartDate.getTime() + 1) / oneWeekDuration, ); const semester = getAcadSem(acadWeekNumber); let weekType = null; let weekNumber = null; switch (semester) { case sem2: // Semester 2 starts 22 weeks after Week 1 of semester 1 acadWeekNumber -= 22; case sem1: if (acadWeekNumber === 1) { weekType = 'Orientation'; break; } if (acadWeekNumber > 18) { weekType = 'Vacation'; weekNumber = acadWeekNumber - 18; break; } acadWeekNumber -= 1; ({ weekType, weekNumber } = getAcadWeekName(acadWeekNumber)); break; case special2: // Special Term II starts 6 weeks after Special Term I acadWeekNumber -= 6; case special1: // Special Term I starts on week 41 of the AY acadWeekNumber -= 40; weekType = 'Instructional'; weekNumber = acadWeekNumber; break; default: if (acadWeekNumber === 53) { // This means it is the 53th week of the AY, and this week is Vacation. // This happens 5 times every 28 years. weekType = 'Vacation'; weekNumber = null; } break; } return { year: acadYear, sem: semester, type: weekType, num: weekNumber, }; } /** * Get the first day of the exam week for the given semester * @param {string} year * @param {number} semester * @returns {Date} */ export function getExamWeek(year, semester) { const startDate = getAcadYearStartDate(year); if (!startDate) { console.warn(`[nusmoderator] Unsupported year: ${year}`); return null; } const examWeek = { 1: 16, 2: 38, 3: 45, 4: 51, }; const weeks = examWeek[semester]; if (!weeks) { console.warn(`[nusmoderator] Unknown semester: ${semester}`); return null; } const d = new Date(startDate.valueOf()); d.setDate(startDate.getDate() + weeks * 7); return d; } export default { getAcadYearStartDate, getAcadYear, getAcadSem, getAcadWeekName, getAcadWeekInfo, getExamWeek, };
9fd7429ab94751329fe0389a7cc28a30c5c13574
[ "JavaScript", "TypeScript", "Shell" ]
23
TypeScript
JingYenLoh/nusmods
3880e588b42cfa1086cbc15710aa32fbc86d794c
12233fc371955c274cdfce25d3b4e519fffd3b6b
refs/heads/master
<file_sep>package semaforo; public class LuzVerdeEnLa27 extends Thread { @Override public void run() { System.out.println("********************************************************************************************************************************"); int paRojo = 50; Thread luzVerdeEn27 = new Thread(); for(int x = 50; x>0;x--) { try { if(x >=6) { System.out.println("Av.27 de Febrero en LUZ VERDE...... Segundos restantes: "+(x-5)+"\t*\tAv.<NAME> en LUZ ROJA... Segundos Restantes: "+paRojo); luzVerdeEn27.sleep(1000); paRojo = paRojo - 1; } } catch (InterruptedException ex) { System.out.println("Pare y siga las instrucciones del AMET..."); } } } } <file_sep>package semaforo; public class LuzAmarillaEnLa27 extends Thread{ //int paRojo = 5; @Override public void run() { Thread luzAmarillaEn27 = new LuzAmarillaEnLa27(); for (int x = 5; x > 0; x--) { try { System.out.println("Av.27 de Febrero en LUZ AMARILLA... Segundos restantes: "+x+"\t*\tAv.<NAME> en LUZ ROJA... Segundos Restantes: "+x); luzAmarillaEn27.sleep(1000); //paRojo = paRojo - 1; } catch (InterruptedException ex) { System.out.println("Pare y siga las instrucciones del AMET..."); } } } } <file_sep>package semaforo; public class Semaforo extends Thread{ public static void main(String[] args) throws InterruptedException { LlamaLuces inicia = new LlamaLuces(); System.out.println("\t\t\t\t\t\t\tSyC Software\n\n" + "\t\tSemafor de la Av.27 de Febrero\t\t\t\t\tSemafor de la Av.Abraham Lincoln\n"); boolean on = true; while(on == true) { inicia.CorriendoHilos(); } } }
3464ef96cd29673dc4f7388f2730867f0e39fbfc
[ "Java" ]
3
Java
Sergio2805/Programacion1_Tarea4_Semaforo
1132809cc661fc5873cce9fb82cf942e44921b30
cdf1c3398575ef335f9e4a1274788ac3682519ae
refs/heads/master
<file_sep>"""FruitsShop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url,include from django.contrib import admin from django.views.static import serve from FruitsShop import settings from fruits.views import index import xadmin urlpatterns = [ url(r'^cart/',include('cat.urls')), url(r'^order/',include('orders.urls')), url(r'^ueditor/',include('DjangoUeditor.urls')), url(r'^user/',include('users.urls')), url(r'^fruits/',include('fruits.urls')), url(r'^$',index,name='index'), url(r'^captcha/',include('captcha.urls')), url(r'^media/(?P<path>.*)',serve,{'document_root':settings.MEDIA_ROOT},name='media'), url(r'^static/(?P<path>.*)',serve,{'document_root':settings.STATIC_ROOT},name='static'), url(r'^xadmin/', xadmin.site.urls), ] <file_sep>from django.shortcuts import render from django.views import View from .models import * from django.core.paginator import PageNotAnInteger,Paginator,EmptyPage from django.views.generic import ListView # Create your views here. def index(request): """ 分类 :param request: :return: """ dict = {} resp = ['fruit', 'seafood', 'meet', 'egg', 'vegetables', 'ice'] types = CommType.objects.all().order_by('id') for key, value in enumerate(types): dict[(resp[key])] = value res = {} for ty in types: res[ty.class_name] = ty.comminfo_set.all()[:4] """ 水果 obj obj obj obj """ user = request.user types = CommType.objects.all() result = {'types':dict,'goods':res} result['type'] = 'user' return render(request,'df_goods/index.html',result) def lists(request): """ type_id 商品分类 p=?页面 :param request: type_id p=? type 默认 价格 :return: """ if request.method=='GET': dict = {} resp = ['fruit', 'seafood', 'meet', 'egg', 'vegetables', 'ice'] type_id = request.GET.get('type_id') page_num = request.GET.get('p','1') comms = CommInfo.objects.filter(type_id=type_id).order_by('?')[:2] # 分页 # 默认 default type = request.GET.get('type', 'default') if type == 'default': adds = CommInfo.objects.filter(type_id=type_id) elif type == 'price': adds = CommInfo.objects.filter(type_id=type_id).order_by('-c_price') elif type == 'hot': adds = CommInfo.objects.filter(type_id=type_id).order_by('-c_click') paginator = Paginator(adds,3) page_num = int(page_num) try: page = paginator.page(page_num) except PageNotAnInteger as e: #非整数 page = paginator.page(1) except EmptyPage as e: page_num = int(page_num) #输出数字的范围 #两种情况 # 1 大于获取最后一页 # 2 小于第一页 if page_num >= paginator.num_pages: page = paginator.page(paginator.num_pages) else: page = paginator.page(1) # #页码 # 标签 types = CommType.objects.all().order_by('id') for key,value in enumerate(types): dict[resp[key]] = value result = {'comms':comms,'page':page,'types':dict,'type':type} result['type'] = 'goods' return render(request,'df_goods/list.html',result) class ListsView(ListView): goods = CommInfo.objects.all() context_object_name = 'lists' paginate_by = 3 template_name = 'df_goods/list.html' class Detail(View): def get(self,request): dict = {} result = {} res = ['fruit','seafood','meet','egg','vegetables','ice'] com_id = request.GET.get('com_id') good = CommInfo.objects.get(id=com_id) good.c_click += 1 good.save() comm = CommInfo.objects.get(id=com_id) tags = CommTags.objects.filter(comminfo=comm) types = CommType.objects.all().order_by('id') for key,value in enumerate(types): dict[(res[key])] = value # 新品推荐 goods = comm.type.comminfo_set.order_by('-id')[:2] if request.user.id: count = ShopCat.objects.filter(user=request.user).count() result['count'] = count result['com'] = comm result['tags'] = tags result['types'] = dict result['comms'] = goods result['type'] = 'goods' return render(request,'df_goods/detail.html',result) def post(self,request): pass <file_sep>from django.shortcuts import render,redirect from django.http import JsonResponse from fruits.models import * from datetime import datetime from alipay import AliPay from FruitsShop import settings import os # Create your views here. def add_order(request): if request.method == 'POST': result = {} if request.user.id: cartlist = request.POST.getlist('cartlist[]') o_money = request.POST.get('o_money',None) if len(cartlist)==1 and len(cartlist[0]) > 12: order = CommOrders.objects.get(o_id=cartlist[0]) result['status'] = 1 result['Meg'] = '订单提交成功' # 生产订单号 else: order = CommOrders() order.o_id = '{}{}'.format(datetime.now().strftime('%Y%m%H%M%S'),request.user.id) order.user = request.user order.o_money = o_money order.o_type = False order.save() for id in cartlist: try: cart = ShopCat.objects.get(id=id) orderinfo = OrderInfo(content=cart.s_num,comm=cart.comm,order=order) orderinfo.save() cart.delete() result['status'] = 1 result['Meg'] = '订单提交成功' except Exception as e: result['status'] = 0 result['Meg'] = '网络延迟,请重新提交,或刷新网页' return JsonResponse(result) # 创键用于支付宝的对象 ali_pay = AliPay( appid= settings.ALIPAY_APPID, app_private_key_path=os.path.join(settings.BASE_DIR,'keys/private'), alipay_public_key_path=os.path.join(settings.BASE_DIR,'keys/public'), app_notify_url=None, sign_type='RSA2', # 沙箱测试 False,生产True debug=False ) # 网站端的支付需要跳转的支付页面,执行支付 ##http://openapi.alipaydev.com/qateway.do?order= order_string = ali_pay.api_alipay_trade_page_pay( # 定单号 out_trade_no=order.o_id, #订单总额 total_amount= order.o_money, # 订单描述信息 subject='天天生鲜购物单-{}'.format(order.o_id), return_url='http://www.zhihu.com' ) # 拼接支付地址 url= settings.ALIPAY_URL + '?'+ order_string # 将数据返回前端,前端跳转支付界面 result['url'] = url result['o_id'] = order.o_id return JsonResponse(result) else: result['status'] = 300 return JsonResponse(result) if request.method == 'GET': # good_id = request.GET.get('good_id') pass def order(request): if request.method =="POST": result = {} res = request.POST.getlist('cartid') cart_list = [ShopCat.objects.get(comm_id=x) for x in request.POST.getlist('cartid')] result['title'] = '天天生鲜-提交订单' result['type'] = 'goods' result['cart_list'] = cart_list return render(request,'df_order/place_order.html',result) elif request.method == 'GET': result = {} o_id = request.GET.get('o_id',None) if o_id: try: orders = CommOrders.objects.get(o_id=o_id) except Exception as e: return redirect('/') else: return redirect('/') result['title'] = '天天生鲜-提交订单' result['type'] = 'goods' result['orders'] = orders result['cart_list'] = None return render(request,'df_order/place_order.html',result) def check_pay(request): if request.method == 'GET': result = {} o_id = request.GET.get('o_id') alipy = AliPay( appid=settings.ALIPAY_APPID, app_notify_url=None, app_private_key_path=os.path.join(settings.BASE_DIR,'keys/private'), alipay_public_key_path=os.path.join(settings.BASE_DIR,('keys/public')), sign_type='RSA2', debug=True ) while True: response = alipy.api_alipay_trade_query(o_id) code = response.get('code') trade_status = response.get('trade_status') print(response) if code == '10000' and trade_status == 'TRADE_SUCCESS': order = CommOrders.objects.get(o_id=o_id) orderinfos = order.orderinfo_set.all() order.o_type = True order.save() for orderinfo in orderinfos: #减掉库存 comm = CommInfo.objects.get(id=orderinfo.comm_id) if int(comm.c_stock) - int(orderinfo.content) >0: comm.c_stock = int(comm.c_stock) - int(orderinfo.content) else: comm.delete() comm.save() return JsonResponse({ 'status':1, 'msg':'支付成功' }) elif(code == '10000' and trade_status=='WAIT_BUYER_PAY') or code =='40004': continue else: return JsonResponse({ 'status':0, 'msg':'交易失败' }) <file_sep>from django.db import models from df_user.models import UserProfile from df_goods.models import GoodInfo # Create your models here. class OrderInfo(models.Model): o_id = models.CharField(max_length=100,primary_key=True,verbose_name='订单编号') o_date = models.DateTimeField(auto_now_add=True,verbose_name='订单日期') o_pay = models.BooleanField(choices=((True,'已支付'),(False,'未支付')),default=False,verbose_name='是否支付') o_total_price = models.CharField(max_length=100,verbose_name='订单总额') user = models.ForeignKey(UserProfile,verbose_name='用户',on_delete=models.CASCADE) class Meta: verbose_name = '订单' verbose_name_plural = verbose_name def __str__(self): return self.o_id class OrderDetailInfo(models.Model): count = models.IntegerField(verbose_name='商品数量') goods = models.ForeignKey(GoodInfo,on_delete=models.CASCADE,verbose_name='商品') order = models.ForeignKey(OrderInfo,on_delete=models.CASCADE,verbose_name='订单') class Meta: verbose_name = '订单详情' verbose_name_plural = verbose_name def __str__(self): return self.goods.g_title <file_sep># -*- coding: utf-8 -*- from django.conf.urls import url from .views import * urlpatterns = [ url(r'^order_check/',order_check,name='order_check'), url(r'^delete/',delete,name='delete'), url(r'^cartinfo/',CartInfo.as_view(),name='cart_info'), url(r'^add_cart/',AddCart.as_view(),name='add_cart'), ]<file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-05-27 10:57 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('fruits', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.AddField( model_name='shopcat', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='用户'), ), migrations.AddField( model_name='orderinfo', name='comm', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='fruits.CommInfo', verbose_name='订单商品'), ), migrations.AddField( model_name='orderinfo', name='order', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='fruits.CommOrders', verbose_name='订单'), ), migrations.AddField( model_name='commorders', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='用户'), ), migrations.AddField( model_name='comminfo', name='tags', field=models.ManyToManyField(to='fruits.CommTags', verbose_name='商品标签'), ), migrations.AddField( model_name='comminfo', name='type', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='fruits.CommType', verbose_name='商品分类'), ), ] <file_sep># -*- coding: utf-8 -*- from django.contrib.auth.forms import forms from captcha.fields import CharField class CheckForm(forms.Form): email = forms.EmailField()<file_sep>from django.contrib import admin from .models import * # Register your models here. class UserAdmin(admin.ModelAdmin): list_display = ['email','phone','address','postcode'] list_filter = ['last_login'] search_fields = ['username','email','phone','postcode'] admin.site.register(FruitsUsers,UserAdmin) class EmailAdmin(admin.ModelAdmin): list_display = ['email','code','send_time','over_time','email_type'] list_filter = ['send_time','over_time'] search_fields = ['email','code','email_type'] admin.site.register(CheckEmail,EmailAdmin) <file_sep>default_app_config = 'fruits.apps.FruitsConfig'<file_sep>function cprice(type) { var stock = parseInt($('#stock').text()) if (type=='add'){ input = document.getElementsByTagName('input') var num = parseInt($('.num_show').attr('value')) if (num < stock){ num += 1 } }else if(type=="minus"){ var num = parseInt($('.num_show').attr('value')) if (num >1 ){ num -= 1 } } $('.num_show').attr('value',num) $('.num_show')[0].value=num // 展示数量 $('.num_name').text('数量: '+num) //价格 var price = $('.show_pirze > em')[0].textContent price = parseFloat(price) var price = price * num price = price.toFixed(2) console.log(price) $('.total > em').text(price) } window.onload = function (ev) { function add() { console.log('add函数') var num = $('.num_show').val() } var num = 1 $('#add_cart').mousedown(function () { // 发请求添加购物车 // 商品数量,商品id //post请求 var num = $('.num_show').val() var good_id = $('.operate_btn').attr('id') var url="/cart/add_cart/" var csrf_token = $('#csrf_token').text() $.ajax({ url:url, data:{ //总价 s_money: $('.total > em').text(), //库存 stock: $('#stock').text(), good_id:good_id, num:num, next_href:window.location.href, csrfmiddlewaretoken: csrf_token }, type:'POST', async:true, success:function (data) { alert(data.Meg) if (data.url){ window.location.href =data.url }else if (data.status == 1){ $('#show_count').text(data.count) } }, error :function (data) { console.log(data) } }) }) $('.num_show').blur(function (ev) { var stock = parseInt($('#stock').text()) var num = parseInt($(this).val()) if (num <1){ num = 1 }else if(num > stock){ num = stock } $('.num_show').val(num) $('.num_show').attr('value',num) // 展示数量 $('.num_name').text('数量: '+num) //价格 var price = $('.show_pirze > em')[0].textContent price = parseFloat(price) var price = price * num price = price.toFixed(2) console.log(price) $('.total > em').text(price) }) $('.add').mousedown(function () { cprice('add') }) $('.minus').mousedown(function () { cprice('minus') }) // 添加购物车 //点击购物车没有登录的状态 // $('.cart_name').mousedown(function (env) { // user_id = $(this).attr('id') // if (user_id == None){ // //get请求,带着本业网址 // url='/cart/cartinfo/?next='+ window.location.href // $.get(url,function (data) { // // }) // // // } // }) }<file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2018-04-26 09:14 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='emailmodels', options={'verbose_name': '邮箱验证', 'verbose_name_plural': '邮箱验证'}, ), migrations.AddField( model_name='emailmodels', name='send_type', field=models.CharField(choices=[('register', '注册邮件'), ('forget', '找回密码')], default=1, max_length=20), preserve_default=False, ), ] <file_sep># -*- coding: utf-8 -*- from django.contrib.auth.forms import forms class CheckForm(forms.Form): user_name = forms.CharField(max_length=255) pwd = forms.CharField(max_length=20,min_length=6) cpwd = forms.CharField(max_length=20,min_length=6,required=False) email = forms.EmailField(required=False)<file_sep># -*- coding: utf-8 -*- from django import forms from captcha.fields import CaptchaField class RegisterForm(forms.Form): email = forms.EmailField(required=True, error_messages={'invalid': '请输入正确的邮箱'}) nick_name = forms.CharField(required=True) password = forms.CharField(max_length=6, required=True, error_messages={'invalid': '密码不得少于6位'}) repassword = forms.CharField(max_length=6, required=True, error_messages={'invalid': '密码不得少于6位'}) captcha = CaptchaField(required=True, error_messages={'invalid': '请输入正确的验证码'}) class LoginFrom(forms.Form): email = forms.EmailField(required=True, error_messages={'invalid': '请输入正确的邮箱'}) password = forms.CharField(max_length=6, required=True, error_messages={'invalid': '密码不得少于6位'}) captcha = CaptchaField(required=True, error_messages={'invalid': '请输入正确的验证码'}) class Amend_pd(forms.Form): email = forms.EmailField(required=True, error_messages={'invalid': '请输入正确的邮箱'}) captcha = CaptchaField(required=True, error_messages={'invalid': '请输入正确的验证码'}) class Alterpasswd(forms.Form): email = forms.EmailField(required=True, error_messages={'invalid': '请输入正确的邮箱'}) password = forms.CharField(max_length=6, required=True, error_messages={'invalid': '密码不得少于6位'}) repassword = forms.CharField(max_length=6, required=True, error_messages={'invalid': '密码不得少于6位'}) <file_sep>from django.db import models # Create your models here. # 商品种类的数据模型 class TypeInfo(models.Model): title = models.CharField(max_length=100,verbose_name='分类名称') class_name = models.CharField(max_length=50,default='',verbose_name='') type_img = models.ImageField(upload_to='df_type/%Y/%m/',verbose_name='分类封面图',default='df_type/default.jpg') class Meta: verbose_name = '商品分类' verbose_name_plural = verbose_name def __str__(self): return self.title # 商品信息的数据模型 class GoodInfo(models.Model): g_title = models.CharField(max_length=100,verbose_name='商品名称') g_pic = models.ImageField(upload_to='df_goods/%Y/%m',verbose_name='商品图片',default='df_goods/default.jpg') # DecimalField() 小数 g_price = models.DecimalField(max_digits=5,decimal_places=2,verbose_name='商品价格') g_unit = models.CharField(max_length=50,verbose_name='计量单位') g_click = models.IntegerField(verbose_name='浏览次数') g_desc = models.CharField(max_length=150,verbose_name='商品描述') g_stock = models.IntegerField(verbose_name='库存数量') g_content = models.TextField(verbose_name='商品详情') # 商品与商品类型之间的关系 一对多 type = models.ForeignKey(TypeInfo,on_delete=models.CASCADE) class Meta: verbose_name = '商品' verbose_name_plural = verbose_name def __str__(self): return self.g_title <file_sep># -*- coding: utf-8 -*- from django.core.mail import send_mail import random import datetime from register_demo import settings from users.models import EmailModels # 随机生成验证码 def codes(lenght=16): strs = 'qwertpoiuytasdfghjklzxcvbnmQWERTYUIOPSDFGHJKLZXCVBNM123456789' code ='' for x in range(lenght): code += random.choice(strs) return code # 发送邮件 def send_email(to_email,send_type='register'): email = EmailModels() # 获取验证码 email.code = codes() #收件人 email.email = to_email # 设置时间验证邮件过期时间 email.send_time = datetime.datetime.now() #设置邮件是三天后过期 email.overtime = datetime.datetime.now()+ datetime.timedelta(days=3) # 邮件类型 email.send_type = send_type email.save() try: if send_type=='register': look = '欢迎注册cctv开心网' html_message = '<a href="http://127.0.0.1:8000/users/active_email/{}">点击此处http://192.168.12.242:8000/users/active_email/{}验证激活cctv开心网,开启快乐之旅</a>'.format(email.code,email.code) else: look = '修改密码' html_message = '<a href="http://127.0.0.1:8000/users/ame_password/{}">点击此处http://192.168.12.242:8000/users/ame_password/{}激活连接,修改密码</a>'.format(email.code,email.code) res = send_mail(look,'',settings.EMAIL_HOST_USER,[to_email],html_message=html_message) except EmailModels as e: return False else: if res: return True else: return False<file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-05-27 15:13 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('fruits', '0002_auto_20180527_1057'), ] operations = [ migrations.AlterField( model_name='commorders', name='o_id', field=models.CharField(max_length=50, primary_key=True, serialize=False, verbose_name='订单号'), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-05-27 10:57 from __future__ import unicode_literals import DjangoUeditor.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='CommInfo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('c_name', models.CharField(max_length=20, verbose_name='商品名称')), ('c_price', models.FloatField(verbose_name='商品价格')), ('c_comfrom', models.CharField(max_length=100, verbose_name='商品产地')), ('c_images', models.ImageField(default='df_goods/fruit.jpg', upload_to='df_goods/', verbose_name='商品图片')), ('c_unit', models.CharField(max_length=50, verbose_name='单位/斤')), ('c_desc', models.CharField(max_length=255, verbose_name='诱惑')), ('c_content', DjangoUeditor.models.UEditorField(default='', verbose_name='商品描述')), ('c_stock', models.IntegerField(verbose_name='商品库存')), ('c_click', models.IntegerField(verbose_name='商品点击率')), ], options={ 'verbose_name': '商品', 'verbose_name_plural': '商品', 'db_table': 'commodity', }, ), migrations.CreateModel( name='CommOrders', fields=[ ('o_id', models.CharField(max_length=10, primary_key=True, serialize=False, verbose_name='订单号')), ('o_date', models.DateTimeField(auto_now_add=True, verbose_name='订单时间')), ('o_money', models.CharField(max_length=200, verbose_name='订单价格')), ('o_type', models.BooleanField(choices=[(True, '已支付'), (False, '未支付')])), ], options={ 'verbose_name': '订单详情', 'verbose_name_plural': '订单详情', 'db_table': 'orders', }, ), migrations.CreateModel( name='CommTags', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('tags', models.CharField(max_length=20, verbose_name='商品标签')), ], options={ 'verbose_name': '商品标签', 'verbose_name_plural': '商品标签', 'db_table': 'tags', }, ), migrations.CreateModel( name='CommType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('class_name', models.CharField(max_length=50, verbose_name='商品分类')), ('type_img', models.ImageField(upload_to='df_type/', verbose_name='商品分类图片')), ], options={ 'verbose_name': '商品分类', 'verbose_name_plural': '商品分类', 'db_table': 'type', }, ), migrations.CreateModel( name='OrderInfo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('content', models.CharField(max_length=255, verbose_name='订单商品数量')), ], options={ 'verbose_name': '订单详情表', 'verbose_name_plural': '订单详情表', 'db_table': 'orderinfo', }, ), migrations.CreateModel( name='ShopCat', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('s_num', models.IntegerField(verbose_name='购买的数量')), ('s_money', models.FloatField(verbose_name='商品总价')), ('comm', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='fruits.CommInfo', verbose_name='商品种类')), ], options={ 'verbose_name': '购物车', 'verbose_name_plural': '购物车', 'db_table': 'cart', }, ), ] <file_sep>from django.shortcuts import render from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage from .models import TypeInfo,GoodInfo # Create your views here. def goods(request): context = {} # 商品分类 types = TypeInfo.objects.all() goods = {} hot_goods = {} for type in types: # 把分类名称作为key,值对应的分类下前四个商品 goods[type.title] = type.goodinfo_set.all()[:4] # 该分类下的人气商品 hot_goods[type.title] = type.goodinfo_set.all().order_by('-g_click')[:3] context['goods'] = goods context['hot_goods'] = hot_goods context['types'] = types # 在前端界面中会判断type从而知道进入的是哪个界面,展示不同的标签 context['type'] = 'goods' return render(request,'df_goods/index.html',context) def goodslist(request): if request.method == 'GET': context = {} t_id = request.GET.get('t_id') # 获取分类id及id对应商品 try: TypeInfo.objects.get(id=t_id) except Exception as e: return render(request,'404.html') # 取出新品推荐的商品 newsgoods = GoodInfo.objects.filter(type_id=t_id).order_by('-id')[:2] # 获取排序方式 sort_type = request.GET.get('s_type','default') # 默认排序 if sort_type == 'default': goods = GoodInfo.objects.filter(type_id=t_id).order_by('-id') elif sort_type == 'price': goods = GoodInfo.objects.filter(type_id=t_id).order_by('g_price') elif sort_type == 'hot': goods = GoodInfo.objects.filter(type_id=t_id).order_by('-g_click') page_num = request.GET.get('p',1) pages = Paginator(goods,3) try: goods = pages.page(page_num) except PageNotAnInteger as e: goods = pages.page(1) except EmptyPage as e: goods = pages.page(pages.num_pages) context['goods'] = goods context['newsgoods'] = newsgoods context['s_type'] = sort_type context['type'] = 'goods' return render(request,'df_goods/list.html',context) # 商品详情界面 def goodsdetail(request): if request.method == 'GET': # 取出商品id g_id = request.GET.get('g_id') # 取出商品 try: good = GoodInfo.objects.get(id=g_id) except Exception as e: return render(request,'404.html') else: # 浏览次数+1 good.g_click +=1 good.save() # 获取商品对应类型的商品集合,排序 取俩 newsgoods = good.type.goodinfo_set.order_by('-id')[:2] context = { 'title':'天天生鲜-{}'.format(good.g_title), 'type':'goods', 'good':good, 'newsgoods':newsgoods, } return render(request,'df_goods/detail.html',context) <file_sep>from django.shortcuts import render,HttpResponse,redirect from django.http.response import JsonResponse from django.contrib.auth.views import login_required from django.views import View # Create your views here. from fruits.models import * class AddCart(View): def get(self,request): pass def post(self,request): result = {} if request.user.is_authenticated: good_id = request.POST.get('good_id',None) num = request.POST.get('num',None) stock = request.POST.get('stock') s_money = request.POST.get('s_money') if good_id and num: cart = ShopCat.objects.filter(comm_id=good_id,user=request.user) if cart: if (cart[0].s_num + int(num)) > int(stock): cart[0].s_num = stock else: cart[0].s_num = cart[0].s_num + int(num) cart[0].s_money = cart[0].s_money + float(s_money) cart = cart[0] else: cart = ShopCat(comm_id=good_id,user=request.user,s_num=num,s_money= s_money) cart.save() result['status']=1 result['Meg'] = '购物车添加成功' else: result['status'] = 0 result['Meg'] = '购物车添加失败' result['count'] = ShopCat.objects.filter(user=request.user).count() else: next_href = request.POST.get('next_href') next_href = next_href.split('8000')[1] result['status'] = 0 result['Meg'] = '请先登录' result['url'] = 'http://127.0.0.1:8000/user/login/?next={}'.format(next_href) return JsonResponse(result) class CartInfo(View): def get(self,request): result = {} if request.user.is_authenticated: user = request.user carts = ShopCat.objects.filter(user=user) result['carts'] = carts result['type'] = 'cart' return render(request,'df_cart/cart.html',result) else: return redirect('/user/login/') # next_href = request.POST.get('next_href') # next_href = next_href.split('8000')[1] # result['status'] = 0 # result['Meg'] = '请先登录' # result['url'] = 'http://127.0.0.1:8000/user/login/?next={}'.format(next_href) # return JsonResponse(result) def post(self,request): pass def order_check(request): if request.method == 'POST': result = {} goods_id = request.POST.get('goods_id',None) num = request.POST.get('num',None) if goods_id and num: try: cart = ShopCat.objects.get(comm_id=goods_id) cart.s_num = num cart.save() result['status'] = 1 result['Meg'] = '修改成功' except Exception as e: result['status'] = 0 result['Meg'] = '修改失败' return JsonResponse(result) else: return HttpResponse(status=404) def delete(request): if request.method=='GET': result = {} good_id = request.GET.get('id') try: ShopCat.objects.get(comm_id=good_id).delete() result['status'] = 1 result['Meg'] = '删除成功' except Exception as e: result['status'] = 0 result['Meg'] = '删除失败,网络原因,请刷新页面' return JsonResponse(result) <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-05-27 20:47 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.AddField( model_name='fruitsusers', name='u_name', field=models.CharField(default=1, max_length=50, verbose_name='收件人'), preserve_default=False, ), ] <file_sep>from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class FruitsUsers(AbstractUser): address = models.CharField(max_length=200,default='中国',verbose_name='地址') phone = models.CharField(max_length=11,blank=True,default=110,verbose_name='电话') postcode = models.CharField(max_length=6,verbose_name='邮编') u_name = models.CharField(max_length=50,verbose_name='收件人',default='小花') class Meta: db_table = 'users' verbose_name = '用户信息表' verbose_name_plural = verbose_name # 邮箱验证 class CheckEmail(models.Model): email = models.EmailField(verbose_name='注册邮箱') code = models.CharField(max_length=100,verbose_name='验证码') send_time = models.DateTimeField(auto_now_add=True,verbose_name='发送时间') over_time = models.DateTimeField(verbose_name='过期时间') email_type = models.CharField(max_length=25,choices=(('login','登录'),('register','注册')),verbose_name='邮箱类型') #是否已经激活 email_actiate = models.BooleanField(choices=((True,'已经激活'),(False,'没有激活')),verbose_name='激活状态') class Meta: db_table = 'email' verbose_name = '验证邮箱' verbose_name_plural = verbose_name def __str__(self): return '{}'.format(self.email)<file_sep>from django.conf.urls import url from .views import * urlpatterns = [ url(r'^login/',mylogin,name='login'), url(r'^logout/',mylogout,name='logout'), url(r'^register/$',register,name='register'), url(r'^check_user/$',check_user,name='check_user'), ]<file_sep>// $('body').ready(function () { window.onload = function (ev) { // alert('页面加载完成') function remove() { $('h6').remove() } $('.ch').blur(function (ev) { console.log($(this).val()) console.log($(this)) // id值 console.log($(this)[0].id) var url = "/user/checkuser/" if ($(this)[0].id == 'user_name'){ var data = {'user_name':$(this).val()} }else if($(this)[0].id == 'email'){ var data={'email':$(this).val()} }else if($(this)[0].id == 'cpwd'){ var data = {'cpwd':$(this).val(),'pwd':$('#pwd').val()} } console.log(data) $.get(url,data,function (data) { remove() console.log(data) if (data){ var h6 = '<h6>'+data.Meg.err+'</h6>' console.log($("#"+data.name)) $($("#"+data.name)).after(h6) }else{ console.log(data) } }) }) $.ajaxSetup({ data: { 'csrfmiddlewaretoken': '{{ csrf_token }}' } }) $('#reg_form').submit(function (even) { even.preventDefault() $.ajax({ url:'/user/checkuser/', data:$('form').serialize(), type:'POST', async:true, success:function (data,status,xhr) { remove() console.log(data) if (data.name == 0){ // 数据不合法 for (key in data.Meg){ var h6 = '<h6>'+data.Meg[key]+'</h6>' $('#'+key).after(h6) } } else if(data.status == 0){ h6 = '<h6>'+data.Meg.err+'</h6>' $('#'+data.name).after(h6) } else if (data.status == 1){ // 注册成功 console.log('注册成功') window.location.href = '/user/login' } }, error:function (status,xhr,errorThrown) { console.log(status,xhr,errorThrown) }, complate:function () { console.log('请求完成') } }) }) } // })<file_sep>from django.db import models from df_user.models import UserProfile from df_goods.models import GoodInfo # Create your models here. class CartInfo(models.Model): user = models.ForeignKey(UserProfile,on_delete=models.CASCADE,verbose_name='用户') goods = models.ForeignKey(GoodInfo,on_delete=models.CASCADE,verbose_name='商品') count = models.IntegerField(verbose_name='数量')<file_sep># -*- coding: utf-8 -*- from django.conf.urls import url from .views import * urlpatterns = [ url(r'^centerinfo/',centerinfo,name='centerinfo'), url(r'^centersize/',centersize,name='centersize'), url(r'^center/',center,name='center'), url(r'logout/',logoutuser,name='logout'), url(r'^checklogin/',checklogin,name='checklogin'), url(r'^checkuser/',checkinfo,name='checkuser'), url(r'^register/',RegisterUser.as_view(),name='register'), url(r'^login/',LoginUser.as_view(),name='login') ]<file_sep>from django.conf.urls import url from .views import * urlpatterns = [ url(r'^$',goods,name='goods_idx'), url(r'^list/$',goodslist,name='goods_list'), url(r'^detail/$',goodsdetail,name='goods_detail'), ]<file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-05-27 20:49 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0002_fruitsusers_u_name'), ] operations = [ migrations.AlterField( model_name='fruitsusers', name='u_name', field=models.CharField(default='小花', max_length=50, verbose_name='收件人'), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-05-25 14:44 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('df_goods', '0001_initial'), ] operations = [ migrations.CreateModel( name='OrderDetailInfo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('count', models.IntegerField(verbose_name='商品数量')), ('goods', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='df_goods.GoodInfo', verbose_name='商品')), ], options={ 'verbose_name': '订单详情', 'verbose_name_plural': '订单详情', }, ), migrations.CreateModel( name='OrderInfo', fields=[ ('o_id', models.CharField(max_length=100, primary_key=True, serialize=False, verbose_name='订单编号')), ('o_date', models.DateTimeField(auto_now_add=True, verbose_name='订单日期')), ('o_pay', models.BooleanField(choices=[(True, '已支付'), (False, '未支付')], default=False, verbose_name='是否支付')), ('o_total_price', models.CharField(max_length=100, verbose_name='订单总额')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='用户')), ], options={ 'verbose_name': '订单', 'verbose_name_plural': '订单', }, ), migrations.AddField( model_name='orderdetailinfo', name='order', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='df_order.OrderInfo', verbose_name='订单'), ), ] <file_sep>from django.conf.urls import url from .views import * urlpatterns = [ url(r'^$',order,name='order_idx'), url(r'^add_order/$',add_order,name='add_order'), url(r'^check_pay/$',check_pay,name='check_pay'), ]<file_sep>djngo-构建注册,登录,找回密码,注销登录的操作 <file_sep>from django.conf.urls import url from .views import * urlpatterns = [ url(r'^$',cart,name='cart_idx'), url(r'^add_cart/$',add_cart,name='cart_add'), url(r'^query_count',query_count,name='query_count'), url(r'^update/$',update,name='cart_update'), url(r'^delete/$',delete,name='cart_delete'), ]<file_sep>from django.shortcuts import render, HttpResponse,redirect from users.models import * # Create your views here. from django.views import View from django.http import JsonResponse from .froms import * from django.contrib.auth.hashers import make_password from django.db.models import Q from django.contrib.auth import logout, login, authenticate from django.contrib.auth.backends import ModelBackend from fruits.models import * from django.core.paginator import PageNotAnInteger,Paginator,EmptyPage # Create your views here. def center(request): if request.method == 'GET': result = {} user = request.user orders = CommOrders.objects.filter(user=user) #分页 page = Paginator(orders,4) result['orders'] = orders result['type'] = 'center' return render(request,'df_user/user_center_order.html',result) def centerinfo(request): result = {} result['type'] = 'centerinfo' return render(request,'df_user/user_center_info.html',result) def centersize(request): if request.method == 'GET': result = {} result['type'] = 'centersize' return render(request, 'df_user/user_center_site.html',result) elif request.method =='POST': result ={} username = request.POST.get('username') address = request.POST.get('address') postcode = request.POST.get('postcode') phone = request.POST.get('phone') user = FruitsUsers.objects.get(id=request.user.id) user.u_name = username user.address = address user.postcode = postcode user.phone = phone user.save() result['type'] = 'centerinfo' return render(request, 'df_user/user_center_info.html', result) class RegisterUser(View): def get(self, request): return render(request, 'df_user/register.html') def post(self, request): pass class LoginUser(View): def get(self, request): return render(request, 'df_user/login.html') def post(self, request): form = CheckForm(request.POST) next = request.GET.get('next') if form.is_valid(): username = form.cleaned_data['user_name'] pwd = form.cleaned_data['pwd'] # 判断用户是否存在 res = FruitsUsers.objects.filter(Q(username=username) | Q(email=username)) if res: user = authenticate(request, username=username, password=pwd) if user: login(request, user) status = 1 Meg = {'err': '登录成功'} name = 1 next = next else: status = 0 Meg = {'err': '账号密码错误'} name = "pwd" next = None result = {'status': status, 'Meg': Meg, 'name': name,'next':next} return JsonResponse(result) else: status = 0 Meg = {'err': '该用户尚未注册'} name = 'username' result = {'status': status, 'Meg': Meg, 'name': name} return JsonResponse(result) else: result = {'status': 0, 'Meg': form.errors, 'name': 0} return JsonResponse(result) def checkinfo(request): """ status 0 有错 1 成功 Meg{'err':信息} :param request: :return: """ if request.method == "POST": form = CheckForm(request.POST) if form.is_valid(): # 判断昵称,email是否存在 user_name = form.cleaned_data['user_name'] email = form.cleaned_data['email'] pwd = form.cleaned_data['pwd'] cpwd = form.cleaned_data['cpwd'] if FruitsUsers.objects.filter(username=user_name): status = 0 Meg = {'err': '该昵称已经存在'} name = 'user_name' else: if FruitsUsers.objects.filter(email=email): status = 0 Meg = {'err': '该邮箱已经注册'} name = 'email' else: if pwd != cpwd: status = 0 Meg = {'err': '两次密码不一致'} name = 'cpwd' else: user = FruitsUsers(username=user_name, email=email, is_active=1, is_staff=1, password=make_password(cpwd)) user.save() status = 1 Meg = {'err': '注册成功'} name = None result = {'status': status, 'Meg': Meg, 'name': name} return JsonResponse(result) else: status = 0 Meg = form.errors return JsonResponse({'status': status, 'Meg': Meg, 'name': 0}) elif request.method == "GET": user_name = request.GET.get('user_name', None) email = request.GET.get('email', None) cpwd = request.GET.get('cpwd', None) pwd = request.GET.get('pwd', None) if user_name or email: user = FruitsUsers.objects.filter(username=user_name) email = FruitsUsers.objects.filter(email=email) if user or email: if email: Meg = {'err': '邮箱已经存在'} elif user: Meg = {'err': '用户名已经存在'} status = 0 else: if not user: Meg = {'err': '用户可以使用'} elif not email: Meg = {'err': '邮箱可以使用'} status = 1 if user_name: res = 'user_name' else: res = 'email' result = {'status': status, 'Meg': Meg, 'name': res} return JsonResponse(result) elif cpwd: if cpwd == pwd: status = 1 Meg = {'err': '两次密码一致'} else: status = 0 Meg = {'err': '两次密码不一致'} res = 'cpwd' result = {'status': status, 'Meg': Meg, 'name': res} return JsonResponse(result) else: result = None return JsonResponse(result) def checklogin(request): """ name 0 数据不合法 status 0 1 Meg={'err':''} :param request: :return: """ if request.method == 'GET': username = request.GET.get('username', None) if username: user = FruitsUsers.objects.filter(Q(email=username) | Q(username=username)) if user: status = 1 Meg = {'err': '用户可以用'} else: status = 0 Meg = {'err': '账号密码错误'} result = {'status': status, 'Meg': Meg} return JsonResponse(result) else: return HttpResponse(status=404) class CheckUserAuth(ModelBackend): def authenticate(self, request, username=None, password=<PASSWORD>, **kwargs): username = username password = <PASSWORD> try: user = FruitsUsers.objects.get(Q(username=username) | Q(email=username)) if user: if user.check_password(password): return user else: None else: return None except Exception as e: return None def logoutuser(request): if request.user.id: logout(request) return redirect('/') else: return HttpResponse(status=404) <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-05-24 11:16 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='GoodInfo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('g_title', models.CharField(max_length=100, verbose_name='商品名称')), ('g_pic', models.ImageField(default='df_goods/default.jpg', upload_to='df_goods/%Y/%m', verbose_name='商品图片')), ('g_price', models.DecimalField(decimal_places=2, max_digits=5, verbose_name='商品价格')), ('g_unit', models.CharField(max_length=50, verbose_name='计量单位')), ('g_click', models.IntegerField(verbose_name='浏览次数')), ('g_desc', models.CharField(max_length=150, verbose_name='商品描述')), ('g_stock', models.IntegerField(verbose_name='库存数量')), ('g_content', models.TextField(verbose_name='商品详情')), ], options={ 'verbose_name': '商品', 'verbose_name_plural': '商品', }, ), migrations.CreateModel( name='TypeInfo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=100, verbose_name='分类名称')), ('class_name', models.CharField(default='', max_length=50, verbose_name='')), ('type_img', models.ImageField(default='df_type/default.jpg', upload_to='df_type/%Y/%m/', verbose_name='分类封面图')), ], options={ 'verbose_name': '商品分类', 'verbose_name_plural': '商品分类', }, ), migrations.AddField( model_name='goodinfo', name='type', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='df_goods.TypeInfo'), ), ] <file_sep># -*- coding: utf-8 -*- from django.conf.urls import url from .views import RegisterView,LoginView,Active_email,Amend_pd,Ame_password,AlterPassword,Center,Logot,Modify,Update from django.views.static import serve from register_demo import settings urlpatterns = [ url(r'^media/(?P<path>\w+)',serve,{'document_root':settings.MEDIA_ROOT},name='media'), url(r'^update/',Update.as_view(),name='update'), url(r'^modify_center/',Modify.as_view(),name='modify_center'), url(r'^logout/',Logot.as_view(),name='logout'), url(r'^center/', Center.as_view(),name='center'), url(r'^alterpasswd/$',AlterPassword.as_view(),name='alterpasswd'), url(r'^ame_password/(?P<code>\w+)',Ame_password.as_view()), url(r'amend_pd/$',Amend_pd.as_view(),name='amend_pd'), url(r'active_email/(?P<code>\w+)',Active_email.as_view()), url(r'^login/',LoginView.as_view(),name='login'), url(r'^register/$',RegisterView.as_view(),name='register'), ]<file_sep>from datetime import datetime import os from django.shortcuts import render from django.contrib.auth.views import login_required from django.http import JsonResponse from alipay import AliPay # Create your views here. from df_cart.models import CartInfo from .models import OrderInfo,OrderDetailInfo from df_goods.models import GoodInfo from dailyfresh import settings @login_required def order(request): """ 订单 :param request: :return: """ if request.method == 'POST': cart_list = [CartInfo.objects.get(id=c_id) for c_id in request.POST.getlist('cartid')] context = { 'title':'天天生鲜-提交订单', 'type':'goods', 'cart_list':cart_list } return render(request,'df_order/place_order.html',context) @login_required def add_order(request): if request.method =='POST': cartlist = request.POST.getlist('cartlist[]') total_price = request.POST.get('total_price') #创建订单 order = OrderInfo() #订单编号 时间201805252044156 # strftime('%Y%m%H%M%S')编码格式 order.o_id = '{}{}'.format(datetime.now().strftime('%Y%m%H%M%S'),request.user.id) order.user = request.user order.o_total_price = total_price order.save() #将商品储存订单储存订单详情表 for x in cartlist: cart = CartInfo.objects.get(id=x) order_detail = OrderDetailInfo() order_detail.goods = cart.goods order_detail.order = order order_detail.count = cart.count order_detail.save() #订单信息和订单详情保存后,删除购物车中的商品 cart.delete() #创建用于支付宝的对象 ali_pay = AliPay( appid=settings.ALIPAY_APPID, app_notify_url=None,#使用默认回调的地址 alipay_public_key_path=os.path.join(settings.BASE_DIR,'keys/public'), app_private_key_path=os.path.join(settings.BASE_DIR,'keys/private'), #使用的加密方式 sign_type='RSA2', #默认是Flase 测试环境配合沙箱环境使用 如果是的生产环境 将改为True debug=False ) #网站端的支付需要跳转到的支付页面,执行支付 #http://openapi.alipaydev.com/qateway.do?order= order_string = ali_pay.api_alipay_trade_page_pay( #订单号 out_trade_no=order.o_id, #订单总额 total_amount=total_price, #订单描述信息 subject='天天生鲜购物单-{}'.format(order.o_id), #回调地址,订单支付成功后回调地址 return_url='https://www.baidu.com', ) #拼接支付地址 url = settings.ALIPAY_URL + '?'+order_string #将数据返回给前端,前段跳转到支付界面支付 result={'status':1,'msg':'请求成功','url':url,'o_id':order.o_id} return JsonResponse(result) # 监测订单是否支付 def check_pay(request): if request.method == 'GET': o_id = request.GET.get('o_id') alipay = AliPay( appid=settings.ALIPAY_APPID, app_notify_url=None, app_private_key_path=os.path.join(settings.BASE_DIR,'keys/pri'), alipay_public_key_path=os.path.join(settings.BASE_DIR,'keys/pub'), sign_type='RSA2', # 沙箱环境下没有查询订单服务的 debug=True ) while True: response = alipay.api_alipay_trade_query(o_id) # code 40004 支付订单未创建 # code 10000 trade_status WAIT_BUYER_PAY 等待支付 # oode 10000 trade_status TRADE_SUCCESS 支付成功 # response 是字典 code = response.get('code') trade_status =response.get('trade_status') if code == '10000' and trade_status == 'TRADE_SUCCESS': # 支付成功 # 返回支付结果 return JsonResponse({ 'status':1, 'msg':'支付成功' }) elif (code == '10000' and trade_status =='WAIT_BUYER_PAY') or code == '40004': # 表示支付暂时没有完成 continue else: return JsonResponse({ 'status':0, 'msg':'支付失败' }) <file_sep>from django.shortcuts import render,redirect from django.http import JsonResponse from django.contrib.auth.hashers import make_password from django.contrib.auth.views import login,logout,login_required # Create your views here. from .models import UserProfile def mylogin(request): if request.method == 'GET': return render(request,'df_user/login.html') elif request.method == 'POST': username =request.POST.get('username') password = request.POST.get('password') context = {} if UserProfile.objects.filter(username=username): user = UserProfile.objects.get(username=username) if user.check_password(password): context['status'] = 1 context['msg'] = '登录成功' context['next'] = request.GET.get('next','') login(request,user) else: context['satus'] = 0 context['msg'] = '账户或密码错误' else: context['status'] = 0 context['msg'] = '用户不存在' return JsonResponse(context) @login_required def register(request): if request.method == 'GET': return render(request,'df_user/register.html') elif request.method == 'POST': # 取出用户名 密码 邮箱 username = request.POST.get('username') password = request.POST.get('<PASSWORD>') email = request.POST.get('email') context = {} if UserProfile.objects.filter(username=username): context['status'] = 0 context['msg'] = '该用户已存在,请重新输入用户名' return JsonResponse(context) else: try: user = UserProfile(username=username, password=<PASSWORD>_<PASSWORD>(password), email=email) user.save() except Exception as e: print(e) return JsonResponse({ 'status':500, 'msg':'您的网络不稳定,注册失败,请稍后重试!' }) else: return JsonResponse({ 'status':200, 'msg':'注册成功' }) def mylogout(request): logout(request) return redirect('/goods/') # 判断用户是否存在 def check_user(request): if request.method == 'GET': username = request.GET.get('username') # 判断用户是否存在 if UserProfile.objects.filter(username=username): return JsonResponse({ 'status':0, 'msg':"该用户名已被占用,请换个名字。" }) else: return JsonResponse({ 'status':1, 'msg':'恭喜您,该用户名可以使用!' }) <file_sep># -*- coding: utf-8 -*- from django.conf.urls import url from .views import * urlpatterns = [ url(r'^$',order,name='order'), url(r'^checkorder/',check_pay,name='checkorder'), url(r'add_order/',add_order,name='add_order') ]<file_sep>from django.db import models from users.models import FruitsUsers from DjangoUeditor.models import UEditorField # Create your models here. # 商品名称 class CommInfo(models.Model): c_name = models.CharField(max_length=20, verbose_name='商品名称', null=False) c_price = models.FloatField(verbose_name='商品价格', null=False) c_comfrom = models.CharField(max_length=100, verbose_name='商品产地') c_images = models.ImageField(upload_to='df_goods/', default='df_goods/fruit.jpg', verbose_name='商品图片') c_unit = models.CharField(max_length=50,verbose_name='单位/斤') c_desc = models.CharField(max_length=255,verbose_name='诱惑') # c_stock = models.IntegerField(verbose_name='未知,int') type = models.ForeignKey('CommType', on_delete=models.CASCADE, verbose_name='商品分类') tags = models.ManyToManyField('CommTags', verbose_name='商品标签') # 水果描述 # c_content = models.TextField(verbose_name='商品描述') c_content = UEditorField( verbose_name='商品描述', width=600, height=300, toolbars='full', imagePath='ueditor/', filePath='files/', upload_settings={'imagesMaxSize':12040000}, default='' ) # 库存 c_stock = models.IntegerField(verbose_name='商品库存') c_click = models.IntegerField(verbose_name='商品点击率') class Meta: db_table = 'commodity' verbose_name = '商品' verbose_name_plural = verbose_name def __str__(self): return '{}'.format(self.c_name) # 购物车 class ShopCat(models.Model): user = models.ForeignKey(FruitsUsers,on_delete=models.CASCADE, verbose_name='用户') comm = models.ForeignKey(CommInfo, on_delete=models.CASCADE, verbose_name='商品种类') s_num = models.IntegerField(verbose_name='购买的数量') s_money = models.FloatField(verbose_name='商品总价') class Meta: db_table = 'cart' verbose_name = '购物车' verbose_name_plural = verbose_name def __str__(self): return '{}'.format(self.s_num) # 商品分类(水果,蔬菜) class CommType(models.Model): class_name = models.CharField(max_length=50, verbose_name='商品分类') type_img = models.ImageField(upload_to='df_type/', verbose_name='商品分类图片') class Meta: db_table = 'type' verbose_name = '商品分类' verbose_name_plural = verbose_name def __str__(self): return '{}'.format(self.class_name) # 商品标签(热销) class CommTags(models.Model): tags = models.CharField(max_length=20, verbose_name='商品标签') class Meta: db_table = 'tags' verbose_name = '商品标签' verbose_name_plural = verbose_name def __str__(self): return '{}'.format(self.tags) # 订单表 class CommOrders(models.Model): user = models.ForeignKey(FruitsUsers, on_delete=models.CASCADE, verbose_name='用户') # 订单号 o_id = models.CharField(max_length=50,verbose_name='订单号',primary_key=True) # 订单时间 o_date = models.DateTimeField(auto_now_add=True, verbose_name='订单时间') # 总价 o_money = models.CharField(max_length=200, verbose_name='订单价格') o_type = models.BooleanField(choices=((True,'已支付'),(False,'未支付'))) class Meta: db_table = 'orders' verbose_name = '订单详情' verbose_name_plural = verbose_name def __str__(self): return '{}'.format(self.o_id) # 订单详情 class OrderInfo(models.Model): comm = models.ForeignKey(CommInfo, on_delete=models.CASCADE, verbose_name='订单商品') order = models.ForeignKey(CommOrders, on_delete=models.CASCADE, verbose_name='订单') content = models.CharField(max_length=255, verbose_name='订单商品数量') class Meta: db_table = 'orderinfo' verbose_name = '订单详情表' verbose_name_plural = verbose_name def __str__(self): return '{}'.format(self.comm) <file_sep># -*- coding: utf-8 -*- import xadmin from .models import * from fruits.models import * from xadmin import views class GlobleSettings(): site_title = '天天生鲜管理系统' site_footer = '天天生鲜管理系统, 哈哈版权所有' menu_style = 'accordion' xadmin.site.register(views.CommAdminView,GlobleSettings) class Basesetings(): enable_themes = True use_bootswath = True xadmin.site.register(views.BaseAdminView,Basesetings) class EmailAdmin(object): list_display = ['email','code','send_time','over_time','email_type'] list_filter = ['send_time','over_time'] search_fields = ['email','code','email_type'] xadmin.site.register(CheckEmail,EmailAdmin) class ComminfoXadmin(): list_display = ['c_name', 'c_price', 'c_comfrom', 'c_images', 'c_content','c_click'] search_fields = ['c_name', 'c_price', 'c_comfrom'] style_fields = {'c_content':'ueditor'} xadmin.site.register(CommInfo, ComminfoXadmin) class CommAdmin(): list_display = ['tags'] search_fields = ['tags'] xadmin.site.register(CommTags,CommAdmin) class ShopCatAdmin(): list_display = ['user','comm','s_num'] search_fields = ['user','comm','s_num'] xadmin.site.register(ShopCat,ShopCatAdmin) class CommOrderAdmin(): list_display = ['user', 'o_num', 'o_date','o_money'] search_fields = ['user', 'o_num', 'o_date','o_money'] xadmin.site.register(CommOrders,CommOrderAdmin) class CommTypeAdmin(): list_display = ['class_name', 'type_img'] search_fields = ['class_name', 'type_img'] xadmin.site.register(CommType,CommTypeAdmin) <file_sep>from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class UserProfile(AbstractUser): address = models.CharField(max_length=200,null=True,verbose_name='收货地址') postcode = models.CharField(max_length=6,null=True,verbose_name='验证码') phone = models.CharField(max_length=11,null=True,verbose_name='手机号码') <file_sep>from django.shortcuts import render, HttpResponse, redirect # Create your views here. from django.views import View from .forms import RegisterForm, LoginFrom from .forms import Amend_pd as Amend_password, Alterpasswd from .models import UsersModels, EmailModels from utils.send_email_util import send_email # 密码加密 from django.contrib.auth.hashers import make_password import datetime import time # 引入login 函数,自动记录session from django.contrib.auth import login as logins, logout from django.contrib.auth import authenticate # 利用内置的检查模块 from django.contrib.auth.backends import ModelBackend from django.db.models import Q class RegisterView(View): def get(self, request): form = RegisterForm() return render(request, 'register.html', {'form': form}) def post(self, request): form = RegisterForm(request.POST) if form.is_valid(): # 判断昵称是否已经存在 email = form.cleaned_data['email'] # 判断是不是已经注册过 if not UsersModels.objects.filter(email=email): nick_name = form.cleaned_data['nick_name'] users = UsersModels.objects.filter(nick_name=nick_name) if not users: password = form.cleaned_data['password'] repassword = form.cleaned_data['repassword'] if form.cleaned_data['password'] == form.cleaned_data['repassword']: # users = UsersModels(nick_name=nick_name,password=<PASSWORD>) # 发送邮件 res = send_email(email, send_type='register') if res: mg = UsersModels(email=email, password=make_password(password), nick_name=nick_name, username=email) mg.save() return HttpResponse('邮件验证发送成功') else: return HttpResponse('邮件发送失败') else: return render(request, 'register.html', {'form': form, 'error': '两次密码不一样请重新输入'}) else: return render(request, 'register.html', {'form': form, 'errMeg': '该用户已经存在请重新填写!'}) else: return render(request, 'register.html', {'form': form, 'error': '该用户已注册,请检查邮箱地址/登录'}) else: return render(request, 'register.html', {'form': form}) class LoginView(View): def get(self, request): form = LoginFrom() return render(request, 'login.html', {'form': form}) def post(self, request): form = LoginFrom(request.POST) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] # 判断用户是否存在 res = UsersModels.objects.filter(email=email) if res: # 判断该用户密码是否正确 # 直接使用user.password == <PASSWORD> 肯定是不通过的 # 需要对密码加密后再判断 # user = UserProfile.objects.get(email=email,password=make_password(password)) # 1.用户名 2.密码 # authenticate 会对password进行加密后再对比 # 如果正好密码匹配返回这个user对象,如果不匹配返回None # 判断密码是否正确 user = authenticate(request=request, username=email, password=<PASSWORD>) if user: # 利用login函数 logins(request, user) return redirect('index') else: # 密码错误 return render(request, 'login.html', {'form': form, 'errMsg': '账号或密码错误,请仔细检查'}) else: # 用户不存在 return render(request, 'login.html', {'form': form, 'errMsg': '该用户不存在,请检查邮箱'}) else: return render(request, 'login.html', {"form": form}) class IndexView(View): def get(self, request): return render(request, 'index.html') def post(self, request): return HttpResponse('这是post请求到主页') class Active_email(View): def get(self, request, code): # 判断验证码是否正确 if EmailModels.objects.filter(code=code): # 判断是否失效 now = datetime.datetime.now() # 转换为时间戳 now_time = time.mktime(now.timetuple()) email = EmailModels.objects.get(code=code) over_time = email.overtime over_time = time.mktime(over_time.timetuple()) if now_time < over_time: form = LoginFrom() return render(request, 'login.html', {'form': form}) return HttpResponse('<a href="http://127.0.0.1:8000/users/register">验证码已失效,请点击重新注册</a>') def post(self): return redirect('index') # 注册验证码 class Amend_pd(View): def get(self, request): form = Amend_password() return render(request, 'amend_passwd.html', {'form': form}) def post(self, request): form = Amend_password(request.POST) if form.is_valid(): # 判断是否是已存在邮箱 email = UsersModels.objects.filter(email=form.cleaned_data['email']) if email: # 发送邮件 res = send_email(email[0].email, send_type='forget') if res: return HttpResponse('修改密码邮件发送成功') else: return HttpResponse('修改密码邮件发送失败') else: return render(request, {"form": form, 'error': '该账户尚未注册请检查后重试'}) else: return render(request, 'amend_passwd.html', {'form': form}) # 修改密码验证码 class Ame_password(View): def get(self, request, code): # 判断验证码 if EmailModels.objects.filter(code=code): # 判断是否失效 now = datetime.datetime.now() # 转换为时间戳 now_time = time.mktime(now.timetuple()) email = EmailModels.objects.get(code=code) over_time = email.overtime over_time = time.mktime(over_time.timetuple()) if now_time < over_time: email = email.email return render(request, 'writer_passwd.html', {"email": email}) return HttpResponse('<a href="http://12192.168.3.11:8000/users/register">验证码已失效,请点击重新注册</a>') def post(self, request): return redirect('index') # 修改密码 class AlterPassword(View): def get(self, request): return redirect('index') def post(self, request): form = Alterpasswd(request.POST) print(form) email = form.cleaned_data['email'] password = form.cleaned_data['password'] repassword = form.cleaned_data['repassword'] if form.is_valid(): if password == repassword: mg = UsersModels.objects.get(email=email) mg.password = <PASSWORD>(password) mg.save() return HttpResponse('<a href="http://127.0.0.1:8000/">密码修改成功,密码是{},点击重新登录</a>'.format(password)) else: return render(request, 'writer_passwd.html', {'form': form, 'error': '密码不一致,请仔细检查'}) else: return render(request, 'writer_passwd.html', {'form': form}) class Center(View): def get(self,request): return render(request,'center.html') def post(self,request): return redirect('index') class Logot(View): def get(self,request): logout(request) return redirect('index') def post(self,request): pass class Modify(View): def get(self,request): return render(request,'modify_center.html') def post(self,request): pass class Update(View): def get(self, request): return redirect('index') def post(self, request): nick_name = request.POST.get('nick_name') birday = request.POST.get('birday','') phone = request.POST.get('phone','') sex = request.POST.get('optionsRadios') mg = UsersModels.objects.get(email=request.user.email) mg.nick_name=nick_name mg.birday = birday mg.phone = phone mg.sex = sex mg.save() return redirect('index') class CustomBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: # 可以通过email\mobile账号登录 user = UsersModels.objects.get(Q(email=username) | Q(nick_name=username)) # check_password 验证用户的密码是否正确 if user.check_password(password): return user else: if user.password == password: return True else: return None except Exception as e: return None <file_sep># -*- coding: utf-8 -*- from django.conf.urls import url from .views import * urlpatterns = [ url(r'^detail/',Detail.as_view(),name='detail'), url(r'^list/',lists,name='list'), # url(r'^list/',ListsView.as_view(),name='list') ]<file_sep>from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. # 定义自己数据模型 class UsersModels(AbstractUser): # 添加需要的字段, # 昵称 nick_name = models.CharField(max_length=20,verbose_name='昵称',default='') # 生日 #blank=True 表示表单的数据可以为空,默认 birday = models.DateField(verbose_name='生日',null=True,blank=True) # 手机号 phone = models.CharField(max_length=11,verbose_name='手机号',default='') # 地址 address = models.CharField(max_length=20,verbose_name='地址',default='') # 头像 image = models.ImageField(upload_to='images/%Y/%m',default='images/default.png') # 性别 #choices 表示只能两个选择一个 sex = models.CharField(max_length=20,verbose_name='性别',choices=(('man','男'),('women','女'))) class Meta: db_table = 'users' # 后台管理 verbose_name = '用户信息' verbose_name_plural = verbose_name # 邮箱验证类 class EmailModels(models.Model): # 验证码 code = models.CharField(verbose_name='验证码',max_length=20) # 接受用户的邮箱 email = models.CharField(verbose_name='收件人',max_length=20) # 发送时间 send_time = models.DateField(max_length=20,verbose_name='发送时间') # 过期时间 overtime = models.DateField(max_length=20,verbose_name='过期时间') # 邮件类型 1 注册邮件 2 找回密码邮件 # choices 选项,只能其中选择一个 send_type = models.CharField(choices=(('register','注册邮件'),('forget','找回密码')),max_length=20) class Meta: verbose_name = '邮箱验证' verbose_name_plural = verbose_name<file_sep>window.onload = function (ev) { console.log($('.ch')) $.ajaxSetup({ data:{'csrfmiddlewaretoken':'{{csrf_token}}'} }) $('.ch').blur(function (eve) { var url = 'http://127.0.0.1:8000/user/checklogin/' if ($(this)[0].id=='username'){ var data = {'username':$(this).val()} } $.get(url,data,function (data) { console.log(data) if (data.status ==0){ $('#user_error').css('display','block') } }) }) // 提交数据 $('form').submit(function (eve) { eve.preventDefault() console.log(window.location.href) $.ajax({ url:window.location.href, data:$(this).serialize(), type:"POST", success:function (data,status,xhr) { console.log(data) // 表单不合法 if (data.name==0){ if (data.Meg.pwd){ $('#pwd_error').css('display','block') } } else if(data.name == 'pwd'){ $('#pwd_error').css('display','block') } else if(data.status == 1){ if (data.next){ window.location.href= data.next }else { window.location.href= '/' } } }, error:function (status,xhr,errorThrow) { console.log(status.xhr,errorThrow) }, commplate:function () { console.log('请求完成') } }) }) } <file_sep>$(function () { // 定义变量记录每一个数据是否有误 // 用户名错误 var error_name = false // 密码错误 var error_pwd = false // 检查密码 var error_check_pwd = false // 邮箱错误 var error_email = false // 用户协议错误 var error_check = false // 失去焦点,检测用户名 $('#user_name').blur(function () { check_user_name() }) $('#pwd').blur(function () { check_pwd() check_cpwd() }) $('#cpwd').blur(function () { check_cpwd() }) $('#email').blur(function () { check_email() }) // 检测用户名是否合法 function check_user_name() { // 获取输入框内容长度 var len =$('#user_name').val().length // 规定用户名不能小于6位 大于20位 if (len<6 || len>20){ // next() 获取标签的下一个兄弟标签 $('#user_name').next().text('请输入5-20个字符的用户名') $('#user_name').next().show() error_name = true }else{ // 实时检测用户名是否被占用 var url = '/user/check_user?username='+$('#user_name').val() $.get(url,function (data) { if (data.status == 0){ // 用户名被占用 error_name = true }else{ // 用户名未被占用 error_name = false } $('#user_name').next().text(data.msg) $('#user_name').next().show() }) } } // 检测密码是否合法 function check_pwd() { // 获取密码输入框值的长度 var len = $('#pwd').val().length // 不能少于8位 大于20位 if (len < 8 ||len>20){ $('#pwd').next().text('密码最少8位,最大20位') $('#pwd').next().show() error_pwd = true }else{ $('#pwd').next().hide() error_pwd = false } } // 检测两次面是否一致 function check_cpwd() { var pwd = $('#pwd').val() var cpwd = $('#cpwd').val() if(pwd != cpwd) { $('#cpwd').next().text('两次密码输入不一致') $('#cpwd').next().show() error_check_pwd = true }else{ $('#cpwd').next().hide() error_check_pwd = false } } // 检测邮箱 function check_email() { // 正则表达式 var re = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/ if (re.test($('#email').val())){ $('#email').next().hide() error_email = false }else{ $('#email').next().text('请输入正确的邮箱地址') $('#email').next().show() error_email = true } } // 检测是否同意用户协议 $('#allow').click(check_protocol) function check_protocol() { // is(:checked) if($(this).is(':checked')){ error_check = false $('#allow_err').hide() }else{ error_check = true // 找到下一个标签的下一个标签 // prev()找上一个标签 // prevent()找父级标签 // children() 找后代标签 $('#allow').next().next().text('请勾选同意') $('#allow').next().next().show() } } // form表单的提交事件 $('#reg_form').submit(function (ev) { // 禁止默认表单提交事件 ev.preventDefault() // 检测各个数据的可用性 check_email() check_cpwd() check_pwd() check_user_name() if (error_check == false && error_email == false && error_check_pwd == false && error_name == false && error_pwd==false){ // 提交注册请求 data = { csrfmiddlewaretoken:$('input[name="csrfmiddlewaretoken"]').val(), username:$('#user_name').val(), password:$('#pwd').val(), email:$('#email').val() } $.ajax({ url:'/user/register/', data:data, type:'POST', async:true, success:function (data) { if(data.status == 0){ $('#user_name').next().text(data.msg) $('#user_name').next().show() }else if(data.status == 500){ $('#user_name').next().hide() alert(data.msg) }else { $('#user_name').next().hide() alert(data.msg) window.location.href = '/user/login/' } } }) } }) })<file_sep>from django.shortcuts import render from django.contrib.auth.views import login_required from django.http import JsonResponse from .models import CartInfo # Create your views here. @login_required def cart(request): if request.method == 'GET': # 找到登录用户购物车所有信息 all_cart = CartInfo.objects.filter(user=request.user) context = { 'title':'天天生鲜-我的购物车', 'all_cart':all_cart, 'type':'cart' } return render(request,'df_cart/cart.html',context) def add_cart(request): if request.method == 'POST': if request.user.is_authenticated: # 取出商品id 商品数 try: g_id = request.POST.get('g_id') count = request.POST.get('count') # 判断商品是否已经在用户的购物车中,如果在,增加数量,如果不在,创建保存 try: cart = CartInfo.objects.get(goods_id=g_id,user=request.user) except Exception as e: # 没有找到商品 cart = CartInfo(goods_id=g_id, count=count, user=request.user) else: # 修改商品数据 cart.count += int(count) # 保存商品购物车记录 cart.save() except Exception as e: print(e) return JsonResponse({ 'status':2, 'msg':'加入购物车失败' }) else: return JsonResponse({ 'status':1, 'msg':'加入购物车成功', 'count':CartInfo.objects.filter(user=request.user).count() }) else: next_href = request.POST.get('next_href') next_href = next_href.split('8000')[1] return JsonResponse({ 'errMsg':'请先登录', 'url':'/user/login/?next={}'.format(next_href), 'status':0 }) # 查询登录用户的购物车商品数 def query_count(request): if request.method == 'GET': # 判断用户是否登录 if request.user.is_authenticated: # 查询登录用户的购物车商品数 count = CartInfo.objects.filter(user=request.user).count() return JsonResponse({ 'status':1, 'count':count }) else: return JsonResponse({ 'status':1, 'count':0 }) @login_required def update(request): if request.method == 'GET': c_id = request.GET.get('c_id') count = request.GET.get('count') try: cart = CartInfo.objects.get(id=c_id) cart.count = count cart.save() except Exception as e: print(e) return JsonResponse({ 'status':0, 'msg':'添加数量失败' }) else: return JsonResponse({ 'status':1, 'msg':'添加成功', 'count':cart.count }) # 删除购物车 def delete(request): if request.method == 'GET': c_id = request.GET.get('c_id') try: cart = CartInfo.objects.get(id=c_id) cart.delete() except Exception as e: return JsonResponse({ 'status':0, 'msg':'删除失败' }) else: return JsonResponse({ 'status':1, 'msg':'删除成功' }) <file_sep>window.onload = function (ev) { //计算商品总价函数 function cart_total() { //声明变量记录商品总价和商品总个数 var totalPrice = 0 var totalCount = 0 //找到所有的商品小计标签 //each() 类似于for循环,让找到的每一个标签都去执行某个函数 $('.col07').each(function () { //找到上一个标签中的input //prev()找上一个标签 find()找到某个标签中的某个标签 var count = $(this).prev().find('input').val() var price = $(this).prev().prev().text() //展示小计价格 var current_total = parseInt(count) * parseFloat(price) //展示小计价格 $(this).text(current_total.toFixed(2)) //判断当前商品是否被选中 //siblings()找到所有的兄弟节点 //children()找后台的标签 //prop()获取某个属性值有的返回True.没有返回false, 设置某个属性值 if($(this).siblings('.col01').children('input').prop('checked')){ //总计+=小计 totalPrice += current_total //商品总个数 totalCount += parseInt(count) $('#totalprice').text(totalPrice.toFixed(2)) $('.totalnum').text(totalCount.toFixed(2)) } else { $('#totalprice').text(0) $('.totalnum').text(0) } }) } cart_total() $('.add').mousedown(function () { var stock = $(this).siblings('#stock').attr('class') console.log(stock) var value = parseInt($(this).siblings('input').attr('value')) var good_id = parseInt($(this).siblings('input').attr('id')) value += 1 if (value > parseInt(stock)){ value = stock } $(this).siblings('input').attr('value',value) cart_total() send(good_id,value) }) $('.minus').mousedown(function () { var good_id = parseInt($(this).siblings('input').attr('id')) var value = parseInt($(this).siblings('input').attr('value')) value -= 1 if (value >= 1){ $(this).siblings('input').attr('value',value) cart_total() send(good_id,value) } }) $('.num_show').blur(function () { var good_id = parseInt($(this).attr('id')) var value = parseInt($(this).val()) var stock = parseInt($(this).siblings('#stock').attr('class')) if (value > stock){ value = stock }else if(value < 1){ value = 1 } $(this).attr('value',value) $(this).val(value) cart_total() send(good_id,value) }) function send(goods_id,num) { var csrf = $('form').attr('id') console.log(csrf) url = '/cart/order_check/' data = { goods_id:goods_id, num:num, csrfmiddlewaretoken:$('form').attr('id') } $.post(url,data,function (data) { console.log(data) if (data.status == 1){ console.log(data.Meg) } else if(data.status == 0){ consoe.log(data.Meg) $(this).siblings('input').attr('value',num) cart_total() alert('网络原因,请刷新页面') }} ) } //实现全选择和全消 $('#checkall').click(function () { console.log('点击去哪徐') //获取全选和全消 var is_true = $(this).prop('checked') //找到所有的复选框 $('.check').prop('checked',is_true) //全算计算价格 cart_total() }) //选择或者取消一个框 $('.check').click(function () { //点击当前选框是被选中的状态 if ($(this).prop('checked')){ //判断所有的复选框是否被选中 //找到所有的被选中的复选模 var check_num = $('.check:checked').length if (check_num == $('.check').length){ //如果都是选中的状态.展示全选状态 $('#checkall').prop('checked',true) }else { $('#checkall').prop('checked',false) } } else{ //点击后复选框没有被选中 //取消全选状态 $('#checkall').prop('checked',false) } cart_total() }) $.ajaxSetup({ data:{'csrfmiddlewaretoken':$('form').attr('id')} }) //提交订单 $('from').submit(function (env) { env.preventDefault() $.ajax({ url:'/add_order/', data:{ } }) }) }
90e1204e9ee58de633db8a8872d18e61c2c049f5
[ "JavaScript", "Python", "Markdown" ]
47
Python
917868607/login--django
6356c4e13caac5921334d0298f8f05640e5f0938
a897edbc85f53d7211640fdf2d6d4618d3da535f
refs/heads/master
<repo_name>bjonamu/react-native-btns<file_sep>/LinkButton.js import React from 'react' import PropTypes from 'prop-types' import { View, Text } from 'react-native' import Button from './Button' import { Colors } from './Themes' import Styles from './Styles/ButtonStyles' const LinkButton = ({ leftIcon, rightIcon, label, labelStyle, uppercase, active, disabled, activityIndicatorColor, onPress }) => { if (leftIcon || rightIcon) { return ( <Button style={Styles.buttonWithIcon} active={active} onPress={onPress} activityIndicatorColor={activityIndicatorColor}> <View style={Styles.iconCont}>{leftIcon}</View> <Text style={labelStyle || Styles.defaultLabel}>{uppercase ? label.toUpperCase() : label }</Text> <View style={Styles.iconCont}>{rightIcon}</View> </Button> ) } return ( <Button label={label} active={active} disabled={disabled} onPress={onPress} uppercase={uppercase} labelStyle={labelStyle} activityIndicatorColor={activityIndicatorColor} /> ) } LinkButton.defaultProps = { label: 'Link button', activityIndicatorColor: Colors.snow } LinkButton.propTypes = { active: PropTypes.bool, disabled: PropTypes.bool, label: PropTypes.string, uppercase: PropTypes.bool, leftIcon: PropTypes.element, rightIcon: PropTypes.element, activityIndicatorColor: PropTypes.string, onPress: PropTypes.func.isRequired } export default LinkButton <file_sep>/Footer.js import React from 'react' import PropTypes from 'prop-types' import { View, StyleSheet } from 'react-native' import { Metrics } from './Themes' const Footer = ({ children, height }) => ( <View style={[styles.container, { height }]}>{children}</View> ) const styles = StyleSheet.create({ container: { position: 'absolute', bottom: 0, left: 0, right: 0, justifyContent: 'center', alignItems: 'center', flexDirection: 'row' } }) Footer.defaultProps = { height: Metrics.baseHeight } Footer.propTypes = { height: PropTypes.number } export default Footer <file_sep>/Themes/Metrics.js export default { baseMargin: 10, baseHeight: 50, baseSize: 50, buttons: { tiny: 40, normal: 50, large: 60 } } <file_sep>/index.js import LinkButton from './LinkButton' import IconButton from './IconButton' import SuperButton from './SuperButton' import FooterButton from './FooterButton' import Footer from './Footer' export { LinkButton, IconButton, SuperButton, FooterButton, Footer } <file_sep>/Themes/Colors.js export default { snow: 'white', transparent: 'rgba(0,0,0,0)' } <file_sep>/README.md # react-native-btns React native buttons for real world apps. Easy to setup, configure and use. [![Screenshot](https://s26.postimg.org/st94b9o5l/Simulator_Screen_Shot_15_Sep_2017_10.17.44_AM.png)](https://postimg.org/image/t60ihg6f9/) ## Installation ```bash npm install react-native-btns --save ``` or ```bash yarn add react-native-btns ``` ## Usage ```js import { LinkButton, IconButton, SuperButton, FooterButton } from 'react-native-btns' ``` ### LinkButton ```js <LinkButton uppercase labelStyle={styles.label} onPress={() => this.doSomethingUseful()} /> ``` #### LinkButton props | Props | Default values | Possible values | | ---------------------- | -------------- | ------------------------------------------ | | label | Link button | **any string** | | labelStyle | | **style object** | | uppercase | false | Boolean | | leftIcon | **none** | Icon element e.g react-native-vector-icons | | rightIcon | **none** | Icon element e.g react-native-vector-icons | | active | false | Boolean | | disabled | false | Boolean | | activityIndicatorColor | white | Color string (hex or rbg/a) | | onPress | **none** | function | ### IconButton ```js <IconButton round size={50} icon={<Icon size={30} name='fingerprint' style={styles.whiteIcon} />} backgroundColor='#F70044' onPress={() => this.doSomethingUseful()} /> ``` #### IconButton props | Props | Default values | Possible values | | ---------------------- | -------------- | --------------------------- | | size | 50 | Integer | | round | false | Boolean | | active | false | Boolean | | disabled | false | Boolean | | activityIndicatorColor | white | Color string (hex or rbg/a) | | borderColor | **none** | Color string (hex or rbg/a) | | onPress | **none** | function | ### SuperButton ```js <SuperButton uppercase size='large' backgroundColor='#11CD86' onPress={() => this.doSomethingUseful()} /> ``` #### SuperButton props | Props | Default values | Possible values | | ---------------------- | -------------- | ------------------------------------------ | | size | 'normal' | enum 'tiny', 'normal', 'large' | | label | Link button | **any string** | | labelStyle | | **style object** | | uppercase | false | Boolean | | leftIcon | **none** | Icon element e.g react-native-vector-icons | | rightIcon | **none** | Icon element e.g react-native-vector-icons | | round | false | Boolean | | softCorners | false | Boolean | | active | false | Boolean | | disabled | false | Boolean | | backgroundColor | transparent | Color string (hex or rbg/a) | | activityIndicatorColor | white | Color string (hex or rbg/a) | | borderColor | transparent | Color string (hex or rbg/a) | | borderWidth | 0 | Number | | onPress | **none** | function | ### FooterButton ```js <FooterButton uppercase size='large' label='Next' backgroundColor='#066FA5' labelStyle={{ fontSize: 14, color: '#fff' }} rightIcon={<Icon size={20} name='chevron-thin-right' style={styles.whiteIcon} />} onPress={() => this.doSomethingUseful()} /> ``` #### FooterButton props | Props | Default values | Possible values | | ---------------------- | -------------- | ------------------------------------------ | | size | 'normal' | enum 'tiny', 'normal', 'large' | | label | Link button | **any string** | | labelStyle | | **style object** | | uppercase | false | Boolean | | leftIcon | **none** | Icon element e.g react-native-vector-icons | | rightIcon | **none** | Icon element e.g react-native-vector-icons | | active | false | Boolean | | disabled | false | Boolean | | backgroundColor | transparent | Color string (hex or rbg/a) | | activityIndicatorColor | white | Color string (hex or rbg/a) | | onPress | **none** | function | TODO * ADD: disabledColor prop * ADD: elevation prop <file_sep>/IconButton.js import React from 'react' import PropTypes from 'prop-types' import Button from './Button' import { Metrics, Colors } from './Themes' import styles from './Styles/ButtonStyles' const IconButton = ({ icon, size, active, disabled, activityIndicatorColor, backgroundColor, borderColor, round, onPress }) => { let borderRadius = 0 if (round) { borderRadius = size / 2 } const customStyle = { width: size, height: size, backgroundColor, borderColor, borderRadius } return ( <Button active={active} disabled={disabled} onPress={onPress} style={[ styles.IconButton, customStyle ]} activityIndicatorColor={activityIndicatorColor} > {icon} </Button> ) } IconButton.defaultProps = { activityIndicatorColor: Colors.snow, backgroundColor: Colors.transparent, borderColor: Colors.transparent, size: Metrics.baseSize } IconButton.propTypes = { round: PropTypes.bool, active: PropTypes.bool, disabled: PropTypes.bool, size: PropTypes.number, icon: PropTypes.element, borderColor: PropTypes.string, backgroundColor: PropTypes.string, activityIndicatorColor: PropTypes.string, onPress: PropTypes.func.isRequired } export default IconButton <file_sep>/FooterButton.js import React from 'react' import SuperButton from './SuperButton' import PropTypes from 'prop-types' import Footer from './Footer' import { Metrics } from './Themes' const FooterButton = ({ size, leftIcon, rightIcon, label, labelStyle, uppercase, active, disabled, backgroundColor, activityIndicatorColor, onPress }) => ( <Footer height={Metrics.buttons[size]}> <SuperButton size={size} label={label} active={active} disabled={disabled} onPress={onPress} leftIcon={leftIcon} rightIcon={rightIcon} uppercase={uppercase} labelStyle={labelStyle} backgroundColor={backgroundColor} activityIndicatorColor={activityIndicatorColor} /> </Footer> ) FooterButton.defaultProps = { size: 'normal', label: 'Footer button' } FooterButton.propTypes = { size: PropTypes.oneOf(['tiny', 'normal', 'large']), active: PropTypes.bool, disabled: PropTypes.bool, label: PropTypes.string, uppercase: PropTypes.bool, leftIcon: PropTypes.element, rightIcon: PropTypes.element, backgroundColor: PropTypes.string, activityIndicatorColor: PropTypes.string, onPress: PropTypes.func.isRequired } export default FooterButton
cb8c7d6162f3922d2ee357da6cf8803e1a6e605e
[ "JavaScript", "Markdown" ]
8
JavaScript
bjonamu/react-native-btns
ab272f8a1c2849ff7a11042a9cc79e80bafaa81e
aaa733b48012a074f3422c7dc2366b683410fe1a
refs/heads/master
<file_sep>select from tabl
2a80ce98bea4a4d2841ecc81f69663c01a99b154
[ "SQL" ]
1
SQL
htc-mmellali/apollo14
972be8fb23cdee232663ee188b827140f42fd466
f10be5c95be9d8c22faf59c1bc1c74145d03df9f